text:
Q: How to get stringstream to treat uint8_t as a number not a character? I have this code and wondering if it's possible to have stringstream to treat uint8_t as a number not a character?
uint8_t s;
std::stringstream sstream( "255" );
sstream >> s;
std::cout << s << " equals 50/'2' not 255 " << std::endl;

s should be 255 not 50/'2'

A: If you are using std::stringstream in order to convert uint8_t to string, then you can use std::to_string instead. Allowed in c++11 only.
C++11 Feature
#include <stdint.h>
#include <iostream>
uint8_t value = 7;
std::cout << std::to_string(value) << std::endl;
// Output is "7"

A: Cast it to an int:
std::cout << (int)s << " equals 2 not 255 " << std::endl;


text:
Q: Solution for detecting a magnetic field I have an Arduino based circuit that performs a mechanical job and I'd like the circuit to turn on when it detects a magnetic field. I want to use a magnet as a trigger for the circuit. When a magnet is attached to something like say a stick and put near the circuit board I'd like it to detect the magnetic field and turn on.
I have learnt that an operational amplifier can be used for this purpose but need guidance on how to do it as I am a novice in embedded systems & electronics.

A: One way or another, you need some kind of transducer that can make a electrical signal that is a function of magnetic field strength.  No, a opamp can't do this.  A opamp may be useful in tranforming the raw signal from such a transducer into something the microcontroller can read, but by itself a opamp is not a magnetic sensor.
Two possibilities come to mind:
*

*Reed switch.  These are the bare switch parts of a relay, usually enclosed in a small glass envelope.  The right magnetic field causes the switch to close.  This will be the simplest solution if you have a strong enough magnetic field.  This usually means a reasonable permanent magnet can be placed with a half inch or so of the reed switch.

*Hall effect sensor.  The underlying physics of these sensors creates a small electrical signal proportional to the magnetic field in a particular direction.  However, you rarely get bare Hall sensors directly.  Usually they are integrated into a single package with something that either makes a reasonable size voltage proportional to magnetic field strength, or provides a digital output, usually with some hysteresis, to indicate presence or abscence of some level of magnetic field.  Allegro is a supplier that makes a lot of these things with various options.

redpajama_set_name: RedPajamaStackExchange


