text:
Q: undefined variable confusion codeigniter active records I have the following code,
This is where i process the textfield input type wherein i type in the ingredient of an recipe.
The proper format of how one should input the ingredient is like this.
5-ml milk, 4-ml water, 2-pcs carrot
There are always delimiter in between since i have different columns for quantity, unit of measurement and the name.
I have no problem with the separation. I have another table. Which is named ingredients.
This is where i populate different ingredients like milk and put in what food group they belong and their nutritional info(what it gives off, like calcium).
Anyhow, I get a database error, Somehow, when i try to insert after all that processing, both the type and nutrition are null. I've thought about it, maybe my query was wrong? but it didnt give off any warning or notice. Though it only gave me notice/warning that both the values are undefined when i tried to declare them at array $comp which are the values to be inserted.
I get this error,

Error Number: 1048
Column 'nutrition' cannot be null
INSERT INTO component (componentname, quantity, unit,
  nutrition, type) VALUES ('milk', '5', 'ml', NULL, NULL)
Filename: C:\www\KG\system\database\DB_driver.php
Line Number: 330

The code:
function insertrecipe()
    {
        $ingredients = $this->input->post('ingredients');
        $recipename = $this->input->post('recipename');

        $recipe = array(
            'recipename' => $recipename,
            'description' => $this->input->post('description'),
            'instruction' => $this->input->post('instructions'),
            'serving' => $this->input->post('serving'),
            );

        $this->db->insert('recipe', $recipe);

        $this->ingredient($ingredients,$recipename);
    }

    function ingredient($ingredients,$recipename)
    {
    $ids = array();
    $first_slice = explode(',',$ingredients);
    $secondslice = $this->second_slice($first_slice);

            foreach($secondslice as $qty => $iname)
            {
                $arr = explode('-',$qty);
                $third_slice[$arr[1]] = $arr[0];

                $sql = $this->db
                            ->select('nutrition,group')
                            ->where('ingname', $iname)
                            ->from('ingredients')
                            ->get()
                            ->result_array();

                $result = $this->db->query($sql);

                foreach($result->result_array() as $row)
                {
                $ingredient_type = $this->get_ingredient_type($row['group']);
                }

                foreach($third_slice as $measure => $num)
                {
                $comp = array(
                                'componentname' => $iname,
                                'quantity' => $num,
                                'unit' => $measure,
                                'nutrition' => $nutri,
                                'type' => $ingredient_type
                                );
                    if($insert2 = $this->db->insert('component',$comp))
                    {
                        $latest_id = $this->db->insert_id();

                        $ids[] = $latest_id;
                    }
                }

            }
    }

    function second_slice($data)
    {
            foreach($data as $key => $value)
            {
            $ingredient = explode(' ', trim($value));
            $second_slice[$ingredient[0]] = $ingredient[1];
            }

    return $second_slice;
    }

    function get_ingredient_type($data)
    {
                //foreach($data->result_array() as $row)
                //{
                    if($data['group'] == "vegetable")
                    {
                        $type = 1;
                    }
                    else if($data['group'] == "fruit")
                    {
                        $type = 2;
                    }
                    else if($data['group'] == "dairy")
                    {
                        $type = 3;
                    }
                    else if($data['group'] == "seafood")
                    {
                        $type = 4;
                    }
                    else
                    {
                        $type = 5;
                    }
                //}
    return $type;
    }

The database  table of component has the following columns.
componentid componentname   quantity    unit    nutrition   type

nutrition is varchar unit is int. I guess they're not null or cols that dont accept null values.
I've separated different foreach loops into functions. I originally thought the error was because i had 3-5 for each loop within that function alone. so i decided to separate them into functions.


text:
Q: How can I get a Facebook page share thumbnail to link to a larger image? I recently took a look at Alcatel Philippines' FB page and tried using View Image on the thumbnail of one of their shared links. Instead of getting a tiny thumbnail, I got a rather large, full-sized image.
This is what the post that I'm talking about looks like:

That thumbnail is 90x47 but when I right-click on it and choose View Image, I get shown this. I also noticed that instead of linking directly to an image, it instead links to a php script. How can I do this? Thanks.

A: Nothing strange- that's default by nature.
It's a normal feed. Where you can provide a link and picture. So, whenever you click on that feed it is re-directed to the link. And if you specifically open the picture (right-click on it and choose View Image), it will show the actual image you have provided in the picture url while publishing.
You can look at any feed any app is publishing, it looks just the same!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Double Counting Table Cell in Loop jQuery I am using the below code to loop through the cells in my table which contain an input and totaling them up to display in the total column. Ultimately the #testerField will be changes to $this and fired off of a jQuery listener over the whole table.
The table structure is something like this:
Non Input Cell -> Non Input Cell -> Cell with Input (x8) -> Total Cell
For some reason, it keeps double counting (iterating over) the first cell in the loop. Why is this occurring?
sumFunction = function() {
    var row = $("#testerField").closest("tr");
    var lastCell = row.find("td:last");

    var total = 0;

    row.add('td:has(:input)').each(function() {
        var value = $(this).find(":input").val();

        if (value > 0) {
            total = Number(total) + Number(value);
        }
    });

    lastCell.html(total);
}

Here is the HTML of one Table Row

                        1
                        Trouble
                        <input id="testerField" type="number"/>
                        <input type="number"/>
                        <input type="number"/>
                        <input type="number"/>
                        <input type="number"/>
                        <input type="number"/>
                        <input type="number"/>
                        <input type="number"/>
                        <input type="number"/>
                        <input type="number"/>
                        <input type="number"/>
                        <input type="number"/>

A: Consider the following example.

$(function() {
  function calcSum() {
    var row = $("#testerField").closest("tr");
    var lastCell = $("td:last", row);
    var total = 0;
    $("td > input", row).filter(function() {
      return $(this).val() > 0;
    }).each(function(i, el) {
      total += parseInt($(el).val());
    });
    lastCell.html(total);
  }

  $("table").ready(calcSum);
  $("table input").change(calcSum);
});
table input {
  width: 3em;
}

    1
    Trouble
    <input id="testerField" type="number" />
    <input type="number" />
    <input type="number" />
    <input type="number" />
    <input type="number" />
    <input type="number" />
    <input type="number" />
    <input type="number" />
    <input type="number" />
    <input type="number" />
    <input type="number" />
    <input type="number" />

Here we iterate over each input in the row and only if they have a Value higher than 0.

A:

var row = $("#testerField").closest("tr");
    var lastCell = row.find("td:last");
    $("table input").change(() => {
        var total = 0;
        $("td > input", row).each((i, el) => total += Number($(el).val()));
        lastCell.html(total);
    });

        1
        Trouble
        <input id="testerField" type="number"/>
        <input type="number"/>
        <input type="number"/>
        <input type="number"/>
        <input type="number"/>
        <input type="number"/>
        <input type="number"/>
        <input type="number"/>
        <input type="number"/>
        <input type="number"/>
        <input type="number"/>
        <input type="number"/>


text:
Q: Why [App Actions Test Tool] not support shortcuts xml file? I had created App Actions using the Android Shortcuts framework:
https://developers.google.com/assistant/app/get-started
shortcuts.xml
<?xml version="1.0" encoding="utf-8"?>
<shortcuts xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    >
    <capability android:name="custom.actions.intent.PLUS_DAYS"
        queryPatterns="@array/PlusQueries">
        <intent
            android:action="android.intent.action.VIEW"
            android:targetPackage="com.noen.maihue.datetimeplus"
            android:targetClass="com.noen.maihue.datetimeplus.MainActivity">
            <parameter
                android:name="day_number"
                android:key="day_number"/>
        </intent>
    </capability>
    <shortcut
        android:shortcutId="Plus_Days"
        android:shortcutShortLabel="@string/PlusDayShort">
        <capability-binding android:key="custom.actions.intent.PLUS_DAYS">
            <parameter-binding
                android:key="day_number"
                android:value="@string/day_number"/>
        </capability-binding>
    </shortcut>
    <!-- Specify more shortcuts here. -->
</shortcuts>

Androidmanifest.xml
<activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <meta-data
                android:name="android.app.shortcuts"
                android:resource="@xml/shortcuts" />
        </activity>

But if I create a Preview to test, it occur error:
    App Actions Test Tool v3.5.5
    No Android Module with actions file reference found. You need one Android Module with an actions file reference.
    Create Actions.xml

Why App Actions Test Tool not support shortcuts xml file?

A: You need do install another Android Studio plugin "Google Assistant", this plugin also contains an "app actions test tool"


text:
Q: How to show secondary notification icon when using a large icon? When setting a large icon in the push notification, the secondary notification is empty. In the status bar the app of the application is displayed but when opening to see the notification its empty.
here is the link of the notification that i get: http://i.stack.imgur.com/XHoxY.jpg
Here is my code:
new NotificationCompat.Builder(this)
        .setAutoCancel(true)
                        .setSmallIcon(R.drawable.ic_launcher)
                        .setContentTitle(title)
                        .setTicker(title)                .setContentText(msg).setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher));
If I change the target to android:targetSdkVersion="20" it works. But if using a greater SDK it doesn't display the smallicon

A: Per the notification style guidelines, notification icons must be a flat icon - on Android 5.0+ devices, any non-transparent pixels are changed to solid white as seen by your small icon showing a solid square.


text:
Q: Moment estimator $\hat{\theta}$ of $\mathrm{Beta}(\theta,1)$ and bias of $\hat{\theta}$ I'm trying to find the moment estimator for the density function $$f(y)=\theta y^{\theta-1}$$ and check whether this is biased.
I know this is a $Beta(\theta,1)$ distribution and it looks like I only need to find the first moment in order to find the estimator.
For $Y\sim \mathrm{Beta}(\theta,1)\implies\bar{Y}=\frac{\theta}{\theta+1}$
$$\theta\bar{Y}+\bar{Y}=\theta \implies \hat{\theta}=\frac{\bar{Y}}{1-\bar{Y}}$$
I'm pretty sure I've got that correct but I have no idea how to check whether this is biased or not. Finding the convolution isn't panning out too well and I can't seem to figure out a way to manipulate the expression in $\bar{Y}$ to give me anything to work with.
Any pointers towards answering this would be greatly appreciated.

A: Assuming $X_1,X_2,\ldots,X_n$ are i.i.d $\mathsf{Beta}(\theta,1)$, we have $E(\overline X)=\frac{\theta}{1+\theta}$, the population mean.
Let $g(x)=\frac{x}{1-x}$ be a function on $(0,1)$, so that $g''>0$ for all $x\in(0,1)$.
That is, as @Henry says, $g$ is convex.
By Jensen's inequality,
$$E( g(\overline X))>g (E(\overline X))$$
Or, $$E\left[\frac{\overline X}{1-\overline X}\right]>\frac{E(\overline X)}{1-E(\overline X)}=\theta$$
Note that equality does not hold in the inequality above as $g$ is not a constant or an affine function.
Finding the actual value of $E\left[\frac{\overline X}{1-\overline X}\right]$ is non-trivial as the sampling distribution of $\overline X$ is not a standard one. So I would not worry about the exact bias of the estimator here.


text:
Q: Tkinter Canvas will not update color change via itemconfig I am working on a project which deals with a kind of a map which has some lines as paths. These paths can have two states, active and inactive with different colors. There is a method which should change the fill-color.
I can't figure out why my canvas lines won't update. Here's my simplified code:
import Tkinter

inactive = "#385c61"
active = "#7dd5cd"

map = Tkinter.Canvas()

class GuiPart(object):

    def __init__(self, master):
        #some code

    def initGui(self, master):
        map = Tkinter.Canvas(left, width=660, height=600, bg="#35424b", bd="0", highlightthickness="0")
        map.pack()
        global inactive, active
        pathA = map.create_line(135, c, 135, e, fill=inactive, width=w)

    def setActivePath(self):
        global active, inactive
        map.itemconfig(pathA, fill=active)
        map.update_idletasks()
        map.update()

