text:
Q: Adding a popup on Google maps markers flutter how would i add a popup to show details about a particular marker on google maps when clicked or tapped using flutter/dart. have tried using onTap function but gives me errors any ideas on how i can achieve this
populateHospitals() {
    Hospitals = []; //array to obtain individual hospital data
    Firestore.instance.collection('markers').getDocuments().then((docs) {
      if (docs.documents.isNotEmpty) {
        setState(() {
          hospitalsToggle = true;
        });
        for (int i = 0; i < docs.documents.length; ++i) {
          Hospitals.add(docs.documents[i].data);
          initMarker(docs.documents[i].data);
        }
      }
    });
  }

  initMarker(hospitals) {
    mapController.clearMarkers().then((val) {
      mapController.addMarker(MarkerOptions(
          position:
              LatLng(hospital['location'].latitude, hospital['location'].longitude),// draws the markers of the hospitals
              draggable: false, // disables dragging of the marker
              consumeTapEvents: true,
              infoWindowText: InfoWindowText(hospital['hospitalname'], 'hospital'), //displays the hospitals name when the icon is clicked

              ));

    });
  }

A: Use Following Read more at source code at https://github.com/flutter/plugins/blob/master/packages/google_maps_flutter/google_maps_flutter/example/lib/place_marker.dart
 List <Marker> markers = new List<Marker>();

//Run the loop and add locations to marker

markers.add(
            Marker(
                markerId: <SOMEID>,
                position: LatLng(hospital['location'].latitude, hospital['location'].longitude),

                onTap: () {
                  //this is what you're looking for!
                  print(hospital['hospitalname']);

                }
            )

        );

//Now add this to your map.


text:
Q: Specific TFS queries in Visual Studio I have some queries that I would like to run on work items within TFS, however the build in fields are too restrictive.
Is there a short cut within TFS where I can run a SQL type query?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to Update the sql table using datagridview checkbox I am working on user rights based ristriction on menues and forms.I want to know how to update the table in sql server  from datagridview checkbox
i have displayed the result  but want to know how to edit table when checkbox is uncheck.
here is the image of my form
here is what i have done till now
Private Sub FillGrid()

    Try

        Dim dt As New DataTable
        Dim strSqll As String
        'strSqll = "Select ugr.programid,ugr.Userid,ugr.menuid,mf.menuname,ugr.ChkAdd, ugr.ChkEdit, ugr.ChkDel, ugr.ChkPrint, ugr.ChkView from UserRights ugr inner join menus mf on(mf.menuid=ugr.menuid and mf.programid=ugr.programid) Where ugr.UserID='admin'"
        strSqll = "Select ugr.programid,ugr.Userid,ugr.menuid,mf.menuname, " _
           & "ugr.ChkAdd,ugr.ChkEdit,ugr.ChkDel,ugr.ChkPrint,ugr.ChkView " _
           & "from UserRights ugr inner join menus mf on(mf.menuid=ugr.menuid and mf.programid=ugr.programid) " _
           & "Where ugr.UserID='" & cmbUserName.SelectedValue.ToString() & "'"
        Dim cmd As New SqlCommand(strSqll, cnMain.dbconnection())
        cmd.CommandType = CommandType.Text
        Dim da As New SqlDataAdapter(cmd)

        da.Fill(dt)
        dgvUserrights.DataSource = dt
        SettingGridColumns()
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try

End Sub

Private Sub SettingGridColumns()
    dgvUserrights.AllowUserToAddRows = False
    dgvUserrights.RowHeadersVisible = False
    dgvUserrights.Columns(0).Visible = False
    dgvUserrights.Columns(1).Visible = False
    dgvUserrights.Columns(2).Visible = False

    dgvUserrights.Columns(3).HeaderText = "Menu "
    dgvUserrights.Columns(4).HeaderText = "Add"
    dgvUserrights.Columns(5).HeaderText = "Edit"
    dgvUserrights.Columns(6).HeaderText = "Del"
    dgvUserrights.Columns(7).HeaderText = "Print"
    dgvUserrights.Columns(8).HeaderText = "View"

    dgvUserrights.Width = Me.Width - dgvUserrights.Left - 20
    dgvUserrights.Columns(3).Width = Convert.ToInt32(dgvUserrights.Width * 0.42)
    dgvUserrights.Columns(4).Width = Convert.ToInt32(dgvUserrights.Width * 0.11)
    dgvUserrights.Columns(5).Width = Convert.ToInt32(dgvUserrights.Width * 0.11)
    dgvUserrights.Columns(6).Width = Convert.ToInt32(dgvUserrights.Width * 0.11)
    dgvUserrights.Columns(7).Width = Convert.ToInt32(dgvUserrights.Width * 0.11)
    dgvUserrights.Columns(8).Width = Convert.ToInt32(dgvUserrights.Width * 0.11)

End Sub

please guide me how to edit the record and make changes in table .
Thanks ..


text:
Q: C fibonacci and equation problem with my code Hello im new to C programming and this is my C Quiz question.
I tried really hard but i cant find the solution or whats wrong with my code.
This equation block cant work.
Any help will be appreciated
Write a C program that displays the below menu and performs the
corresponding operation, according to the selected menu item.
Write separate functions for each menu item and call the related function according to the
selection.
The menu:
(1) Calculate fibonacci value of the entered number,
(2) Calculate the equation (Get value of R from the user),
(3) Get four numbers from the user, sort them in ascending order
Enter your choice:
When the user enters a number (1, 2 or 3) corresponding function will be called
to perform the operation.
The user will enter -1 if he wants to continue and the
menu will be appeared on the screen again.
Question Equation Pic
#include <stdio.h>
#include <stdlib.h>

int fibonacci(int numForFibonacci)
{
    int i = 0;
    int j = 1;
    int k = 1;

    for (int b = 1; b <= numForFibonacci; b++)
    {
        k = i + j;
        printf("%d \n", i);
        i = j;
        j = k;
        printf("%d ", k);
    }
    printf("\n");
    return k;
}

float theEquation(float numR)
{
    float multipl, result = 1;

    for (int i = 1; i <= numR; i++)
    {
        multipl = (2i + 4) / (i * i);
        result *= multipl;
    }
    printf("Result is %f", result);
    return result;
}

int ascending(int n)
{

    int k = 0, i = 0, j = 0, number[4];
    for (int w = 0; w < n; w++)
        scanf("%d", &number[w]);
    for (i = 0; i < n; ++i)
    {
        for (j = i + 1; j < n; ++j)
        {
            if (number[i] > number[j])
            {
                k = number[i];
                number[i] = number[j];
                number[j] = k;
            }
        }
    }
    for (i = 0; i < n; ++i)
        printf("\n%d \n", number[i]);
    return i;
}

int main()
{
    int choice, choiceFibo;
    float choiceR;
    do
    {
        printf("[1]Fibonacci calculation\n");
        printf("[2]calculating the equation: (2k+4)/(k*k)\n");
        printf("[3]sorting numbers in ascending order\n");
        scanf("%d", &choice);
        if (choice == 1)
        {
            printf("enter a number for fibonacci\n ");
            scanf("%d", &choiceFibo);
            fibonacci(choiceFibo);
        }
        else if (choice == 2)
        {
            printf("[2]enter a number for (2k+4)/(k*k)\n");
            scanf("%f", &choiceR);
            theEquation(choiceR);
        }
        else
        {
            printf("[3]enter four numbers to sort them in ascending order\n");
            ascending(4);
        }
        printf("If you want to do another calculation enter '-1'.\n");
        scanf("%d", &choice);
    } while (choice == -1);

    return 0;
}

A: TL;DR: Two main issues:

*

*<integer>i in GNU C represents a complex number, not multiplication.

*integer division is not what you'd expect

Your issue lies on this line:
multipl = (2i + 4) / (i * i);

You might think that 2i would evaulate as 2 * i, but in C, 2i is a complex int.
This can be seen here:
#include <stdio.h>

int main()
{
    int i=1;
    printf("%d", 2i);

    return 0;
}

You would expect this to print 2, but instead we get a warning.
Compiled with onlinegdb:
warning: format '%d' expects argument of type 'int', but argument 2 has type 'complex int'

Second issue: Integer division. The other answer already covered it pretty well, but for the sake of self-contained answers:
In C, integer division finds the integer solution and discards the remainder.
2/5 = 0
6/5 = 1
10/5 = 2
10/4 = 2
10.0 / 4 = 2.5
(double)10/4 = 2.5

You need to "type coerce" one of the values in your numerator or denominator to a float/double, which will coerce the entire fraction to a float/double.
You can do this either with 2.0*i or (double)2*i. Either one works, but the second one is more explicit for readability.
To fix the issue, simply change 2i to (double)2*i.

A: There are only three edits required to get a clean compile:

*

*Change int main() to int main(void)

*Change (2i + 4) / (i * i) to (2*i + 4) / (i * i)

*Change int ... number[4]; to int ... number[4]={0};
If you did not see something similar to the following upon your compile, then turn on all warnings:
>  s0_15.c - 4 warnings
>       28, 28    warning: implicit conversion discards imaginary component: '_Complex int' to 'float'
>       45, 17    warning: variable 'number[i]' may be uninitialized when used here
>       38, 5     note: variable 'number' is declared here
>       54, 27    warning: variable 'number[i]' may be uninitialized when used here
>       38, 5     note: variable 'number' is declared here
>       58, 5     warning: function declaration isn't a prototype.

To ensure accurate calculations, see integer division addressed in another answer under your post.


text:
Q: Loading DataGridView only once based on listbox item selected I am developing a WinForm App using Visual Studio 2017.
I created a list box as follows.

the following dataGridview would appear when i click Fruits for the first time.

i.e whenever i press fruits i should get the above data grid. and similarly corresponding values for vegetables too. But the problem is when i click fruits one more time again the values are getting added. I get the same values again instead of just retaining it. Here is my code.
public Form1()
    {
        FruitList.Add("Mango");
        FruitList.Add("Apple");

        InitializeComponent();
    }
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
    {
        string a = listBox2.SelectedItem.ToString();
        if (a == "Fruits")
        {
            toolStripStatusLabel1.Text = a;
            dataGridView2.Columns.Add("key", "Fruit");
            dataGridView2.Columns.Add("value", "Name");
            foreach (var var in FruitList)
            {
                dataGridView2.Rows.Add("Fruit", var);
            }

        }
    }

And when i select Vegetable only values related to that should appear in dataGridview. But I am getting all things addedd up as i click the item in listbox
How to load the dataGridView values only once.
I am completely new to visual studio and C#. Just exploring various features of it. It would be nice if anyone could help. Thanks in advance
As per er-shoaib 's answer after adding,
 dataGridView2.Rows.Clear();

On above the line
string a = listBox2.SelectedItem.ToString();

I get the contents reloaded.
This is fine unless i dont delete or make any changes. If i delete a selected row say the row Mango using a Button control and when i press the Fruits item in List again , the items are loaded from the beginning. How to make the changes retain throughout the app. Like till i close the Form. Any help on this.

A: You need to clear all the rows before filling new rows to data grid view when you click on item in list box.
Add this line
dataGridView2.Rows.Clear();

On above the line
string a = listBox2.SelectedItem.ToString();

A: Before for loop, clear the datagrid and then start for loop and add items.
    datagrid2.rows.clear().


text:
Q: android Rotation cause NullPointerException when capture photo I am using android:configChanges="orientation|keyboardHidden" in menifest. But still its refresh my activity. Here is my activity tag in menifest.
<activity
    android:name="com.paksoft.people.MiActivity"
    android:label="@string/app_name"
    android:configChanges="orientation|keyboardHidden"
    android:screenOrientation="portrait"
    android:windowSoftInputMode="adjustPan" >
</activity>

