text:
Q: Is there a way to have global Flex 4 states (user roles)? I am having an issue with flex states in my application. What I am looking to do is on creation complete of the application, obtain a user role guest/user/superUser (based on username and password) from a server, then set the state client side based on that information. My .mxml classes need to include certain graphic elements based on that state. I am running into the issues of including elements based on the states defined at the Application level of the project. I am trying to avoid having to define the states in each .mxml file that needs it.
I feel that this is possibly something easy that I am overlooking or maybe there is a better way to do this. Any examples input is very helpful.
I know that this returns the current state
Application.application.currentState;

but I am looking to almost "populate" the
<mx:states>
    <mx:State name="state1"/>
</mx:states>

of every .mxml file from the states defined in the Application

A: If you are looking for dynamic states - here is your solution (The first two states – default and big - are added at compile time. The third state Bang-a-Gong is added at runtime):
private function init():void {
    // Create a new state and give it a name.
    var stateBang:State = new State();
    stateBang.name = 'Bang-a-Gong';

    // Set the overrides with an array of AddChild, AddItems,
    // RemoveChild, SetEventHandler, SetProperty, and SetStyle
    stateBang.overrides =
        [ new SetProperty( btn, "label", "Bang-a-Gong" ),
          new SetProperty( btn, "height", "150" ),
          new SetProperty( btn, "width", "300" ),
          new SetStyle( btn, "fontSize", "22" ),
          new SetStyle( btn, "fontWeight", "bold" ),
          new SetStyle( btn, "color", "#FF0000" ) ];

    // Add our new state to the available states of this component.
    this.states.push( stateBang );

    // Just for kicks lets add a transition for this state.
    var transition:Transition = new Transition();
    transition.toState = 'Bang-a-Gong';

    // Create a new transition effect.
    var resize:Resize = new Resize( btn );

    // Create an composite effect, either: Sequence or Parallel.
    var sequence:Sequence = new Sequence();

    // Add our resize effect.
    sequence.addChild( resize );

    // now add our composition effect to the transition we created.
    transition.effect = sequence;

    // Push our new transition into the transitions array for this component.
    this.transitions.push( transition );
}

In another case, if I understood in right way, you should create some Object in main application, and access it from all child components via FlexGlobals.topLevelApplication.
If you want to change child states, you should have some instance with already defined states as minimum in one place, and later copy them, to child components, but what sense if they are all custom logic?
So, let me know, if it helps.


text:
Q: What is a call to `char()`, `uint8_t()`, `int64_t()`, integer `T()`, etc, as a function in C++? I've never seen this call to char() as a function before. Where is this described and what does it mean? This usage is part of the example on this cppreference.com community wiki page: https://en.cppreference.com/w/cpp/string/basic_string/resize:
short_string.resize( desired_length + 3 );
std::cout << "6. After:  \"";
for (char c : short_string) {
    std::cout << (c == char() ? '@' : c);  // <=== HERE ===
}

This wording in the description also doesn't make any sense to me and I don't understand what it's saying:

Initializes appended characters to CharT().

Highlighted in context:

Adjacently related

*

*What motivated me to study the std::string::resize() method was trying to learn how to pre-allocate a std::string for use in C function calls as a char* buffer. This is possible by first pre-allocating the std::string by calling the my_string.resize() function on it. Then, you can safely write into &my_string[0] as a standard char* up to index my_string.size() - 1. See also:

*

*Directly write into char* buffer of std::string

*Is there a way to get std:string's buffer

*How to convert a std::string to const char* or char*

*

*See my detailed answer to this question here.

Update:

*

*3.5 months after asking the original question, I was made aware of this question also: What does int() do in C++?

A: It returns 0 with the specified type, same as char(0). It's called value initialization.
The syntax mimics that of calling a default constructor for a class.

A: It's the constructor† for char; with no arguments it constructs '\0'. Rarely used since primitives offer other ways to initialize them, but you initialize them with () just like you would a user-defined class, which ensures they get initialized to something; char foo; has undefined value, while char foo = char(); or char foo{}; is definitely '\0'.

†As HolyBlackCat notes, it's not technically a constructor, because it's not a class, but it behaves like one for most purposes.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Dropdowns - selects dynamics-jquery I'm try to do a dynamic selects with jQuery, example:
<select >
<option value=1> 1</option>
<option value=2> 2</option>
<option value=3> 3</option>
<option value=4> 4</option>
</select>

when I get value="x"
I would like to add
count=x;
for(int i=1 ; i<=count; i++){
<select > </select>
}

I have a problem with me code , this code add and add.. I dont want this
I just want add the 'x' select
http://jsfiddle.net/hqLPp/48/

A: If you want result on same page, then this might be useful,
this will be on your page, where you want result
    <script>
    function showSelectBox(str)
    {
    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    xmlhttp.onreadystatechange=function()
      {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
        document.getElementById("myresult").innerHTML=xmlhttp.responseText;
        }
      }
    xmlhttp.open("GET","test.php?q="+str,true); // Pass value to another page Here->test
    xmlhttp.send();
    }
    </script>

    <select name='check' onchange="showSelectBox(this.value)">
            <option>Select</option>
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            <option value="4">4</option>
    </select>

    <div id="myresult">

    </div>

Now On test.php Simply Call Value & put select box,
    <?php
    $q = $_GET['q'];

    for($i=1 ; $i<=$q; $i++)
    {
        echo '<select > </select>';
    }
    ?>


text:
Q: How to update div on database update I have made a code for chatting and it is member based this is the code:
The code is available here : Code For Chat.php
What I want is it to update the div id window everytime there is a update/insert/change in the database as if I have it update every X number of seconds A) it is too fast or B) too slow...

A: A solution could be: Save the hour/minutes when you make your last update in DB in a txt file(or something like this) and compare it with the time when your jquery is accessed. If these two "times" are different get your data from DB.(I think this is the fastest way)


text:
Q: discord.py server template So I am trying to make a command that will create template, code:
@client.command()
async def template(ctx, name):
    await ctx.guild.create_template(name = name, description = None)
    await ctx.send('Done.')

Everytime when I use this command I got this error:
AttributeError: 'Guild' object has no attribute 'create_template'

A: *

*You have wrote 'Guild' as 'guild'

*Usage of create_template: await discord.Guild.create_template(*, name, description=None)
(Just so you know)


text:
Q: How can I identify if a binary file is set-user-ID? In Linux, how can I identify if a binary file is set-user-ID?
Can I use ls -l?

A: executing ls -l you will get something like:
-rwSr--r--   1 user user    8111573 Sep 26  2012 net-snmp.tar

where the S (can be also s) indicate this file have SUID set
S is set when you do not have execution flag set
s is set when you have execution flag set

A: Either manually look at the file with ls -l filename, or from a script you can use
[ -u filename ] && echo SUID-bit is set

See also man bash:
   -u file
          True  if  file  exists  and its set-user-id bit is set.

See also info ls:
 The file mode bits listed are similar to symbolic mode
 specifications (*note Symbolic Modes::).  But 'ls' combines
 multiple bits into the third character of each set of permissions
 as follows:

 's'
      If the set-user-ID or set-group-ID bit and the corresponding
      executable bit are both set.

 'S'
      If the set-user-ID or set-group-ID bit is set but the
      corresponding executable bit is not set.


text:
Q: EF6 InvalidOperationException on Update, but works after manual DB Change I am trying to update an entity's FK. I am doing it like this:
myEntity.FK_ID= Guid.Parse("aff4b5d9-e197-4f0d-85ff-b04464d9e4f0"); //Entity with this Guid exists inside the DB
myEntity.ForeignKeyProperty= null;

Then I try to update the entity (new context) like this:
using (MyContext db = new MyContext ())
{
    //db.Benutzer.Attach(entity); // <-- Same Exception
    db.Entry(entity).State = EntityState.Modified;
}

This results in a InvalidOperationException:
A referential integrity constraint violation occurred: The property value(s) of 'MyTable.MyTable_ID' on one end of a relationship do not match the property value(s) of 'MyEntity.FK_ID' on the other end.

I really don't know why. I then tried the following:
I changed the value of FK_ID to the target value inside the Database. This worked (okay, EF chaching some stuff maybe...)
But then I rechanged the value to something else and it STILL works.
After the manual DB change it now works for this one entity EVERYTIME. If I try to update another entity I get the same Exception. Any ideas on why this is happening?!
Regards,
Marcel
EDIT:
Here's a more complete Code:
    //In MVC-Controller
Benutzer dbBenutzer = Database.GetBenutzerByID(model.ID_Benutzer);

// ... Do some other changes to the entity

dbBenutzer.ChangeMitarbeiter = null;
dbBenutzer.MitarbeiterChange_ID = CurrentUser.Mitarbeiter_ID;

//...SaveChanges via
Database.Update<Benutzer>(dbBenutzer);

// In Repository
public static int Update<E>(E entity) where E : class
{
    using (Context db = new MMVContext())
    {
        try
        {
            db.Entry(entity).State = EntityState.Modified;  //EXCEPTION
            return SaveRepositoryChanges<E>(db);
        }
        catch (Exception e)
        {
            Logging.Error(e.ToExtString());
            return -1;
        }
    }
}


text:
Q: A grammar for the complement of language $L=\{a^{t+3}b^t:t \ge 0\}$ Assume that the  language $L=\{a^{t+3}b^t:t \ge 0\}$ is given.
Q1 : How can we write a grammar for the complement of this language?
Q2 : Assume that $L'=\{a^nb^m:n\ge0,m\gt n\}$ is given. Can you write a grammar for $L'\cap L$?
Note: I can easily write a grammar like this for the language $L$ itself.
S->aaaP
P->aPb
P->E

Also, I can easily write the grammar for $L'$:
S->PbX
X->bX
X->E
P->aPb
P->E

In these grammars, by E , i mean the empty string.
The first problem is the complementation and the second one is that i don't know how strings are made in the language $L' \cap L$ .
Thanks in advance.

A: Corrected HINT: Everything matching the regular expression
$$b^*+ab^*+aab^*+aaaaa^*+(a+b)^*ba(a+b)^*\tag{1}$$
is in the complement of $L$, and it's easy to write a grammar for this part of the complement. Every string in the rest of the complement begins with $aaa$, contains at least one $b$, and does not contain the string $ba$, so it must be $a^nb^m$ for some $n\ge 3$ and $m\ge 1$. You can handle this part of the complement by breaking it into two parts:

*

*strings of the form $a^{n+3}b^m$ such that $1\le m<n$, those that have too few $b$s; and

*strings that begin $a^{n+3}b^m$ such that $0\le n<m$, those that have too many $b$s.

Those in the first part must begin with at least $5$ $a$s; you can get them with
$$\begin{align*}
&S\to aaaaaFbX\\
&F\to aFb\mid A\\
&A\to aA\mid\epsilon\\
&X\to aY\mid a\mid\epsilon\\
&Y\to aY\mid bY\mid\epsilon
\end{align*}$$
See if you can work out a grammar for the other part and combine it with a grammar for the regular expression $(1)$ to get the desired grammar for the complement of $L$.