root = Tkinter.Tk()
gui = GuiPart(root)
gui.initGui(root)

gui.setActivePath()

root.mainloop()

If I change the color with itemconfig inside initGui it works like it should, but later I have to call setActivePath from another class, so it has to be a own method.
(I know I call map = Tkinter.Canvas(...) twice, but otherwise I get an error, have to fix that too)
Any ideas?

A: You need to make map and pathA attributes of the class so that setActivePath can reference it. This is why you were getting the error where you had to create two canvases.
import Tkinter

inactive = "#385c61"
active = "#7dd5cd"

class GuiPart(object):

    def __init__(self, master):
        #some code

    def initGui(self, master):
        self.map = Tkinter.Canvas(left, width=660, height=600, bg="#35424b", bd="0", highlightthickness="0")
        self.map.pack()
        global inactive, active
        self.pathA = map.create_line(135, c, 135, e, fill=inactive, width=w)

    def setActivePath(self):
        global active, inactive
        self.map.itemconfig(self.pathA, fill=active)
        self.map.update_idletasks()
        self.map.update()

root = Tkinter.Tk()
gui = GuiPart(root)
gui.initGui(root)

gui.setActivePath()

root.mainloop()

Everything else looks OK to me, though you are saying that this has not resolved your issue. As far as I can see, self.map.itemconfig(self.pathA, fill=active) is correct use of this method (see here and here) so it is possible that your problem is outside of the code you have posted. I can't test the code properly as you have not included the code in the __init__ method and because on the computer I am using at sixth form only Python 3.4.1 is installed. Please edit your question to include the code in the __init__ method.


text:
Q: OAuth2 for custom API I'm trying to use OAuth2 for an API I'm creating but could use some explanation for how the flow would work. I've found similar questions (ex: Securing my REST API with OAuth while still allowing authentication via third party OAuth providers (using DotNetOpenAuth)) but they don't make things clear with regards to the third-party login.
I do not wish to use OpenID (yet, anyways), especially when authentication by delegation might work just fine. It seems overly complicated and does not have many well-supported libraries. (I'm using PHP + Laravel 4)
The problem is separated into 4(ish) entities:

*

*Resource Owner - The end user

*Client - Browser (My website), a mobile app, or similar

*Authorization Server - My OAuth2 server

*Resource Server - My API. Serves user data.

I think I've figured out the flow for when the user creates an account at my auth server and uses that account to log in:

*

*User fills in username/password on Client.

*Client connects to Auth Server using the Resource Owner flow, authenticates the User, and authorizes the Client automatically.

*The user is redirected from the AUth Server back to the Client, with a Token + signed JWT containing a user ID.

*Client saves the token in a session.

*Client uses the token + signed JWT user id to request data from the Resource Server.

*The Resource Server validates the JWT and returns data depending on the token scopes.

I haven't tested the workflow yet, but this seems like it would work. Third-party login, however, has proven to be more difficult. This is what I've got so far:

*

*User clicks login with Google/Facebook/LinkedIn.

*User is redirected from Client to Google's Auth Server (not mine).

*User logs in using user/pass and authorizes Client to fetch some protected resource (userinfo.email) - This authenticates the user by delegation.

*User is redirected back to Client, with a Token + signed JWT containing a Google user id.

*Client validates the JWT.

*Client uses the Client Credentials flow to connect to the Resource Server. Recieves a new token.

*Client saves the token in a session.

*Client requests to convert the Google user id to an application user id. (This connection was made during signup.)

*Resource Server returns the application user id. (Signed JWT)

*Client uses the token + signed JWT user id to request data from the Resource Server.

*The Resource Server validates the JWT and returns data depending on the token scopes.

This might work, but it feels awfully complicated. Surely there must be a way to skip a few of those steps? I'm particularly interested in step 8-10. As far as I know, the user never have to interact with my Auth Server at all using third-party login. The problem is how you best connect a successful id_token (or something) from Google/Facebook/LinkedIn to the "account" resource at my API.
Right now, I'm not worried about any other clients connecting to the API, but it's something that will happen sometime in the future.

A: "As far as I know, the user never have to interact with my Auth Server at all using third-party login."
That's only partly true. Theoretically, you could use the token of the Third-Party login as your own. So a normal resource request would be:

*

*Client requests resource - sends token (from 3rd party) and type of login (facebook/google/etc)

*Server validates request by checking the token with the 3rd party Authorization Server and returns data.

The downside with that is, that your API server has to talk with the 3rd party server every time a request gets made (whether data from them is needed or not). Instead when you generate your own token you have more control and it's simpler to validate requests.
I would stick with your workflow though. I did something similar once and my steps were pretty much the same. When "counting" steps you also have to consider, that for step 2-4 you basically have to do nothing since the Google, Facebook and co have done a good job already ;)

A: A late contribution to your question.
Found this resource explaining the use of OAuth2 : OAuth2 in 8 Steps


text:
Q: Managing User Profiles in asp.net MVC2 I'm trying to add user management to a web app using .net MVC2, similarly to ProfileProvider: retrieve list of all profiles.
I'd like to display profile information (first name, last name) on the "list all users" page, but I can't figure out how to get all profiles.  ProfileManager.GetAllProfiles() returns a collection of ProfileInfo objects rather than actual Profile objects.
While the ProfileInfo class does give me access to some useful info, I can't actually get any properties of that particular profile.
Is there a way to get all Profiles in the system so that I can list them on an admin page?

A: You could try using the MembershipProvider.GetAllUsers to get more extensive information about each user. This will give you a collection of MembershipUser.


text:
Q: Determine Uiwebview or just use ios's Safari Is it possible to determine user use application Uiwebview or just use ios Safari by using javascript?

A: From Apple documentation:

You can determine whether a webpage is displaying in standalone mode using the window.navigator.standalone read-only Boolean JavaScript property.

So you should check window.navigator.standalone property:
if (window.navigator.standalone) {
  // standalone app ~ UIWebView
} else {
  // Safari
}


text:
Q: Some question of vector bundles Let $\mathbb{P}(V)$ be a $r+1$ dimensional projective space where $V$ is a vector space.
I don't understand tensor product $V\otimes \mathcal{O}_{\mathbb{P}}$... and why this is trivial bundle....
help me...

A: Let $X$ be a ringed space defined over a commutative ring $k$, $M$ an $\mathcal{O}_X$-module and let $V$ be a module over $k$. Then $V \otimes_k M$ is defined to be the $\mathcal{O}_X$-module which is associated to the presheaf $U \mapsto V \otimes_k \Gamma(U,M)$. One verifies that this satisfies the usual adjunction $\hom(V \otimes_k M,N) \cong \hom(V,\hom(M,N))$ (in other words, $\mathsf{Mod}(X)$ is tensored over $\mathsf{Mod}(k)$). If $V$ is a free module, say $V=k^{\oplus I}$, then $V \otimes_k M = M^{\oplus I}$ is a direct sum of copies of $M$. In particular, if $M = \mathcal{O}_X$, this is a free module aka trivial bundle.


text:
Q: Why is my Elasticseach API(_nodes/stats) getting stuck? I'm using Elasticsearch v6.5.1 on a 40 nodes cluster with analysis-icu plugin installed.
When making a consecutive _nodes/stats to 40 nodes the request get stuck after a while. I have enabled trace logs for root as well as transport and slowlogs too which reveal that the query is being served in few milliseconds.
Any help is appreciated.


text:
Q: Excel Worksheet Change VBA to update formula range in a worksheet for changing input data I have found this answer on SO that is close to what I want to do, but my knowledge of VBA is too basic to modify for my specific situation.
Automatically copy formulas as data expands
The difference in my case is that the data my formulas refer to is not the entire previous worksheet. For example, I want my formulas in sheet "B" to use data from sheet "A" that corresponds to those rows containing cells with string "XYZ." Sheet "A" is linked to a data source that updates regularly, changing the number of rows containing said string. As "A" updates, "B" calculates what it needs to, then is plotted automatically (which I already have a sub for), but I cannot figure out how to automatically make the range of formulas reflect the fluctuating range of data.
Any ideas?

A: Based on some reasonable assumptions of what I think you are trying to do I wrote and tested the following code snippet (adapted from your link).  Add this to the code of worksheet A, and see how it works when you have strings in column A, and values in column B of sheet A. Where there is "XYZ" in A, the value in column B will be transferred to sheet B, column A. When you change anything on sheet A, B will be updated.
If this doesn't help you solve the problem, you will have to explain more clearly what is missing...
Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
' when worksheet changes, copy value adjacent to a cell with the string "XYZ" in it
' to worksheet "B", starting in "A1".
' after clearing out everything that was in that range first

    Dim oRangeDest As Range
    Dim oRangeSearch As Range
    Dim searchString As String
    Dim foundCell As Range
    Dim firstFound As String

    'Define output range
    Set oRangeDest = Worksheets("B").Range("A1")
    Set oRangeSearch = Worksheets("A").Range("A:A")

    ' value of string to search for:
    searchString = "XYZ"

    Application.ScreenUpdating = False
    Application.EnableEvents = False

    ' clear the formulas in sheet B:
    Worksheets("B").Activate
    With ActiveSheet
      .Range(oRangeDest, oRangeDest.End(xlDown)).Select
      Selection.Clear
      .Range("A1").Select
    End With

    Worksheets("A").Activate ' can only search on active sheet

    ' find cells in column A on sheet 1 with "XYZ" in them:
    Set foundCell = oRangeSearch.Find(What:=searchString, _
        After:=ActiveSheet.Cells(1, 1), _
        LookIn:=xlValues, _
        LookAt:=xlPart, _
        SearchOrder:=xlByColumns, _
        SearchDirection:=xlNext, _
        MatchCase:=False, _
        SearchFormat:=False)
    If Not foundCell Is Nothing Then
        ' if found, remember location
        firstFound = foundCell.Address
        ' copy the value of the next cell over to the next available cell on sheet B
        Do
            ' copy something from a cell adjacent to the one we found:
            ' obviously we could access a different column, value or formula, etc...
            oRangeDest.Value = foundCell.Offset(0, 1).Value
            Set oRangeDest = oRangeDest.Offset(1, 0) ' down one row for next time
            ' find next instance
            Set foundCell = oRangeSearch.FindNext(After:=foundCell)
            ' repeat until back where we started
        Loop Until firstFound = foundCell.Address
    End If

    Application.EnableEvents = True

End Sub

Screen shots of sheets A and B (slightly messed up by the alt key...):


text:
Q: SQL Server 2012 fails to install or remove Got an odd problem here. Installed programs is showing SQL Server 2012 installed, but fails to remove itself when running the uninstaller. To add insult to injury, it also won't let install the components I do want, saying a dependency failed (SQL Client Connectivity SDK), but not being very helpful otherwise.
Anyone else encounter this error / have an idea how to solve it?

A: Have you previously installed SQL 2012? Or did you inherit this machine and don't know its history?
Open the SQL Server Configuration Manager, and see if your instance in listed there. If it's not there, then SQL doesn't think it's there, and vice versa.
Next, look for a file like this:
C:\Program Files\Microsoft SQL Server\110\Setup Bootstrap\Log\Summary.txt
Take a look through the file and see if it sheds a clue as to the problem.
You should also see a series of folders for each of the install attempts.
Also, I would try running the setup program and try the repair option.
Another possibility, is to install a new instance with a new name.
For uninstalling, try downloading CCleaner and running the uninstall through that.

A: I ran in to the same problem. I had SQL 2008 Express & needed SQL 2012 Express. I left 2008 on. After installing 2012 I realized I'd installed only the core engine & none of the tools.
Final solution that worked for me:

