text:
Q: Should I use a single function or an object in OOP? I'm new to OOP, and I want to know if I should use a single function, or an object.
Should I do this:
class Escape_String{
    protected $string;

    function __construct($string){
        if(get_magic_quotes_gpc)
            return $string;
        else
            return addslashes($string);
    }
}

$string = new Escape_String($_GET['string']);

or should I just use a function instead of an object? (Like this:)
escapeString($string){
    if(get_magic_quotes_gpc)
        return $string;
    else
        return addslashes($string);
}

$string = escapeString($_GET['string']);

of course the real object Escape_String/function escapeString are a little bit more complicated, but you should know what I mean

A: in you case it is better to name class something like StringUtils and to make static method escapeString
I recommend to read a book like http://shop.oreilly.com/product/mobile/9780596007126.do and reading sourse code of popular frameworks like Symfony2

A: Try something like this:
class StringUtil
{

    static public function escapeString( $string )
    {
        if(get_magic_quotes_gpc) {
            return $string;
        } else {
            return addslashes($string);
        }
    }

}

It is static for easy use.
echo StringUtil::escapeString($string);

A: In this case, I would say this is best suited as a function or as a public static method on a class, if you have other similar methods you want to group into a class library.  I would not make a class just for this method however.


text:
Q: Misleading 404 error with Tastypie API I'am using the lasted version of Tastypie for a simple API resource.
On a post Tastypie gave me a 404 file not found reply. Looking at my logs the error actually turned out to be me not posting the User FK correctly. However, I found the 404 error very misleading.
Is this a normal response to an error in TastyPie? If not I'm I doing something wrong?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Armed with the information that $f(0)=0$ and $f'(0)=1$, evaluate: $\lim_{z\rightarrow 0}\frac{f(z^2)}{z}$ Armed with the information that $f(0)=0$ and $f'(0)=1$, evaluate: $(i)\lim_{z\rightarrow 0}\frac{f(z^2)}{z}, (ii) \lim_{z\rightarrow i}\frac{f(z^2+1)}{z-i}$ .
For $(i)$ let $u:=z^2$ be so $\lim_{z\rightarrow 0}\frac{f(z^2)}{z}=\lim_{u\rightarrow 0}\sqrt{u}\frac{f(u)}{u}=\lim_{u\rightarrow 0}\sqrt{u}\lim_{u\rightarrow 0}\frac{f(u)-f(0)}{u-0}=0\cdot f'(0)=0\cdot 1=0$ Is this argument well? could you do the same with $(ii)$? thanks for your help.

A: Use L'Hospital rule
$$\lim_{z\rightarrow 0}\dfrac{f(z^2)}{z}=\lim_{z\rightarrow 0}\dfrac{2zf'(z^2)}{1}=0$$
and
$$\lim_{z\rightarrow i}\frac{f(z^2+1)}{z-i}=2i.$$

A: All you need to know is that the composition of differentiable functions is differentiable again. By $f(0)=0$ the both limits are just the differential quotient of $z\mapsto f(z^2)$ and $z\mapsto f(z^2+1)$ at the point $z_0=0$ and $z_0=\mathrm i$. Hence the limits are (by the chain rule) $0$ and $2\mathrm i$.

A: Note that $f'(0)=1$ is same as saying $(f(z)-f(0))/z\to 1$ as $z\to 0$. Thus we have $f(z) /z\to 1$ as $z\to 0$. Then $f(z^{2})/z=z\cdot f(z^{2})/z^{2}\to 0\cdot 1=0$.
Let $w=z^{2}+1$ so that $w\to 0$ as $z\to i$. Then $$\frac{f(z^{2}+1)}{z-i}=\frac{f(w)}{w}\cdot (z+i) \to 1\cdot 2i=2i$$ as $z\to i$.


text:
Q: ¿Cómo solucionar "la aplicacion se detuvo"? Estoy desarrollando una aplicación  en Android Studio y al correrla en el emulador se detiene antes de abrir nada. El caso es que si tengo el emulador configurado en español o en inglés (hay varios idiomas) funciona perfectamente, pero en catalán o cualquier otro idioma se detiene.
Este es el log del error:
05-24 09:07:22.114 3498-3498/com.example.juditmasana.batecs365
E/AndroidRuntime: FATAL EXCEPTION: main

Process: com.example.juditmasana.batecs365, PID: 3498

java.lang.RuntimeException: Unable to start activity ComponentInfo{ com.example.juditmasana.batecs365/com.example.juditmasana.batecs365.MainActivity}: android.view.InflateException: Binary XML file line #11: Binary XML file line #23: Error inflating class android.widget.ImageView
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)

... y así sigue un buen rato...
Este es el XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="MainActivity"
    tools:showIn="@layout/app_bar_main">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/scrollView4" >

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:weightSum="1"
            android:layout_alignParentTop="true"
            android:layout_marginTop="0dp">

            <FrameLayout
                android:layout_width="match_parent"
                android:layout_height="28dp"></FrameLayout>

            <LinearLayout
                android:orientation="vertical"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textAlignment="center"
                android:background="#000000">

                <FrameLayout
                    android:layout_width="match_parent"
                    android:layout_height="240dp"
                    android:layout_gravity="center">

                    <com.google.android.youtube.player.YouTubePlayerView
                        android:id="@+id/youtube_player"
                        android:layout_width="match_parent"
                        android:layout_height="240dp"
                        android:layout_marginBottom="30dp" />

                    <!--<ImageButton
                        android:layout_width="59dp"
                        android:layout_height="54dp"
                        android:id="@+id/play"
                        android:background="@drawable/play"
                        android:layout_gravity="center"
                        android:visibility="visible"/>-->
                </FrameLayout>

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAppearance="?android:attr/textAppearanceLarge"
                    android:id="@+id/titleVideo"
                    android:textSize="20dp"
                    android:textStyle="bold"
                    android:paddingTop="10dp"
                    android:paddingBottom="10dp"
                    android:textColor="#ffffff" />

            </LinearLayout>

            <LinearLayout
                android:orientation="vertical"
                android:layout_width="match_parent"
                android:layout_height="80dp"
                android:weightSum="1"
                android:gravity="bottom">

                <Button
                    style="?android:attr/buttonStyleSmall"
                    android:layout_width="210dp"
                    android:layout_height="wrap_content"
                    android:text="@string/crea_el_teu_batec"
                    android:id="@+id/batecPropi"
                    android:background="@drawable/drawable_button"
                    android:textColor="#FFEBEE"
                    android:onClick="nouBatec"
                    android:layout_gravity="center"
                    android:layout_weight="0.31"
                    android:textSize="18dp"
                    android:textStyle="bold"
                    android:shadowColor="#cecece"
                    android:singleLine="true" />

            </LinearLayout>

            <FrameLayout
                android:layout_width="match_parent"
                android:layout_height="30dp"></FrameLayout>

            <LinearLayout
                android:orientation="vertical"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="bottom">

                <FrameLayout
                    android:layout_width="156dp"
                    android:layout_height="wrap_content"
                    android:layout_gravity="right">

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textAppearance="?android:attr/textAppearanceSmall"
                        android:text="@string/segueix_nos"
                        android:id="@+id/segueixXS"
                        android:textSize="15dp"
                        android:gravity="center_vertical"
                        android:layout_gravity="bottom|center_horizontal" />
                </FrameLayout>

                <LinearLayout
                    android:orientation="horizontal"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:layout_gravity="bottom|right"
                    android:gravity="bottom|end">

                    <android.support.design.widget.FloatingActionButton
                        android:layout_width="50dp"
                        android:layout_height="50dp"
                        android:id="@+id/facebook"
                        android:layout_marginRight="5dp"
                        app:srcCompat="@drawable/ic_facebook"
                        android:scaleType="center"
                        app:backgroundTint="#3b5998"
                        android:layout_gravity="bottom|right" />

                    <android.support.design.widget.FloatingActionButton
                        android:layout_width="50dp"
                        android:layout_height="50dp"
                        android:id="@+id/twitter"
                        android:layout_marginRight="5dp"
                        app:srcCompat="@drawable/ic_twitter"
                        android:scaleType="center"
                        app:backgroundTint="#1dcaff"
                        android:layout_gravity="bottom|right"
                        android:paddingBottom="5dp" />

                    <android.support.design.widget.FloatingActionButton
                        android:layout_width="50dp"
                        android:layout_height="50dp"
                        android:id="@+id/youtube"
                        android:layout_gravity="bottom|right"
                        app:backgroundTint="#b31217"
                        app:srcCompat="@drawable/ic_youtube"
                        android:scaleType="center"/>

                </LinearLayout>
            </LinearLayout>

        </LinearLayout>
    </ScrollView>

</RelativeLayout>