text:
Q: How to use IndexMenu? I have installed the indexMenu plugin, in my sidebar I have created a menu like this:
...
{{indexmenu>.#1|js#kde.png}}

and I want to hide one entry in my menu:

How can I do this?

A: I was a little bit confused, in case you want to hide this menu item, then why don't just not create this item?
Please correct me if my understanding wrong.
Maybe this link helps? http://www.dokuwiki.org/plugin:indexmenu#skip_files

A: Go to the plugin-settings and type the following behind namespace ids to skip:
/(collaborateur)/


text:
Q: How to allow the option of increasing the tickets purchased Ok, the code below works. But the thing is that it doesn't allow the user to alter the amount purchased.
I'm trying to figure out how to have the user, once they've purchased a ticket and get to paypal page, to be able to alter the amount of tickets they would like to have.
As it is, once you land on the paypal page, it shows what you purchased, and that's it, pretty much.
Any advice?
EDIT
If anyone needs an example of what I'm talking about, here's one: Paying for multiple items (at once) via paypal
Look at the image at bottom. Do you see the quantity column? That's what I meant. But when I tried what they did in that one, it doesn't work. I think it's because in that one, it uses _cart, wheres mine is _donation?
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">

<input type="hidden" name="cmd" value="_donations">

<input type="hidden" name="item_name" value="Name Of Business">

<input type="hidden" name="item_number" value="Tickets">
<select name="amount">
    <optgroup label="Sponsorship">
         <option value="15000" name="platinum">$15,000 - Platinum Sponsorship</option>
         <option value="10000">$10,000 - Gold Sponsorship</option>
         <option value="5000">$5000 - Silver Sponsorship</option>
         <option value="2500">$2,500 - Bronze Sponsorship</option>
   </optgroup>
   <optgroup label="Individual Seating">
         <option value="500">$500 per seat</option>
   </optgroup>
         <optgroup label="Program Book Tribute Journal Ad">
         <option value="600">$600 - Half Page</option>
         <option value="1000">$1000 - Full Page</option>
   </optgroup>

</select>
<input type="hidden" name="currency_code" value="USD">

<input type="image" name="submit" border="0"
 src="https://www.paypal.com/en_US/i/btn/btn_donate_LG.gif"
 alt="PayPal - The safer, easier way to pay online">

 </form>

EDIT TWO
Ok, kinda confused about how to get the item increments to show up.
Advice would be appreciated.
These are the changes I've added to the post above:
<input type="hidden" name="cmd" value="_cart">
<input type="hidden" name="upload" value="1">

Then to have the increment ability added ... I'm really confused by these lines and how to make it work for mine.
<input type="hidden" name="item_name_1" value="Item Name 1">
<input type="hidden" name="amount_1" value="1.00">

So, for the first item in my drop-down box (ie, the platinum ticket), I've modified it slightly, adding the name value:
<option value="15000" name="platinum">$15,000 - Platinum Sponsorship</option>

And then,
<input type="hidden" name="item_name_1" value="platinum">
<input type="hidden" name="amount_1" value="15000.00">

But as far as I can tell, that doesn't allow the user to change the quantity to what they want.
End of EDIT TWO
EDIT THREE Based on Jared's code beneath but posting a full version of it.
  <form action="https://www.paypal.com/cgi-bin/webscr" method="post">

   <input type="hidden" name="business" value="BLAHBLAH">

   <input type="hidden" name="cmd" value="_cart">
   <input type="hidden" name="upload" value="1">

   <input type="hidden" name="item_name" value="Corporation">

   <input type="hidden" name="item_number" value="Ticket Purchase">
   <select name="amount">
      <optgroup label="Sponsorship">
         <option value="Platinum Sponsorship">$15,000 - Platinum Sponsorship</option>
         <option value="Gold Sponsorship">$10,000 - Gold Sponsorship</option>
      </optgroup>
  </select>
  <input type="hidden" name="currency_code" value="USD">
  <input type="hidden" name="option_select0" value="Platinum Sponsorship">
  <input type="hidden" name="option_amount0" value="15000.00">
  <input type="hidden" name="option_select1" value="Gold Sponsorship">
  <input type="hidden" name="option_amount1" value="10000.00">
  <input type="hidden" name="option_index" value="0">

  <input type="image" name="submit" border="0"
  src="https://www.paypal.com/en_US/i/btn/btn_donate_LG.gif"
  alt="PayPal - The safer, easier way to pay online">

 </form>

All I get from this form is Your shopping cart is empty.
END OF EDIT THREE
EDIT FOUR
1. <input type="hidden" name="item_name" value="Donation">
2. <input type="hidden" name="button_subtype" value="products">
3. <input type="hidden" name="no_note" value="1">
4. <input type="hidden" name="no_shipping" value="2">
5. <input type="hidden" name="currency_code" value="USD">
6. <input type="hidden" name="weight_unit" value="lbs">
7. <input type="hidden" name="add" value="1">
8. <input type="hidden" name="bn" value="PP-ShopCartBF:btn_cart_LG.gif:NonHosted">

Do we need 2, 3, 4, & 6?
I get one, it's a way to label it, right?
2, what is button_subtype?
3, that's to say that there is no more additional info included, right?
4, is that needed? it's just purchase of a ticket online.
5, obviously needed.
6, is weight_unit really needed? as mentioned previously, it's just an online ticket.
7, is? I'm guessing a way for the incrementation to happen?
8, is to denote that the button is not hosted from paypal, right?
You don't have to answer any of those questions, and your answer has been accepted. Just wondering, is all.
Thank you again, Jared.
END OF EDIT FOUR

A: The donation button does not allow you to use a quanity because its intended for a donation, not a purchase. You can, however have the function of the add to cart button but appear as a donation button. Simply:
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">

<input type="hidden" name="cmd" value="_cart">

<input type="hidden" name="item_name" value="Name Of Business">

<input type="hidden" name="item_number" value="Tickets">
<select name="amount">
    <optgroup label="Sponsorship">
         <option value="15000" name="platinum">$15,000 - Platinum Sponsorship</option>
         <option value="10000">$10,000 - Gold Sponsorship</option>
         <option value="5000">$5000 - Silver Sponsorship</option>
         <option value="2500">$2,500 - Bronze Sponsorship</option>
   </optgroup>
   <optgroup label="Individual Seating">
         <option value="500">$500 per seat</option>
   </optgroup>
         <optgroup label="Program Book Tribute Journal Ad">
         <option value="600">$600 - Half Page</option>
         <option value="1000">$1000 - Full Page</option>
   </optgroup>

</select>
<input type="hidden" name="currency_code" value="USD">

<input type="image" name="submit" border="0"
 src="https://www.paypal.com/en_US/i/btn/btn_donate_LG.gif"
 alt="PayPal - The safer, easier way to pay online">

 </form>

A: <input type="hidden" name="Ticket"><select name="os0">
<optgroup label="Sponsorship">
    <option value="Platinum Sponsorship">$15,000 - Platinum Sponsorship</option>
    <option value="Gold Sponsorship">$10,000 - Gold Sponsorship</option>
</optgroup>
</select>
<input type="hidden" name="currency_code" value="USD">
<input type="hidden" name="option_select0" value="Platinum Sponsorship">
<input type="hidden" name="option_amount0" value="15000.00">
<input type="hidden" name="option_select1" value="Gold Sponsorship">
<input type="hidden" name="option_amount1" value="10000.00">
<input type="hidden" name="option_index" value="0">

A: <form target="paypal" action="https://www.paypal.com/cgi-bin/webscr" method="post" >
<input type="hidden" name="cmd" value="_cart">
<input type="hidden" name="business" value="Your Email Here">
<input type="hidden" name="lc" value="US">
<input type="hidden" name="item_name" value="Donation">
<input type="hidden" name="button_subtype" value="products">
<input type="hidden" name="no_note" value="1">
<input type="hidden" name="no_shipping" value="2">
<input type="hidden" name="currency_code" value="USD">
<input type="hidden" name="weight_unit" value="lbs">
<input type="hidden" name="add" value="1">
<input type="hidden" name="bn" value="PP-ShopCartBF:btn_cart_LG.gif:NonHosted">

<input type="hidden" name="on0" value="Sponsorship">

<select name="os0">
<optgroup label="Sponsorship">
    <option value="Platinum Sponsorship">Platinum Sponsorship $15,00.00 USD</option>
    <option value="Gold Sponsorship">Gold Sponsorship $10,000.00 USD</option>
</optgroup>
</select>

<input type="hidden" name="currency_code" value="USD">
<input type="hidden" name="option_select0" value="Platinum Sponsorship">
<input type="hidden" name="option_amount0" value="15000.00">
<input type="hidden" name="option_select1" value="Gold Sponsorship">
<input type="hidden" name="option_amount1" value="10000.00">
<input type="hidden" name="option_index" value="0">
<input type="image" src="https://www.paypal.com/en_US/i/btn/btn_donate_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">

</form>

This is how your button should look, this is from paypal.


text:
Q: The time-like geodesics (orbits) in the Schwarzschild spacetime I am trying to plot Schwarzschild's orbit without invoking the geodesic equation.
As a reference I am using Chandrasekhar's Book (The Mathematical theory of Black Holes, Oxford University Press). In page 98 of the book the equation(Eqn.94) is given
$$\left( \frac{du}{d\phi} \right) ^2=2Mu^3-u^2+\frac{2M}{L^2}u-\frac{1-E^2}{L^2}$$
The plots should come like the plots given in page 116 onwards.
I used NDSolve in Mathematica
E2 = 0.3; L = 2.5; M = 1;

Chandra1 =
 NDSolve[
   {u'[ϕ] - (2 M u[ϕ]^3 + u[ϕ]^2 -(2 M)/L^2 u[ϕ] +(1 - E2^2)/L^2)^(1/2) == 0, u[0] == 0},
   u, {ϕ, -π, π}]

PolarPlot[Evaluate[{1/u[ϕ]} /. Chandra1], {ϕ, 0, 2}, PlotRange -> All]

But it is not working, instead of reporting the following error:

 NDSolve::mxst: Maximum number of 4331206 steps reached at the point
 t == 0.654767877735252`

Please help me how to tackle this type of problem.

A: I like the analytical solution @Artes. Nevertheless, if we need to find a numerical solution using NDSolve[], then we can differentiate the equation and use the first-order equation at one point as a boundary condition, for example,
E2 = 3/10; L = 5/2; M = 1;
eq = {u''[x] == 3 M u[x]^2 - u[x] + M/L^2, u[0] == 4/3,
  u'[0] == -(Sqrt[(54743/3)]/75)};
U = NDSolveValue[eq, u, {x, 0, 4.5}]

Compare this solution with the analytical solution:
 u[\[Phi]_, c_, M_, L_, E2_] :=
     With[{g2 = -((-18 L^2 + 216 M^2)/(216 L^2)),
       g3 = -((-L^2 - 36 M^2 + 54 E2^2 M^2)/(216 L^2))},
      2/M WeierstrassP[\[Phi] -
          InverseWeierstrassP[1/12 (-1 + 6 c M), {g2, g3}], {g2, g3}] +
       1/(6 M)]
{PolarPlot[Re[1/U[x]], {x, 0, 4.5}, PlotRange -> All],
 PolarPlot[1/u[x, 4/3, 1, 5/2, 3/10], {x, 0, 4.5}, PlotRange -> All]}

A: Studying basic solutions at the theoretical physics it is advantageous when one can get  an exact solution. At the first sight one can see that the solution can be given in terms of elliptic functions (and elliptic integrals), though there are some tricks to remember in order to play with them seamlessly.
Instead of dealing with approximate numbers we are going to use exact numbers or more generally symbols M, L, E2 and rewrite your differential equation (you have been trying to solve in Mathematica  different one) as your wrote it in TeX:
(u'[ϕ])^2 - 2M u[ϕ]^3 + u[ϕ]^2 - (2M)/L^2 u[ϕ] + (1 - E2^2)/L^2 == 0

Now we can observe that our equation can be rewritten to the canonical Weierstrass form $w'(x)^2 -4w(x)^3+g_2 w(x)+g_3 =0$ substituting $u(\phi) \mapsto a w(\phi) + b$, and in order to determine a and b we evaluate
((u'[ϕ])^2 - 2M u[ϕ]^3 + u[ϕ]^2 - (2M)/L^2 u[ϕ] + (1 - E2^2)/L^2) 1/a^2 ==0 /.{
   u[ϕ] -> a w[ϕ] + b, u'[ϕ] -> a w'[ϕ]} // Collect[#, w[ϕ], Simplify] &

-((E2^2 + (1 + b^2 L^2) (-1 + 2 b M))/(a^2 L^2)) + (2(b - 3 b^2 M - M/L^2) w[ϕ])/a
  + (1 - 6 b M) w[ϕ]^2 - 2a M w[ϕ]^3 + w'[ϕ]^2 == 0

immediatelly we can find a and b
Solve[{(1 - 6 b M) == 0, 2 a M == 4}, {a, b}]

{{a -> 2/M, b -> 1/(6 M)}}

and so the canonical Weierstrass form is
(((u'[ϕ])^2 - 2M u[ϕ]^3 + u[ϕ]^2 - (2M)/L^2 u[ϕ] + (1 - E2^2)/L^2) 1/a^2/. {
 u[ϕ] -> 2/M w[ϕ] + 1/(6M), u'[ϕ] -> 2/M w'[ϕ]}//Expand//Simplify[ #,{a ==2/M,
                                                                      b ==1/(6M)}]&) == 0

 (L^2 + (36 - 54E2^2) M^2)/(216L^2) + (1/12 - M^2/L^2) w[ϕ] - 4w[ϕ]^3 + w'[ϕ]^2 == 0

and consequently
g2 = -((-18L^2 + 216M^2)/(216L^2)); g3 = -((-L^2 - 36M^2 + 54E2^2 M^2)/(216 L^2));

 DSolve[(L^2 + (36 - 54E2^2) M^2)/(216 L^2) + (1/12 - M^2/L^2) w[ϕ] - 4 w[ϕ]^3
         + w'[ϕ]^2 == 0, w[ϕ], ϕ]

 {{w[ϕ] -> WeierstrassP[ϕ - C[1], {-((-18 L^2 + 216M^2)/(216L^2)),
                              -((-L^2 - 36 M^2 + 54 E2^2 M^2)/(216L^2))}]},
  {w[ϕ] -> WeierstrassP[ϕ + C[1], {-((-18 L^2 + 216M^2)/(216L^2)),
                              -((-L^2 - 36 M^2 + 54 E2^2 M^2)/(216L^2))}]}}

We are going to use a more general initial condition $u(0)=c$ and so we can determine C[1] from  u[0]==  2/M w[ϕ] + 1/(6M) == c :
Solve[2/M w[0] + 1/(6 M) == c, w[0]]

 {{w[0] -> 1/12 (-1 + 6 c M)}}

That is, we can put
C[1] -> InverseWeierstrassP[1/12 (-1 + 6c M), {g2, g3}]

(or C[1] -> -InverseWeierstrassP[1/12 (-1 + 6c M), {g2, g3}] where g2, g3 are the same as above and finally denoting the solution by uw we can get:
uw[ϕ_, c_, M_, L_, E2_] :=
  With[{g2 = -((-18 L^2 + 216 M^2)/(216 L^2)),
        g3 = -((-L^2 - 36 M^2 + 54 E2^2 M^2)/(216 L^2))},
        2/M WeierstrassP[ϕ - InverseWeierstrassP[1/12 (-1 + 6 c M), {g2, g3}], {g2, g3}]
        + 1/(6 M)]

We have provided a general symbolic solution, for any values of $M, L, E$.
Edit
In order to replicate the orbits  from Chandrasekhar's book we have to get appropriate parameters $M, L, E$ as well as c, nevertheless those plots were drawn in a different setting, namely using parameters $l, e$ instead of $L, E$.
The original question does not contain sufficent information to plot appropriate orbits despite prompting in comments to complete the post with necessary details.  One has to get through ~$30$ pages long subsection $19\;$ The geodesics in the Schwarzschild space-time: the time-like geodesics in Chandrasekhar's book.   Although the starting point in the book is the equation $(94)$, then after appropriate transformations Chandrasekhar arrives to a relation expressing the angle  $\phi$ as a function (incomplete elliptic integral of the first kind $F$ modulo certain elementary translations and rescalings) of another variable $\chi$ related to $u = 1/r$, where $r$ is the radial variable in the spherically symmetric four-dimensional Lorentzian manifold- the Schwarzschild space-time.
$$ u=\frac{1+e \cos(\chi)}{l} $$
Parameters $l$ and $e$ are constant and counterparts respectively of  latus rectum and eccentricity, while $L$ and $E$ are the first integrals of motion being conterparts of angular momentum and energy. To identify L and E2 i.e. $L$ and $E$ in terms of l and e i.e. $l$ and $e$ we define two indentically equal polynomials of the third order:
f[u_]  := 2 M u^3 - u^2 + (2 M)/L^2 u - (1 - E2^2)/L^2
f1[u_] := 2 M (u - (1 - e)/l) (u - (1 + e)/l) (u - (1/(2 M) - 2/l))

and a simple function:
rel[M_, l_, e_] := {M, L, E2} /. ToRules @
  Reduce[
    Join[
      Thread[
        Coefficient[f[u, M, L, E2] - f1[u, M, l, e], u, {0,1}] == {0, 0}],
      {L > 0, E2 > 0, M > 0}],
    {L, E2}]

we choose plots $a, b, c, d, f$ rom the book  for which $(M, l, e)$ are:
Mle = {{3/14, 11, 1/2}, {3/14, 15/2, 1/2}, {3/14, 3, 1/2}, {3/14, 3/2, 1/2},
       {3/14, 9/7, 0}}

then $(M,L,E)$ are
MLE2 = rel @@@ Mle

{{3/14, 22 Sqrt[3/577], Sqrt[43790/44429]}, {3/14, 15/Sqrt[127], 16 Sqrt[17/4445]},
 {3/14, 6/Sqrt[43], Sqrt[286/301]}, {3/14, Sqrt[3/5], 4 Sqrt[2/35]},
 {3/14, (3 Sqrt[3])/7, (2 Sqrt[2])/3}}

Now we replicate graphics (we have to to use Re before WeierstrassP even though in our cases values of functions are real because there may appear small imaginary part (usually we use Chop instead of Re) see e.g. this answer)
(a)
PolarPlot[ Re[1/uw[ϕ, 1/10, 3/14, 22 Sqrt[3/577], Sqrt[43790/44429]]],
           {ϕ, 0, 24 Pi}, PlotStyle -> Thick]

(b)
PolarPlot[ Re[1/uw[ϕ, 5/30, 3/14, 15/Sqrt[127], 16 Sqrt[17/4445]]],
           {ϕ, 0, 16 Pi}, PlotStyle -> Thick]

(c)
PolarPlot[ Re[1/uw[ϕ, 4/18, 3/14, 6/Sqrt[43], Sqrt[286/301]]],
           {ϕ, 0, 12 Pi}, PlotStyle -> Thick]

(d)
PolarPlot[{ Re[1/uw[ϕ, 1/3, 3/14, Sqrt[3/5], 4 Sqrt[2/35]]],
            Re[1/u[ϕ, 3, 3/14, Sqrt[3/5], 4 Sqrt[2/35]]]},
          {ϕ, 0, 16 Pi}, PlotStyle -> Thick]

(f)
PolarPlot[ Re[1/uw[ϕ, 5, 3/14, (3 Sqrt[3])/7, (2 Sqrt[2])/3]],
           {ϕ, 0, 4 Pi}, PlotStyle -> Thick]

To add another plots with imaginary eccentricity we should slightly modify the function rel, that would be a simple exercise for the reader.


text:
Q: REGEX - PHP Get only bold section in a string I am new to Regex. I have a string like:
Hello ABCD World
or
ABCDHello World

I basically want to retain the text inside bold tags but remove all other characters in the string.
I have found the code to remove bold part in the string:
$string = 'This is an example text';
echo preg_replace('/(.+?)+(<\/b>)/i', '', $string);

So how do I make it to work in opposite way?
Regards
Ahmar

A: Use a DOM parser instead of a regex if you want to extract data from a HTML or XML document. While a regex will work in simple cases too, it can get weird if the use case gets more complicated or the input data changes in an unexpected way. A DOM parser is more stable and convenient for that purpose.
Example code:
$doc = new DOMDocument();
$doc->loadHTML('Hello ABCD World');

foreach($doc->getElementsByTagName('b') as $element) {
    echo $element->nodeValue;
}

A: use preg_match_all:
preg_match_all("'(.*?)'si", $text, $match);

foreach($match[1] as $val)
{
    echo $val."
";
}

A: Try this
function getTextBetweenTags($string, $tagname) {
$pattern = "/<$tagname ?.*>(.*)<\/$tagname>/";
preg_match_all($pattern, $string, $matches);
return $matches[1];
}

$str = 'This is an example text';
$txt = getTextBetweenTags($str, "b");
print_r($txt);


text:
Q: I am trying to install pandas (python3.9) in mac os and facing error **I am trying to install pandas in my Mac OS and facing an error. I have recently installed python3.9. I am new to python.
some libraries like NumPy and scipy are installed using homebrew
trying installing with homebrew showing me another error
==> Searching for similarly named formulae...
Error: No similarly named formulae found.
Error: No available formula or cask with the name "pandas".
**
  ERROR: Command errored out with exit status 1:
   command: /opt/homebrew/opt/python@3.9/bin/python3.9 /opt/homebrew/lib/python3.9/site-packages/pip install --ignore-installed --no-user --prefix /private/var/folders/y9/02mz9m7s2970mz8k77cgbng80000gn/T/pip-build-env-p4vzzze2/overlay --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- setuptools wheel 'Cython>=0.29.21,<3' 'numpy==1.16.5; python_version=='"'"'3.7'"'"' and platform_system!='"'"'AIX'"'"'' 'numpy==1.17.3; python_version=='"'"'3.8'"'"' and platform_system!='"'"'AIX'"'"'' 'numpy==1.16.5; python_version=='"'"'3.7'"'"' and platform_system=='"'"'AIX'"'"'' 'numpy==1.17.3; python_version=='"'"'3.8'"'"' and platform_system=='"'"'AIX'"'"'' 'numpy; python_version>='"'"'3.9'"'"''
       cwd: None
  Complete output (229 lines):
  Ignoring numpy: markers 'python_version == "3.7" and platform_system != "AIX"' don't match your environment
  Ignoring numpy: markers 'python_version == "3.8" and platform_system != "AIX"' don't match your environment
  Ignoring numpy: markers 'python_version == "3.7" and platform_system == "AIX"' don't match your environment
  Ignoring numpy: markers 'python_version == "3.8" and platform_system == "AIX"' don't match your environment
  Collecting Cython<3,>=0.29.21
    Using cached Cython-0.29.21-py2.py3-none-any.whl (974 kB)
  Collecting numpy
    Using cached numpy-1.19.5.zip (7.3 MB)
    Installing build dependencies: started
    Installing build dependencies: finished with status 'done'
    Getting requirements to build wheel: started
    Getting requirements to build wheel: finished with status 'done'
      Preparing wheel metadata: started
      Preparing wheel metadata: finished with status 'error'
      ERROR: Command errored out with exit status 1:
       command: /opt/homebrew/opt/python@3.9/bin/python3.9 /opt/homebrew/lib/python3.9/site-packages/pip/_vendor/pep517/_in_process.py prepare_metadata_for_build_wheel /var/folders/y9/02mz9m7s2970mz8k77cgbng80000gn/T/tmp_nyvr3sn
           cwd: /private/var/folders/y9/02mz9m7s2970mz8k77cgbng80000gn/T/pip-install-nfwyqhvs/numpy_a96abd5ed3de4c71ba29057fb2c27e1f
      Complete output (209 lines):
      Running from numpy source directory.
      setup.py:480: UserWarning: Unrecognized setuptools command, proceeding with generating Cython sources and expanding templates
        run_build = parse_setuppy_commands()
      Processing numpy/random/_bounded_integers.pxd.in
      Processing numpy/random/_philox.pyx
      Processing numpy/random/_bounded_integers.pyx.in
      Processing numpy/random/_sfc64.pyx
      Processing numpy/random/_mt19937.pyx
      Processing numpy/random/bit_generator.pyx
      Processing numpy/random/mtrand.pyx
      Processing numpy/random/_generator.pyx
      Processing numpy/random/_pcg64.pyx
      Processing numpy/random/_common.pyx
      Cythonizing sources
      blas_opt_info:
      blas_mkl_info:
      customize UnixCCompiler
        libraries mkl_rt not found in ['/opt/homebrew/Cellar/python@3.9/3.9.1_4/Frameworks/Python.framework/Versions/3.9/lib', '/usr/local/lib', '/usr/lib']
        NOT AVAILABLE

      blis_info:
        libraries blis not found in ['/opt/homebrew/Cellar/python@3.9/3.9.1_4/Frameworks/Python.framework/Versions/3.9/lib', '/usr/local/lib', '/usr/lib']
        NOT AVAILABLE

      openblas_info:
        libraries openblas not found in ['/opt/homebrew/Cellar/python@3.9/3.9.1_4/Frameworks/Python.framework/Versions/3.9/lib', '/usr/local/lib', '/usr/lib']
        NOT AVAILABLE

      atlas_3_10_blas_threads_info:
      Setting PTATLAS=ATLAS
        libraries tatlas not found in ['/opt/homebrew/Cellar/python@3.9/3.9.1_4/Frameworks/Python.framework/Versions/3.9/lib', '/usr/local/lib', '/usr/lib']
        NOT AVAILABLE

      atlas_3_10_blas_info:
        libraries satlas not found in ['/opt/homebrew/Cellar/python@3.9/3.9.1_4/Frameworks/Python.framework/Versions/3.9/lib', '/usr/local/lib', '/usr/lib']
        NOT AVAILABLE

      atlas_blas_threads_info:
      Setting PTATLAS=ATLAS
        libraries ptf77blas,ptcblas,atlas not found in ['/opt/homebrew/Cellar/python@3.9/3.9.1_4/Frameworks/Python.framework/Versions/3.9/lib', '/usr/local/lib', '/usr/lib']
        NOT AVAILABLE

      atlas_blas_info:
        libraries f77blas,cblas,atlas not found in ['/opt/homebrew/Cellar/python@3.9/3.9.1_4/Frameworks/Python.framework/Versions/3.9/lib', '/usr/local/lib', '/usr/lib']
        NOT AVAILABLE

      accelerate_info:
        libraries accelerate not found in ['/opt/homebrew/Cellar/python@3.9/3.9.1_4/Frameworks/Python.framework/Versions/3.9/lib', '/usr/local/lib', '/usr/lib']
      Library accelerate was not found. Ignoring
        libraries veclib not found in ['/opt/homebrew/Cellar/python@3.9/3.9.1_4/Frameworks/Python.framework/Versions/3.9/lib', '/usr/local/lib', '/usr/lib']
      Library veclib was not found. Ignoring
        FOUND:
          extra_compile_args = ['-faltivec', '-I/System/Library/Frameworks/vecLib.framework/Headers']
          extra_link_args = ['-Wl,-framework', '-Wl,Accelerate']
          define_macros = [('NO_ATLAS_INFO', 3), ('HAVE_CBLAS', None)]

        FOUND:
          extra_compile_args = ['-faltivec', '-I/System/Library/Frameworks/vecLib.framework/Headers']
          extra_link_args = ['-Wl,-framework', '-Wl,Accelerate']
          define_macros = [('NO_ATLAS_INFO', 3), ('HAVE_CBLAS', None)]

      non-existing path in 'numpy/distutils': 'site.cfg'
      lapack_opt_info:
      lapack_mkl_info:
        libraries mkl_rt not found in ['/opt/homebrew/Cellar/python@3.9/3.9.1_4/Frameworks/Python.framework/Versions/3.9/lib', '/usr/local/lib', '/usr/lib']
        NOT AVAILABLE

      openblas_lapack_info:
        libraries openblas not found in ['/opt/homebrew/Cellar/python@3.9/3.9.1_4/Frameworks/Python.framework/Versions/3.9/lib', '/usr/local/lib', '/usr/lib']
        NOT AVAILABLE

      openblas_clapack_info:
        libraries openblas,lapack not found in ['/opt/homebrew/Cellar/python@3.9/3.9.1_4/Frameworks/Python.framework/Versions/3.9/lib', '/usr/local/lib', '/usr/lib']
        NOT AVAILABLE

      flame_info:
        libraries flame not found in ['/opt/homebrew/Cellar/python@3.9/3.9.1_4/Frameworks/Python.framework/Versions/3.9/lib', '/usr/local/lib', '/usr/lib']
        NOT AVAILABLE

      atlas_3_10_threads_info:
      Setting PTATLAS=ATLAS
        libraries lapack_atlas not found in /opt/homebrew/Cellar/python@3.9/3.9.1_4/Frameworks/Python.framework/Versions/3.9/lib
        libraries tatlas,tatlas not found in /opt/homebrew/Cellar/python@3.9/3.9.1_4/Frameworks/Python.framework/Versions/3.9/lib
        libraries lapack_atlas not found in /usr/local/lib
        libraries tatlas,tatlas not found in /usr/local/lib
        libraries lapack_atlas not found in /usr/lib
        libraries tatlas,tatlas not found in /usr/lib
      <class 'numpy.distutils.system_info.atlas_3_10_threads_info'>
        NOT AVAILABLE

[![enter image description here][1]][1]File "/opt/homebrew/Cellar/python@3.9/3.9.1_4/Frameworks/Python.framework/Versions/3.9/lib/python3.9/os.py", line 756, in encode
          raise TypeError("str expected, not %s" % type(value).__name__)
      TypeError: str expected, not int
      ----------------------------------------
  ERROR: Command errored out with exit status 1: /opt/homebrew/opt/python@3.9/bin/python3.9 /opt/homebrew/lib/python3.9/site-packages/pip/_vendor/pep517/_in_process.py prepare_metadata_for_build_wheel /var/folders/y9/02mz9m7s2970mz8k77cgbng80000gn/T/tmp_nyvr3sn Check the logs for full command output.
  ----------------------------------------
ERROR: Command errored out with exit status 1: /opt/homebrew/opt/python@3.9/bin/python3.9 /opt/homebrew/lib/python3.9/site-packages/pip install --ignore-installed --no-user --prefix /private/var/folders/y9/02mz9m7s2970mz8k77cgbng80000gn/T/pip-build-env-p4vzzze2/overlay --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- setuptools wheel 'Cython>=0.29.21,<3' 'numpy==1.16.5; python_version=='"'"'3.7'"'"' and platform_system!='"'"'AIX'"'"'' 'numpy==1.17.3; python_version=='"'"'3.8'"'"' and platform_system!='"'"'AIX'"'"'' 'numpy==1.16.5; python_version=='"'"'3.7'"'"' and platform_system=='"'"'AIX'"'"'' 'numpy==1.17.3; python_version=='"'"'3.8'"'"' and platform_system=='"'"'AIX'"'"'' 'numpy; python_version>='"'"'3.9'"'"'' Check the logs for full command output.


text:
Q: Detecting Overlapping Circles in OpenCV I'm using the OpenCV library for Python to detect the circles in an image. As a test case, I'm using the following image:
bottom of can:

I've written the following code, which should display the image before detection, then display the image with the detected circles added:
import cv2
import numpy as np

image = cv2.imread('can.png')
image_rgb = image.copy()
image_copy = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
grayscaled_image = cv2.cvtColor(image_copy, cv2.COLOR_GRAY2BGR)

cv2.imshow("confirm", grayscaled_image)
cv2.waitKey(0)

cv2.destroyAllWindows()

circles = cv2.HoughCircles(image_copy, cv2.HOUGH_GRADIENT, 1.3, 20, param1=60, param2=33, minRadius=10,maxRadius=28)

if circles is not None:
    print("FOUND CIRCLES")
    circles = np.round(circles[0, :]).astype("int")
    print(circles)
    for (x, y, r) in circles:
        cv2.circle(image, (x, y), r, (255, 0, 0), 4)
        cv2.rectangle(image, (x - 5, y - 5), (x + 5, y + 5), (0, 128, 255), -1)
    cv2.imshow("Test", image + image_rgb)
    cv2.waitKey(0)

cv2.destroyAllWindows()

I get this:resultant image

I feel that my problem lies in the usage of the HoughCircles() function. It's usage is:
cv2.HoughCircles(image, method, dp, minDist[, circles[, param1[, param2[, minRadius[, maxRadius]]]]])
where minDist is a value greater than 0 that requires detected circles to be a certain distance from one another. With this requirement, it would be impossible for me to properly detect all of the circles on the bottom of the can, as the center of each circle is in the same place. Would contours be a solution? How can I convert contours to circles so that I may use the coordinates of their center points? What should I do to best detect the circle objects for each ring in the bottom of the can?

A: Not all but a majority of the circles can be detected by adaptive thresholding the image, finding the contours and then fitting a minimum enclosing circle for contours having area greater than a threshold
import cv2
import numpy as np

block_size,constant_c ,min_cnt_area = 9,1,400
img = cv2.imread('viMmP.png')
img_gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
thresh = cv2.adaptiveThreshold(img_gray,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV,block_size,constant_c)
thresh_copy = thresh.copy()
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
    if cv2.contourArea(cnt)>min_cnt_area:
        (x,y),radius = cv2.minEnclosingCircle(cnt)
        center = (int(x),int(y))
        radius = int(radius)
        cv2.circle(img,center,radius,(255,0,0),1)
cv2.imshow("Thresholded Image",thresh_copy)
cv2.imshow("Image with circles",img)
cv2.waitKey(0)

Now this script yields the result:

But there are certain trade-offs like, if the block_size and constant_c are changed to 11 and 2 respectively then the script yields:

You should try applying erosion with a kernel of proper shape to separate the overlapping circles in the thresholded image
You may look at the following links to understand more about adaptive thresholding and contours:
Threshlding examples: http://docs.opencv.org/3.1.0/d7/d4d/tutorial_py_thresholding.html
Thresholding reference: http://docs.opencv.org/2.4/modules/imgproc/doc/miscellaneous_transformations.html
Contour Examples:
http://docs.opencv.org/3.1.0/dd/d49/tutorial_py_contour_features.html


text:
Q: r2020a matlab_kernel not supporting python 3.8 I am trying to install 'matlab_kernel' for JupyterLab.
But I am getting stuck at step python setup.py install with an issue

OSError: MATLAB Engine for Python supports Python version 2.7, 3.6, and 3.7, but your version of Python is 3.8

Following this video here: https://www.youtube.com/watch?v=WufMGW5Bv4g
He installs it perfectly with the same version of MATLAB and python.
What am I missing ??
(I am successfully able to install octave_kernel)


text:
Q: PHP compare array Is there anyway to compare arrays in php using an inbuilt function, short of doing some sort of loop?
$a1 = array(1,2,3);
$a2 = array(1,2,3);

if (array_are_same($a1, $a2)) {
    // code here
}

Btw, the array values will not always be in the same order.

A: Also you can try this way:
if(serialize($a1) == serialize($a2))

A: if ( $a == $b ) {
    echo 'We are the same!';
}

A: Comparing two arrays to have equal values (duplicated or not, type-juggling taking into account) can be done by using array_diff() into both directions:
!array_diff($a, $b) && !array_diff($b, $a);

This gives TRUE if both arrays have the same values (after type-juggling). FALSE otherwise. Examples:
function array_equal_values(array $a, array $b) {
    return !array_diff($a, $b) && !array_diff($b, $a);
}

array_equal_values([1], []);            # FALSE
array_equal_values([], [1]);            # FALSE
array_equal_values(['1'], [1]);         # TRUE
array_equal_values(['1'], [1, 1, '1']); # TRUE

As this example shows, array_diff leaves array keys out of the equation and does not care about the order of values either and neither about if values are duplicated or not.

If duplication has to make a difference, this becomes more tricky. As far as "simple" values are concerned (only string and integer values work), array_count_values() comes into play to gather information about which value is how often inside an array. This information can be easily compared with ==:
array_count_values($a) == array_count_values($b);

This gives TRUE if both arrays have the same values (after type-juggling) for the same amount of time. FALSE otherwise. Examples:
function array_equal_values(array $a, array $b) {
    return array_count_values($a) == array_count_values($b);
}

array_equal_values([2, 1], [1, 2]);           # TRUE
array_equal_values([2, 1, 2], [1, 2, 2]);     # TRUE
array_equal_values(['2', '2'], [2, '2.0']);   # FALSE
array_equal_values(['2.0', '2'], [2, '2.0']); # TRUE

This can be further optimized by comparing the count of the two arrays first which is relatively cheap and a quick test to tell most arrays apart when counting value duplication makes a difference.

These examples so far are partially limited to string and integer values and no strict comparison is possible with array_diff either. More dedicated for strict comparison is array_search. So values need to be counted and indexed so that they can be compared as just turning them into a key (as array_search does) won't make it.
This is a bit more work. However in the end the comparison is the same as earlier:
$count($a) == $count($b);

It's just $count that makes the difference:
    $table = [];
    $count = function (array $array) use (&$table) {
        $exit   = (bool)$table;
        $result = [];
        foreach ($array as $value) {
            $key = array_search($value, $table, true);

            if (FALSE !== $key) {
                if (!isset($result[$key])) {
                    $result[$key] = 1;
                } else {
                    $result[$key]++;
                }
                continue;
            }

            if ($exit) {
                break;
            }

            $key          = count($table);
            $table[$key]  = $value;
            $result[$key] = 1;
        }

        return $result;
    };

This keeps a table of values so that both arrays can use the same index. Also it's possible to exit early the first time in the second array a new value is experienced.
This function can also add the strict context by having an additional parameter. And by adding another additional parameter would then allow to enable looking for duplicates or not. The full example:
function array_equal_values(array $a, array $b, $strict = FALSE, $allow_duplicate_values = TRUE) {

    $add = (int)!$allow_duplicate_values;

    if ($add and count($a) !== count($b)) {
        return FALSE;
    }

    $table = [];
    $count = function (array $array) use (&$table, $add, $strict) {
        $exit   = (bool)$table;
        $result = [];
        foreach ($array as $value) {
            $key = array_search($value, $table, $strict);

            if (FALSE !== $key) {
                if (!isset($result[$key])) {
                    $result[$key] = 1;
                } else {
                    $result[$key] += $add;
                }
                continue;
            }

            if ($exit) {
                break;
            }

            $key          = count($table);
            $table[$key]  = $value;
            $result[$key] = 1;
        }

        return $result;
    };

    return $count($a) == $count($b);
}

Usage Examples:
array_equal_values(['2.0', '2', 2], ['2', '2.0', 2], TRUE);           # TRUE
array_equal_values(['2.0', '2', 2, 2], ['2', '2.0', 2], TRUE);        # TRUE
array_equal_values(['2.0', '2', 2, 2], ['2', '2.0', 2], TRUE, FALSE); # FALSE
array_equal_values(['2'], ['2'], TRUE, FALSE);                        # TRUE
array_equal_values([2], ['2', 2]);                                    # TRUE
array_equal_values([2], ['2', 2], FALSE);                             # TRUE
array_equal_values([2], ['2', 2], FALSE, TRUE);                       # FALSE

A: Just check $a1 == $a2 -- what's wrong with that?

A: array_intersect() returns an array containing all the common values.

A: Conclusion from the commentary here:
Comparison of array values being equal (after type juggling) and in the same order only:
array_values($a1) == array_values($a2)

Comparison of array values being equal (after type juggling) and in the same order and array keys being the same and in the same order:
array_values($a1) == array_values($a2) && array_keys($a1) == array_keys($a2)

A: @Cleanshooter i'm sorry but this does not do, what it is expected todo: (so does array_diff mentioned in this context)
$a1 = array('one','two');
$a2 = array('one','two','three');

var_dump(count(array_diff($a1, $a2)) === 0); // returns TRUE

(annotation: you cannot use empty on functions before PHP 5.5)
in this case the result is true allthough the arrays are different.

array_diff [...] Returns an array containing all the entries from array1 that are not present in any of the other arrays.

which does not mean that array_diff is something like: array_get_all_differences. Explained in mathematical sets it computes:
{'one','two'} \ {'one','two','three'} = {}

which means something like all elements from first set without all the elements from second set, which are in the first set.
So that
var_dump(array_diff($a2, $a1));

computes to
array(1) { [2]=> string(5) "three" }

The conclusion is, that you have to do an array_diff in "both ways" to get all "differences" from the two arrays.
hope this helps :)

A: A speedy method for comparing array values which can be in any order...
function arrays_are_same($array1, $array2) {
    sort($array1);
    sort($array2);
    return $array1==$array2;
}

So for...
    $array1 = array('audio', 'video', 'image');
    $array2 = array('video', 'image', 'audio');

arrays_are_same($array1, $array2) will return TRUE

A: get the array from user or input the array values.Use sort function to sort both arrays. check using ternary operator. If the both arrays are equal it will print arrays are equal else it will print arrays are not equal. there is no loop iteration here.
sort($a1);
sort($a2);
echo (($a1==$a2) ? "arrays are equal" : "arrays are not equal");

A: If you want to search some array inside a big array of arrays (>10k) then much more quickly is comparing serialized arrays (saved in cache). Example from work with URL:
/**
@return array
*/
function createCache()
{
    $cache = [];
    foreach ($this->listOfUrl() as $url => $args)
    {
        ksort($args);
        $cache['url'][$url] = $args;
        $cache['arr'][crc32(serialize($args))] = $url;
    }
    return $cache;
}

/**
@param array $args
@return string
*/
function searchUrl($args)
{
    ksort($params);
    $crc = crc32(serialize($params));
    return isset($this->cache['arr'][$crc]) ? $this->cache['arr'][$crc] : NULL;
}

/**
@param string $url
@return array
*/
function searchArgs($url)
{
    return isset($this->cache['url'][$url]) ? $this->cache['url'][$url] : NULL;
}

A: verify that the intersections count is the same as both source arrays
$intersections = array_intersect($a1, $a2);
$equality = (count($a1) == count($a2)) && (count($a2) == count($intersections)) ? true : false;

A: Compare values of two arrays:
$a = array(1,2,3);
$b = array(1,3,2);

if (array_diff($a, $b) || array_diff($b, $a)) {
    echo 'Not equal';
}else{
    echo 'Equal';
}

A: If you do not care about keys and that just the values then this is the best method to compare values and make sure the duplicates are counted.
$mag = '{"1":"1","2":"2","3":"3","4":"3"}';
$mag_evo = '1|2|3';

$test1 = array_values(json_decode($mag, true));
$test2 = array_values(explode('|', $mag_evo));

if($test1 == $test2) {
    echo 'true';
}

This will not echo true as $mag has 2 values in the array that equal 3.
This works best if you only care about the values and keys and you do not care about duplication.
    $mag = '{"1":"1","2":"2","3":"3","4":"3"}';
    $mag_evo = '1|2|3';
$test1 = json_decode($mag, true);
$test2 = explode('|', $mag_evo);

// There is no difference in either array.
if(!array_diff($test1, $test2) && !array_diff($test2, $test1)) {
    echo 'true';
}

This will return true as all values are found in both arrays, but as noted before it does not care about duplication.

A: this is a simple way to get the difference:
$array1 = [40,10,30,20,50];
$array2 = [10,30];
$result = array_filter(
                       $array1,
                       function($var) use($array2){
                                if(in_array($var, $array2)){
                                   return $var;
                                }
                         }
             );
print_r($result); //Array ( [0] => 10 [1] => 30 )

A: I just wanted to contribute that:
echo var_export([1 => 2, 0 => 1, 3] == [1, 2, 3], 1);
Echoes true. Therefore the == operator does not check that the elements in the array are in the same order, in the manner you would expect. Meaning array_values of the above are [2, 1, 3] and [1, 2, 3]. Yet because their keys have the same values, they are equal according to == operator.
(Remember [1, 2, 3] creates this array: [0 => 1, 1 => 2, 2 => 3])

A: if(count($a1) == count($a2)){
    $result= array_intersect($a1, $a2);
    if(count($a1) == count($result))
        echo 'the same';
    else
        echo 'a1 different than a2';
} else
        echo 'a1 different than a2';

A: As far as I can tell, there isn't a single built-in function that'll do it for you, however, something like:
if (count($a) == count($b) && (!count(array_diff($a, $b))) {
  // The arrays are the same
}

Should do the trick

A: try this :
$array1 = array("street" => array("Althan"), "city"   => "surat", "state"  => "guj", "county" => "india");
        $array2  = array("street" => array("Althan"), "city"   => "surat", "state"  => "guj", "county" => "india");

    if (array_compare($array1, $array2))
    {
             echo "
";
             print_r("succsses..!");
             echo "
";
             exit;

    }
    else
    {
            echo "
";
            print_r("Faild..!");
            echo "
";
            exit;
    }

    function array_compare($op1, $op2)
    {

            foreach ($op1 as $key => $val)
            {
                    if (is_array($val))
                    {
                            if (array_compare($val, $op2[$key]) === FALSE)
                                    return false;
                    }
                    else
                    {

                            if (!array_key_exists($key, $op2))
                            {
                                    return false; // uncomparable
                            }
                            elseif ($val < $op2[$key])
                            {
                                    return false;
                            }
                            elseif ($val > $op2[$key])
                            {
                                    return false;
                            }
                    }
            }
            return true; // $op1 == $op2
    }


text:
Q: Get an NSWindow object from NSWorkspace? I have the following which opens TextEdit using a Cocoa objective-c application:
[[NSWorkspace sharedWorkspace] openFile:@"/Users/abs/Documents/my.txt" withApplication:@"TextEdit"];

 NSDictionary * currentAppInfo = [[NSWorkspace sharedWorkspace] activeApplication];

 int pid = [[currentAppInfo objectForKey: @"NSApplicationProcessIdentifier"] intValue];

However, I am trying to get a NSWindow object or the likes for the application that I've just opened. So I can set height and width and various other things. How can I do this?

A: AppleScript is the way to go:
set theFile to "/Users/Anne/Desktop/File.txt"
tell application "TextEdit"
    open (POSIX file theFile) as alias
    set bounds of window 1 to {10, 10, 100, 100}
end tell

Use NSAppleScript to run the script:
NSString *path = @"/Users/Anne/Desktop/File.txt";

int X = 10;
int Y = 10;
int width = 400;
int height = 800;

NSString *theSource = [NSString stringWithFormat:@""
                       "set theFile to \"%@\"\n"
                       "tell application \"TextEdit\"\n"
                       "open (POSIX file theFile) as alias\n"
                       "set bounds of window 1 to {%d, %d, %d, %d}\n"
                       "end tell",
                       path,X,Y,width,height];

NSAppleScript *theScript = [[NSAppleScript alloc] initWithSource:theSource];
[theScript executeAndReturnError:nil];

A: Can't imagine how that's possible (what if you opened a Carbon app? or the app didn't open a window at all?).
Sometimes the Accessibility API lets you do things of this nature.


text:
Q: Proving an inequality about hitting time of a Markov chain Q) Let $T_C = \text{inf}\{n\geq 1:X_n\in C\}$. Suppose that $S-C$ is finite and for each $x\in S-C$, $P_x(T_C<\infty)>0$. Show that there is an $N<\infty$ and $\epsilon>0$ s.t. for all $x\in S-C, P_x(T_C>kN)\leq (1-\epsilon)^k$.
Couple of questions to make sure I am using the hypothesis of the question correctly.
$1$) Since $P_x(T_C<\infty)>0$, does that mean $\exists$ $N_x$ for each $x\in S-C$ s.t. $P_x(T_C<N_x)>0$?
$2$) Since $S-C$ is finite, there exists an $N=\underset{x\in S-C}{\text{max}}N_x$?
If the above are true, I can take $\epsilon=\text{min}_xP(T_C<N)$ and
$$P_x(T_C>kN)= P_x(T_C\circ \theta_{(k-1)N}>N;1_{\{T_C>(k-1)N\}}) = E_x(E_x(1_{\{T_C\circ \theta_{(k-1)N}>N\}}|\mathcal{F}_{\{(k-1)N\}});1_{\{T_C>(k-1)N\}}) = P_{X_{(k-1)N}}(T_C>N)P_x(T_C>(k-1)N)\leq (1-\epsilon).P_x(T_C>(k-1)N)$$
and the answer follows by induction. Thanks.

A: 1) and 2) are both correct. 1) follows from the fact $(T_C <\infty)=\bigcup_N (T_C <N)$.


text:
Q: excel not refreshing all pivot tables I am trying to refresh pivot tables using vba.
I have code that modifies the underlying table query, and refreshes the query.
Once that is done, it refreshes the pivot tables, which in turn will refresh a summary sheet. For some reason, the final pivot table is not being refreshed. It will refresh normally.
Methods tried:
1.
Dim PC As PivotCache
For Each PC In ThisWorkbook.PivotCaches
    While DateDiff("s", PC.RefreshDate, Now) > 60
    PC.Refresh
    Wend
Next

2.
Sheets("Pivots").PivotTables("Pivot1").PivotCache.Refresh
Sheets("Pivots").PivotTables("Pivot2").PivotCache.Refresh
Sheets("Pivots").PivotTables("Pivot3").PivotCache.Refresh
Sheets("Pivots").PivotTables("Pivot4").PivotCache.Refresh

3.
ThisWorkbook.RefreshAll

I have tried including a DoEvents before refreshing pivot tables, after the refresh of the tables has occurred.
I have also tried copying the file to another file, and recreating it there. the effect stays, it simply moves to whichever pivot table it considers the last one created.
File size is 279Kb as xlsb, and 336 Kb as xlsm.
Data for the tables is coming from SQL server 2012, and all tables are on the same excel sheet. The tables are updated, but the pivot is not.

A: Try something like
Sub refreshTables()
Dim pt As PivotTable
Dim ws As Worksheet
For Each ws In Worksheets
    For Each pt In ws.PivotTables
        pt.RefreshTable
    Next pt
Next ws
End Sub


text:
Q: getting navigator.getUserMedia() no longer works in insecure origins I am using navigator.getUserMedia to capture webcam images in html5.It works fine till last week.Now getting messages like getUserMedia()  no longer works  in insecure origins and capturing image from webcam broken . I searched about getUserMedia in web and find it is deprecated and browsers do not support it future. Is there any alternative function for  getUserMedia that works in all browsers.
my html code is
  <video id="video" width="640" height="480" autoplay></video>
  <button id="snap" class="sexyButton">Snap</button>
   <canvas id="canvas" width="640" height="480"></canvas>

and script function is
         <script>
    window.addEventListener("DOMContentLoaded", function() {
        // Grab elements, create settings, etc.
        var canvas = document.getElementById("canvas"),
            context = canvas.getContext("2d"),
            video = document.getElementById("video"),
            videoObj = { "video": true },
            errBack = function(error) {
                console.log("Video capture error: ", error.code);
            };
        if(navigator.getUserMedia) { // Standard
            navigator.getUserMedia(videoObj, function(stream) {
                video.src = stream;
                video.play();
            }, errBack);
        } else if(navigator.webkitGetUserMedia) { // WebKit-prefixed
            navigator.webkitGetUserMedia(videoObj, function(stream){
                video.src = window.webkitURL.createObjectURL(stream);
                video.play();
            }, errBack);
        } else if(navigator.mozGetUserMedia) { // WebKit-prefixed
            navigator.mozGetUserMedia(videoObj, function(stream){
                video.src = window.URL.createObjectURL(stream);
                video.play();
            }, errBack);
        }

        // Trigger photo take
        document.getElementById("snap").addEventListener("click", function() {
            context.drawImage(video, 0, 0, 640, 480);
        });
    }, false);

         </script>

A: Chrome now (as of 47+) enforces a new security rule that pages using getUserMedia must be served over HTTPS. This is to reduce the risk of malicious actors using camera or microphone devices to spy on users. It has been announced for over 4 months.

*

*https://twitter.com/juberti/status/659192698214023168

*https://groups.google.com/forum/#!topic/discuss-webrtc/efuWL9JqoOo
As for your other comment that "getUserMedia in web and find it is deprecated and browsers do not support it future" - this is entirely incorrect.

A: Chrome 47, getUserMedia() no longer works on insecure origins
Few days ago Chrome 47 has been released.
One major change is WebRTC won't work without HTTPS.
According internal security policy Chrome browser does not support getUserMedia() for unsecure pages since version 47. So you will not be able to use microphone if your page is not HTTPS.
http://flashphoner.com/getusermedia-no-longer-works-on-insecure-origins/


text:
Q: Get object ID inside array Mongodb Nodjs REST API I have been created a rest api with nodejs and mongodb atlas.
I have an array of objects each object has an id and I want to get those object by id

exports.GetUserInfo = (req , res  , next)=>{
Client.find({ReadingHistory:
mongoose.Schema.ObjectId("5e557c8f0fda580b28866b9f")})
.select()
.exec()
.then(doc=>{
    if (doc) {
        console.log('from the database',doc);
    } else {
        console.log('invalid ID')
    }

        if (doc) {
            res.status(200).json({
                ReadingHistory: doc,

            });
        } else {
            res.status(404).json({message: 'Sorry... no data'})
        }

  })
     .catch(err =>{
        console.log(err);
        res.status(500).json({error: err})
     });
}

}

A: The ObjectId from MongoDB can't be compared by === or !==, we have to use ObjectId.prototype.equals. So you can write the following code:
function find(id) {
  return resultArray.find(obj => obj._id.equals(id));
}

And the complete pseudo code could be:
exports.GetUserInfo = (req , res , next) => {
  const conditions = {id: req.params.clientId};
  const result = Client.find(conditions); // suppose Client.find() returns the query result from mongodb.
  return result.ReadingHistory.find(Obj => obj._id.equals(conditions));
}


text:
Q: Is support function of a convex curve in $\mathbb{R}^2$ absolutely continuous? There is an example of a convex function of two variables that is convex but not absolutely continuous. The level set of this function is a convex curve.
To construct one example of such a function one needs to take a Cantor ladder $c$ and define $f(x,y) = g(x+y)$ where $g(x) = \int_0^x c(t) dt$.
Is it possible to give a example of a convex curve whose support function is not absolutely continuous?


text:
Q: Create word cloud (word mosaic) programmatically I'm writing an ios app that can create a word cloud or word mosaic with a pattern selected by user. My question is, how can I calculate the coordinates of each word, considering the sizes of each word is randomly calculated? Or any other approach?

Note that the pattern I want to work on is like this

but, rather like that, my app will fill the white areas with word mosaic, while preserving the photo of the user.
[EDIT]
my algorithm right now is to randomly set the size and position of each words and just put them there. How can I check if each word that I'm putting doesn't intersect with each other and the photo?
Reference: http://www.imagechef.com/ic/word_mosaic/


text:
Q: How to extract compressed MNIST dataset into test, train sets? I'm trying to extract a compressed MNIST file from here.
How can I do it from python script and split into train nd test samples.
Code which I tried
def fetch(url):
  import requests, gzip, os, hashlib, numpy
  fp = os.path.join("/tmp", hashlib.md5(url.encode('utf-8')).hexdigest())
  if not os.path.isfile(fp):
    with open(fp, "rb") as f:
      dat = f.read()
  else:
    with open(fp, "wb") as f:
      dat = requests.get(url).content
      f.write(dat)
  return numpy.frombuffer(gzip.decompress(dat), dtype=np.uint8).copy()
X_train = fetch("http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz")[0x10:].reshape((-1, 28, 28))
Y_train = fetch("http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz")[8:]
X_test = fetch("http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz")[0x10:].reshape((-1, 28, 28))
Y_test = fetch("http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz")[8:]

I get error FileNotFoundError: [Errno 2] No such file or directory: '/tmp/d8b415e67abd11881e156b8f111d3300'
when I try The if not os.path.isfile(fp):  be if os.path.isfile(fp):.
I get error
> TypeError Traceback (most recent call last)
> <ipython-input-3-a98ee7ff45b8> in <module> 14 f.write(dat) 15 return
> numpy.frombuffer(gzip.decompress(dat), dtype=np.uint8).copy()
> ---> 16 X_train = fetch("http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz")[0x10:].reshape((-1,
> 28, 28)) 17 Y_train =
> fetch("http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz")[8:]
> 18 X_test =
> fetch("http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz")[0x10:].reshape((-1,
> 28, 28))
>
> TypeError: 'NoneType' object is not subscribable

How to fetch them successfully?


text:
Q: How do I save data of the user? I have Model:
models.py
class UserProfile(models.Model):
    user = models.OneToOneField(User, related_name='userprofile')
    points = models.IntegerField(default=0)

urls.py
urlpatterns = [
    url(r'^$', demo),
    url(r'^demo/$', demo),
]

demo.html
<form action="" method="POST">
    <button type="submit">+</button>
</form>

views.py
def demo(request):
    if request.method == "POST":
    # I don't understand how I can get "points" from the model   "UserProfile"
    #to add 1 and  to save in the DB
    return render(request, 'app/demo.html')

I would like that after pressing on the button points of the user increased one. I really cannot figure it out.

A: Try something like this
def demo(request):
    if request.method == "POST":
        profile = UserProfile.objects.get(user=request.user)
        profile.points += 1
        profile.save()
        return render(request, 'app/demo.html', {"user":request.user,
                                                 "profile":profile)


text:
Q: Trying to use custom hook gives error "Block-scoped variable 'X' used before its declaration." I am trying to write my first custom hook.
I don't understand why the error is showing, as the function is declared a few lines above where it is called.
Relevant code:
function getNextAnswerState(answer: string) {
  switch (answer) {
    case "blank":
      return ("correct");
    case "correct":
      return ("wrong");
    case "wrong":
      return ("forgotten");
    case "forgotten":
      return ("blank");
  }
  return "blank";
}

function useAnswerState() {
  const [answer, setAnswer] = useState("blank");

  const handleGetNextCellStatus = () => {
    let nextCellStatus = getNextAnswerState(answer)
    setAnswer(nextCellStatus);
  }

  return {answer, handleGetNextCellStatus};
}

interface letterProps {
  cellIndex: number,
  layerSize: number,
  letter: string
}

function LetterCell({cellIndex, layerSize, letter}: letterProps) {
  const {answerStatus, setAnswerToNext} = useAnswerState();
  ...

The errors:
[tsserver 2448] [E] Block-scoped variable 'useAnswerState' used before its declaration.
[tsserver 2454] [E] Variable 'useAnswerState' is used before being assigned.

A: Looks like it was a small syntax error somewhere.


text:
Q: Internal Server Error and no error logs show a error I installed Ckan 2.8.2. I start the application and it run. But if I click on groups, dataset or organization - I got a "internal server error".
I increase the log-level. I search in every logfile. I restart database before starting Ckan. I created the datastore, set permissions.
I use tail -f to monitor postgres behavior. I looked the output over paster in the python virtual-env.
Expected result is no internal error, and I can read and upload datasets.
One time I could do it, and after that nothing works, only login, create user etc.
Here the Ckan config file:
[DEFAULT]

# WARNING: *THIS SETTING MUST BE SET TO FALSE ON A PRODUCTION ENVIRONMENT*
#debug = true

[server:main]
use = egg:Paste#http
host = 0.0.0.0
port = 5000

[app:main]
use = egg:ckan
full_stack = true
cache_dir = /tmp/%(ckan.site_id)s/
beaker.session.key = ckan

# This is the secret token that the beaker library uses to hash the cookie sent
# to the client. `paster make-config` generates a unique value for this each
# time it generates a config file.
beaker.session.secret = BbMsj+g52f3rb72NrsGp3sFLh

# `paster make-config` generates a unique value for this each time it generates
# a config file.
app_instance_uuid = 60fbd1aa-28fb-4813-8521-6013b7b6edce

# repoze.who config
who.config_file = %(here)s/who.ini
who.log_level = warning
who.log_file = %(cache_dir)s/who_log.ini
# Session timeout (user logged out after period of inactivity, in seconds).
# Inactive by default, so the session doesn't expire.
# who.timeout = 86400

## Database Settings
sqlalchemy.url = postgresql://ckan_default:#####@localhost/ckan_default

ckan.datastore.write_url = postgresql://ckan_default:#####@localhost/datastore_default
ckan.datastore.read_url = postgresql://datastore_default:######@localhost/datastore_default

# PostgreSQL' full-text search parameters
ckan.datastore.default_fts_lang = english
ckan.datastore.default_fts_index_method = gist

Site Settings
ckan.site_url = http://localhost:5000
ckan.use_pylons_response_cleanup_middleware = true

## Authorization Settings

ckan.auth.anon_create_dataset = false
ckan.auth.create_unowned_dataset = false
ckan.auth.create_dataset_if_not_in_organization = false
ckan.auth.user_create_groups = false
ckan.auth.user_create_organizations = false
ckan.auth.user_delete_groups = true
ckan.auth.user_delete_organizations = true
ckan.auth.create_user_via_api = false
ckan.auth.create_user_via_web = true
ckan.auth.roles_that_cascade_to_sub_groups = admin

## Search Settings

ckan.site_id = default
solr_url = http://127.0.0.1:8983/solr/#/ckan

## Redis Settings

# URL to your Redis instance, including the database to be used.
ckan.redis.url = redis://localhost:6379/0

## CORS Settings

# If cors.origin_allow_all is true, all origins are allowed.
# If false, the cors.origin_whitelist is used.
# ckan.cors.origin_allow_all = true
# cors.origin_whitelist is a space separated list of allowed domains.
# ckan.cors.origin_whitelist = http://example1.com http://example2.com

## Plugins Settings

# Note: Add ``datastore`` to enable the CKAN DataStore
#       Add ``datapusher`` to enable DataPusher
#       Add ``resource_proxy`` to enable resorce proxying and get around the
#       same origin policy
ckan.plugins = stats text_view image_view recline_view

# Define which views should be created by default
# (plugins must be loaded in ckan.plugins)
ckan.views.default_views = image_view text_view recline_view

# Customize which text formats the text_view plugin will show
#ckan.preview.json_formats = json
#ckan.preview.xml_formats = xml rdf rdf+xml owl+xml atom rss
#ckan.preview.text_formats = text plain text/plain

# Customize which image formats the image_view plugin will show
#ckan.preview.image_formats = png jpeg jpg gif

## Front-End Settings

# Uncomment following configuration to enable using of Bootstrap 2
#ckan.base_public_folder = public-bs2
#ckan.base_templates_folder = templates-bs2

ckan.site_title = test
ckan.site_logo = /base/images/ckan-logo.png
ckan.site_description =
ckan.favicon = /base/images/ckan.ico
ckan.gravatar_default = identicon
ckan.preview.direct = png jpg gif
ckan.preview.loadable = html htm rdf+xml owl+xml xml n3 n-triples turtle plain atom csv tsv rss txt json
ckan.display_timezone = server

# package_hide_extras = for_search_index_only
#package_edit_return_url = http://another.frontend/dataset/<NAME>
#package_new_return_url = http://another.frontend/dataset/<NAME>
#ckan.recaptcha.publickey =
#ckan.recaptcha.privatekey =
#licenses_group_url = http://licenses.opendefinition.org/licenses/groups/ckan.json

# ckan.template_footer_end =

## Internationalisation Settings
ckan.locale_default = en
ckan.locale_order = en pt_BR ja it cs_CZ ca es fr el sv sr sr@latin no sk fi ru de pl nl bg ko_KR hu sa sl lv
ckan.locales_offered =
ckan.locales_filtered_out = en_GB

## Feeds Settings

ckan.feeds.authority_name =
ckan.feeds.date =
ckan.feeds.author_name =
ckan.feeds.author_link =

## Storage Settings

ckan.storage_path = /var/lib/ckan
ckan.max_resource_size = 10
ckan.max_image_size = 2

## Datapusher settings

# Make sure you have set up the DataStore

ckan.datapusher.formats = csv xls xlsx tsv application/csv application/vnd.ms-excel application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
ckan.datapusher.url = http://127.0.0.1:8800/
#ckan.datapusher.assume_task_stale_after = 3600

# Resource Proxy settings
# Preview size limit, default: 1MB
#ckan.resource_proxy.max_file_size = 1048576
# Size of chunks to read/write.
#ckan.resource_proxy.chunk_size = 4096

## Activity Streams Settings

#ckan.activity_streams_enabled = true
#ckan.activity_list_limit = 31
#ckan.activity_streams_email_notifications = true
#ckan.email_notifications_since = 2 days
ckan.hide_activity_from_users = %(ckan.site_id)s

## Email settings

#email_to = errors@example.com
#error_email_from = ckan-errors@example.com
#smtp.server = localhost
#smtp.starttls = False
#smtp.user = username@example.com
#smtp.password = your_password
#smtp.mail_from =

## Logging configuration
[loggers]
keys = root, ckan, ckanext

[handlers]
keys = console

[formatters]
keys = generic

[logger_root]
level = DEBUG
handlers = console

[logger_ckan]
level = DEBUG
handlers = console
qualname = ckan
propagate = 0

[logger_ckanext]
level = DEBUG
handlers = console
qualname = ckanext
propagate = 0

[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic

[formatter_generic]
format = %(asctime)s %(levelname)-5.5s [%(name)s] %(message)s


text:
Q: Working with Redis to store Session - Django I have installed django-redis-session via pip and add this settings to the settings.py file:
SESSION_ENGINE = 'redis_sessions.session'

When I go to the terminal and type:
$ redis-cli monitor

I can see there are changes when I log in and log out (using python-social-auth).
My question is: How can I get the session (from redis) based on the user?
If I call is_authenticated() User's function it works, but my DB's (PostgreSQL) Session table has 0 rows.
Fianlly, is there any way to write the session key and data manually? I will need to use a complex PK for session based in two fields stored in redis.

A: You should be able to get the current session with request.session. This should work, whichever session backend you use, whether or not the user is logged in.
See the docs on using sessions in views for more info.


text:
Q: Ubuntu 16.04 Firefox can't play some video despite flash installed I'm facing an issue with Firefox 59.0.2 in Ubuntu 16.04 (up to date): Some video simply won't play.
All youtube videos work, but the following doesn't work (it loads forever):
https://www.reddit.com/r/Breath_of_the_Wild/comments/89uxbm/this_is_without_a_doubt_the_hardest_shrine/
It works in both Google Chrome and Opera. Is this a Flash problem? (I think both Chrome and Opera include their own flash renderer).
I already have adobe-flashplugin installed on my system.
Could you please help me troubleshoot this issue?
Many Thanks!


text:
Q: Cake PHP parent/child/grandchildren menus i want to display menus with their children and grand children
output will be like this
Parent
-child
-grandchildren
Parent 1
-child
heres my function in my MenuItemsController
public function buildTree($arr, $parent_id = 0) {
    $op=array();
    foreach ($arr as $item){
    if ($item['parent_id']== $parent_id){
                       $op[$item['id']]=array('name'=>$item['name'],'parent'=>$item['parent_id']
    );
            $children=buildtree($arr,$item['id']);
            if (children) {
            $op[$item['id']]['parent_id']  =$children;

           }
          }
        }

        return $op;

    }

Heres on my View Element app\view\elements\navigation.ctp
<?php
    App::import('Controller', 'MenuItems');
    $menu_items = new MenuItemsController();

?>

<?php
foreach($mainMenuItems as $item) {
echo "
".$item['MenuItem']['name']."
";
$child=$menu_items->buildsubmenus($item['MenuItem']['id']);
            pr($child);
}

?>

A: Your controller needs to generate the tree and pass it to the view. How to generate it? it depends on your application, maybe you need to call the data base, maybe it's just a static array, etc.
You'll need to create your own format for the tree, for example:
Array
(
    [0] => Array
        (
            [0] => child 11
            [1] => Array
                (
                    [0] => grandchild 121
                    [1] => grandchild 122
                )

        )

    [1] => parent 2
    [2] => Array
        (
            [0] => child 31
        )

)

then you can pass it to the view and loop the array to create the menu. To do that , you could use a recursive function to display the array.. or if you know that there wont be more than 3 levels you could simply use 3 for loops
=) so this has nothing to do with cakephp.. however, if your menu is stored on the database, maybe you could use the tree behaviour to retrieve the menu from the DB, however you'll still need to pass it to the view and create a function to display it
Hope this helps


text:
Q: How to add an item to database directly in django without forms I know, this question has already been discussed, but I am unable to grab that.
Here are two models I have
# Create your models here.
GENDER_CHOICES = [
    ('Male', 'M'),
    ('Female', 'F')]
class upload(models.Model):
    name = models.CharField(max_length=100,null=True)
    gender = models.CharField(max_length=10,null=True, choices=GENDER_CHOICES)
    phone = models.CharField(max_length=50,null=True)
    email=  models.EmailField(max_length=50,null=True)
    file=models.FileField(upload_to='uploads/',null=True)

    def __str__(self):
        return self.name

class text(models.Model):
    texts=models.CharField(max_length=200,null=True,blank=True)
    upload_text=models.ForeignKey(upload, blank=True, null=True, on_delete = models.CASCADE)

I have a form for model upload. I inserted the data, and an audio file. Then I want this audio file to convert to text and save the text in the database.
For that purpose, I created another model text.
But I don't know how to insert the text to this model in relation to the information entered in model upload
Here is my views.py file function
def display(request):
    print('display functio')
    d=upload.objects.last()
    test=sr.takeCommand(d.file.path)
    print(test) **# I can see text here**
    p = text.objects.create(texts=test)
    p.save(force_insert=True)
    print(test)
    return render(request,'thanks.html',{'print':test})

But I am unable to enter it. It throws an error
UNIQUE constraint failed: sub_app_text.id

A: This is because you insert it twice. The .create(…) method [Django-doc] already inserts in in the database. So you can implement this as:
def display(request):
    print('display functio')
    d=upload.objects.last()
    test=sr.takeCommand(d.file.path)
    # will store the record in the database
    p = text.objects.create(texts=test)
    print(test)
    return render(request,'thanks.html',{'print':test})
you can link it to d with:
def display(request):
    print('display functio')
    d=upload.objects.last()
    test=sr.takeCommand(d.file.path)
    # will store the record in the database
    p = text.objects.create(texts=test, upload_text=d)
    print(test)
    return render(request,'thanks.html',{'print':test})

Note: Models in Django are written in PerlCase, not
snake_case, so you might want to rename the model from text to Text.


text:
Q: How can I create a custom HTMLHelper extension that handles an item with an index In my MVC4 website, I have a page where I'm looping through a list of items that are part of my model and putting them in a table.
My model is named JobModel and it has a list of TaskModel objects accessible in a property named Tasks.
I'm using syntax like this for each item in the list...
@Html.DisplayFor(m => m.Tasks[i].TaskName)
@Html.DisplayFor(m => m.Tasks[i].TaskName)

This works fine.
However, I have a need to create a Custom DisplayFor extension, that I'll name DisplayFor2 for this discussion.
My code looks like this...
public static IHtmlString DisplayFor2<TProperty>(this HtmlHelper<TaskModel> html, Expression<Func<TaskModel, TProperty>> ex) {
   //Build my custom html here...
}

When I attempt this code,
@Html.DisplayFor2(m => m.Tasks[i].TaskName)

I get the compiler complaining that:
The type arguments for method 'IHtmlString MySite.HtmlHelpers.HelperExtensions.DisplayFor2<TProperty>(this HtmlHelper<TaskModel>, Expression<Func<TaskModel,TProperty>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

What do I need to do?
*UPDATE*
I changed my method to this, and now it works.
public static IHtmlString TableCellFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> ex)

But when I do this, I don't know the index of the child item, so it's proven useless.


text:
Q: How to access a struct from an external package in Go I'm trying to import a struct from another package in the following file:
// main.go
import "path/to/models/product"
product = Product{Name: "Shoes"}

// models/product.go
type Product struct{
 Name string
}

But in the main.go file the struct Product is undefined. How do I import the struct?

A: In Go you import "complete" packages, not functions or types from packages.
(See this related question for more details: What's C++'s `using` equivalent in golang)
See Spec: Import declarations for syntax and deeper explanation of the import keyword and import declarations.
Once you import a package, you may refer to its exported identifiers with qualified identifiers which has the form: packageName.Identifier.
So your example could look like this:
import "path/to/models/product"
import "fmt"

func main() {
    p := product.Product{Name: "Shoes"}
    // Use product, e.g. print it:
    fmt.Println(p) // This requires `import "fmt"`
}


text:
Q: Getting cookie value from cookie string javascript I'm trying to reload the page only when the cookie (userInfo) value includes pageCount=1.
This is my cookie value for userInfo:
lastBranchVisitedName=No branch set&mostRecentBranchId=&pageCount=4&lastPageUrl=/personal/life-health/over-50s-insurance/&allocatedBranchId=70&allocatedBranchTelephone=01993 894 700&allocatedBranchName=Motor Direct&locationLatitude=51.8969248&locationLongitude=-2.0758525999999997&lastPageDateTime=28/03/2017 14:37:26

What i am trying to achieve is that once the geoLocation is allowed, if the pageCount=1 then reload the page once. Currently the page is reloading regardless of what pageCount=.
Here is my current Javascript:
// Hide / show notification depending on cookie
window.onload = function () {

if (setCookieValue("geoPopUpCompleted") == undefined) {

    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(setPosition);

    } else {
        alert("Unfortunately we're unable to find your location");
    }

}

// Get page count
var pageCount = getCookie("pageCount");
function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}

function setPosition(position) {
    setCookieValue("locationLongitude", position.coords.longitude);
    setCookieValue("locationLatitude", position.coords.latitude);
    setCookieValue("geoPopUpCompleted", true);

    if (pageCount) {
        (function () {
            if (window.localStorage) {
                if (!localStorage.getItem("firstLoad")) {
                    localStorage["firstLoad"] = true;
                    window.location.reload();
                }
                else
                    localStorage.removeItem("firstLoad");
            }
        })();
   }
}
}

// GEO cookie settings
function setCookieValue(cookieName, cookieValue) {
    var cookieExpireDate = "expires=Sun, 31 Dec 4017 12:00:00 UTC; path=/";
    document.cookie = cookieName + "=" + cookieValue + "; " + cookieExpireDate;
}

Not looking for JQuery solutions.
Thanks for your help

A: The following code that worked for me... hope this helps someone else.
// Hide / show notification depending on cookie
window.onload = function () {

if (setCookieValue("geoPopUpCompleted") == undefined) {

    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(setPosition);

    } else {
        alert("Unfortunately we're unable to find your location");
    }

}

function setPosition(position) {
    setCookieValue("locationLongitude", position.coords.longitude);
    setCookieValue("locationLatitude", position.coords.latitude);
    setCookieValue("geoPopUpCompleted", true);

    // Get page count
    var pageCount = getCookie("pageCount");
    function getCookie(c_name) {
        if (document.cookie.length > 0) {
            c_start = document.cookie.indexOf(c_name + "=1");
            if (c_start != -1) {
                c_start = c_start + c_name.length + 1;
                c_end = document.cookie.indexOf(";", c_start);
                if (c_end == -1) c_end = document.cookie.length;
                return unescape(document.cookie.substring(c_start, c_end));
            }
        }
        return "";
    }

    // Reload page once
    if (pageCount) {
        (function () {
            if (window.localStorage) {
                if (!localStorage.getItem("firstLoad")) {
                    localStorage["firstLoad"] = true;
                    window.location.reload();
                }
                else
                    localStorage.removeItem("firstLoad");
            }
        })();
    }
}
}

// GEO cookie settings
function setCookieValue(cookieName, cookieValue) {
var cookieExpireDate = "expires=Sun, 31 Dec 4017 12:00:00 UTC; path=/";
document.cookie = cookieName + "=" + cookieValue + "; " + cookieExpireDate;
}


text:
Q: Outlook Calendar my outlook calendar does not load. if go to the event viewer in control panel i get this message.
Faulting application name: HxCalendarAppImm.exe, version: 16.0.14326.21344, time stamp: 0x63ed45a6
Faulting module name: KERNELBASE.dll, version: 10.0.19041.2546, time stamp: 0xe8e9ac9b
Exception code: 0xc000027b
Fault offset: 0x000000000010fd12
Faulting process id: 0x3104
Faulting application start time: 0x01d94cecbbc6eb25
Faulting application path: C:\Program Files\WindowsApps\microsoft.windowscommunicationsapps_16005.14326.21344.0_x64__8wekyb3d8bbwe\HxCalendarAppImm.exe
Faulting module path: C:\Windows\System32\KERNELBASE.dll
Report Id: 78ba004a-bb0b-41b5-9f07-f8ad0eaf9b6a
Faulting package full name: microsoft.windowscommunicationsapps_16005.14326.21344.0_x64__8wekyb3d8bbwe
Faulting package-relative application ID: microsoft.windowslive.calendar
i uninstalled the program and reinstalled it same fault


text:
Q: 1-dimensional diffusion process Let $(X_t, t ≥ 0)$ be a 1-dimensional diffusion process with generator $Af(x) =\frac{1}{2}a(x)f''(x)+b(x)f'(x), \mathcal{D}(A)=C^2({\mathbb{R}})$ where $b$ and $a=\sigma^2$ are continuous functions of $x$ and $\sigma(x)> 0$ for all $x$. Let $\tau_0=\inf\{t\ge 0: X_t=0\}.$
1) Suppose that for some $x_0$, $b(x)\leq 0,$ for all $x\ge x_0$. Show that for any $x> 0$: $\mathcal{P}^{x}[\tau_0< \infty]=1.$
2) Suppose that for some $x_0,$ $\frac{b(x)}{a(x)}>\epsilon> 0,$ for all $x\ge x_0.$ Show that for any $x> 0$: $\mathcal{P}^x[\tau_0< \infty]<1$

A: This is Exercise 3.1 (page 221) in Rick Durrett's Stochastic Calculus: A Practical Introduction. There is a solution in the back.
You use the fact that ${\cal P}^x(\tau_0<\infty)=1$ if and only if $\varphi(\infty)=\infty$ where $\varphi$ is the natural scale function $$\varphi(x)=\int_0^x\exp\left(\int_0^y-{2b(z)\over a(z) }dz \right)dy.$$


text:
Q: How to read in integers (X and Y points) from a file and plot a least regression line in Java? Error So, Assuming I'm to read from a .txt file a set of points and plot a least square regression line on top of the points.  (i'm not that familiar with stats either)

My program would plot the points using text (for example, with "X"s representing the points, "-"s the regression line segments,
  and " * "s where a line segment and a point are located at the same spot)

These are the points to be read from the file (first integer x and second y). x-coordinates are in the range [0, 40] and the y-coordinates in the range [1, 20].
20 10
0  1
40 20
13 17
13 12
10 ?
the x coordinates represent time
15 0
10 20

There are some invalid points in this text but the program would eventually ignore it but do not stop reading the file.
Here's what i've come up with, but still gives error of ArrayIndexBound:2
import java.awt.*;
import java.io.*;
import java.util.StringTokenizer;

public class A{
    public static void main(String[] args){

        processValuesFromFile("points.txt");

    }

    public static void processValuesFromFile(String filename){
        BufferedReader inputFile;
        String line;
        int[][] points;

        try{
            inputFile = new BufferedReader(new FileReader(filename));
            line = inputFile.readLine();

            while(line!= null){
                points = readPoints(inputFile,line);
                printPoints(points);
                //
                line = inputFile.readLine();
            }
            inputFile.close();

        }catch (IOException | ArrayIndexOutOfBoundsException ioe){
            System.out.println(ioe.getMessage());
            //ioe.printStackTrace();
        }
    }

    public static int[][] readPoints(BufferedReader inputFile, String line) throws IOException{
        String[] split;
        String inputLine;
        int[][] points;
        int pointSize = 9;

        points = new int[pointSize][pointSize];
        for(int row=0; row<pointSize;row++){
            inputLine = inputFile.readLine();
            System.out.println(inputFile);
            split = inputLine.split("\\s+");

            for(int col =0; col <pointSize;col++){
                points[row][col] = Integer.parseInt(split[col]);
            }

        }
        return points;

    }

    public static void printPoints(int[][] points) {
        for (int row=0; row < points.length; row++) {
            for (int col=0; col < points[row].length; col++) {
                System.out.print(points[row][col] +"\t");
            }
            System.out.println();
        }
    }
}

A: It's better to create a class that represent the points.
class Point{

int x;
int y;

}

and then you create an array or a collection of points
Point[] points = new Point[10];

or
List<Point> points = new ArrayList<Point>();


text:
Q: Android BroadcastReceiver handling multiple messages I wondered how BroadcastReceivers handle multiple message requests (broadcast intents).
Assuming a BroadcastReceiver still processing a message/intent on the UI thread and at the same time another broadcast message(s) is/are fired from some other thread(s). Will the subsuquent broadcast messages be put into a queue or something?
Thx

A: I think what you want is here: http://codetheory.in/android-broadcast-receivers/

Asynchronous Processing
Generally after the execution of onReceive() of the receiver class is
  finished, the Android system is allowed to recycle the receiver, i.e.,
  another intent can be passed to it. For potentially long running
  operations it is recommended to trigger a service instead on the
  context object passed to it. This is a reason why any asynchronous
  operation wasn't allowed to perform till API level 11. But that has
  changed now.
Since API 11, if you want to pass on the processing of some task in
  another thread you could do something like this:
// Sample code from: http://stackoverflow.com/a/22741384

final PendingResult result = goAsync();
Thread thread = new Thread() {
   public void run() {
      int i;
      // Do processing
      result.setResultCode(i);
      result.finish();
   }
};
thread.start();

Using goAsync() we returned an object of the type PendingResult on
  which calling the finish() method indicates the Android system that
  the receiver is no more alive and can be recycled.

What he is saying here, is that your receiver is recycled AFTER it completes execution, meaning that you can receive one at a time, but you can receive many.
EDIT ON COMMENTS
I stand slightly corrected by a statement made by an Android Framework Engineer, Dianne Hackborn (https://groups.google.com/forum/#!topic/android-developers/ClIGNuGJUts):

A particular receiver can only process one broadcast at a time.  As
  each broadcast happens, it is processed to determine the targets it
  should go to, and dispatched into the message queue for each target.

So it seems it does create a queue for you. Honestly I would not recommend relying too much on broadcasts, they are tricky in the best of times, and I have found Message Handlers FAR more reliable. But there are times when they are necessary.
I think the best option here is to actually go and try it and see for yourself what happens.

A: I'm just going to give an example that I used for Bluetooth connection that shows how you use an IntentFilter to pick up different actions:
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
getApplication().registerReceiver(mReceiver, filter);

And the BroadcastReceiver:
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                Toast.makeText(getApplicationContext(), "Device not found", Toast.LENGTH_LONG).show();
        }
    }
};

I hope this helps you.


text:
Q: C# BackgroundWorker Exiting Unexpectedly I have thef ollowing background worker in my app which is meant to start a user's session automatically if there is not already one available.
This is done on a backgroundworker (backgroundInit) on initialisation. As you can see below, I have a while loop which continues to run as long as the var checker remains false:
var checker = false;
var i = 0;
while (checker == false)
{
   _session = funcs.GetSession(_servers, _name);
   _sessID = _session[0].Trim();
   _servName = _session[1];

   checker = funcs.CheckRunning("lync.exe");
   i++;

   if (i > 200)
   {
      break;
   }
}

The CheckRunning method just checks if a specified program (in this case, "lync") is currently running and returns either true or false accordingly (This is done via a CMD command).
When I run the app in an empty session however, the while loop only iterates one time before breaking out, even though "Lync" is definitely not running.
Is there any reason why running a process or too many processes from within a Backgroundworker may cause it to exit?

A: As the comments mentioned, this was not an issue with the BackgroundWorker, but rather an exception occurring at _sessID = session[0].Trim(); where the session had not yet started, so there is no ID.
To resolve this, I simply placed a Try/Catch block around this assignment, and let the program silently ignore the exception:
    try
    {
        _sessID = _session[0].Trim();
        _servName = _session[1];
    }
    catch (Exception exp)
    {
        // MessageBox.Show(exp.Message);
    }

This works for me, as the loop will continue checking until the counter i reaches the 200 limit, at which stage the program will accept failure.