*

*Uninstall 2008 completely, which I had to do one component at a time in Control Panel - Programs & Features.

*Find the core SQL Server app (64-bit in my case) and uninstall it. It shows up like this
Microsoft SQL Server Server 2012 (64-bit)
The above uninstalled all the 2012 components - I had something like 9 or 10 total entries for SQL Server 2012.

*Install SQL Server 2012 Express Advanced. This download includes all the tools & free add-ons. Express does not include Server Profiler...

SQL Server 2012 Express (64-bit) Download options:

*

*SQLEXPR_x64_ENU  just the database engine, no tools, reporting services or full-text search

*SQLEXPRWT_x64_ENU  WT means With Tools. Database engine with tools (SQL Server Management Studio, Distributed Replay - Admin Tool, LocalDB

*SQLEXPRADV_x64_ENU  Advanced. Database engine with tools plus
SSDT, Full-text search, some Reporting services features


text:
Q: 2 jars with 50 balls each. Pick any ball with $>50\%$ probability. You are blindfolded and placed in front a table with two jars. One jar has $50$ red balls and other has $50$ blue balls.
What should be your strategy so that you pick up the red ball with more than $50\%$ probability.

A: Take one ball from each jar. You're guaranteed to get a red.

A: If the red and blue balls are identical in shape and size and picking one ball from two jars which are also identical should result in the probability of getting a red ball as .5. Now if the experiment is biased in some way, then the probability of getting a red ball may be greatr than .5.

A: I don't think moving the balls makes any difference.
The question is what is your strategy to improve from 50% of the balls. Not 50% out of one jar.
Ultimately there are always 100 balls in front of you and you have a 50/50 chance. The only way to change that is to take two balls out, or throw away one balls so that N changes.

A: take 49 red balls from one jar and put them in the other jar wit the blue balls,
now its 100 % he will pick red from the first jar, and 50% red from the mixed jar.


text:
Q: Find temperature unit from settings app I am working on an iOS app in Swift 3, I need to get user preferred unit for temperature from settings app (Celsius or Fahrenheit). I tried finding a solution for it but no success. :(
Can anyone suggest how to do this.
Thanks in advance!

A: This can be done with the MeasurementFormatter in swift.
This method does not use any private API's. Remember to run this on an actual device(iOS 10+) as the simulator does not have that option.
    let formatter = MeasurementFormatter.init()
    let temperature = Measurement.init(value: 37.0, unit: UnitTemperature.celsius)
    let localTemperature = formatter.string(from: temperature)
    if(localTemperature.contains("C")) {
        print("UNIT IS °C")
    } else {
        print("UNIT IS °F")
    }

A: The kCFLocaleTemperatureUnitKey key is not documented. So apple might have problem with that. Please read this thread for more. His app was rejected because of this key.
let locale = NSLocale.current as NSLocale
let obj = locale.object(forKey: NSLocale.Key(rawValue: "kCFLocaleTemperatureUnitKey"))
print("\(obj!)")

A: You need to expose NSLocaleTemperatureUnit of type NSLocaleKey,
FOUNDATION_EXPORT NSLocaleKey const NSLocaleTemperatureUnit;

Then you will be able to access NSLocale information based on the temperature unit NSLocaleKey.
NSLocale *locale = [NSLocale currentLocale];
__unused id info = [locale objectForKey:NSLocaleTemperatureUnit];

For example

A: I've modified other answers for more elegant option
extension Locale {

    var temperatureUnit: UnitTemperature {
        let units: [UnitTemperature] = [.celsius, .fahrenheit, .kelvin]

        let measurement = Measurement(value: 37, unit: UnitTemperature.celsius)

        let temperatureString = MeasurementFormatter().string(from: measurement)

        let matchedUnit = units.first { temperatureString.contains($0.symbol) }
        if matchedUnit != nil {
            return matchedUnit!
        }

        return usesMetricSystem ? .celsius : .fahrenheit
    }
}


text:
Q: Ranking between two strings For the word "BOOKKEEPER". It's sorted representation is "BEEEKKOOPR" How can I find the different permutations of the word between "BEEEKKOOPR" and "BOOKKEEPER"?
similar example:
For "BBAA"
AABB - 1
ABAB - 2
ABBA - 3
BAAB - 4
BABA - 5
BBAA - 6

6 - 1 = 5 So there are 5 words before "BBAA"
"BEEEKKOOPR" would be number 1. "BOOKKEEPER" would be some distance away. I'm not sure how to go about this as I believe this is a combinatorics problem and I don't have much experience with the subject.

A: discounting B (which must lead every string), there are 9 symbols.
we can rank
(B = 0)
E = 1
K = 2
O = 3
P = 4
R = 5
now, for BOOKKEEPER
we can include every combination that gives 2 or fewer for the first digit:
3 "1"s and 2 "2"s
5 * 8!
+
all valid combinations where 3 is the first digit
if 3 is the first digit, and 2 or fewer is the second digit, include all combinations, so:
5 * 8!
+
4 * 7!
+
all valid combinations starting with 33
if the next digit is a 1, of which there are 3, include it
5 * 8!
+
4 * 7!
+
3 * 6!
+
all valid combinations 332
if the next digit is a 1, of which there are 3, include it
5 * 8!
+
4 * 7!
+
3 * 6!
+
3 * 5!
+
all valid combinations 3322
the next digit must be a 1, and the digit after that must be a 1, so really its
all valid combinations 332211
if the next digit is 1, include all values:
5 * 8!
+
4 * 7!
+
3 * 6!
+
3 * 5!
+
2!
+
all valid combinations 3322114
of which there is only 1: 332211415 ie, BOOKEEPER
so the number of values below BOOKEEPER is
5*8! + 4*7! + 3*6! + 3*5! + 2! + 1, and between BOOKEEPER AND BEEEKKOOPR
is
5*8! + 4*7! + 3*6! + 3*5! + 2!
since we just subtract off the extra 1.
At least, that's how I'd solve it.


text:
Q: System.StackOverflowException was unhandled - C#, .NET How to fix it.
It look like this page is dedicated to that kind of error.

A: It appears that InvokeRequired is true. This causes unbounded recursion. There's nothing that will change it to false. Perhaps invoking would fix it?

A: Your function is calling itself forever.
You need to make it stop calling itself.
In this case, you need to Invoke it to the UI thread instead of simply calling itself again:
Invoke(new Action(UpdateAdvert));


text:
Q: Vue data target in components WHen I add a data-target to my component it stops showing the elements. I tried harcoding an ID but no matter what I do it dosent shown with data-target:
Vue.component('kk-directory', {
props: ['directoryData'],
template: '
'+
                '<input type="checkbox" v-model="directoryData.Selected" v-on:change=" $root.selectedChange(directoryData)" v-show="!directoryData.Migrate">'+
                ''+
                '**'+
                    '{{ directoryData.Name }}:'+
                    'files({{ directoryData.FileCountCurrentFolder }}), files total ( 5000}">{{ directoryData.FileCountTotal }}), GB ({{ directoryData.SizeGB }})'+
                ''+
                '
'+
                     '
'+
                        '<kk-directory :directory-data="dir"></kk-directory >'+
                    '
'+
                '
'+
            '
'

})
Is in not possible to bind a data-target in components?

A: I figured it out. Following worked:
''


text:
Q: Possible volumes of lattice polytopes All polytopes here are assumed to be convex lattice polytopes.
Given a polytope $P$, set $$v(P):= (\operatorname{vol}(F))_{F\text{ a face of }P},$$ where the volume of a $d$-dimensional polytope $P\subseteq \Bbb R^n$ is defined to be its ($d$-dimensional) Euclidean volume divided by the determinant of the lattice induced by $P$.
Let $\mathcal P$ be a polytopal cell complex, $m$ the total number of faces. For each polytope $P$ isomorphic to $\mathcal P$ as a polytopal cell complex, fix an identification of the faces of $P$ with those of $\mathcal P$, so that all the vectors $v(P)$ for such $P$ live in the same vector space $\Bbb R^m$ (after choosing a linear order for the faces). Define $v(\mathcal P)$ to be the set of all such $v(P)$, and let $$v(\mathcal P)^\vee:= \{x\in \Bbb R^m \mid x\cdot v \geq 0 \text{ for all }v\in v(\mathcal P)\}.$$
Questions:

*

*Is $v(\mathcal P)^\vee$ strongly convex? If not, what is its lineality space?

*Is $v(\mathcal P)^\vee$ polyhedral?


text:
Q: AddColumns says I'm comparing a number to a table I'm somewhat new to PowerApps and I'm stuck at trying to reproduce a JOIN using the AddColumns function and a LookUp function as I saw on this link: Syntax for joining tables. This JOIN will go inside of a Data Table.
I have two SQL tables I'm trying to JOIN using that method
mT_SalesAttributeDB_FamilyMaterialGroupMaterials: ([ID], [MaterialGroupID], [MaterialID], [Comment], [Created], [Updated])
mT_SalesAttributeDB_Materials: ([ID], [MaterialName], [Description], [ShortDesc], [Abbr], [Superseded], [HasNoDrawing], [Created], [Updated])
What I'm wanting to accomplish is this:
SELECT
    *
FROM
    mT_SalesAttributeDB_FamilyMaterialGroupMaterials AS Grps
    INNER JOIN
    mT_SalesAttributeDB_Materials AS Mats ON Grps.MaterialID = Mats.ID
WHERE
    Grps.MaterialGroupID = tblMaterialGroups_Families.Selected.ID

I think this is what that should look like:
AddColumns(
    Filter(
        mT_SalesAttributeDB_FamilyMaterialGroupMaterials,
        Text(tblMaterialGroups_Families.Selected.ID) = MaterialGroupID
    ),
    "MaterialName",
    LookUp(
        mT_SalesAttributeDB_Materials,
        ID = mT_SalesAttributeDB_FamilyMaterialGroupMaterials[@MaterialID],
        MaterialName
    )
)

However, the equality inside of the LookUp, ID = mT_SalesAttributeDB_FamilyMaterialGroupMaterials[@MaterialID] gives an error on the equal sign saying I can't compare a number to a table
As a reference, I've tried this and it works fine
Filter(
    mT_SalesAttributeDB_FamilyMaterialGroupMaterials,
    Text(tblMaterialGroups_Families.Selected.ID) = MaterialGroupID
)

Is the problem that I'm trying to use a preview object that isn't fully released? Or am I joining them incorrectly?
EDIT
I've also tried this and still get the same error about not being able to compare a number to a Table
AddColumns(
    Filter(
        mT_SalesAttributeDB_FamilyMaterialGroupMaterials,
        mT_SalesAttributeDB_FamilyMaterialGroupMaterials[@MaterialGroupID] = Text(tblMaterialGroups_Families.Selected.ID)
    ),
    "SpecName",
    LookUp(
        mT_SalesAttributeDB_Materials,
        mT_SalesAttributeDB_Materials[@ID] = mT_SalesAttributeDB_FamilyMaterialGroupMaterials[@MaterialID],
        mT_SalesAttributeDB_Materials[@MaterialName]
    )
)

NOTE: I also wanted to mention that I attempted the exact same AddColumns with a List Box to make sure it wasn't something to do with Data Tables being in preview, and I still get the error that I can't compare a Number to a Table
EDIT 2
I seem to be getting close. I can get the error to stop and it to populate "SpecName", however, it just grabs the first MaterialName from mT_SalesAttributeDB_Materials instead of doing a proper LookUp
AddColumns(
    Filter(
        mT_SalesAttributeDB_FamilyMaterialGroupMaterials,
        MaterialGroupID = Text(tblMaterialGroups_Families.Selected.ID)
    ),
    "MaterialName",
    LookUp(
        mT_SalesAttributeDB_Materials,
        ID in mT_SalesAttributeDB_FamilyMaterialGroupMaterials.MaterialID,
        MaterialName
    )
)

I changed the "=" to an "in" and it seems that mT_SalesAttributeDB_FamilyMaterialGroupMaterials.MaterialID is the same as mT_SalesAttributeDB_FamilyMaterialGroupMaterials[@MaterialID]

A: Okay, so I finally got it with some help from Google. I had a few things that were likely causing me problems with my tables.

*

*_Materials.MaterialID was changed to .MaterialName so I wouldn't have two fields with the same name but different meanings. I think that helped when PowerApps was using context.

*_Materials.ID is stored as an INT however, for some reason I decided to store _FamilyMaterialGroupMaterials as a VARCHAR. So I changed that to an INT so MaterialID and ID would be exactly the same thing in each table. (I assume this helps with the JOIN)

Once I had that updated, this is the correct syntax to JOIN two tables. You can see I even added in a second Column once I got it working
AddColumns(
    Filter(
        mT_SalesAttributeDB_FamilyMaterialGroupMaterials,
        MaterialGroupID = tblMaterialGroups_Families.Selected.ID
    ),
    "MaterialName",
    LookUp(
        mT_SalesAttributeDB_Materials,
        ID = MaterialID
    ).MaterialName,
    "ShortDesc",
    LookUp(
        mT_SalesAttributeDB_Materials,
        ID = MaterialID
    ).ShortDesc
)

Hopefully my full day wasted trying to figure that out will help someone else.


text:
Q: How to setup a popup registeration page in wordpress with function.php everyone:
I wonder if there is existing tutorial on how to create a popup registration page in wordpress by utilizing function.php? or is there another way that can do with it?
Thank you!

A: You can add the HTML for the area via wp_footer, include the style with wp_enqueue_style(), and include the javascript to show/hide the popup with wp_enqueue_script().
wpse90382_popup_function() {
    add_action( 'wp_footer', 'wpse90382_popup_html' );
    wp_enqueue_style( 'your_style', get_template_directory_uri() . 'your_stylesheet.css' );
    wp_enqueue_script( 'your_script', get_template_directory_uri() . 'your_javascript.js' );
}
wpse90382_popup_html() {
    ?>

Your HTML

    <?php
}
if ( some condition )
    wpse90382_popup_function();


text:
Q: How to get unique / distinct elements inside JSON array in MySQL 5.7 I have mysql 5.7 with a denormalized table that has some JSON columns. I need to extract unique / distinct values per row for an array column.
For e.g: ["a", "b", "b", "a", "c"] expected output should be ["a", "b", "c"];
SET @json = '["a", "b", "b", "a", "c"]';
I need to get unique values in this list.
["a", "b", "c"];

A: There is no direct method to get distinct values out of a JSON array in MySQL. One method could be to utilize a Sequence/Number Generator table concept. This sequence table could be used as a Derived Table (subquery), or you can create a permanent table storing numbers in your database.
We will then use this sequence table to JSON_EXTRACT() values out from array at first key, second key, third key and so on. Once we have extracted out the values in separate row, we can simply use DISTINCT to get unique values out of them. Afterwards, we can use JSON_ARRAYAGG() function to re-aggregate these unique values back as a JSON array.
Schema (MySQL v5.7)
SET @json = '["a", "b", "b", "a", "c"]';

Query
SELECT Json_arrayagg(dt.val) AS unq_json_array
FROM   (SELECT DISTINCT Json_extract(@json, Concat('$[', seq.n, ']')) AS val
        FROM   (SELECT 0 AS n UNION ALL SELECT 1 UNION ALL
                SELECT 2 UNION ALL SELECT 3 UNION ALL
                SELECT 4 UNION ALL SELECT 5 UNION ALL
                SELECT 6 UNION ALL SELECT 7 UNION ALL
                SELECT 8 UNION ALL SELECT 9) AS seq) AS dt
WHERE  dt.val IS NOT NULL;

Result
| unq_json_array  |
| --------------- |
| ["a", "b", "c"] |

View on DB Fiddle

A: The following may help those using MySQL 8
You could use a combination of JSON_TABLE, JSON_OBJECTAGG, and JSON_KEYS to do it without too much trouble. It's too bad we couldn't do something like JSON_ARRAYAGG(DISTINCT item).
For example:
SET @json = '["a", "b", "b", "a", "c"]';

SELECT JSON_KEYS(JSON_OBJECTAGG(item, ""))
FROM JSON_TABLE(@json, '$[*]'
    COLUMNS(
        item TEXT PATH '$'
    )
) as items;

I also made a DBFiddle to show my work: https://www.db-fiddle.com/f/6hgSEXPJWcm2CH8K16z6gQ/0

JSON_TABLE https://dev.mysql.com/doc/refman/8.0/en/json-table-functions.html
JSON Search Functions: https://dev.mysql.com/doc/refman/8.0/en/json-search-functions.html


text:
Q: ORA-00979: not a GROUP BY expression Why does this work
SELECT DISTINCT FIRSTNAME, LASTNAME
FROM books, CUSTOMERS, orders, orderitems
WHERE STATE IN('FL ', 'GA')
GROUP BY orders.order#, firstname, lastname
HAVING SUM(retail*quantity) > 80

but when firstname, lastname is removed from group by it doesn't?

ORA-00979: not a GROUP BY expression

A: As I can guess
First of all GROUP BY operation is performed and then DISTINCT. In GROUP BY clause you must indicate all non-aggregates . For example you are not permitted to do the following:
SELECT FIRST_NAME, LAST_NAME
FROM EMPLOYEES
GROUP BY HIRE_DATE

You should do it by this way:
SELECT FIRST_NAME, LAST_NAME
FROM EMPLOYEES
GROUP BY HIRE_DATE,FIRST_NAME, LAST_NAME

A: In that case where firstname, lastname are removed from the group by, you get that error because you're SELECTing a column(s) that aren't in the GROUP BY expression, or aren't part of an aggregation/function (i.e. MIN, MAX, AVG, and others).
You could also eliminate the DISTINCT as well.


text:
Q: How to mixing run ruby and javascript? How to use ruby and javascript mixing?
For example:
<div>
    $(".pop-up-confirm").click( function(e) {
      var domain_name = $("input#domain_name")[0].value;
      var msg = #{call_ruby_function(domain_name)};
    }
</div>

First, I use js to get the value domain_name from input.
Second, I want call ruby_function, use domain_name as parameter.
The first step is correct, but I how to make the second correct.

A: You cannot execute ruby in the browser. You can only execute javascript. You can either rewrite your function in javascript, or make a request to your ruby server.

A: To solve your issue you should perform AJAX request.
$.get('/some-path', { domain: domain_name }, function(data) {
  # data is your message
});

Ruby code will be executed in server-side and your message should be returned to you to work with in client-side
My example requires jQuery to be available


text:
Q: Presentations of simple groups Finite simple groups (non-abelian) can generated by two elements.
Let $G=\langle x,y|x^l=y^m=(xy)^n=1,...\rangle$ be a finite simple group (non-abelian), and $\langle x,y|x^p=y^q=(xy)^r=1,...\rangle$  be another presentation of $G$. (Here, "..." means possibly more relations).
1) If $(1/l)+(1/m)+(1/n)<1$, then does it imply that $(1/p)+(1/q)+(1/r)<1$?
2) If $(1/l)+(1/m)+(1/n)=1$, then does it imply that $(1/p)+(1/q)+(1/r)=1$?
3) If $(1/l)+(1/m)+(1/n)>1$, then does it imply that $(1/p)+(1/q)+(1/r)>1$?
(For a group $G=\langle x,y|x^l=y^m=(xy)^n=1,...\rangle$ to be a group of symmetries of a compact orientable surface, there are some restrictions on the integers $l,m,n$ and genus of surface, due to Riemann-Hurwitz relation. If the integers (l,m,n) satisfy some conditions as above, then it will allow us to consider less number of presentations of finite simple groups to check for possibility of action of the group on the surface).