... y este el código:
public class MainActivity extends YouTubeBaseActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    private YouTubePlayerView youTubePlayerView;
    private YouTubePlayer.OnInitializedListener onInitializedListener;
    private static final String API_KEY = "AIzaSyBl4SvN4KOuN2ImoLO4iRI0oTrHG4fxB9A";
    public String VIDEO_ID;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        //setSupportActionBar(toolbar);

        //Create buttons social networks
        FloatingActionButton fcbk = (FloatingActionButton) findViewById(R.id.facebook);
        FloatingActionButton twttr = (FloatingActionButton) findViewById(R.id.twitter);
        FloatingActionButton utb = (FloatingActionButton) findViewById(R.id.youtube);
        fcbk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intentfcbk = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/solidaridadSJD/"));
                startActivity(intentfcbk);
            }
        });
        twttr.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intenttwttr = new Intent(Intent.ACTION_VIEW, Uri.parse("https://twitter.com/solidaridadSJD"));
                startActivity(intenttwttr);
            }
        });
        utb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intentutb = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.youtube.com/user/obrasocialsjd"));
                startActivity(intentutb);
            }
        });

        //Declara el drawerLayout
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        //Controlador del Video de la pàgina principal
        youTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtube_player);
        onInitializedListener = new YouTubePlayer.OnInitializedListener() {
            public void onInitializationFailure(Provider provider, YouTubeInitializationResult result) {
            }
            public void onInitializationSuccess(Provider provider, YouTubePlayer player, boolean wasRestored) {
                /** add listeners to YouTubePlayer instance **/
                player.setPlayerStateChangeListener(playerStateChangeListener);
                player.setPlaybackEventListener(playbackEventListener);
                player.setShowFullscreenButton(true);
                /** Start buffering **/
                if (!wasRestored) {
                    player.cueVideo(VIDEO_ID);
                }
            }
        };
        new videoPlay(youTubePlayerView).execute("");

    }
    // Per poder agafar la informació de la pàgina www.365Batecs.org
    private class videoPlay extends AsyncTask<String, String, ArrayList<String>>{
        YouTubePlayerView myoutube;
        public videoPlay(YouTubePlayerView youTubePlayerView) {
            this.myoutube = youTubePlayerView;
        }
        @Override
        protected void onPreExecute(){
            super.onPreExecute();
        }
        protected ArrayList<String> doInBackground(String... params) {
            ArrayList<String> video = new ArrayList<>();
            String srcVideo;
            String title;
            try {
                Document doc = Jsoup.connect(getString(R.string.batecs_org)).get();
                Elements titleVideo = doc.select("iframe.youtube-field-player");
                title = titleVideo.attr("title");
                title = title.substring(25, title.length()-6);

                video.add(title);
                Log.e("Title", title);
                Elements videoPath = doc.select("iframe.youtube-field-player");
                srcVideo = videoPath.attr("src");
                srcVideo = srcVideo.substring(30, srcVideo.length() - 58);
                video.add(srcVideo);
                Log.e("Video: ",srcVideo);
                return video;

            }
            catch (IOException ex){
                ex.printStackTrace();
                Log.e("error", "HA SALTAT");
                return null;

            }
        }

        protected void onPostExecute(ArrayList<String> video){
            TextView titleVideo = (TextView) findViewById(R.id.titleVideo);
            if(video == null){
                final AlertDialog.Builder noConnection = new AlertDialog.Builder(MainActivity.this);
                noConnection.setTitle(R.string.sensecon);
                noConnection.setMessage(R.string.comprovila);
                noConnection.setIcon(R.drawable.ic_connection);
                noConnection.setPositiveButton(R.string.Tornarapr, new DialogInterface.OnClickListener(){
                    public void onClick(DialogInterface dialogInterface, int which){
                        new videoPlay(youTubePlayerView).execute("");
                    }
                });
                noConnection.create();
                noConnection.show();
            }
            else{
                titleVideo.append(video.get(0));
                VIDEO_ID =video.get(1);
                myoutube.initialize(API_KEY, onInitializedListener);
                Log.e("src: ", VIDEO_ID);
            }

            super.onPostExecute(video);
        }
    }

    private PlaybackEventListener playbackEventListener = new PlaybackEventListener() {
        @Override
        public void onBuffering(boolean arg0) {
        }
        @Override
        public void onPaused() {
        }
        @Override
        public void onPlaying() {
        }
        @Override
        public void onSeekTo(int arg0) {
        }
        @Override
        public void onStopped() {
        }
    };

    private PlayerStateChangeListener playerStateChangeListener = new PlayerStateChangeListener() {
        @Override
        public void onAdStarted() {
        }
        @Override
        public void onError(ErrorReason arg0) {
        }
        @Override
        public void onLoaded(String arg0) {
        }
        @Override
        public void onLoading() {
        }
        @Override
        public void onVideoEnded() {
        }
        @Override
        public void onVideoStarted() {
        }
    };

    //Botó per crear el teu nou batec
    public void nouBatec(View view){
        Intent instruc = new Intent(this, InstruccionsActivity.class);
        startActivity(instruc);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.

        return super.onOptionsItemSelected(item);
    }

    //Quan es selecciona una de les opcions del drawerLayaout
    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
       int id = item.getItemId();
       if (id == R.id.nav_info) {
            Intent info = new Intent(this,InformacioActivity.class);
            startActivity(info);

        }else if (id == R.id.nav_material) {
            Intent material = new Intent(this,MaterialActivity.class);
            startActivity(material);
        }
       else if (id == R.id.nav_ambit) {
            Intent ambit = new Intent(this,CercaAmbitActivity.class);
            ambit.putExtra("url","http://www.365batecs.org/sense-llar");
            ambit.putExtra("title", "Sense llar");
            startActivity(ambit);
        }
        else if (id==R.id.nav_app){
           Intent sobre_app = new Intent(this,SobreAppActivity.class);
           startActivity(sobre_app);
       }
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}

A: Yo creo que el problema son los hilos de tu aplicación, date una sumergida por aquí.


text:
Q: Audit.Net: Process of saving in different dataprovider Is it possible to establish some mechanism so that in case the insertion of the audit fails in the default dataprovider, oracle for example, another data provider is used, for example in a file?
Thanks for the help

A: There is not a data provider with automatic fallback capabilities, but you can implement a custom data provider.
Say you want the Sql data provider by default, and another data provider as fallback. Inherit from the SQL data provider (SqlDataProvider) and fallback to another DataProvider when a SqlException is thrown:
public class FallbackSqlDataProvider : SqlDataProvider
{
    public AuditDataProvider FallbackProvider { get; set; }

    public override object InsertEvent(AuditEvent auditEvent)
    {
        try
        {
            return base.InsertEvent(auditEvent);
        }
        catch (SqlException)
        {
            return FallbackProvider?.InsertEvent(auditEvent);
        }
    }
    public override async Task<object> InsertEventAsync(AuditEvent auditEvent)
    {
        try
        {
            return await base.InsertEventAsync(auditEvent);
        }
        catch (SqlException)
        {
            return await FallbackProvider?.InsertEventAsync(auditEvent);
        }
    }
    public override void ReplaceEvent(object eventId, AuditEvent auditEvent)
    {
        try
        {
            base.ReplaceEvent(eventId, auditEvent);
        }
        catch (SqlException)
        {
            FallbackProvider?.ReplaceEvent(eventId, auditEvent);
        }
    }
    public override async Task ReplaceEventAsync(object eventId, AuditEvent auditEvent)
    {
        try
        {
            await base.ReplaceEventAsync(eventId, auditEvent);
        }
        catch (SqlException)
        {
            await FallbackProvider?.ReplaceEventAsync(eventId, auditEvent);
        }
    }
}

Then you can set the fallback data provider on FallbackProvider property, for example like this:
var dp = new FallbackSqlDataProvider()
{
    ConnectionString = "cnnstring",
    TableName = "table",
    IdColumnName = "id",
    JsonColumnName = "data",

    FallbackProvider = new Log4netDataProvider()
    {
        Logger = LogManager.GetLogger(typeof(Log4netDataProvider)),
        LogMessageBuilder = (ev, id) => ev.ToJson()
    }
};

Audit.Core.Configuration.Setup()
    .UseCustomProvider(dp);

Also check this related issue.


text:
Q: sizeof array without explicit length Can sizeof safely be used on an array that has been declared without an explicit size specified inside the square brackets, but which gets initialised in the declaration?
Consider the following code:
unsigned int arr[] = { 1, 2, 3 };
size_t bytes = sizeof arr;

If compiled on macOS with clang-800.0.42.1 without any special compiler flags, this yields the expected result of 12.
But does the C standard (or any C standard, if they differ on this) guarantee this to be the case? Or do I have to declare it like unsigned int arr[3] in order for it to be "sane"?

A: Yes, the standard guarantees that the array element count will be equal to the number of elements in the array initializer in case no size is specified. See
C11 standard draft 6.7.9p22 and 6.7.9p25:

If an array of unknown size is initialized, its size is determined by
  the largest indexed element with an explicit initializer. The array
  type is completed at the end of its initializer list.
EXAMPLE 2 The declaration
int x[] = { 1, 3, 5 };

defines and initializes x as a one-dimensional array object that has three elements, as no size was specified and there are three initializers.

A: unsigned int arr[] = { 1, 2, 3 }; actually defines a complete array. The size of the array is known in this compilation unit and is n*sizeof(type) where n is the number of elements in the initialization list (here 3) and type is the underlying object type (here unsigned int).
That means that sizeof(arr) is defined in same scope as arr and has the expected value.

What would be completely different would be extern int arr[];. That would be a simple declaration that an array of that name will be provided in another compilation unit, but the compiler has no way to know its size. In that case using sizeof(arr) will be an error.
Another example of mere declaration is
void func(int arr[]) {
    ...
}

Here again the compiler only knows that the function will receive an int array, but again cannot know its size. But here the compiler generates a pointer that will receive the address of the array and sizeof(arr) is defined but is the size of that pointer and not the size of the original array.


text:
Q: Is it possible to decompile .asmx file from client side to get the code? Is it possible to get the source code of a webservice asmx file. An android app calling the service can be de-compiled to fetch the source code. This exposes the code which is a problem.
Can the service be similarly de-compiled from client side.
To secure Android native code, code can be obfuscated, or token based authentication can be used to avoid hacking.
But if my asmx source code is exposed to the client, then the complete server side code is shared.
Is there any way to restrict this and secure web service.

A: Sure, it's possible. Plenty of vulnerabilities such as path traversal can be exploited to disclose source, or worse. But, without such a vulnerability, it should not be possible to download the raw ASMX file from a properly configured server.


text:
Q: How do I open a WinSCP GUI session from command line? If I have a session named "hpc" and I run:
winscp hpc

I get into command line mode. How do I run the GUI and open a session from the command line (Windows)?

A: WinSCP has two executables, winscp.exe and winscp.com. The winscp.exe is GUI, while the winscp.com is command-line.
If you use just the winscp, due to an extension precedence in Windows, the .com wins. Make sure you use a full GUI executable name:
winscp.exe hpc

References:
https://winscp.net/eng/docs/executables
https://winscp.net/eng/docs/commandline


text:
Q: Laravel-False response in axios inside vue.js This is my code for my Laravel controller
public function show($postId){
        $reaction = Reaction::where([
            'post_id' => $postId,
            'user_id' => auth()->id(),
            ])->first();

    if ($reaction) {
        return response()->json(['isHeart' => true]);
    } else {
        return response()->json(['isHeart' => false]);
    }

}

Code for my Vue.js below

axios.defaults.headers.common['X-CSRF-TOKEN'] = document.head.querySelector('meta[name="csrf-token"]').content;
export default{
    data(){
        return{
            isFilled:false,
            isHeart:false,
        };
    },
    created(){
        axios.get('/posts/heart-status/${this.postId}')
        .then(response =>{
            console.log(response.data.isHeart)
            this.isFilled = response.data.isHeart;
        })
        .catch(function (error) {
          console.error(error);
        })
    },
    methods:{
        toggleFill(){
            if(this.isFilled){
                this.unheart();
                this.isFilled = false;
            }else{
                this.heart();
                this.isFilled = true;
                this.isHeart = true
      setTimeout(() => {
        this.isHeart = false;
      }, 1000);
            }
        },
        checkHeartStatus(){
        axios.get('/posts/heart-status/${this.postId}')
        .then(response =>{
            console.log(response.data.isHeart)
            this.isFilled = response.data.isHeart;
        })
        .catch(function (error) {
          console.error(error);
        })
    },
        heart(){
            axios.post('/posts/heart',{
                post_id: this.postId,
            })
            .then(response =>{
                this.isFilled = true;
                this.isHeart = true
                console.log(response);
            })
            .catch(error =>{
                console.error(error);
            });
        },
        unheart(){
            axios.post('/posts/unheart',{
                post_id: this.postId
            })
            .then(response =>{
                this.isFilled = false;
                this.isHeart = false;
                console.log(response);
            })
            .catch(error =>{
                console.error(error);
            });
        }
    },
    props: {
        postId:{
            type: Number,
            required: true
        }
    }
};

</script>

So I want to get a response = true ,in this code but even though it has data it always return false.
And when i go to posts/heart-status/1 it will give me true, but then in the code above with the method created() it will give me false.

A: already know the problem, instead of using single quotes I use backticks
created(){
        axios.get(`/posts/heart-status/${this.postId}`)
        .then(response =>{
            console.log(response.data.isHeart)
            this.isFilled = response.data.isHeart;
        })
        .catch(function (error) {
          console.error(error);
        })
    },