A: It's possible that launching of ACTION_IMAGE_CAPTURE intent will push your activity out of memory. See for example: Android startCamera gives me null Intent and ... does it destroy my global variable?
In this situation, onCreate() of your activity is called before onActivityResult(). You should prepare your activity to reinitialize itself, probably using onSaveInstanceState(Bundle).
Note that the decision whether to shut down the activity, or keep it in background, depends on the overall system state that is beyond your control.
PS: android:configChanges attribute is irrelevant because the activity is destroyed not as response of the system to orientation switch (and this cannot happen with android:screenOrientation="portrait"), but because the system resources are drained by launching the Camera app to fullfill the ACTION_IMAGE_CAPTURE intent.


text:
Q: Load date from local database into list, error I have a local database with 2 columns. One is an integer datatype and the other is datetime datatype.
I can successfully load data into the database with following code:
dataIn = myPort.ReadLine();
dt = DateTime.Now;

dbConnection.Open();

using (var insertCmd = new SqlCommand(@"INSERT INTO Measurements (Distance,DateTime) VALUES (@Distance,@DateTime)", dbConnection))
{
    insertCmd.Parameters.Add("@Distance", SqlDbType.VarChar).Value = dataIn;
    insertCmd.Parameters.Add("@DateTime", SqlDbType.DateTime).Value = dt;
    insertCmd.ExecuteNonQuery();
}

dbConnection.Close();

But when running the code below, to select some data and add it to a list, I get the following error.
"The conversion of a varchar data type to a datetime data type resulted in an out-of-range value"
DateTime today = DateTime.Now;
DateTime yearAgo = DateTime.Now.AddYears(-1);
DateTime sdate = new DateTime();
SqlDataReader reader;
List<DateTime> dates = new List<DateTime>();
SqlCommand selectCmd = new SqlCommand("SELECT * FROM Measurements where DateTime between '" + today + "' And '" + yearAgo + "'", dbConnection);
dbConnection.Open();

reader = selectCmd.ExecuteReader();

while (reader.Read())
{
    sdate = reader.GetDateTime(reader.GetOrdinal("DateTime"));
    dates.Add(sdate);
    textBox1.AppendText(sdate.ToString());
}

reader.Close();
dbConnection.Close();

A: As was mentioned in the comments, you should not be using string concatenation to build your select query. You should be using a parameterized query, just like you do when inserting. This will not only eliminate the formatting issue that is likely causing the exception you're seeing, but also protect you from SQL Injection attacks.
DateTime today = DateTime.Now;
DateTime yearAgo = DateTime.Now.AddYears(-1);
DateTime sdate = new DateTime();
SqlDataReader reader;
List<DateTime> dates = new List<DateTime>();

SqlCommand selectCmd = new SqlCommand("SELECT * FROM Measurements where DateTime betweeen @today AND @yearAgo", dbConnection);
dbConnection.Open();

selectCmd.Parameters.AddWithValue("today", today);
selectCmd.Parameters.AddWithValue("yearAgo", yearAgo);

reader = selectCmd.ExecuteReader();

while (reader.Read())
{
   sdate = reader.GetDateTime(reader.GetOrdinal("DateTime"));
   dates.Add(sdate);
   textBox1.AppendText(sdate.ToString());
}
reader.Close();
dbConnection.Close();

As a side note, the query as you've written it will never return results. You are requesting every record created on or after @today AND on or before @yearAgo. It's like asking for every number greater than or equal to 10 AND less than or equal to 5; any number greater than or equal to 10 cannot be less than or equal to 5. You need to flip the @today and @yearAgo parameters in your query.
"SELECT * FROM Measurements where DateTime between @yearAgo and @today"


text:
Q: Is there a way to end all sessions for a subject ID? What I'd like to do is end all sessions for a user when a user changes/resets their password (using ASP.NET Core Identity). I'm using the oidc-client-js library inside of a SPA. I've figured out how to end the current session for a user and cause any tabs that're in that same session (say, other tabs in the same browser windows) to recognize the session is over via the check session iFrame, but any other sessions (say in an incognito window) still seem to have the session functioning, even if their refresh tokens/all persisted grants for that subject ID have been revoked.
Is there some way to make that iFrame return to the client that the session is over for all sessions, like maybe have the iFrame page be checking the persisted grants for that session or something? I'm okay if a currently issued access_token continues working (they're short-lived), but just want the refresh tokens to be invalidated and the session to end.

A: Option 1
There is an OpenID Connect Session draft specification which would do what you want - it allows front end clients to check the current session state via an iframe. This is a draft and may not be implemented by ASP.NET Core Identity though.
https://openid.net/specs/openid-connect-session-1_0.html
Option 2
An alternative mechanism for resolving your problem programatically is by putting a check in your token exchange code. Your access tokens will presumably be relatively short lived, and so the front end has to regularly acquire new access tokens (either via refresh token, or by id token on the implicit flow for instance.
In your token exchange you could check for timestamp when the password was last updated.
If it is more recent than the timestamp when the token was issued, then instead of issuing the fresh access token you could return a 401 and manage a redirect to your authentication endpoint by a mechanism of your choice.
This doesn't instantly log the user out of alternative browser windows, because it depends upon the expiry window of your access tokens. If does have the advantage of working cross browser though, because it doesn't depend upon browser specific session information. It can also check for customers who are blacklisted, or who have changed their email address and other checks which might be relevant to a desire to force re-authentication.
For belt and braces you can use both these techniques.


text:
Q: Transmit video and extra data with Gstreamer RTSP I am streaming my laptop's webcamera (Ubuntu) with this:
gst-rtsp-launch '( v4l2src device=/dev/video0 ! video/x-raw,framerate=30/1,width=320,height=240 ! videoconvert ! queue ! x265enc tune="zerolatency" byte-stream=true bitrate=80 ! rtph265pay name=pay0 pt=96 )'
As I understand RTSP should be able to transmit extra information? For example, CCTV from camera and weather temperature.
How could I implement this? It probably wont be terminal one-liner, but a script, right?
P.S. - in what units bitrate is measured? I calculated ~97 kbps with Wireshark.

A: You could use rtpklvdepay and rtpklvpay to add extra metadata.
https://gstreamer.freedesktop.org/documentation/rtp/rtpklvdepay.html?gi-language=c
https://gstreamer.freedesktop.org/documentation/rtp/rtpklvpay.html?gi-language=c
x265enc Bitrate value is in kbits.
https://gstreamer.freedesktop.org/documentation/x265/index.html?gi-language=c#properties
Best regards


text:
Q: Start loading with jQuery infinite scroll immediately I'm using the Infinite Scroll jQuery plugin with Masonry. Each page has about a hundred small images, which is enough to fill an iPad screen, but not nearly enough for something large, like an iMac's screen.
No matter how high I set the bufferPx option when calling infinite scroll, no additional content is loaded, until the viewer starts scrolling. Is there a way I can modify this behaviour, such that infinite scroll loads additional content before the viewer scrolls?

A: Well, that's the whole point of an infinite scroller: a viewer scrolls, new content loads. You have a sandbox or a fiddle to show the code you've tried? If you do your reading on http://www.infinite-scroll.com/ you could have found what you need: "In 1.4 you can trigger the loading of the next page of content at will".

A: More info would help, but I can provide a simple setup that could ease your qualms.
You can set your infinitescroll object to a variable when you initiate it (for convenience), then target that variable in the callback function in order to get the container height, compare it to the height of the current window, and if it is smaller, you can fire the 'retrieve' method to make it start loading more images. After it fills the screen, it will politely wait for the scroll event as usual.
$infinite = $('#infinitebox');
$infinite.infinitescroll({options}, function() {
    if ( $infinite.height() < $(window).height() ) {
        $infinite.infinitescroll('retrieve');
    }
});


text:
Q: Notepad++ new 1 file I have tried installing Notepad++ on my PC and I have stumbled upon the following behavior: when opening a new document a file called "new X" is created. My goal is to change that. I have tried the following with no result. What are the steps that are needed to be done to do what I have asked for?

A: I inspected Notepad++ 7.5.1 source code (for example in its GitHub repository see file master/PowerEditor/src/Notepad_plus.cpp at line 3430 and after) and it looks like Notepad++ is designed to always have at least one document open. In the code you can see that even if the last non-empty document is closed, it is immediately replaced by new document.
You can potentially modify this behavior by rewriting Notepad++ source code to your needs and created your custom build, but I doubt it is an easy task because the above behavior is there most likely for a reason, e.g. it might be needed to do much more checks in various text-editing methods if there was a possibility that no document is open.
So tl;dr: In Notepad++ you must always have at least one document open.
If you really want to find editor which allows closing all documents, try searching/asking for example at Software Recommendations Stack Exchange site to obtain a recommendation for an alternative.


text:
Q: Songs are increasing in time when I add them to my Ipod? I'm adding some songs from my iTunes onto my iPod and 1 of the 2 songs is 4:31 min long. When I add it to my iPod and then play it ONLY on my iPod, the time changes to 10:19 min long. And, it doesn't stop at 4:31 and start again. I don't even know what is wrong with it. Can anyone help?

A: It's likely that particular song was encoded with a variable bit rate instead of a constant one.  While this improves compression efficiency, unless the MP3 has proper VBR headers, the length will be computed incorrectly on some programs/devices.
You can use the tool VBRFix to add this header to existing VBR-encoded MP3s (vbrfix is also available from most Linux package repositories).


text:
Q: Limit $\lim_{x\to\infty}(x^3+x^2)^{1/3}-(x^4-x^3)^{1/4}$ $$\lim_{x\to\infty}(x^3+x^2)^{1/3}-(x^4-x^3)^{1/4}.$$
The solution is 7/12. I dont know who to get to that solution. My thoughts were that the second root is bigger that the first one so the solution should be minus infinity.

A: We have that, for example by using Hopital,
$$\lim_{t\to 0} \frac{(1+t)^a-1}{t}=\lim_{t\to 0} \frac{a(1+t)^{a-1}}{1}=a.$$
Another way: the limit is simply the definition of the derivative of $t\to (1+t)^a$ evaluated at $t=0$.
Then note that if $x>0$ then
$$\begin{align}
(x^3+x^2)^{1/3}-(x^4-x^3)^{1/4}&=
\frac{(1+1/x)^{1/3}-(1-1/x)^{1/4}}{1/x}\\
&=\frac{(1+1/x)^{1/3}-1}{1/x}+\frac{(1-1/x)^{1/4}-1}{-1/x}.
\end{align}$$
Can you take it from here? What is the limit as $x\to +\infty$?

A: Write $x=1/h$, such that $h \to 0$, if $x \to \infty$
So, the limit becomes $\lim_{h\to0}\frac {{(1+h)^{1/3}} - (1-h)^{1/4}}{h}$
Using L'Hospital rule, we get it to be $\frac{7}{12}$


text:
Q: NodeJS, MongoDB findOne with paremeter and the date I get error when I add another {  } after {ad_id: advertisement._id}. How to handle this??
Error: UnhandledPromiseRejectionWarning: MongoError: >1 field in obj: { $lte: new Date(1551205719440), $gte: new Date(1551202119440) }
    let adContacts = await AdvertisementContact.findOne({ad_id: advertisement._id}, {
        "created_at": {
            "$lte": moment().toDate(),
            "$gte": moment().subtract(24, 'hours').toDate()
          }
    });

I would really appreciate if anyone could fix this.

A: try enclosing both filter criteria in one single object:
let adContacts = await AdvertisementContact.findOne({
ad_id: advertisement._id,
"created_at": {
    "$lte": moment().toDate(),
    "$gte": moment().subtract(24, 'hours').toDate()
  }
});

The problem with your implementation is that you are sending two parameters to findOne, according to documentation first parameter is filter, second parameter is projection.


text:
Q: Numeric Up-Down control, detect up or down Is there a way to detect with the Numeric Up-down control to see if the Up or Down button is pressed without coding?
I know I could keep track of the current value and write some code in the method ValueChanged. I was just thinking maybe there is an easier/shorter way to do this

A: If you want to track specifically the buttons being used and not the value being changed directly you can create your own UserControl that inherits from NumericUpDown and override the UpButton() and DownButton() methods. Otherwise if you want to track all value changes, using the ValueChanged event is the best way to cover all ways of changing the value, including programatically.


text:
Q: Excel 2007: Why #REF!+#REF!=number in evaluating formulas? Total A.xlsx contains formulas adding cells (without the help of functions, just the "+" sign) from several files named 01 A.xlsx, 02 A.xlsx and so on.
All files (including the total) are in the same folder on a server mapped as M:
I don't see any error in cells (no colored corners in cells, no #REF! or #VALUE!, totals are as expected), in Edit Links updating all is OK, but when trying to evaluate any formula, the steps are like this:

*

*#REF!+rest of the formula

*#REF!+#REF!+rest of the formula=#REF!+rest of the formula

Step 2 repeats until the end.
Last step: #REF=number (the value I see in the cell and it is perfect)
It's like when you enter a password and you are pressing different keys, but the field displays **** and when you send the data, it works despite seeing ****.
I have recently switched from Excel 2003 to Excel 2007. I've converted all the files to xlsx and updated the links by replacing xls with xlsx.
Everything looks fine, but evaluating formula is always #REF! until the last step.
I was using evaluation formula to quickly find which file contained a certain value. It was pretty seldom and random enough to not require a permanent breaking of the formula in separate cells.


text:
Q: How to implement standard functionalities using SuiteScript I'd like to build suitescript implementing same functionalities with standard function.
For instance on item detail page (List/WebSite/Items) clicking view button of any non inventory item, you could find out Convert To Inventory button.
Thanks to inspect that browser support, it shows some as follows
I want to build script that archive same functionalities like getNLMultiButtonByName('multibutton_convertinvt').onMainButtonClick(this);return false; but it throws error like getNLMultiButtonByName is not defined.
I want your help.
Regard

A: Probably you're looking for something similar
function onLoad(type, form, request){
     if(type=='view') {
            form.addButton('custpage_button','Custom Button',"getNLMultiButtonByName('multibutton_convertinvt').onMainButtonClick(this);return false;");
        }

}


text:
Q: Change window title dynamically in libGDX How can I change window title during my game? I can't find any method for that. For example I want to show how many points I scored in title bar.

A: try this :
Gdx.graphics.setTitle(""+yourScore);

Good luck !


text:
Q: SVG animate. Fill path after drawn I have created an svg file where the outlines get "drawn" when the page loads.
After the animation is done I want to fill in the outlines.
So this is what I have done.
There are multiple paths. Here is one:
<path id="b1" class="b1" d="M95.4,204.9a31.7,31.7,0,0,1,23,9.6,32.8,32.8,0,0,1,6.9,10.8,38.7,38.7,0,0,1,0,27.4,32.8,32.8,0,0,1-6.9,10.8,31.7,31.7,0,0,1-23,9.6,25.7,25.7,0,0,1-11.9-2.6,25.4,25.4,0,0,1-8.3-6.8v7.7H61V174H75.1v40.3a25.4,25.4,0,0,1,8.3-6.8A25.7,25.7,0,0,1,95.4,204.9Zm-1.7,13.3a19.5,19.5,0,0,0-8,1.6,18.5,18.5,0,0,0-6.1,4.4,19.7,19.7,0,0,0-4,6.6,24.6,24.6,0,0,0,0,16.5,19.7,19.7,0,0,0,4,6.6,18.5,18.5,0,0,0,6.1,4.4,20.9,20.9,0,0,0,16.1-.1,18.1,18.1,0,0,0,6.1-4.5,19.7,19.7,0,0,0,3.9-6.6,24.6,24.6,0,0,0,0-16.1,19.8,19.8,0,0,0-3.9-6.6,18.1,18.1,0,0,0-6.1-4.5A19.6,19.6,0,0,0,93.7,218.2Z" transform="translate(-60.5 -173.5)" fill="none" stroke="#1d1d1b" stroke-miterlimit="10"/>

This is the css for the animation of the outlines:
@keyframes offset{
    to {
        stroke-dashoffset: 0;
    }
}

.b1{
    animation: offset 2s linear forwards;
    stroke-dasharray: 324.774;
    stroke-dashoffset: 324.774;
}

Up until here everything works just fine.
After two seconds the animation is done and now I want to fill it.
This is how I tought I might do it:
@keyframes fill {
    0% {
       fill: white;
       }
    100% {
       fill: black;
       }
      }

      #fill {
          animation-name: fill;
          animation-duration: 2s;
          animation-delay:2s;
      }