A:
No.  The simple group of order 60 is a counterexample to (1) and (3).

If {x,y} is a generating set of G, call its signature 1/|x| + 1/|y| + 1/|xy|.  It appears that the signature of most generating sets of non-abelian simple groups are less than 1.
I'll assume that l,m,n are required to be the exact orders (and are not just sneakily enlarged to make it easier to get < 1, since it is already easy to get < 1).  Hence you are just asking for some sort of "law of inertia" for the "signature" of two-generator sets.

However, the simple group of order 60 has the following signatures: 3/5, 11/15, 13/15, 9/10, 31/30.

It does however appear to be a bit rare.  The simple groups I've checked other than A5 all have all signatures less than 1.
I didn't see any simple groups satisfying the hypothesis of (2), so I guess it could be vacuously true.

Maybe this table of signatures up to order 10000 will help:

*

*60 PSL(2,4): 3/5, 11/15, 13/15, 9/10, 31/30

*168 PSL(2,7): 3/7, 15/28, 13/21, 9/14, 61/84, 3/4, 11/14, 17/21, 5/6, 25/28, 11/12, 41/42

*360 PSL(2,9): 3/5, 13/20, 7/10, 11/15, 3/4, 47/60, 13/15, 9/10, 11/12, 19/20

*504 PSL(2,8): 1/3, 23/63, 25/63, 3/7, 5/9, 37/63, 13/21, 13/18, 95/126, 7/9, 11/14, 17/21, 17/18, 41/42

*660 PSL(2,11): 3/11, 23/66, 21/55, 14/33, 151/330, 27/55, 1/2, 17/33, 8/15, 17/30, 13/22, 3/5, 103/165, 2/3, 15/22, 7/10, 11/15, 25/33, 87/110, 5/6, 13/15, 9/10, 61/66

*1092 PSL(2,13): 3/13, 27/91, 25/78, 33/91, 211/546, 16/39, 3/7, 19/42, 10/21, 19/39, 1/2, 151/273, 15/26, 13/21, 9/14, 17/26, 2/3, 131/182, 29/39, 11/14, 17/21, 5/6, 71/78, 41/42

*2448 PSL(2,17): 3/17, 35/153, 33/136, 43/153, 361/1224, 21/68, 1/3, 25/72, 13/36, 25/68, 3/8, 257/612, 59/136, 23/51, 17/36, 35/72, 1/2, 77/153, 211/408, 5/9, 19/34, 41/72, 7/12, 11/18, 21/34, 5/8, 131/204, 205/306, 93/136, 25/36, 17/24, 13/18, 37/51, 53/72, 3/4, 7/9, 19/24, 55/68, 5/6, 31/36, 7/8, 91/102, 11/12, 17/18, 23/24

*2520 Alt(7): 3/7, 19/42, 10/21, 17/35, 1/2, 107/210, 8/15, 15/28, 19/35, 47/84, 17/30, 7/12, 83/140, 3/5, 37/60, 13/21, 9/14, 13/20, 2/3, 71/105, 7/10, 61/84, 11/15, 3/4, 47/60, 11/14, 17/21, 5/6, 59/70, 13/15, 25/28

*3420 PSL(2,19): 3/19, 39/190, 37/171, 24/95, 451/1710, 47/171, 3/10, 29/95, 14/45, 29/90, 1/3, 67/190, 311/855, 2/5, 37/90, 19/45, 25/57, 43/95, 277/570, 85/171, 1/2, 23/45, 8/15, 49/90, 5/9, 167/285, 3/5, 23/38, 19/30, 29/45, 62/95, 227/342, 7/10, 32/45, 41/57, 13/18, 11/15, 143/190, 23/30, 7/9, 4/5, 73/90, 13/15, 101/114, 9/10, 14/15, 17/18

