text:
Q: Enable IKE tracing on windows 10 VPN I have an IKEV2 VPN setup (including certs) that worked fine on windows 7. On Windows 10, the same config fails with 'IKE authentication credentials are unacceptable'. Server is StrongSwan. The last line in the log for a connection attempt is:
2016-02-11T12:34:57.457606+00:00 e01pfw01 charon: [info] 05[IKE] assigning virtual IP 10.7.220.6 to peer '**<removed>**'
2016-02-11T12:34:57.461904+00:00 e01pfw01 charon: [info] 05[IKE] CHILD_SA rw-ops{5592} established with SPIs c221e19b_i 29212c9e_o and TS 10.6.75.0/24 10.7.240.0/20 === 10.7.220.6/32
2016-02-11T12:34:57.518381+00:00 e01pfw01 vpn: [notice] + **<removed>** 10.7.220.6/32 == 212.159.106.131 -- 62.23.139.70 == 10.6.75.0/24
2016-02-11T12:34:57.580529+00:00 e01pfw01 vpn: [notice] + **<removed>** 10.7.220.6/32 == 212.159.106.131 -- 62.23.139.70 == 10.7.240.0/20
2016-02-11T12:34:57.581975+00:00 e01pfw01 charon: [info] 05[ENC] generating IKE_AUTH response 1 [ IDr CERT AUTH CPRP(ADDR) SA TSi TSr N(AUTH_LFT) ]
2016-02-11T12:34:57.582578+00:00 e01pfw01 charon: [info] 05[NET] sending packet: from 62.23.139.70[4500] to 212.159.106.131[4500] (1412 bytes)

I cannot see any issues in the strongswan log, in fact I don't even see a response to the t line above (even though I can see from a pcap that the client sends a response), so I would like to debug the IKE authentication process on the Windows 10 client. Can anyone tell me how this is done?
I have tried netsh set ras tracing * enabled. Log files are created, but nothing relevant to IKE authentication. netsh ipsec dynamic set config property=ikelogging value=1 fails with 'The request is not supported`. I haven't been able to unearth anything else.
It occurred to me that if the windows 10 client was causing a crash in strongswan, but something would appear in the log, right?

A: For enabling logs atleast in Creators update and above for windows we added a new trace provider.
Netsh trace start VpnClient per=yes maxsize=0 filemode=single
<Repro the scenario>
Netsh trace stop

There is also VpnClient_dbg for additional verbose logging

A: Ok - for anyone that experiences similar issues: The windows event log showed that the connection failed with error code 13801. I looked that up here: https://blogs.technet.microsoft.com/rrasblog/2009/08/12/troubleshooting-common-vpn-related-errors/. #4 is 'VPN Server Name as given on client doesn't match with the subjectName of the server certificate.'. I was trying to connect to the VPN server's IP address. I switched to the hostname and voila.
I would still be interested to know how to enable useful logging on the windows 10 VPN though ...