The problem is that I allready have an id and a class assigned to the path I tried to change the path's id with the #fill.
If I do this the outline animation get's overwritten and it just waits two seconds . After the two seconds the path get's filled by animation.
How can I make this work?
What I want is to first animate the outlines and when they are done the shape must be filled.
Thnx.

A: You can have as many keyframes as you like in an animation. Just animate the path between 0% and 50%, and then animate the fill between 50% and 100%.
Here you go:

.b1 {
  animation: stroke_fill 4s linear forwards;
  stroke-dasharray: 324.774;
  stroke-dashoffset: 324.774;
}
@keyframes stroke_fill {
  0% {
    fill: white;
  }
  50% {
    fill: white;
    stroke-dashoffset: 0;
  }
  100% {
    fill: black;
    stroke-dashoffset: 0;
  }
}
<svg width="300" height="300" viewBox="0 0 300 300">
  <path id="b1" class="b1" d="M95.4,204.9a31.7,31.7,0,0,1,23,9.6,32.8,32.8,0,0,1,6.9,10.8,38.7,38.7,0,0,1,0,27.4,32.8,32.8,0,0,1-6.9,10.8,31.7,31.7,0,0,1-23,9.6,25.7,25.7,0,0,1-11.9-2.6,25.4,25.4,0,0,1-8.3-6.8v7.7H61V174H75.1v40.3a25.4,25.4,0,0,1,8.3-6.8A25.7,25.7,0,0,1,95.4,204.9Zm-1.7,13.3a19.5,19.5,0,0,0-8,1.6,18.5,18.5,0,0,0-6.1,4.4,19.7,19.7,0,0,0-4,6.6,24.6,24.6,0,0,0,0,16.5,19.7,19.7,0,0,0,4,6.6,18.5,18.5,0,0,0,6.1,4.4,20.9,20.9,0,0,0,16.1-.1,18.1,18.1,0,0,0,6.1-4.5,19.7,19.7,0,0,0,3.9-6.6,24.6,24.6,0,0,0,0-16.1,19.8,19.8,0,0,0-3.9-6.6,18.1,18.1,0,0,0-6.1-4.5A19.6,19.6,0,0,0,93.7,218.2Z"
  transform="translate(-60.5 -173.5)" fill="none" stroke="#1d1d1b" stroke-miterlimit="10" />
</svg>


text:
Q: Strange outcome when testing identity with numpy I have a question about identity testing using numpy. Please, attend at this piece of code:
#! /usr/bin/env python
# encoding: UTF-8

import numpy

data = numpy.array([[1, 2, 3],
                [4, 5, 6],
                [7, 8, 9]])

This returns False, of course
row1 = numpy.array([5, 1, 2])

print row1 in data

This should give false as well, but because it starts with one element of the rows of data (4), it returns True.
row2 = numpy.array([4, 8, 9])
print row2 in data

Somebody can explain the reason in depth?
Thank you all for your time!


text:
Q: Restlet add parameter to webservice call I cannot seem to find anything on the subject on the site of restlet or anywhere on how to add parameters to a webservice call.
I am able to use restlet to call a webservice that doesn't need any parameters and handle the respond.
If you know any other frameworks that are able to call a webservice and pass parameters(rest) please tell me.
Thanks in advance.

A: To add a query parameter to a webservice call with Restlet (version 2.3) you can do the following:
// Create a client resource which will call a given service
ClientResource clientResource = new ClientResource("http://serviceToCall.com");

// Add a query parameter
clientResource.addQueryParameter("queryParameterName", "queryParameterValue");

// Make a "GET"
clientResource.get();

Here is the corresponding Javadocs.

A: Give this a try. Based on the example from the Restlet wiki:
// Create the client resource
ClientResource resource = new ClientResource("http://www.restlet.org");

// Add a query parameter equiv to ?A=1
resource.getReference().addQueryParameter("A","1");

// Customize the referrer property
resource.setReferrerRef("http://www.mysite.org");

// Write the response entity on the console
resource.get().write(System.out);


text:
Q: Java How do i repeat sort until no swaps are done in bubblesort? I am taking 10 elements and performing a bubble sort on them. I want to add an algorithm that repeats the sort until no swaps are needed to make this more efficient.
Essentially I want to:

*

*repeat until no swaps done in a pass

*For elements 1 to (n-1)

*compare contents of element value 1 with the contents of the next value

*if value 1 is greater than value 2

*then swap the values