*4080 PSL(2,16): 3/17, 47/255, 49/255, 1/5, 27/85, 83/255, 1/3, 23/51, 39/85, 7/15, 151/255, 3/5, 21/34, 319/510, 19/30, 37/51, 11/15, 129/170, 23/30, 91/102, 9/10

*5616 PSL(3,3): 3/13, 29/104, 25/78, 17/52, 115/312, 3/8, 21/52, 16/39, 5/12, 47/104, 11/24, 19/39, 77/156, 1/2, 167/312, 13/24, 15/26, 7/12, 5/8, 17/26, 103/156, 2/3, 73/104, 17/24, 29/39, 3/4, 19/24, 43/52, 5/6, 71/78, 11/12

*6048 PSU(3,3): 1/4, 7/24, 13/42, 1/3, 59/168, 31/84, 3/8, 11/28, 23/56, 5/12, 3/7, 73/168, 19/42, 11/24, 10/21, 1/2, 29/56, 15/28, 13/24, 47/84, 7/12, 101/168, 13/21, 5/8, 9/14, 2/3, 17/24, 61/84, 3/4, 43/56, 11/14, 19/24, 17/21, 5/6

*6072 PSL(2,23): 3/23, 47/276, 45/253, 29/138, 661/3036, 57/253, 1/4, 35/138, 17/66, 35/132, 3/11, 27/92, 457/1518, 1/3, 31/92, 15/44, 23/66, 26/69, 389/1012, 5/12, 29/69, 14/33, 19/44, 127/276, 355/759, 1/2, 67/132, 17/33, 25/46, 7/12, 27/46, 13/22, 173/276, 321/506, 2/3, 89/132, 15/22, 49/69, 3/4, 25/33, 73/92, 5/6, 37/44, 121/138, 11/12, 61/66

*7800 PSL(2,25): 3/13, 37/156, 19/78, 1/4, 25/78, 17/52, 1/3, 23/65, 281/780, 11/30, 21/52, 16/39, 5/12, 173/390, 9/20, 31/65, 29/60, 19/39, 77/156, 1/2, 137/260, 8/15, 17/30, 15/26, 7/12, 119/195, 37/60, 13/20, 17/26, 103/156, 2/3, 7/10, 29/39, 3/4, 101/130, 47/60, 43/52, 5/6, 71/78, 11/12

*7920 M11: 3/11, 27/88, 15/44, 23/66, 3/8, 21/55, 101/264, 183/440, 5/12, 14/33, 19/44, 9/20, 151/330, 11/24, 41/88, 27/55, 59/120, 1/2, 67/132, 17/33, 21/40, 8/15, 119/220, 13/24, 145/264, 17/30, 23/40, 7/12, 13/22, 3/5, 37/60, 103/165, 5/8, 13/20, 79/120, 2/3, 89/132, 15/22, 7/10, 17/24, 63/88, 3/4, 25/33, 47/60, 87/110, 19/24, 33/40, 37/44

*9828 PSL(2,27): 3/14, 20/91, 41/182, 3/13, 2/7, 53/182, 27/91, 5/14, 33/91, 3/7, 10/21, 263/546, 19/39, 23/42, 151/273, 13/21, 9/14, 59/91, 17/26, 5/7, 131/182, 31/42, 29/39, 11/14, 17/21, 19/21, 71/78, 41/42

A: This is an attempt to explain Jack's answer geometrically, and to argue that $A_5$ is the only possible interesting (ie non-abelian) example.
We are interested in actions of finite simple groups on surfaces $\Sigma$.  We are looking for simple groups $G$ that act on surfaces of different curvatures.  The quotient $\Sigma$ is an orbifold of the same curvature as $\Sigma$, so we can just appeal to the classification of such orbifolds. (See, for instance, Peter Scott's article The geometries of 3-manifolds for a nice introduction to 2-dimensional orbifolds.)
There are only two infinite families of spherical orbifolds, having cyclic and dihedral fundamental groups.  As these have no non-abelian simple quotients, we discard them. The remaining orbifolds correspond to the symmetries of the Platonic solids.  The only interesting simple quotient we see here is $A_5$.
Famously there are seventeen Euclidean 2-orbifolds, and each has a free abelian subgroup of finite index, which we may as well quotient by.  Now, I don't have a classification of these quotients to hand (the wikipedia article on Wallpaper Groups uses Conway notation, with which I'm not comfortable), but I'm willing to bet that, once again, no interesting simple quotients arise.
Finally, we are left with the hyperbolic case.  It's a theorem that every finite group can be realised as the symmetries of a closed hyperbolic surface, so of course $A_5$ is no exception.  Jack's calculation appears to show that $A_5$ acts on a small enough hyperbolic surface $\Sigma$ that the quotient is covered by (and hence must be, I suppose) a triangular orbifold.

A: The only groups where 1/l+1/m+1/n is greater than one are the cyclic groups, the dihedral groups, and the groups A(4), S(4), and A(5). Therefore, A(5) is the only simple groups where 1/l+1/m+1/n>1. As mentioned above, it is also a group such that 1/p+1/q+1/r<1, so it is a counterexample to (1) and (3).
All groups such that 1/l+1/m+1/n=1 are solvable, so therefore (2) is vacuously true.
Therefore your statement can be made into the stronger (and more accurate) statement: The only simple group with presentation $G=\langle x,y|x^l=y^m=(xy)^n=1,...\rangle$, when 1/l+1/m+1/n>1 is the group A(5)


text:
Q: Domain error in arguments using invgauss.rvs() function I'm trying to generate random gaussian random variables as follows:
mu = 0
k=10
r = invgauss.rvs(mu, size=k)

however I keep getting the following error
ValueError: Domain error in arguments.

Any help would be greatly appreciated.

A: mu has to be greater than 0, according to documentation


text:
Q: Createjs, how do you extend the class of an Animate CC library object? I am in the process of converting a large flash application to canvas using Typescript and I am having trouble using classes to extend library objects.
Using a class library for buttons,
class BtnClass {
    constructor(el: createjs.MovieClip) {
        el.addEventListener("mouseover", MouseOverHandler.bind(el));
    }
}

If I have an object placed on stage in Animate CC, I could use this class by adding the actions in frame for export and all works well,
Btn1 = new BtnClass(this.buttons.btn1_mc);

But I cannot get this to work for dynamically placed library objects.
I get an error when trying to extend my object with this class on a library object that is not placed on the Animate CC stage.
var libraryObject = new lib.btn2_mc();
var dynamicButton = createjs.extend(new BtnClass(libraryObject), libraryObject);
currentElement.addChild(dynamicButton);

Error: Argument of type 'BtnClass' is not assignable to parameter of type '() => any'. Type 'BtnClass' provides no match for the signature '(): any'.
Any ideas are appreciated.

A: I am extending the createjs component in the following way and its works. Please try let me know if you have any issues
class BtnClass extends (lib.btn2_mc as { new(): any; }) {
}

A: The extend method takes classes as parameters, not instances.
createjs.extend(BtnClass, lib.btn2_mc);

It then returns the prototype, which you can append methods on to. You can then promote the methods from the super class, giving you access to the prototype methods if you override them. See the EaselJS classes for specific usages.
Not sure it will solve your problem, but at least its the correct syntax.


text:
Q: Why is child state resolve functions are executed before parent state promises are resolved I'm using ui-router v0.2.13. This page states that:

All resolves on one state will be resolved before moving on to the
  next state, even if they aren't injected into that child

And more

All resolves for all the states being entered are triggered and
  resolvesd before the transition will enter any states (regardless of
  the resolve being injected somewhere)

However, in my case, child state resolve function is executed before parent's resolve promise is resolved. How is this possible?
Here:
$stateProvider
    .state('route1', {
        url: "/route1",
        templateUrl: "route1.html",
        resolve: {
            parent: ["$timeout", "$q", function ($timeout, $q) {
                var d = $q.defer();
                $timeout(function () {
                    d.resolve();
                }, 5000);
                return d.promise;
            }]
        }
    })
    .state('route1.list', {
        url: "/list",
        templateUrl: "route1.list.html",
        controller: function ($scope) {
            $scope.items = ["A", "List", "Of", "Items"];
        },
        resolve: {
            child: function () {
                alert("I'm shown before `parent` resolved");
            }
        }
    });

If you navigate to /route1/list the alert is immediately shown instead of waiting 5 seconds until a parent resolve promise is resolved.