text:
Q: onOptionsItemSelected does not work while set option menu item text by Spannable String builder recently i am working on changing menu item background and I change it by code which I have found there
here is the code
 public void setMenuBackground() {
    // TODO Auto-generated method stub

    inflater.setFactory(new Factory() {

        public View onCreateView(String name, Context context,
                AttributeSet attrs) {
            // TODO Auto-generated method stub
            if (name.equalsIgnoreCase("com.android.internal.view.menu.IconMenuItemView")) {
                LayoutInflater f = (LayoutInflater) cxt
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                final View[] view = new View[1];
                try {
                    view[0] = f.createView(name, null, attrs);
                } catch (ClassNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (InflateException e) {
                    // TODO Auto-generated catch block
                    hackAndroid23(name, attrs, f, view);
                }
                new Handler().post(new Runnable() {

                    public void run() {
                        // TODO Auto-generated method stub
                        view[0].setBackgroundColor(Color.WHITE);
                    }

                });
                return view[0];
            }
            return null;
        }

    });
}

static void hackAndroid23(final String name,
        final android.util.AttributeSet attrs, final LayoutInflater f,
        final View[] view) {
    try {
        f.inflate(new XmlPullParser() {

            public int next() throws XmlPullParserException, IOException {
                try {
                    view[0] = f.createView(name, null, attrs);
                } catch (InflateException e) {
                } catch (ClassNotFoundException e) {
                }
                throw new XmlPullParserException("exit");
            }

            public void defineEntityReplacementText(String entityName,
                    String replacementText) throws XmlPullParserException {
                // TODO Auto-generated method stub

            }

            public int getAttributeCount() {
                // TODO Auto-generated method stub
                return 0;
            }

            public String getAttributeName(int index) {
                // TODO Auto-generated method stub
                return null;
            }

            public String getAttributeNamespace(int index) {
                // TODO Auto-generated method stub
                return null;
            }

            public String getAttributePrefix(int index) {
                // TODO Auto-generated method stub
                return null;
            }

            public String getAttributeType(int index) {
                // TODO Auto-generated method stub
                return null;
            }

            public String getAttributeValue(int index) {
                // TODO Auto-generated method stub
                return null;
            }

            public String getAttributeValue(String namespace, String name) {
                // TODO Auto-generated method stub
                return null;
            }

            public int getColumnNumber() {
                // TODO Auto-generated method stub
                return 0;
            }

            public int getDepth() {
                // TODO Auto-generated method stub
                return 0;
            }

            public int getEventType() throws XmlPullParserException {
                // TODO Auto-generated method stub
                return 0;
            }

            public boolean getFeature(String name) {
                // TODO Auto-generated method stub
                return false;
            }

            public String getInputEncoding() {
                // TODO Auto-generated method stub
                return null;
            }

            public int getLineNumber() {
                // TODO Auto-generated method stub
                return 0;
            }

            public String getName() {
                // TODO Auto-generated method stub
                return null;
            }

            public String getNamespace() {
                // TODO Auto-generated method stub
                return null;
            }

            public String getNamespace(String prefix) {
                // TODO Auto-generated method stub
                return null;
            }

            public int getNamespaceCount(int depth)
                    throws XmlPullParserException {
                // TODO Auto-generated method stub
                return 0;
            }

            public String getNamespacePrefix(int pos)
                    throws XmlPullParserException {
                // TODO Auto-generated method stub
                return null;
            }

            public String getNamespaceUri(int pos)
                    throws XmlPullParserException {
                // TODO Auto-generated method stub
                return null;
            }

            public String getPositionDescription() {
                // TODO Auto-generated method stub
                return null;
            }

            public String getPrefix() {
                // TODO Auto-generated method stub
                return null;
            }

            public Object getProperty(String name) {
                // TODO Auto-generated method stub
                return null;
            }

            public String getText() {
                // TODO Auto-generated method stub
                return null;
            }

            public char[] getTextCharacters(int[] holderForStartAndLength) {
                // TODO Auto-generated method stub
                return null;
            }

            public boolean isAttributeDefault(int index) {
                // TODO Auto-generated method stub
                return false;
            }

            public boolean isEmptyElementTag()
                    throws XmlPullParserException {
                // TODO Auto-generated method stub
                return false;
            }

            public boolean isWhitespace() throws XmlPullParserException {
                // TODO Auto-generated method stub
                return false;
            }

            public int nextTag() throws XmlPullParserException, IOException {
                // TODO Auto-generated method stub
                return 0;
            }

            public String nextText() throws XmlPullParserException,
                    IOException {
                // TODO Auto-generated method stub
                return null;
            }

            public int nextToken() throws XmlPullParserException,
                    IOException {
                // TODO Auto-generated method stub
                return 0;
            }

            public void require(int type, String namespace, String name)
                    throws XmlPullParserException, IOException {
                // TODO Auto-generated method stub

            }

            public void setFeature(String name, boolean state)
                    throws XmlPullParserException {
                // TODO Auto-generated method stub

            }

            public void setInput(Reader in) throws XmlPullParserException {
                // TODO Auto-generated method stub

            }

            public void setInput(InputStream inputStream,
                    String inputEncoding) throws XmlPullParserException {
                // TODO Auto-generated method stub

            }

            public void setProperty(String name, Object value)
                    throws XmlPullParserException {
                // TODO Auto-generated method stub

            }
        }, null, false);
    } catch (InflateException e1) {
        // "exit" ignored
    }
}

it works fine for me but when I changing the text color of menu by code
  SpannableStringBuilder text = new SpannableStringBuilder();
        text.append(str4);
        text.setSpan(new ForegroundColorSpan(Color.BLACK), 0,
                text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
 item.setTitle(text);

I got text with color black bu the problem is
when press the button which the text color changed it give me an error with the following
java.lang.IllegalArgumentException: Invalid payload item type at android.util.EventLong.writeEvent
   (nativemethod) at android app.activity.onMenuItemSelected(Activity.java:2533)....

A: Are you doing all this to change the color of the text of elements in the overflow menu button?
If this is the attempt, you should instead simply change the theme of your app by using the Android Asset Studio. This will generate the complete right theme for your app, including the background of the menu overflow items.
Here's the official documentation about Themes. Basically you're going to zip the content of that generated theme in the zip in your project and define the theme as your app theme in your AndroidManifest file.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Foreach loop not working - is this a nested array? I have an array that I can't seem to retrieve the info from. Is this a nested array?
print_r() results:
Array (
    [0] => Array (
        [0] => Array (
            [title] => Hampton
            [day] => 1st and 3rd Monday
            [time] => 7:30pm
            [contact] => Jan Boyd
            [phone] => 0438 584 558
            [email] =>
        )
        [1] => Array (
            [title] => Frankston
            [day] => 1st and 3rd Wed
            [time] => 9:30am
            [contact] => Vaness Ogues-Canele
            [phone] => 0420 834 791
            [email] =>
        )
    )
)

The code I am using to try to retrieve the info:
foreach( $groups as $group ) { ?>
    <?php echo $group['title'] ?>
    <?php echo $group['day'] ?>
    <?php if ($group['time']) { ?>
<?php }  ?>

A: Have you tried going into the first array with this?
foreach( $groups[0] as $group ) { ?>
    <?php echo $group['title'] ?>
    <?php echo $group['day'] ?>
    <?php if ($group['time']) { ?>
<?php }  ?>

If possible, you could try two foreach loops:
foreach( $groups as $tmp ) { ?>
    foreach ($tmp as $group) {
        <?php echo $group['title'] ?>
        <?php echo $group['day'] ?>
        <?php if ($group['time']) { ?>
    <?php } ?>
<?php }  ?>

A: Try this
foreach( $groups as $group ) {
if(is_array($group)) // it check's array or not
{
 echo $group['title'];
 echo $group['day'];
 echo $group['time'];
}
else
    echo $group;}

A: foreach( $groups as $group )
 foreach( $group as $groups_re )
  {
    echo $groups_re['title'];
    echo $groups_re['day']
    if ($groups_re['time'])
     {
      }
  }


text:
Q: TypeError: __init__() got multiple values for keyword argument 'choices' class StatisticsBaseForm(forms.Form):
    type_choice = forms.ChoiceField(_("Type"), choices=settings.STATISTICS_TYPE_CHOICES, default=0)
    period = forms.ChoiceField("Period", max_length=20, choices=settings.PERIODS, default='week')

    def __init__(self, *args, **kwargs):
        super(StatisticsBaseForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper(self)

    class Meta:
        model = Statistics
        fields = '__all__'

The traceback is the following
  File "/home/jeremie/Projects/Work_Projects/django/loanwolf/statistics/urls.py", line 6, in <module>
    from loanwolf.statistics.views import StatisticsIndexView
  File "/home/jeremie/Projects/Work_Projects/django/loanwolf/statistics/views.py", line 8, in <module>
    from loanwolf.statistics.forms import StatisticsBaseForm
  File "/home/jeremie/Projects/Work_Projects/django/loanwolf/statistics/forms.py", line 17, in <module>
    class StatisticsBaseForm(forms.Form):
  File "/home/jeremie/Projects/Work_Projects/django/loanwolf/statistics/forms.py", line 18, in StatisticsBaseForm
    type_choice = forms.ChoiceField(_("Type"), choices=settings.STATISTICS_TYPE_CHOICES, default=0)
TypeError: __init__() got multiple values for keyword argument 'choices'

I have this error, but I didn't manage to fix it. How could I go ahead on the error? At the beginning, StatisticsBaseForm was a forms.ModelForm, and type_choice and period was in my Statistics model where both were SmallIntegerfield. In that specific context, everything worked fine.

A: Change to
type_choice = forms.ChoiceField(label=_("Type"), choices=settings.STATISTICS_TYPE_CHOICES, initial=0)
period = forms.ChoiceField(label="Period", choices=settings.PERIODS, initial='week')


text:
Q: (quasi) convexity $\frac{x}{y}$ Hej,
I have the function $\frac{x}{y}$ on the domain $R_{++}$.
The Hessian matrix is - as I have calculated it - positive semidefinite.
But I'm not really sure, if the function is really convex at all on the domain.
Thanks for any help.

A: Something went wrong with your calculation, because the Hessian matrix
$$
\begin{pmatrix}
0 & -1/y^2 \\ -1/y^2 & 2/y^3
\end{pmatrix}
$$
has negative determinant.
There is a similar function with positive semidefinite Hessian in the positive quadrant, namely $v(x,y)=x^2/y$. The Hessian is
$$
\begin{pmatrix}
2/y & -2x/y^2 \\ -2x/y^2 & 2x^2/y^3
\end{pmatrix}
= \frac{2}{y^3}\langle x,y \rangle \otimes \langle x,y \rangle \ge 0
$$
Given its simple form, I wonder if there is any "obvious" reason for the convexity of $v$.


text:
Q: Viewpoint gem and Exchange resource account I'm trying my hand at using the Viewpoint gem (by zenchild @ github) as the base for a meeting scheduling system. It's great at reading calendar information from regular Exchange 2007 accounts, but I got stuck trying to change the SOAP request header to allow me to read resource accounts as a delegate.
I came across Link and it seems to indicate what I need to end up with, and I have the feeling I'm in the right place, but I'm just not quite there yet as a ruby/soap programmer. Any help would be appreciated...
Thanks!

A: Scott,
I just saw your posting and I know it's a little old, but if you still need to solve your issue the upcoming version of Viewpoint has delegate access integrated into it.  You can get it today by cloning the github repo.
http://github.com/zenchild/Viewpoint
If you take a look the README file it talks about it a bit, but if you need additional help send me a message on github or stackoverflow and I'll help you out.
Cheers,
Dan


text:
Q: How to create custom share dialog in Android I am using share option from my application to social media. Android default share dialog works fine. I want to customize the dialog so that I can rearrange the share dialog UI similarly as in Flipboard android app. Can any one point out how to do that?

A: i faced this problem. i found solution in this answer i hope it helps you too..
I write the code of this post below in case of not exist in the future:
You must use a custom ListAdapter to add your image. On way is to subclass the ArrayAdapter (used by default by the AlertDialog). Here is an example:
final Item[] items = {
    new Item("Email", android.R.drawable.ic_menu_add),
    new Item("Facebook", android.R.drawable.ic_menu_delete),
    new Item("...", 0),//no icon for this one
};

ListAdapter adapter = new ArrayAdapter<Item>(
    this,
    android.R.layout.select_dialog_item,
    android.R.id.text1,
    items){
        public View getView(int position, View convertView, ViewGroup parent) {
            //Use super class to create the View
            View v = super.getView(position, convertView, parent);
            TextView tv = (TextView)v.findViewById(android.R.id.text1);

            //Put the image on the TextView
            tv.setCompoundDrawablesWithIntrinsicBounds(items[position].icon, 0, 0, 0);

            //Add margin between image and text (support various screen densities)
            int dp5 = (int) (5 * getResources().getDisplayMetrics().density + 0.5f);
            tv.setCompoundDrawablePadding(dp5);

            return v;
        }
    };

new AlertDialog.Builder(this)
    .setTitle("Share Appliction")
    .setAdapter(adapter, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int item) {
            //...
        }
    }).show();

Here is the Item class
public static class Item{
    public final String text;
    public final int icon;
    public Item(String text, Integer icon) {
        this.text = text;
        this.icon = icon;
    }
    @Override
    public String toString() {
        return text;
    }
}


text:
Q: Obtaining GPS data every 1 second I am wondering if there is a way to gather GPS location data every second?  My understanding is is the locationListener is only called when the location is changed.  I have a thread running every second in this manner:
private void startTimer() {
    _mHandler.removeCallbacks(mUpdateTimeTask);
    _mHandler.postDelayed(mUpdateTimeTask, 1000);
}

private Runnable mUpdateTimeTask = new Runnable() {
    public void run() {
        _mHandler.postDelayed(this, _interval);

         // work
    }
};

A: LocationManager
You can set the mintime to 1000ms for location updates in the method requestLocationUpdates.

A: Why do you need to query the location every second? register a listener and set up synchronized members to hold the last location and query them in your 1-second-interval thread.


text:
Q: How can I format a Google Sheets spreadsheet cell with the API? My application generates a table of data and creates a new spreadsheet document in a user's Google Drive. How can I add formatting (color, font-weight, width, etc.) to individual cells? I can't seem to find any documentation, much less how I could implement this through the google-api-ruby-client.
Most of my findings date back to Google API mailing lists that state it isn't supported.
However, I found that another application accomplishes my desired result. An example of "Smartsheet" exporting a document to Google Drive:
From Smartsheet.com:

And the resulting sheet in my Google Drive:

A: (Feb 2017) As of Google I/O 2016, developers no longer need to export to Excel nor create a new Sheet w/the desired formatting, so the other answers are now dated. You can now format cells using the Google Sheets API. Here's a short Python example that bolds the 1st row (assuming the file ID is SHEET_ID and SHEETS is the API service endpoint):
DATA = {'requests': [
    {'repeatCell': {
        'range': {'endRowIndex': 1},
        'cell':  {'userEnteredFormat': {'textFormat': {'bold': True}}},
        'fields': 'userEnteredFormat.textFormat.bold',
    }}
]}

SHEETS.spreadsheets().batchUpdate(
        spreadsheetId=SHEET_ID, body=DATA).execute()

I also made a developer video on this subject if that helps (see below). BTW, you can do the same in Ruby (see its API quickstart sample) or any other language supported by the Google APIs Client Libraries.
The Sheets API provides features not available in older releases, namely giving developers programmatic access to a Sheet as if you were using the user interface (frozen rows, cell formatting[!], resizing rows/columns, adding pivot tables, creating charts, etc.). If you're new to the API, I've created a few videos with somewhat more "real-world" examples:

*

*Migrating SQL data to a Sheet plus code deep dive post

*Formatting text using the Sheets API plus code deep dive post

*Generating slides from spreadsheet data plus code deep dive post
To see what else you can do with Google Sheets via its REST API or Google Apps Script, check out my other videos. As you can tell, the Sheets API is primarily for document-oriented functionality as described above, but to perform file-level access such as import/export, copy, move, rename, etc., use the Google Drive API instead.

A: The APIs only provide access to the data and do not expose any methods to add formatting.

A: Smartsheet utilizes the ability of the Google API to import an Excel file. The code is roughly along these lines:
DocsService client = new DocsService(<YOUR APP NAME>);
client.setOAuthCredentials(<OAUTH PARAMETERS>);

DocumentListEntry newEntry = new SpreadsheetEntry();
newEntry.setMediaSource(new MediaByteArraySource(<EXCEL FILE BYTE ARRAY OUTPUT STREAM>, DocumentListEntry.MediaType.XLS.getMimeType()));
newEntry.setTitle(new PlainTextConstruct(<FILE NAME>));

DocumentListEntry insertedEntry = client.insert(new URL("https://docs.google.com/feeds/default/private/full/"), newEntry);

// This is your URL to the new doc
String docUrl = insertedEntry.getDocumentLink().getHref();

We already had the ability to export a Smartsheet to an Excel file with formatting via Apache POI. Adding export to a Google Spreadsheet was quite simple for us to implement and it provided some additional functionality beyond what you could do via the API.
Sorry for the delayed response - just happened across this question.

A: Another option (and the one that ended up using) is to manually create a Google Sheet file, with all of the formatting pre-configured, as a template.  Then, instead of creating a new spreadsheet document in the user's Google Drive, copy the template, like so:
var config = require('./config');
var google = require('googleapis');

function createSheetFromTemplate(user, templateFileId, done) {

  var oauth2Client = new google.auth.OAuth2(config.google.clientId, config.google.clientSecret);

  oauth2Client.setCredentials({
    access_token: user.google.token,
    refresh_token: user.google.refreshToken,
  });

  var drive = google.drive({
    version: 'v2',
    auth: oauth2Client
  });
  drive.files.copy({
    fileId: templateFileId,
    resource: {
      title: 'New Google Sheet',
      parents: [{
        id: 'root'
      }]
    }
  }, function(err, response) {
    if (err) done(err)

    initializeSpreadsheet(response.id, user, done);
  });
}

In that code, templateFileId is the file id of your shared template.  You can get this fileId from your shared template file in any number of ways, but the quick-and-dirty way is just to copy-and-paste it out of the URL when you share it.
For instance, if the sharing URL is:
https://docs.google.com/spreadsheets/d/1234567890abcdefghijklmnop/edit?usp=sharing
Then the file id is 1234567890abcdefghijklmnop
In my case there is nothing private in the template itself, so I just shared it with 'anyone with the link' configured for 'can view', as described here:
https://support.google.com/drive/answer/2494886
If you need to keep the contents of the template file private, then you'll need to find some way to ensure that the account specified by config.google.clientId has access to it.
Hope that helps!

A: If, like me, uploading a pre-formatted Excel sheet isn't sufficient, then Google Apps Script looks like it might be the way to go.  The Range class specifically lets you manipulate at least some of the formatting you were asking about.
https://developers.google.com/apps-script/reference/spreadsheet/range
setFontColor() and setFontWeight() are there, but I don't know of anything for cell width yet.
Importantly, I have also not yet figured out how to bind a Google Apps Script to the sheet that I'm creating using the Google Drive API SDK (Node/Javascript in my case, Ruby in yours).
https://developers.google.com/apps-script/guides/bound
It's been a while since your question, so I'm betting you've already solved it some other way.  I'm also not necessarily suggesting porting everything in your app over to Google Apps Script (although I'm seriously considering it myself...), but if you or some other reader figures out how to bind a Google App Script to a spreadsheet with the google-api-ruby-client, you might be good-to-go.


text:
Q: robotium nullPointerexception I setup a test project to test another Android project. Everything is working fine. I can call solo.clickOnView and the test will run fine. Problem happens when i try to update a view, for example, i want to update an EditText by calling solo.enterText.
Robotium version
3.6
String hello="Hello world"
solo.enterText(myEditText, hello);

I'm sure that myEditText is a non-null object. Run the test and the below message will come
Error message
java.lang.NullPointerException
at android.app.Instrumentation.runOnMainSync(Instrumentation.java:338)
at com.jayway.android.robotium.solo.TextEnterer.setEditText(TextEnterer.java:52)
at com.jayway.android.robotium.solo.Solo.enterText(Solo.java:1404)
at com.darakok.test.TestMain.testDisplayBlackBox(TestMain.java:30)
at java.lang.reflect.Method.invokeNative(Native Method)
at android.test.InstrumentationTestCase.runMethod(InstrumentationTestCase.java:204)
at android.test.InstrumentationTestCase.runTest(InstrumentationTestCase.java:194)
at android.test.ActivityInstrumentationTestCase2.runTest(ActivityInstrumentationTestCase2.java:186)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:520)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1447)

A: See API docs, this method works only with index of an element. So if you want to use id:
String hello="Hello world";
solo.typeText(myEditText, hello);

A: Perhaps myEditText isn't actually assigned towards the right EditText?
String hello = "Hello world";

//Based on the ID of the EditText you've given via the layout XML:
EditText myEditText = (EditText) tester.getView(R.id.my_edit_text);
solo.enterText(myEditText, hello);

Another possible reason for this occuring is when the myEditText block being executed before the entire Activity (or even just the EditText itself) has loaded properly. In those cases, I suggest assertCurrentActivity(), sleep() or waitForView()

A: you might not have initialized the object.
Just make sure that the objects which you are using have been  initialized.

A: Try to do an extra check before execute your code:
solo.enterText(myEditText, hello);  // your code

you can write the follow snapcode:
ArrayList<View> views = solo.getViews();
for (View view : views) {
    // check if your view is on the views arraylist, use a break point o whatever
}

Maybe when you try to modify your view, it is not attached on layout or maybe it is not editable.


text:
Q: Override order of resource bundles How can I override the order that Java takes when searching for a label in the resource bundles?
Taken from the docs, the default order is this:
ButtonLabel_fr_CA_UNIX
ButtonLabel_fr_CA
ButtonLabel_fr
ButtonLabel_en_US
ButtonLabel_en
ButtonLabel

However I want to override this order by having variants taken first, like this:
ButtonLabel_fr_CA_UNIX
ButtonLabel_en_US_UNIX
ButtonLabel_fr_CA
ButtonLabel_fr
ButtonLabel_en_US
ButtonLabel_en
ButtonLabel

I defined a new class extending ResourceBundle class where you can set the parent bundle but I don't know when this class is being instantiated and what happens when I change the language in the FacesContext.
Is it possible to override the order somehow?

A: I needed to extend class ResourceBundle.Control and override method getCandidateLocales where you can specify the order of used locales.
Instance of this class is then passed to the getBundle method - I called this in the constructor of the class that extends ResourceBundle like this:
final Locale locale = FacesContext.getCurrentInstance().getViewRoot().getLocale();
final CustomControl control = new CustomControl();
setParent(getBundle("MyBundle", locale, control));

This class can be used as <resource-bundle> in faces-config.xml or loaded with <f:loadBundle ...>
<resource-bundle>
    <base-name>com.package.MyBundle</base-name>
    <var>bundle</var>
</resource-bundle>


text:
Q: Customizing "next" and "previous" arrow in Carousel of Twitter Bootstrap I'm new beginner of Twitter Bootstrap. I tried to place a Carousel lightbox at the center of my page. I edited css to do so. However, I found no where to edit the location of "next" and "previous" arrow.
Here's my page.
http://www.nienyiho.com/portfolio

A: Here are some relevant sections from the bootstrap.css file in case you can't find it on exactly 54 and 74
.carousel-control .glyphicon,
.carousel-control .icon-prev,
.carousel-control .icon-next {
  position: absolute;
  top: 50%;
  left: 50%;
  z-index: 5;
  display: inline-block;
  width: 20px;
  height: 20px;
  margin-top: -10px;
  margin-left: -10px;
  font-family: serif;
}

.carousel-control .icon-prev:before {
  content: '\2039';
}

.carousel-control .icon-next:before {
  content: '\203a';
}

A: If you want to edit it using the CSS (I assume you do) then it can be found on lines 54 and 74 of bootstrap-carousel.css


text:
Q: SQL Server 2008: How do you convert an XML variable into tabular data? Say I have this XML variable:
declare @xml xml='< Employee EmployeeId="1" FirstName="John" LastName="Smith" />
< Employee EmployeeId="2" FirstName="Jack" LastName="Brown" />
< Employee EmployeeId="3" FirstName="Albert" LastName="Gordon" />
< Employee EmployeeId="4" FirstName="Kate" LastName="White" />'

And a table with this structure:
EmployeeId (int)
FirstName varchar(50)
LastName varchar(50)

How do you populate it? I'm using SQL Server 2008.

A: INSERT INTO YourTable
SELECT
    tab.col.value('@EmployeeId','int'),
    tab.col.value('@FirstName','varchar(50)'),
    tab.col.value('@LastName','varchar(50)')
FROM @xml.nodes('/Employee') as tab(col)

A:
How do you populate it?

Assuming you mean the table and not the xml.
insert into YourTable (EmployeeID, FirstName, LastName)
select
  e.value('@EmployeeId', 'int'),
  e.value('@FirstName', 'varchar(50)'),
  e.value('@LastName', 'varchar(50)')
from @xml.nodes('Employee') as n(e)

A: you can do it like this way too
DECLARE @xml XML
SET @xml = '<root>
  <row>one</row>
  <row>two</row>
  <row>three</row>
</root>'

CREATE TABLE #Fields(Field varchar(MAX))

INSERT INTO #Fields
SELECT
    x.y.value('text()[1]', 'varchar(5)')
FROM @xml.nodes('root/row') x(y)

SELECT * FROM #Fields
DROP TABLE #Fields


text:
Q: Is indexing an array literal good practice? In my code I have the following simple function:
function selectedWeekDay() {
    return ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][day];
}

Where 'day' is an integer defined elsewhere.
This clearly works, but I actually haven't seen this type of thing done in any other code example I've seen; creating an array literal just to select from an ordered arrangement of data.
My question is, is this good practice? Or would it be better to use a switch statement?

A: As such, this is perfectly fine since your array is really small.
But with larger array it may cost you memory and/or CPU time (depending on the smartness of your Jitter and your garbage collector).
A switch statement is definitely a bad idea (it wouldn't scale for larger collections).
I would do a simple closure to improve your initial code while keeping the array private
var selectedWeekDay = (function() {
    var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
    return function(day) {
        // do some bound checking
       return days[day];
    };
}());


text:
Q: Problem with the social-share-button gem for Rails Wondering if anyone has experience with this social-share-button gem for Rails?
I have installed the gem ok and get the social share buttons to show, but upon clicking (dev environment) nothing happens.
I get the following error in the Chrome console every time I click:
Uncaught ReferenceError: SocialShareButton is not defined at HTMLAnchorElement.onclick (VM7889 62:777) onclick @ VM7889 62:777

It looks like SocialShareButton is defined in the gem in the social-share-button.coffee file I can see on GitHub but don't know where to go from there.

A: The problem was there was confusion around where to put the
#= require social-share-button

As I did not have a app/assets/javascripts/application.coffee file and so the #= did not work in my application.js file.
I changed this to //= require social-share-button in app/assets/javascripts/application.js and it threw a new error:
Uncaught ReferenceError: $ is not defined ...

I assumed this meant I needed jQuery (even though it looked like the gem had been updated to remove the need for jQuery based on their notes), so I installed that and voila! It works.


text:
Q: Discord bot responds to DMs only, not to commands in guilds I'm programming my first bot for discord by javascript and with discord.js v14. My bot simply obeys the command in private chat, it doesn't send a message back if it's through a server. Can someone help me?
My code:
//npm é um gerenciador de pacotes

const { Client, GatewayIntentBits, Partials } = require('discord.js');
const config = require('./config.json');
const { Guilds, GuildMembers, DirectMessages } = GatewayIntentBits;
const { Channel, GuildMember, Message, User, Reaction } = Partials;
const client = new Client({
  intents: [Guilds, GuildMembers, DirectMessages],
  partials: [Channel, GuildMember, Message, User, Reaction],
});

client.on('ready', () => {
  console.log(
    `Bot foi iniciado, com ${client.users.cache.size} usuários, em ${client.channels.cache.size} canais, em      ${client.guilds.cache.size} servidores.`,
  );
  client.user.setActivity(
    `Eu estou em ${client.guilds.cache.size} servidores.`,
  ); //atualiza status do bot
});

client.on('guildCreate', (guild) => {
  console.log(
    `O bot entrou nos servidores: ${guild.cache.name} (id: ${guild.cache.id}). População: ${guild.cache.memberCount} membros.`,
  );
  client.user.setActivity(`Estou em ${client.guilds.cache.size} servidores!`);
}); //toda vez q o bot entra num server, esse comando é executado e atualiza o status do bot

client.on('guildDelete', (guild) => {
  console.log(
    `O bot foi removido do servidor: ${guild.cache.name} (id: ${guild.cache.id}).); client.user.setActivity(Serving ${client.guilds.cache.size} servers!`,
  );
}); //avisa caso o bot seja excluido de um servidor

client.on('messageCreate', async (message) => {
  let prefix = config.prefix; //liga o prefixo do arquivo config para comando

  if (message.author.bot) return; //nao responda outros bots
  if (!message.content.startsWith(config.prefix)) return;
  //if(message.channel.type === "dm") return; //nao responda por DM

  const args = message.content.slice(config.prefix.length).trim().split(/ +/g); //liga o prefix do config para comando
  const comando = args.shift().toLowerCase(); //parametros do comando

  if (comando === 'ping') {
    //define o comando depois do prefixo digitado pelo usuario
    const m = await message.channel.send('Ping?'); //mensagem
    m.edit(
      `:ping_pong: Pong! A latencia é ${
        m.createdTimestamp - message.createdTimestamp
      } ms. A latencia da API é ${Math.round(client.ws.ping)} ms`,
    ); //edita a propria mensagem 'm'
  }
}); //evento de mensagem do bot

client.login(config.token); //liga o bot

I tried to reinstall discord.js, I also installed an older version, but apparently the problem is not in the library because it works, but only in private chat.

A: It's because without the MessageContent intent you only receive the message.content in DMs but not in guilds. It will be an empty string in guilds.
You will need to add MessageContent to your intent array:
const { Guilds, GuildMembers, DirectMessages, MessageContent } =
  GatewayIntentBits;
const { Channel, GuildMember, Message, User, Reaction } = Partials;
const client = new Client({
  intents: [Guilds, GuildMembers, DirectMessages, MessageContent],
  partials: [Channel, GuildMember, Message, User, Reaction],
});


text:
Q: Is it a Bad practice to use same View at several events only by hiding and changing fields? Assume if there is a reset password button where user reset the password, and there is edit account button for a already logged in user, For a fact in my case When I reset password My interface includes few components(TextViews,EditTexts)which is normally not in account settings interface, So is it a good practise if I already make those components in my account settings inteface and set them invisible? And then only when user press Rest those get visible?.
*It would look little messy like that. Or is it good to have seperate interfaces?
*And if I keep seperate interfaces how does it affect to my project fucntioning overall? Does it make slow or Size(MB) gets bigger or what?
*I think good program practice to use less interfaces and re-use is it right ?
The below image is roughly interface design which addresses my question. Circled are common features. I know if I do this I have to control everything through my code through IDs. So any help would be so appreciated.

A: Reuse is a good practice and I'm personally in favor of your approach. But reusing the layout files can also be tricky, considering the cases in which you're loading a rather large layout file and hiding most of it ! In this cases, loading unwanted hierarchy of this layout, poses a strain on performance.

Keep your layout files, as flat as possible. By this I mean that, nested layouts are more time and resource-consuming to render. Designing with the least views possible, is of course a skill and you should work on it.
Also, take advantage of tools like TraceView and ..., to measure the performance of your application, when using different layout files or reusing them.
For greater details on how to analyze and measure your application performance, you can read this article.


text:
Q: Clarification on the proof that the homomorphic image of a Sylow p-subgroup is Sylow p-subgroup. I realize this question has been asked 3 times now on the site, but I cannot understand the first line of the most popular proof:
Homomorphic image of a Sylow p-subgroup is Sylow p-subgroup.
The claim is as follows: Let $\phi: G\to H$ be a homomorphism of groups and let $P\leq G$ be a Sylow $p$-subgroup of $G$. Then $\phi(P)\leq H$ is a Sylow $p$-subgroup of $H$.
The first line of the proof states: $\phi(P)=\frac{PN}{N}$.
How do I understand this part? I would think to define $PN=\{ pn\in G : p\in N , n\in N\}$ but this makes no sense because $\phi(P)\subset H$ as sets.
Any ideas on how to understand the first line appreciated! (so I can  move on to the second line).

A: This is a bit of "abuse of notation".
First of all, $N = \ker \phi$ (you should have stated this, but I got it from the linked post).  This means that $H \cong G/N$ in a natural way (the first isomorphism theorem), so $\phi(P)$, while it is formally a subset of $H$, can be treated as a subset of $G/N$ instead via this isomorphism.  Since $PN/N$ is also a subset of $G/N$, the equality then makes sense.


text:
Q: How can I add an item from a List into a Session in ASP.NET? Right now I've got a CheckBoxList which is dynamically populated with information based on a search from the user. After the user checks items on the list and presses a button, I want to add that item to a list which is saved between postbacks. I (think) I've correctly created a Session and saved a list to it, but I need to know how to then add to that list properly. Still very new to ASP.NET.
List<Book> currentBookSelection;
List<Book> finalBooklist;

protected void Page_Load(object sender, EventArgs e) {
    if (Session["booklist"] == null) {
        finalBooklist = new List<Book>();
        Session.Add("booklist", finalBooklist);
        System.Diagnostics.Debug.Write("FINAL Booklist Session created.");
    } else {
        finalBooklist = Session["booklist"] as List<Book>;
        System.Diagnostics.Debug.Write("FINAL Booklist Session ALREADY created.");
        System.Diagnostics.Debug.Write("Number of books in FINAL: " + finalBooklist.Count());
    }

    currentBookSelection = new List<Book>();
}

This next part is a snippet from the method used to pull information (saved as strings) via a forloop for each item on the checkbox saved as strings - and added to an object of a custom class.
cblResults.Items.Add(bookTitle);
currentBookSelection.Add(new Book(bookTitle, bookAuthor, bookPrice, bookCoverURL, bookISBN, bookNumPages, bookAmazonURL));

Finally, when the user presses the button... If the user checks a box, find the object in currentBookSelection with the same title, and then add that object to the finalBooklist - which should be persistent across refreshes/postbacks.
protected void btnAddSelected_Click(object sender, EventArgs e) {
    foreach (ListItem item in cblResults.Items) {
        if (item.Selected) {
            foreach (Book book in currentBookSelection) {
                if (book.title == item.Text) {
                    finalBooklist.Add(book);
                    System.Diagnostics.Debug.Write(book.title + " added to FinalBooklist");
                }
            }
        }
    }

    System.Diagnostics.Debug.Write("Button click event finished.");
    cblResults.Items.Clear();
}

SOLUTION: I had to save my currentBookSelection into a Session as well - or else when I pressed the button it would simply return back to size 0. Thanks to @Steve and the others for the help!
protected void Page_Load(object sender, EventArgs e) {
    if (Session["finalbooklist"] == null) {
        finalBooklist = new List<Book>();
        Session.Add("finalbooklist", finalBooklist);
        System.Diagnostics.Debug.Write("FINAL Booklist Session created.");
    } else {
        finalBooklist = Session["finalbooklist"] as List<Book>;
        System.Diagnostics.Debug.Write("Number of books in FINAL: " + finalBooklist.Count());
        PrintFinalBookList();
    }

    if (Session["currentbooklist"] == null) {
        currentBookSelection = new List<Book>();
        Session.Add("currentbooklist", currentBookSelection);
        System.Diagnostics.Debug.Write("CURRENT Booklist created");
    } else {
        currentBookSelection = Session["currentbooklist"] as List<Book>;
        System.Diagnostics.Debug.Write("Number of books in CURRENT: " + currentBookSelection.Count());
    }
}


text:
Q: Need help in generating a formula for nextID excel column I have a an excel sheet with the following columns
ID, City, Record no.
I need to generate a column called Next ID based on the record number.
i.e if the city is same I need to populate the Next ID column with the ID of the previous record number.
Is there a way to do this in excel?
Here is the sample data, with the Next Column populated manually for reference:
ID  City    Record no.  **Next ID
121 Paris     3
122 Paris     2          121
123 Paris     1          122
124 New York  2
125 New York  1          124

Please see attached image

I've edit the question as I was not able to add a image in the comments. My data is not sorted so I used the second formula. This works for some cases but doesn't work for others. see the pink colored cells which should have a value but do not.

A: If your data is always sorted use this:
=IF(B2=B1,A1,"")

in D2 and copy/drag down

If not sorted then use this:
=IFERROR(INDEX(A:A,AGGREGATE(15,6,ROW($C$2:$C$6)/(($C$2:$C$6=C2+1)*($B$2:$B$6=B2)),1)),"")


text:
Q: how to write ocr array into word document in two coloumn matlab i want save a scanned image text in to word file
I   = imread('1.jpg');
ocrResults     = ocr(I);
recognizedText = ocrResults.Text;
A  = recognizedText;

OCR text saver in cell array A
now i want print this cell array to word document in two column
With Regards
Sachin


text:
Q: May I add a GetMutableSizePrefixedRoot (or GetSizePrefixedMutableRoot)? We are using flatbuffers with size prefixed buffers and want to mutate a flatbuffer but there is no GetMutableSizePrefixedRoot or GetSizePrefixedMutableRoot.
I could make a PR and add one like that.
template<typename T> T *GetMutableSizePrefixedRoot(void *buf) {
  return GetMutableRoot<T>(reinterpret_cast<uint8_t *>(buf) +
                           sizeof(uoffset_t));
}

I could also change the code generator so that a GetMutableSizePrefixedXXX (e.g. GetMutableSizePrefixedMonster) will be generated .


text:
Q: Spring Boot @ConditionalOnProperty not seeing property dynamically set I have a Spring Boot application and an external library. The application imports the library. There is a @Configuration class in the library which is loaded conditionally based on the value of this property.
I am using Spring Boot 2.2.6
The relevant classes are shown below:
@Configuration
@ConditionalOnProperty(prefix = "custom", name = "enabled", havingValue = "true")
public class LibraryTrueConfiguration {

    // Load the Beans

}

@Configuration
@ConditionalOnProperty(prefix = "custom", name = "enabled", havingValue = "false")
public class LibraryFalseConfiguration {
    // Load the Beans
}

@Configuration
@ComponentScan("com.lo.bu.custom.lib") // top level package of the lib
public class SharedLibConfiguration {

}

Application's main class:
@Import(SharedLibConfiguration .class)
@SpringBootApplication
public class ServiceApp {

    public static void main(final String[] args) {
        SpringApplication.run(ServiceApp.class, args);
    }

}

Dynamically setting properties in Application's below config, these properties set are not being reflected by library for loading relevant configuration.
If my application.yml has custom.enabled=false and I am setting custom.enabled=true here in below code - it's not getting reflected in configuration file library is loading. It is loading file for custom.enabled=false
@Configuration
public class DynamicPropsConfig {

  // Service which fetch dynamic properties from DB
  @Autowired
  DynamicPropsLoader dynamicPropsLoader;
  @Autowired
  CustomProperties customProperties;

  @DependsOn("dynamicPropsLoader")
  @Autowired
  void setDynamicPropertiesInEnvironment(ConfigurableEnvironment environment) {
    System.out.println("[Before]customProperties = " + customProperties);

      environment.getPropertySources().addFirst(new MapPropertySource("custom",
          dynamicPropsLoader.getCustomPropertiesMap()));

    final HashMap<Object, Object> customPropertiesMap = dynamicPropsLoader
        .getCustomPropertiesMap().keySet()
        .stream()
        .collect(HashMap::new, (m, v) -> m.put(v, environment.getProperty(v)), HashMap::putAll);
    System.out.println("[After]customPropertiesMap = " + customPropertiesMap);

  }

}

@Component
public class DynamicCustomPropsClr implements CommandLineRunner {

  @Autowired
  Environment environment;
  @Autowired
  ConfigurableEnvironment configurableEnvironment;
  @Value("${custom.enabled:}")
  String customEnabled;

  @Override
  public void run(String... args) throws Exception {
    System.out.println("environment.getProperty(\"custom.enabled\") = " + environment
        .getProperty("custom.enabled"));
    System.out.println(
        "configurableEnvironment.getProperty(\"custom.enabled\") = " + configurableEnvironment
            .getProperty("custom.enabled"));
    System.out.println("customenabled = " + customenabled);
  }
}

output
------
environment.getProperty("custom.enabled") = true
configurableEnvironment.getProperty("custom.enabled") = true
customEnabled = false

A: This helped me fix the issue. We need to use EnvironmentPostProcessor along with META-INF/spring.factories file mentioned
Load spring boot app properties from database


text:
Q: Wordpress: How to make unique field with ACF and custom post type So I'm working on a custom post type to work together with Advanced custom fields. And I have this little script that is supposed to block duplicate emails from being entered. But the script does not work as I want it to.
The code that u see below is for the custom post type page that I've linked to ACF.
function init_members() {
    $labels = array(
        'name'               => 'Members',
        'singular_name'      => 'Member',
        'menu_name'          => 'Members',
        'name_admin_bar'     => 'Member',
        'add_new'            => 'New member',
        'add_new_item'       => 'New member',
        'new_item'           => 'New member',
        'edit_item'          => 'Edit member',
        'all_items'          => 'All members',
        'search_items'       => 'Search member',
        'not_found'          => 'No members found',
        'not_found_in_trash' => 'No members found in trash'
    );

    $args = array(
        'labels' => $labels,
        'public' => true,
        'exclude_from_search' => true,
        'rewrite' => array('slug' => 'member'),
        'has_archive' => false,
        'supports' => array('title'),
        'show_in_rest' => true,
        'menu_icon' => 'dashicons-groups'

    );
    register_post_type('members', $args);
}
add_action('init', 'init_members');

function add_member_columns ( $columns ) {
    unset($columns['date']);
    return array_merge ( $columns, array (
        'contactperson'   => __ ( 'Contactperson' ),
        'phone_number'   => __ ( 'Phonenumber' ),
        'email'   => __ ( 'Email' ),
    ) );
}
add_filter ('manage_members_posts_columns', 'add_member_columns' );

function fill_member_columns ( $column, $post_id ) {
    switch ( $column ) {
        case 'contactperson':
            echo get_post_meta ( $post_id, 'contactperson', true );
            break;
        case 'phone_number':
            echo get_post_meta ( $post_id, 'phone_number', true );
            break;
        case 'email':
            echo get_post_meta ( $post_id, 'email', true );
            break;
    }
}
add_action ('manage_members_posts_custom_column', 'fill_member_columns', 10, 2 );

So the script I have for trying to filter the use of duplicate emails is as follows.
the source where I got it from is here
add_filter('acf/validate_value/name='.'email', 'acf_unique_value_field', 10, 4);

function acf_unique_value_field($valid, $value, $field, $input) {
    if (!$valid || (!isset($_POST['post_ID']) && !isset($_POST['post_id']))) {
        return $valid;
    }
    if (isset($_POST['post_ID'])) {
        $post_id = intval($_POST['post_ID']);
    } else {
        $post_id = intval($_POST['post_id']);
    }
    if (!$post_id) {
        return $valid;
    }
    $post_type = get_post_type($post_id);
    $field_name = $field['name'];
    $args = array(
        'post_type' => $post_type,
        'post_status' => 'publish, draft, trash',
        'post__not_in' => array($post_id),
        'meta_query' => array(
            array(
                'key' => 'email',
                'value' => $value
            )
        )
    );
    $query = new WP_Query($args);
    if (count($query->posts)){
        return 'This Value is not Unique. Please enter a unique '.$field['label'];
    }
    return true;
}

I probably oversee something pretty obvious. But I'm not able to find what I'm overseeing.

A: I think the problem might be that you aren't querying all existing posts.  If your posts per page default is configured to 5, and the 6th post turns out to have the same mail address as the updated one, your check will not find any matching posts.
Try the following: in acf_unique_value_field(), fix your query like so:
    $args = array(
        'post_type' => $post_type,
        'post_status' => 'publish, draft, trash',
        'post__not_in' => array($post_id),
        'posts_per_page' => -1,
        'meta_query' => array(
            array(
                'key' => 'email',
                'value' => $value
            )
        )
    );
    $query = new WP_Query($args);

'posts_per_page' => -1, will query an unlimited number of posts.
Also, I've seen you're using get_post_meta to retrieve ACF field values. I advise against doing so. Use ACF's get_field instead (and update_field for updating if necessary).


text:
Q: How to create bottom actionsheet with animation view like Facebook IOS I want to create a modal view like Facebook similar like below:

So on the tap of three dots ie more icon , i want to create a modal which will appear on the click of a button and then it shouldbe exited while dragging it down.
I tried the example from the link
But I am not getting the similar behaviour. Please let me know what should I use as I am not using storyboard also.
Thanks!


text:
Q: Add 'Delete my account' link in Customer Navigation Menu Is there a way to place a link (ie called Delete my account next to the Log out link in the Customer Navigation Account Dashboard?
I know there are paid extensions available for that but I'd like to know if it's possible by means of a simple module or via the local.xml?

A: app/design/frontend/{package}/{theme}/layout/local.xml
For the Customer account navigation :
<customer_account>
    <reference name="customer_account_navigation">
        <action method="addLink">
            <name>delete_my_account</name>
            <path>module/controller</path> //path to your controller function for deleting account
            <label>Delete my account</label>
        </action>
    </reference>
</customer_account>

EDIT:
The function in your controller
public function indexAction()
{
    $id = Mage::getSingleton('customer/session')->getCustomer()->getId();
    $customer = Mage::getModel('customer/customer')->load($id);
    $customer->delete();
}


text:
Q: Is there a specific language that the Phantasy Star series used as the basis for the naming of its techniques (spells)? Phantasy Star is a science fantasy jrpg series. After the second game the  "magic" was largely referred to as Techniques.
The naming scheme for Techniques are what really sets them a part from the names commonly given to spells.
I was wondering what language or languages that the names where drawn from.


text:
Q: Facing problem regarding live-server in Atom and NodeJS I want to set a live environment for my web application. I'm using AngularJS and NodeJS (MEAN) and I want both to run live simultaneously. What I did is, I installed live-server through npm and started server by
live-server --`host=192.168.XX.XX --port=9999`

It is showing the following error:

Refused to apply style from 'http://192.168.XX.XX:9999/main.css'
  because its MIME type ('text/html') is not a supported stylesheet MIME
  type, and strict MIME checking is enabled.

Also tried giving the path to my project folder in public by
live-server --`host=192.168.XX.XX --port=9999` --open=public

but facing same error. Please help! Thankyou

A: First I would check to see if you have a typo in the path name in the script tag.  If you have an extra / in the name then you will get this error.
Second, try minifying the css file.

A: It was just the other index.html file i placed outside the public folder.
By the way, one solution worked for me.
Place this link in the head of your HTML.
<base href="/" target="_blank">


text:
Q: How to create reusable layouts and scaffolding templates in Grails 3.x I am fairly new to Grails and I am having a hard time finding information on this. I'm coming from CakePHP where you can easily create a plugin to theme you application and I am trying to replicate this kind of setup in Grails.
I want to create re-usable layouts and scaffolding templates so that all applications I create with Grails will have a common look and feel. I have successfully customized layouts and scaffolding templates in one Grails application and was exploring packaging this into a plugin that could be imported in another project but I have not managed to make this work yet (I did package the plugin and import it in another project but I can't seem to figure out how to access the plugin's layouts and scaffolding templates from the applications).
What is the best way to achieve this? Is it even a good idea to package this as a plugin or should I simply overwrite Grails' default main layout and import my own scaffolding template in every project?
If going the plugin route is a good way to go:

*

*How do I apply my plugin's layouts and scaffolding template from my
application

*I would like to create a "help page" in the plugin that would be
accessible from the main application (in dev only). This page would
enable me to confirm that the layouts are working fine and would
also    provide other developers using this plugin instructions on
how to use    the plugin's templates. How to I access a web page
from the plugin    through my Grails application?

If the plugin is not the way to go, what do you recommend?

A: Yes, a plugin is a great way to go. I'll simply quote the documentation:

When a plugin provides a controller it may also provide default views
  to be rendered. This is an excellent way to modularize your
  application through plugins. Grails' view resolution mechanism will
  first look for the view in the application it is installed into and if
  that fails will attempt to look for the view within the plugin. This
  means that you can override views provided by a plugin by creating
  corresponding GSPs in the application's grails-app/views directory.
For example, consider a controller called BookController that's
  provided by an 'amazon' plugin. If the action being executed is list,
  Grails will first look for a view called
  grails-app/views/book/list.gsp then if that fails it will look for the
  same view relative to the plugin.

Basically, you can access a plugin's views by accessing them as if the views are in the application itself.


text:
Q: sql oracle: Listing Records that has a value repeated more than N number of times within the same month I am suppose to fetch from my records, if there is more than three records with the same Tradename stored within the same month.
An example of the record I have
TradeID      Tradename           PrescDT
------------------------------------------
1109         Panadol             sysdate-1
1123         Opioids             sysdate-3
1125         Doxycycline         sysdate-3
1138         Panadol             sysdate-14
1139         Panadol             sysdate-3
1141         Panadol             sysdate-5
1142         Codeine             sysdate-5
1162         Opioids             sysdate-14
1167         Codeine             sysdate-14
1168         Prednisone          sysdate-14
1170         Codeine             sysdate-21
1172         Codeine             sysdate-22

so it should return me with only this, where I only want the tradename and date
Tradename           PrescDT
------------------------------
Panadol             sysdate-1
Panadol             sysdate-14
Panadol             sysdate-3
Panadol             sysdate-5

I have tried using this but the returns me with all the records repeating at least thrice within the same month and it's not what I'm looking for
SELECT Tradename, PrescDT
FROM (
    SELECT p.*, COUNT(*) OVER (PARTITION BY TRUNC(PrescDT, 'MM')) AS c
    FROM PRESCRIPTION p
    ) p
WHERE c > 3
ORDER BY prescDT ASC;

A: Your query is almost right. You need to include the tradename into the PARTITION BY clause:
SELECT Tradename, PrescDT
FROM (
    SELECT p.*, COUNT(*) OVER (PARTITION BY Tradename, TRUNC(PrescDT, 'MM')) AS c
    FROM PRESCRIPTION p
    ) p
WHERE c > 3
ORDER BY prescDT ASC;


text:
Q: How to compile the multithread code with gcc I have seen the given two makefiles as follows:
all: thread1 thread2 thread3

CFLAGS=-I/usr/include/nptl -D_REENTRANT
LDFLAGS=-L/usr/lib/nptl -lpthread

clean:
    rm -f thread1 thread2 thread3

######################

all: thread1 thread2 thread3

CFLAGS=-D_REENTRANT
LDFLAGS=-lpthread

clean:
    rm -f thread1 thread2 thread3

Without using makefile, what is the correct command line to compile the thread1.c with gcc?

gcc -o thread1
  CFLAGS=-I/usr/include/nptl
  -D_REENTRANT LDFLAGS=-L/usr/lib/nptl -lpthread thread1.c

A: Your question is answered here
gcc: Do I need -D_REENTRANT with pthreads?
Essentially all you need is
gcc thread1.c -o thread1 -pthread
and gcc will handle all the defines for you.

A: If your code don't have external dependencies beyond pthread:
gcc thread1.c -o thread1 -D_REENTRANT -lpthread

Quote:

Defining _REENTRANT causes the compiler to use thread safe (i.e. re-entrant) versions of several functions in the C library.

A: Almost:
gcc -o thread1 -I/usr/include/nptl -D_REENTRANT -L/usr/lib/nptl thread1.c -lpthread

The *FLAGS variables contain the arguments that are passed to the compiler and linker invocartion, respectively. (In your case you're compiling and linking in one go.) Make sure to add libraries after your own object files.

A: Those two makefiles will generate two different sets of command-line arguments.  You could check it yourself just by running make:
$ make -f makefile1
cc -I/usr/include/nptl -D_REENTRANT  -L/usr/lib/nptl -lpthread  thread1.c   -o thread1
$ make -f makefile2
cc -D_REENTRANT  -lpthread  thread1.c   -o thread1

Choose your favourite.


text:
Q: why is adding subdepth package makes lstlisting give Matlab error loading file? If I have a dollar each time I find a conflict between Latex packages I would be a rich man.
I added \usepackage[low-sup]{subdepth} and now I am starting to get errors from matlab-prettifier when reading some Matlab code.
If I remove subdepth the error goes away. If I keep subdepth but remove breqn the error goes away also.  But I'd like to use both these three packages in the same Latex file.
Here is a MWE
\documentclass[11pt]{article}%
\usepackage{matlab-prettifier}
\usepackage{breqn}   %do not use this with tex4ht.  added 4/2/16
\usepackage[low-sup]{subdepth} %added 4/29/16 to lower subscript
\begin{document}
\begin{lstlisting}
J = 8*u1-4
\end{lstlisting}
\end{document}

The error is  pdflatex foo.tex
(/usr/local/texlive/2015/texmf-dist/tex/latex/subdepth/subdepth.sty) (./foo.aux
) (/usr/local/texlive/2015/texmf-dist/tex/latex/base/ts1cmr.fd)
(/usr/local/texlive/2015/texmf-dist/tex/context/base/supp-pdf.mkii
[Loading MPS to PDF converter (version 2006.09.02).]
)
! Missing { inserted.
<to be read again>
                   \global
l.10 J = 8*u1-4

?

I can fix this by changing my Matlab code, from J = 8*u1-4 to J = 8*u1+4 but this will make my Matlab code produce wrong results, and I'd like to keep Matlab code as is, but still load it in Latex.
File list
*File List*
 article.cls    2014/09/29 v1.4h Standard LaTeX document class
  size11.clo    2014/09/29 v1.4h Standard LaTeX file (size option)
matlab-prettifier.sty    2014/06/19 v0.3 A package for prettyprinting Matlab so
urce code
textcomp.sty    2005/09/27 v1.99g Standard LaTeX package
  ts1enc.def    2001/06/05 v3.0e (jk/car/fm) Standard LaTeX file
  xcolor.sty    2007/01/21 v2.11 LaTeX color extensions (UK)
   color.cfg    2007/01/18 v1.5 color configuration of teTeX/TeXLive
  pdftex.def    2011/05/27 v0.06d Graphics/color for pdfTeX
infwarerr.sty    2010/04/08 v1.3 Providing info/warning/error messages (HO)
 ltxcmds.sty    2011/11/09 v1.22 LaTeX kernel commands for general use (HO)
listings.sty    2015/06/04 1.6 (Carsten Heinz)
  keyval.sty    2014/10/28 v1.15 key=value parser (DPC)
 lstmisc.sty    2015/06/04 1.6 (Carsten Heinz)
listings.cfg    2015/06/04 1.6 listings configuration
   breqn.sty    2015/08/11 v0.98d Breaking equations
   expl3.sty    2015/12/20 v6326 L3 programming layer (loader)
expl3-code.tex    2015/12/20 v6326 L3 programming layer
l3pdfmode.def    2015/11/11 v6250 L3 Experimental driver: PDF mode
flexisym.sty    2015/08/11 v0.98d Make math characters macros
  cmbase.sym    2007/12/19 v0.92
mathstyle.sty    2015/08/11 v0.98d Tracking mathstyle implicitly
    calc.sty    2014/10/28 v4.3 Infix arithmetic (KKT,FJ)
subdepth.sty    2007/09/02 v0.1 Unify subscript depths
  ts1cmr.fd    2014/09/29 v2.5h Standard LaTeX font definitions
supp-pdf.mkii
 ***********

TL 2015

A: The subdepth package changes some \fontdimen parameters for the math fonts and it has to do it when those fonts are first loaded. In your case, the first loading happens during initialization of lstlisting and the combination between this step, the needed setup for subdepth and the presence of breqn that changes the meaning of all characters in math, breaks.
If you have a formula before lstlisting, this doesn't happen, because subdepth does its work at font initialization. So adding
\sbox0{$$}

just after \begin{document} will help.
Be careful that you need to load math fonts in advance also when doing font size changes such as \footnotesize (if you have lstlisting in that context, of course).


text:
Q: Next and previous links and ID displayed in the URL for sharing I have a database with a few images already set, I would like to have the url display an ID from each query as the user hits next. The user should be able to share the URL and paste it into their browser, the url should pull that unique ID from the query. The issue i am having is every time i paste a url, I get a random image and not the image that is in the ID. I'm at a loss here and im not sure what to do :( here's the code I have so far.
<?php
if (isset($_GET['id'])) {
    include("PHP/db.php");

    echo $where = $_GET["id"];
    echo $query = "SELECT * FROM images WHERE ID =" . $where;

    $result = mysqli_query($dbc, $query);
    $row = mysqli_fetch_array($result);
    $ID = $row['ID'];
    $title = $row['name'];

    $image =  "";
}

if($_GET['next4']) {
    echo 'HELLO THIS IS THE NEXT IF METHOD';

    include("PHP/db.php");

    $query = "SELECT * FROM images ORDER BY RAND() LIMIT 1";
    $result = mysqli_query($dbc, $query);
    $row = mysqli_fetch_array($result);
    $ID = $row['ID'];
    $title = $row['name'];

    $image =  "";
}

?>

 <?php echo $title ?>

    <?php echo $image ?>

        <a href="?id=<?php echo $ID ?>" name="name4" >Next

            <a href="?id=<?php echo $ID ?>">Previous

A: Try this:
<?php
include("PHP/db.php");

$query2 = "SELECT * FROM images ORDER BY RAND() LIMIT 1";
$result2 = mysqli_query($dbc, $query2);
$rand_row = mysqli_fetch_array($result2);
$rand_id = $rand_row ['ID'];

if (!isset($_GET['id'])) {
    $_GET['id'] = $rand_id;
}

if (isset($_GET['id'])) {
    echo $where = $_GET["id"];
    echo $query = "SELECT * FROM images WHERE ID =" . $where;

    $result = mysqli_query($dbc, $query);
    $row = mysqli_fetch_array($result);
    $ID = $row['ID'];
    $title = $row['name'];
    $image = "";
}
?>

 <?php echo $title ?>

    <?php echo $image ?>

            <a href="?id=<?php echo $rand_id; ?>" name="name4" >Next

            Previous

I changed:
-link to next is now id=rand
-changed your code to give me a "rand ID" and its already defined on the href of the page you load

A: It will go inside condition (next == true).
Make sure that your variables are initialized before use.


text:
Q: RadioButtonList inside gridview - Server side code too slow, can I do it on the client? I've got a radio button list inside a grid view like so:
<asp:GridView ID="gvLineItems" runat="server">
<asp:TemplateField>
      <asp:RadioButtonList ToolTip="Please provide an answer to the method." AutoPostBack="true" RepeatDirection="Horizontal" ID="rbAnswer" runat="server" SelectedValue='<%# DataBinder.Eval(Container, "DataItem.AnswerID")%>' OnSelectedIndexChanged="rbAnswer_SelectedIndexChanged">
                                    <asp:ListItem Text="Yes" Value="Yes" style="color:green;"></asp:ListItem>
                                    <asp:ListItem Text="No" Value="No" style="color:red;"></asp:ListItem>
                                    <asp:ListItem Text="N/A" Value="N/A" style="color:gray;"></asp:ListItem>
                                    <asp:ListItem Value="" Text="" style="display: none" />
                                </asp:RadioButtonList>
</asp:TemplateField>
</asp:GridView>

Currently when you change the selection of the radio button it calls rbAnswer_SelectedIndexChanged() in code behind...
The code behind this (and I will shorten it), is something to the effect of:
 protected void rbAnswer_SelectedIndexChanged(object sender, EventArgs e)
        {
           GridViewRow gr = (GridViewRow)((DataControlFieldCell)((RadioButtonList)sender).Parent).Parent;
            RadioButtonList rbl = (RadioButtonList)gr.FindControl("rbAnswer");

            //since the answer changed set some hidden fields as being changed...
            HtmlInputHidden hiddenFieldAnswered = (HtmlInputHidden)gr.FindControl("hdnAnswered");
            hiddenFieldAnswered.Value = "1";
            HtmlInputHidden hiddenField = (HtmlInputHidden)gr.FindControl("hdnIsChanged");
            hiddenField.Value = "1";

            Panel p;
            p = (Panel)gr.FindControl("pnlAnswer");

            switch (rbl.SelectedItem.Text)
            {
                case "No":
                    gr.Cells[0].BackColor = System.Drawing.Color.Red;
                    p.Visible = true;
                    break;
                case "Yes":
                    gr.Cells[0].BackColor = System.Drawing.Color.Green;
                    p.Visible = false;
                    break;
                case "N/A":
                    gr.Cells[0].BackColor = System.Drawing.Color.Gray;
                    p.Visible = false;
                    break;
                default:
                    gr.Cells[0].BackColor = System.Drawing.Color.Transparent;
                    p.Visible = false;
                    break;
            }
        }

Basically if you select an answer it changes the color of a cell in the gridview and it either hides or unhides a panel.  Doing this as back end code causes a big delay in the application.  Can I do this in jquery?  If so how do I access the radiobuttonlist, the answer, the panel, and a way to change the color of the first cell (gr.cells[0].backcolor) in jquery?
If I do this all on the client side it may increase the usability for the end users, they are complaining right now it is too slow.

A: You can try this. attach click event on radio buttons. I dint test this function, but might it will help you. use jquery file version 1.7 or later
In MarkUp File : Provide a RowStyle-CssClass attribute in GridView  like
<asp:GridView ID="gvLineItems" runat="server" RowStyle-CssClass="row">

this will help you to find the parent row.
$(function(){

     var gvLineItemsRadioObjs = $('[id$=gvLineItems] input[type=radio]');
     gvLineItemsRadioObjs.on('click', function(){

         var $this = $(this);

         //var parentRow =  $this.parents('tr'); // find the parent row.
         var parentRow =  $this.parents('tr.row'); // find the parent row.

         var firstCell = parentRow.find('td:eq(0)'); //find the first cell

         var p =parentRow .find('[id$=pnlAnswer]'); // find the panel

         switch($this.val()) //check the value
         {
            case 'No':
               firstCell.css('background-color', 'red');
               p.show();
               break;
            case 'Yes':
               firstCell.css('background-color', 'green');
               p.hide();
               break;
            case 'N/A':
               firstCell.css('background-color', '');
               p.hide();
               break;
            default:
               firstCell.css('background-color', 'red');
               p.show();
               break;
         }

    });
});

A: Doing a postback whenever a user click a radio button is frustrating to users.
You can do something like this in jQuery
$("#tableName").click(function (e) {
if(e.target.nodeName == "INPUT") {
    var radio = $(e.target);
    // Change to whatever element you want to change color
    var chgColor = radio.parent().find(":eq(0)");
    var pnlAnswer = $("#tableName #pnlAnswer");

    switch(radio.val()) {
        case "NO":
            tr.css("background-color": "#FF0000");
            pnlAnswer.show();
            break;
        case "YES":
            tr.css("background-color": "#00FF00");
            pnlAnswer.hide();
            break;
        // ...
    }
}

});
You need to examine the html code that your page generates then figure out how you can manipulate it using jQuery.


text:
Q: Fetching google's answers, and displaying them? I'm starting a personal assistant project. I've noticed that if you type something like "How old is Obama" on Google, the first hit is a little thing that says "51 years (August 4, 1961)". This works for a lot of things, like, if you type "Who is Romney's wife" it returns "Ann Romney (m. 1969)". This is incredibly useful. How can I fetch this data and retrieve it?
Also, if nothing pops up, like saying "How much money is google worth", then scan each of the hits one by one and determines it. (I can do the determination part, I just need to know the scanning).
Can this be done using urllib2?

A: Have you considered wolframalpha ?
Its more helpful in doing dynamic computations based on a vast collection of built-in data, algorithms, and methods.
Also, Here is an example:
How old is Obama


text:
Q: Claims authorization for specific resources I am writing an example file storage system (example just for stackoverflow).
My current domain models look as such:
public class User
{
    public int ID { get; set; }
    public string LoginIdentifier { get; set; }
    public string Password { get; set; }
}

public class File
{
    public int ID { get; set; }
    public int UserID { get; set; }
    public string FileName { get; set; }
    public byte[] Data { get; set; }
}

The code I am writing to create the IPrincipal:
private static IPrincipal CreatePrincipal(User user)
{
    Debug.Assert(user != null);

    var identity = new GenericIdentity(user.LoginIdentifier, "Basic");

    // TODO: add claims
            identity.AddClaim(new Claim("Files", "Add"));

    return new GenericPrincipal(identity, new[] { "User" });
}

In my system, a user can add files, they can also retrieve, delete, and update them, however, the caveat to that is a user can only retrieve and modify their own files (where File.UserID should match the identity of the logged in user).
My Files controller looks as follows.
[Authorize]
public class FilesController : ApiController
{
    private readonly FileRepository _fileRepository = new FileRepository();

    public void Post(File file)
    {
        // not sure what to do here (...pseudo code...)
        if (!CheckClaim("Files", "Add"))
        {
            throw new HttpError(HttpStatusCode.Forbidden);
        }

        // ... add the file
        file.UserID = CurrentPrincipal.UserID; // more pseudo code...

        _fileRepository.Add(file);
    }

    public File Get(int id)
    {
        var file = _fileRepository.Get(id);

        // not sure what to do here (...pseudo code...)
        if (!CheckClaim("UserID", file.UserID))
        {
            throw new HttpError(HttpStatusCode.Forbidden);
        }

        return file;
    }
}

Maybe using Claims isn't the right tool for the job, but hopefully this illustrates the problem.
How should I wire up my controllers to ensure the currently logged in user has access to do specific actions and more specifically, certain resources?

A: I am not sure if claims are the right approach for what you are doing. What you really want to represent are permissions. A claim typically represent an identity attribute such as user name, email or roles it belong to, but not permissions. You could represent permissions with claims, but you might need tons of it depending on how big your application is. A typical approach is to map a role to a set of permissions (in your case, add files would be a permission). You can also create a custom Authorization filter deriving from the AuthorizeAttribute to check if the current principal has the right permissions to execute the action. That filter might receive the permissions required to execute the action as arguments.

A: Pablo is right - claims describe identity. You use that identity to come to an authorization decision though. There is a separate abstraction for that called ClaimsAuthorizationManager.
Have a look here:
http://leastprivilege.com/2012/10/26/using-claims-based-authorization-in-mvc-and-web-api/


text:
Q: Computing R^2 given cov matrix and R^2 from regression on another parameter Consider the linear regression model with design matrix
$X = [x_1 \mid x_2 \mid \cdots\mid x_p] \in\mathbb R^{n\times p}$. Assume that $x^T_j 1_n = 0$, for $j = 1, \ldots , p$, that is, the columns of $X$ are centered. (Here, and elsewhere $1_n \in\mathbb R^n$ is the vector of all-ones of length $n$). Note that the model does not include an
intercept.
Assume that:
$$
\frac{1}{n}X^TX=\begin{bmatrix}I_{p-1} & z\\z & a^2\end{bmatrix}, z\in R^{p-1}, a^2\in R
$$
where $a^2$ and $z$ are given quantities. Assume that $a^2=10\|z\|^2$.
Let R$^2_j$ be the $R^2$ obtained when regressing x$_j$ onto the rest of covariates $\{x_1, \ldots , x_{j−1}, x_{j+1}, \ldots , x_p\}.$
Find R$^2_p$, that is, the coefficient of determination resulting from regressing $x_p$ onto $\{x_1, \ldots , x_{p−1}\}.$
I'm not really sure how to convert from one $\mathbb R^2$ to another $\mathbb R^2$. Hopefully someone can point me in the right direction or towards a formula I can use, as I can't seem to find much helpful information.

A: Steps:
1: Reshape $X$ matrix: $X_{-p} = (x_1,\dots,x_{p-1})$ and $Y=(x_p)$.
2: Find total sum of square of $Y$.
3: Find $\hat\beta = (X_{-p}'X_{-p})^{-1}X_{-p}'Y$
4: Find model SS, which is $\hat Y' \hat Y$ given $\bar Y = 0 $
5: The ratio of model SS to total SS is the $R^2$ that you need.


text:
Q: Произвольно меняется код php Ребят, всем привет. Есть сайт, стоит на хостинге reg.ru. В исходниках сайт содержит следующий код:
var countvisits = <?php echo $_COOKIE['countvisits'];?>;

Но через какое-то время этот код меняется на:
var countvisits = {!~comment2~!};

Что это может быть? Как это изменить?


text:
Q: Cannot find solution to the problem in prepared statement(procedural php) <?php

    if(isset($_POST['register-button']))
    {
    include 'dbh.inc.php';
    error_reporting(0);
    $uname = $_POST['username'];
    $name = $_POST['name'];
    $email = $_POST['email'];
    $pwd = $_POST['pass'];
    $rpwd = $_POST['repass'];
    $city = $_POST['city'];
    $age = $_POST['age'];
    $gender = $_POST['gender'];
    $courses = implode(',',$_POST['lang']);

    if(empty($uname) || empty($name) || empty($email) || empty($pwd) ||  empty($rpwd) || empty($city) || empty($age) || empty($gender) || empty($courses)){
        header("Location: ../register.php?error=emptyfields&name=".$name."&email=".$email."&city=".$city."&age=".$age);
        exit();
    }
    elseif(!filter_var($email, FILTER_VALIDATE_EMAIL) && !preg_match("/^[a-zA-Z0-9]*$/", $uname){
        header("Location: ../register.php?error=invaliduname&email");
        exit();
    }
    elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)){
        header("Location: ../register.php?error=invalidemail&username=".$uname."name=".$name."&city=".$city."&age=".$age);
        exit();
    }
    elseif(!preg_match("/^[a-zA-Z0-9]*$/", $username)){
        header("Location: ../register.php?error=invalidusername&name=".$name."email=".$email."&city=".$city."&age=".$age);
        exit();
    }
    elseif($pwd!=$rpwd){
        header("Location: ../register.php?error=passwordcheck&username=".$uname."name=".$name."&email=".$email."&city=".$city."&age=".$age);
        exit();
    }
    else{
        $sql1 = "select * from users where uname=?";
        $sql2 = "select * from users where email=?";

        $stmt1 = mysqli_stmt_init($conn);
        $stmt2 = mysqli_stmt_init($conn);

        if(!mysqli_stmt_prepare($stmt1,$sql1) && !mysqli_stmt_prepare($stmt2,$sql2)){
            header("Location: ../register.php?error=sqlerror");
            exit();
        }
        else{
            mysqli_stmt_bind_param($stmt1,"s",$uname);
            mysqli_stmt_bind_param($stmt2,"s",$email);

            mysqli_stmt_execute($stmt1);
            mysqli_stmt_execute($stmt2);

            mysqli_stmt_store_result($stmt1);
            mysqli_stmt_store_result($stmt2);

            $resultcheck1=mysqli_stmt_num_rows($stmt1);
            $resultcheck2=mysqli_stmt_num_rows($stmt2);

            if($resultcheck2>0){
                header("Location: ../register.php?error=registeredemail");
                exit();
            }
            elseif($resultcheck1>0){
                header("Location: ../register.php?error=usernametaken");
                exit();
            }
            else{
                $sql="insert into users values(?,?,?,?,?,?,?,?)";
                $stmt=mysqli_stmt_init($conn);
                if(!mysqli_stmt_prepare($stmt,$sql)){
                    header("Location: ../register.php?error=sqlerror");
                    exit();
                }
                else{
                    $hpass = password_hash($pwd, PASSWORD_DEFAULT);
                    mysqli_bind_param($stmt,"ssssssss",$uname,$name,$email,$hpass,$city,$age,$gender,$courses);
                    mysqli_stmt_execute($stmt);

                    session_start();
                    $_SESSION['uid']=$uname;

                    header("Location: ../index.php");
                    exit();
                }
            }
        }
    }
    }
    else
    {
    header("Location: ../index.php");
    exit();
    }
?>

Warning: mysqli_stmt_bind_param(): invalid object or resource mysqli_stmt in C:\xampp\htdocs\php\responsive_website\includes\signup.inc.php on line 50
Warning: mysqli_stmt_execute(): invalid object or resource mysqli_stmt in C:\xampp\htdocs\php\responsive_website\includes\signup.inc.php on line 53
Warning: mysqli_stmt_store_result(): invalid object or resource mysqli_stmt in C:\xampp\htdocs\php\responsive_website\includes\signup.inc.php on line 56
Warning: mysqli_stmt_num_rows(): invalid object or resource mysqli_stmt in C:\xampp\htdocs\php\responsive_website\includes\signup.inc.php on line 59
Fatal error: Uncaught Error: Call to undefined function mysqli_bind_param() in C:\xampp\htdocs\php\responsive_website\includes\signup.inc.php:78 Stack trace: #0 {main} thrown in C:\xampp\htdocs\php\responsive_website\includes\signup.inc.php on line 78

A: Your problem is that you are only exiting if both prepares (of $stmt1 and $stmt2) fail, where you should exit if either of them fail. Change this line:
if(!mysqli_stmt_prepare($stmt1,$sql1) && !mysqli_stmt_prepare($stmt2,$sql2)){

to
if(!mysqli_stmt_prepare($stmt1,$sql1) || !mysqli_stmt_prepare($stmt2,$sql2)){

You should also use mysqli_error() to find out why the prepare failed, perhaps adding that to the location you redirect to e.g.
header("Location: ../register.php?error=sqlerror&msg=" . urlencode(mysqli_error($conn)));

Your other problem is that you have a typo, mysqli_bind_param should be mysqli_stmt_bind_param on line 78.


text:
Q: Why does a lot of Angular source code avoid enclosing the contents of a file in a closure? I am assuming because it is a standard practice in the Angular world that, any sort of module system has to be wrapped as an Angular module and angular should be the only global variable used which will avoid any conflict.

A: It is not only standard practice in Angular, but in all software: Try to minimize global objects / variables / functions as much as possible. For reasons, see Why is Global State so Evil?
But this could be avoided in other ways as Angular, one could e.g. append your object to the ng object, but this is something like a "global state in Angular".
The main feature is the possibility of dependency injection: You inject modules into angular with a predefined interface, one implementation of the I in SOLID.
That enables you to mock objects for unit testing, and enables test driven-development.


text:
Q: Magento Related Product don't show up I am trying to get the related products block to show up on my product detail page.
I have the folling code in the respective .phtml file
<?php

<?php echo "Related product block"?>
<?php if($this->getItems()->getSize()): ?>

    <?php echo $this->__('Related Products') ?>

<?php echo $this->__('Check items to add to the cart or')  ?> <?php echo $this->__('select all') ?>

    <?php foreach($this->getItems() as $_item): ?>

            <?php if(!$_item->isComposite() && $_item->isSaleable()): ?>
                <?php if (!$_item->getRequiredOptions()): ?>
                    <input type="checkbox" class="checkbox related-checkbox" id="related-checkbox<?php echo $_item->getId() ?>" name="related_products[]" value="<?php echo $_item->getId() ?>" />
                <?php endif; ?>
            <?php endif; ?>

                <a href="<?php echo $_item->getProductUrl() ?>" title="<?php echo     $this->htmlEscape($_item->getName()) ?>" class="product-image"><img src="<?php echo $this->helper('catalog/image')->init($_item, 'thumbnail')->resize(50) ?>" width="50" height="50" alt="<?php echo $this->htmlEscape($_item->getName()) ?>" />

<a href="<?php echo $_item->getProductUrl() ?>"><?php echo $this->htmlEscape($_item->getName()) ?>

                    <?php echo $this->getPriceHtml($_item, true, '-related') ?>
                    <?php if ($this->helper('wishlist')->isAllow()) : ?>
                        <a href="<?php echo $this->getAddToWishlistUrl($_item) ?>" class="link-wishlist"><?php echo $this->__('Add to Wishlist') ?>
                    <?php endif; ?>

    <?php endforeach ?>

The echo above the code shows up on my page. Which of course proves that i implemented the block correctly.
Just everything in the if-statement doesn't show.
I spend some time looking for solutions and i tried rebuilding the indexes and my related product is visible on the frontend.
Anyone know how i can fix this?

A: Magento will always return a low number or 0 for the condition:
$this->getItems()->getSize()

if some/all of the related products are in the user's cart, and consequently items will appear as though they are missing.
To prevent this behaviour, duplicate the core Magento 'Related' class:
/app/code/core/Mage/Catalog/Block/Product/List/Related.php

to local:
/app/code/local/Mage/Catalog/Block/Product/List/Related.php

Then comment out the following lines in the if statement:
if (Mage::helper('catalog')->isModuleEnabled('Mage_Checkout')) {
    //mod - show all related products, even if they have been added to the cart
    //Mage::getResourceSingleton('checkout/cart')->addExcludeProductFilter($this->_itemCollection,
    //    Mage::getSingleton('checkout/session')->getQuoteId()
    //);
    $this->_addProductAttributesAndPrices($this->_itemCollection);
}

A: On your 4 line:
<?php if($this->getItems()->getSize() > 0 ? true : false) ?>

Try it.

A: At the top of your code type
var_dump($this->getItems()->getSize()) // does this print NUll, False or > 0

If the code above print NULL or false or less than 1, then do
print_r($this->getItems());

If none of the above print the information you expected then check your block getItems() method
Also where is the closing IF for if($this->getItems()->getSize()):


text:
Q: Python scrapy_selenium SeleniumMiddleware returns Timeout error from renderer I'm using scrapy to run tests using Selenium Webdriver. Most of the time script works fine, but sometimes it returns a Timeout error when initializing SeleniumMiddleware.
Below is my custom download middleware which inherits from SeleniumMiddleware.
class CustomDownloadMiddleware(SeleniumMiddleware):
def __init__(self, *args, **kwargs):

    try:
        super().__init__(*args, **kwargs) # This is where Timeout exception happens
    except Exception as e:
        print("-- Unable initialize Selenium Middleware ---")
        print(e) # This is where it prints the exception message

def process_request(self, request, spider):
    """Process a request using the selenium driver if applicable"""
    ...

Below is the error message I'm receiving.
Message: session not created
source-app-1  | from timeout: Timed out receiving message from renderer: 600.000
source-app-1  |   (Session info: headless chrome=102.0.5005.182)

I'm using Python with scrapy, scrapy_selenium libraries and I use Chrome webdriver.
I see this failure at a rate of about 1 in 10.
FYI... There is a similar post related to this issue but there is no clear answer to what's causing it or how to fix it. (I've tried all posible solutions mentioned in that post)
Selenium Timed out receiving message from renderer
UPDATE
I dive deeper and the Timeout exception is happening when the code initiates the webdriver.Chrome() class, from python's selenium packages.


text:
Q: How to write a new key to every existing UID with Firebase Functions I am trying to write a new key to every existing UID when a new notification sent.
The code works like this; When a new message is written to realtime database a new notification is sent to every device.
So far it works in my code.
But I want to write to the existing UID's, a new entry for notification count badge in my android app to show unread count.
EDIT: Problem is solved. See next code block.
Here is my code:
import * as functions from 'firebase-functions';

const admin = require("firebase-admin");
admin.initializeApp();

/** NOTIFICATIONS */

exports.sendNotification = functions.database.ref('/notifications/{pushId}')
    .onCreate((snapshot, context) => {

        const notification = snapshot.val();
        const title = notification.title;

        const topic = 'notifications';

        const message = {
            data: {
                title: notification.title,
                body: notification.message,
                link: notification.link,
            },
            topic: topic
        };

        // Send a message to devices subscribed to the provided topic.
        admin.messaging().send(message)
            .then((response: String) => {
                // Response is a message ID string.
                console.log('Successfully sent message: ', response);
                writeBadge()

            })
            .catch((error: String) => {
                console.log('Error sending message: ', error);
            });

        return null;
    });

    // The problem is in this function

function writeBadge() {

    return admin.database().ref('/users').once('value').then(function (snapshot) {

        snapshot.forEach((userSnapshot => {
            const uid = userSnapshot.key;

            const myRef = admin.database().ref("/users/" + uid + "/badge").push();
            const key = myRef.key;
            userSnapshot.child("badge/" + key).set({
                key: true
            });

            console.log('Pushed UID: ' + uid);

        }));

    });
}

This is the answer I was looking. This works for me.
function writeBadge() {

    return admin.database().ref('/users').once('value').then(function (snapshot) {

        snapshot.forEach((userSnapshot => {
            const uid = userSnapshot.key;

            const myRef = admin.database().ref("/users/" + uid + "/badge").push();

            myRef.set({
                key: true
            });

            console.log('Pushed UID: ' + uid);

        }));

    });
}


text:
Q: Cross table highlighting variable combinations I'd like to make a data frame containing a table of proportions, and in this table I'd like to highlight certain combinations of the two variables. I'd like to highlight in yellow the cells with values for:

blue and low
  high and green
  red and high

Current code:
df <- data.frame(op=c("high","medium","low","high","high","medium","low","high","medium"),fr=c("blue","red","green","green","red","blue","red","green","red"))
mytable <- table(df$op,df$fr)
df2 <- prop.table(mytable)


text:
Q: Can't load image from MySQL to React.js using Node.js So I'm trying to get data from my database to display products in React.js using Node.js.
The problem is that my image from my MySQL database doesn`t load up.
[Here is my database][1]
Code from the Nodejs server:
const cors = require('cors');
const bodyParser = require('body-parser');

const { response } = require('express');

const bcrypt = require('bcrypt');
const saltRounds = 10;

dotenv.config({ path: './.env' });

const app = express();
app.use(express.json());
app.use(
    cors({
        origin: [ 'http://localhost:3001' ],
        methods: [ 'GET', 'POST' ],
        credentials: true
    })
);

app.get('/products', async (req, res) => {
    db.query('SELECT * FROM products', (error, results) => {
        if (error) res.send(error);
        res.send(results);
    });
});

And the data is display on port:3000/products like this
[
  {
    "productID": 1000,
    "productName": "Polyfloral Honey",
    "price": 12.99,
    "description": "Enjoy the goodness of fresh honey all year, with this deeply refreshing nectar.",
    "quantity": 100,
    "image": {
    "type": "Buffer",
    "data": [
    137,
    80,
    78,
    71,
    13,
    10,
    26,
    10,
    0,
    0,....
]

React code:
ReactJs part In App.js:
    useEffect(() => {
        Axios.get('http://localhost:3000/products').then((response) => {
            setProductsList(response.data);
            console.log(response.data);
        });
    }, []);

And I send it to:
    const Ourwork = ({ setProductsList, productsList }) => {

    return (
        <Work exit="exit" variants={pageAnimation} initial="hidden" animate="show">
            {productsList.map((product) => (
                <Product
                    productName={product.productName}
                    description={product.description}
                    price={product.price}
                    image={product.image.data}
                    url={product.url}
                />
            ))}
        </Work>
    );
};

Where I tried to access the image from database:
const Product = ({ productName, url, price, image }) => {

    return (
        <ProductStyle>
            <Link to={url}>
                <SmallCircle onMouseOver={Scale} onMouseLeave={UnScale}>

                </SmallCircle>
            </Link>

{productName}

{price}

        </ProductStyle>
    );
};

The problem is that product.image is undifined.
At first I thought that it is 431 Error, but I updated Node and NPM to latest versions and used --max-http-header-size=16384 so I don't have problems here.
I tried to convert image to base64 but it doesn't work but I still can't read the image source.
I'm stuck here for 3 days and any help would be welcomed!