text:
Q: Xamarin.Forms: How To Populate A Pie Chart From Web API Data? Good Day Everyone. I'm creating a Xamarin.Forms Portable Application. And I'm currently coding a PieChart (OxyPlot) that contains static data.
What I want to do is to have a Dynamic Data in every Pie Slice I have. Meaning, the data should come from my database.
I'm already able to retrieved data from my database and display it as a List in the Mobile Application that I'm creating using Web Api like this one :
ClientListPage.xaml
<?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="XamarinFormsDemo.Views.ClientListPage"
             xmlns:ViewModels="clr-namespace:XamarinFormsDemo.ViewModels;assembly=XamarinFormsDemo"
             xmlns:controls="clr-namespace:ImageCircle.Forms.Plugin.Abstractions;assembly=ImageCircle.Forms.Plugin.Abstractions"
             BackgroundImage="bg3.jpg"
             Title="Client List1">

<StackLayout>

  <SearchBar Placeholder="Search" Text="{Binding Keyword}" SearchCommand="{Binding SearchCommand}" x:Name="txtSearch" />

    <ListView ItemsSource="{Binding CustomerList, Mode=TwoWay}"
              HasUnevenRows="True"
              IsPullToRefreshEnabled="True"
              x:Name="listView">

      <ListView.ItemTemplate>
        <DataTemplate>
          <ViewCell>
            <Grid Padding="10" RowSpacing="10" ColumnSpacing="5">
              <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="*"/>
              </Grid.RowDefinitions>
              <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="*"/>
              </Grid.ColumnDefinitions>

              <controls:CircleImage Source="icon.png"
                     HeightRequest="66"
                     HorizontalOptions="CenterAndExpand"
                     Aspect="AspectFill"
                     WidthRequest="66"
                     Grid.RowSpan="2"
                   />

              <Label Grid.Column="1"
                     Text="{Binding CUSTOMER_NAME}"
                     TextColor="#24e97d"
                     FontSize="24"/>

              <Label Grid.Column="1"
                      Grid.Row="1"
                       Text="{Binding CUSTOMER_CODE}"
                       TextColor="White"
                       FontSize="18"
                       Opacity="0.6"/>

              <Label Grid.Column="1"
                  Grid.Row="2"
                  Text="{Binding CUSTOMER_MOBILE_NUMBER}"
                   TextColor="White"
                   FontSize="18"
                   Opacity="0.6"/>

              <Label Grid.Column="1"
                  Grid.Row="3"
                  Text="{Binding CUSTOMER_EMAIL_ADDRESS}"
                   TextColor="White"
                   FontSize="18"
                   Opacity="0.6"/>

            </Grid>
          </ViewCell>
        </DataTemplate>
      </ListView.ItemTemplate>

    </ListView>
</StackLayout>

</ContentPage>

ClientListPage.xaml.cs
using Newtonsoft.Json;
using OxyPlot;
using OxyPlot.Series;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Xamarin.Forms;
using XamarinFormsDemo.Models;
using XamarinFormsDemo.ViewModels;

namespace XamarinFormsDemo.Views
{
    public partial class ClientListPage : ContentPage
    {

        CustomerVM viewModel;
        public ClientListPage()
        {
            NavigationPage.SetHasNavigationBar(this, true);

            InitializeComponent();
            viewModel = new CustomerVM();
            BindingContext = viewModel;
        }

        async override protected void OnAppearing()
        {
            base.OnAppearing();

            var json = await GetCustomerAsync();

            var customers = JsonConvert.DeserializeObject<Customer[]>(json);

            foreach (Customer c in customers)
                viewModel.CustomerList.Add(c);
        }

        async Task<string> GetCustomerAsync()
        {
            var client = new HttpClient();

            client.BaseAddress = new Uri("http://192.168.1.11:50857/");

            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage response = await client.GetAsync("api/Customer");
            if (response.IsSuccessStatusCode)
            {
                return await response.Content.ReadAsStringAsync();
            }
            else return response.ReasonPhrase;
        }

    }
}

CustomerVM.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Xamarin.Forms;
using XamarinFormsDemo.Models;
using XamarinFormsDemo.Services;
using XamarinFormsDemo.Views;

namespace XamarinFormsDemo.ViewModels
{
    public class CustomerVM : INotifyPropertyChanged
    {

        private ObservableCollection<Customer> _customerList; // keep all customers
        private ObservableCollection<Customer> _searchedCustomerList; // keep a copy for searching
        private Customer _selectedCustomer = new Customer();

        private string _keyword = "";
        public string Keyword
        {
            get
            {
                return _keyword;
            }
            set
            {
                this._keyword = value;

                // while keyword changed we filter Employees
                //Filter();
            }
        }

        public ObservableCollection<Customer> CustomerList
        {
            get
            {
                return _customerList;
            }
            set
            {
                _customerList = value;
                OnPropertyChanged();
            }
        }

        public CustomerVM()
        {
            CustomerList = new ObservableCollection<Customer>();
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            var handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }

    }
}

But this time, I need to do it in a PieChart.
I really don't have an idea how to do this. But I think the way I retrieved the data from my WEB API above has similarity on how am I going to do this in my chart. Hope you can help me.
Thanks a lot. These are some of my codes :
SalesPerProductViewModel.cs
using OxyPlot;
using OxyPlot.Annotations;
using OxyPlot.Axes;
using OxyPlot.Series;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using XamarinFormsDemo.Models;

namespace XamarinFormsDemo.ViewModels
{
    public class SalesPerProductViewModel : INotifyPropertyChanged
    {

        private ObservableCollection<Sales> _salesList; // keep all customers

        public ObservableCollection<Sales> SalesPerProductModel
        {
            get
            {
                return _salesList;
            }
            set
            {
                _salesList = value;
                OnPropertyChanged();
            }
        }

        public SalesPerProductViewModel()
        {

            SalesPerProductModel = new ObservableCollection<Sales>();

        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

    }
}

SalesPerProductPage.xaml (This is where the dynamic chart should be displayed)
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:oxy="clr-namespace:OxyPlot.Xamarin.Forms;assembly=OxyPlot.Xamarin.Forms"
             xmlns:ViewModels="clr-namespace:XamarinFormsDemo.ViewModels;assembly=XamarinFormsDemo"
             x:Class="XamarinFormsDemo.Views.SalesPerProductPage"
             BackgroundImage="bg3.jpg"
             Title="Sales Per Product">

  <ContentPage.BindingContext>
    <ViewModels:SalesPerProductViewModel/>
  </ContentPage.BindingContext>

  <Label Text="TOTAL SALES LABEL HERE!"
       TextColor="#24e97d"/>

    <oxy:PlotView Model="{Binding SalesPerProductModel}" />
</ContentPage>

SalesPerProductPage.xaml.cs
using OxyPlot;
using OxyPlot.Xamarin.Forms;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XamarinFormsDemo.ViewModels;
using Xamarin.Forms;
using XamarinFormsDemo.Models;
using Newtonsoft.Json;
using System.Net.Http;
using System.Net.Http.Headers;
using OxyPlot.Series;

namespace XamarinFormsDemo.Views
{
    public partial class SalesPerProductPage : ContentPage
    {
        private PlotModel modelForSales;
        SalesPerProductViewModel viewModelforSales;

        public SalesPerProductPage()
        {
            InitializeComponent();
            viewModelforSales = new SalesPerProductViewModel();
            BindingContext = viewModelforSales;

        } //end of SalesPerProductPage()

        async override protected void OnAppearing()
        {
            base.OnAppearing();

            var json = await GetSalesPerProductAsync();

            var salesPerProduct = JsonConvert.DeserializeObject<Sales[]>(json);

            modelForSales = new PlotModel
            {
                Title = "Sales Per Product",
                TitleColor = OxyColors.Teal,
                TitleFontSize = 30,
                TextColor = OxyColors.White,
                DefaultFont = "Arial Black",
                DefaultFontSize = 20

            };

            dynamic seriesP2 = new PieSeries { StrokeThickness = 2.0, InsideLabelPosition = 0.8, AngleSpan = 360, StartAngle = 0 };

            foreach (Sales c in salesPerProduct)
            {
                seriesP2.Slices.Add(new PieSlice(c.PRODUCT_CODE, c.PRODUCT_ID) { IsExploded = false, Fill = OxyColors.Teal });
            }

            modelForSales.Series.Add(seriesP2);
            this.SalesPerProductModel = modelForSales;
        }

        public PlotModel SalesPerProductModel { get; private set; }

        async Task<string> GetSalesPerProductAsync()
        {
            var client = new HttpClient();

            client.BaseAddress = new Uri("http://192.168.1.11:50857/");

            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage response = await client.GetAsync("api/Sales");
            if (response.IsSuccessStatusCode)
            {
                return await response.Content.ReadAsStringAsync();
            }
            else return response.ReasonPhrase;
        }

    }
}

Sales.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace XamarinFormsDemo.Models
{
    public class Sales
    {
        public int Id { get; set; }
        public int ORDER_ID { get; set; }
        public int ORDER_DETAILS_ID { get; set; }
        public int PRODUCT_ID { get; set; }
        public string PRODUCT_CODE { get; set; }
        public string NET_AMOUNT { get; set; }
    }
}

A: You're assigning your PlotModel to a local variable. You must assign it to your ViewModel. Here's your refactored working code:
SalesPerProductPage.xaml:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:oxy="clr-namespace:OxyPlot.Xamarin.Forms;assembly=OxyPlot.Xamarin.Forms"
             xmlns:local="clr-namespace:App1"
             x:Class="App1.SalesPerProductPage">

  <ContentPage.Content>
      <oxy:PlotView Model="{Binding SalesPerProductModel}"></oxy:PlotView>
  </ContentPage.Content>

</ContentPage>

SalesPerProductPage.xaml.cs:
public partial class SalesPerProductPage : ContentPage
{
    public SalesPerProductViewModel viewModelforSales { get; set; }

    public SalesPerProductPage()
    {
        InitializeComponent();

        viewModelforSales = new SalesPerProductViewModel();
        BindingContext = viewModelforSales;
    }

    async protected override void OnAppearing()
    {
        base.OnAppearing();

        var json = await GetSalesPerProductAsync();

        var salesPerProduct = JsonConvert.DeserializeObject<Sales[]>(json);

        PlotModel modelForSales = new PlotModel
        {
            Title = "Sales Per Product",
            TitleColor = OxyColors.Teal,
            TitleFontSize = 30,
            TextColor = OxyColors.White,
            DefaultFont = "Arial Black",
            DefaultFontSize = 20

        };

        dynamic seriesP2 = new PieSeries { StrokeThickness = 2.0, InsideLabelPosition = 0.8, AngleSpan = 360, StartAngle = 0, FontSize = 24 };

        foreach (Sales c in salesPerProduct)
        {
            seriesP2.Slices.Add(new PieSlice(c.PRODUCT_CODE, c.PRODUCT_ID));
        }

        modelForSales.Series.Add(seriesP2);
        viewModelforSales.SalesPerProductModel = modelForSales;
    }

    async Task<string> GetSalesPerProductAsync()
    {
        var client = new HttpClient();

        client.BaseAddress = new Uri("http://10.0.0.17:64550/");

        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        HttpResponseMessage response = await client.GetAsync("api/Sales");
        if (response.IsSuccessStatusCode)
        {
            return await response.Content.ReadAsStringAsync();
        }
        else return response.ReasonPhrase;
    }
}

SalesPerProductViewModel:
public class SalesPerProductViewModel : INotifyPropertyChanged
{

    public event PropertyChangedEventHandler PropertyChanged = delegate { };