A: All resolves are guaranteed to be resolved before transition is actually performed. But the statements don't point out that resolve functions will be called synchronously. And that's is correct.
According to the ui-router source code, invocables are resolved as "parallel" as possible. Only ones dependent on other invocables (either from parents or from current state declaration) will be executed after their dependencies are resolved.
So the only way to make child invocable to be invoked after parent is resolved is to specify parent as dependency of child invocable.
.state("route1",{
   //..
   resolve: {
        parent: ["$timeout", "$q", function ($timeout, $q) {
            var d = $q.defer();
            $timeout(function () {
                d.resolve();
            }, 5000);
            return d.promise;
        }]
    }
 })
 .state("route1.list",{
    //...
    resolve: {
         child: ["parent", function(parent) {
             //will be called only after parent is resolved
         }]
 })

Excerpt from the GitHub resolve.js source code comments:

Invocables are invoked eagerly as soon as all dependencies are available.
      This is true even for dependencies inherited from a parent call to $resolve.

A: So what is actually going on is that since you are not injecting "parent" into the child routes resolved, it will not wait for the parent before trying to resolve child. If you try this:
resolve: {
  child: function(parent) {
    alert("Child Resolved!");
  }
}

then your child's resolved will be called after the timeout (resolve) of the parent.
I believe what the doc means is that it will wait for all resolved before carrying out the actual transition to the state such as loading the controller and rendering the templates.
In the plunker below (which I mostly borrowed from an old scotch.io example) I played with moving around the dependencies. If the child resolve depends on a parent resolve then the parent promise is resolved before the child. If the child doesn't depend then the child resolves first (even if the timeout length is set to 0).
In all cases though, the parent and child controllers aren't entered, and the views aren't rendered until both the child and parent are both resolved.
http://plnkr.co/edit/EtU03AfgUAlWNsEH0TuU?p=preview


text:
Q: Deduping database records comparing values in numerous fields So I'm trying to clean some phone records in a database table.
I've found out how to find exact matches in 2 fields using:
/* DUPLICATE first & last names */

SELECT
    `First Name`,
    `Last Name`,
     COUNT(*) c
FROM phone.contacts
GROUP BY
    `Last Name`,
    `First Name`
HAVING c > 1;

Wow, great.
I want to expand it further to look at numerous fields to see if a phone number in 1 of 3 phone fields is a duplicate.
So I want to check 3 fields (general mobile, general phone, business phone).
1.to see that they are not empty ('')
2.to see if the data (number) in any of them appears in the other 2 phone fields anywhere in the table.
So pushing my limited SQL past its limit I came up with the following which seems to return records with 3 empty phone fields & also records that don't have duplicate phone numbers.
/* DUPLICATE general & business phone nos */

SELECT
    id,
   `first name`,
   `last name`,
   `general mobile`,
   `general phone`,
   `general email`,
   `business phone`,
    COUNT(CASE WHEN `general mobile` <> '' THEN 1 ELSE NULL END) as gen_mob,
    COUNT(CASE WHEN `general phone` <> '' THEN 1 ELSE NULL END) as gen_phone,
    COUNT(CASE WHEN `business phone` <> '' THEN 1 ELSE NULL END) as bus_phone
FROM phone.contacts
GROUP BY
   `general mobile`,
   `general phone`,
   `business phone`
HAVING gen_mob > 1 OR gen_phone > 1 OR bus_phone > 1;

Clearly my logic is flawed & I wondered if someone could point me in the right direction/take pity etc...
Many thanks

A: The first thing you should do shoot the person that named your columns with spaces in them.
Now then, try this:
SELECT DISTINCT
   c.id,
   c.`first name`,
   c.`last name`,
   c.`general mobile`,
   c.`general phone`,
   c.`business phone`
from contacts_test c
join contacts_test c2
    on (c.`general mobile`!= '' and c.`general mobile` in (c2.`general phone`, c2.`business phone`))
    or (c.`general phone` != '' and c.`general phone` in (c2.`general mobile`, c2.`business phone`))
    or (c.`business phone`!= '' and c.`business phone` in (c2.`general mobile`, c2.`general phone`))

See a live demo of this query in SQLFiddle.
Note the extra check for phone != '', which is required because the phone numbers are not nullable, so their "unknown" value is blank. Without this check, false matches are returned because of course blank equals blank.
The DISTINCT keyword was added in case there are multiple other rows that match, which would result in a nxn result set.

A: In my experience, when cleaning up data, it's much better to have a comprehending view of the data, and a simple way to manage it, than to have a big and bulky query that does all the analysis at once.
You can also, (more-or-less) renormalize the database, using something like:
Create view VContactsWithPhones
as
Select id,
       `Last Name` as LastName,
       `First Name` as FirstName,
       `General Mobile` as Phone,
       'General Mobile' as PhoneType
From phone.contacts c
UNION
Select id,
       `Last Name`,
       `First Name`,
       `General Phone`,
       'General Phone'
From phone.contacts c
UNION
Select id,
       `Last Name`,
       `First Name`,
       `Business Phone`,
       'Business Phone'
From phone.contacts c

This will generate a view with triple the rows of the original table, but with a Phone column, that can be of one of three types.
You can than easily select from that view:
//empty phones
SELECT *
FROM VContactsWithPhones
Where Phone is null or Phone = ''

//duplicate phones
Select Phone, Count(*)
from VContactsWithPhones
where (Phone is not null and Phone <> '')  -- exclude empty values
group by Phone
having count(*) > 1

//duplicate phones belonging to the same ID (double entries)
Select Phone, ID, Count(*)
from VContactsWithPhones
where (Phone is not null and Phone <> '')  -- exclude empty values
group by Phone, ID
having count(*) > 1

//duplicate phones belonging to the different ID (duplicate entries)
Select v1.Phone, v1.ID, v1.PhoneType, v2.ID, v2.PhoneType
from VContactsWithPhones v1
   inner join VContactsWithPhones v2
     on v1.Phone=v2.Phone and v1.ID=v2.ID
where v1.Phone is not null and v1.Phone <> ''

etc, etc...

A: You can try something like:
SELECT * from phone.contacts p WHERE `general mobile` IN (SELECT `general mobile` FROM phone.contacts WHERE id != p.id UNION SELECT `general phone` FROM phone.contacts WHERE id != p.id UNION SELECT `general email` FROM phone.contacts WHERE id != p.id)

Repeat 3 times for each: general mobile, general phone and general email. It can be put in a single query but would be less readable.


text:
Q: get all data from select2 I have a simple select2 input field:
https://select2.org
$('.inputField').select2({
   tags: true
});

The user can add values if there are not available.
Now I have a button, which calls a function getData()
function getDatat() {
   $('.inputField').select2('data');
}

This function gets the value of the selected data.
But I would like to have all data. Also the unselected data is in the dropdown menu.
Any idea how I can solve this?


text:
Q: how to push json array on solana blockchain and get it using anchor project How can I push json on the blockchain and get it using anchor project. I am trying to push simple json like this:
[
    {
        "text": "What is React?",
        "code": "001",
        "Options": ["Framework", "Frontend Language", "User Interface", "Backend"]
    }
]

I am trying with calculator project example like this (lib.rs):
use std::vec;

use anchor_lang:: prelude::*;

declare_id!("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS");

#[program]
pub mod myfirstproject {
use super::*;

    pub fn create(ctx: Context < Create >, init_message: String) -> Result<()> {
        let calculator = &mut ctx.accounts.calculator;
        calculator.greeting = init_message;
        Ok(())
    }

    pub fn add(ctx: Context<Addition>, num1: i64, num2: i64) -> Result<()> {
        let calculator = &mut ctx.accounts.calculator;
        calculator.result = num1 + num2;
        Ok(())
    }

    pub fn pushjson(ctx:Context<PushingData>, myjson:Vec::new) -> Result<()>{
        let calculator = &mut ctx.accounts.calculator;
        calculator.data_array = myjson;
        Ok(())
    }
}

#[derive(Accounts)]
pub struct Create < 'info> {
#[account(init, payer = user, space = 264)]
pub calculator: Account < 'info, Calculator>,

#[account(mut)]
pub user: Signer < 'info>,
pub system_program: Program < 'info, System>
}

#[derive(Accounts)]
pub struct Addition<'info> {
#[account(mut)]
pub calculator: Account<'info, Calculator>
}

#[derive(Accounts)]
pub struct PushingData<'info> {
#[account(mut)]
pub calculator: Account<'info, Calculator>
}

#[account]
pub struct Calculator {
pub greeting: String,
pub result: i64,
pub remainder: i64,
pub data_array: vec![]
}

(test file myfirstproject.ts)
const assert = require('assert')
const anchor1 = require('@project-serum/anchor')
const { SystemProgram } = anchor1.web3

describe('myfirstproject', () => {
const provider = anchor1.AnchorProvider.env();
anchor1.setProvider(provider)
const calculator = anchor1.web3.Keypair.generate()
const program = anchor1.workspace.Myfirstproject

it('Creates a calculator', async () => {
    await program.rpc.create("Welcome to Solana calculator", {
        accounts: {
            calculator: calculator.publicKey,
            user: provider.wallet.publicKey,
            systemProgram: SystemProgram.programId
        },
        signers: [calculator]
    })
    const account = await program.account.calculator.fetch(calculator.publicKey)
    assert.ok(account.greeting === "Welcome to Solana calculator")
})

it('Add two numbers', async () => {
    await program.rpc.add(new anchor1.BN(2), new anchor1.BN(3), {
        accounts: {
            calculator: calculator.publicKey
        }
    })
    const account = await program.account.calculator.fetch(calculator.publicKey)
    assert.ok(account.result.eq(new anchor1.BN(5)))
})

it('Push Json Data', async () => {
    let myArray = [
        {
            "text": "What is React?",
            "code": "001",
            "Options": ["Framework", "Frontend Language", "User Interface", "Backend"]
        }
    ]
    await program.rpc.pushjson(myArray, {
        accounts: {
            calculator: calculator.publicKey
        }
    })
    const account = await program.account.calculator.fetch(calculator.publicKey)
    assert.ok(account.data_array.eq(myArray))
})
})

I am not able to make it work, how to push the json data on the blockchain or first of all how to test it locally with the anchor project.
If someone can help.
Thanks


text:
Q: Replicate Column-1 values in rest of the columns for non blank values only I have data frame like this -

A
B
C
D

Name-1
3.5
NA
3

Name-2
Na
NA
1

Name-3
NA
7
NA

Name-4
NA
NA
NA

Name-5
1
NA
1

I am looking for the result like given below

A
B
C
D

Name-1
Name-1

Name-1

Name-2

Name-2

Name-3

Name-3

Name-4

Name-5
Name-5

Name-5

Can any one help me with the codes. I about 200 columns in this I need to repeat this task

A: Try this using across() from dplyr:
library(dplyr)
#Code
new <- df %>% mutate(across(B:D,~ifelse(!is.na(.),A,'')))

Output:
       A      B      C      D
1 Name-1 Name-1        Name-1
2 Name-2               Name-2
3 Name-3        Name-3
4 Name-4
5 Name-5 Name-5        Name-5

Some data used:
#Data
df <- structure(list(A = c("Name-1", "Name-2", "Name-3", "Name-4",
"Name-5"), B = c(3.5, NA, NA, NA, 1), C = c(NA, NA, 7L, NA, NA
), D = c(3L, 1L, NA, NA, 1L)), class = "data.frame", row.names = c(NA,
-5L))

A: Another option is case_when
library(dplyr)
df %>%
    mutate(across(B:D, ~ case_when(!is.na(.) ~ A)))

data
df <- structure(list(A = c("Name-1", "Name-2", "Name-3", "Name-4",
"Name-5"), B = c(3.5, NA, NA, NA, 1), C = c(NA, NA, 7L, NA, NA
), D = c(3L, 1L, NA, NA, 1L)), class = "data.frame", row.names = c(NA,
-5L))

A: Try the code below
> cbind(df[1], ifelse(!is.na(df[-1]), df$A[row(df)], ""))
       A      B      C      D
1 Name-1 Name-1        Name-1
2 Name-2               Name-2
3 Name-3        Name-3
4 Name-4
5 Name-5 Name-5        Name-5

Data
> dput(df)
structure(list(A = c("Name-1", "Name-2", "Name-3", "Name-4",
"Name-5"), B = c(3.5, NA, NA, NA, 1), C = c(NA, NA, 7, NA, NA
), D = c(3, 1, NA, NA, 1)), class = "data.frame", row.names = c(NA,
-5L))

A: A for loop approach:
for(col in 2:ncol(your_data)) {
  your_data[[col]] = ifelse(!is.na(your_data[[col]]), your_data[[1]], "")
}

Or the same thing using lapply instead:
your_data[-1] = lapply(your_data[-1], function(x) ifelse(!is.na(x), your_data[[1]], ""))

A: Similar to Duck, but for any number of columns, assuming first column is always named A:
library(dplyr)

df %>% mutate(across(-A,  ~if_else(!is.na(.), A, "")))


text:
Q: SQLAlchemy query with variable class name and attributes Hi I have a question about Python and a SQL query.
The class :
class person(db.Model):
__tablename__ = "person"

id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Integer, unique=False, nullable=False)
street = db.Column(db.Integer, unique=False, nullable=False)

Then I like to get all 'items' of a column in a list.
example:
streets = [person.street for person in db.session.query(Person.street).distinct()]]