This is what I have done so far :
    {

        //create array
        int[] iList = new int[10];
        Scanner sc = new Scanner(System.in);

        //takes in array input for 10 numbers

        System.out.println("Enter a array of numbers ");

        for(int i = 0; i< 10; i++ )
        {
            int num = i + 1;
            System.out.println("Enter number " + num);
            iList[i] = sc.nextInt();

        }

        //Bubble sorts the array

        System.out.println("The array =");

        for(int a = 0; a < iList.length; a++ )
        {
          for(int b = a+1; b < iList.length; b++)
          {
                if(iList[a] > iList[b])
                {
                    int iTemp = iList[a];
                    iList[a] = iList[b];
                    iList[b] = iTemp;

                }
                  System.out.println("Progress = " + Arrays.toString(iList) );
           }

        }

    } ```

A: Here is my implementation :
public static void sort(int[] nums) {
        boolean isSwapped;
        int size = nums.length - 1;

        for (int i = 0; i < size; i++) {
            isSwapped = false;
            for (int j = 0; j < size - i; j++) {
                if (nums[j] > nums[j+1]) {
                    int temp = nums[j];
                    nums[j] = nums[j + 1];
                    nums[j + 1] = temp;
                    isSwapped = true;
                }
            }
            if (!isSwapped) break;
        }

        System.out.println("Sorted Array: " + Arrays.toString(nums));
    }


text:
Q: ASP.NET MVC5 Passing an ID and a redirect to another controller Trying to redirect to another controller action (Course) while passing in the selected ID from a different controller which shows the COurses via a viewmodel
What is the correct syntax to display EDIT to the user, redirect to the Courses Controller, select the EDIT action on the Courses Controller and pass in the selected id
I've tried
 @Html.ActionLink({"Edit", Action="Edit", area = "Courses", courseID = item.CourseID})

but the syntax is wrong
Thanks in advance

A: Assuming you don't have a route for edit course, you can use Html.Routelink and just use the default routing.
@Html.RouteLink("Edit", "Default", new System.Web.Routing.RouteValueDictionary {{"controller", "courses"}, {"action", "edit"}, {"id", item.CourseID }})

However if you have a specific route for this like the sample route below,
 routes.MapRouteLowerCase(
            "Edit_course", // Route name
            "courses/edit/{courseid}", // URL with parameters
            new
            {
                controller = "Courses",
                action = "Edit",
                courseid = UrlParameter.Optional
            },
            new string[] { "MyProject.Controllers" }
        );

I guess you can use:
@Html.RouteLink("Edit", "Edit_course", new System.Web.Routing.RouteValueDictionary {{"controller", "courses"}, {"action", "edit"}, {"courseid", item.CourseID }})

This way, you can generate a url to that specific route, rather than just creating a url based on first matching route by action name.

A: The following:
@Html.ActionLink("Edit", "Edit", "Courses", new { courseID = item.CourseID},null)

will redirect you to: localhost:56802/Courses/Edit?courseID=1
In order to redirect you to localhost:56802/Courses%20/Edit/2:
Method 1:
If you are using the default route:
                    routes.MapRoute(
                    name: "Default",
                    url: "{controller}/{action}/{id}",
                    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });

use the following:
@Html.ActionLink("Edit", "Edit", "Courses", new { id = item.CourseID},null)

Method 2:
Use the following route:
                        routes.MapRoute(
                        name: "Default",
                        url: "{controller}/{action}/{courseID}",
                        defaults: new { controller = "Home", action = "Index", courseID = UrlParameter.Optional });

@Html.ActionLink("Edit", "Edit", "Courses", new { courseID = item.CourseID},null)


text:
Q: Credential Security Android App I build an Android Application, that needs some password and some Identiy information, for tests I just put them in String variables, Now I am looking for a way to Encrypt them, Any ideas ( Without Hash code ).
Thanks for your responses.

A: AccountManager can helps you to store in a secure place, username and password of your application:
https://developer.android.com/reference/android/accounts/AccountManager.html


text:
Q: conexion php para guardar este formulario tengo el siguiente formulario: y necesito guardarlo en una base de datos que se llame guardar.php, pero el archivo php no estoy seguro de como hacerlo para guardar toda esta informacion con todos estos campos, los trate de guardar al principio en las varialbes nombre, materno, paternos, matricula, sexo, tipolicencia, nacimientoMes, selcombo, birthday_year y despues trate de crear una variable llamada db que es igual a un mysql_select_db que llama a la tabla llamada altas donde estan estos campos y llama a una variable llamada conexion que, al principio solo hace conexion con la base de datos, despues hice un insert into a las altas con el nombre de todos los campos y las values entre comillas simples con el nombre de las varialbes que estan arriba, despues puse que hiciera un query con la variable consulta que es lo que hace el inser into, pero cuando lo ejecuto, todas las variables que hice al inicio me marca error xampp y no estoy seguro porque, alguna ayuda con esto? somos 3 personas y ninguno nos puede dar esto haha apenas estamos aprendiendo, esto es lo que tenemos en el codigo de php:
<?php
$conexion=mysql_connect("localhost","root","","bdlogin");

$nombre=$_post["nombre"];
$materno=$_post["materno"];
$paterno=$_post["paterno"];
$matricula=$_post["matricula"];
$sexo=$_post["sexo"];
$tipolicencia=$_post["tipoLicencia"];
$nacimientoMes=$_post["nacimientoMes"];
$selcombo=$_post["selCombo"];
$birthday_year=$_post["birthday_year"];

$db=mysql_select_db("altas",$conexion);
$consulta="insert into altas(nombre, materno, paterno, edad, matricula, sexo, licencia, mes, dia, anio) VALUES('$nombre','$materno','$paterno','$matricula','$sexo','$tipolicencia','$nacimiento','$selcombo','$birthday_year')";
$res=mysql_query($consulta);
mysql_close($conexion);
?>

* {
  padding: 0;
  margin: 0;
}
p {
  margin-bottom: 20px;
}
.wrapper {
  width: 80%;
  margin: auto;
  overflow:hidden;
}
header {
  background: rgba(0,0,0,0.9);
  width: 100%;
  position: fixed;
  z-index: 10;
}

nav {
  float: left;
}
nav ul {
  list-style: none;
  overflow: hidden;
}
nav ul li {
  float: left;
  font-family: Arial, sans-serif;
  font-size: 16px;
}
nav ul li a {
  display: block;
  padding: 20px;
  color: #fff;
  text-decoration: none;
}
nav ul li:hover {
  background: #3ead47;
}
.contenido {
  padding-top: 80px;
}
#informacion{
  width: auto;
  background-color: gray;
  margin-top: 5%;
  margin-left: 20%;
  margin-right: 20%;
  margin-bottom: auto;
}
#lasAltas{
  width: auto;
  background-color: gray;
  margin-top: 3%;
  margin-left: 1%;
  margin-right: 55%;
  margin-bottom: auto;
  justify-content: center;
}
input{
  margin: 1%;
  background: lightgray;
}

<form method="post" action="guardar.php" id="lasAltas">

dar de alta

<input name="nombre" id="nombreAlta" type="text" placeholder="nombre">

<input name="materno" id="maternoAlta"type="text" placeholder="apellido materno">

<input name="paterno" id="paternoAlta"type="text" placeholder="apellido paterno">

<input name="edad" id="edadAlta"type="text" placeholder="edad">

<input name="matricula" id="matricula" type="text" placeholder="matricula vehicular">

<input name="sexo"type="radio">hombre <input name="sexo" type="radio">mujer

tipo de licencia

<select name="tipoLicencia" id="Licencia">
        <option value="A">A</option>
        <option value="B">B</option>
    </select>

fecha de nacimiento

    <select name="nacimientoMes" id="nacimientoMes">
        <option value="">mes</option>
        <option value="enero">enero</option>
        <option value="febrero">febrero</option>
    </select>
    <select NAME="selCombo" id="diaAuto">dia
    <option value="">dia</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
    </select>
    <select name="birthday_year" id="year" >
    <option value="0">Año</option>
    <option value="2019">2019</option>
    <option value="2018">2018</option>
    <option value="2017">2017</option>
    <option value="2016">2016</option>
    <option value="2015">2015</option>
    <option value="2014">2014</option>
    <option value="2013">2013</option>
    <option value="2012">2012</option>
    <option value="2011">2011</option>
    <option value="2010">2010</option>
    <option value="2009">2009</option>
    <option value="2008">2008</option>
    <option value="2007">2007</option>
    <option value="2006">2006</option>
    <option value="2005">2005</option>
    <option value="2004">2004</option>
    <option value="2003">2003</option>
    <option value="2002">2002</option>
    <option value="2001">2001</option>
    <option value="2000">2000</option>
    <option value="1999">1999</option>
    <option value="1998">1998</option>
    <option value="1997">1997</option>
    <option value="1996">1996</option>
    <option value="1995">1995</option>
    <option value="1994">1994</option>
    <option value="1993">1993</option>
    <option value="1992">1992</option>
    <option value="1991">1991</option>
    <option value="1990">1990</option>
    </select>

    <input type="submit" value="guardar datos">
</form>

A:

<?php
//mysqli_connect se utiliza para conectar al servidor!
$conexion=mysqli_connect("localhost","root","");

// Recibes los datos que enviastes con la petición POST y los guardas en una variable.

$nombre=$_POST["nombre"];
$materno=$_POST["materno"];
$paterno=$_POST["paterno"];
$matricula=$_POST["matricula"];
$sexo=$_POST["sexo"];
$tipolicencia=$_POST["tipoLicencia"];
$nacimientoMes=$_POST["nacimientoMes"];
$selcombo=$_POST["selCombo"];
$birthday_year=$_POST["birthday_year"];

//mysqli_select_db esta función selecciona la base de datos agregándole 2 parámetros el nombre de la base de datos y conexión que guardas en la variable $conexion

$db=mysqli_select_db("TuBaseDeDatos",$conexion);

//Creas tu query y la guardas en la variable $consulta
$consulta="INSERT INTO TuTabla(nombre,materno, paterno, edad, matricula, sexo, licencia, mes, dia, anio) VALUES('$nombre','$materno','$paterno','$matricula','$sexo','$tipolicencia','$nacimiento','$selcombo','$birthday_year')";

//Con la función mysqli_query ejecutas la query que se guarda en la variable $consulta y guardas el resultado que sera true(exitoso) o false(error) en la variable $res.
$res=mysqli_query($consulta);

// Si la query es exitosa la función mysqli_query devolverá true, en caso contrario false y ocupamos un if que se ejecutara si la expresión es verdadera .

if($res){
    echo "insertado!";
}
else{
    echo "error al ingresar!"
}

mysqli_close($conexion);
?>

PD: hay varias formas de conectar a una base de datos MYSQL y se ocupan las siguientes api(interfaz de programación de aplicaciones).
las api están compuestas por funciones que permiten generar cierta abstracción y en la cual tu sabes que hace la función y que parámetros necesita , sin preocuparte del como lo hace internamente.
1-mysql(fue el primer api obsoleta desde la versión 5.5)
2-mysqli(Esta api agrega mejoras con respecto a programación orientada a objetos)
3-pdo(genera una abstracción que permite acceder a diferentes sistemas de base de datos)
error: Uncaught Error: Call to undefined function mysql_connect(),  ,te esta diciendo que estas llamando a una función que no esta definida y este error se genera porque en realidad la api mysql quedo obsoleta desde la versión 5.5 , así que para este propósito tendrás que utilizar la api mysqli , como vez a todos las funciones mysql la remplaze por mysqli ,simplemente.
Ejemplo:
mysql_connect() | mysqli_connect()
mysql_query()   | mysqli_query()


text:
Q: Tasks, priorities, scheduling and async/await I'm trying to monitor a connection by performing regular 'pings' with a parallel 'timeout' task in case the ping doesn't come back in time.
var pingTask = await Task.WhenAny(
    Task.Run(() =>
    {
        try
        {
            PingThing();
            return true;
        }
        catch
        {
            return false;
        }
    }),
    Task.Run(() =>
    {
        Task.Delay(5000).Wait();
        return false;
    })
);
if (!pingTask.Result) //etc...

I seem to be getting cases where 'other stuff' is taking priority, and this code gets put to one side. So where the pings normally take milliseconds, I'm getting five second timeouts.
The thing is, when I initially put a stopwatch inside the code to check, it didn't say anything like 5 seconds. Which has me wondering whether the CPU isn't shutting down my thread(s) to do other work. But that in turn makes me wonder why it would shut down the first Task, but keep the second one up (otherwise the 'timeout' Task would also take longer).
So I have several questions:

*

*is this a plausible hypothesis?

*is there a way to set the priority inside a task?

*if so is that a good or bad idea?

*is using await here a bad idea (does it somehow signal low priority)?

*is there a way to monitor what all the threads are doing to try and work out what the 'other stuff' is that's stealing my processor time?

Leaky abstractions FTW...


text:
Q: Why does $\mu(\{f_n \to f\})=\mu(\bigcap_{\epsilon \in \mathbb Q^+}\bigcup_{n\in\mathbb N}\bigcap_{m\ge n}\{\mid f_m-f\mid<\epsilon\})$ holds? If $f_n \to f$ a.e, i.e. $\forall \epsilon >0 \exists n_0\in\mathbb N \,\forall x\in N^c \forall n\ge n_0:\mid f_n(x)-f(x)\mid <\epsilon$.
Why does $\mu(\{f_n \to f\})=\mu(\bigcap_{\epsilon \in \mathbb Q^+}\bigcup_{n\in\mathbb N}\bigcap_{m\ge n}\{\mid f_m-f\mid<\epsilon\})$ holds?

A: $x\in\bigcap_{\epsilon\in\mathbb Q^+}\bigcup_{n\in\mathbb N}\bigcap_{m\geq n}\{|f_m-f|<\epsilon\}$ is exactly the statement that for every positive $\epsilon\in\mathbb Q$ an integer $n$ exists such that for every $m\geq n$ we have $|f_m(x)-f(x)|<\epsilon$.
This is evidently equivalent with the same statement with the only difference that $\mathbb Q$ is replaced by $\mathbb  R$, and that statement on its own is exactly the statement that $\lim_{n\to\infty}f_n(x)=f(x)$ or equivalently $x\in\{f_n\to f\}$.
So we have:$$\{f_n\to f\}=\bigcap_{\epsilon\in\mathbb Q^+}\bigcup_{n\in\mathbb N}\bigcap_{m\geq n}\{|f_m-f|<\epsilon\}$$and consequently:$$\mu(\{f_n\to f\})=\mu(\bigcap_{\epsilon\in\mathbb Q^+}\bigcup_{n\in\mathbb N}\bigcap_{m\geq n}\{|f_m-f|<\epsilon\})$$


text:
Q: Pascal's Triangle - Exception in thread "main" java.util.NoSuchElementException I really need help within the next 4 hours. I am trying to create a program that takes in an int and outputs a Pascal's Triangle of that size. However, once I tried to take in the value of "ROW" through the Scanner, I have been getting the following error message:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at Pascal.main(Pascal.java:9)

The program seems fine if I define ROW as a static int along with int "max", but as soon as I use Scanner with it, the problem resurfaces. Thanks in advance.
import java.util.*;
import java.util.Scanner;

public class Pascal {
    private static int max = 0;

    public static void main(String[] args) {
        Scanner kb = new Scanner(System.in);
        int ROW = kb.nextInt();
        int[][] pascal = new int[ROW + 1][];
        pascal[1] = new int[1 + 2];
        pascal[1][1] = 1;
        for (int i = 2; i <= ROW; i++) {
            pascal[i] = new int[i + 2];
            for (int j = 1; j < pascal[i].length - 1; j++) {
                pascal[i][j] = pascal[i - 1][j - 1] + pascal[i - 1][j];
                String str = Integer.toString(pascal[i][j]);
                int len = str.length();
                if (len > max)
                    max = len;
            }
        }

        for (int i = 1; i <= ROW; i++) {
            for (int k = ROW; k > i; k--)
                System.out.format("%-" + max + "s", " ");
            for (int j = 1; j < pascal[i].length - 1; j++)
                System.out.format("%-" + (max + max) + "s", pascal[i][j]);
            System.out.println();
        }

    }
}

A: This is a possible solution using matrix...
import java.util.Scanner;

public class PascalTriangle {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Type N: ");
        pascalTriangle(scanner.nextInt());
        scanner.close();
    }

    public static void pascalTriangle(final int N) {
        int[][] triangle = new int[N][N];

        for (int i = 0; i < N; i++) {
            for (int j = 0; j <= i; j++) {
                if (j == 0)
                    triangle[i][0] = 1;
                else
                    triangle[i][j] = triangle[i - 1][j - 1] + triangle[i - 1][j];
                System.out.print(triangle[i][j] + "\t");
            }
            System.out.println();
        }
    }
}

Output:
Type N: 13
1
1   1
1   2   1
1   3   3   1
1   4   6   4   1
1   5   10  10  5   1
1   6   15  20  15  6   1
1   7   21  35  35  21  7   1
1   8   28  56  70  56  28  8   1
1   9   36  84  126 126 84  36  9   1
1   10  45  120 210 252 210 120 45  10  1
1   11  55  165 330 462 462 330 165 55  11  1
1   12  66  220 495 792 924 792 495 220 66  12  1


text:
Q: Counting the word frequency in two list and output it in a dictionary firstly thanks for clicking in.
I am just a beginner and have no background.
so I have two list of words, one is a checklist, another one is a sort of article,
what I need to do is use the words in the checklist to check the article, see how many time it repeated.
here is what I wrote:

my idea is use for loop to take one word in the first list and use it to compare with each word of the second list, and take another word in the first list and use it to compare with each word of the second list until the first list's words are all done.
what's the problem of my code?
could anyone just some suggestion for my code.

A: Some error handling fixes your code right up. You see, your code trys to add numbers to a key that doesn't exist. Then, if the word isn't in it, it creates that value at 1?
Try this instead:
def check_lists(listA,listB):
  dictionary={}
  for x in listA:
    for y in listB
      if x == y:
        try:
          dictionary[x]+=1
        except KeyError:
          dictionary[x]=1
  return dictionary

This basically takes two lists and compares each value in listA against each value in listB. It then tries to add one to the key in the dictionary, and if the key doesn't exist (hence the try and except statements) creates a key and adds one.
Call it like this:
check_dict=check_lists(joylist,poslist)

A: If I understand your post correctly, you have an article (or a long list of words, called joylist in your example) and you want to extract the word count for a subset of these (poslist in your case)?
Looking at your current solution, you'll get what you want with a little more work (@Agent Biscuit's solution), but this is not the most efficient solution because you'll be iterating over the entire keywords list every time, which you don't need to do. Since you're using a dictionary anyway, you might as well pre-load it:

# Create a new dictionary from the checklist with counts of 0
word_counts = {x: 0 for x in poslist}

# Iterate over all the words in the article
for word in joylist:

    # Check if the word is one we care about tracking. If it is then
    # increment the count associated with that word by one
    if word in word_counts:
        word_counts[word] += 1

If you don't want to use a list comprehension to create your dictionary then we can do this from an empty dictionary as well:
# Create the word-count dictionary from our list of keywords
word_counts = dict()
for word in poslist:
    word_counts[word] = 0

# Iterate over all the words in the article
for word in joylist:

    # Check if the word is one we care about tracking. If it is then
    # increment the count associated with that word by one
    if word in word_counts:
        word_counts[word] += 1

Finally, if you want to filter out counts of zero then you can do that too:
for k in list(word_counts.keys()):
    if word_counts[k] == 0:
        del word_counts[k]

A: You can use the get method of the dict.
poslist = ['a', 'b', 'c', 't']
joylist = ['a', 'd', 'b', 'n', 'a', 'd', 'x', 'm']

c = {}

for j in joylist:
    if j in poslist:
        c[j] = c.get(j, 0) + 1
    else:
        c[j] = c.get(j, 0)

print(c)

Output:
{'a': 2, 'd': 0, 'b': 1, 'n': 0, 'x': 0, 'm': 0}


text:
Q: Opening app from email link in NativeScript vue iOS Edit For more explanation on how to use this plugin with vue, please see NativeScript vue, vuex and urlhandler

I'm trying to make it so that a link in an email can open an app I'm building (its a test app I'm building to learn NativeScript). I am using https://www.npmjs.com/package/nativescript-urlhandler with NativeScript vue on iOS.
In platforms/ios/######/app/App_Resources/iOS/Info.plist I have added
<key>CFBundleURLTypes</key>
<array>
   <dict>
       <key>CFBundleURLName</key>
       <string>com.#######.######</string>
   </dict>
   <dict>
       <key>CFBundleURLSchemes</key>
       <array>
           <string>mycustomappfoobar</string>
       </array>
   </dict>
</array>

And within app.js, I have added:
const handleOpenURL = require("nativescript-urlhandler").handleOpenURL;

handleOpenURL(function(appURL) {
    console.log('Got the following appURL', appURL);
  });

When tapping on mycustomappfoobar://test (link in email) nothing happens...
I looked at the Angular example, and handleOpenURL is being called on initialisation... So I tried putting handleOpenURL within vues mounted hook - but this doesn't work either. Really stumped...
new Vue({
    mounted() {
      handleOpenURL(function(appURL) {
        console.log('Got the following appURL', appURL);
      });
    },
    render: h => h("frame", [h(Home)]),
    store: Store
}).$start();

A: You are updating wrong info.plist. Basically anything inside platforms folder is auto generated. Use the one within your App_Resources/iOS/info.plist.

A: You are calling handleOpenURL too late. This should be called prior to your Vue context being created so that the UIAppDelegate can be properly augmented behind the scenes.
From https://github.com/hypery2k/nativescript-urlhandler/blob/cd6939119910b6345e444055ad17716a7c0ad1d6/demo/app/app.ts
import { handleOpenURL, AppURL } from 'nativescript-urlhandler';

import './app.scss';
import './bundle-config';
import * as app from 'application';

handleOpenURL((appURL: AppURL) => {
    console.log('handleOpenURL', appURL);
});

app.start({ moduleName: 'main-page' });


text:
Q: Select only one state in a map in a Shiny application I have the following dataset:
library(rgdal)
library(leaflet)

tmp <- tempdir()
url <- "http://personal.tcu.edu/kylewalker/data/mexico.zip"
file <- basename(url)
download.file(url, file)
unzip(file, exdir = tmp)
mexico <- readOGR(dsn = tmp, layer = "mexico", encoding = "UTF-8")

pal <- colorQuantile("YlGn", NULL, n = 5)
state_popup <- paste0("Estado: ",
                  mexico$name,
                  "
PIB per c?pita, miles de pesos, 2008: ",
                  mexico$gdp08)

On top of this data I build the following Shiny Application:
# load necessary packages
library(leaflet)
library(shiny)
library(shinydashboard)

ui <- fluidPage(
  # place the contents inside a box
  shinydashboard::box(
    width = 12
    , title = "Click on the map!"
    # separate the box by a column
    , column(
      width = 2
      , shiny::actionButton( inputId = "clearHighlight"
                             , icon = icon( name = "eraser")
                             , label = "Clear the Map"
                             , style = "color: #fff; background-color: #D75453; border-color: #C73232"
      )
    )
    # separate the box by a column
    , column(
      width = 10
      , leaflet::leafletOutput( outputId = "myMap"
                                , height = 850
      )
    )
  ) # end of the box
) # end of fluid page

# create the server
server <- function( input, output, session ){

  # create foundational map
  foundational.map <- shiny::reactive({
    leaflet() %>%
      #addTiles( urlTemplate = "https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_all/{z}/{x}/{y}.png") %>%
      #setView( lng = -87.567215
      #         , lat = 41.822582
      #         , zoom = 11 ) %>%
      addProviderTiles("CartoDB.Positron") %>%
      addPolygons( data = mexico
                   , fillOpacity = 0
                   , opacity = 0.2
                   , color = "#000000"
                   , weight = 2
                   , layerId = mexico$states
                   , group = "click.list"
      )
  })

  output$myMap <- renderLeaflet({

    foundational.map()

  })

  click.list <- shiny::reactiveValues( ids = vector() )

  shiny::observeEvent( input$myMap_shape_click, {

    click <- input$myMap_shape_click
    click.list$ids <- c( click.list$ids, click$id )
    lines.of.interest <- mexico[ which( mexico$states %in% click.list$ids ) , ]

    if( is.null( click$id ) ){
      req( click$id )
    } else if( !click$id %in% lines.of.interest@data$id ){
      leaflet::leafletProxy( mapId = "myMap" ) %>%
        addPolylines( data = lines.of.interest
                      , layerId = lines.of.interest@data$id
                      , color = "#6cb5bc"
                      , weight = 5
                      , opacity = 1
        )

    } # end of if else statement

  }) # end of shiny::observeEvent({})

  shiny::observeEvent( input$clearHighlight, {

    output$myMap <- leaflet::renderLeaflet({

      click.list$ids <- NULL
      foundational.map()

    }) # end of re-rendering $myMap

  }) # end of clearHighlight action button logic

} # end of server

shiny::shinyApp( ui = ui, server = server)

This gives me a map of Mexico where I can select a state. This works fine. However right now if I select another state I have a multiple selections.
What I would like to have is that when I move to another state the ONLY that other state is selected.
Any thoughts on how to accomplish that in the code above?

A: Below is a working example. What have I changed?

*

*There was an observeEvent() on the bottom that also recreated a reactive() in its body. That is bad practice, in that case it is better to use a reactiveVal(). So I added the reactiveVal named myMap_reval to hold our map object.

*I added a part to the observeEvent() that is used to color the selected polygon border. It now first checks if the click.list$ids is empty. If so, it will first reset the color of the previously selected polygon's border. Also, the observer now sets the click.list$ids to just the newly selected value, instead of adding it to a vector.

Hope this helps!

library(rgdal)
library(leaflet)

tmp <- tempdir()
url <- "http://personal.tcu.edu/kylewalker/data/mexico.zip"
file <- basename(url)
download.file(url, file)
unzip(file, exdir = tmp)
mexico <- readOGR(dsn = tmp, layer = "mexico", encoding = "UTF-8")

pal <- colorQuantile("YlGn", NULL, n = 5)
state_popup <- paste0("Estado: ",
                      mexico$name,
                      "
PIB per c?pita, miles de pesos, 2008: ",
                      mexico$gdp08)

# load necessary packages
library(leaflet)
library(shiny)
library(shinydashboard)

ui <- fluidPage(
  # place the contents inside a box
  shinydashboard::box(
    width = 12
    , title = "Click on the map!"
    # separate the box by a column
    , column(
      width = 2
      , shiny::actionButton( inputId = "clearHighlight"
                             , icon = icon( name = "eraser")
                             , label = "Clear the Map"
                             , style = "color: #fff; background-color: #D75453; border-color: #C73232"
      )
    )
    # separate the box by a column
    , column(
      width = 10
      , leaflet::leafletOutput( outputId = "myMap"
                                , height = 850
      )
    )
  ) # end of the box
) # end of fluid page

# create the server
server <- function( input, output, session ){

  # function to create foundational map
  foundational.map <- function(){
    leaflet() %>%
      #addTiles( urlTemplate = "https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_all/{z}/{x}/{y}.png") %>%
      #setView( lng = -87.567215
      #         , lat = 41.822582
      #         , zoom = 11 ) %>%
      addProviderTiles("CartoDB.Positron") %>%
      addPolygons( data = mexico
                   , fillOpacity = 0
                   , opacity = 0.2
                   , color = "#000000"
                   , weight = 2
                   , layerId = mexico$state
                   , group = "click.list")
  }

  # reactiveVal for the map object, and corresponding output object.
  myMap_reval <- reactiveVal(foundational.map())
  output$myMap <- renderLeaflet({
    myMap_reval()
  })

  # To hold the selected map region id.
  click.list <- shiny::reactiveValues( ids = vector() )

  shiny::observeEvent( input$myMap_shape_click, ignoreNULL = T,ignoreInit = T, {

    # If already selected, first remove previous selection
    if(length(click.list)>0)
    {
      remove_id = click.list$ids
      lines.of.interest <- mexico[ which( mexico$state %in% remove_id) , ]
      leaflet::leafletProxy( mapId = "myMap" ) %>%
        addPolylines( data = lines.of.interest
                      , layerId = lines.of.interest@data$id
                      , color = "#000000"
                      , weight = 2
                      , opacity = 0.2)
    }

    # add current selection
    click <- input$myMap_shape_click
    click.list$ids <- click$id  # we only store the last click now!
    lines.of.interest <- mexico[ which( mexico$state %in% click.list$ids ) , ]
    print(click)
    if( is.null( click$id ) ){
      req( click$id )
    } else if( !click$id %in% lines.of.interest@data$id ){
      leaflet::leafletProxy( mapId = "myMap" ) %>%
        addPolylines( data = lines.of.interest
                      , layerId = lines.of.interest@data$id
                      , color = "#6cb5bc"
                      , weight = 5
                      , opacity = 1
        )
    }

  }) # end of shiny::observeEvent({})

  # oberver for the clearHighlight button.
  shiny::observeEvent( input$clearHighlight, {
    click.list$ids <- NULL
    myMap_reval(foundational.map()) # reset map.
  })

}

shiny::shinyApp( ui = ui, server = server)


text:
Q: Validar checkbox Estou tentando fazer com o que um formulário ao ser enviado verifique se o check box esta selecionado, se não ele emite um alert pedindo para selecionar pelo menos uma categoria. O campo do check box busca categorias do banco de dados. O problema é que ao enviar o post ele da a mensagem, ai selecionamos ao menos 1 categoria, e quando tentamos de novo ele dá a mesma mensagem. Enquanto não selecionamos todos ele não para de dar a mensagem.
Utilizei o script abaixo no meu formulário:

Meu Form está assim:

<form id="formulario" action="dados_anuncio.asp?opc=inserir&id=<%=Request.QueryString("id")%>&idPlano=<%=Request.QueryString("idPlano")%>" method="post" name="form1" onSubmit="return validar(this);">
            <select name="id_plano" class="list_of_vochers" id="id_plano" >
              <option value="1">Plano Ouro GRÁTIS</option>
                  </select>
            Selecione até 5 categorias:
            <input name="idDoCliente" type="hidden" id="idDoCliente" value="<%=id%>">
<input name="idDoTipo" type="hidden" id="idDoTipo" value="<%=idTipo%>">
<%planoId_1 = Request.QueryString("idPlano")%>
<%Set csTipo = Server.CreateObject("ADODB.Recordset")
csTipo.Open "SELECT * FROM categorias_profissionais where id_tipo = "&planoId_1&" order by nome asc", Conexao%>

  <% While NOT csTipo.EoF %>

       <input id="id_categoria" name="id_categoria" type="checkbox" value="<% = csTipo("id") %>" onclick="verificar()"/>   <% = csTipo("nome") %>

<% csTipo.MoveNext %>
  <% Wend %>

                  Caso não encontre sua categoria, digite-a no campo abaixo:
                  <input name="outro" type="text"  id="outro" placeholder="Caso não tenha sua categoria acima digite aqui." />
                  <select name="estado" class="list_of_vochers" id="estado"  onChange="combo('#estado','#cidade','combo_subcategorias.asp')">
                    <option value="0" selected>Selecione o Estado</option>
                    <%
While (not csEstado.EOF)
%>
                    <option value="<%=(csEstado.Fields.Item("id").Value)%>"><%=(csEstado.Fields.Item("uf").Value)%> - <%=(csEstado.Fields.Item("nome").Value)%></option>
                    <%
  csEstado.MoveNext()
  Wend
%>
                  </select>
                  <select name="cidade" class="list_of_vochers" id="cidade" >
                    <option value="0">Selecione sua Cidade</option>

                  </select>
Descrição do Anúncio
<% planoId = Request.QueryString("idPlano")
if planoId = 1 then%>
<textarea name="descricao" id="descricao" type="text" placeholder="Exemplo Profissional: Sou profissional especializado em acabamentos em porcelanato com experiência de 10 anos atuando em obras residenciais e comerciais. Tenho um ótimo custo benefício, qualidade e compromisso com prazos."></textarea>
<%else%>
<textarea name="descricao" id="descricao" type="text" placeholder="Exemplo Fornecedor: Somos uma loja de materiais de construção e estamos a mais de 15 anos no mercado fornecendo diversas linhas de materiais e produtos para todos os tipos de obras. Nossos preços são competitivos e nossos produtos são de qualidade."></textarea>
<%end if%>

                <iframe width='100%' height='340px' frameborder='0' src='upload1.asp?idCliente=<%=Request.QueryString("id")%>' scrolling="no">

<%if planoId = 2 then%>
DADOS DE LOCALIZAÇÃO DO FORNECEDOR

                    <input name="logradouro" type="text" class="form-control" id="logradouro" placeholder="Logradouro, número" />
                    <input name="bairro" type="text" class="form-control" id="bairro" placeholder="Bairro" />
                    <input name="cep" type="text" class="form-control" id="cep" placeholder="Cep" onKeyPress="return txtBoxFormat(this, '99.999-999', event);" maxlength="10"/>
                    <%end if%>

<button type="submit" class="btn btn-primary btn-sm">Finalizar Cadastro</button>
                  </form>

A: Criei um exemplo com validação somente com javascript, mas é interessante realizar uma verificação no servidor também. Segue abaixo o link do exemplo:
http://jsbin.com/coredazoce/edit?html,js,output


text:
Q: Animate setStyle in Prototype? This is my code:
$$('.container ul')[0].setStyle({
  top: '20px'
});

Is there a way to animate that code in Prototype?
Thanks!

A: If you add script.aculo.us to your page that will provide the animation you are looking for.
try using the morph() method which will tween between your current style and the style you pass
$$('.container ul')[0].morph({
  top: '20px'
});


text:
Q: What is the multi-label binary classification? Reading PyTorch docs  BCEWithLogitsLoss:

where c is the class number (c > 1 for multi-label binary classification, c = 1 for single-label binary classification), nn is the number of the sample in the batch and p_cp
  c is the weight of the positive answer for the class cc .

What is the multi-label binary classification? Binary assume only two labels AFIK

A: Multi-label in terms of binary classification means that both the classes can be true class for a single example.
For example, in case of dog-cat classifier, for an image containing both dog and cat, it'll predict both dog and cat.

In the multi-label problem there is no constraint on how many of the classes the instance can be assigned to. Wiki


text:
Q: Does Erlang have a way to get the current continuation? Does Erlang have a way to reify the current continuation? I'm thinking something like Scheme/Racket's call-with-current-continuation or let/cc.
I am aware that there are some issues surrounding continuations and concurrency. (I'm reading a paper on "subcontinuations" right now that is discussing some of these issues.)

A: This is not a feature supported in Erlang.


text:
Q: My wx.OnPaint() function is not called constantly in the wx main loop I working on a project using OpenGL and wxPython to make a navigatable 3D user interface.
However, the OnPaint() function doesn't seem to be called continuously in the main loop. That makes my interface not being updated constantly. The function is only called I drag around the window. For example: when I press an arrow key, the object in the window only moves when I drag around the window.
I boiled my code down to these lines of codes. Can anyone help me make the OnPaint() function called constantly in print a bunch of "HI" without the need to drag around the window?
if __name__ == "__main__":
    app = MyApp()
    app.MainLoop()

class MyApp(wx.App):
    def OnInit(self):
        frame = MyFrame()
        frame.Show()
        return True

class MyFrame(wx.Frame):
    def __init__(self):
        self.size = (1000, 700)
        wx.Frame.__init__(self, None, title ="wx", size=self.size)
        self.canvas = MyCanvas(self)

class MyCanvas(GLCanvas):

    def __init__(self, parent):
        GLCanvas.__init__(self, parent, -1, size=(1000, 700))
        self.Bind(wx.EVT_PAINT, self.OnPaint)

    def OnPaint(self, event):
        print("HI")

A: A wx.Window like wx.Frame or GLCanvascan be forced to be repainted by .Refresh().
e.g. You can use the wx.IdleEvent to triggers the canvas to be refreshed continuously.
class MyFrame(wx.Frame):
    def __init__(self):
        self.size = (1000, 700)
        wx.Frame.__init__(self, None, title ="wx", size=self.size)
        self.canvas = MyCanvas(self)
        self.Bind(wx.EVT_IDLE, self.OnIdle)

    def OnIdle(self, event):
        self.Refresh()         # refresh self and all its children
        #self.canvas.Refresh() # refresh self.canvas


text:
Q: How do I know what a character has seen? Apparently, Roderick has spotted something:

A good question
However, I can't for the life of me figure out what it is!
Is there some way to highlight whatever it is he's discovered? Holding alt doesn't seem to do anything.
(This particular instance is behind the permanently closed General Store in Cyseal, but I'm sure it'll come up again later)

A: So as it turns out, what's supposed to happen is that the newly discovered thing appears, with a shiny overlay. For some reason it wasn't happening in my previous position, but here's what it normally looks like:

A strange rock formation!

Secretly, it was a grave!


text:
Q: Git Submodules new Branch on parent dir If I have a project that contains a number of submodules, and I switch to a new branch, from the parent directory, will it include those submodules in my new branch? How will they be affected?

A: A submodule is a SHA1 entry recorded in the index as a special entry 160000.
When you change branches, your index will reflect the SHA1 of those same submodules are recorded in that new branch.
A git submodule update --init --recursive will update said submodules.
That means you can have different version of the same submodule, as referenced by different branches.
Remmeber:

*

*Whatever branch you chose in the parent repo, the submodules are always in a detached HEAD mode (unless you go in a submodule, and checkout a branch there)

*You need to configure a submodule a certain way (see "git submodule tracking latest") in order for it to follow its own upstream branch (you can convert an existing submodule to that mode).
And you would need to make a submodule update --remote from the parent repo in order to trigger a fetch from the submodule configured to follow a branch.


text:
Q: Utilize standard visualuzation parameters for ImageCollection in Earth Engine I've noticed that for many image collections in EE there's a set of properties describing default vizulatization parameters. For example, for Landsat LANDSAT/LO08/C01/T1_RT it is:
...
visualization_0_bands: B4,B3,B2
visualization_0_max: 30000.0
visualization_0_min: 0.0
visualization_0_name: True Color (432)
visualization_1_bands: B5,B4,B3
visualization_1_max: 30000.0
visualization_1_min: 0.0
visualization_1_name: Near Infrared (543)
visualization_2_bands: B7,B5,B3
visualization_2_max: 30000.0
visualization_2_min: 0.0
visualization_2_name: Shortwave Infrared (753)
...

Is there a quick way of applying those? (other then explicitly getting each parameter at a time with get())

A: That's a good question, I wondered the same thing. I am not aware that there is a pre-built function that accomplishes that.
So for convenience I made a function myself, to retrieve the visualization parameters with the corresponding number as a dictionary from a collection. Here's how it works:
function getVis(collection, number){
  var visNumber = ee.String(ee.Number(number))

  var bands = ee.String("visualization_0_bands").replace("0", visNumber)
  var max = ee.String("visualization_0_max").replace("0", visNumber)
  var min = ee.String("visualization_0_min").replace("0", visNumber)

  if(collection.getString(max).getInfo() === null){
    print("Visualisation number "+ number + " is not available,",
    "or the collection has no visualisation properties.",
    "Pick a number which exists in the properties.",
    "An empty visualization will be returned.")
    return {}
  }

  return ee.Dictionary({
    bands: collection.getString(bands).split(","),
    max: ee.Number.parse(collection.getString(max)),
    min: ee.Number.parse(collection.getString(min))
  }).getInfo()
}

var collection = ee.ImageCollection("LANDSAT/LO08/C01/T1_RT")

var visParams = getVis(collection, 1)

Map.addLayer(collection.mosaic(), visParams, "Test")

You could save only the function in a script and implement it whenever you need it with require().


text:
Q: Using $wpdb to insert data into a table Intro

Hello, I am doing some research on how to to use $wpdb to insert data into a table in my database that is not pre-configured by wordpress...

The Ideal

I am working on a walking website, where a user can register, join a team or go solo, and enter their miles on a weekly basis. As they enter their miles, they will be on a leader board, acquire badges, and have their progress displayed on a Google API map of the Appalachian Trail.

I can do all this on a website I build without Wordpress very easily, but this year I thought I would change it up and learn more about how wordpress works...

The Question(s)

My major issue, is that I am getting pulled in several directions on what would be best practice? Would it be a page template? A plugin I would need to develop? Or should I use a plugin that allows php in I have pages created? Or some other method I have yet to discover?

Thanks in advanced.

A: If i understand well, users will update their datas in front-office, and you need to save datas in your custom table.
I think you must check on wp_ajax process which will allow you to post datas in JS to a WP_ajax handler.
This handler will be a PHP function, (can be written in your theme's functions.php) that will insert your datas in your database.


text:
Q: PHP OAuth1 provider for Canonical MaaS I'm trying to authenticate to the MAAS REST API through PHP but I'm not having any luck finding the best way to do so. Basing on the (outdated) examples here: https://maas.io/docs/snap/3.0/ui/api-authentication for ruby and python you need to send the 3 parts of the key but all examples using PHP OAuth1 have only 2 parts of the key so I'm wondering if there is anything about that would allow me to use PHP with MAAS.
TIA


text:
Q: Notice: Undefined variable... variables declared error i recently posted but i do not think i explained it to well.
I have a page products page the url is for example http:.......rest_id=3/area='Enfield'. I have been using similar query throughout my website but this one is not working, even though it was working for about 2 minutes earlier.
I am using a GET statement to get the area name which is in the url, then from there i use the area name to get the correct data from the DB, such as phone number, twitter and Facebook handles. but nothing is showing.
I have error handlers, the only error i have is Notice: Undefined variable: twit in... For all 3 variables, even though they have been declared.
Any ideas why this may be happening.
  if (isset($_GET['area'])) {
                    $franc_dets = $_GET['area'];
                    $get_franc_d = "SELECT * FROM Franc_dets WHERE Fran_City = '$franc_dets'";
                    mysqli_stmt_execute($run_get_franc_d);
                    $iii = 1;

                    while ($row_get_fram = mysqli_fetch_array($run_get_franc_d)) {
                        $fran_phone = $row_get_fram['Fran_Contact_Num'];
                        $twit = $row_get_fram['Twitter'];
                        $iii++;

HTML
   ......

Problems ordering?

<?php echo $fran_phone ?>

Social media

                        <a id='sm_twit' href='https://twitter.com/<?php echo $twit ?>'>@<?php echo $twit ?>

                <a id='sm_fb' href='https://www.facebook.com/<?php echo $fb; ?>'><?php echo $fb; ?>

A: You declare $twit within the while loop. If your query returns no results, then $twit is never defined, therefore the notice you see. In your case I see 2 reasons why you would get no results even if there is data in your DB:

*

*There is quotes in your URL and in your queries, which can conflicts and make the query fail.

*You put your query in mysqli_stmt_execute() which expect a Mysqli Statement, not a string. You have to pass your query in mysqli_prepare(). Then put the result in mysqli_stmt_execute()

Make sure to handle properly the case where no results are returned, which can be as simple that giving a default value to $twit outside the while loop or tell the user that there is no results.
Also, the way you put the variable in your query makes your website vulnerable to SQL injection. I suggest you read on the subject. Use prepared queries with placeholders. See the examples in the PHP manual


text:
Q: How to make simple but effective Hitbox with pygame I'm working on my first game, Catch the cat. I'm new to pygame so don't expect a lot from me.
It is simple game, where you need to click on a cat. As the score goes higher, the cat will go faster.
I need to make hitbox for the cat. Can anyone help?
Here is the code:
    #IMPORTS FOR THE GAME
import pygame, sys
from pygame.locals import *
pygame.init()
#game speed settings
FPS = 5
fpsClock = pygame.time.Clock()
#Display settings
DISPLAY = pygame.display.set_mode((600, 600))
pygame.display.set_caption('Catch the cat')
#background music settings
pygame.mixer.music.load('backmusic.wav')
pygame.mixer.music.play(-1, 0.0)
#COLORS
WHITE = (255, 255, 255)
AQUA = (0, 255, 255)
BLACK = (0, 0, 0)
HITBOXCOLOR = (0, 255, 255, 255)
#CAT IMAGE SETUP
catImg = pygame.image.load('cat.png')
catx = 10
caty = 20
direction = 'right'
# SCORE DISPLAY SETUP
fontObj = pygame.font.Font('freesansbold.ttf', 20)
score = 0
textSurfaceObj = fontObj.render(str(score), True, AQUA, BLACK)
textRectObj = textSurfaceObj.get_rect()
textRectObj.center = (10, 10)
while True:
    DISPLAY.fill(WHITE)
    DISPLAY.blit(textSurfaceObj, textRectObj)
    if direction == 'right':
        catx += 5
        if catx == 300:
            direction = 'down'
    elif direction == 'down':
        caty += 5
        if caty == 300:
            direction = 'left'
    elif direction == 'left':
        catx -= 5
        if catx == 10:
            direction = 'up'
    elif direction == 'up':
        caty -= 5
        if caty == 20:
            direction = 'right'
    DISPLAY.blit(catImg, (catx, caty))
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
    pygame.display.update()
    fpsClock.tick(FPS)

A: Use pygame.Rect objects. You can get a rectangle with the size of the cat by get_rect from the cat surface. Set the position of the cat by the key word attribute topleft.
Use the MOUSEBUTTONDOWN event and collidepoint() to test if the mouse is on the cat when it is clicked:
while True:
    # [...]

    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

        if event.type == pygame.MOUSEBUTTONDOWN:
            cat_rect = catImg.get_rect(topleft = (catx, caty))
            if cat_rect.collidepoint(event.pos):
                print("hit")


text:
Q: Social tags not seen in My Site after I add it using the API Here is my code to tag a page with a tag and title. Later on in the code, I loop through and display the URL and the associated tag. Here I see my tag, but I do not see it in "My site - Tags and Notes".
protected override void CreateChildControls()
{
    Control control = Page.LoadControl(_ascxPath);
    Controls.Add(control);

    Literal lt = new Literal();

    SPServiceContext objServiceContext = SPServiceContext.Current;
    SocialTagManager objSocialTagManager = new SocialTagManager(objServiceContext);

    try
    {
        TermStore objTermStore = objSocialTagManager.TaxonomySession.DefaultKeywordsTermStore;
        Term objTerm = objTermStore.KeywordsTermSet.CreateTerm("I Like Iting", objTermStore.DefaultLanguage);

        System.Uri objURI = new Uri("http://spdev01/Lists/Calendar/calendar.aspx");

        SocialTag objTag = objSocialTagManager.AddTag(objURI, objTerm, "Calendar YoYo");

        lt.Text = objTag.Url.ToString() + objTag.Term.Name + "

";
    }
    catch (Exception ex)
    {
        lt.Text = ex.Message + ex.StackTrace + "
";
    }
    finally
    {
        Controls.Add(lt);
    }

    //Display all the tags
    string myaccount = @"domain\sharepoint";
    UserProfileManager objUPManager = new UserProfileManager(objServiceContext);
    UserProfile objProfile = objUPManager.GetUserProfile(myaccount);
    SocialTag[] allTags = objSocialTagManager.GetTags(objProfile);

    Literal ltTags = new Literal();

    foreach (SocialTag tag in allTags)
        ltTags.Text += string.Format("Tag: {0} - URL: {1}
", tag.Term.Name, tag.Url.ToString());

    Controls.Add(ltTags);
}

I don't see the custom tag in "My Site" but I see it when I loop through the "MyTags" property. Do I have to run a specific job to see it under "My site"?

A: After creating a new term object, commit the changes on TermStore object
objTermStore.CommitAll();
And after creating the SocialTag update the new object
objTag.Update();
Once these methods are called, you will be able to see the Tag in "My Site"
Regards,
Ram.


text:
Q: Directory.CreateDirectory(Path) does not create the given folder This code is running in a ASP Page.
    try
    {
        DirectoryInfo di = Directory.CreateDirectory(destDir);
        DirectoryInfo diOut = Directory.CreateDirectory(destDir + "\\output");

        if (di.Exists)
        {
            ErrorLog(Server.MapPath("Logs/ErrorLog"),"created or existing destDir: " + destDir );
        }

        if (diOut.Exists)
        {
           ErrorLog(Server.MapPath("Logs/ErrorLog"),"created or existing outputDir:" + destDir +"\\output" );
        }

    }
    catch(Exception e)
    {
        ErrorLog(Server.MapPath("Logs/ErrorLog"),"caught error: " + e.ToString() );
    }

The value of dst dir is:

d:\foo-server\THE\jobgenerator\xmlinput\tmp_JobGenerator_09_08_201216_09_21_718374_THE

The parent folder d:\foo-server\THE\jobgenerator\xmlinput already exists.
The log output says that the destDir has been created but when I check the folder I can see that there has been nothing created. The Site is running on a IIS, the configured user has full permission on the parent folder.
I dont understand why the di.Exists results in true even if the folder has not been created. Also no Exception will be thrown.
Thanks for the help.


text:
Q: Excel: Dependent drop-down calculations through multiple sheets (with different columns position) What I am trying to do is doing some calculations (on main sheet as down in SS) through different sheets with similar structure in the same Workbook, so once when I pick something from drop-down it should calculate for instance Total Tonnage through all the sheets and it will give me the results on main page (J4). There are more fields to calculate, but I just need another idea or opinion how to proceed..The sheets are similar but not consistent, combined numbers/text, just some random data actually.

Here are the formulas what I have been using on Column J4 - J7
J4 =IF($A$4=Calculation!$A$2&" ";SUM(tbl_CS1B[Menge '[t']]);IF($A$4=Calculation!$A$4&" ";SUM(tbl_CS2A[Menge '[t']]);IF($A$4=Calculation!$A$7&" ";SUM(tbl_CS3E[Menge '[t']]);IF($A$4=Calculation!$A$8&" ";SUM(tbl_CS3F[Menge '[t']]);IF($A$4=Calculation!$A$9&" ";SUM(tbl_CS3G[Menge '[t']]);IF($A$4=Calculation!$A$10&" ";SUM(tbl_CS3H[Menge '[t']]);IF($A$4=Calculation!$A$11&" ";SUM(tbl_CS3K[Menge '[t']]);IF($A$4=Calculation!$A$12&" ";SUM(tbl_CS3P[Menge '[t']]);IF($A$4=Calculation!$A$15&" ";SUM(tbl_CS7A[Menge '[t']]);IF($A$4=Calculation!$A$16&" ";SUM(tbl_CS7B[Menge '[t']]);IF($A$4=Calculation!$A$17&" ";SUM(tbl_CS7D[Menge '[t']]);IF($A$4=Calculation!$A$18&" ";SUM(tbl_CS7E[Menge '[t']]);""))))))))))))
J5 =IF($A$4=Calculation!$A$2&" ";SUMPRODUCT(1/COUNTIF(tbl_CS1B[Charge];tbl_CS1B[Charge]));IF($A$4=Calculation!$A$4&" ";SUMPRODUCT(1/COUNTIF(tbl_CS2A[Charge];tbl_CS2A[Charge]));IF($A$4=Calculation!$A$7&" ";SUMPRODUCT(1/COUNTIF(tbl_CS3E[Charge];tbl_CS3E[Charge]));IF($A$4=Calculation!$A$8&" ";SUMPRODUCT(1/COUNTIF(tbl_CS3F[Charge];tbl_CS3F[Charge]));IF($A$4=Calculation!$A$9&" ";SUMPRODUCT(1/COUNTIF(tbl_CS3G[CS3G Charge];tbl_CS3G[CS3G Charge]));IF($A$4=Calculation!$A$10&" ";SUMPRODUCT(1/COUNTIF(tbl_CS3H[Charge];tbl_CS3H[Charge]));IF($A$4=Calculation!$A$11&" ";SUMPRODUCT(1/COUNTIF(tbl_CS3K[Charge];tbl_CS3K[Charge]));IF($A$4=Calculation!$A$12&" ";SUMPRODUCT(1/COUNTIF(tbl_CS3P[Charge];tbl_CS3P[Charge]));IF($A$4=Calculation!$A$15&" ";SUMPRODUCT(1/COUNTIF(tbl_CS7A[Charge];tbl_CS7A[Charge]));IF($A$4=Calculation!$A$16&" ";SUMPRODUCT(1/COUNTIF(tbl_CS7B[Charge];tbl_CS7B[Charge]));IF($A$4=Calculation!$A$17&" ";SUMPRODUCT(1/COUNTIF(tbl_CS7D[Charge];tbl_CS7D[Charge]));IF($A$4=Calculation!$A$18&" ";SUMPRODUCT(1/COUNTIF(tbl_CS7E[Charge];tbl_CS7E[Charge]));""))))))))))))
J6 =IF($A$4=Calculation!$A$2&" ";SUMPRODUCT((tbl_CS1B[Rohstoff-Charge]<>"")/COUNTIF(tbl_CS1B[Rohstoff-Charge];tbl_CS1B[Rohstoff-Charge]&""));IF($A$4=Calculation!$A$4&" ";SUMPRODUCT((tbl_CS2A[Rohware Charge]<>"")/COUNTIF(tbl_CS2A[Rohware Charge];tbl_CS2A[Rohware Charge]&""));IF($A$4=Calculation!$A$7&" ";SUMPRODUCT((tbl_CS3E[Rohstoff-Charge]<>"")/COUNTIF(tbl_CS3E[Rohstoff-Charge];tbl_CS3E[Rohstoff-Charge]&""));IF($A$4=Calculation!$A$8&" ";SUMPRODUCT((tbl_CS3F[Rohstoff-Charge]<>"")/COUNTIF(tbl_CS3F[Rohstoff-Charge];tbl_CS3F[Rohstoff-Charge]&""));IF($A$4=Calculation!$A$9&" ";SUMPRODUCT((tbl_CS3G[Rohware Charge]<>"")/COUNTIF(tbl_CS3G[Rohware Charge];tbl_CS3G[Rohware Charge]&""));IF($A$4=Calculation!$A$10&" ";SUMPRODUCT((tbl_CS3H[Rohrware Charge]<>"")/COUNTIF(tbl_CS3H[Rohrware Charge];tbl_CS3H[Rohrware Charge]&""));IF($A$4=Calculation!$A$11&" ";SUMPRODUCT((tbl_CS3K[Rohstoff-Charge]<>"")/COUNTIF(tbl_CS3K[Rohstoff-Charge];tbl_CS3K[Rohstoff-Charge]&""));IF($A$4=Calculation!$A$12&" ";SUMPRODUCT((tbl_CS3P[Rohstoff-Charge]<>"")/COUNTIF(tbl_CS3P[Rohstoff-Charge];tbl_CS3P[Rohstoff-Charge]&""));IF($A$4=Calculation!$A$15&" ";SUMPRODUCT((tbl_CS7A[Rohstoff-Charge]<>"")/COUNTIF(tbl_CS7A[Rohstoff-Charge];tbl_CS7A[Rohstoff-Charge]&""));IF($A$4=Calculation!$A$16&" ";SUMPRODUCT((tbl_CS7B[Rohstoff-Charge]<>"")/COUNTIF(tbl_CS7B[Rohstoff-Charge];tbl_CS7B[Rohstoff-Charge]&""));IF($A$4=Calculation!$A$17&" ";SUMPRODUCT((tbl_CS7D[Rohware Charge]<>"")/COUNTIF(tbl_CS7D[Rohware Charge];tbl_CS7D[Rohware Charge]&""));IF($A$4=Calculation!$A$18&" ";SUMPRODUCT((tbl_CS7E[Rohstoff-Charge]<>"")/COUNTIF(tbl_CS7E[Rohstoff-Charge];tbl_CS7E[Rohstoff-Charge]&""));""))))))))))))
J7 =IF($A$4=Calculation!$A$2&" ";COUNTA(tbl_CS1B[Faß]);IF($A$4=Calculation!$A$4&" ";COUNTA(tbl_CS2A[Faß]);IF($A$4=Calculation!$A$7&" ";COUNTA(tbl_CS3E[Faß]);IF($A$4=Calculation!$A$8&" ";COUNTA(tbl_CS3F[Faß]);IF($A$4=Calculation!$A$9&" ";COUNTA(tbl_CS3G[Faß]);IF($A$4=Calculation!$A$10&" ";COUNTA(tbl_CS3H[Faß]);IF($A$4=Calculation!$A$11&" ";COUNTA(tbl_CS3K[Faß]);IF($A$4=Calculation!$A$12&" ";COUNTA(tbl_CS3P[Faß]);IF($A$4=Calculation!$A$15&" ";COUNTA(tbl_CS7A[Faß]);IF($A$4=Calculation!$A$16&" ";COUNTA(tbl_CS7B[Faß]);IF($A$4=Calculation!$A$17&" ";COUNTA(tbl_CS7D[Faß]);IF($A$4=Calculation!$A$18&" ";COUNTA(tbl_CS7E[Faß]);""))))))))))))
So, as you can see it works but the formulas are kilometers long. Does anyone can help with any other solution(s) or approaches to solve similar things through whole workbook? My WB is formatted as a table from Power Query which gives me more possibilties, like Pivot tables and so on. But I would like to have those infos spilled on one page not on XY pages, like one pivot sheet for one material and so on..
Can that be achieved using INDIRECT function or some other combination?
I am using Office 2016.

A: Power Query and Power Pivot are likely your best options.
You can use INDIRECT, it's a good solution but adds overhead to the calculations.
You could also put the repetitive parts of the calculation into a VBA function and pass it the sheet name but that adds VBA to the file.
Power Query can read data from tables, including multiple tables in one workbook, and then you can append the data together in the data model. You can add DAX measures for your calculations. This also has the side-effect of making it easier to port to PowerBI because the data model exists (if you choose to go down that route).
It's hard to go into detail because I can't see the whole workbook. I'm also not sure whether the screenshot is of the Calculations worksheet or one of the Materials worksheet. And I don't know what is meant by "just for one instance nearby".
If you have an anonymised copy of the full workbook I can take a more detail look at it.


text:
Q: Need to update application settings created by another user A developer who is no longer on the project created the app/appid that our website currently uses to link with Facebook.
I would like to update settings on the app since we have re-branded / changed our domain name and I have no idea how to access it.
Just knowing how to send email to the email contact associated with the app would probably be helpful, but I would also like to know how to move the app from his account to mine.

A: There's no other option than to get him to add you as an admin for the app.


text:
Q: How to access Webservices in Client Application? I am working on Web-services.I Generated WSDL file for my web application.Here based on user name I am getting User details. And I want to run this Web-Service in another application.
That's why I generated .java files using d:>wsimport -keep -s src Wsdl url and I wrote Client Class to get details. But here I got an exception. how can I overcome this.
Below is my UserName.java class. By using this class I generated wsdl file.
public class UserName implements UserId {
String result = null;

@Override
public String getName(String name) {
    try {

        String name1 = name;

        JAXBContext jaxbContext = JAXBContext.newInstance(User.class);

        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        File file = new File("D:/MyWorkspace/JaxWsWithxml/User.xml");
        User userUnmarshal = (User) jaxbUnmarshaller.unmarshal(file);

        List<User> list = userUnmarshal.getUser();
        for (User user : list)
            if (user.getName().equals(name1)) {
                result = user.getName();
                System.out.println("Id " + " " + user.getId() + "  "+ user.getName());

            }

    } catch (JAXBException e) {
        e.printStackTrace();
    }
    return result;
}
}

Below is UserId.java Interface
 public interface UserId
{
 public String getName(String name);
}

Below is Client.java In another application I got .java files using WSDL file
public class Client {

public static void main(String[] args) {
    // TODO Auto-generated method stub
String name1="raj";
int id;
String a=name(name1);
System.out.println("Name is"+a);

}
public static String name(String name1)
{
    UserNameService us=new UserNameService();
    UserName userNmae=us.getUserName();
    return userNmae.getName(name1);
}

 }

Here  UserNameService is service name in WSDL file and UserName port name in WSDL file.
My Exception is:
Exception in thread "main" com.sun.xml.internal.ws.client.ClientTransportException:
HTTP transport error: java.net.ConnectException: Connection refused: connect
at com.sun.xml.internal.ws.transport.http.client.HttpClientTransport.getOutput(Unknown Source)
at com.sun.xml.internal.ws.transport.http.client.HttpTransportPipe.process(Unknown Source)
at com.sun.xml.internal.ws.transport.http.client.HttpTransportPipe.processRequest(Unknown Source)

This is my exception how can I solve Thank you...

A: At first you need to check whether the deployed service is running fine.Since, you are facing connection refused exception, I guess the server is not running properly. Or may be your client application can't access the web-service URL. Since, you already have a WSDL, you can also invoke a web-service by directly referencing the WSDL from java code/ JAX-WS Client.

A: HTTP transport error means your application not running currently. First you should run your Web-service application first and Then execute your client code. It will be work fine. No changes required in your code.


text:
Q: finding max value from multidimensional array in R I have an array of dim 4x1x4x71x128.
The first dim refers to 4 different models.
The third dim refers to lower CI, Correlation, Upper CI and p-value.
What I need as output is a new array of dim 1x1x1x71x128 where the first dim refers to the max value of Correlation(3rd dim) among the 4 models(1st dim).
I tried the following:
newarray <- array(NA, c(1,1,1,71,128))
for (i in 1:4) {
  for (j in 1:nrow(array[1,1,1,,])) {
    for (k in 1:ncol(array[1,1,1,,])){
      newarray[i,1,1,j,k] <- max(array[i,1,1,j,k], na.rm = FALSE)
    }
  }
}

This returns me the maximum value not for Correlation but for lower CI. However, when I change operation to:
newarray[i,1,1,j,k] <- max(array[i,1,2,j,k], na.rm = FALSE)

It does not work. I believe I am not looping right but can't seem to figure it out.
Thanks for you help in advance!

A: x.max <- apply(x , c(3,4,5) ,
                   function(x)
                     ifelse(all(is.na(x)), NA, max(x, na.rm = TRUE)))

Solved!
Result is of dim 4x71x128 with the 2nd element of 1st dim being the desired output.