text:
Q: 500 Internal Server Error - wordpress htaccess today I visite my site web and I get error: 500 Internal Server Error and in my view i get this:
�p��1�U��?���D~"1�$�A0.�Х��X����#�B��v��A�z��Sc�ߊ{3$�͗�{{�B�_�Q�"��`��%��ݽ�q{��)�dӚ����lE��] h�^2 �x�cw7�k�μ ?�l���7n8�U��;j��stlx��wR����RX��[J�ݣ׏����jg�H@�M\�Y�ç���ڽr�� ���fР��q��Uf�?�b��B��z秫

status code:  500 Internal Server Error
my .htaccess
RewriteEngine Off

SetEnv DEFAULT_PHP_VERSION 53

DirectoryIndex index.cgi index.php

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

A: On my local xampp wordpress configuration your .htaccess file is working.
Have you updated your webserver / PHP version the last days or something?
If not maybe follow the steps mentioned here

A: There are many reasons due to which this error occurs, like:

*

*Incorrectly configured

*.htaccess file PHP memory limit

*Plugins issue

Enable a debug log from within WordPress config, it might give a clue to the exact problem.
For this open wp-config.php in the root directory and find

define('WP_DEBUG', false);

Comment it using // at the start, then paste the following:

define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);
define('WP_DEBUG_DISPLAY', false);
@ini_set('display_errors',0);

This will start outputting errors to a file in wp-content folder called error.log
After that you can take the help of this link to fix the internal server error: https://www.navthemes.com/how-to-remove-internal-server-error-in-wordpress/


text:
Q: Is there a way to synchronize entities between 2 databases? I have two databases on different sites with the same rather complex schema.
Is there a way to take single user and his entities and move everything to another database?
I tried JMSSerializer and it's symfony bundle. Every time I have different errors trying to import 'parent' object, I believe that these errors I have because of circular references. Serializing each single object for certain user in 'relations chain' is too complex for export and import.
So I'd like to know if there an intelligent tool for merging two mysql databases, probably with doctrine support or something else...
Thanks in advance.


text:
Q: Android NDK, and placing function outside activity class Mentioned in the article:
http://androidcookbook.com/Recipe.seam?recipeId=77
Is:
"In the Activity class, outside any methods:
static {
    System.loadLibrary("sqrt-demo");
}
// In a method of the Activity class where you need to use it:
double d = SqrtDemo.sqrtC(123456789.0);

"
If a designer wants to place all NDK actions (loading a library,defining a function) outside of the activity, can she/he?
I tried to solve this question by creating a new class and importing it into the activity. I placed the load library in the classes constructor, and I placed the method definition in the other class. The activity appears to load the library but will crash, with the error that It cannot find the function
Edit to add details:
I attempted this again but by placing the loadLibrary function back in the Activity. I get the same crash report:
    java.lang.UnsatisfiedLinkError: Native method not found:

A: It appears I have found the issue, it was an overlook on my part.
You can load the library from the imported class, and you can place the method definition in the the imported class. YOU MUST however modify the function as so:
initial header: JNIEXPORT jobjectArray JNICALL Java_com_stackoverflow_MainAcitivty_helloWorld(){
to JNIEXPORT jobjectArray JNICALL Java_com_stackoverflow_newclass_helloWorld(){


text:
Q: Font rendering issue in IOS I tried to use font BabeNeue which is available at font-squirrel
I have used following code
<input type="submit" name="checkout" value="Checkout" class="checkout">

Following CSS
input#purchase, input.checkout, .btn-border {
color: #D39229;
background: rgba(0, 0, 0, 0);
border: 3px #D39229 solid;
font-size: 18px;
padding-left: 20px;
padding-right: 20px;
border-radius: 0px;
padding: 4px 20px;
line-height: 18px;
box-sizing: border-box;
white-space: nowrap;
vertical-align: middle;
display: inline-block;
cursor: pointer;
align-items: start;
-webkit-font-smoothing: antialiased;
font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-family: 'BebasNeue', 'Trebuchet MS', sans-serif;
font-size: 18px;
}

and imported font from my location
Now font rendered correctly in windows, but it has issue with iPhone and Mac. text is shifting bit up.

Now if I change button font to Arial, It works fine on all browsers and devices.
Demo here

A: I've had trouble's with this font on firefox and chrome (getting the size and line-height right)
I've tinkered with the code a bit and this worked fine for me
(couldn't tell what align-items did though never seen or used it before)
input#purchase, input.checkout, .btn-border {
  padding: 4px 20px;
  font-family: 'BebasNeue', 'Trebuchet MS', sans-serif;
  font-size: 18px;
  line-height: 1;
  display: inline-block;
  box-sizing: border-box;
  border: 3px #D39229 solid;
  border-radius: 0px;
  cursor: pointer;
  color: #D39229;
  background: rgba(0, 0, 0, 0);
  /* I couldn't tell if you needed this or not so I just left it alone*/
  align-items: start;
}


text:
Q: A formula for $\int\limits_0^\infty (\frac{x}{e^x-1})^n dx$ The Stirling numbers of the first kind $\begin{bmatrix} n \\ k \end{bmatrix}$ are defined by
$\sum\limits_{k=0}^n \begin{bmatrix} n \\ k \end{bmatrix}x^k:=\prod\limits_{k=0}^{n-1}(x+k)$ with $n\in\mathbb{N}_0$ .
Which proof exists for
$$\frac{1}{n}\int\limits_0^\infty \left(\frac{x}{e^x-1}\right)^n dx=\sum\limits_{k=1}^n (-1)^{k-1}\begin{bmatrix} n \\ n-k+1 \end{bmatrix}\zeta(k+1)\quad,\quad n\in\mathbb{N}$$
?
I am also looking for literature where a proof is written, so that it isn't necessary to write one down here.

A: Your identity is just a consequence of integration by parts, together with the identity:
$$ \int_{0}^{+\infty}\frac{x^k}{e^x-1}\,dx = k!\cdot\zeta(k+1)\tag{1} $$
that simply follows by expanding $\frac{1}{e^x-1}$ as $e^{-x}+e^{-2x}+e^{-3x}+\ldots$ So the whole point is just to compute
$$ \frac{d^{n-1}}{dx^{n-1}}\frac{1}{(e^x-1)^n} \tag{2}$$
by recalling, for instance, that by stars and bars we have:
$$ \frac{1}{(1-x)^{m+1}}=\sum_{n\geq 0}\binom{m+n}{n}x^n.\tag{3} $$

A: A more general formula holds. Take a look at formula (10) in this paper by Adamchik for $p=n+1$ and $a=n$. The hypergeometric function on the l.h.s. can be written as the integral given just before formula (16). By letting $x=\ln(1/t)$ one can easily obtain your integral.


text:
Q: TreeView children's margin in WPF I'm writing the WPF app that uses TreeView control inside the UserControl. TreeView control has the same width as the UserControl.
The problem is that I need to make the children nodes to have the full with of the TreeView. I can't assign the width by the static expression as well as UserControl that contains TreeView may have variable width.
I thought that the solution can be reached by assigning the TreeView child item the width of the UserControl. But if I do so the TreeView child item will be out of control, as well as there is margin in the children item. For example
Item A
---Item B
Can you tell, how can I get the width of --- ? Or to make ItemB be under the Item A without using static margin metrics?
Thank you

A: You can edit the Style of TreeViewItem and make its Horizontal Alignment as Stretch instead of Left. Also ensure you host your ContentPresenter inside the Grid.
In this case, eventhough the header text seems to be leeser in width, the mouse hover or Selected color will cover the entire width of treeview. I hope that is what you need.


text:
Q: Find a substring in a column value from a list in another Table in PowerBI using power Query Hi I'm trying to match a list of strings which is in a table to a column in another table which are file names. for example

table2.column1

apple

pear

berry

orange

table1.column1
table1.Colum2

The guy with the apple
apple

the boy has an apple
apple

The dog has a berry
berry

the girl went to get an orange
orange

an apple a day
apple

This is what its should look like in the end. in code I would just do this,
let stringName = table1.ColumnName
let siteName = table2.ColumnName
let matchcolumn = []

stringName.foreach((element) => {

 siteName.foreach((site) => {
     if(element.includes(site)){
         matchcolumn.push(site)
     }else{}
 })
})

can anyone tell me how i would do it in the powerbi query editor.

A: In powerquery, create a lookup table with keywords to search for loaded as Table2
Create a table with a column to look up, here Column1
Use code below to find matches from Table2 against Column1 of Table1
let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Changed Type" = Table.TransformColumnTypes(Source,{{"Column1", type text}}),
#"Added Custom" = Table.AddColumn(#"Changed Type", "Custom", each  Text.Combine( List.Select(Table2[keyword], (x) => Text.Contains([Column1], x, Comparer.OrdinalIgnoreCase)), ", "))
in #"Added Custom"


text:
Q: The data in my ArrayList repeats the last entered data of the array. What is the reason for this? When I'm using the ArrayList using an custom adapter for listing the images in a list view the code shows no error. The problem is that while using the code only my last entered data is showimg in the list view.  Why can't the previously entered data be viewed?
My activity class:
public class SocialActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_social);
        String json;
        ImageView babu = (ImageView) findViewById(R.id.babu);
        ListView lvsoc = (ListView) findViewById(R.id.list_social);
        LinearLayout l1 = (LinearLayout) findViewById(R.id.layhead);
        LayoutInflater inflater = null;
        ArrayList<SubjectData> arrayList = new ArrayList<SubjectData>();
        ArrayAdapter<SubjectData> a;
        /*ArrayList<String> allcategory = new ArrayList<>();
        ArrayList<String> allcategory1 = new ArrayList<>();
        ArrayList<String> img = new ArrayList<>();
        ArrayList<String> img1 = new ArrayList<>();*/
        arrayList.add(new SubjectData("JAVA", "https://www.tutorialspoint.com/java/", "https://s18955.pcdn.co/wp-content/uploads/2017/11/Facebook-share-icon.png"));
        arrayList.add(new SubjectData("Python", "https://www.tutorialspoint.com/python/", "https://www.tutorialspoint.com/python/images/python-mini.jpg"));
        /*arrayList.add(new SubjectData("Javascript", "https://www.tutorialspoint.com/javascript/", "https://www.tutorialspoint.com/javascript/images/javascript-mini-logo.jpg"));
        arrayList.add(new SubjectData("Cprogramming", "https://www.tutorialspoint.com/cprogramming/", "https://www.tutorialspoint.com/cprogramming/images/c-mini-logo.jpg"));
        arrayList.add(new SubjectData("Cplusplus", "https://www.tutorialspoint.com/cplusplus/", "https://www.tutorialspoint.com/cplusplus/images/cpp-mini-logo.jpg"));
        arrayList.add(new SubjectData("Android", "https://www.tutorialspoint.com/android/", "https://www.tutorialspoint.com/android/images/android-mini-logo.jpg"));*/

        //SocialAdapter customAdapter = new SocialAdapter(SocialActivity.this, arrayList);
        lvsoc.setAdapter((ListAdapter) arrayList);

        //arrayList.add(new SubjectData("JAVA", "https://www.tutorialspoint.com/java/", "https://www.tutorialspoint.com/java/images/java-mini-logo.jpg"));
        babu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i;
                i = new Intent(SocialActivity.this, MainActivity.class);
                startActivity(i);
            }
        });

    }
    @Override
    public void onBackPressed() {
        Intent i = new Intent(SocialActivity.this, MainActivity.class);
        startActivity(i);
        super.onBackPressed();
    }
}

My adapter class:
import java.util.ArrayList;

public class SocialAdapter implements ListAdapter {
    ArrayList<SubjectData> arrayList;
    Context context;
    public SocialAdapter(Context context, ArrayList<SubjectData> arrayList) {
        this.arrayList=arrayList;
        this.context=context;
    }

    @Override
    public boolean areAllItemsEnabled() {
        return false;
    }

    @Override
    public boolean isEnabled(int position) {
        return true;
    }

    @Override
    public void registerDataSetObserver(DataSetObserver observer) { }

    @Override
    public void unregisterDataSetObserver(DataSetObserver observer) { }

    @Override
    public int getCount() {
        return arrayList.size();
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public boolean hasStableIds() {
        return false;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final SubjectData subjectData=arrayList.get(position);
        if(convertView==null){
            LayoutInflater layoutInflater = LayoutInflater.from(context);
            convertView=layoutInflater.inflate(R.layout.list_row, null);
            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent i = new Intent(Intent.ACTION_VIEW);
                    i.setData(Uri.parse(subjectData.Link));
                    context.startActivity(i);
                    //Toast.makeText(context,subjectData.Link,Toast.LENGTH_LONG).show();
                }
            });
            TextView tittle=convertView.findViewById(R.id.title);
            ImageView imag=convertView.findViewById(R.id.list_image);
            tittle.setText(subjectData.SubjectName);
            Picasso.get()
                    .load(subjectData.Image)
                    .into(imag);

        }
        return convertView;
    }

    @Override
    public int getItemViewType(int position) {
        return position;
    }

    @Override
    public int getViewTypeCount() {
        return arrayList.size();
    }

    @Override
    public boolean isEmpty() {
        return false;
    }
}

My class for holding subject data:
package com.gjinfotech.eschoolsolution.ClassAdapter;

public class SubjectData {
    public static  String SubjectName;
    public static String Link;
    public static String Image;
    public SubjectData(String subjectName, String link, String image) {
        this.SubjectName = subjectName;
        this.Link = link;
        this.Image = image;
    }
}

A: Your SubjectData has all static fields. So every instance of SubjectData has the same information.
Instead:
public class SubjectData {
    public String SubjectName;
    public String Link;
    public String Image;
    public SubjectData(String subjectName, String link, String image) {
        this.SubjectName = subjectName;
        this.Link = link;
        this.Image = image;
    }
}


text:
Q: Bitbucket CRLF issue? Issue:
Bitbucket shows that the entire file has changed even though I dont see any differences. And there are no merge conflicts in these files.
Details:
I created a sprint branch (named "sprintbranch") and the developers created a feature branch(named "featurebranchX") from the sprint branch. I started merging feature branches back to the sprint branch as and when features were implemented. Now there are two scenarios where I face an issue:

*

*Developer creates a pull request to merge featurebranch1 into sprintbranch

*If there are merge conflicts, developer merges sprintbranch into featurebranch1 and creates a pull request to merge featurebranch1 into sprintbranch.

Both times bitbucket shows that the entire file has changed. And there are no merge conflicts.
When this happens, I cannot do a code review since I dont know what specific lines have been modified by the developer. Also I lose history at this point - looking back I wont be able to figure out what was implemented or merged into the sprint branch.
My guess is that the issue is with line endings. Something to do with CRLF. But when I commit my work I do see that the appropriate line endings are being used automatically (either by git or by the tool like SmartGit)
How do I resolve this so it doesnt keep happening?
Update:
I just found out that I can append a query string w=1 at the end of a url of a pull request to ignore cr lf differences.
But these files are still there in the commit and when I do merge it back, it will include those differences right?

A: Even though Bitbucket can ignore whitespace in diffs (using the w=1 query parameter), those changes will still be included in the merge.
But you can configure git to convert all line endings to either LF or CRLF. Your team should first decide which option it will be, and then set the text property in the .gitattributes file accordingly, like so:
* text eol=lf

This Github help page shows more information. (The information is for git in general, not specifically Github.)
You also need the global configuration option git config --global core.autocrlf input (Mac & Linux) or git config --global core.autocrlf true (Windows).
# Make sure you won't lose your work in progress......
$ git add . -u
$ git commit -m "Saving files before refreshing line endings"

# Remove every file from the git index
$ git rm --cached -r .

# Rewrite the git index
$ git reset --hard

# Prepare all changed files for commit
$ git add .
# It is perfectly safe to see a lot of messages here that read
# "warning: CRLF will be replaced by LF in file."

# And commit.
$ git commit -m "Normalize all the line endings"

More information is available in the Github article.


text:
Q: Why does PHP DateTime->add(DateInterval) fails over daylight saving time shift? I'm using php 8. I have a DateTimeImmutable object in timezone "Europe/Zurich"
$start = new DateTimeImmutable('2021-03-28 01:00', new DateTimeZone("Europe/Zurich"));
// Europe/Zurich is in UTC+1 during winter, UTC+2 in summer

Then I add 1, resp. 2 hours using DateInterval
$oneHour = $start->add(new DateInterval('PT1H'));
$twoHour = $start->add(new DateInterval('PT2H'));
echo $oneHour->format('c');
echo $twoHour->format('c');

What i expect:
"2021-03-28T03:00:00+02:00"
"2021-03-28T04:00:00+02:00"

What i get:
"2021-03-28T03:00:00+02:00"
"2021-03-28T03:00:00+02:00" <-- same result!

Is this a php bug? Why does it fail? Is it expected behaviour?


text:
Q: select all post_meta starting with "temp_size" based on post ID in my worpdress database I have rows where post_id is the page's id and meta keys are temp_size45, temp_size99,....
I would like to show all those values from those meta keys that start with "temp_size"
So then it would look like this
temp_size45 value
temp_size99 value
...
....
so it would be something like this SELECT meta_value FROM wp_postmeta WHERE post_id = %d AND meta_key = all that start with temp_size

A: SELECT meta_value
FROM   wp_postmeta
WHERE  post_id = <some post id> AND meta_key LIKE 'temp_size%'


text:
Q: AngularJS dashboard and authentification I'm developing a very complicated dashboard app with AngularJS + Laravel5.2 that handles internal work of an organization. While it's good to load the app while user fills login form I don't want for someone to see internal app logic through angular controllers unless authenticated. Plus I have multiple user roles and I don't want users to load functions that they don't have access to. How can I achieve that?

A: Here's a tutorial for user authentication using Angular and Laravel:
https://scotch.io/tutorials/token-based-authentication-for-angularjs-and-laravel-apps


text:
Q: Sorting with a custom order schema in MySQL I have many rows in a MySQL table with a reference represented by a number between 0 and 10000.
I'd like to sort my rows by this reference in a custom order, like this one :

*

*All the rows with a reference between 2000 and 2999

*Then all the rows with a reference between 4000 and 4999

*Then all the rows with a reference between 3000 and 3999

*Then all the rows with a reference between 1000 and 1999
Is it possible to do something like this with only one MySQL query?

A: You can use conditional ordering, like :
SELECT t.*
FROM mytable t
ORDER BY
    CASE
        WHEN t.num BETWEEN 2000 AND 2999 THEN 1
        WHEN t.num BETWEEN 4000 AND 4999 THEN 2
        WHEN t.num BETWEEN 3000 AND 3999 THEN 3
        WHEN t.num BETWEEN 1000 AND 1999 THEN 4
    END,
    t.num

A: You can use order by with case:
order by
case
  when reference between 2000 and 2999 then 0
  when reference between 4000 and 4999 then 1
  when reference between 3000 and 3999 then 2
  when reference between 1000 and 1999 then 3
  else 4
end

you can have additional ordering with other columns too.

A: You can try below - using define a custom order by CASE WHEN Expression
select * from tablename
order by
case when reference>=2000 and reference<=2999 then 1
     when reference>=4000 and reference<=4999 then 2
     when reference>=3000 and reference<=3999 then 3
     when reference>=1000 and reference<=1999 then 4 end


text:
Q: Is It possible to find out why I was systematically downvoted?
Possible Duplicate:
Serial Downvoting Victim

Seems to me that I was systematically downvoted, is it possible to find out who did it?

A: This seems to be a trend. Wait 24 hours, they should all be reversed if they fit the mass-downvoting profiler.
As for who did it, that is the problem with anonymous voting. It is anonymous.
While you waiting, you and this guy, can go hate the world together :)


text:
Q: strange behavior on contact form I am having a strange problem with this form. I have made it yesterday night and it was working fine, sending all the emails as it should. However, I've run it today and it won't simply work at all. I am always getting the error message. Any clues? Thank you.
 <?php
$name     =   $_POST['name'];
$email    =   $_POST['email'];
$subject  =   $_POST['subject'];
$message  =   $_POST['message'];
$depart = $_POST['departamento'];

$headers  = "From: $email\r\n";
$headers .= "Reply-To: $email\r\n";

   $corpo = "Nova Mensagem\n";
   $corpo .= "De: " . $name . "\n";
   $corpo .= "Email: " . $email . "\n";
   $corpo.=" Para o departamento " . $depart. "\n";
   $corpo .= "Mensagem: " . $message . "\n";
    if ($depart = administrativo)
     {
      $email_to = '';
       }
       elseif ($depart = financeiro)
       {
       $email_to = '';
        }
   elseif ($depart = Suporte)
         {
    $email_to = '';
      }
     else
      {
     $email_to = '';
    }

$status = mail($email_to, $subject, $corpo, $headers);

if($status) {
    echo "<script> window.location.href = ''; </script>";
}
else {
    echo "<script> window.location.href = ''; </script>";
}
?>

A: Instead of = use == for comparison
for example - instead of:
if( $depart = administrativo)

use
if( $depart == "administrativo" )

A: You should enclose strings within quotes. Moreover, == (comparing objects of different types) && === (comparing objects of same types) are used for comparing and = is used for assigning. So, change the code as follows (inside the if statements) :
if ($depart == 'administrativo')
{
    $email_to = '';
}
elseif ($depart == 'financeiro')
{
    $email_to = '';
}
elseif ($depart == 'Suporte')
{
    $email_to = '';
}
else
{
    $email_to = '';
}


text:
Q: Intel integrated graphics 4000 with AMD Radeon HD 6850 I upgraded my computer processor recently to Intel I7 3770K which is a great processor but I was wondering if the Intel HD 4000 could do teamwork with my AMD Radeon HD 6850?
I was also kind of worried if this setup could cause performance loss due the bad things I've heard about using multiple graphics cards.
The big question is:
Can my integrated graphics card do teamwork with my primary graphics card?

A: You can not team up those 2 cards as such. Those two cards wont support Crossfire. And no, there wont be any performance loss. I assume that your OS will let you choose which one to use  for what kind of tasks. I would myself get rid off the Intel one since it's bad.


text:
Q: why a nested element is selected by last-of-type? I have a very simple HTML structure as shown in the following:

a
a1

b

c

d

And document.body.querySelector('div > div:last-of-type') returns
a1
, not
d
.
I thought document.body.querySelector('div > div:last-of-type') should be same to document.body.querySelector('div > div:nth-of-type(3)'), which returns
d
.
So to summarize my questions:

*

*Why does document.body.querySelector('div > div:last-of-type') return
a1
, not
d
? Is it a bug?

*What is the correct way to select
d
?

A: If you want to select from div children of the initial container div, give the div a class or an ID such as .container and then select it as document.body.querySelector('div.container > div:last-of-type');
Your current code is selecting from divs that are the last div child of any other div, you aren't specifying that you want to look at exclusively the container div's children

A: According to the document#querySelector spec

The querySelector() methods on the Document, DocumentFragment, and
  Element interfaces must return the first matching Element node within
  the subtrees of the context object.

What is the 1st matching element?
We can use document#uerySelectorAll with the same selector, and as you can see the 1st result in the array is
a1
.

const result = Array.from(document.body.querySelectorAll('div > div:last-of-type'));

console.log(result);

a
a1

b

c

d

How can you get the
d
?
Create a selector that will match only what you want:

console.log(document.body.querySelector('body > div > div:last-of-type'));

console.log(document.body.querySelector('p + div'));

a
a1

b

c

d

A: So this is the canonical way to get the last child

console.log(document.body.querySelector('div').lastElementChild)

a
a1

b

c

d

A: *

*
Why does document.body.querySelector('div > div:last-of-type') return
a1
, not
d
? Is it a bug?

No, it's not a bug. The reason is twofold:

*

*If a selector matches multiple elements, querySelector() returns only the first matching element.

*The selector is not scoped to the element whose querySelector() method is called.

Since
a1
 is the first element that matches div > div:last-of-type, that is what is returned by your code.

*
What is the correct way to select
d
?

document.querySelector('body > div > div:last-of-type')

No need to overcomplicate matters.


text:
Q: I need help to merge 2 macros I need help to merge 2 macros. Bascially, after "MACRO1" finishes running in File 1 ( macro 1 itself located in file 1), i want excel to run " MACRO 2" in File 2 (macro 2 itself located in file 2) . I tried using the following code:
Windows("2.xls").Activate
Application.Run "2.xls!Macro2"

However, Instead of running in file 2, it runs in file 1 which overwrite all the original data i had in File 1. ( It goes back to 1.xls even i gave the code Windows("2.xls").Activate)
My target:
After excel finished all the updates in file 1 by macro 1, i would like macro 2 to excute the command i put in macro 1 in file 2.  What can i do to tell excel to run in the different file instead of the one file that i wrote the codes on?I need a VBA code that can help me to achiece this. Can anyone help??
Thanks.

A: I might be missing something, but I threw together a sample (using Office 2007) and it seems to work for me.  Here's what I did:
In 1.xlsm I have the following two macros:
Sub Macro1()

    Sheet1.Range("A1").Value = "This is Workbook 1"

End Sub

Sub RunOverwrite()

    Call Application.Run("Macro1")
    Call Application.Run("2.xlsm!Macro2")

End Sub

I have the following macro in a second workbook, called 2.xlsm:
Sub Macro2()

    Sheet1.Range("A1").Value = "This is Workbook 2"

End Sub

When I execute the RunOverwrite sub in the first workbook, it first writes "This is Workbook 1" in cell A1 of the first workbook ("1.xlsm"), and then writes "This is Workbook 2" in cell A1 of the second workbook ("2.xlsm").
Am I missing something from your original inquiry?

A: You could try rewriting your Macro to take in the name of a workbook as an argument.  Then you just call it twice with the workbooks you want it to run on.
When you call it, it would look something like this:
Macro2("C:\Desktop\Workbook1.xls")
Macro2("C:\Desktop\Workbook2.xls")

In order for this to work, your macro would look something like this:
Sub Macro1(TargetBook as Workbook)
    ' Code goes here
End Sub


text:
Q: javascript function does not take effect when trying to change display property I am quite a noob for javascript so sorry for this very basic question:
So i've been looking around but found no answer for this very simple question (I strongly believe its not that hard but couldn't figured out why my code doesn't work).
So i try to make an Image appear after I click on another image. This is similar to what happened when you click on a picture and then the picture enlarged while making the background darker.
My method is having an img inside a div container in which the div container will be on top of the page. The div container will have display:none attribute and i will use javascript to get the div ID and set the display:none to display:block.
However I stumbled upon something I don't know that make my code not work.
Hope anyone can help me find the problem that I wasn't aware of.
This is my Code:
HTML

enter <!DOCTYPE html>

    <?php
    header('Content-Type:text/html;Charset=UTF-8');
    ?>
    <title> Western Drive - Driving Changes </title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

    <link rel="stylesheet" href="stylesheet.css" type=text/css>
    <link rel="stylesheet" href="testing.css" type=text/css>

    <?php include("header.php");?>
    <?php include("menu.php");?>

 Single Speed Reducer

<?php include("selector.php");?>

    <?php include("footer.php");?>

CSS

#preview_image{ position:absolute;
width:53%;
height:70%;
margin:12% 10% 10% 25%;
border:solid 3px red;
z-index:1;}

#preview_image img{
max-height:100%;
max-width:100%;
margin:0% 0% 0% 0%;
}
#preview_image onclick{
max-height:100%;
max-width:100%;
margin:0% 0% 0% 0%;
}

When i try to click img WPDA it supposed to make the change the display:none into display:block , but nothing happened...

A: Take the function definition out of the window.onload function. The scope of the name preview is only that function body, so it can't be referenced from the onclick handler, which is looking for a global function. Also, as pointed out in the other answers you're setting the display style of the wrong element, it should be preview_image.

A: I'm not going to hand-parse your code and work out every potential problem with it, but there is an obvious mistake. That mistake is related to scope. Scope means the visibility of variables and functions. There are two types of scope: global scope and function scope. Variables and functions declared within functions are visible only within the scope of that function.
Let's have a look at where you declare your handler function:
window.onload=function(){
    function preview(arg1)
    {
    document.getElementById("img1").style.display='block';
    document.getElementById("img1").src = arg1+'_Drawing.jpg';
    }
}

Do you see the problem? The function preview only exists within the scope of the anonymous function. Later you invoke it:

Now, however, you are invoking it in the global scope. But preview doesn't exist in the global scope, so nothing will run. You will probably get an error in your browser console. If you're using Chrome, for instance,  you'll see "ReferenceError: preview is not defined".
The simplest solution is simply to take the function declaration out of the onload handler. It doesn't need to be there, because the declaration itself doesn't need to wait until the page is loaded. It only needs to wait if you are looking for elements to bind the function to. Since your binding is actually done in an onclick attribute, nothing needs to wait for the DOM to be ready.
This code will probably (no promises) work:
function preview(arg1)
{
    document.getElementById("img1").style.display='block';
    document.getElementById("img1").src = arg1+'_Drawing.jpg';
}

A: You have to set the div display, not the image
document.getElementById("img1").style.display='block';

Becomes:
document.getElementById("preview_image").style.display='block';

EDIT:
Barmar's answer complete the game ;-)
EDIT #2:
Change all:

To

Then close the image tag:

Then change your function to this:
preview = function(arg1){
    document.getElementById("preview_image").style.display='block';
    document.getElementById("img1").src = arg1+'_Drawing.jpg';
}

And move the onclick from image to div eg:

A: Change this line
document.getElementById("img1").style.display='block';

to
document.getElementById("preview_image").style.display='block';

since preview_image is hidden not it's content.


text:
Q: MyPy Version 0.812 Not Excluding setup.py Files I've been unable run MyPy without it complaining about duplicate modules. I found this existing SO post and tried both to exclude setup.py and to have MyPy not follow imports, but I'm still experiencing the following output:

mypy --follow-imports skip --exclude 'setup' --exclude 'setup.py' --exclude setup --exclude '/setup$'  --exclude '/setup.py$' --exclude '/init.py$' .

test-ghilston-python-cookiecutter/example_package_with_logging/setup.py: error: Duplicate module named 'setup' (also at './test-ghilston-python-cookiecutter/example_package/setup.py')

test-ghilston-python-cookiecutter/example_package_with_logging/setup.py: note: Are you missing an init.py? Alternatively, consider using --exclude to avoid checking one of them.

Found 1 error in 1 file (errors prevented further checking)

I've added quite a few --exclude parameters to showcase attempting to pass in a variety of different ways to represent the file setup.py.
One can read the official documentation describing the exclude flag here, which I believe I am following correctly.
Any help is appreciated, as clearly this is user error on my part.


text:
Q: Perl HTTP request : POST fails while GET succeeds When I try to submit a POST request with Perl, it often ends in a 301 redirect to the homepage. Here is the code :
use LWP::UserAgent;

$ua = LWP::UserAgent->new;

# This does not work
my $url = 'http://www.opensubtitles.org/en/search2';
my $req = HTTP::Request->new(POST => $url);
$req->content('MovieName=the+terminator+(1996)');

# Pass request to the user agent and get a response back
print $req->as_string."\n";;
my $res = $ua->request($req);
if (!$res->is_success) {
  print $res->status_line, "\n";
}
else {
  print "Success in posting search\n";
}

In order to make it work, I have to manually use Firefox, go to the url (!). Then the script works. However, using a GET request works flawlessly :
# This works
my $url = 'http://www.opensubtitles.org/en/search2?MovieName=the+terminator+(1996)';
my $req = HTTP::Request->new(GET => $url);

Why is that ?

A: The site doesn't expect a POST to that URL, so it redirects you to back to the search page.
Firefox will use GET, not POST, if you just put the URL into the address line, that's why it works.


text:
Q: make terminal selection automatically copy to the system clipboard buffer? Is there a way to have terminal applications (gnome-terminal, terminator, etc) automatically move selected text to the CLIPBOARD system buffer, and not just the PRIMARY (i.e. terminal-local) buffer?
I found this which describes the primitives, but not to the extent that I could make the behavior change: primary / clipboard intro...
I've got a specific hosted VM use case where I'm very frequently copying text from a bash or vim session in the linux guest back to the windows host... and after 20 years of linux I'm so used to the buffer "just being there" that I'm trying to replicate that behavior...

A: The primary is not local to the terminal, you can paste it in other X applications by using the middle mouse button.
What you should install is autocutsel:

Autocutsel tracks changes in the server's cutbuffer and CLIPBOARD selection. When the CLIPBOARD is changed, it updates the cutbuffer. When the cutbuffer is changed, it owns the CLIPBOARD selection.

On my Ubuntu 12.04 system I can just install this with apt-get install autocutsel,  your distro might have it as well.

A: Some clipboard managers provide this function. xfce4-clipman is a good example, it will also work not only in Xfce, but on any Desktop Environment. From its help page:

Sync selections: Sync the primary clipboard with the default clipboard in a way that it is possible to paste what gets selected


text:
Q: Xamarin form android load image after 1 second I have a problem with Xamarin Form and the Image on Android.
When I go on the page I see for some moments only the entry, and after about 1 second appear the images.
How can I fix ?
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="YYY.Views.Basic.YYYSetup">

  <Grid Padding="5,0,5,0">
    <Grid>
      <Grid.RowDefinitions>
        <RowDefinition Height="auto"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="auto"/>
      </Grid.RowDefinitions>
      <Grid Grid.Row="0" >
        <Grid.RowDefinitions>
          <RowDefinition/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
          <ColumnDefinition Width="*"/>
          <ColumnDefinition Width="*"/>
          <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        ....
      </Grid>
      <Grid Grid.Row="1">
        <Grid.ColumnDefinitions>
          <ColumnDefinition Width="*"/>
          <ColumnDefinition Width="*"/>
          <ColumnDefinition Width="*"/>
          <ColumnDefinition Width="*"/>
          <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
          <RowDefinition Height="*"/>
          <RowDefinition Height="*"/>
          <RowDefinition Height="auto"/>
          <RowDefinition Height="*"/>
          <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <Image Source="YYY_01.png" Grid.Row="4" Grid.Column="2">
          <Image.GestureRecognizers>
            <TapGestureRecognizer Tapped="ChangeDir" NumberOfTapsRequired="1" />
          </Image.GestureRecognizers>
        </Image>

        <Image Source="BSW_plus.png" Grid.Column="0" Grid.Row="0">
          <Image.GestureRecognizers>
            <TapGestureRecognizer Tapped="S1Plus" NumberOfTapsRequired="1" />
          </Image.GestureRecognizers>
        </Image>

        <Image Source="BSW_minus.png" Grid.Column="0" Grid.Row="3">
          <Image.GestureRecognizers>
            <TapGestureRecognizer Tapped="S1Minus" NumberOfTapsRequired="1" />
          </Image.GestureRecognizers>
        </Image>

        <Image Source="BSW_plus.png" Grid.Column="1" Grid.Row="0">
          <Image.GestureRecognizers>
            <TapGestureRecognizer Tapped="S2Plus" NumberOfTapsRequired="1" />
          </Image.GestureRecognizers>
        </Image>

        <Image Source="BSW_minus.png" Grid.Column="1" Grid.Row="3">
          <Image.GestureRecognizers>
            <TapGestureRecognizer Tapped="S2Minus" NumberOfTapsRequired="1" />
          </Image.GestureRecognizers>
        </Image>

        <Image Source="BSW_plus.png" Grid.Column="2" Grid.Row="0">
          <Image.GestureRecognizers>
            <TapGestureRecognizer Tapped="S3Plus" NumberOfTapsRequired="1" />
          </Image.GestureRecognizers>
        </Image>

        <Image Source="BSW_minus.png" Grid.Column="2" Grid.Row="3">
          <Image.GestureRecognizers>
            <TapGestureRecognizer Tapped="S3Minus" NumberOfTapsRequired="1" />
          </Image.GestureRecognizers>
        </Image>

        <Image Source="BSW_plus.png" Grid.Column="3" Grid.Row="0">
          <Image.GestureRecognizers>
            <TapGestureRecognizer Tapped="MorePYYY" NumberOfTapsRequired="1" />
          </Image.GestureRecognizers>
        </Image>

        <Image Source="BSW_minus.png" Grid.Column="3" Grid.Row="3">
          <Image.GestureRecognizers>
            <TapGestureRecognizer Tapped="LessPYYY" NumberOfTapsRequired="1" />
          </Image.GestureRecognizers>
        </Image>

        <Image Source="BSW_plus.png" Grid.Column="4" Grid.Row="0">
          <Image.GestureRecognizers>
            <TapGestureRecognizer Tapped="MoreCYYY" NumberOfTapsRequired="1" />
          </Image.GestureRecognizers>
        </Image>

        <Image Source="BSW_minus.png" Grid.Column="4" Grid.Row="3">
          <Image.GestureRecognizers>
            <TapGestureRecognizer Tapped="LessCYYY" NumberOfTapsRequired="1" />
          </Image.GestureRecognizers>
        </Image>

        <Image Source="BSW_srv_1.png" Grid.Column="0" Grid.Row="1" Aspect="AspectFit"/>
        <Image Source="BSW_srv_2.png" Grid.Column="1" Grid.Row="1" Aspect="AspectFit"/>
        <Image Source="BSW_srv_3.png" Grid.Column="2" Grid.Row="1" Aspect="AspectFit"/>
        <Image Source="BSW_pYYY.png" Grid.Column="3" Grid.Row="1" Aspect="AspectFit"/>
        <Image Source="BSW_cYYY.png" Grid.Column="4" Grid.Row="1" Aspect="AspectFit"/>
        <Entry Grid.Row="2" Grid.Column="0" IsEnabled="False" Text="{Binding Path=YYYVariation, StringFormat='{}{0:F0}', Mode=OneWay}" TextColor="{Binding Path=YYYColor, Mode=OneWay}" />
        <Entry Grid.Row="2" Grid.Column="1" IsEnabled="False" Text="{Binding Path=YYYVariation, StringFormat='{}{0:F0}', Mode=OneWay}" TextColor="{Binding Path=YYYColor, Mode=OneWay}" />
        <Entry Grid.Row="2" Grid.Column="2" IsEnabled="False" Text="{Binding Path=YYYVariation, StringFormat='{}{0:F0}', Mode=OneWay}" TextColor="{Binding Path=YYYColor, Mode=OneWay}" />
        <Entry Grid.Row="2" Grid.Column="3" IsEnabled="False" Text="{Binding Path=PYYY, StringFormat='{}{0:F0}%', Mode=OneWay}"  TextColor="{Binding Path=YYYColor, Mode=OneWay}"/>
        <Entry Grid.Row="2" Grid.Column="4" IsEnabled="False" Text="{Binding Path=CYYY, StringFormat='{}{0:F0}%', Mode=OneWay}" TextColor="{Binding Path=YYYColor, Mode=OneWay}"/>

      </Grid>

...


text:
Q: Start app as root with pm2 I have a daemon that must be run as root on startup.
I use pm2 to start other apps but can not figure out if it can start an app as root. Can it be done?
If not, what are my options?

A: Wasted about an hour
On AWS EC2 machine, one system was in inconsistent state due to earlier installations, that forced sudo elevations in the application for all commands to OS, like sh, etc.
pm2 was running as root:
ps aux | grep pm2
# root ... PM2 v4.1.2: God Daemon (/root/.pm2)

Now pm2 is running as ubuntu:
ps aux | grep pm2
# ubuntu  ...  PM2 v4.1.2: God Daemon (/home/ubuntu/.pm2)

Below commands worked:
sudo pm2 kill
sudo npm remove pm2 -g

sudo npm i -g pm2@latest
sudo pm2 update
sudo chown -R ubuntu:ubuntu /home/ubuntu/.pm2

Hope that helps

A: I had problems with sudo pm2 start api, but this was since pm2 was already running without sudo privileges, therefor you need to run:
pm2 kill
sudo pm2 start api

This kills the pm2 deamon first, so that it starts in sudo, but then you need sudo for ALL pm2 commands afterwards, like: sudo pm2 ls

A: If you only need your daemon to be run as root in order to access a port number (such as 80 or 443), the pm2 documentation recommends using authbind.  So, if you want the user yourusername to have access to port 80, run:
$ sudo apt-get install authbind
$ sudo touch /etc/authbind/byport/80
$ sudo chown yourusername /etc/authbind/byport/80
$ sudo chmod 755 /etc/authbind/byport/80
$ authbind --deep pm2 update

And then use authbind --deep pm2 instead of pm2.  The documentation suggests setting up an alias.

A: I would recommend:
sudo pm2 start index.js

OR
pm2 start 'http-server' /var/www -p 80
sudo pm2 startup
pm2 save

OR
pm2 start 'which http-server' /var/www -p 80

To start it on your HTTP Port
Also, I always put -i 0 at the end  -  this starts up as many worker processes as you have cores. Check THIS
It is not always necessary to start PM2 as root. If you have PM2 as root and the cli module installed, security is a big risk. This is only required if you're starting your app on a port between 1 and 1024

A: You should start pm2 as a root, (sudo pm2 start app.js), then your app will start as a root

A: First, install pm2 globally.
Then set  root permissions to pm2 using  this  command
sudo chown ubuntu:ubuntu /home/ubuntu/.pm2/rpc.sock /home/ubuntu/.pm2/pub.sock

A: you might consider routing your traffic with iptables, since there is a reason behind this errror
sudo iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 3000


text:
Q: "The creator of this fault did not specify a Reason" Exception I have the following code in WCF service to throw a custom fault based on certain situations.  I am getting a "The creator of this fault did not specify a Reason" exception.  What am I doing wrong?
//source code
if(!DidItPass)
{
    InvalidRoutingCodeFault fault = new InvalidRoutingCodeFault("Invalid Routing Code - No Approval Started");
    throw new FaultException<InvalidRoutingCodeFault>(fault);
}

//operation contract
[OperationContract]
[FaultContract(typeof(InvalidRoutingCodeFault))]
bool MyMethod();

//data contract
[DataContract(Namespace="http://myuri.org/Simple")]
public class InvalidRoutingCodeFault
{
    private string m_ErrorMessage = string.Empty;

    public InvalidRoutingCodeFault(string message)
    {
        this.m_ErrorMessage = message;
    }

    [DataMember]
    public string ErrorMessage
    {
        get { return this.m_ErrorMessage; }
        set { this.m_ErrorMessage = value; }
    }
}

A: serviceDebug includeExceptionDetailInFaults="true"

is NOT the solution
The following code works even with serviceDebug includeExceptionDetailInFaults="false"
// data contract

[DataContract]
public class FormatFault
{
    private string additionalDetails;

    [DataMember]
    public string AdditionalDetails
    {
        get { return additionalDetails; }
        set { additionalDetails = value; }
    }
}

// interface method declaration

    [OperationContract]
    [FaultContract(typeof(FormatFault))]
    void DoWork2();

// service method implementation

    public void DoWork2()
    {
        try
        {
            int i = int.Parse("Abcd");
        }
        catch (FormatException ex)
        {
            FormatFault fault = new FormatFault();
            fault.AdditionalDetails = ex.Message;
            throw new FaultException<FormatFault>(fault);
        }
    }

// client calling code

    private static void InvokeWCF2()
    {
        ServiceClient service = new ServiceClient();

        try
        {
            service.DoWork2();
        }
        catch (FaultException<FormatFault> e)
        {
            // This is a strongly typed try catch instead of the weakly typed where we need to do -- if (e.Code.Name == "Format_Error")
            Console.WriteLine("Handling format exception: " + e.Detail.AdditionalDetails);
        }
    }

There is no need to add fault reason if its not required. Just make sure the FaultContract attribute is correct

A: After some addtional research, the following modified code worked:
if(!DidItPass)
{
    InvalidRoutingCodeFault fault = new InvalidRoutingCodeFault("Invalid Routing Code - No Approval Started");
    throw new FaultException<InvalidRoutingCodeFault>(fault, new FaultReason("Invalid Routing Code - No Approval Started"));
}

A: I solved this problem using a two parameter constructer.
// service method implementation

 throw new FaultException<FormatFault>(fault,new FaultReason(fault.CustomFaultMassage));

CustomFaultMassage is property from data contract.

A: One can also encounter this exception if one does not specify the FaultContract(typeof(className)) attribute for the method

A: If you do not want to be notified of such exceptions go to Debug -> Exceptions and uncheck "User-unhandled" for "Common Language Runtime Exceptions" or for specific exceptions.

A: The short answer is you are doing nothing wrong, just reading the results incorrectly.
On the client side when you catch the error, what is caught is of the type System.ServiceModel.FaultException<InvalidRoutingCodeFault>.
Your InvalidRoutingCodeFault object is actually in the .detail property of the FaultException.  SO....
// client code
private static void InvokeMyMethod()
{
    ServiceClient service = new MyService.ServiceClient();

    try
    {
        service.MyMethod();
    }
    catch (System.ServiceModel.FaultException<InvalidRoutingCodeFault> ex)
    {
        // This will output the "Message" property of the System.ServiceModel.FaultException
        // 'The creator of this fault did not specify a Reason' if not specified when thrown
        Console.WriteLine("faultException Message: " + ex.Message);
        // This will output the ErrorMessage property of your InvalidRoutingCodeFault type
        Console.WriteLine("InvalidRoutingCodeFault Message: " + ex.Detail.ErrorMessage);
    }
}

The Message property of the FaultException is what is displayed on the error page so if it's not populated like in John Egerton's post, you will see the 'The creator of this fault did not specify a Reason' message.  To easily populate it, use the two parameter constructor when throwing the fault in the service as follows, passing your error message from your fault type:
InvalidRoutingCodeFault fault = new InvalidRoutingCodeFault("Invalid Routing Code - No Approval Started");
throw new FaultException<InvalidRoutingCodeFault>(fault, new FaultReason(fault.ErrorMessage));

A: I have code exactly like Rashmi has and I got the "The creator of this fault...."  error.  It was happening when I was debugging in VS2010.  I found this post:
http://sergecalderara.wordpress.com/2008/11/25/systemservicemodelfaultexception1-was-unhandled-by-user-code/
which explained a couple of debugging options that I needed to turn off.  Problem solved.

A: You might try this in the server config (behaviors -> serviceBehaviors -> behavior):
<serviceDebug includeExceptionDetailInFaults="true" />

A: By using strongly typed try catch, I was able get around with the error "The creator of this fault did not specify a Reason".

A: Updating the service reference in the client solved the problem. Same could work for you.


text:
Q: number of zeros of a holomorphic function Determine the number of zeros of the holomorphic function
$ f (z) = e ^ {z + 3} + z ^ 3 + z ^ 2 + z + 1 $
in the unitary disk.
Anyone know how this exercise is solved?

A: Let $f$ be as you defined and $g$ equal $e^{z+3}$ then on the boundary of the unit disk you have $|f-g|<|g|$. Thus by Rouché theorem $f$ has the same number of zeros as $g$, namely none inside the disk.


text:
Q: javascript namespacing in sharepoint 2010 master page I have made an custom master page in a Sharepoint Foundation site, and i would to insert custom javascript using namespacing.
this is my code:
 <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.min.js"></script>
 <script type="text/javascript">
     var CapMossJs = {
         setCurrentMonthInCombo: function () {
             //var objComboMesi = getField('select', 'Mese');
             var datCurrent = new Date();
             var intCurrMonth = datCurrent.getMonth();
            window.alert(intCurrMonth);
        },

         hideUtenteSrcurlTemplatelink: function() {
         }
     }
 </script>
 <script type="text/javascript">
     $().ready(function () {
         CapMossJs.setCurrentMonthInCombo();
     });
 </script>

that i have inserted in the master page after the lines
 id="onetidPageTitleAreaFrameScript"
 if (document.getElementById("onetidPageTitleAreaFrame") != null)   {
   document.getElementById("onetidPageTitleAreaFrame").className="ms-areaseparator";

after line 491 in practice.
In a normal page made with visual studio 2010 this code works, instead in the master page i have an error from jquery that the property or method is not supported from object: could someone explain why ? without namespacing there are no problems.

A: You can't put a script tag inside another script tag, and none of the code that you add should be inside that if statement.

A: The same code without namespacing works without problems, the two lines relative to the "if" are only a reference of the place in code , if you open with SharePoint Designer a custom form it will be clear: in every case my scripts tags are after line 491 , where there is already another script tag.


text:
Q: Python Recursion with Lists code not functioning properly I am attempting to create a recursive algorithm in order to solve the "Knight's Journey" chess-based riddle, where you try to visit each space of a chessboard exactly once with a knight. My code uses recursion to split into each possible next move every time the knight is supposed to move again, but I am experiencing an error where the knight does not move for one turn, then continues on the next turn. Here is my code:
def recursivePlay(board, knightSpot, myMoves):

    if(len(board) == 63):
        print("FOUND IT\n")
        print("the seed is: ")
        print(myMoves+"\n")
        print(board)

    for i in range(8):
        moving = bash(i)
        x = moving.x + knightSpot.x
        y = moving.y + knightSpot.y

        if(not(steppedOn(board,x,y)) and validMove(knightSpot,x,y)):

            board.append(knightSpot)

            knightSpot = Spot(x,y)

            myMoves.append(i)

            recursivePlay(board,knightSpot,myMoves)

def bash(num):
    if(num < 4):
        num += 2
        return Spot(2*((-1)**int(num/2)), (-1)**int(num))
    else:
        num -= 2
        return Spot((-1)**int(num), 2*((-1)**int(num/2)))

def validMove(knightSpot, x, y):
    tempx = knightSpot.x
    tempy = knightSpot.y

    if(tempx == x and tempy == y):
        return False

    if(abs(tempx-x) == 2):
        return (abs(tempy-y) == 1)

    if(abs(tempy-y) == 2):
        return (abs(tempx-x) == 1)

def steppedOn(myList, mySpotX, mySpotY):

    if(mySpotX < 0 or mySpotX > 7 or mySpotY < 0 or mySpotY > 7):
        return True

    check = False

    for i in myList:
        if(i.compare(mySpotX, mySpotY)):
            check = True

    return check

class Spot(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __repr__(self):
        return ("{"+str(self.x)+", "+str(self.y)+"}")

    def compare(self, compx, compy):
        return self.x == compx and self.y == compy

When I run the method recursivePlay, my output is:
    FOUND IT

    the seed is:

    [2, 0, 2, 0, 2, 0, 2, 3, 2, 4, 0, 0, 1, 3, 1, 3, 1, 3, 1, 6, 0, 2, 0, 2, 0, 4,
 2, 0, 3, 1, 1, 3, 1, 3, 2, 2, 0, 2, 5, 0, 2, 0, 2, 0, 5, 3, 1, 3, 1, 7, 2, 0, 2,
 6, 6, 4, 0, 1, 0, 5, 1, 6, 3]

    Spaces visited:

    [{0, 0}, {2, 1}, {0, 2}, {2, 3}, {0, 4}, {2, 5}, {0, 6}, {2, 7}, {4, 6},
{6, 7}, {7, 5}, {5, 6}, {3, 7}, {1, 6}, {3, 5}, {1, 4}, {3, 3}, {1, 2}, {3, 1},
 {1, 0}, {2, 2}, {0, 3}, {2, 4}, {0, 5}, {2, 6}, {0, 7}, {1, 5}, {3, 6}, {3, 6},
 {5, 5}, {3, 4}, {1, 3}, {3, 2}, {1, 1}, {3, 0}, {5, 1}, {7, 2}, {5, 3}, {7, 4},
 {6, 2}, {4, 3}, {6, 4}, {4, 5}, {6, 6}, {6, 6}, {5, 4}, {7, 3}, {5, 2}, {7, 1},
 {5, 0}, {4, 2}, {6, 3}, {4, 4}, {6, 5}, {6, 5}, {5, 2}, {6, 0}, {4, 1}, {2, 0},
 {7, 3}, {6, 1}, {4, 5}, {5, 7}]

As you can see it repeats a spot at row 5 spot 5 of spaces visited and row 6 spot 5 of spaces visited. The bash function should never return 0, i.e. a lack of movement, and the validMove function also contains a conditional to prevent this. Can anyone tell me why this is happening?

A: The primary problem is you're not handling recursion correctly -- you set up temporary state and recur but don't deal with potential failure of the recursion and unwinding the temporary state before trying another possibility.  That's why you accumulate duplicates and quit too soon due to total length.  I've reworked your code but read my note that follows regarding a larger issue:
def recursivePlay(layout, board, knightSpot, moves):

    if len(board) == layout.x * layout.y - 1:
        return True

    for i in range(8):
        newSpot = bash(i)

        newSpot.x += knightSpot.x
        newSpot.y += knightSpot.y

        if not steppedOn(board, newSpot) and validMove(layout, knightSpot, newSpot):

            board.append(knightSpot)
            knightSpot = newSpot
            moves.append(i)

            if recursivePlay(layout, board, knightSpot, moves):
                return True

            knightSpot = board.pop()
            moves.pop()

    return False

def bash(num):
    if num < 4:
        num += 2
        return Spot(2 * (-1)**(num // 2), (-1)**num)
    num -= 2
    return Spot((-1)**num, 2 * (-1)**(num // 2))

def validMove(layout, knightSpot, spot):

    if spot.x < 0 or spot.x >= layout.x or spot.y < 0 or spot.y >= layout.y:
        return False

    if abs(knightSpot.x - spot.x) == 2:
        return abs(knightSpot.y - spot.y) == 1

    if abs(knightSpot.y - spot.y) == 2:
        return abs(knightSpot.x - spot.x) == 1

    return False

def steppedOn(used_spots, spot):

    for used_spot in used_spots:
        if used_spot == spot:
            return True

    return False

class Spot(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __repr__(self):
        return "{" + str(self.x) + ", " + str(self.y) + "}"

    def __eq__(self, other):
        return self.x == other.x and self.y == other.y

myMoves = []
myBoard = []
myLayout = Spot(5, 5)

if recursivePlay(myLayout, myBoard, Spot(0, 0), myMoves):

    print("FOUND IT FOR", myLayout, "\n")
    print("the seed is: ")
    print(myMoves, "\n")
    print(myBoard)

I've added the ability to specify board size.  Your solution is brute force. If you read the Wikipedia article on Knight's Tour, specifically brute-force algorithms, you'll see that you can't expect this code to return a result in short order for an 8 x 8 board.  I've left the code set for a 5 x 5 board, which your algorithm solves quickly, and you can increase that as patience allows and/or you add heuristics.


text:
Q: My iPhone 6s was stolen My iPhone 6s was stolen 4 days ago. I know it was stolen because I saw it on a cctv footage. I already reported to the police. We haven't caught the theft yet and I am here trying to move on from it. I'm really looking forward to find answers to my concerns.
I use my "fingerprint" as an unlock code to my phone but if my phone can't read my finger it shows a 4 digit code. I opened my apple id using my laptop and i found out that my apple id is still signed in to my iphone but its offline and the theft haven't hacked or opened my phone yet. So what I did was change my apple id's name, bday, and password. Next is I opened my iCloud, its too late when i realized that I set the Find My iPhone on my phone. So, I opened find my iPhone but i can't locate it because it was offline. But I set the Alarm sound and Lock mode for my iPhone. I even changed all my accounts and social media passwords thinking that it might protect my accounts from being hacked or used by the theft.
I asked people here and they said that, "there's no place or people here that can hacked iPhone 6s" and "if you have iCloud signed in to your iPhone its impossible for the  theft to hacked your phone." I don't know if this is true or not, but I hope so too. I'm still hoping that I could retrieve my iPhone from the theft.
Is there anything more that I can do to protect my iPhone?
Does the theft really haven't hacked my iPhone yet?
Will the theft be able to make use of my iPhone?
Will the theft be able to format my phone?

A: As long as the phone is on your iCloud account with 'find my phone' enabled they shouldn't be able to re-activate it.
If you're really concerned about what's on your phone being found you can remotely wipe it https://support.apple.com/kb/ph2701?locale=en_US.


text:
Q: Как очистить память в связаном списке #include "dictionary.h"
#include <ncurses.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int listprint(List* node)
{
    if (!node) {
        return -1;
    }

    List* ptr = node;
    do {
        printf("%2d %-10s", ptr->value, ptr->key);
        ptr = ptr->next;
    } while (ptr != NULL);
    return 0;
}

    List* list_createnode(char* key, int value)
{
    List* p;
    p = calloc(sizeof(*p), 1);
    if (p != NULL) {
        p->key = key;
        p->value = value;
        p->next = NULL;
    }
    return p;
}

int printDictionary(dictionary* d)
{
    if (!d) {
        return -1;
    }
    for (int i = 0; i < d->count; i++) {
        listprint(d->lines[i]);
        printf("\n");
    }
    return 0;
}

List* list_lookup(List* list, char* key)
{
    for (; list != NULL; list = list->next) {
        if (strcmp(list->key, key) == 0) {
            return list;
        }
    }
    return NULL; /* Не нашли */
}

List* list_search(List* node, int value)
{
    for (; node != NULL; node = node->next) {
        if (node->value == value) {
            return node;
        }
    }
    return NULL;
}

List* list_addend(List* node, char* key, int value)
{
    List* newnode = list_createnode(key, value);

    if (node == NULL) {
        return newnode;
    }

    List* temp = node;
    while (temp->next != NULL) {
        temp = temp->next;
    }
    temp->next = newnode;
    return node;
}

int fill_dictionary(Dictionary* d)
{
    if (d == NULL) {
        return -1;
    }

    FILE* file;
    char name[] = "./source/d.txt";
    if ((file = fopen(name, "r")) == NULL) {
        printf("Не удалось открыть файл\n");
        return -1;
    }

    fseek(file, 0, SEEK_END);
    long pos = ftell(file);
    if (pos > 0) {
        rewind(file);
    } else {
        return -1;
    }

    char* str = calloc(sizeof(char), 100);
    if (str == NULL) {
        return -1;
    }

    d->count = 0;

    for (int i = 0; fgets(str, 100, file); i++) {
        d->count++;

        char* pch = strtok(str, " \n");

        for (int j = 1; j < 4 && pch != NULL; j++) {
            char* word = strdup(pch);
            d->lines[i] = list_addend(d->lines[i], word, j);
            pch = strtok(NULL, " \n");
            printf("%ld %p %s\n",strlen(pch),&word,word);
            //free(word);
        }

        while (pch != NULL) {
            char* word = strdup(pch);
            d->lines[i] = list_addend(d->lines[i], word, 0);
            pch = strtok(NULL, " \n");
            //free(word);
        }
        //free(pch);
    }
    fclose(file);
    free(str);
    return d->count;
}


text:
Q: Sequelize ORM add primary key column in selection, While I excluded it
I've prepare a query through sequelize, which get record with
  association hasOne,  aggregation function SUM() and with Group By
  clause, But sequelize query automatically added target table primary
  key column and  that column cause group by clause error.

Here is my Node Function, Which get data from service.
exports.getCustomerByManagerId = async (userId, limit, offset) => {
  const customers = await models.Customer.findAndCountAll({
    where: { account_manager_id: userId },
    include: [
      { model: models.UserProfile, as: 'accountmanager', attributes: userProfileSanitizer.sanitizeuserProfile() },
      {
        model: models.Task,
        as: 'customertask',
        attributes: [
          [sequelize.literal('SUM(IF(customertask.status = 1, 1, 0))'), 'todo'],
          [sequelize.literal('SUM(IF(customertask.status = 2, 1, 0))'), 'pendingTask'],
          [sequelize.literal('SUM(IF(customertask.status = 3, 1, 0))'), 'completeTask'],
          [sequelize.literal('COUNT(customertask.id)'), 'totalTask']
        ]
      }
    ],
    group: ['`customer`.`customer_id`'],
    order: [
      ['createdAt', 'DESC']
    ],
    limit,
    offset
  });

And sequelize query produce result query AS :
SELECT `customer`.`customer_id`, `customer`.`userId`, `customer`.`name`, `customer`.`account_manager_id`, `customer`.`start_date`, `customer`.`renewal_date`, `customer`.`customer_type`,
`customer`.`SKU`, `customer`.`variation`, `customer`.`similar`, `customer`.`setCost`, `customer`.`SKUCost`, `customer`.`variationCost`, `customer`.`similarCost`,
`customer`.`actual_monthly_cost`, `customer`.`address1`, `customer`.`address2`, `customer`.`city`, `customer`.`state`, `customer`.`category`, `customer`.`createdAt`,
`customer`.`updatedAt`, `accountmanager`.`userId` AS `accountmanager.userId`, `accountmanager`.`firstName` AS `accountmanager.firstName`, `accountmanager`.`lastName`
AS `accountmanager.lastName`, `accountmanager`.`isTermsofService` AS `accountmanager.isTermsofService`,
`customertask`.`id` AS `customertask.id`,
SUM(IF(customertask.status = 1, 1, 0)) AS `customertask.todo`,
SUM(IF(customertask.status = 2, 1, 0)) AS `customertask.pendingTask`,
SUM(IF(customertask.status = 3, 1, 0)) AS `customertask.completeTask`,
COUNT(customertask.customer_id) AS `customertask.totalTask`
FROM `customer` AS `customer`
LEFT OUTER JOIN `user_profiles` AS `accountmanager` ON `customer`.`account_manager_id` = `accountmanager`.`userId`
LEFT OUTER JOIN `task` AS `customertask` ON `customer`.`customer_id` = `customertask`.`customer_id`
WHERE `customer`.`account_manager_id` = 1
GROUP BY `customer`.`customer_id`
ORDER BY `customer`.`createdAt` DESC LIMIT 0, 10;

This is added by sequelize which cause error customertask.id AS
  customertask.id,  and when I remove this line and execute query in
  mysql workbench editor then it works
ERROR AS : Error Code: 1055. Expression #27 of SELECT list is not in
  GROUP BY clause and contains nonaggregated column
  'DBName.customertask.id' which is not functionally dependent on
  columns in GROUP BY clause

A: Adding raw:true will help and it will not add the primary key by default.

A: I'll preface this by saying that I don't know if this is the solution of not but it's too much to write in a comment..
Have you tried explicitly excluding the id field from customertask so it's not a selected attribute? e.g.
exports.getCustomerByManagerId = async (userId, limit, offset) =>
{
    const customers = await models.Customer.findAndCountAll({
        where: { account_manager_id: userId },
        include: [
            { model: models.UserProfile, as: 'accountmanager', attributes: userProfileSanitizer.sanitizeuserProfile() },
            {
                model: models.Task,
                as: 'customertask',
                attributes: {
                    include: [
                        [ sequelize.literal('SUM(IF(customertask.status = 1, 1, 0))'), 'todo' ],
                        [ sequelize.literal('SUM(IF(customertask.status = 2, 1, 0))'), 'pendingTask' ],
                        [ sequelize.literal('SUM(IF(customertask.status = 3, 1, 0))'), 'completeTask' ],
                        [ sequelize.literal('COUNT(customertask.id)'), 'totalTask' ]
                    ],
                    exclude: [ 'id' ] // <---------- exclude the id
                }
            }
        ],
        group: [ '`customer`.`customer_id`' ],
        order: [
            [ 'createdAt', 'DESC' ]
        ],
        limit,
        offset
    });
};


text:
Q: C# DataGridView 1st CheckBox Cell redrawing as unchecked. Why? Issue Solved - Posted for reference.
Hi, I have a strange error occurring.
I have a DataGridView that I am using to store a list of records, these records are being updated from a source by a BackgroundWorker.  There is a CheckBox Column that allows the user to select records from the DataGridView for processing.
When I check the CheckBox the first row(and only the first row), the checkbox does not seem to refresh correctly and displays as unchecked. The checkbox is still being treated as checked and the logic tied to it is working correctly.  This is a cosmetic issue that may confuse users.
any other CheckBox in the DataGridView draws correctly at all times.
Clicking anywhere on the DataGridView causes the CheckBox state to redraw correctly.
It seems like a redrawing issue, but I am having trouble tracking down why it is drawing like this.
Some details of relevance.
It is necessary for me to reload the dataset with each refresh.
I have set the cell highlight colors to be the same as the non-highlighted ones.
I have a routine that checks the Checked state of the CheckBoxes, records the records that have been selected and rechecks the checkboxes when the dataset has been replaced.  -This is working correctly
See the following code.
private void BgwDocketList_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {

        var checkedRows = from DataGridViewRow r in Dgv_Batch.Rows
            where Convert.ToBoolean(r.Cells[0].Value) == true
            select r;

        List<int> L = new List<int>();

        foreach (DataGridViewRow x in checkedRows)
        {
            L.Add((int)x.Cells[1].Value);
        }
        Dgv_Batch.DataSource =e.Result;
        foreach (DataGridViewRow v in Dgv_Batch.Rows)
        {
            if (L.Count(x=>x==(int)v.Cells[1].Value)>0)
            {
                v.Cells[0].Value = true;
            }
        }
    }

Have tried changing the selected cell programmatically
I have tried setting focus to the DataGridView in an attempt to programmatically recreate the effect of clicking on the control.  This does not redraw the checkbox.  only a mouse click seems to do this.
...Ok...
While Writing this I have managed to solve the problem.  I guess it helps to write down the steps to ensure they are checked out.
The issue was that after updating the checkboxes I needed to use
 DataGridView.EndEdit()

I would have expected that routine to have worked on the last record last as opposed to the first.  I guess this relates back to the DataGridView.DataGridViewSelectedRowCollection containing a reversed index.
I have posted this Question anyway in the hope that It may help someone with the same issue.

A: Utilize
DataGridView.EndEdit();

This will solve the problem.


text:
Q: Best and safest API for a function which fills a buffer with variable-length data I have a function which receives a buffer and returns some data in the buffer. The data can be smaller than the buffer capacity.
Which is the best and safest API for this?

*

*int fn(void *buffer, size_t buffer_len): the size of the data written to buffer is returned by the function. Downside: the return value must also have a way to indicate that some error occurred (in-band error indicator).

*errno_t fn(void *buffer, size_t *buffer_len): in this case, buffer_len works both as input (the buffer capacity) and output (the data size). The function can return an error code. I think this is OK, but somewhat awkward.

*errno_t fn(void *buffer, size_t *data_len, size_t buffer_len): like the previous, but with input/output separated in two arguments. Also returns error code, but is also awkward due to too many arguments.

(Any other options?)

A: I think the best API for such case is to create a buffer specification and deal with it, like:

struct sbuf {
  void *data;
  size_t size, pos, length;
};

// void if malloc() errors do abort(). int otherwise, to report error
void sbuf_alloc(sbuf *sb, size_t minsize);
void sbuf_free(sbuf *sb);

int /* or errno_t, whatever */ fn(sbuf *sb);

With such API, you'll avoid 1) long and cumbersome argument lists, 2) chance to mistake length for size and vice versa, and will gain instead understanding of object-like gist of your buffers.

A: A question we have pondered frequently.

*

*Look at how similar situations are handled elsewhere in your API. Consistency is a very high priority and if there are established principles, stick to them.

*The language matters. It is hard/impossible to return values in parameters in some languages (Java).

*Consider using a struct or collection instead of a raw pointer. The byte array in Java carries its length with it.

*I/O parameters are horrible to code with. Avoid them!

*A return value should not be both a success indicator and a length, but if you break any rules this one is the least serious.

Overall my preference in C/C++ generally is to return bool success/failure, and provide a secondary function (GetLastError()) to get the real error code.
In the case of Read (only) my preference is to return the length read as return value of function, with a special value for error (-1). Not the nicest, but convenient.
If the data you are reading is known to be Ascii, then return a null-terminated string to give the length, and bool true/false for the function return.
[Regrettably this is all a matter of opinion, which makes this a question at risk of being closed.]

A: I'd support david's point of maintaining consistency, and since this seems to be C (and not C++), the required functionality is very much like the POSIX file read:
input buffer instead of a file.
output buffer for user, remains same.
number of bytes read or length, remains same.
So, I think sticking to POSIX is a good thing, and so the first option would be better, with a return of -1 for error (negative values for multiple errors is possible but appears clumsy):
int fn(void *buffer, size_t buffer_len)

A: Which approach is best depends upon when in the process the code which is
filling the buffer will become aware of how big the buffer needs to be, and
upon whether it would be possible to perform the operation partially, return
to the caller, and then continue the operation later (after the caller
either created a bigger buffer or done everything that will ever need to be
done with the buffer's present contents, thus allowing the space to be
reused).  A nice general approach would be to pass a void** along with a
function which given a void** and a requested size, will behave in a
fashion roughly equivalent to:
void *resize(void **handle, size_t size)
{
  void *new_mem = realloc(*handle, size);
  if (!new_mem) return 0;
  *handle = new_mem;
  return new_mem;
}

but could use allocation mechanisms other than realloc to acquire memory.
Using that approach would allow the function which is filling the buffer
to expand it as its going along.  Another approach is to define an
abstract "state" structure, such that the usage pattern would be:
GRABBER_STATE *state = start_reading_data(...);
do {
  int n=get_items(state, buffer, buff_size));
  if (!n) break;
  process_n_items(buffer, n);
} while(1);
done_reading_data(state);

Here, it won't matter if the buffer is large enough to hold everything.
What's important is that if there are items that don't get handled the
first time through the loop, they can be handled on later passes.


text:
Q: After updating from typo3 7 to typo3 8 several invalid values in page contents I updated a typo3 site from version 6 to version 7 and now to version 8 heading for 9 or 10. Now some contents on my page are missing. When I look in the page editor all elements have errors like [INVALID VALUE ('ce_head-image')] or [INVALID VALUE ('ce_product')]. What does this mean?

A: Your content elements (CEs) have no rendering definition.
the rendering definition can be missing because of:

*

*the basic rendering extension is missing

*

*EXT:CSC leaves the core and is an TER extension

*the names of the CEs is changed inside the basic rendering extension (there should be an upgrade wizard)

*the same for CE types defined by additional extensions

*

*extension is no longer supported for the newer TYPO3 version

*changed names in newer versions (upgrade wizard?)

*the registering of additional CEs does not work any longer as it has been changed in the core

As the names you have sounds unfamiliar my firsst guess would be the last reason.


text:
Q: Creating a NPS report with data from Delighted.com? My company is using Delighted.com as one way of measuring customer engagement via a net promoter score(NPS). I've integrated Delighted.com with Salesforce and each survey response and score is found in the Contact Record using a related List.
I've made a "contacts with Accounts and Records" report and have the usual first name, last name, score, comment,timestamp and have the Account: Delighted NPS column added to the report, which i've chosen to Average.
Am I on the right path?? Any advice? My goal is to have the NPS report be on my team's dashboard for us to monitor and track the NPS score.
Thanks.


text:
Q: Proof verification: Squeeze theorem for integrals This was a problem in my analysis textbook-

Suppose that $f(x)\le g(x)\le h(x)$ for all $x\in[a,b]$ and that
  $\int_{a}^{b}f$ and $\int_{a}^{b}h$ exists and are equal. Prove that
  $\int_{a}^{b}g$ exists and equals $\int_{a}^{b}f =\int_{a}^{b} h$.

Attempted proof:
We first prove that $g$ is integrable on $[a,b]$. We claim that for any partition $P$ of $[a,b]$, we have $L_P(f)\le L_P(g)$ and $U_P(g) \le U_P(h)$. Our claim is easy to verify: If $J$ be any subinterval of $[a,b]$, then $f(x)\le g(x)$ on $J$. Clearly, $m_J(f) =\inf \{f(x) \mid x \in J\} \le g(x)$ for all $x \in J$. It follows that $m_J(f)$ is a lower bound for the set $\{g(x) \mid x\in J\}$. Hence, $m_J(f) \le m_J(g)$. It immediately follows by the definition of lower sum that $L_P(f)\le L_P(g)$ for any partition P. It can be verified similarly that $U_P(g) \le U_P(h)$.
Let $\varepsilon >0$ be given. Since $f$ is integrable on $[a,b]$, there exists a partition $P_1$ of $[a,b]$ such that $U_{P_1}(f)-L_{P_1}(f)<\frac{\varepsilon}{2}$. Likewise, since $h$ is integrable on $[a,b]$, there exists a partition $P_2$ of $[a,b]$ such that $U_{P_1}(h)-L_{P_1}(h)<\frac{\varepsilon}{2}$. Let $P=P_1 \cup P_2$. Then we have the following:
$$U_P(f)-L_P(f)\le \frac{\varepsilon}{2}$$
and
$$U_P(h)-L_P(h)\le \frac{\varepsilon}{2}$$
Now, we consider the following:
$$\begin{align}
U_P(g)-L_P(g) &\le U_P(h)-L_P(h) \\
& < \left( L_P(h) + \frac{\varepsilon}{2} \right) - \left( U_P(f) -\frac{\varepsilon}{2} \right) \\
& = \left( L_P(h) - U_P(f) \right) + \varepsilon
\end{align}$$
To complete the proof, we notice that $L_P(h)\le \int_{a}^{b} h$ and $\int_{a}^{b} f \le U_P (f)$. Hence, it follows that $L_P(f) - U_P(f) \le \int_{a}^{b} h -\int_{a}^{b} f =0$. It follows from this that
$$U_P(g)-L_P(g) < \varepsilon$$
Hence, $g$ is integrable on $[a,b]$.

Is this proof correct? Or did I go wrong somewhere? Alternative proofs are appreciated.

A: Here is an alternative proof that seems easier to me.
By your own argument, we have $L(P,f) \leqslant L(P,g) \leqslant U(P,g) \leqslant U(P,h)$ for any partition $P$.
Thus, since $f$ and $h$ are Riemann integrable,
$$\int_a^bf = \sup_{P}L(P,f) \leqslant \sup_{P} L(P,g)= \underline{\int}_a^bg \\\leqslant \overline{\int_a^b}g = \inf_{P}\,\,U(P,f) \leqslant \inf_{P} \,\,U(P,h)= \int_a^bh$$
Since the integrals of $f$ and $h$ are equal, it follows that the upper and lower Darboux integrals of $g$ must be equal,
$$\underline{\int}_a^bg = \overline{\int_a^b}g, $$
whence, $g$ is Riemann integrable with
$$\int_a^b f = \int_a^b g = \int_a^b h$$


text:
Q: Adding products to PrestaShop 1.6.0.9 with WebService I am trying to add products to my shop powered by PrestaShop 1.6.0.9. Here is my code:
<?php
    ini_set('display_errors',1);
    ini_set('display_startup_errors',1);
    error_reporting(-1);
    define('DEBUG', true);
    define('_PS_DEBUG_SQL', true);
    define('PS_SHOP_PATH', 'http://myshop.com');
    define('PS_WS_AUTH_KEY', 'E6R9IDPK2R519WB9QAJ45MUACZ9GANC2');

    require_once('PSWebServiceLibrary.php');

    try {
            $webService = new PrestaShopWebservice(PS_SHOP_PATH, PS_WS_AUTH_KEY, DEBUG);
            $opt = array('resource' => 'products');

            $xml = $webService->get(array('url' => PS_SHOP_PATH.'/api/products?schema=synopsis'));
            $resources = $xml->children()->children();

            unset($resources->position_in_category);
            unset($resources->manufacturer_name);

            $resources->price = '1000';
            $resources->active = '1';
            $resources->quantity = '50';
            $resources->link_rewrite = 'blabla';
            $resources->name->language[0][0] = 'blabla';
            $resources->description->language[0][0] = '
blabla
';
            $resources->description_short->language[0][0] = 'blabla';
            $resources->associations = '';

            $opt = array('resource' => 'products');
            $opt['postXml'] = $xml->asXML();
            $xml = $webService->add($opt);
    }
    catch (PrestaShopWebserviceException $ex) {
        echo 'Other error:
'.$ex->getMessage();
    }
?>

But I receive this error as XML:
<?xml version="1.0" encoding="UTF-8"?>
<prestashop xmlns:xlink="http://www.w3.org/1999/xlink">
<errors>
<error>
<![CDATA[127]]>
<message><![CDATA[XML error : String could not be parsed as XML
XML length : 7891
Original XML : %3C%3Fxml+version%3D%221.0%22+encoding%3D%22UTF-8%22%3F%3E%0A%3Cprestashop+xmlns%3Axlink%3D...................
</error>
</errors>
</prestashop>

I receive  error for every update or insert. What can be the problem? And how can I fix this? My PrestaShop version is 1.6.0.9.

A: I found the bug in PSWebServiceLibrary.php in public function add($options). The problem was with request:
$request = self::executeRequest($url, array(CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_POSTFIELDS => 'xml='.urlencode($xml)));

Notice, that CURLOPT_POSTFIELDS => 'xml='.urlencode($xml). This sends XML as string with prepending 'xml=' string to the beginning of file and url encoding the whole XML, but PS expects XML, so it should be this way:
$request = self::executeRequest($url, array(CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_POSTFIELDS => $xml));

A: Try this Solution. It works for me
<title>Add Product</title>
<?php

define('DEBUG', true);
define('PS_SHOP_PATH', 'http://myshop.com');
define('PS_WS_AUTH_KEY', 'E6R9IDPK2R519WB9QAJ45MUACZ9GANC2');
require_once('PSWebServiceLibrary.php');

try
{
    $webService = new PrestaShopWebservice(PS_SHOP_PATH, PS_WS_AUTH_KEY, DEBUG);
    $opt = array('resource' => 'products');
    if (isset($_GET['Create']))
        $xml = $webService->get(array('url' => PS_SHOP_PATH.'/api/products?schema=blank'));
    else
        $xml = $webService->get($opt);
    $resources = $xml->children()->children();
}
catch (PrestaShopWebserviceException $e)
{
    // Here we are dealing with errors
    $trace = $e->getTrace();
    if ($trace[0]['args'][0] == 404) echo 'Bad ID';
    else if ($trace[0]['args'][0] == 401) echo 'Bad auth key';
    else echo 'Other error';
}

if (count($_POST) > 0)
{
// Here we have XML before update, lets update XML
    foreach ($resources as $nodeKey => $node)
    {
        $resources->$nodeKey = $_POST[$nodeKey];
    }
    try
    {
        $opt = array('resource' => 'products');
        if ($_GET['Create'] == 'Creating')
        {
            $opt['postXml'] = $xml->asXML();
            $xml = $webService->add($opt);
            echo "Successfully added.";
        }
    }
    catch (PrestaShopWebserviceException $ex)
    {
        // Here we are dealing with errors
        $trace = $ex->getTrace();
        if ($trace[0]['args'][0] == 404) echo 'Bad ID';
        else if ($trace[0]['args'][0] == 401) echo 'Bad auth key';
        else echo 'Other error
'.$ex->getMessage();
    }
}

// Title
echo '
Product\'s ';
if (isset($_GET['Create'])) echo 'Creation';
else echo 'List';
echo '
';

// We set a link to go back to list if we are in creation
if (isset($_GET['Create']))
    echo 'Return to the list';

if (!isset($_GET['Create']))
    echo '<input type="button" onClick="document.location.href=\'?Create\'" value="Create">';
else
    echo '<form method="POST" action="?Create=Creating">';

echo '
';
if (isset($resources))
{

echo '
';
if (count($_GET) == 0)
{
    echo 'Id
';

    foreach ($resources as $resource)
    {
        echo '
'.$resource->attributes().'
';
    }
}
else
{
    echo '
';
    foreach ($resources as $key => $resource)
    {
        echo '
'.$key.'	';
        if (isset($_GET['Create']))
            echo '<input type="text" name="'.$key.'" value=""/>';
        echo '
';
    }
}

}
echo '

';

if (isset($_GET['Create']))
    echo '<input type="submit" value="Create"></form>';

?>

A: You can use a simpler way just using direct XML input and the product schema,
adding values directly with $vars value like $myID etc.
Note that I am using 2 languages in PS.
$ps_product = <<<XML
<prestashop>
<product>
    <id></id>
    <id_manufacturer></id_manufacturer>
    <id_supplier></id_supplier>
    <id_category_default></id_category_default>
    <new></new>
    <cache_default_attribute></cache_default_attribute>
    <id_default_image></id_default_image>
    <id_default_combination></id_default_combination>
    <id_tax_rules_group></id_tax_rules_group>
    <position_in_category></position_in_category>
    <type></type>
    <id_shop_default></id_shop_default>
    <reference></reference>
    <supplier_reference></supplier_reference>
    <location></location>
    <width></width>
    <height></height>
    <depth></depth>
    <weight></weight>
    <quantity_discount></quantity_discount>
    <ean13></ean13>
    <upc></upc>
    <cache_is_pack></cache_is_pack>
    <cache_has_attachments></cache_has_attachments>
    <is_virtual></is_virtual>
    <on_sale></on_sale>
    <online_only></online_only>
    <ecotax></ecotax>
    <minimal_quantity></minimal_quantity>
    <price></price>
    <wholesale_price></wholesale_price>
    <unity></unity>
    <unit_price_ratio></unit_price_ratio>
    <additional_shipping_cost></additional_shipping_cost>
    <customizable></customizable>
    <text_fields></text_fields>
    <uploadable_files></uploadable_files>
    <active></active>
    <redirect_type></redirect_type>
    <id_product_redirected></id_product_redirected>
    <available_for_order></available_for_order>
    <available_date></available_date>
    <condition></condition>
    <show_price></show_price>
    <indexed></indexed>
    <visibility></visibility>
    <advanced_stock_management></advanced_stock_management>
    <date_add></date_add>
    <date_upd></date_upd>
    <meta_description><language id='1'></language><language id='2'></language></meta_description>
    <meta_keywords><language id='1'></language><language id='2'></language></meta_keywords>
    <meta_title><language id='1'></language><language id='2'></language></meta_title>
    <link_rewrite><language id='1'></language><language id='2'></language></link_rewrite>
    <name><language id='1'></language><language id='2'></language></name>
    <description><language id='1'></language><language id='2'></language></description>
    <description_short><language id='1'></language><language id='2'></language></description_short>
    <available_now><language id='1'></language><language id='2'></language></available_now>
    <available_later><language id='1'></language><language id='2'></language></available_later>
<associations>
<categories>
    <category>
    <id></id>
    </category>
</categories>
<images>
    <image>
    <id></id>
    </image>
</images>
<combinations>
    <combination>
    <id></id>
    </combination>
</combinations>
<product_option_values>
    <product_option_value>
    <id></id>
    </product_option_value>
</product_option_values>
<product_features>
    <product_feature>
    <id></id>
    <id_feature_value></id_feature_value>
    </product_feature>
</product_features>
<tags>
    <tag>
    <id></id>
    </tag>
</tags>
<stock_availables>
    <stock_available>
    <id></id>
    <id_product_attribute></id_product_attribute>
    </stock_available>
</stock_availables>
<accessories>
    <product>
    <id></id>
    </product>
</accessories>
<product_bundle>
    <product>
    <id></id>
    <quantity></quantity>
    </product>
</product_bundle>
</associations>
</product>
</prestashop>
XML;

$xml = new SimpleXMLElement($psXML);
$opt = array( 'resource' => 'products' );
$opt['postXml'] = $xml->asXML();
$xml = $webService->add( $opt );

I'm using this way in order to add carts directly in PS. If you don't have values for some node (you can pass data only for required fields) just use the following schema (for example id_default_image):
<id_default_image/>

instead of
<id_default_image></id_default_image>

Hope this will help you.


text:
Q: ResourceExhaustedError When running network demo fourth try I have 1600 videos and I want to make joint annotation label data about videos.
I've already made the open pose network and I put my videos as input of the network and saved the joint data as json file.
When I put my first video data as input, there are no errors. And when I put second, third video as input, there are no errors too.
But When I put the fourth video data as input, I got these error message.
enter image description here
enter image description here
these above images are the error message.(OOM)
The size of first, second, third, fourth video is the same.
When I change name first and fourth video name, I got the same error when putting fourth video.
I think this error is about the graph. but I couldn't know why exactly.
I think there are many genious on stackoverflow. So please answer my question... :)

A: I solve this problem by using cpu. not using gpu.
I use cpu only in tensorflow for solving this problem. and it works!


text:
Q: Why doesn't my FPDF class function SetMargins() effect the first row? I am using the FPDF class to create a pdf based on the results from a mysql query. The information was outputted in a table to pdf as expected but my problem occurred when I used SetMargins() to set the page margins. Everything except the first row is effected. The first line seems to be hardcoded to a certain position or margin definition.
Here is my code:
class Table extends FPDF
{
    public function CreateTable($header, $data)
    {
        //Header
        $this->SetFillColor(255);
        $this->SetTextColor(0);
        $this->SetFont('Arial','B', 12);
        foreach ($header as $col) {
            $this->Cell($col[1], 10, $col[0], 1, 0, 'C');
            //Cell(float w [, float h [, string txt [, mixed border [, int ln [, string align [, boolean fill [, mixed link]]]]]]])
        }

        $this->Ln();

        //Data
        $this->SetFillColor(255);
        $this->SetTextColor(0);
        $this->SetFont('Arial', '', 8);
        foreach ($data as $row) {

            $i = 0;
            foreach ($row as $field) {
                $this->Cell($header[$i][1], 6, $field, 1, 0, 'C');
                $i++;

            }
            $this->Ln();
        }

    }
}

//column headings for the department table
$dept_header = array(array('Name', 75), array('Phone', 40), array('Fax', 40));

//column headings for the team tables
$team_header = array(array('Name', 35), array('Role', 30), array('Office', 25), array('Cell', 25), array('Email', 45), array('Pager', 25));

//get data
$query = new ConnectQuery();
$dept_data = $query->all('SELECT * FROM Table');

$team_data = $query->all('SELECT CONCAT_WS(" ", FIRST_NAME, LAST_NAME), JOB_ROLE, OFFICE_PHONE, MOBILE_PHONE, EMAIL, PAGER_NUM FROM Table2');

$pdf = new Table('P', 'mm', 'Letter');

$pdf->AddPage();
$pdf->SetMargins(5, 5);
$pdf->CreateTable($team_header, $team_data);
$pdf->CreateTable($dept_header, $dept_data);

$pdf->Output();

?>

A: Just define the page margin BEFORE you add the first page. The position is not reset by setMargins() call, which results in the "hardcoded postition" which was set in AddPage():
$pdf = new Table('P', 'mm', 'Letter');
$pdf->SetMargins(5, 5);
$pdf->AddPage();

A: There's a property in the FPDF class called $cMargin, which is used to calculate the x-offset of the text before it gets printed within the cell, but there doesn't appear to be a setter for it. It's a public property, so after you've instantiated your FPDF class, just call:
$pdf = new fpdf('P','mm','A4');
$pdf->cMargin = 0;

Or you can workaround your 1st line like
$pdf->Ln(); //workaround for 1st line
  $pdf->Cell(..);


text:
Q: Find a string inside quotes in Javascript The title explains my problem. I am trying to get a string that has quotation marks around it so I can use Node.js to pass into a weather module. Here's my code so far (I have not set the var CityToSearch yet in this code which is what I need help with)
And also yes I'm using Discord.js to send messages.
const Discord = require('discord.js')
const bot = new Discord.Client()
const PREFIX = '/';
const embed = new Discord.MessageEmbed()
const ping = require('minecraft-server-util')
const weather = require('weather-js')

bot.on('message', message => {
  if (message.channel.type === 'dm') {return}
  let args = message.content.substring(PREFIX.length).split(' ')
  if(message.content.startsWith(PREFIX))
  switch (args[0]) {
case 'weather':
if (args.includes('"')){
        var CityToSearch =
      }
      weather.find({search: `city, ${CityToSearch}`, degreeType: 'F'}, function(err, result) {
              if(err) console.log(err);
              var currentw = new Discord.MessageEmbed()
                .setColor(0x00ffff)
                .setTitle(`Current Weather in ${args[1]} in state ${args[2]}`)
                .addField('Temperature', result[0].current.temperature)
                .addField('Sky Text', result[0].current.skytext)
                .addField('Humidity', result[0].current.humidity)
                .addField('Wind Speed & Direction', result[0].current.winddisplay)
                .addField('Feels Like', result[0].current.feelslike)
                .addField('Location', result[0].current.observationpoint)
                .addField('Time', result[0].current.observationtime)
                .addField('Date', result[0].current.date)
              message.channel.send(currentw)
            });

A: You can split the actual string with ". So that the string will be split and the string at index 1 will be the city you are looking for.

const str = '/weather "San Fransico" California';
console.log(str.split('"'));
console.log(str.split('"')[1]);

A: I would NOT split the arguments on spaces initially. You can use the Regular Expression below with your arguments to yank out the command, and then parse the inputs as needed:
const args = message.content.substring(PREFIX.length).match(/\/([^\s]+) (.+)/)
if (args) {  // valid input?
  const command = args[1]
  const input = args[2]

  switch (command) {
    case 'weather':
      const cityMatch = input.match(/"([^"]+)"/)
      const CityToSearch = (cityMatch) ? cityMatch[1] : input.split(/\s/)[0]
      weather.find({search: `city, ${CityToSearch}` ...)

    // other commands...

  }
}