This shall return a list of streets in the column streets.
But how can I make this attribute item variable?
I tried:
streets = [x.column_name for x in db.session.query((Class.attribute).distinct()]

I hope to find a solution that provides a list of items in the column, when we pass in a variable 'column-name"...
the problem:
x.column_name fails.... I learned in the documents that inside the list comprehension the 'x' is local to that list. If I change to x.street, then the street list is returned. Why?
How can I replace a well-known attribute to that class by a variable name?


text:
Q: Approximate 4 circles inside ellipse to get the radii I need the approximate radii of the following ellipse.

The bottom/top and left/right radii should be the same nevertheless need to be checked. Which means 4 radii should be the result of my code. I did the following in paint, the green circle should give me the top radius and red the left (the right and bottom one aren't drawn here).
The idea I'm working on is to crop the image (left/right/top/bottom side) and approximate circles to the cropped images. With the cv2.findContours-feature some white pixels get recognized as highlighted here.
Is there a way to approximate my drawn red circle from above with these given coordinates? The problems I've seen on the internet are all with a given center point or angle which I don't have. Is there a cv2 function that draws circles with only some given coordinates or something similar?

A: Use this function : cv2.fitEllipse(points) and pass contour points -Ziri
Yes this did the trick. I got the radii after your function with:
(x, y), radius = cv2.minEnclosingCircle(i)


text:
Q: Difference between "lightning bolt" and "lightning flash"
A. I was frightened by a bolt of lightning
B. I was frightened by a flash of lightning

Here are two sentences above, and I chose B as my answer, but answer in my book turns out to be A. I found that there are both expressions available in my dictionary, which makes me confused and not know which one is more acceptable. I'm wondering whether there are some nuances in two sentences.
The definitions:

bolt: lightning that appears as a white line in the sky
flash: a bright light that shines for a short time and then stops shining

A: *

*bolt - a flash of lightning that looks like a white line against the sky

*flash - a sudden bright light that quickly disappears
A lightning flash is the entire discharge whereas a lightning bolt is a single jagged white line from the discharge.
I must admit that both are frightening.

A: With out more context, I'd say either "bolt" or "flash" is OK. "Flash" emphasizes the suddenness and light, and "bolt" makes me think more of the light traveling through the sky. Your book may prefer "A" because the "flash" is the result of the bolt of lightning, and not the lightning itself, but I'm just guessing.
Used figuratively, "bolt" tends to be applied to things that move quickly. For example,

He grabbed his backpack and was out the door like a bolt of lightning.

"Flash" on the other hand tends to be applied to things that are sudden and figuratively or literally have to do with light or enlightenment. For example,

As soon as I stopped worrying about it, the answer came to me like a flash of lightning.


text:
Q: FilePond,Laravel restore uploaded temporary files on validation failure after searching a lot here and there I am going to put my question here . If any body can help out in this regard . Let me explain the things I am working on Laravel and Filepond .
Filepond upload and revert is working perfectly but I am facing problem in restoring the file back if the validation gets failed i-e restore the file on filepond.

                 files: [{
                     source: 'filename',
                     options: {
                       type: 'limbo',
                    },

                }, ],

the source is coming from laravel controller function
FilePond.setOptions({
                server: {

                    process: './filepond-upload',
                    revert: './filepond-delete',
                    restore: './filepond-restore',
                    // restore: {
                    //     url    :'./filepond-restore/?id=',
                    //     method :'GET',

                    // },
                    headers: {
                        'X-CSRF-TOKEN': '{{ csrf_token() }}',
                        'Access-Control-Expose-Headers': 'Content-Disposition,'
                        // 'Access-Control-Expose-Headers': 'Content-Disposition',
                    }

                }

            });

Controller function -
public function filepondRestore(Request $request, string $id) {
   $abc = ('/posts/tmp/post6399a6ba2ea280.18814893/presentation_1.png');
   return response()->json('', 200, [
      'Content-Type' => 'image/png',
      'Content-Disposition' => 'inline;
      filename="'.$abc.'"',
   ]);
}

but either get 302 redirection or 500 server error.
If any body have implemented such kind of functionality I ll be thankful for sharing.
Thanks in advance.
Happy Coding


text:
Q: How long does it take a Widow Mine to attack an enemy unit? I have been trying to incorporate the new Widow Mine unit into my army. When I burrow the Widow Mine their is a circle that indicates it's attack radius. However, I have noticed that when enemy units enter into it's attack radius, the Widow Mine's ability Unstable Payload doesn't activate instantly.
Instead the Widow Mine takes "a few seconds" and then fires it's missile. This has become increasingly perplexing as I have seen:

*

*Zerglings run partly into and then out of the firing radius of a Widow Mine without the ability triggering.

*Zerglings on Creep with the Metabolic Boost run through the attack radius of a Widow Mine without it detonating.

How long does an enemy unit need to be in the attack radius of a Widow Mine for the Unstable Payload ability to be triggered?

A: A Widow Mine takes 1.5 in game seconds to lock on to an enemy and fire.
This translates to different real time seconds based on game speed:
Slower - 2.49s
Slow   - 1.875s
Normal - 1.5s
Fast   - 1.241s
Faster - 1.088s

Source


text: Q: Rails: How to upload image from URL to S3 through controller I'm trying to find a way to import an image from URL to Amazon S3 without using a client-side hack (jQuery). It looks like Paperclip doesn't allow for uploading from a URL.


text:
Q: How much can you bring from Skyrim SE to Skyrim VR? I read an article the other day that suggested Skyrim VR is now moddable by PC users via mod managers.  The current limitations are as one would expect:

*

*No SKSE yet; the devs have made it clear that this requires a lot of work involving the new addresses under the hood, so SKSE-required mods are not currently supported

*No physics model/skeleton changes work yet.   This means UNP bodies with the physics model and CBP use in general doesn't work yet

*Fores New Idles (FNIS) doesn't work yet

Right now, this kills most of my mods that affect gameplay (my needs mods, some of my companions, and things requiring FNIS) but should keep tree replacers and body replacers intact.  The Unofficial Patch also works, and all DLC are included with SVR.
My question is, what about saves and such?  I've been doing another playthrough in SE and have cleared the College of Winterhold and Thieves Guild quests. I can see the benefit of just starting from scratch, but when you're 80 hours in, that's harder to stomach than if you're 800 hours in, since you just did everything.   What specifically will and will not port over, beyond just certain mods?

A: With the exception of SKSE, both CBBE and many, many mods work well with VR.  In fact, I have both FNIS and XP32 running, along with 35 other mods.
Limitations: anything that needs SKSE or SKSE-reliant mods.  First person mods are a bit hit-and-miss, since your person is at a non-visible angle.  Skyrim VR with the 2017 textures, RLO, and VWDE is ludicrously pretty.


text:
Q: How to debug function values Trying to understan what is wrong in function? but cant find what is wrong
Sub test()
Dim a as double, b as double
    a = "10,31"
    b = "10,31"
Msgbox check(a,b)
End Sub

Function check(a as double, b as double)
    ff = TypeName(a) ' double
    gg = TypeName(b) ' double
    If a= b Then GoodExVat = True Else GoodExVat = False: diffExVAt = b - a ' here a = 10,31 b=10,31 diffExVAt = -3.5527136788005-15
check = diffExVAt
End Function

if a and b seted as  10,31 everything is ok, but when 10,31 comes from other function or expression then i got -3.5527136788005-15
What is that? It is not first time i got same thing. What is wrong with Excel?

A: Do not use : in It-Else, it is a bit confusing. If you write it normally, it should work ok:
Sub Test()
    Dim a As Double, b As Double
    a = "10,31"
    b = "10,31"
    MsgBox check(a, b)
End Sub

Function check(a As Double, b As Double)
    ff = TypeName(a)    ' double
    gg = TypeName(b)    ' double
    If a = b Then
        GoodExVat = True
    Else
        GoodExVat = False
    End If

    diffExVAt = b - a    ' here a = 10,31 b=10,31 diffExVAt = -3.5527136788005-15
    check = diffExVAt

End Function

And concerning debugging - simply use F8 and the Step-by-step method.

Concerning the 10,31 coming from other function and expression and getting a -3.55...-15, then the problem is in the floating point mathematics:

*

*Floating point inaccuracy examples

*Is floating point math broken?


text:
Q: Imagick from Azure Blob I have a PHP site that currently pulls images off an Azure Blob, writes it to disk using file_put_contents, then imagick reads the file from the disk using readImageFile. I would rather this live in memory than be wrote to disk, then read from disk. How can I accomplish this? When I try to ReadImageBlob, I get the below error:
Warning: Imagick::readimageblob() expects parameter 1 to be string, resource given in <file> <line>

Below is a snippet of my code (This is just testing code, not production):
// Get Data from Azure Storage Blob
$blob = $blobClient->getBlob($containerName, $documentPath);

// Get TIF file from Blob and convert to PDF
$im = new imagick();
$im->readImageBlob($blob->getContentStream());
$im->setImageFormat('pdf');

// Echo as PDF
header('Content-Type: application/pdf');
echo $im;

A: You should be able to use stream_get_contents to read the string from the stream that you have. Example:
$im->readImageBlob(stream_get_contents($blob->getContentStream()));


text:
Q: Android Nexus 7 DPI for Eclipse The Nexus 7 is that TVDPI, but that is not used in programming apps for it.  Eclipse uses the HDPI, LDPI, MDPI, XHDPI, and XXHDPI folders.  After my research, I still have found no solid conclusion.
Four different sources, four different answers:
1.33 x MDPI
HDPI
XHDPI
No direct answer
So my question:
Does anyone really know which density (HDPI/LDPI/MDPI/XHDPI/XXHDPI) the Nexus 7 uses?

A:
The Nexus 7 is that TVDPI, but that is not used in programming apps for it.

It certainly can be. You are welcome to use -tvdpi resource set qualifiers, as is covered in the documentation.

Eclipse uses the HDPI, LDPI, MDPI, XHDPI, and XXHDPI folders.

No, it uses -ldpi, -mdpi, -tvdpi, -hdpi, -xhdpi, and -xxhdpi resource set qualifiers, as is covered in the documentation.

Does anyone really know which density (HDPI/LDPI/MDPI/XHDPI/XXHDPI) the Nexus 7 uses?

It uses -tvdpi, as is covered in the documentation.

A:
You can find all the info right in eclise while working with xml layouts. It's very convinient tool to test your design on multiple screens before running on actual devices too.

A: Keep in mind this is for the Nexus 7 ( 2012 ). The more recent Nexus 7 ( 2013 ) resolution is 1200 x 1920, with a density of 320dpi(2.0x)


text:
Q: Table not updating values the more you interact JS I have set up a table with html and populate the values with php.
The idea is to have the user able to update order statuses with a status and a message.
It works fine for first time, but the more you use it, it updates another row or not at all.
Not sure if it is an caching issue.
Please help!
Here is what I have:

                <?php $query = "SELECT user_orders.quote_id,user_orders.date_converted,user_orders.estimated_time_of_arrival,user_orders.order_balance,user_orders.status, user_orders.factory_message,
              users.user_id, users.user_firstname, users.user_lastname
             FROM user_orders
             INNER JOIN users ON user_orders.user_id=users.user_id WHERE user_orders.status != 0 ORDER BY date_converted DESC";

                $select_users = mysqli_query($connection, $query);
                while ($row = mysqli_fetch_assoc($select_users)) {
                    $quote_id = $row['quote_id'];
                    $date_converted = $row['date_converted'];
                    $estimated_time_of_arrival = $row['estimated_time_of_arrival'];
                    $user_id = $row['user_id'];
                    $user_firstname = $row['user_firstname'];
                    $user_lastname = $row['user_lastname'];
                    $total = $row['order_balance'];
                    $factory_message = $row['factory_message'];
                    $status = $row['status'];

                    ?>

                        <?php echo $quote_id ?>
                        <?php echo $date_converted ?>
                        <?php echo $estimated_time_of_arrival ?>
                        <?php echo $user_firstname . " " . $user_lastname ?>
                        <?php echo $total ?>

                        <a href="/app/order_pdf.php?quote_id=<?php echo $quote_id ?>" target="_blank">View</a

                        <?php
                        if ($status === '2') {
                            echo "Approved	";
                        } elseif ($status === '3') {
                            echo "Declined	";
                        } else {
                            echo "Pending	";
                        }
                        ?>

                        <select class="status" name="status">

                                <?
                                if ($status === "2") {

                                    ?>
                                    <option disabled>Please Select</option>
                                    <option value="1">Pending</option>
                                    <option value="2" selected>Accepted</option>
                                    <option value="3">Declined</option>

                                    <?

                                } elseif ($status === "3") {
                                    ?>

                                    <option disabled>Please Select</option>
                                    <option value="1">Pending</option>
                                    <option value="2">Accepted</option>
                                    <option value="3" selected>Declined</option>

                                    <?
                                } else {
                                    ?>
                                    <option disabled>Please Select</option>
                                    <option value="1" selected>Pending</option>
                                    <option value="2">Accepted</option>
                                    <option value="3">Declined</option>
                                    <?
                                }
                                ?>

                            </select>

                        <input class="message" name="message" style="width:100%;"
                                   value="<?php echo $factory_message ?>">

                        Update

                    <?php
                } ?>

And the Js.
$(document).ready(function () {

    $(".factoryUpdate").click(function () {

        var quote_id = $(".quoteid", $(this).parent().parent()).val();
        var message = $(".message", $(this).parent().parent()).val();
        var status = $(".status", $(this).parent().parent()).val();

        var update = $(".update", $(this).parent().parent());

        $.ajax({

            url: "#",
            method: "POST",
            data: {

                "quoteid": quote_id,
                "message": message,
                "status": status
            },
            cache: false,
            success: function () {
                location.reload();
            }
        });

    });
});

A: You are using anchor tag as a button with an empty href, which essentially reloads the page. Sometimes, the reload might happen before the AJAX call gets made.
Add an event object as argument to your onClick function and use preventDefault to prevent the browser from following the href link.
$(document).ready(function () {
    $(".factoryUpdate").click(function (e) {
        e.preventDefault();

        var quote_id = $(".quoteid", $(this).parent().parent()).val();
        var message = $(".message", $(this).parent().parent()).val();
        var status = $(".status", $(this).parent().parent()).val();

        var update = $(".update", $(this).parent().parent());

        $.ajax({

            url: "#",
            method: "POST",
            data: {

                "quoteid": quote_id,
                "message": message,
                "status": status
            },
            cache: false,
            success: function () {
                location.reload();
            }
        });
    });
});

I hope this resolves your issue.


text:
Q: Add Excel data to mail The following code generates mail to send an Excel sheet as a .pdf document.
I would like to customize the body of the e-mail with a range of cells from the actual Excel sheet on a different tab. So basically I have pre-written text pulling figures from the Excel sheet that I want to use as my automated body.
Sub Email_ActiveSheet_As_PDF()

'Do not forget to change the email ID
'before running this code

Dim OutApp As Object
Dim OutMail As Object
Dim TempFilePath As String
Dim TempFileName As String
Dim FileFullPath As String

With Application
    .ScreenUpdating = False
    .EnableEvents = False
End With

' Temporary file path where pdf
' file will be saved before
' sending it in email by attaching it.

TempFilePath = Environ$("temp") & "\"

' Now append a date and time stamp
' in your pdf file name. Naming convention
' can be changed based on your requirement.

TempFileName = ActiveSheet.Name & "-" & Format(Now, "dd-mmm-yy h-mm-ss") & ".pdf"

'Complete path of the file where it is saved
FileFullPath = TempFilePath & TempFileName

'Now Export the Activesshet as PDF with the given File Name and path

On Error GoTo err
With ActiveSheet
    .ExportAsFixedFormat _
      Type:=xlTypePDF, _
      Filename:=FileFullPath, _
      Quality:=xlQualityStandard, _
      IncludeDocProperties:=True, _
      IgnorePrintAreas:=False, _
      OpenAfterPublish:=False
End With

'Now open a new mail

Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)

On Error Resume Next
With OutMail
    .To = "michaelbrentklein@gmail.com"
    .Subject = "2014 Pickup Report Now Available"
    .Body = **NEED HELP HERE**
    .Attachments.Add FileFullPath '--- full path of the pdf where it is saved
    .Send   'or use .Display to show you the email before sending it.
    .Display
End With
On Error GoTo 0

'Since mail has been sent with the attachment
'Now delete the pdf file from the temp folder

Kill FileFullPath

'set nothing to the objects created
Set OutMail = Nothing
Set OutApp = Nothing

'Now set the application properties back to true
With Application
    .ScreenUpdating = True
    .EnableEvents = True
End With
MsgBox ("Email has been Sent Successfully")
Exit Sub
err:
    MsgBox err.Description

End Sub

A: Here is the VBA from my beloved lazy-man daily dashboard that I think does what your trying to accomplish...  I wrote this for a similar situation awhile ago and I've been using it daily for 3+ years now.  I don't know if you are updating links on your file before you send the PDF, but I included it just in case...
You can set a scheduler task in windows to auto open this file every day at XX:XX time The only requirement is the computer is on and the user logged in or at the locked screen.
Here is the features it can offer you.

*

*Update all the workbook links

*Include specific cell data into your email body or subject/to/cc/bcc
        (I used it to include all my email styling and html markup )

*Save the File to PDF format

*Email the File to a specified email address or distribution group

*Save the Excel File with the new values

*Close the Excel File after X amount of time
    (for the instances where you're not at the computer when this runs)

You can put each code block in a separate module.
**Make sure your Workbook_Open code goes in the standard This.Workbook module.. **
The Workbook_Open includes the calls to the rest of the standalone module's functions
VBA CODE
Look for inline comments and update values to get it to fit your needs

Put this code within the This.Workbook Module
Private Sub Workbook_Open()
Application.DisplayAlerts = False
With ThisWorkbook
    .UpdateLinks = xlUpdateLinksAlways
End With
Run ("UpdateLinks")
Run ("SavePDF")
Run ("SendEmail")
Run ("SaveIt")
Run ("MsgBoxDelay")
Application.DisplayAlerts = True
End Sub

Update All Cell Links
Option Explicit

Private Sub UpdateLinks()
    Dim Sh As Worksheet
    Dim Links As Variant
    Dim i As Integer
'   Change sheet YourSheetName to suit
    Set Sh = ThisWorkbook.Worksheets("YourSheetName")
    Links = ActiveWorkbook.LinkSources
    If Not IsEmpty(Links) Then
        For i = 1 To UBound(Links)
                                Application.ScreenUpdating = False
                                Application.DisplayAlerts = False
            Workbooks.Open Links(i)
            Sh.Calculate
                    ActiveWorkbook.Close Savechanges:=True
                                Application.ScreenUpdating = True
                                Application.DisplayAlerts = True
        Next i
    End If
End Sub

Save the Excel =to> PDF
Sub SavePDF()
            Application.DisplayAlerts = False
'Update this path to match where you would like the PDF to be saved from.
  'NOTE THIS LOCATION AS IT WILL BE USED FOR ATTACHING THE FILE TO SEND VIA EMAIL

    ChDir "\\NameofDrive\NameofDirectory\FolderName\FileName"
    ActiveSheet.ExportAsFixedFormat _
    Type:=xlTypePDF, _
    Filename:="\\NameofDrive\NameofDirectory\FolderName\FileName.pdf", _
        Quality:=xlQualityStandard, _
        IncludeDocProperties:=True, _
        IgnorePrintAreas:=False, _
        OpenAfterPublish:=False  ' Optional open PDF once finished..

            Application.DisplayAlerts = True
End Sub

Email Module
Sub SendEmail()
Application.DisplayAlerts = False
Dim OutApp As Object
Dim OutMail As Object
Dim EmailMarkup As String
Dim Send As Boolean
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
Dim headerTxt As String
    headerTxt = Range("n1").Text 'change o1 to the cell you want to reference
Dim bodyTxt As String
    bodyTxt = Range("o1").Text 'change o1 to the cell you want to reference
On Error Resume Next
With OutMail
.To = "" 'put email or distribution group name.
.CC = ""
.BCC = ""

.Subject = "Email Subject"
.EmailMarkup = "" & " " & headerTxt & "" & bodyTxt & ""
.attachments.Add ("\\NameofDrive\NameofDirectory\FolderName\FileName.pdf")  'add the full file path to your attachment if you want to use this function..

.Send 'or use .Display

End With
On Error GoTo 0

Set OutMail = Nothing
Set OutApp = Nothing
Application.DisplayAlerts = True

End Sub

Save the Excel file new values
    Sub SaveIt()
     Application.DisplayAlerts = False
        ChDir "\\NameofDrive\NameofDirectory\FolderName\" 'update to the correct folder
        ActiveWorkbook.Save
     Application.DisplayAlerts = True
    End Sub

Popup to prevent the file from closing once the timer has ran out. Plus the function to
Save/Close Excel after specified amount of time without intervention by user.
 Declare Function MessageBoxTimeout Lib "user32.dll" Alias "MessageBoxTimeoutA" ( _
    ByVal hwnd As Long, _
    ByVal lpText As String, _
    ByVal lpCaption As String, _
    ByVal uType As Long, _
    ByVal wLanguageID As Long, _
    ByVal lngMilliseconds As Long) As Long

    Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" ( _
    ByVal lpClassName As String, _
    ByVal lpWindowName As String) As Long

Public Sub MsgBoxDelay()
        Const cmsg As String = "This work book will auto-close in 30 seconds.  Click YES to CLOSE FILE, Click NO to KEEP OPEN"
        Const cTitle As String = "This work book will auto-close in 30 seconds.Close the Excel File?"
        Dim retval As Long
        retval = MessageBoxTimeout((FindWindow(vbNullString, Title)), cmsg, cTitle, 4, 0, 60000)

        If retval <> 7 Then
            Call SaveIt
            ThisWorkbook.Close
        End If

    End Sub


text:
Q: How to re-create my local git repository from GitHub I had a git repository on my hard drive, but had to replace my hard drive and lost my repository. I have the repository on GitHub, and I used to git push origin master from my local repository.
How do I get my repository back from GitHub and get back to where I was?

A: You can simply clone the repository, and you will be back to the last pushed version:
git clone https://github.com/username/repository.git

By default, the master branch will be checked out.

A: Use git clone: If you had any non-pushed local changes they will be gone.
http://git-scm.com/book/en/v2/Git-Basics-Getting-a-Git-Repository


text:
Q: Export from python 3.5 to csv I scraped six different values with Python 3.5 using beautifulSoup. Now I have the following six variables with values:

*

*project_titles

*project_href

*project_desc

*project_per

*project_mon

*project_loc

The data for e.g. "project_titles" looks loke this:
['Formula Pi - Self-driving robot racing with the Raspberry Pi', 'The Superbook: Turn your smartphone into a laptop for $99'] --> seperated by a comma.
Now I want to export this data to a csv.
The Headlines should be in A1 (project_titles), B1 (project_href) and so on.
And in A2 I need the first value of "project_titles". In B2 the first value of "project_href".
I think I need a loop for this, but I didn't get it. Please help me...

A: Here are a few hints:
When you have a string like you want to separate on a given character, use string.split to get list, which you can get the first value using lst[0].
Then, take a look at the csv module to do your export.


text:
Q: Use cookies coming from Node.JS on port 8080 when developing with React.JS on port 3000 I generated a react application using create-react-app, and I run it on port 3000 (localhost:3000) when I develop.
The React App calls APIs exposed by a Node.JS server running on port 8080 (localhost:8080). The Node.JS server exposes login APIs, and it sets some cookies.
If I build the React App, and I deploy it on the public folder of the Node.JS server everything works fine.
When I run the React App with:
npm start

I can't use the cookies coming from Node.JS server after performing the login since they're coming from a different url (different port).
Did someone experience this issue?


text:
Q: $count=true support in OneDrive API? It looks like the OData $count parameter is not (yet?) supported in the Microsoft Graph API v1.0 for OneDrive.
Request URL: https://graph.microsoft.com/v1.0/me/drive/root/children?$count=true
Response:
{
  "error": {
    "code": "",
    "message": "The query specified in the URI is not valid. Query option 'Count' is not allowed. To allow it, set the 'AllowedQueryOptions' property on EnableQueryAttribute or QueryValidationSettings.",
    "innerError": {
      "request-id": "e65aff74-1c6f-434b-8cd3-04e0c247fb71",
      "date": "2016-10-19T09:48:39"
    }
  }
}

Is this understanding correct?

A: The $count parameter isn't supported with OneDrive. You can get a count of the children however by moving one level up:
/v1.0/me/drive/root/

This includes a folder property that contains the number of child items:
{
    "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users('id')/drive/root/$entity",
    "createdDateTime": "2012-08-03T08:12:58Z",
    "id": "{id}",
    "lastModifiedDateTime": "2016-10-18T14:19:21Z",
    "name": "root",
    "webUrl": "{webUrl}",
    "folder": {
        "childCount": 28
    },
    "root": {},
    "size": 0,
    "specialFolder": {
        "name": "documents"
    }
}