    private PlotModel _salesPerProductModel;
    public PlotModel SalesPerProductModel
    {
        get
        {
            return _salesPerProductModel;
        }
        set
        {
            if (value != _salesPerProductModel)
            {
                _salesPerProductModel = value;
                PropertyChanged(this, new PropertyChangedEventArgs("SalesPerProductModel"));
            }
        }
    }

    public SalesPerProductViewModel()
    {
    }
}

A: When you parsed your json and populated the list to feed into the listview, you can do the same for populating the series in your viewmodel. Once you have a list of Customer objects, go through them and use their data to create the pie slices as necesarry.
Something among the lines of:
 var json = await GetCustomerAsync();
 var customers = JsonConvert.DeserializeObject<Customer[]>(json);

 dynamic seriesP1 = new PieSeries { StrokeThickness = 2.0, InsideLabelPosition = 0.8, AngleSpan = 360, StartAngle = 0 };

 foreach (Customer c in customers) {
    seriesP1.Slices.Add(new PieSlice(c.CustomerName, c.SomeValue) { IsExploded = false, Fill = OxyColors.Teal });
 }

I do not know what your Customer class looks like, what values you want to show, etc. So keep that in mind. This is just an example of what I mean.
Also, structure your code so you only make the Http call once, then use that list of customers for both the list and the chart, don't download the data twice just to show it in two different ways.


text:
Q: How to change tax label in cart? So I'm trying to change the tax name from 'tax' to 'calculating' in the cart based on whether the user is logged in or not.
I think I'm using the correct hook, but I'm unsure what object is referencing the label, tried looking at documentation but there's not much info on labels. Here's what I got so far, it's nothing really but it kind of illustrates what I had in mind.
I'm not that into Woocomerce, any help would be much appreciated.
Thanks
function check_text() {
  if (is_user_logged_in() === false) {
    echo "Calculating";
  }
}
add_filter('woocommerce_cart_totals_after_order_total', 'check_text');

A: i think you have to add following to change tax label on cart to your custom label in your theme/function.php file.
 `add_filter( 'woocommerce_countries_inc_tax_or_vat', function ()
   {
      return __( '(calculating)', 'woocommerce' );
   });`

i hope that this work for you and for any probelm feel free to ask.
Thank you


text:
Q: R - Use Optional Arguments in Nested Functions like 'kmeans' I am trying to create a function that uses dist and kmeans from tm package.
My aim is to give the opportunity for having arguments as lists, in the main one, such way it could be used as arguments on above-mentioned functions.
There is an example:
tmpClust<-function(corpora, dist.args=list(method = "manhattan"), k, kmeans.args=list(algorithm="Lloyd"))
{
    dtm<-DocumentTermMatrix(corpora)

    dm<-dist(dtm, dist.args)

    x<-kmeans(dm, k, kmeans.args)

    x$cluster
}
data(crude)
tmpClust(crude, k=3)

I get:

Error in kmeans(dm, k, kmeans.args) : 'iter.max' must be positive
In addition: Warning message:
  In kmeans(dm, k, kmeans.args) : NAs introduced by coercion

And if I modify, on tmpClust, to kmeans.args=list(), I have:

Error in if (is.na(iter.max) || iter.max < 1L) stop("'iter.max' must be positive") :
    missing value where TRUE/FALSE needed

What I need to solve this?
I had tried use ellipsis but with no success.


text:
Q: How can I see the magnitude and frequency of a signal (DFT) in PLECS? I am trying to obtain the Fourier transform of a signal by using the DFT of PLECS but I got some weird results.
Here is a very simple sinewave generator and the DFT block:
DFT_plecs_1

Here are the results on the scope:
DFT_plecs_2

A: The fundamental frenquency of DFT block should always equal to 1 Hz which is the fundamental frequency of your signal. That means, if Ts is 1/8s, then the number of samples should be 8, if you increase Ts to 1/2s, then the number should be 2.


text:
Q: Debug python that wont respect a catch statement I am trying to run avg as part of a program.  The program normally is executed automatically, so I cant see the standard output from python.
When I run the program by calling it directly, it works perfectly, however when I run it via automation, it fails.
It will say in the syslog -> "Starting scan of: xxx", but it never says "Unexpected error" OR "Scan Results".  Which means, its failing, but not using the catch statement, or reporting the error in the "out" variable.
The offending function:
# Scan File for viruses
# fpath -> fullpath, tname -> filename, tpath -> path to file
def scan(fpath, tname, tpath):
    syslog("Starting scan of: " + tname)
    command = ["avgscan",
          "--report=" + tpath + "scan_result-" + tname +".txt",
          fpath]
    try:
        out = subprocess.call(command)
        syslog("Scan Results: " + str(out))
    except:
        syslog("Unexpected error: " + sys.exc_info()[0])
    finally:
        syslog("Finished scan()")

Both idea's so far are around the debugging code itself, prior to this, the scan was just a simple subprocess.call(command) with a simple syslog output.  The with statement, the try catch was added to help the debugging.

A: I am suspecting the error is actually from the opening of the debug file; with statements do not prevent exceptions from being raised. In fact, they usually raise exceptions of their own.
Note the change of the scope of the try/except block.
# Scan File for viruses
# fpath -> fullpath, tname -> filename, tpath -> path to file
def scan(fpath, tname, tpath):
    syslog("Starting scan of: " + tname)
    command = ["avgscan",
        "--report=" + tpath + "scan_result-" + tname +".txt",
        fpath]
    try:
        with open(tpath + tname + "-DEBUG.txt", "w") as output:
            out = subprocess.call(command, stdout = output, stderr = output)
            syslog("Scan Results: " + str(out))
    except:
        syslog("Unexpected error: " + sys.exc_info()[0])
    finally:
        syslog("Finished scan()")

A: So I solved it.  Solved it in so much as I am no longer using AVG Scan, and using libclamscan.
By using a scanner that works directly with python, the results are faster, and errors are all gone.  In case someone comes across this via a search, here is the code I am now using:
import os.path
import pyclamav.scanfile

def r_scan(fpath):
    viruslist = []
    if os.path.isfile(fpath):
        viruslist = f_scan(fpath, viruslist)
    for root, subFolders, files in os.walk(fpath):
        for filename in files:
            viruslist = f_scan(
                             os.path.join(root, filename), viruslist)
    writeReport(fpath, viruslist)

def f_scan(filename, viruslist):
    result = pyclamav.scanfile(filename)
    if result[0] > 0:
        viruslist.append([result[1], filename])
    return viruslist

def writeReport(fpath, viruslist):
    header = "Scan Results: \n"
    body = ""
    for virusname, filename in viruslist:
        body = body + "\nVirus Found: " + virusname + " : " + filename

    with open(fpath + "-SCAN_RESULTS.txt", 'w') as f:
        f.write(header+body)


text:
Q: Guess game in C# and i can't make the number of the user guess to show when the game start I am creating a Guess game in C# and i can't make the number of the user guess to show when the game start which is 10, it will show only when the user already try 1 guess and it show 10 which in total the program will give the user 11 guesses, can you help me?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace GuessingGame
{
    public partial class Form1 : Form
{
    int _randnum;
    int _userguess;

    void GetRandomNumber()
    {
        int min = 1;
        int max = 101;
        Random randomiser;
        randomiser = new Random();

        _randnum = randomiser.Next(min, max);

    }
    public Form1()
    {
        InitializeComponent();
    }

    private void label1_Click(object sender, EventArgs e)
    {

    }

    private void buttonGuess_Click(object sender, EventArgs e)
    {
        string user = textBox1.Text;
        string guessnum = Convert.ToString(_userguess);
        int guess = 0;

        if (int.TryParse(user, out guess))
        {
            if (_userguess == 0)
            {
                buttonGuess.Enabled = false;
                label3.Text = "Game Over";
            }

            else if (guess == _randnum)
            {
                label3.Text = "Good guess";
                buttonGuess.Enabled = false;

            }
            else if (guess < _randnum)
            {
                label3.Text = "Too low guess";
                _userguess--;

            }
            else if (guess > _randnum)
            {
                label3.Text = "Too High guess";
                _userguess--;
            }
            else if (guess < 0 || guess > 100)
            {
                label3.Text = "Your guess is out of the range";
                _userguess--;
            }
        }
        else
        {
            label3.Text = "Yous should introduce a number";
            _userguess--;
        }
        label2.Text = guessnum;
    }

    private void buttonExit_Click(object sender, EventArgs e)
    {
        Application.Exit();
    }

    private void textBox1_TextChanged(object sender, EventArgs e)
    {

    }

    private void Form1_Load(object sender, EventArgs e)
    {
        GetRandomNumber();
        _userguess = 10;
    }

    private void buttonNew_Game_Click(object sender, EventArgs e)
    {
        GetRandomNumber();
        buttonGuess.Enabled = true;
        _userguess = 10;
    }
}

}

A: What you can do is have a NewGame function which does the game setup and gets rid of the text in label2, and sets the guess counter to 11.
private void NewGame()
{
    GetRandomNumber();
    buttonGuess.Enabled = true;
    label2.Text = string.Empty;
    _userguess = 11;
}

Then you can use this in both the Form Load and New Game Button Click functions:
private void Form1_Load(object sender, EventArgs e)
{
    NewGame();
}

private void buttonNew_Game_Click(object sender, EventArgs e)
{
    NewGame();
}

A: You are Setting the guessnum string at the wrong point. You want it to show the number after the if statement, so you schould set the variable after the if statement. If you set the String before the if statement it gets the inital value of _userguess, which is 10.
To show 10 in the beginning of the game you have to set the text of label2 also when you start a new game.
If you want to let guessnum put out the correct string every time you call it. You should make it a property or method.
private string guessnum{ get{ return _userguess.ToString(); } }


text:
Q: Can I automatically add shared examples to certain tests? I would like to run a shared example automatically if the described_class matches some description.
For example, when I have a module I often write a shared example and include it into anything which includes the module.
module ExtraStuff
  def self.stuff
    42
  end
end

class Thing
  include ExtraStuff
end

shared_examples ExtraStuff do
  it 'has stuff' do
    expect( described_class.stuff ).to eq 42
  end
end

describe Thing do
  it_behaves_like ExtraStuff
end

But sometimes I forget. Or it's included into many classes and its tedious to add it_behaves_like to every class.
config.before does not work because "it_behaves_like is not available from within an example (e.g. an it block) or from constructs that run in the scope of an example (e.g. before, let, etc)".


text:
Q: Getting the recordset into an XML using VBScript My SQL query returns a single column result which is actually an XML. When I click on the recordset, it opens up a results.xml.
This is the output XML I am grabbing into result_string by using
result_string = objRecordSet.Fields(colname).Value

<TEST_SUITE SUITE_ID="122675741" PART_NUMBER="MTSTE-26248-00" REVISION="A"     SUITE_TYPE="PRODUCTION" SUITE_NAME="HOT-LOW" SUITE_STOP_ON_FAIL="TRUE" TARGET_DURATION="0" SEQUENCE="1" UPDATED="2016-12-15T00:21:46.510">
  <SUITE_DESCRIPTION>"HOT-LOW"</SUITE_DESCRIPTION>
  <TESTS>
    <TEST TEST_ID="122663528" TEST_NAME="Set Suite Environment Variables" PART_NUMBER="MTTST-65899-00" REVISION="A" MODULE="TEST Set Environment Variables.vi" MODULE_LIBRARY="BIG-IP_TESTS" TEST_STOP_ON_FAIL="TRUE"   TEST_TYPE="BEGIN_SESSION">
      <PARAMETERS>
        <PARAMETER PARAMETER_ID="122663469" PARAMETER_NAME="TOS" PARAMETER_VALUE="build_2.0.1.1647.0_centos6_x86_64" />
        <PARAMETER PARAMETER_ID="82137" PARAMETER_NAME="chain" PARAMETER_VALUE="TRUE" />
      </PARAMETERS>
      <MEASUREMENTS>
        <MEASUREMENT MEASUREMENT_ID="70784" MEASUREMENT_NAME="TOS" UNITS="" UPPER_LIMIT="" LOWER_LIMIT="" COMPARISON="LOG" INPUT_SCALE_FACTOR="" OUTPUT_SCALE_FACTOR="" />
        <MEASUREMENT MEASUREMENT_ID="81537" MEASUREMENT_NAME="chain" UNITS="" UPPER_LIMIT="" LOWER_LIMIT="" COMPARISON="LOG" INPUT_SCALE_FACTOR="" OUTPUT_SCALE_FACTOR="" />
      </MEASUREMENTS>
    </TEST>
  </TESTS>
</TEST_SUITE>

from this I need one Test_ID. How can I store into XML this result_string and get the Test_ID. Or is there any easy way to get the Test_ID?
I did something like this, but not sure if this is correct, and also I am getting an error on line objCommand.Execute ,, adExecuteStream.
Dim strm
Set strm = CreateObject("ADODB.Stream")

strm.Open

Set objCommand.ActiveConnection = objConnection
objCommand.CommandText = script_testID
objCommand.Properties("Output Stream")= strm
objCommand.Properties("Output Encoding") = "UTF-8"
objCommand.Properties("XML Root") = "Root"  'this can be anything you want

objCommand.CommandType = 4
objCommand.Execute ,, adExecuteStream
strm.Position = 0
text = strm.ReadText
Set xmlDoc = CreateObject("Microsoft.XMLDOM")
xmlDoc.Async = "false"

xmlDoc.LoadXML(strm.ReadText)
strm.Close : Set strm = Nothing
Set objCommand = Nothing

A: You're already parsing the XML data, so you can easily extract the value like this:
...
xmlDoc.LoadXML(strm.ReadText)

test_id = xmlDoc.SelectSingleNode("//TEST/@TEST_ID").Value
...

I would recommend using Msxml2.DOMDocument instead of the deprecated Microsoft.XMLDOM, though, and I also recommend checking for parse errors before working with the data:
...
Set xmlDoc = CreateObject("Msxml2.DOMDocument.6.0")
xmlDoc.Async = False
xmlDoc.LoadXML strm.ReadText

If xmlDoc.ParseError <> 0 Then
    WScript.Echo xmlDoc.ParseError.Reason
    WScript.Quit 1
End If

test_id = xmlDoc.SelectSingleNode("//TEST/@TEST_ID").Value
...

Note that the XPath expression (//TEST/@TEST_ID) is case-sensitive.

A: test_id = Split(Split(result_string, "TEST_ID=""", 2)(1), """", 2)(0)


text:
Q: PHP thinks my variable is undefined. My instructor wrote exactly the same and it works just fine for him. I'm lost Here's the issue:
Notice: Undefined variable: schoolmarks in /Applications/XAMPP/xamppfiles/htdocs/Side-Projects/Formation Complete Développeur Web/PHP/cours/PHP 2/2-Objects.php on line 20
In Maths, I had global /20.
And my code:

<?php
    class Student {
        public $activeStudent = TRUE; // we set $activeStudent to TRUE by default
        public $name;
        public $age;
        public $schoolmarks;

        // function construct allows to create a new instance or object
        // Let's make our new instance and make it have the above properties
        public function __construct($name, $age, $schoolmarks) {
            // '$this' means this exact object, that we're using right here
            $this->name = $name;
            $this->age = $age;
            $this->schoolmarks = $schoolmarks;
        }
        public function introducesHimself() {
            if($this->activeStudent) {
                echo "My name is $this->name and I have $this->age" . "yo.
";
                foreach($this->schoolmarks as $classe => $mark) {
                    echo "In $classe, I had global $schoolmarks/20.
";
                }
            }
        }
    }

    $schoolmarksofJames = array('Maths' => 15, 'French' => 12, 'English' => 18, 'HTML' => 17, 'Javascript' => 11);
    $James = new Student("James", "25", $schoolmarksofJames);
    $James->introducesHimself();

    echo '

';

    $schoolmarksofHarrys = array('Philosophy' => 15, 'Chinese' => 12, 'English' => 18, 'HTML' => 17, 'PHP' => 11);
    $Harrys = new Student("Harrys", "21", $schoolmarksofHarrys);
    $Harrys->introducesHimself();
?>


text: Q: Как связать heroku и nic.ru? Я впервые пытаюсь это сделать, поэтому возникли проблемы. Для начала я, конечно, прочитал про dns, что это и зачем. Купил DNS-хостинг на nic.ru, как и сам домен, конечно. Как было сказано в одном руководстве, я добавил запись вида "www CNAME example.herokudns.com". Подождал сутки, но ничего не изменилось. В другом руководстве было сказано, что нужно сделать запись вида "www CNAME mydomain.ru.", но, опять же, не получилось. Да, я еще плохо разбираюсь в различных видах DNS записях, но помогите, пожалуйста, на данном этапе. Что я делаю не так?


text:
Q: Permissions Error #200 on creating new blank Custom Audience through FB Ads API I am getting the following error when trying to create a new blank Custom Audience through the Facebook Ads API. I have a whitelisted APP_ID. The ads_management extended permission is enough? The user must be an Administrator of the ads account to be able to do it?
{
"error"=>{
    "message"=>"(#200) Permissions error",
    "type"=>"OAuthException",
    "code"=>200
}
}

A: You have to use the power editor and start to create a new custom audience and accept the TOS before you are able to do it through the API the first time.


text:
Q: Calling/Choosing a Random Function with PHP I have two functions that parse data and store a random item in an array. Now I want to implement logic that chooses one of these functions at random when executed via PHP. How can I achieve this?
My functions:
ReadQuote($csvFile, $arrayForStorage);
GetRandomURL($pageURL, $arrayForStorage);

I don't think the code is necessary for each of these functions, but if it is needed I will display it. Pretty lengthy though.

A: Like this?
if (mt_rand(0, 100) < 50)
  ReadQuote($csvFile, $arrayForStorage);
else
  GetRandomURL($pageURL, $arrayForStorage);


text:
Q: How to type only the first positional parameter of a Protocol method and let the others be untyped? Problem
How to only type the first positional parameter of a Protocol method and let the others be untyped?
Example, having a protocol named MyProtocol that has a method named my_method that requires only the first positional parameter to be an int, while letting the rest be untyped.
the following class would implement it correctly without error:
class Imp1(MyProtocol):
  def my_method(self, first_param: int, x: float, y: float) -> int:
    return int(first_param - x + y)

However the following implementation wouldn't implement it correctly, since the first parameter is a float:
class Imp2(MyProtocol):
  def my_method(self, x: float, y: float) -> int: # Error, method must have a int parameter as a first argument after self
    return int(x+y)

I thought I would be able to do that with *args, and **kwargs combined with Protocol like so:
from typing import Protocol, Any

class MyProtocol(Protocol):
    def my_method(self, first_param: int, /, *args: Any, **kwargs: Any) -> int:
        ...

But (in mypy) this makes both Imp1 and Imp2 fail, because it forces the method contract to really have a *args, **kwargs like so:
class Imp3(MyProtocol):
    def my_method(self, first_param: int, /, *args: Any, **kwargs: Any) -> int:
        return first_param

But this does not solves what I am trying to achieve, that is make the implementation class have any typed/untyped parameters except for the first parameter.
Workaround
I manged to circumvent the issue by using an abstract class with a setter set_first_param, like so:
from abc import ABC, abstractmethod
from typing import Any

class MyAbstractClass(ABC):
    _first_param: int

    def set_first_param(self, first_param: int):
        self._first_param = first_param

    @abstractmethod
    def my_method(self, *args: Any, **kwargs: Any) -> int:
        ...

class AbcImp1(MyAbstractClass):
    def my_method(self, x: float, y: float) -> int:
        return int(self._first_param + x - y) # now i can access the first_parameter with self._first_param

But this totally changes the initial API that I am trying to achieve, and in my opinion makes less clear to the implementation method that this parameter will be set before calling my_method.
Note
This example was tested using python version 3.9.13 and mypy version 0.991.

A: One reasonable workaround would be to make the method take just the typed arguments, and leave the untyped arguments to a callable that the method returns. Since you can declare the return type of a callable without specifying the call signature by using an ellipsis, it solves your problem of leaving those additional arguments untyped:
from typing import Protocol, Callable

class MyProtocol(Protocol):
    def my_method(self, first_param: int) -> Callable[..., int]:
        ...

class Imp1(MyProtocol):
  def my_method(self, first_param: int) -> Callable[..., int]:
      def _my_method(x: float, y: float) -> int:
          return int(first_param - x + y)
      return _my_method

print(Imp1().my_method(5)(1.5, 2.5)) # outputs 6

Demo of the code passing mypy:
https://mypy-play.net/?mypy=latest&python=3.12&gist=677569f73f6fc3bc6e44858ef37e9faf

A: If your MyProtocol can accept any number of arguments, you cannot have a subtype (or implementation) which accepts a set number, this breaks the Liskov substitution principle as the subtype only accepts a limited set of cases accepted by the supertype.
[original paragraph]
Then, if you keep on inheriting from Protocol, you keep on making protocols, protocols are different from ABCs, they use structural subtyping (not nominal subtyping), meaning that as long as an object implements all the methods/properties of a protocol it is an instance of that protocol (see PEP 544 for more details).
[end original paragraph]
[edit upon further reading]
In my opinion, protocols should only be inherited by other protocols which will be used with structural subtyping. For nominal subtyping (which for instance allows default implementation) I would use ABCs.
[edit upon further reading]
Without more detail on the implementations you'd want to use, @blhsing's solution is probably the most open because it does not type the Callable's call signature.
Here is a set of implementations around a generic protocol with contravariant types (bound to float as it is the top of the numeric tower), which would allow any numeric type for the two x and y arguments.
from typing import Any, Generic, Protocol, TypeVar

T = TypeVar("T", contravariant=True, bound=float)
U = TypeVar("U", contravariant=True, bound=float)

class MyProtocol(Protocol[T, U]):
    def my_method(self, first_param: int, x: T, y: U) -> int:
        ...

class ImplementMyProtocol1(Generic[T, U]):
    """Generic implementation, needs typing"""
    def my_method(self, first_param: int, x: T, y: U) -> int:
        return int(first_param - x + y)

class ImplementMyProtocol2:
    """Float implementation, and ignores first argument"""
    def my_method(self, _: int, x: float, y: float) -> int:
        return int(x + y)

class ImplementMyProtocol3:
    """Another float implementation, with and extension"""
    def my_method(self, first_param: int, x: float, y: float, *args: float) -> int:
        return int(first_param - x + y + sum(args))

def use_MyProtocol(inst: MyProtocol[T, U], n: int, x: T, y: U) -> int:
    return inst.my_method(n, x, y)

use_MyProtocol(ImplementMyProtocol1[float, float](), 1, 2.0, 3.0)  # OK MyProtocol[float, float]
use_MyProtocol(ImplementMyProtocol1[int, int](), 1, 2, 3)  # OK MyProtocol[int, int]
use_MyProtocol(ImplementMyProtocol2(), 1, 2.0, 3.0)  # OK MyProtocol[float, float]
use_MyProtocol(ImplementMyProtocol3(), 1, 2.0, 3.0)  # OK MyProtocol[float, float]

A: *

*Signature of method 'Imp1.my_method()' does not match signature of the base method in class 'MyProtocol'
must be I suppose
 class Imp1(MyProtocol):
     def my_method(self, first_param: int, *args: Any, **kwargs: Any) -> int:
         ...

*Yours Imp2 the same as in Imp1 but does not even have first named parameter.


text:
Q: Cannot access text file in ASP.Net MVC 3 test project I am trying to access a text file in asp.net mvc3 test project, the common way I know to access it is through HttpContext class like this
HttpContext.Current.Server.MapPath("Temp.txt");
But it returns "Current" as null!
After a little search I found few reasons of Current being null, in my case it is I guess using a router handler to route requests.
But not getting the way to do it for my case.
Can anyone help me on that?

A: HttpContext is not available on test context, only on web enviroment. You need an HttpContext stub. Avoid this direct dependence.
http://vkreynin.wordpress.com/2009/03/23/stub-htttpcontext/


text:
Q: Checking a Google user's gtalk buddies Presence status in my GAE application, when he's logged in I'm creating a GAE application, as a part of which, we wish to show logged in Google user - his gtalk buddies list and their presence status.
Google XMPP API let you create bots, but user's gtalk buddies need not share invitation with the app.
Simple things I want to achieve in a GAE application:
1) I authorize using oAuth.
2) Using the token, I fetch that user's gtalk buddies presence and show to him in my GAE app.
Please help!

A: The XMPP API on App Engine does not provide that functionality.  It cannot operate on behalf of any arbitray user.
You'll have to look into using another XMPP library.


text:
Q: show javascript alert from controller's action in asp.net mvc Is it possible to show a javascript alert message from controller's action in asp.net mvc(C#)?

A: You could pass a variable to the view. If it exists or is set to true, execute your javascript...

A: No, controller actions are executed on the server side. Wheras Javascript is executed on the client side.


text:
Q: Number of running clients in GWT Application? I have a GWT client-server application and I want to display the number of running clients in the clients browser title. I know how to track the number of connecting clients but how can I track the number of closed connections?
public class MyServiceImpl extends RemoteServiceServelt implements MyService
{
 [...]
 static int runningClients=0;
 @Override public Integer runningClients() {return ++runningClients;}
 // TODO: track closed connections
}

Edit: As suggested, I implemented an HTTPSessionListener. Unfortunately, it always returns 0 for both hits and connectedClients.
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class ActiveClientsListener implements HttpSessionListener
{
    private static long hits = 0;
    private static long numberOfConnectedClients = 0;

    public static long hits() {return hits;}
    public static long numberOfConnectedClients() {return numberOfConnectedClients;}

    @Override public synchronized void sessionCreated(HttpSessionEvent arg0)
    {
        hits++;
        numberOfConnectedClients++;
    }

    @Override public synchronized void sessionDestroyed(HttpSessionEvent arg0)
    {
        numberOfConnectedClients--;
    }
}

web.xml
...
<listener>
 <listener-class>org.mypackage.server.ActiveClientsListener</listener-class>
</listener>
...

P.S.: Is my implementation threadsafe or do I have to make the fields volatile or synchronize differently?

A: Assuming that each connected client opens a session, I think I would use an HttpSessionListener for that purpose.
When a session is created, you increase a counter, whenever it is destroyed, decrease it. Make sure that you synchronize the access to the variable.
Of course, the counter will decrease whenever the session times out which is probably "too late". However, you could probably improve this by explicitly destroying the session (session.invalidate()) when a user leaves your application (using addWindowClosingHandler).


text:
Q: How to write a binary struct using python that can be read in c? say a struct like this:
typedef struct testVertex_s {
       char *vert_name; //for test only...
       float x;
       float y;
       float z;
}testvertex_t;

how to write that to a binary file use python ?  I want to read it using fread in c;

A: Why must it be binary? Text is trivial, and much simpler to interact with.
If you really want binary, use the struct module. Make sure to define your endianness, and read each field separately in C, do not try to do a single fread() into a C structure.
You could do the packing like so:
import struct
out = open("myvertex.bin", "wb")
string = "hello"
fmt = "<%usfff" % (1 + len(string))
out.write(struct.pack(fmt, string, 3.14, 47.11, 17))

This writes the string as a plain 0-terminated string, followed immediately by the floats. The resulting data from the above is "hello\x00\xc3\xf5H@\xa4p<B\x00\x00\x88A" (represented as a Python string literal).
For this case, you're going to need to dynamically allocate the string of course, which should be obvious.


text:
Q: Align div elements at the next line What I need is a grid of pictures. The first line of four pictures is looking great. But I can't find the solution to arrange the second line. Well, I know I can use the ul li along with the display: inline-block and vertical-align: text-top; but I want the div solution.
Thank You.

.partners
{
margin: 77px auto 0 auto;
overflow: auto;
text-align: center;
width: 940px;
}
.partners__h2
{
color: #333;
font-size: 22px;
font-weight: bold;
margin-bottom: 32px;
text-align: center;
}
.partner__pic__wrap
{
height: 120px;
margin: 0 auto;
position: relative;
width: 120px;
}
.partner__icon
{
background-repeat: no-repeat;
background-size: cover;
border: 4px solid #fff;
border-radius: 50%;
bottom: -5px;
height: 32px;
position: absolute;
right: -4px;
width: 32px;
z-index: 1;
}
.partner__pic__hover:hover
{
filter: alpha(opacity=70);
opacity: 0.7;
}
.partner__wrap
{
bottom: 0;
text-align: center;
width: 100%;
}
.partner__name
{
color: #333;
display: block;
float: left;
font-size: 14px;
font-weight: bold;
margin-bottom: 0px;
width: 100%;
}
.partner__description
{
color: #666;
float: left;
font-family: Roboto;
font-size: 14px;
font-weight: 300;
margin-top: 10px;
text-align: center;
}
.partner__1
{
float: left;
height: 100%;
position: relative;
width: 221px;
}
.partner__1__icon
{
background-color: #ff4e50;
background-image: url('http://www.q-park.co.uk/DesktopModules/QPark.AdvancedPFL/image.aspx?ServiceID=49');
}
.partner__1__pic
{
background-image: url('http://cdn.bmwblog.com/wp-content/uploads/BMW-M235i-racing-car-las-vegas-02-120x120.jpg');
background-position: center;
border-radius: 50%;
float: left;
height: 120px;
moz-border-radius: 50%;
webkit-border-radius: 50%;
width: 120px;
}
.partner__2
{
float: left;
height: 100%;
margin-left: 19px;
position: relative;
width: 221px;
}
.partner__2__icon
{
background-color: #1cd7ad;
background-image: url('http://www.q-park.co.uk/DesktopModules/QPark.AdvancedPFL/image.aspx?ServiceID=49');
}
.partner__2__pic
{
background-image: url('http://cdn.bmwblog.com/wp-content/uploads/BMW-M235i-racing-car-las-vegas-02-120x120.jpg');
background-position: center top;
border-radius: 50%;
float: left;
height: 120px;
moz-border-radius: 50%;
webkit-border-radius: 50%;
width: 120px;
}
.partner__3
{
float: left;
height: 100%;
margin-left: 19px;
position: relative;
width: 221px;
}
.partner__3__icon
{
background-color: #ffa507;
background-image: url('http://www.q-park.co.uk/DesktopModules/QPark.AdvancedPFL/image.aspx?ServiceID=49');
}
.partner__3__pic
{
background-image: url('http://cdn.bmwblog.com/wp-content/uploads/BMW-M235i-racing-car-las-vegas-02-120x120.jpg');
background-position: center top;
border-radius: 50%;
float: left;
height: 120px;
moz-border-radius: 50%;
webkit-border-radius: 50%;
width: 120px;
}
.partner__4
{
float: left;
height: 100%;
margin-left: 20px;
position: relative;
width: 219px;
}
.partner__4__icon
{
background-color: #4e73db;
background-image: url('http://www.q-park.co.uk/DesktopModules/QPark.AdvancedPFL/image.aspx?ServiceID=49');
}
.partner__4__pic
{
background-image: url('http://cdn.bmwblog.com/wp-content/uploads/BMW-M235i-racing-car-las-vegas-02-120x120.jpg');
background-position: center top;
border-radius: 50%;
float: left;
height: 120px;
moz-border-radius: 50%;
webkit-border-radius: 50%;
width: 120px;
}
.partner__5, .partner__6, .partner__7, .partner__8
{
float: left;
height: 100%;
position: relative;
width: 221px;
}

Lorem ipsum dolor sit amet, consectetuer

Lorem ipsum dolor

Lorem ipsum dolor sit amet, consectetuer

Lorem ipsum dolor

Lorem ipsum dolor sit amet, consectetuer

Lorem ipsum dolor

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa.

Lorem ipsum dolor

Lorem ipsum dolor sit amet, consectetuer

Lorem ipsum dolor

Lorem ipsum dolor sit amet, consectetuer

Lorem ipsum dolor

Lorem ipsum dolor sit amet, consectetuer

Lorem ipsum dolor

Lorem ipsum dolor sit amet, consectetuer

Lorem ipsum dolor

Lorem ipsum dolor sit amet, consectetuer

A: You need to give fixed height instead of 100% for all 8 blocks.
.partner__1, .partner__2, .partner__3, .partner__4, .partner__5, .partner__6, .partner__7, .partner__8 {
    height: 220px;
}

A: You can use flexbox
CSS
.partners__container {
    display: -webkit-flex;
    display: flex;
    -webkit-flex-flow: row wrap;
    flex-flow: row wrap;
}
.partners__container > div {
    -webkit-flex: 1 0 20%;
    flex: 1 0 20%;
}

DEMO HERE

A: you can try this one:
.partners__container {
    display: -webkit-flex;
    display: flex;
    -webkit-flex-flow: row wrap;
    flex-flow: row wrap;
}
.partners__container > div {
    -webkit-flex: 1 0 20%;
    flex: 1 0 20%;
}
.partners {
    width: 940px;
    text-align:center;
    margin: 77px auto 0 auto;
    overflow: auto;
}
.partners__h2 {
    color: #333;
    font-weight: bold;
    font-size: 22px;
    text-align: center;
    margin-bottom: 32px;
}
.partner__pic__wrap {
    width: 120px;
    height: 120px;
    margin: 0 auto;
    position: relative;
}
.partner__icon {
    border-radius: 50%;
    background-repeat: no-repeat;
    background-size: cover;
    width: 32px;
    height: 32px;
    position: absolute;
    bottom: -5px;
    right: -4px;
    z-index: 1;
    border: 4px solid #fff;
}
.partner__pic__hover:hover {
    opacity: 0.7;
    filter: alpha(opacity=70);
}
.partner__wrap {
    bottom: 0;
    width: 100%;
    text-align:center;
}
.partner__name {
    display: block;
    float:left;
    width:100%;
    font-weight: bold;
    color: #333;
    font-size: 14px;
    margin-bottom: 0px;
}
.partner__description {
    font-family: Roboto;
    font-weight: 300;
    color: #666;
    font-size: 14px;
    text-align: center;
    float:left;
    margin-top: 10px;
}
.partner__1 {
    float:left;
    width:221px;
    height: 100%;
    position: relative;
}
.partner__1__icon {
    background-image: url('http://www.q-park.co.uk/DesktopModules/QPark.AdvancedPFL/image.aspx?ServiceID=49');
    background-color: #ff4e50;
}
.partner__1__pic {
    background-image: url('http://cdn.bmwblog.com/wp-content/uploads/BMW-M235i-racing-car-las-vegas-02-120x120.jpg');
    background-position: center;
    float: left;
    width: 120px;
    height: 120px;
    -webkit-border-radius: 50%;
    -moz-border-radius: 50%;
    border-radius: 50%;
}
.partner__2 {
    float:left;
    width:221px;
    height: 100%;
    margin-left: 19px;
    position: relative;
}
.partner__2__icon {
    background-image: url('http://www.q-park.co.uk/DesktopModules/QPark.AdvancedPFL/image.aspx?ServiceID=49');
    background-color: #1cd7ad;
}
.partner__2__pic {
    background-image: url('http://cdn.bmwblog.com/wp-content/uploads/BMW-M235i-racing-car-las-vegas-02-120x120.jpg');
    background-position: center top;
    float: left;
    width: 120px;
    height: 120px;
    -webkit-border-radius: 50%;
    -moz-border-radius: 50%;
    border-radius: 50%;
}
.partner__3 {
    float:left;
    width:221px;
    height: 100%;
    margin-left: 19px;
    position: relative;
}
.partner__3__icon {
    background-image: url('http://www.q-park.co.uk/DesktopModules/QPark.AdvancedPFL/image.aspx?ServiceID=49');
    background-color: #ffa507;
}
.partner__3__pic {
    background-image: url('http://cdn.bmwblog.com/wp-content/uploads/BMW-M235i-racing-car-las-vegas-02-120x120.jpg');
    background-position: center top;
    float: left;
    width: 120px;
    height: 120px;
    -webkit-border-radius: 50%;
    -moz-border-radius: 50%;
    border-radius: 50%;
}
.partner__4 {
    float:left;
    width:219px;
    height: 100%;
    margin-left: 20px;
    position: relative;
}
.partner__4__icon {
    background-image: url('http://www.q-park.co.uk/DesktopModules/QPark.AdvancedPFL/image.aspx?ServiceID=49');
    background-color: #4e73db;
}
.partner__4__pic {
    background-image: url('http://cdn.bmwblog.com/wp-content/uploads/BMW-M235i-racing-car-las-vegas-02-120x120.jpg');
    background-position: center top;
    float: left;
    width: 120px;
    height: 120px;
    -webkit-border-radius: 50%;
    -moz-border-radius: 50%;
    border-radius: 50%;
}
.partner__5, .partner__6, .partner__7, .partner__8 {
    float:left;
    width:221px;
    height: 100%;
    position: relative;
}

DEMO FIDDLE

A:

.partners
{
 margin: 77px auto 0 auto;
 overflow: auto;
 text-align: center;
 width: 940px;
}
.partners__h2
{
 color: #333;
    font-size: 22px;
 font-weight: bold;
 margin-bottom: 32px;
 text-align: center;
}
.partner__pic__wrap
{
 height: 120px;
    margin: 0 auto;
 position: relative;
 width: 120px;
}
.partner__icon
{
 background-repeat: no-repeat;
 background-size: cover;
 border: 4px solid #fff;
 border-radius: 50%;
 bottom: -5px;
 height: 32px;
 position: absolute;
 right: -4px;
 width: 32px;
 z-index: 1;
}
.partner__pic__hover:hover
{
 filter: alpha(opacity=70);
 opacity: 0.7;
}
.partner__wrap
{
 bottom: 0;
 text-align: center;
 width: 100%;
}
.partner__name
{
 color: #333;
 display: block;
 float: left;
 font-size: 14px;
 font-weight: bold;
     margin-bottom: 0px;
     width: 100%;
}
.partner__description
{
 color: #666;
 float: left;
 font-family: Roboto;
 font-size: 14px;
 font-weight: 300;
 margin-top: 10px;
 text-align: center;
}
.partner
{
 float: left;
 height: 100%;
 position: relative;
 margin-left:10px;
 width: 221px;
}
.partner__1__icon
{
 background-color: #ff4e50;
 background-image: url('http://www.q-park.co.uk/DesktopModules/QPark.AdvancedPFL/image.aspx?ServiceID=49');
}
.partner__1__pic
{
     background-image: url('http://cdn.bmwblog.com/wp-content/uploads/BMW-M235i-racing-car-las-vegas-02-120x120.jpg');
     background-position: center;
 border-radius: 50%;
 float: left;
     height: 120px;
 moz-border-radius: 50%;
 webkit-border-radius: 50%;
 width: 120px;
}

.partner__2__icon
{
 background-color: #1cd7ad;
 background-image: url('http://www.q-park.co.uk/DesktopModules/QPark.AdvancedPFL/image.aspx?ServiceID=49');
}
.partner__2__pic
{
background-image: url('http://cdn.bmwblog.com/wp-content/uploads/BMW-M235i-racing-car-las-vegas-02-120x120.jpg');
background-position: center top;
border-radius: 50%;
float: left;
height: 120px;
moz-border-radius: 50%;
webkit-border-radius: 50%;
width: 120px;
}

.partner__3__icon
{
background-color: #ffa507;
background-image: url('http://www.q-park.co.uk/DesktopModules/QPark.AdvancedPFL/image.aspx?ServiceID=49');
}
.partner__3__pic
{
background-image: url('http://cdn.bmwblog.com/wp-content/uploads/BMW-M235i-racing-car-las-vegas-02-120x120.jpg');
background-position: center top;
border-radius: 50%;
float: left;
height: 120px;
moz-border-radius: 50%;
webkit-border-radius: 50%;
width: 120px;
}

.partner__4__icon
{
background-color: #4e73db;
background-image: url('http://www.q-park.co.uk/DesktopModules/QPark.AdvancedPFL/image.aspx?ServiceID=49');
}
.partner__4__pic
{
background-image: url('http://cdn.bmwblog.com/wp-content/uploads/BMW-M235i-racing-car-las-vegas-02-120x120.jpg');
background-position: center top;
border-radius: 50%;
float: left;
height: 120px;
moz-border-radius: 50%;
webkit-border-radius: 50%;
width: 120px;
}

Lorem ipsum dolor sit amet, consectetuer

Lorem ipsum dolor

Lorem ipsum dolor sit amet, consectetuer

Lorem ipsum dolor

Lorem ipsum dolor sit amet, consectetuer

Lorem ipsum dolor

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa.

Lorem ipsum dolor

Lorem ipsum dolor sit amet, consectetuer

Lorem ipsum dolor

Lorem ipsum dolor sit amet, consectetuer

Lorem ipsum dolor

Lorem ipsum dolor sit amet, consectetuer

Lorem ipsum dolor

Lorem ipsum dolor sit amet, consectetuer

Lorem ipsum dolor

Lorem ipsum dolor sit amet, consectetuer

Check with above code once....


text:
Q: Integration of Gauss ${}_{2}F_{1}$ hypergeometric function The indefinite integral representation of Gauss hypergeometric function is
$$\int {{}_2{F_1}\left( {a,b;c;z} \right)dz = \frac{{c - 1}}{{\left( {a - 1} \right)\left( {b - 1} \right)}}} {}_2{F_1}\left( {a - 1,b - 1;c - 1;z} \right)$$
However I don't understand how to find the following definite integral:
$$\int\limits_{ - \infty }^\infty  {\left( {1 + \frac{{{z^2}}}{{{n_2}{{\cos }^2}\left( \theta  \right)}}} \right){}_2{F_1}\left( {a,b;\frac{1}{2};\frac{{{\gamma ^2}}}{{4{\alpha _1}{\alpha _2}}}} \right)dz}$$
where;
$$\gamma  = \frac{{2yz\sin \left( \theta  \right)}}{{\sqrt {{n_1}{n_2}} {{\cos }^2}\left( \theta  \right)}},\quad {\alpha _1} = 1 + \frac{{y^2}}{{{n_1}{{\cos }^2}\left( \theta  \right)}},\quad {\alpha _2} = 1 + \frac{{z^2}}{{{n_2}{{\cos }^2}\left( \theta  \right)}}$$
I would appreciate it if anyone had a solution to this problem. Thank you in advance.

A: Consider the integral in the form
$$ I = \int_{-\infty}^{\infty} (1 + p \, t^2) \, {}_{2}F_{1}\left(a, b; c; \frac{q^2 \, t^2}{4 \, \alpha \, (1 + p \, t^2)} \right) \, dt. $$
Converting the ${}_{2}F_{1}$ into its series form then
$$ I = \sum_{n=0}^{\infty} \frac{(a)_{n} \, (b)_{n}}{n! \, (c)_{n}} \, \left(\frac{q^2}{4 \, \alpha}\right)^n \, J_{n} $$
where $J_{n}$ is the integral
$$ J_{n} = \int_{-\infty}^{\infty} \frac{t^{2 n} \, dt}{(1 + p \, t^2)^{n-1}}. $$
Since
\begin{align}
\int_{-\infty}^{\infty} f(t^2) \, dt &= \int_{-\infty}^{0} f(t^2) \, dt + \int_{0}^{\infty} f(t^2) \, dt \\
&= 2 \, \int_{0}^{\infty} f(t^2) \, dt \hspace{5mm} \text{let} \, t = -u \, \text{in the first integral} \\
&= \int_{0}^{\infty} f(u) \, u^{-1/2} \, du \hspace{5mm} \text{where} \, t = \sqrt{u} \, \text{was used}.
\end{align}
With this then $J_{n}$ becomes
$$ J_{n} = \int_{0}^{\infty} u^{n-1/2} \, (1 + p \, u)^{1-n} \, du.$$
Comparing this to the hypergeometric function ${}_{2}F_{1}$ integral form, namely,
$$ \int_{0}^{\infty} t^{c-b-1} \, (1+t)^{c-a} \, (1-z+t)^{-a} \, dt = \frac{\Gamma(b) \, \Gamma(c-b)}{\Gamma(c)} \, {}_{2}F_{1}(a, b; c; z).$$
In the case $c = a$ this reduces to
\begin{align}
\int_{0}^{\infty} t^{a-b-1} \, (1-z+t)^{-a} \, dt &= \frac{\Gamma(b) \, \Gamma(a-b)}{\Gamma(a)} \, {}_{2}F_{1}(a, b; a; z) \\
&= \frac{\Gamma(b) \, \Gamma(a-b)}{\Gamma(a)} \, (1-z)^{-a}.
\end{align}
Now,
\begin{align}
J_{n} &= \int_{0}^{\infty} u^{n-1/2} \, (1 + p \, u)^{1-n} \, du \\
&= p^{1-n} \, \int_{0}^{\infty} u^{n-1/2} \, \left(\frac{1}{p} + t\right)^{-(n-1)} \, du \\
&= p^{1-n} \, \frac{\Gamma\left(- \frac{3}{2}\right) \, \Gamma\left(n + \frac{1}{2}\right)}{\Gamma(n-1)} \, \left(\frac{1}{p}\right)^{3/2} \\
&= \frac{\Gamma\left(- \frac{3}{2}\right) \, \Gamma\left(\frac{1}{2}\right)}{\sqrt{p}} \, \frac{\left(\frac{1}{2}\right)_{n}}{(n-2)! \, p^{n}}.
\end{align}
Returning to $I$:
\begin{align}
I &= \sum_{n=0}^{\infty} \frac{(a)_{n} \, (b)_{n}}{n! \, (c)_{n}} \, \left(\frac{q^2}{4 \, \alpha}\right)^n \, J_{n} \\
&= \frac{\Gamma\left(- \frac{3}{2}\right) \, \Gamma\left(\frac{1}{2}\right)}{\sqrt{p}} \, \sum_{n=0}^{\infty} \frac{\left(\frac{1}{2}\right)_{n} \, (a)_{n} \, (b)_{n}}{(n-2)! \, (1)_{n} \, (c)_{n}} \, \left(\frac{q^2}{4 \, \alpha \, p}\right)^n \\
&= \frac{\Gamma\left(- \frac{3}{2}\right) \, \Gamma\left(\frac{1}{2}\right)}{\sqrt{p}} \, \sum_{n=2}^{\infty} \frac{\left(\frac{1}{2}\right)_{n} \, (a)_{n} \, (b)_{n}}{(n-2)! \, (1)_{n} \, (c)_{n}} \, \left(\frac{q^2}{4 \, \alpha \, p}\right)^n \\
&= \frac{\Gamma\left(- \frac{3}{2}\right) \, \Gamma\left(\frac{1}{2}\right)}{\sqrt{p}} \, \frac{\left(\frac{1}{2}\right)_{2} \, (a)_{2} \, (b)_{2}}{(1)_{2} \, (c)_{2}} \, \sum_{n=0}^{\infty} \frac{\left(\frac{5}{2}\right)_{n} \, (a+2)_{n} \, (b+2)_{n}}{n! \, (3)_{n} \, (c+2)_{n}} \, \left(\frac{q^2}{4 \, \alpha \, p}\right)^{n+2} \\
I &= \frac{\pi \, (a)_{2} \, (b)_{2}}{2 \, (c)_{2}} \, \left(\frac{q^2}{4 \, \alpha \, p} \right)^{2} \, {}_{3}F_{2}\left(\frac{5}{2}, a+2, b+2; 3, c+2; \frac{q^2}{4 \, \alpha \, p} \right).
\end{align}
Associating the constants will lead to the desired result.
For the case of $c = \frac{1}{2}$ the given result has a nice reduction as seen by
\begin{align}
I_{c = 1/2} &= \int_{-\infty}^{\infty} (1 + p \, t^2) \, {}_{2}F_{1}\left(a, b; \frac{1}{2}; \frac{q^2 \, t^2}{4 \, \alpha \, (1 + p \, t^2)} \right) \, dt \\
&= \frac{\pi \, (a)_{2} \, (b)_{2} \, q^4}{24 \, (\alpha \, p)^2} \, {}_{2}F_{1}\left(a+2, b+2; 3; \frac{q^2}{4 \, \alpha \, p} \right).
\end{align}


text:
Q: How do I carry out a significance test with Tarone's Z-statistic? Context
In this blog the author suggests using Tarone's Z-statistic to test for overdispersion in a binomial model to determine whether or not it is necessary to use a beta-binomial model instead. In their example they generate some synthetic data from binomial and beta-binomial distributions and then calculate the Z-statistic's for each and plot them, along with a theoretical curve of the null distribution to demonstrate that this metric works.
Question
How do I actually calculate/use this to test for overdispersion? I found the author code difficult to follow and I don't quite understand how I could use this to formally test for over-dispersion.
I have searched around but all I can turn up about Tarone's Z-statistic are the two links I have included.
I am working in R using the lme4 and glmmTMB packages and I would greatly appreciate an answer in this form. I know this question kind of straddles the bounds of CV and stackoverflow, but I considered this a "non-trivial problem" - If the community disagrees I am happy to migrate it!
Update:
I have managed to adapt C.A. Kapourani's code and write a function for calculating Z-statistics for my models (see below), but I still have the problem of how to compare two values. Is it sensible to find the Z-score having a cumulative probability equal to the critical probability (i.e. 0.05) like with other Z-scores? If so, can anyone recommend how I might do this in R?
taronesZStat <- function(model){

  #Extracting model residuals
  res <- residuals(model)

  #Number of residuals
  n <- length(res)

  #Calculating Tarone's Z-statistic
  p_hat <- sum(res)/n

  S <- sum((res - n * p_hat)^2 / (p_hat * (1 - p_hat)))

  Z_score <- (S - sum(n)) / sqrt(2 * sum(n * (n - 1)))

  return(Z_score)
}

A: If you would like another explanation of the procedure, you can read the original paper by Tarone (1979), but the blog actually gives a longer and clearer explanation than the original paper.  In any case, the function you have programmed does not correspond to the formula for Tarone's Z statistic.  I would recommend writing a function that directly calculates the Z statistic from the data, rather than taking an input from a model.  To do this, let's start by generating some binomial data.
#Generate example data
N <- c(30, 32, 40, 28, 29, 35, 30, 34, 31, 39);
M <- c( 9, 10, 22, 15,  8, 19, 16, 19, 15, 10);

We can program the Tarone test as a function in R so that it takes the input data directly and outputs all the required elements of a htest object.  (This form of function means that the object will contain all the relevant information for the hypothesis test, and it will print in the default mode for a htest object.)
Tarone.test <- function(N, M) {

    #Check validity of inputs
    if(!(all(N == as.integer(N)))) { stop("Error: Number of trials should be integers"); }
    if(min(N) < 1) { stop("Error: Number of trials should be positive"); }
    if(!(all(M == as.integer(M)))) { stop("Error: Count values should be integers"); }
    if(min(M) < 0) { stop("Error: Count values cannot be negative"); }
    if(any(M > N)) { stop("Error: Observed count value exceeds number of trials"); }

    #Set description of test and data
    method      <- "Tarone's Z test";
    data.name   <- paste0(deparse(substitute(M)), " successes from ",
                          deparse(substitute(N)), " trials");

    #Set null and alternative hypotheses
    null.value  <- 0;
    attr(null.value, "names") <- "dispersion parameter";
    alternative <- "greater";

    #Calculate test statistics
    estimate    <- sum(M)/sum(N);
    attr(estimate, "names") <- "proportion parameter";
    S           <- ifelse(estimate == 1, sum(N),
                          sum((M - N*estimate)^2/(estimate*(1 - estimate))));
    statistic   <- (S - sum(N))/sqrt(2*sum(N*(N-1)));
    attr(statistic, "names") <- "z";

    #Calculate p-value
    p.value     <- 2*pnorm(-abs(statistic), 0, 1);
    attr(p.value, "names") <- NULL;

    #Create htest object
    TEST        <- list(method = method, data.name = data.name,
                        null.value = null.value, alternative = alternative,
                        estimate = estimate, statistic = statistic, p.value = p.value);
    class(TEST) <- "htest";
    TEST; }

Now let's try applying this function to the example data and see what we get:
#Apply Tarone's test to the example data
TEST <- Tarone.test(N, M);
TEST;

        Tarone's Z test

data:  M successes from N counts
z = 2.5988, p-value = 0.009355
alternative hypothesis: true dispersion parameter is greater than 0
sample estimates:
proportion parameter
           0.4359756

In this case we have a low p-value, so we find strong evidence to reject the null hypothesis of a binomial distribution in favour of the alternative of over-dispersion.  We can fit the data to the beta-binomial model to estimate the dispersion parameter:
#Fit the example data to a beta-binomial distribution
MODEL <- VGAM::vglm(cbind(DATA$m, DATA$n-DATA$m) ~ 1, betabinomial, trace = FALSE);
Coef(MODEL);

        mu        rho
0.43507150 0.03355549

A: This is an addendum to the other answer that is too long for a comment. The original question regarded overdispersion in generalized linear mixed models models (I assume, given OP is using lme4). In this case there are covariates that will induce variation in excess of what would be expected for iid binomial data. This is actually a primary motivation for modelling overdispersion -- in many fields, we are unable to measure all relevant covariates, and the variation that these induce can distort inference.
Without a good reason to do otherwise I would always incorporate overdispersion into a model (in biology -- my field -- there is almost always unexplained variation due to flawed experimental conditions, the inherent complexity of natural systems, etc). If I wanted to test for overdispersion with an arbitrary test statistic and arbitrary model, I would use a parametric bootstrap. The idea is to simulate data under a null model (e.g. the arbitrary model, but without overdispersion) and calculate the test statistic for each simulation. This gives an approximation to the distribution of the test statistic under the null.
Here's an example with lme4:
library(lme4)
set.seed(101)

# "actual" data
intercept <- 0.1; slope <- 0.8
covariate <- runif(1000)
latent_response <- intercept + covariate*slope
observed_response <- rbinom(1000, prob=plogis(latent_response), size=10)
realdat <- data.frame(m = observed_response, n=rep(10,1000), x = covariate, grp = rep(1:100, each = 10))
null <- glmer(cbind(m, n-m) ~ x + (1|grp), data=realdat, family="binomial")

# parametric bootstrap with function from Ben's answer
sims <- replicate(1000,{ fakedat <- simulate(null)[[1]]; Tarone.test(rowSums(fakedat), fakedat[,1])$statistic })
obs <- Tarone.test(realdat$n, realdat$m)$statistic
# approximate one-tailed pval
sum(sims > obs)/length(sims)
hist(sims);abline(v=obs,col="red") #no evidence for overdispersion

# what if covariate was not measured?
null2 <- glmer(cbind(n, n-m) ~ (1|grp), data=realdat, family="binomial")
sims2 <- replicate(1000,{ fakedat <- simulate(null2)[[1]]; Tarone.test(rowSums(fakedat), fakedat[,1])$statistic })
sum(sims2 > obs)/length(sims2)
hist(sims2);abline(v=obs,col="red") #now appears to be evidence for overdispersion


text:
Q: How to fix Out of Bound Memory Access(access exceeds upper limit of memory block) int main()
{
    int n = 3;
    int a[n] = {1,2,3};

    ...
    in middle of code, value of n can be increased by 10 so I want to have check before cout otherwise       a[10] is out of bound.
    ...

    cout<<a[n-1];
    return 0;
}

To fix above issue, I simply put one if check.
Corrected code:
int main()
{
    int n = 3;
    int a[n] = {1,2,3};
    ...

    In middle of code, value of n can be increased by 10 so I want to have check before cout otherwise       a[10] is out of bound.
    ...
    if(n<= 3)
    {
         cout<<a[n-1];
    }
    return 0;
}

Is there any other way to avoid Out of Bound Memory Access
I tried to use if check on the basis of size.

A: int a[n] = {1,2,3};

could to be
a[0] = 1
a[1] = 2
a[2] = 3

if n is menor or igual to -1, or mayor or igual to 3, you'll have an excess of memory.
Before to read a[n] you can check it out:
if ( 0 >= n & n < 3)
{
  // ....you can read a[n]
}