text:
Q: RTL images are not flipped inside UITableViewCell I have an app where I need to support Right-To-Left language. The system takes care of everything almost automatically. Except for images.
Some of them (arrows) need to be flipped. In the Assets catalog I set the 'Direction' property of those images  to 'Left To Right, Mirrors'.
This works well with images that are used for buttons (both simple buttons and navigation bar buttons), but the problem occurs when it comes to images that are used in image views inside the table view cell.
When the table is displayed, they are not flipped. When I tap a cell, selecting it, the image flips and remains flipped afterwards. So, I need to tap each cell to flip their images.
I have tried to use imageFlippedForRightToLeftLayoutDirection(), but to no effect. Same with withHorizontallyFlippedOrientation().
Do you have ideas of how to fix that?
P.S. Adding screenshot on request. Top 3 cells have already been tapped, so arrows are flipped as expected. Bottom cells display unflipped images.

Top 3 cells have already been tapped, so arrows are flipped as expected. Bottom cells display unflipped images.

A: Ok, this is the fix I've found so far.
As long as iOS cannot mirror the image correctly for some reason, I've set 'Direction' property to 'Both' and added the right-to-left set of images.
That solved the problem.

A: Seems to be a bug with UIImageView since - as you stated - it works for an image in a UIButton. The trick is to set the image programmatically (instead of selecting it in interface builder). Then the RTL system works as expected:
yourImageView?.image = UIImage(named: "YourImageName")


text:
Q: Put left-floating video at bottom of paragraph If i put a <video> tag with float:right above a
 tag, it appears like this:
textextext o------o
textextext | vid  |
textextext o------o
textextextextextext

Is it possible to get it to appear like this instead?
textextextextextext
textextext o------o
textextext | vid  |
textextext o------o

I've tried doing position: relative and bottom: 0px, but that didn't work.

A: Try This Code

.container{

}
p.p1{ text-align:left; }
.grid{ display: inline-grid; grid-template-columns: auto auto; }
.grid div{ max-width:50%;}

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea

         commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

      <video src="http://movietrailers.apple.com/movies/universal/jurassic-world-fallen-kingdom/jurassic-world-fallen-kingdom-trailer-1_h1080p.mov" width="300" controls></video>

redpajama_set_name: RedPajamaStackExchange


text:
Q: ee.Algorithms.If() in Google Earth Engine trueCase causing an error even though it should be entering falseCase I have a simple function where I am trying to define a geometry based on a simple condition, whether the feature roi exists (condition is true if it exists, false if it does not).
var getShape = function(params){
  // Parameters
  var roi = params.roi
  var selectedStates = params.selectedStates
  // Get state geometry
  var selectedStatesGeometry = ee.FeatureCollection("FAO/GAUL/2015/level1")
    .filter(ee.Filter.inList('ADM1_NAME', selectedStates))
    .geometry()
  // Calculate shape
  var baseShape = ee.Geometry(
    ee.Algorithms.If({ // If roi exists
      condition: roi,
      // then return roi geometry
      trueCase: roi.geometry(ee.ErrorMargin(100)),
      // if not return state borders
      falseCase: selectedStatesGeometry
    })
  )
  return baseShape
}
// Apply function
var test = getShape({
  roi: null,
  selectedStates: ['Oaxaca'],
})
print(test)
Map.addLayer(test)

The issue is that no matter if the condition is true or false the script fails, stating Cannot read property 'geometry' of null. This error is coming from the trueCase, which is understandable since roi does not exist. This defeats the entire purpose of the function, since I am trying to handle cases where roi does not exist. However, I know for a fact the algorithms is 'entering' falseCase, because if I change the outcome of trueCase to a dummy geometry it will output the state borders and not the dummy geometry (at is should).
I am trying to avoid using an if/else loop since it is client-side function which implies I would have to evaluate the outputs, which is bad practice, however I'm not sure I have a choice at this point.

A: You're passing an Object to ee.Algorithms.If():
{
  ...
  trueCase: roi.geometry(ee.ErrorMargin(100))
  ...
}

When you great this object, roi.geometry(ee.ErrorMargin(100)) will get invoked. Since roi is null, you get an error before ee.Algorithms.If() is even invoked.


text:
Q: Android: Working with bitmaps without OutOfMemoryError first the important lines of code:
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), getDrawableForLvl(drawable));
int []pixels = new int[bitmap.getWidth()*bitmap.getHeight()];
bitmap.getPixels(pixels, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());
//..
pixels = null; // please gc remove this huge data
System.gc();

So I'm working on an Android app (game) with multiple levels. Every level is an image that I load as bitmap on level start. Then I have to analyse every pixel (line 3). For that I create an array (line 2). The images are 1280x800, so the array has a size over one million ints. No problems here and since it's a local variable it should be destroyed on method return. But it's java, so it's not -.- Depending on the device the garbage collector is running fast enough in time or not. So when a user starts and closes levels very fast it produces a java.lang.OutOfMemoryError in line 2. I guess because the old array(s) wasn't/weren't removed yet and now I have multiple ones filling the memory.
I could make the array a static member. So it's created once and is always available. Then it's not possible to have multiple instances of it. But I think that's a bad coding style, because it's also available (4 MB) when not needed.
I don't need all pixels at the same time. I'm splitting the images in more than a hundred rectangles, so I could use a way smaller array and fill it one after another with pixels. But I have problems to understand the methods parameters can someone help me here?
There is also a method to get just one pixel at position x,y, but I guess a million function calls is pretty slow.
Has someone a better idea? There is no way to force an object out of memory in java, is there?

Update1:
As vzoha suggested to get only the first quarter:
int []pixels = new int[bitmap.getWidth()/2*bitmap.getHeight()/2];
bitmap.getPixels(pixels, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth()/2, bitmap.getHeight()/2);

gives an ArrayIndexOutOfBound. I think the function call is just getting the pixels of the first quarter, but still expects the full size array and the other fields will be left untouched.
Update2: I guess I can do it row by row (half row by half row for the first quarter):
int []pixels = new int[bitmap.getWidth()/2*bitmap.getHeight()/2];
for(int row = 0; row < bitmap.getHeight()/2; ++row)
    bitmap.getPixels(pixels, bitmap.getWidth()/2, bitmap.getWidth(), 0, row, bitmap.getWidth()/2, 1);

But when I do that for 20x10 parts it's not much better than getting each pixel by itself. Well it is much better but still the method should be capable to do that with one call, shouldn't it? I just don't get this "stride" parameter: "The number of entries in pixels[] to skip between rows (must be >= bitmap's width). Can be negative." How can it be negativ when >= width?

A: The size in pixels doesn't directly translate to how much memory the image will take up in memory. Bitmaps in Android (before using ART) are notoriously difficult to use heavily while avoiding OOM exceptions, enough so, that there's a page dedicated to how to use them efficiently. The problem is normally that there is actually enough memory available, but it has become fragmented and there isn't a single contiguous block the size you need available.
My first suggestion (for a quick win) would be to decode the bitmap with a specific config, you should be able to occupy only 1/4 of the amount of memory you were previously using by switching to use ALPHA_8 for your bitmap config. This will use 1 byte per pixel instead of 4 (the default is ARGB_8888)
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ALPHA_8
bitmap = BitmapFactory.decodeResource(getResources(), getDrawableForLvl(drawable), options);

My next suggestion would be to scale you bitmap to start with and place the appropriate one in your hdpi,xhdpi,xxhdpi folders.

A: In fact it is pretty simple to get just the pixels of a specific area. But the documentation is wrong about the stride parameter. It says:

public void getPixels (int[] pixels, int offset, int stride, int x, int y, int width, int height)
stride: The number of entries in pixels[] to skip between rows (must be >= bitmap's width). Can be negative.

But the truth is it can (and must in most cases) be less than the bitmap's width, it just has to be bigger or equal to the passed width (the second to last parameter of getPixels), meaning the width of the area from which I want the pixels.
So to get the pixels of the first quarter of a bitmap:
int []pixels = new int[bitmap.getWidth()>>1 * bitmap.getHeight()>>1]; // quarter of the bitmap size
bitmap.getPixels(pixels, 0, bitmap.getWidth()>>1, 0, 0, bitmap.getWidth()>>1, bitmap.getHeight()>>1);

Or to get a specific rect with x,y (upper left corner) and width, height:
int []pixels = new int[width*height];
bitmap.getPixels(pixels, 0, width, x, y, width, height);

So pretty simple. It was just the wrong documentation that put a twist in my brain.


text:
Q: Total measure and Riesz theorem As I specified in the other question I asked, analysis is not my field, so I'm sorry if my question is trivial.
Riesz representation theorem states the following:
Given $X$ a locally compact hausdorff space and $\lambda$ a positive, linear and continuous functional on $C_c(X)$, there exists a unique Borel measure $\sigma_\lambda$ on $X$ for which $\lambda(f)=\int_X f d\sigma_\lambda$ for every $f\in C_c(X)$.
Now let's consider $X$ locally compact but not compact.
Given $\lambda$ and $\sigma_\lambda$ as in the theorem, I would like to compute $\sigma_\lambda(X)$ (total mass of $X$ with respect to $\sigma_\lambda$) doing computations using only the functional $\lambda$: I would like to ask you if there is a standard way to do so.
I can not set $\sigma_\lambda(X)=\lambda(1_X)$ ($1_X$ is the indicator function) since $X$ is not compact, but maybe it has sense to compute it as $lim_{n\rightarrow \infty}\lambda(1_{X_n})$ as $1_{X_n}$ tends to $1_{X}$ in $C_c(X)$. I don't know if it makes sense, but first of all I should find such a sequence which is not trivial to me..
Thank you


text:
Q: How does the Chrome Geolocation Sensor work? There is an option within the Chrome dev tools which allows you to change your ubication (More Tools > Sensors). How does it work internally? Does it add an extra HTTP header indicating the GEO coordinates?

A: Yes, it changes the cookie that's sent with the request:
This is the cookie for Mountain View (California, Google HQ):
Cookie: UULE=a+cm9sZToxIHByb2R1Y2VyOjEyIHByb3ZlbmFuY2U6NiB0aW1lc3RhbXA6MTUyMjc1NDM1MDc1MjAwMCBsYXRsbmd7bGF0aXR1ZGVfZTc6MzczODYwNTIwIGxvbmdpdHVkZV9lNzotMTIyMDgzODUxMH0gcmFkaXVzOjkzMDAw

Discard the UULE=a+ and what you're left with is a Base64 encoded string. Decoding that becomes:
role:1 producer:12 provenance:6 timestamp:1522754350752000 latlng{latitude_e7:373860520 longitude_e7:-1220838510} radius:93000

Within that is the longitude and latitude, but I'm not sure what the other parts refer to. Guessing the radius is the radius from the centre of that long/lat (in metres?).
Hope that helps.


text:
Q: Running physics simulation on iOS simulator is different than on device I have a basic helloworld-type routine in Bullet Physics, where each world step is hard-coded to 1/60 of second, and is therefore independent of the refresh-rate or frame-rate of the app or device. There is no interaction, just some objects falling and moving around. It works on both simulator and device, but subtle changes to how they fall, where they hit, vary between the simulator or device, even though repeated runs are always the same within an environment.
I can't understand what would be the difference between a simulator and a device for purposes of just crunching numbers. Would there be a big difference in numerical precision that could cause things like many iterations of a physics world to vary? Or some other obvious reason?


text:
Q: Relation of angle between $e_1,e_2$ with angle between $e_1^*, e_2^*$ in Euclidenan space $\mathbb{R}^2$ Consider Euclidean space $\mathbb{R}^2$.

Let $\{e_1,e_2\}$ be an ordered basis with angle between them acute (i.e. $(e_1,e_2)\leq 0$. Let $\{f_1,f_2\}$ be dual of above basis w.r.t. inner product $(\cdot,\cdot)$. I want to show that $(f_1,f_1)\geq 0$.

Let $f_1=ae_1+be_2$ and $f_2=ce_1+de_2$. Now $(f_i,e_j)=\delta_{ij}$ so
$$a=(f_1,f_1), \hskip5mm b=(f_1,f_2), \hskip5mm c=(f_2,f_1),\hskip5mm d=(f_2,f_2).$$
Then $(f_1,f_2) = (ae_1+be_2, ce_1+de_2)= ac|e_1|^2 + bd |e_2|^2+(ad+bc)(e_1,e_2).$
For simplicity we can assume that $e_1,e_2$ are unit vectors. So
$$(f_1,f_2) =|f_1|^2.(f_2,f_1) +(f_1,f_2).|f_2|^2+\{ |f_1|^2.|f_2|^2+(f_1,f_2)^2\} (e_1,e_2)$$
i.e.
$$\{1-|f_1|^2-|f_2|^2\} (f_1,f_2) =\{ |f_1|^2.|f_2|^2+(f_1,f_2)^2\} (e_1,e_2).$$
After this, I couldn't proceed, and I don't know if this is the way to proceed for proof. How can we prove the assertion?

A: (1) Let $A=[a_{ij}]=[(e_i,e_j)]$ be the Gram matrix of basis $(e_i)_i$, and $B=[b_{ij}]=[(f_i,f_j)]$ the Gram matrix of dual basis $(f_i)_i$ of $(e_i)_i$ w.r.t. $(\cdot,\cdot)$.
(2) Then show that $[b_{ij}]=[a_{ij}]^{-1}$.
(3) Consider the above case for basis $e_1,e_2$. Show that (1,2)-th entry of $B$ and (1,2)-th entry of $A$ are related by
$$(f_1,f_2) = \frac{-1}{(e_1,e_1).(e_2,e_2)-(e_1,e_2)^2}(e_1,e_2).$$
(4) By Cauchy-Schwartz, $(v_1,v_2)^2\leq |v_1|^2.|v_2|^2$ with equality only when $v_1,v_2$ are dependent.
(5) Since $e_1,e_2$ are independent, the denominator of above equation is positive.
(6) q.e.d.

A: I think we can use the natural geometric proof. Let $\alpha$ be the angle between $e_1$ and $e_2$ and $\beta$ be the angle between $f_1$ and $f_2$. It's enough to show that $\alpha+\beta=\pi$ i.e. if $\alpha$ is obtuse then $\beta$ is acute. We can see that $f_1$ is orthogonal to $e_2$ and $f_2$ is orthogonal to $e_1$. Also, $f_i$ and $e_i$ should have an acute angle since $$(f_i,e_i)=|f_i||e_i|\cos(\theta_i)=1>0$$ i.e. $\cos(\theta_i)>0$. Then $\alpha+\beta=\pi$ follows from this picture.


text:
Q: Does Cloud Firestore lock when a backup is taking place? I'm scheduling a backup operation on Cloud Firestore. I'm not sure if data changes while the backup function is running, if those changes would be reflected in the backup.
For completeness that's not the behavior I'm looking for and if the changes would be reflected, is there anyway I can lockout the db? Perhaps dynamically changing the security rules?

A: Firestore's export feature is not a true "backup". Notice that nowhere in the documentation is the word "backup" ever used.  It's just an export, and that export is effectively just querying every collection and writing the documents to a file in a storage bucket.
Data can change during an export.  The export might not contain everything that might have changed while the export happened.  You can expect the export to be inconsistent in that case.
Security rules don't affect the export.  They just affect web and mobile clients.
It's not really possible to "lock" the entire database, except by preventing your code from writing it entirely by controlling it yourself.


text:
Q: How to printf all elements of table (int) I try to display all values of tab but only 8 first elements are displayed no more
int tab[] = {0,2,5,3,9,0,8,9,2,0,4,3,0};
printf("taille %d: \n", sizeof(tab));

    for (int i=0; i<sizeof(tab); i++)
    {
        printf("indice : %d et valeur :%d \n", i, *(tab + i ));
    }

A: sizeof(tab) yields the size in bytes of all the array tab that contains 13 elements each of them having the size equal to sizeof( int ) (that is the same as sizeof( *tab )). That is
sizeof(tab) is equal to 13 * sizeof( int ) that in turn can be equal to 52 provided that sizeof( int ) is equal to 4.
But you need to output only 13 elements of the array.
So you should write for example
int tab[] = {0,2,5,3,9,0,8,9,2,0,4,3,0};
const size_t N = sizeof( tab ) / sizeof( *tab );

printf( "taille %zu: \n", N );

for ( size_t i = 0; i < N; i++ )
{
    printf( "indice : %zu et valeur :%d \n", i, *(tab + i ) );
}
putchar( '\n' );

Pay attention to that to output an object of the type size_t you need to use the conversion specifier zu.
Here is a demonstrative program where the array output is placed in a separate function.
#include <stdio.h>

FILE * output( const int tab[], size_t n, FILE *fp )
{
    fprintf( fp, "taille %zu: \n", n );

    for ( size_t i = 0; i < n; i++ )
    {
        fprintf( fp, "indice : %zu et valeur :%d \n", i, *(tab + i ) );
    }

    return fp;
}

int main(void)
{
    int tab[] = {0,2,5,3,9,0,8,9,2,0,4,3,0};
    const size_t N = sizeof( tab ) / sizeof( *tab );

    fputc( '\n', output( tab, N, stdout ) );

    return 0;
}

The program output is
taille 13:
indice : 0 et valeur :0
indice : 1 et valeur :2
indice : 2 et valeur :5
indice : 3 et valeur :3
indice : 4 et valeur :9
indice : 5 et valeur :0
indice : 6 et valeur :8
indice : 7 et valeur :9
indice : 8 et valeur :2
indice : 9 et valeur :0
indice : 10 et valeur :4
indice : 11 et valeur :3
indice : 12 et valeur :0

A: The line
printf("taille %d: \n", sizeof(tab));

invokes undefined behavior, allowing anything to happen, by passind data having wrong type to printf(). %d expects int, but sizeof returns size_t. The correct format specifier to print size_t in decimal is %zu.
Then, sizeof(tab) is the size of the array tab in bytes (number of char, strictly speaking). It is not the number of elements. To obtain the number of elements, you have to divide that by the size of one element sizeof(*tab).
int tab[] = {0,2,5,3,9,0,8,9,2,0,4,3,0};
printf("taille %zu: \n", sizeof(tab));

for (int i=0; i<sizeof(tab)/sizeof(*tab); i++)
{
    printf("indice : %d et valeur :%d \n", i, *(tab + i ));
}


text:
Q: Woocommerce how to display products which has two categories, one of them should be common I am developing custom Woo shop theme. I want to display in front-page.php NEW COLLECTION products, it should be one block, and inside few smaller blocks with products ant their another vcategories, because, they will have common category NEW and another category depends BEDROOM/BATHROOM/CLOTHING, for now i have reahced display by one category.

            <?php
                $args = array(
                    'post_type'      => 'product',
                    'posts_per_page' => 4,
                    'product_cat'    => 'clothing'
                );

                $loop = new WP_Query( $args );

                while ( $loop->have_posts() ) : $loop->the_post();
                    global $product;
                    $colors = explode(',',$product->get_attribute('color'));
                    $price = $product->get_price_html();
                ?>

                        <a href="<?php the_permalink(); ?>">
                            <img src="<?php echo the_post_thumbnail_url(); ?>">

<?php the_title(); ?>

<?php echo $price ?>

                                <?php foreach ($colors as $color) {
                                        echo '';
                                    }
                                ?>

                <?php

                endwhile;

                wp_reset_query();
            ?>

I hope that my question will be clear, i am adding image with design for better understanding. I think that it should be somethimg like this code, but this code should have NEW as product_cat in $args, and then inside loop somehow do same block but with other categories.
design shows how it should be

A: You can use tax_query to get products from multiple categories. check below code.

    <?php

        $prod_categories = array( 'bedroom', 'bathrooms', 'clothing'); //category slugs

        $args = array(
            'post_type'      => 'product',
            'posts_per_page' => 4,
        );

        if (!empty($prod_categories)) {
            $args['tax_query'] = array(
                array(
                    'taxonomy' => 'product_cat',
                    'field'    => 'slug',
                    'terms'    => $prod_categories,
                    'operator' => 'IN',
            ));
        }

        $loop = new WP_Query( $args );

        while ( $loop->have_posts() ) : $loop->the_post();
            global $product;
            $colors = explode(',',$product->get_attribute('color'));
            $price = $product->get_price_html();
        ?>

                <a href="<?php the_permalink(); ?>">
                    <img src="<?php echo the_post_thumbnail_url(); ?>">

<?php the_title(); ?>

<?php echo $price ?>

                        <?php foreach ($colors as $color) {
                                echo '';
                            }
                        ?>

        <?php

        endwhile;

        wp_reset_query();
    ?>


text:
Q: Why cant i scroll the textview inside my fragment? I already tried to use the solution rom here
Rigth now it's a ScrollView.
Neither of these possibilities will let me Scroll the text.
It minSDK is Version 8. It still has to be able to run on android 2.2.1.
I also included Following Support libaries in my build.gradle
compile 'com.android.support:appcompat-v7:23.1.0'
compile 'com.android.support:design:23.1.0'
compile 'com.android.support:support-v4:23.4.0'

My FragmentOne.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior">

<ScrollView
android:id="@+id/ScrollView1"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
    android:text="lorem ipsum .. (500 Words)"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:gravity="center"
    android:id="@+id/tvStatus"/>

And my FragmentOne.java:
package com.kaba.apps.apptemplate.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.text.method.ScrollingMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class FragmentOne extends Fragment
{
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View fragmentView = inflater.inflate(R.layout.fragment_one, container, false);
        fragmentView.setBackgroundColor(Color.DKGRAY);

        TextView tvStatus = (TextView)fragmentView.findViewById(R.id.tvStatus);
        tvStatus.setTextColor(Color.WHITE);
//        tvStatus.setText("I am fragment one");
//        tvStatus.setMovementMethod(new ScrollingMovementMethod());

        return fragmentView;
    }

}

A: Because you don't have enough content in TextView or Add enough views inside scrollview

A: After days of searching i finally found the mistake in my files
In the app_bar_main.xml you have do be sure, that your include / layout is beneath the </android.support.design.widget.AppBarLayout> in any other case you will experience the same problems as me.
app_bar_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
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="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".TemplateActivity">

<android.support.design.widget.AppBarLayout
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        android:gravity="center"
        app:popupTheme="@style/AppTheme.PopupOverlay">

        <LinearLayout
            android:id="@+id/main_toolbar_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="vertical">

            <TextView
                android:id="@+id/main_toolbar_title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
        </LinearLayout>
    </android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>

    <include layout="@layout/fragment_one"/>
</android.support.design.widget.CoordinatorLayout>

and here it is like it should not be:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    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="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context=".TemplateActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            android:gravity="center"
            app:popupTheme="@style/AppTheme.PopupOverlay">

            <LinearLayout
                android:id="@+id/main_toolbar_layout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/main_toolbar_title"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />
            </LinearLayout>
        </android.support.v7.widget.Toolbar>

    <include layout="@layout/fragment_one"/>

    </android.support.design.widget.AppBarLayout>

</android.support.design.widget.CoordinatorLayout>


text:
Q: Scrolling a div with touch events How can I scroll a div with touch events? I have a DIV with overflow set to hidden. I know I can scroll a DIV with javascript, here is an example for using the mousewheel:
function mousewheelScroll(event, delta) {
    var $t = $(this);
    var change = delta * 8;
    var top = $t.scrollTop();
    top = top - change;
    if (top < 0)
        top = 0;
    if (top > ($t.attr("scrollHeight") - $t.innerHeight()))
        top = ($t.attr("scrollHeight") - $t.innerHeight());
    $t.scrollTop(top);
}

But i haven't found an example that will work with touch events for iOS devices.

A: Check out this plugin, it seems like it's just what you're looking for
http://plugins.jquery.com/project/touch-scroll


text:
Q: How to edit some txt in the tab? https://github.com/dubravcik/pbixrefresher-python/blob/master/pbixrefresher/pbixrefresher.py
I am using pywinauto package to automate the Power BI process.
After I get into Edit Parameters, can I know how to edit the text in the tabs? For example, change '1' to 'a', change '2' to 'b' and lastly change '3' to 'c'. At the end, click 'OK'. Any idea?
Part of the code I have:
win = app.window(title_re = '.*Power BI Desktop')

win.Home.click_input()

win.Transformdata.click_input()

win.Editparameters.click_input()

A: You can use pywinauto set_text function to edit the text box
Below is the sample code
Editable_TextBox = win.child_window(title=<UI_identifier>, control_type="Edit")
Editable_TextBox.set_text(<Text_you_set>)

Or You can use type_keys function
win.Editparameters.type_keys(<Text_you_need_To_set>,with_spaces=True)


text:
Q: How do I build an SQL query that discards repeating data? I have a simple one-table SQLite3 database which stores the state of Internet reachability from my LAN's perspective.
CREATE TABLE inet_visibility (
    recid  INTEGER PRIMARY KEY,
    type   INTEGER CHECK (type >= 0 AND type <= 2),   -- 0 = state change; 1 = periodic; 2 = other
    ts_new TEXT UNIQUE NOT NULL,                      -- entry created; UTC ISO8601
    ts_upd TEXT UNIQUE NOT NULL,                      -- entry updated; UTC ISO8601
    updcnt INTEGER NOT NULL,                          -- update tally
    state  INTEGER CHECK (state >= 0 AND state <= 2), -- 0 == unreachable; 1 = reachable; 2 = unknown
    byhost TEXT NOT NULL,                             -- IP of tester
    method TEXT NOT NULL,                             -- tool/process used to determine state
    note   TEXT DEFAULT ''                            -- optional note/comment
);

After several days of running, I've accumulated the following data:
recid       type        ts_new               ts_upd               updcnt      state       byhost        method      note
----------  ----------  -------------------  -------------------  ----------  ----------  ------------  ----------  ----------
1           0           2019-05-20 10:31:48  2019-05-22 14:45:10  3106        1           192.168.1.47  heartbeat
2           0           2019-05-22 14:46:11  2019-05-23 07:41:52  981         0           192.168.1.47  ping
3           0           2019-05-23 07:42:52  2019-05-26 10:11:14  4438        1           192.168.1.47  heartbeat
4           0           2019-05-26 10:12:15  2019-05-26 10:12:15  0           1           192.168.1.47  ping
5           0           2019-05-26 10:13:24  2019-05-27 09:58:36  1415        1           192.168.1.47  heartbeat
6           0           2019-05-27 09:59:37  2019-05-27 09:59:37  0           1           192.168.1.47  ping
7           0           2019-05-27 10:00:49  2019-05-30 09:48:29  4277        1           192.168.1.47  heartbeat
8           0           2019-05-30 09:49:29  2019-05-30 09:49:29  0           1           192.168.1.47  ping
9           0           2019-05-30 09:50:34  2019-06-02 19:42:50  4877        1           192.168.1.47  heartbeat
10          0           2019-06-02 19:44:33  2019-06-02 19:44:33  0           0                         ping
11          0           2019-06-02 19:46:00  2019-06-03 10:32:44  881         1           192.168.1.47  heartbeat

For the primary report, I'm only interested in the change of state at the earliest time. So for this report, I want the following data:
recid       type        ts_new               ts_upd               updcnt      state       byhost        method      note
----------  ----------  -------------------  -------------------  ----------  ----------  ------------  ----------  ----------
1           0           2019-05-20 10:31:48  2019-05-22 14:45:10  3106        1           192.168.1.47  heartbeat
2           0           2019-05-22 14:46:11  2019-05-23 07:41:52  981         0           192.168.1.47  ping
3           0           2019-05-23 07:42:52  2019-05-26 10:11:14  4438        1           192.168.1.47  heartbeat
10          0           2019-06-02 19:44:33  2019-06-02 19:44:33  0           0                         ping
11          0           2019-06-02 19:46:00  2019-06-03 10:32:44  881         1           192.168.1.47  heartbeat

The two key requirements to note from the above four-line extract are these:
    a) each state value alternates; and b) rec 3 (the earliest) is returned, not recs 4 through 9
I have no idea how to write a query to get these results.
sqlite3 history.db 'select * from inet_visibility group by state order by ts_upd asc'
... gives me only records 1 and 2.
sqlite3 history.db 'select * from inet_visibility group by date(ts_upd),state order by ts_upd asc'
... is a bit closer but too much data: I see records 5, 7, and 9.
I know both these queries are wrong; I was trying to home in on a solution and hit a wall (in my SQL skills).
In essence ... If you consider the data as an order list by ascending ts_upd, I only want the records where state changes relative to the previous record.
An aside: for this primary report, I only care about recid, ts_upd, and state - the rest of the columns can be ignored, if that matters.
Can someone offer a suggestion or a solution?

A: In the more recent versions of SQLite, you can use lag():
select iv.*
from (select iv.*,
             lag(state) over (partition by byhost order by recid) as prev_state
      from inet_visibility iv
     ) iv
where prev_state is null or prev_state <> state;

This assumes that "previous row" is identified based on recid.  It also assumes that you only care about comparing byhost to see if state changed.
EDIT:
If you want recid 11, then you don't care about byhost.  Remove it from the partition by:
select iv.*
from (select iv.*,
             lag(state) over (order by recid) as prev_state
      from inet_visibility iv
     ) iv
where prev_state is null or prev_state <> state;


text:
Q: How do I "capture" and store the complex output of a Flutter function as code so I can write unit tests for it? First of all, apologies if this is a stupid question. I'm new to unit tests so I'm struggling a bit here.
I'm working on an app that queries an API, receives a JSON response and then processes that response to produce a series of complex data structures. Many of these data structures are daily time series, which means each of my functions produces a list (List<Datapoint>) containing hundreds of datapoint objects.
What I'm trying to test is that, for a given API response, each function produces the output it should.
For the input of each test I have already grabbed a sample, real JSON response from the API, and I've stored it inside a test_data folder within my root test folder.
However, for the expect part... how can I obtain a sample output from my function and store it somewhere in my test_data folder?
It would be straightforward if the output of my function were a string, but in this case we're talking about a list with hundreds of custom objects containing different values inside them. The only way to create those objects is through the function itself.
I tried running the debugger to check the value of the output at runtime, which I can do... but that doesn't help me copy it or store it anywhere as code.
Should I try to print the full contents of the output to a string at runtime and store that string? I don't think this would work, as all I see in the console are a bunch of Instance Of when I do functionOutput.toString()... I would probably need to recursively print each of the variables inside those objects.
Please tell me I'm being stupid and there's a simpler way to do this :)


text:
Q: How undefined is undefined behavior? I'm not sure I quite understand the extent to which undefined behavior can jeopardize a program.
Let's say I have this code:
#include <stdio.h>

int main()
{
    int v = 0;
    scanf("%d", &v);
    if (v != 0)
    {
        int *p;
        *p = v;  // Oops
    }
    return v;
}

Is the behavior of this program undefined for only those cases in which v is nonzero, or is it undefined even if v is zero?

A: Let me give an argument for why I think this is still undefined.
First, the responders saying this is "mostly defined" or somesuch, based on their experience with some compilers, are just wrong.  A small modification of your example will serve to illustrate:
#include <stdio.h>

int
main()
{
    int v;
    scanf("%d", &v);
    if (v != 0)
    {
        printf("Hello\n");
        int *p;
        *p = v;  // Oops
    }
    return v;
}

What does this program do if you provide "1" as input?  If you answer is "It prints Hello and then crashes", you are wrong.  "Undefined behavior" does not mean the behavior of some specific statement is undefined; it means the behavior of the entire program is undefined.  The compiler is allowed to assume that you do not engage in undefined behavior, so in this case, it may assume that v is non-zero and simply not emit any of the bracketed code at all, including the printf.
If you think this is unlikely, think again.  GCC may not perform this analysis exactly, but it does perform very similar ones.  My favorite example that actually illustrates the point for real:
int test(int x) { return x+1 > x; }

Try writing a little test program to print out INT_MAX, INT_MAX+1, and test(INT_MAX).  (Be sure to enable optimization.)  A typical implementation might show INT_MAX to be 2147483647, INT_MAX+1 to be -2147483648, and test(INT_MAX) to be 1.
In fact, GCC compiles this function to return a constant 1.  Why?  Because integer overflow is undefined behavior, therefore the compiler may assume you are not doing that, therefore x cannot equal INT_MAX, therefore x+1 is greater than x, therefore this function can return 1 unconditionally.
Undefined behavior can and does result in variables that are not equal to themselves, negative numbers that compare greater than positive numbers (see above example), and other bizarre behavior.  The smarter the compiler, the more bizarre the behavior.
OK, I admit I cannot quote chapter and verse of the standard to answer the exact question you asked.  But people who say "Yeah yeah, but in real life dereferencing NULL just gives a seg fault" are more wrong than they can possibly imagine, and they get more wrong with every compiler generation.
And in real life, if the code is dead you should remove it; if it is not dead, you must not invoke undefined behavior.  So that is my answer to your question.

A: If v is 0, your random pointer assignment never gets executed, and the function will return zero, so it is not undefined behaviour

A: I'd say that the behavior is undefined only if the users inserts any number different from 0. After all, if the offending code section is not actually run the conditions for UB aren't met (i.e. the non-initialized pointer is not created neither dereferenced).
A hint of this can be found into the standard, at 3.4.3:

behavior, upon use of a nonportable or erroneous program construct or of erroneous data,
  for which this International Standard imposes no requirements

This seems to imply that, if such "erroneous data" was instead correct, the behavior would be perfectly defined - which seems pretty much applicable to our case.

Additional example: integer overflow. Any program that does an addition with user-provided data without doing extensive check on it is subject to this kind of undefined behavior - but an addition is UB only when the user provides such particular data.

A: Since this has the language-lawyer tag, I have an extremely nitpicking argument that the program's behavior is undefined regardless of user input, but not for the reasons you might expect -- though it can be well-defined (when v==0) depending on the implementation.
The program defines main as
int main()
{
    /* ... */
}

C99 5.1.2.2.1 says that the main function shall be defined either as
int main(void) { /* ... */ }

or as
int main(int argc, char *argv[]) { /* ... */ }

or equivalent; or in some other implementation-defined manner.
int main() is not equivalent to int main(void).  The former, as a declaration, says that main takes a fixed but unspecified number and type of arguments; the latter says it takes no arguments.  The difference is that a recursive call to main such as
main(42);

is a constraint violation if you use int main(void), but not if you use int main().
For example, these two programs:
int main() {
    if (0) main(42); /* not a constraint violation */
}

int main(void) {
    if (0) main(42); /* constraint violation, requires a diagnostic */
}

are not equivalent.
If the implementation documents that it accepts int main() as an extension, then this doesn't apply for that implementation.
This is an extremely nitpicking point (about which not everyone agrees), and is easily avoided by declaring int main(void) (which you should do anyway; all functions should have prototypes, not old-style declarations/definitions).
In practice, every compiler I've seen accepts int main() without complaint.
To answer the question that was intended:
Once that change is made, the program's behavior is well defined if v==0, and is undefined if v!=0.  Yes, the definedness of the program's behavior depends on user input.  There's nothing particularly unusual about that.

A: When you declare variables (especially explicit pointers), a piece of memory is allocated (usually an int). This peace of memory is being marked as free to the system but the old value stored there is not cleared (this depends on the memory allocation being implemented by the compiler, it might fill the place with zeroes) so your int *p will have a random value (junk) which it has to interpret as integer. The result is the place in memory where p points to (p's pointee). When you try to dereference (aka. access this piece of the memory), it will be (almost every time) occupied by another process/program, so trying to alter/modify some others memory will result in access violation issues by the memory manager.
So in this example, any other value then 0 will result in undefined behavior, because no one knows what *p will point to at this moment.
I hope this explanation is of any help.
Edit: Ah, sorry, again few answers ahead of me :)

A: It is simple. If a piece of code doesn't execute, it doesn't have a behavior!!!, whether defined or not.
If input is 0, then the code inside if doesn't run, so it depends on the rest of the program to determine whether the behavior is defined (in this case it is defined).
If input is not 0, you execute code that we all know is a case of undefined behavior.

A: I would say it makes the whole program undefined.
The key to undefined behavior is that it is undefined. The compiler can do whatever it wants to when it sees that statement. Now, every compiler will handle it as expected, but they still have every right to do whatever they want to - including changing parts unrelated to it.
For example, a compiler may choose to add a message "this program may be dangerous" to the program if it detects undefined behavior. This would change the output whether or not v is 0.

A: Your program is pretty-well defined. If v == 0 then it returns zero. If v != 0 then it splatters over some random point in memory.
p is a pointer, its initial value could be anything, since you don't initialise it. The actual value depends on the operating system (some zero memory before giving it to your process, some don't), your compiler, your hardware and what was in memory before you ran your program.
The pointer assignment is just writing into a random memory location. It might succeed, it might corrupt other data or it might segfault - it depends on all of the above factors.
As far as C goes, it's pretty well defined that unintialised variables do not have a known value, and your program (though it might compile) will not be correct.


text:
Q: Is it possible to change the default initial field value via reflection in java? lets say we have a class with an field and it has a default initial value and that is not changed by the constructor, for example
public class Server {
  private int pingFrequency = 500;

  public Server() {
  }
}

Now I want't to change the default initial value to another value BEFORE the object is constructed. The reason is that this class is used by an library and hide away the object instance. So I could only control when the object is constructed but not where and how.
I've tried to get field via reflection, but I dont't see any way to change the default value
Field pingFrequency =  Class.forName("Server").getDeclaredField("pingFrequency")

I think I must change something in the classloader, but I don't know what and how.
Thank you

A: When you declare a class like
public class Server {
  private int pingFrequency = 500;

  public Server() {
  }
}

it is not different to
public class Server {
  private int pingFrequency;

  public Server() {
    pingFrequency = 500;
  }
}

or
public class Server {
  private int pingFrequency;

  {
    pingFrequency = 500;
  }
  public Server() {
  }
}

In fact, all three variants get compiled to identical bytecode. The code of all field initializers and instance initializer blocks gets copied to every constructor¹ of this class, right between the super constructor call and the rest of the constructor. [JLS §12.5]
¹ which does not delegate to another constructor of this class
The only way to change the assigned value is do modify the code of all constructors, to change the assignment. This can not be done via Reflection, but only via bytecode manipulation tools.
Note that when the field has been declared final, like
public class Server {
  private final int pingFrequency = 500;

  public Server() {
  }
}

there will be an attribute in the bytecode, reporting the constant value [JVMS §4.7.2], additionally to the assignment. However, for such a compile-time constant, every ordinary read access will be replaced with the constant value at compile-time[JLS §13.1], so even changing the assignment would have no effect then (neither would changing the attribute)[JLS §13.4.9]. Trying to replace the actual uses of the field would raise the problem that you can't distinguish them from other uses of the constant number 500.
If the field was static and final, there was no assignment at all, the constant value attribute would be used for initializing the field, however, changing it would have as little effect as for a constant instance field, as the field accesses were still replaced with the old constant value.


text:
Q: Make cell reference between a row and columns with a jump between columns using Excel VBA I have tried before that make reference a row to columns/a column to rows. They are not perfect but they work. However, I have trouble when it jumps and I really need help.

My code doesn't return an error but only 1 cell has value "=".

A: Does this work for you:
*added in factor that user needs reference to cells, not just cell values.
Sub Row2ColumnReferance()

Dim rRangeCopy As Range, CRangePaste As Range
Dim jump As Integer

'get input
Set rRangeCopy = Application.InputBox("Select Copy Range", "Transform", Type:=8)
Set CRangePaste = Application.InputBox("Select Destination Range", "Transform", Type:=8)
jump = Application.InputBox("Enter")

Dim cel As Range, intCnt As Integer

'place new cells
intCnt = 1
For Each cel In rRangeCopy
    CRangePaste.Cells(intCnt, 1).Formula = "=" & cel.Address(False, False)
    intCnt = intCnt + 1
Next

Dim intRows As Integer

'insert space
intCnt = CRangePaste.Rows.Count
For intRows = intCnt To 2 Step -1
    Range(CRangePaste.Cells(intRows, 1), CRangePaste.Cells(intRows + jump - 1, 1)).Insert shift:=xlDown
Next

End Sub


text:
Q: How to execute Select query inside loop in batch script? I am trying to execute a select query at interval of few seconds to get latest values. But it connect to database every time it execute select statement inside my batch script. I want to connect only once and then execute select queries. I tried following code.
@echo off
:loop
cls
(
echo user/pass@xyz
echo select COL1 from TABLE;
)| sqlplus

SLEEP 5
goto loop

A: Try with this sentence:
@echo select COL1 from TABLE; | sqlplus user/pass@xyz


text:
Q: How to solve error in Pandas for "The incoming tabular data stream in remote procedure call protocal stream is incorrect I have a pandas dataframe that I'm writing to a table in SQL Server. The data frame contains the following dtypes:
Contact_ID                      object
Skill_No                       float64
Skill_Name                      object
Campaign_No                    float64
Campaign_Name                   object
Agent_No                       float64
Agent_Name                      object
Team_No                        float64
Team_Name                       object
Start_Date                      object
Disp_Code                      float64
Disp_Name                       object
Disp_Comments                   object

When I try to write to SQL Server I get the following error:
ProgrammingError: ('42000', '[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]The incoming tabular data stream (TDS) remote procedure call (RPC) protocol stream is incorrect. Parameter 16 (""): The supplied value is not a valid instance of data type float. Check the source data for invalid values. An example of an invalid value is data of numeric type with scale greater than precision. (8023) (SQLExecDirectW)')

I have tried converting the data types in my sql table to decimal, float, and back again but nothing seems to work. How can I solve this?

A: I encountered this same error message, which in my case was being caused by some float('inf') and float('-inf') values in some columns of my pandas.DataFrame. I resolved this by changing my infinity values to 1 or -1, which made sense in the context of my project. Alternatively, you could remove those rows.
    df.loc[df[col_name] == float('-inf'), col_name] = -1
    df.loc[df[col_name] == float('inf'), col_name] = 1


text:
Q: How can I check which apt repositories / packages are validated by certain keys? I've inherited an Ubuntu 18.04 server which has had some custom repositories and keys added to it in the past. I'd like to ensure all keys are still in use, and see which packages each of them are validating. Is there a way to do this?
I can list all keys by using apt-key list and looking in /etc/apt/trusted.gpg[.d], but how can I compare them to repositories and packages?

A: The validation is provided by signing the MD5 sums of the packages listed in the Release file of the APT source. Download the Release.gpg from each source and check which keys are used for signing them. This way you'll get a list of the packages signed with the key – not the other way around.
E.g. deb http://us.archive.ubuntu.com/ubuntu/ bionic main restricted

*

*has its Release file signed in Release.gpg

*gpg -vv Release.gpg gives keyid 3B4FE6ACC0B21F32

*Compare the key ID with the ones on your apt-key list:
/etc/apt/trusted.gpg.d/ubuntu-keyring-2012-archive.gpg
------------------------------------------------------
pub   rsa4096 2012-05-11 [SC]
      790B C727 7767 219C 42C8 6F93 3B4F E6AC C0B2 1F32
uid           [ unknown] Ubuntu Archive Automatic Signing Key (2012) <ftpmaster@ubuntu.com>


text:
Q: React Native Movies Example SearchBar I have doubt that why in SearchScreen.js has this code line:
var SearchBar = require('SearchBar');

But I don't see any file SearchBar.js, only see SearchBar.android.js and SearchBar.ios.js. I don't understand why it can run ?

A: You'll find the answer in the React Native documentation:
Platform Specific Code

Platform specific extensions
  React Native will detect when a file has a .ios. or .android. extension and load the right file for each platform when requiring them from other components.
For example, you can have these files in your project:

BigButton.ios.js
BigButton.android.js

With this setup, you can just require the files from a different component without paying attention to the platform in which the app will run.

var BigButton = require('./components/BigButton');

React Native will import the correct component for the running platform.

A: try this
you must use absolute path
var SearchBar = require('./searchBar');


text:
Q: Construct an if from the values of an object I have a Typescript project in which I need to build a dynamic if from the data I receive from the object, I have to add as many conditions as properties the object has.
This is the object:
interface EmailParams {
  sender?: string,
  subject?: string,
  fileType?: string
}

let params: EmailParams = {
  sender: "test@gmail.com"
}

This is what I need:
if (test1.from.toUpperCase() == params.sender?.toUpperCase())

But if the object changes, this is a new object:
interface EmailParams {
  sender?: string,
  subject?: string,
  fileType?: string
}

let params: EmailParams = {
  sender: "test@gmail.com",
  subject: "data"
}

This should be the new if:
if (test1.from.toUpperCase() == params.sender?.toUpperCase() &&
    test1.data.toUpperCase() == params.subject?.toUpperCase()
)

A: You can do this generally by doing something like this:
const keys: (keyof EmailParams)[] = [
  'sender',
  'subject',
];

const test = {
  data: "whatever",
  from: "foobar",
};

const testToEmailParamsMapping: {
  [k in keyof EmailParams]: keyof typeof test
} = {
  subject: 'data',
  sender: 'from',
}

const testEmailParams = (obj: EmailParams): boolean => {
  return keys.every((k: keyof EmailParams) => {
    if (k in testToEmailParamsMapping) {
      // cast is safe because of the check, not sure why compiler doesn't follow
      const testKey: keyof typeof test = testToEmailParamsMapping[k] as keyof typeof test;
      return obj[k]?.toUpperCase() === test[testKey].toUpperCase();
    }
    return true; // we don't care about the keys we don't care about
  });
};

console.log(testEmailParams(params));

If you add a property then there are only two places you need to update: the list of keys, and the mapping that correlates keys in the email params with keys in the test object.
This has some other advantages: you can easily write unit tests for this in a way that would be error-prone with your conditional logic (did you cover every possible branching?) and it's now abstracted into a well-named function you can pass to other parts of the code.
Playground


text:
Q: How to create single check box event for all check boxes in android? I'm new to android it is possible in .net, But i want to build this logic in android is it possible to do that please help me, i know only creating check box event for each check box instead of that i want to create single event for all Check boxes please help me.
Vb.net
private sub Chkbox1_Checkchanged(byval sen as object,byval e as system.eventargs) handles Chkbox1.checked,chkbox2.checked,chkbox3.checked
    blnvalue=true
end sub

android
  chkbox1= (CheckBo1) findViewById(R.id.chkbox1);
  rbtn1.setOnClickListener(new View.OnClickListener()
  {
      public void onClick(View v)
      {
              blnvalue=true;
      }
   });

A: implements  onCheckChangedEvent for for all checkBox.
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

        if (buttonView.getId() == activity.getCheckRefresh()) {
            activity.setRefreshRate("1");
            activity.setEnable(isChecked);
            return;
        }
}

A: Assuming you are in an Activity, you can make your Activity implement View.OnClickListener, and then use this for each View within your Activity, even ones that aren't CheckBox.
public class MyActivity extends Activity implements View.OnClickListener {

    //declare checkboxes

    public void onCreate(Bundle something) {
        //setup stuff and get views

        rbtn1.setOnClickListner(this);
        rbtn2.setOnClickListner(this);
        rbtn3.setOnClickListner(this);
        rbtn4.setOnClickListner(this);
    }

    public void onClick(View v) {
       if(v == rbtn1) {
           //do stuff for checkbox1
       } else if(v == rbtn2) {
           //do stuff for checkbox2
       } else if(v == rbtn3) {
           //do stuff for checkbox3
       } else if(v == rbtn4) {
           //do stuff for checkbox4
       }
    }
}

A: You can also use onChackChanged Event & OnClickEvent for checkbox.
chkbox1= (CheckBo1) findViewById(R.id.chkbox1);
chkbox2= (CheckBo1) findViewById(R.id.chkbox2);

chkbox1.setOnClickListener(this);
chkbox1.setOnCheckedChangeListener(this);

chkbox2.setOnClickListener(this);
chkbox2.setOnCheckedChangeListener(this);

public void onClick(View v)
{
   if(v.getId() == R.id.chkbox2)
          // your code
}

public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

    if (buttonView.getId() == activity.getCheckRefresh()) {
        activity.setRefreshRate("1");
        activity.setEnable(isChecked);
        return;
    }
}

A: u can do this.. here click is an inner class.. and create an instance of it n pass it to every setOnClickListener(click)
class click implements OnClickListener
{
 public void onClick(View v)
{
// your code
}

}


text:
Q: How to save .jpg NOT .JPG When uploading photos from my iPhone to use for eBay they are automatically saved as .JPG (all caps). However eBay only recognizes .jpg. So I have to manually go back in and rename all the files with the lowercase .jpg.
Is there anyway to have them automatically be uploaded in .jpg and not .JPG, its very time consuming. Any help would be greatly appreciated, thanks.

A: I'm not sure about changing how they are uploaded, but if you are uploading them to a folder on ubuntu, you can perform a mass rename to rename everything at once if it makes it easier.
Open up a terminal and type
cd /path/to/photos
rename 's/\.JPG$/.jpg/' *.JPG

And that will find all files in the directory ending with .JGP and change them to .jpg.

A: You make no mention of Ubuntu, but you posted this in AskUbuntu. I'm going to assume you are moving photos like this iPhone -> Ubuntu -> eBay, since anything else would probably be off-topic.
Shotwell can do this easily, it's in the preferences menu 'Rename imported files to lowercase':

If Shotwell can't import directly from the iPhone, just copy the images to your Desktop and then import them into Shotwell from there.
Another easy option is to use pyrenamer from the software center. It's especially useful if you are doing lots of these retroactively, and you can also rename JPEGs based on embedded metadata like dates & times.


text:
Q: One time date to be allowed in android Hi In My Application I have one form with date field.Now If I click the submit button I want to show Toast message already date exist in database.
Suppose today dates I was selected then next click the submit button I am displaying some values.Now If I selected same date I don't want to allow that date.Means One time that date I want to accept for next time means I don't want to allow to next page.
can anyone please help me.

A: This is just concept. You just add one more filed in your table like date_selected. And put 0 as default. When the user will select the date then just update the 0 to 1 for that date. 0 Suppose,means not selected. 1 means selected.

A: You have to add one more field in your sqlite table. So that whenever the user will select the correspond date then you have to put the flag for that date. And while accessing the date you can distinguish that the date has been already selected or not.


text:
Q: Group multiple HTTp samplers as one transaction, and have constant throughput In my application, I would like to combine a group of HTTP samplers as one transaction, and have a constant throughput on the group.. ie. when I created a thread group with multiple HTTP samplers and defined a constant throughput timer in the group, I am seeing that it is considering each HTTP sampler separately...
Test Plan
ThreadGroup
----> request 1
-----> request 2
-----> request 3
------> constant Throughoput timer ( 1.0 req per min)
It executes as :
-----> request1
wait 60 secs
------> request 2
wait 60 secs...
----> request 3
...
what I would like
-----request 1
----- request 2
------ request 3
wait 60 secs
----- request 1
---- request 2
----- request 3
wait 60 secs

A: Depending on what exactly you're trying to achieve:
You can put the requests under the Transaction Controller and tick Generate parent sampler box:

Another option is adding Flow Control Action sampler as the 4th sampler and put the "wait for 60 sec" there

And finally you can put a Constant Timer as a child of the 1st Sampler:

A: use flow control action at the end of the requests
for better understanding difference between timers & flow control action, please go through this video
https://www.youtube.com/watch?v=miZGLaAq4UQ&t=301s


text:
Q: ssh key errors when trying to connect a worker I'm trying to set up concourse for the first time. I went through tutorials and was successful getting concourse running in vagrant and the hello world demo.  I want to know set up worker, for now this is all on my local machine, to do iOS builds. I can't seem to get the right ssh keys set. I keep getting:
{"timestamp":"1499972495.137019873","source":"worker","message":"worker.beacon.restarting","log_level":2,"data":{"error":"failed to dial: failed to construct client connection:%!(EXTRA *errors.errorString=ssh: handshake failed: remote host public key mismatch)","session":"3"}}```

I generated my local worker keys per the tutorial, and found the keys in the vagrant vm at /opt/concourse. However, any public keys I copy from the server for the TSA key don't seem to match what's expected.
Am I having trouble because I'm running the lite version from the tutorial?
Are the keys in /opt/concourse ones I want to use?

A: I've had troubles as well with registering workers at the TSA, although in my case the error message was slightly different (EOF or packet too large). Since it is an SSH error, try to debug it step by step. I am not sure what your setup looks like, mine is as follows:
TSA    (from docker-compose) listening on 2222
Host   (runs concourse). 127.0.0.1:2228 maps to docker container on :2222
nginx  listening on 2222
Worker (on Windows, OS X, …) registers at TSA

Some of those pieces breaks SSH traffic, so try to log in on this port with SSH directly. Go step by step, first test on the host only (to see if you can access the docker container), then test from the worker (to see if you can get through nginx). For the above case
# On the host
ssh -i worker-key-path -p 2222 127.0.0.1 -v
# On the worker
ssh -i worker-key-path -p 2222 example.com -v

Note that the public key of the worker has to be known to TSA in the authorized_worker_keys file.
On a successful login, you should see
Authenticated to example.com ([12.34.56.78]:2222).
[...]
PTY allocation request failed on channel 0
shell request failed on channel 0

If you see an error message like
ssh_exchange_identification: Connection closed by remote host

then the nginx configuration is wrong, which should redirect with stream:
stream {
    server {
    listen 2222;
    proxy_pass 127.0.0.1:2228;
    #proxy_ssl on;
    }
}


text:
Q: Float point to display hexadecimal x86-64 nasm linux Trying to convert float to hexadecimal in nasm

A: How to convert a DWORD (single precision floating point number) to hexadecimal
The hexadecimal notation is just a simplification of the binary notation. Four bits at a time form one hexadecimal digit.
With
SA: dd 500.312

NASM converts the decimal number 500.312 into the internal format "DWORD" - a bunch of 32 bits:
01000011111110100010011111110000

Group them to 4-bit groups (nibbles) and convert every group to decimal:
0100 0011 1111 1010 0010 0111 1111 0000
   4    3   15   10    2    7   15    0

The easiest way to get hexadecimal digits is a lookup table. A string is an appropriate way to form an array of 16 hexadecimal characters:
hex db "0123456789ABCDEF"

Interprete the numbers of each nibble as index of the array  ([hex+index]) and store it in a string to be outputted.
A challenge is to isolate the nibbles from left to right. You can us the ROL,4 instruction, mov the result to another register and isolate the nibble with AND 0x0F. Another way is to use SHLD. When you have isolated the nibble you have also the index of the hex array.
Example:
BITS 64
DEFAULT rel
GLOBAL _start

SECTION .data
    SA dd 500.312               ; Single floating point number
    hex db "0123456789ABCDEF"   ; Array of 16 characters
    lf db 10                    ; New line

SECTION .bss
    outstr resb 16              ; Array of 16 unitialized bytes

SECTION .text

DWORD_to_hex:                   ; ARG: EAX: DWORD value, ESI: Pointer to an array of at least 8 bytes
    xor esi, esi                ; RSI = 0 (access to ESI clears the upper DWORD of RSI)
    mov ecx, 8                  ; RCX = 8
    .LL3:
    xor sil, sil                ; Clear lowest byte of RSI
    shld esi, eax, 4            ; Copy 4 leftmost bits from EAX to ESI
    shl eax, 4                  ; Shift EAX accordingly
    mov dl, [hex + esi]         ; Get a hexadecimal character
    mov [edi], dl               ; Store the character
    add edi, 1                  ; Increment the pointer to outstr
    loop .LL3                   ; Loop RCX times

    ret

_start:                         ; Entry point - here starts the program

    mov eax, [SA]               ; Single floating point number coded as DWORD
    mov rdi, outstr             ; OFFSET outstr
    call DWORD_to_hex

    ; Show hex (8 characters)
    mov eax, 1                  ; SYS_WRITE
    mov edi, 1                  ; STDOUT
    mov rsi, outstr             ; Message address
    mov edx, 8                  ; Number of bytes to display
    syscall                     ; Call Linux

    ; New line
    mov eax, 1                  ; SYS_WRITE
    mov rdi, 1                  ; STDOUT
    mov rsi, lf                 ; Message address
    mov edx, 1                  ; Number of bytes to display
    syscall                     ; Call Linux

    ; Exit (0)
    mov eax, 60                 ; SYS_EXIT
    mov edi, 0                  ; Exitcode
    syscall                     ; Call Linux / no return

Adjust these steps to get the hexadecimal representation of a QWORD (64 bits) which represents a double precision flosting point number.


text:
Q: How to instantiate an unknown number of instances in python3.2 I have been working on a card game in python 3.2 and am not sure about how to instantiate separate players. The game can have anywhere from 2 players to 8 players. I was thinking I could use brute force and have something like:
   players = int(input('how many players?: ))
   if players ==2:
       p1 = Player()
       p2 = Player()
   elif players ==3:
       p1 = Player()
       p2 = Player()
       p3 = Player()
   elif players ==4:
       p1 = Player()
       p2 = Player()
       p3 = Player()
       p4 = Player()

etc...
that seems dirty. Is there a cleaner way of getting around this?
Thank you.

A: Use a list and a for loop:
players = int (input ('how many players?: '))
if not 2 <= players <= 8:
  <raise an exception or something>

p = []
for _ in range (players):
  p.append (Player())

Now you have a list of players that you can do what you like with.


text:
Q: ByteArrayBody from org.apache.http.entity.mime.content cannot be reached I'm having a hard time using the ByteArrayBody class from the org.apache.http.entity.mime.content in my eclipse project (android app). I copied the httpmime-4.5.1.jar in my libs folder and did all the stuff in the javabuild path (adding the .jar and checking it in Order and Export section).
Looks like this class cannot be reached for some reason, do I miss something including the .jar in my project ? Code looks like this :
   ByteArrayOutputStream baos = new ByteArrayOutputStream();

   bp.compress(Bitmap.CompressFormat.JPEG, 75, baos);

   byte[] imageBytes = baos.toByteArray();

   HttpClient httpclient = new DefaultHttpClient();
   HttpPost httpPost = new HttpPost("__mypath__");

   httpPost.setHeader("Content-type", "multipart/form-data;   boundary="+boundary);

   ByteArrayBody bab = new ByteArrayBody(imageBytes, "pic.jpg"); //CRASHING HERE

   //...

Any help would be appreciated,
thx in advance !

A: Got it ! I only included the mime .jar, but I also need the client, the core and the other jars in my libs directory and add them to build path.


text:
Q: What plugins are necessary for Play Framework 2 for intellij (and how to install) I am unable to install Java Play Framework Support for Play 2 in intellij ultimate 2016.2.4. I'm not sure if I really need it. I have the Scala plugin which says it has Play 2 Support. I see all kinds of conflicting documentation.
I had the Playframework Support for Play 1 but unchecked that. When I search for Play 2 plugin I get nothing. I downloaded it directly but was unable to install from disk. The download has a directory scala-play-2 so, again, I'm not sure if this is the plugin I already have. When I click on 2 of the jars, sbt-launch and  scala-play-2-jps-plugin.jar, it says "fail to locate plugin descriptor". When I click scala-play-2.jar it says "Plun play 2.0 support is incompatible with this installation'.
I right click my project to add framework support. I see the Play 2.x framework is unchecked. When I check and enter it does nothing. Not sure if this is related but in the Framework Support dialog it has a select for Java EE version. It only goes to Java EE 7. My project and platform settings are set to jdk 1.8.
If someone has a current working configuration I sure would like to know what that is.

A: Since you have scala plugin, the problem should be you have to install sbt plugin.

*

*Go to settings -> Plugins -> Browse Repositories. And search for sbt plugin. Then you can install. :))


text:
Q: winbase.inl missing in Windows Phone Kits I have some native static library(say MyLib), wich includes windows.h, and I'm trying to reuse it in my WP8 app:

*

*I've copied lib's project file,

*renamed it (MyLibWP),

*changed platform toolset to Windows Phone 8

*tried to build it.

After which I'm getting the following error:

C:\Program Files (x86)\Windows Phone Kits\8.0\Include\winbase.h(10170): fatal error C1083: Cannot open include file: 'winbase.inl': No such file or directory

Kinda weird. Checked the specified folder - it does tell the truth, file is missing.
So, what is wrong with all this stuff?
Edit: tried to copy missing file to \Windows Phone Kits\8.0\Include\ manually, but that doesn't help.

A: I would reinstall the SDK, I have winbase.h on my machine, at C:\Program Files (x86)\Windows Phone Kits\8.0\Include


text:
Q: How to check if your ssh keys are in the ssh-rsa2 format? So recently there were news of OpenSSH dropping support for SHA-1 logins and I am trying to understand which format they are referring to. Since years i've been generating keys via ssh-keygen -t rsa -b 2048. Is this the type not recommended anymore and I should switch for example, to ECDSA?
In this man page, https://www.man7.org/linux/man-pages/man1/ssh-keygen.1.html , the default option rsa for the -t argument explains that the chosen option is using the SHA1 signature, so one should choose rsa-sha2-256 for example.
I tried checking the type of the key with ssh-keygen -l -f key and it shows me that it is indeed SHA256 type. If so, then it solves my question but some clarity would be welcome. thank you!
Source of news: https://www.zdnet.com/article/openssh-to-deprecate-sha-1-logins-due-to-security-risk/

A: The key format has not changed. The only thing that changes is the signature format that's sent during each authentication handshake.
What makes everything confusing is that originally in SSHv2, the key type and the signature type used to be defined in combination. (For example, the same "ssh-rsa" identifier was defined to mean RSA keys and RSA/SHA-1 signatures.) So changing the signature process would have meant assigning a new key type identifier, and that would have meant generating a new key...
However, protocol extensions have been developed to avoid this, and modern SSH clients will automatically negotiate the signature types whenever RSA keys are involved. If you connect with ssh -v you will notice a few additional packets being exchanged:
debug1: SSH2_MSG_EXT_INFO received
debug1: kex_input_ext_info: server-sig-algs=<ssh-ed25519,ssh-rsa,rsa-sha2-256,
                            rsa-sha2-512,ssh-dss,ecdsa-sha2-nistp256,
                            ecdsa-sha2-nistp384,ecdsa-sha2-nistp521>

So you can continue using "ssh-rsa" keys – you only need to upgrade the software on both ends to something reasonably recent, and it will automatically start producing "rsa-sha2-256" signatures from that key. (For example, you might need to install a new version of PuTTY and Pageant, and you might have troubles with older versions of gpg-agent.)
Signatures in ssh-keygen

the default option rsa for the -t argument explains that the chosen option is using the SHA1 signature, so one should choose rsa-sha2-256 for example.

This applies when issuing certificates, but is irrelevant when generating plain keys.
Each certificate is signed by the parent CA at the time it is issued. This long-term signature is stored in the certificate itself (and it's very important to realize that this is a different thing from the short-term signatures that are made during each connection and then thrown away). That's why many HTTPS (X.509) certificates had to be replaced – the issuing CA had stamped them with RSA/SHA-1 signatures.
OpenSSH has also created its own certificate format, which is what the manual page is referring to. These so-called "SSH certificates" are not just regular SSH keys – they're additionaly signed by e.g. your workplace CA. So if you have files whose names end with *-cert.pub, you might need to have those re-issued. (Use ssh-keygen -Lf <file> to check how they were signed).
But plain SSH keys do not hold any long-term signature inside – they're only used to make temporary signatures during each connection. So there is nothing that needs replacement in the key itself.
The -l option

I tried checking the type of the key with ssh-keygen -l -f key and it shows me that it is indeed SHA256 type

No, that is not what ssh-keygen shows at all. The -l option is showing you the key's "fingerprint" and it's telling you that it used SHA256 to compute this fingerprint – but it has nothing to do with the key's type, nor with how the key will actually be used. The fingerprint is just a hash that was computed right now in order to be shown to you.
(Remember that previously SSH software used to show MD5-based key fingerprints – even though there was no MD5 usage in the actual SSHv2 protocol.)
Other key types

Is this the type not recommended anymore and I should switch for example, to ECDSA?

From what I know (i.e. from what I gathered on Security.SE), RSA as a signature algorithm is still strong – problems mostly just occur when trying to use RSA as an encryption algorithm, and that's not an issue with SSHv2. (Well, the ever-increasing key size is not great either.)
ECDSA has its own problems – it is difficult to get its implementation right and certain kinds of programmer mistakes can be disastrous. If you had to switch, EdDSA (that is ssh-ed25519 or ssh-ed448) would be a better option.


text:
Q: State is different that props I have a class like this:

And I render this class from another class.
But I have some problem. When I try to call component Screen with changed props - state doesnt change.
It is screen from react-tool:

I call Screen directly from Dashboard:

Props is different than state. I do not know why.

A: It is not a best practice to set state with props values. you should use props directly.
constructor lifecycle runs only once when the component loads
if you have changes in data while component is loaded you should use the proper lifecycle to change
componentDidUpdate() that runs after every change. here you can run a setState function and it will updated your component with fresh data.
for more reading about update life cycles :
ReactJs componentDidUpdate()

A: i think you can solve that situation of 2 ways.
1- you can define goToPage in your state and use props like you do.
this.state = {
  gotoPage: props.gotoPage,
  page: props.page,
  data: props.data
}

to access that state, use this.state.
2 - How your component just have props, use component stateless and  inside of your component use only props.blabla.
https://itnext.io/react-component-class-vs-stateless-component-e3797c7d23ab
:D


text:
Q: Java "NotSerializableException: java.net.Socket" When Not Sending A Socket So I send a Server object to a client with this thread:
public ConnectionThread(final Server server) {
    super(new Runnable() {
        public void run() {
            try {
                Socket client = server.serverSocket.accept();
                server.clients.add(client);

                ObjectInputStream in = new ObjectInputStream(
                        client.getInputStream());
                ObjectOutputStream out = new ObjectOutputStream(
                        client.getOutputStream());

                System.out.println("Connected client: "
                        + client.getRemoteSocketAddress());
                server.launchNewThread();

                Object input;
                while (!client.isClosed()) {
                    input = in.readObject();

                    if (input != null) {
                        if (input.toString().equals("server")) {
                            out.writeObject(server);
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

And when I call out.writeObject(server) I get this exception:
java.io.NotSerializableException: java.net.Socket

Here is the Server class:
public class Server implements Serializable {
private static final long serialVersionUID = 4634111951586948020L;

public ServerArgs args;

public ArrayList<Socket> clients = new ArrayList<Socket>();
public ServerSocket serverSocket;

public Server(int port) throws IOException {
    serverSocket = new ServerSocket(port);

    launchNewThread();
}

public void launchNewThread() {
    ConnectionThread thread = new ConnectionThread(this);
    thread.start();
}

public static void main(String[] args) throws IOException {
    new Server(27015);
}
}

A: public ArrayList<Socket> clients = new ArrayList<Socket>();
public ServerSocket serverSocket;

You have plenty of non-serializable sockets right there. It's very unclear what the purpose of "sending a server" is, but perhaps you should either just send the ServerArgs or mark those two fields transient.


text:
Q: Setting up AG listeners I am relatively knew to MSSQL so please bare with me.
My infrastructure is currently in AWS.
I have 3 servers running MSSQL. I have a primary replica and two secondary replicas. All three servers are in 1 AG group and there is 1 database being replicated.
Server 1 is in AZ A (Subnet A)
Server 2 is in AZ A (Subnet A)
Server 3 is in AZ B (Subnet B)
All are set for automatic sync failover. I am working on adding a listen for these 3 replicas.
As far as I can tell you can only add a static listener with the two different subnets.
So lets say I add an IP for Server 1 and Server 3. It wont let me add it for Server 2 because its 1 per subnet.
How would this work. Am i missing something here? Am I doing something wrong?

A:
How would this work. Am i missing something here? Am I doing something
wrong?

You don't need another IP for Server 2 because it is in the same subnet as Server 1. Your listener requires 1 valid IP address for each subnet that a cluster node is in. In your case, you have 3 servers, but only 2 subnets so you only need 2 IP addresses for the listener.
Only one IP is ever 'active' for the listener so even if the AG fails over from Server 1 to Server 2, the IP address for the listener will stay the same, but Server 2 will begin listening on that IP.


text:
Q: Listview OnItemClick and button In my application I have listview. Each listview's item has button.
When I press onItemClick button's state change too.
Here is my code
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@drawable/button_gl"/>
    <item android:state_selected="true" android:drawable="@drawable/button_gl"/>
    <item android:state_enabled="false" android:drawable="@drawable/button_unselect"/>
    <item android:state_focused="false" android:drawable="@drawable/prod_button"/>
    <item android:drawable="@drawable/prod_button"/>
</selector>

and this is my listview item button
 <Button
                        android:id="@+id/productAdd"
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        style="@style/button_style"
                        android:background="@drawable/button_indicator"
                        android:layout_gravity="center_vertical"
                        android:gravity="center"
                        android:focusable="false"
                        android:focusableInTouchMode="false"/>

I don't understand what I did wrong here, and why always button get changed his state when I press on Listview's item?

A: You're pointing out that upon list item selection your button changes state and this behavior is undesired. I think that this may be caused by this line:
   <item android:state_selected="true" android:drawable="@drawable/ph_prod_button_gl"/>

If the item is selected also the contained button is selected.
Have you tried removing it?
Let me know if this works.


text:
Q: How to call a rest service in listitemreader then write those list items into a flat file How to call a rest service in listitemreader then write those list items into a flat file using spring batch.

A: You batch job steps needs to have the following itemReader, itemProcesor and itemWriter.

*

*listitemreader - read the element of the list

*itemProcessor  - create an item processor that processes the item read - by making a test call

*FlatFileItemWriter - writes the processor record to the file
The Spring batch guide explains the user of reader,writer and processor in good detail - http://docs.spring.io/spring-batch/reference/html/readersAndWriters.html


text:
Q: find: 'home/': No such file or directory while trying to automate maintenance tasks I'm trying to create a bash script to perform some maintenance tasks on a remote server using ssh. I've been trying to figure it out on my own, but I'm having some difficulty. I was hoping someone here on Stack Overflow might be able to help me out.
I'm not very familiar with bash scripting, so any guidance or suggestions you could provide would be greatly appreciated.
Here's what I'm trying to accomplish:

*

*Connect to a remote server via ssh

*Delete files that are older than 3 months

*Update server packages

*Check disk sizes and send a notification if the disk is 75% full

Commands:

*

*SSH into the remote server.

*Update server packages.

*Delete files older than 3 months.

*Check disk sizes and send notification if 75% full.

# maintenance.sh
# Connect to the remote server
ssh username@remote_server_ip "cd /"

# Update server packages
ssh username@server "apt-get update && apt-get upgrade"

# Delete files older than 3 months
ssh username@server "find home/ -mtime +90 -delete"

# Check disk sizes and send notification if 75% full
ssh username@server "disk_size=$(df -h / | grep -v Filesystem | awk '{print $5}')
if [[ $disk_size > 75 ]]; then
  echo 'Low disk space on server. Disk usage is currently at $disk_size%' | mail -s 'Low Disk $ip a Alert' admin@example.com "

Problems:

*

*The find command doesn't seem to be working as intended. It's not deleting any files.

codemastermind@ThinkPad-X230:~/scripts$ ./maintenance.sh
find: 'home/': No such file or directory
E: Could not get lock /var/lib/dpkg/lock-frontend - open (11: Resource temporarily unavailable)
E: Unable to acquire the dpkg frontend lock (/var/lib/dpkg/lock-frontend), is another process using it?
codemastermind@ThinkPad-X230:~/scripts$


text:
Q: Using facebook to login then signal to create a userprofile I've spent some time on Django packages looking at the ridiculous amount of options for facebook integration. I was hoping someone could narrow the choices for what I want to do. I want to be able to access the API with python and perform various tasks. The main task right now is the following:
I need to get the users facebook email from cookies and then use it to create a local profile where other information will be stored. If there is a good example of someone doing this or if a particular module has good docs that would suffice.
Edit: Also note - I do not want to use registration. I want the profile to be created when the user uses FB login.

A: Facebook: http://catherinetenajeros.blogspot.com/2013/03/facebook-login.html
 def get_profile(request, token=None):
    args = {
        'client_id': settings.FACEBOOK_APP_ID,
        'client_secret': settings.FACEBOOK_APP_SECRET,
        'redirect_uri': request.build_absolute_uri(reverse('pets:fb_callback')),
        'code': token,
    }

    target = urllib.urlopen('https://graph.facebook.com/oauth/access_token?' + urllib.urlencode(args)).read()
    response = cgi.parse_qs(target)
    access_token = response['access_token'][-1]

    return access_token

def fb_login(request):
    args = {
        'client_id': settings.FACEBOOK_APP_ID,
        'scope': settings.FACEBOOK_SCOPE,
        'redirect_uri': request.build_absolute_uri(reverse('app_name:fb_callback')),
    }
    return HttpResponseRedirect('https://www.facebook.com/dialog/oauth?' + urllib.urlencode(args))

def fb_callback(request):
    access_token = get_profile(request, request.GET.get('code'))
    fb_profile = urllib.urlopen('https://graph.facebook.com/me?access_token={0}'.format(access_token))
    fb_profile = json.load(fb_profile)

    fb_username = fb_profile.get('username', fb_profile['email'].split('@')[0])
    fb_id = fb_profile.id
    fb_email = fb_profile.email

    [.........]


text: Q: Permutable subgroups, but a conjugate one one group does not commute with other group Let $G$ be a finite group and $A,B \le G$ subgroups. Do you know an example where $AB = BA$, but $A^gB \ne BA^g$ for some conjugate $A^g$ of $A$?


text:
Q: Measurement of quantum state Consider a particle in a box system. Assume its state to be a superposition of the ground and the first excited energy states. Consider two observers A and B (rest of the world). A made the measurement of the energy of the system and got energy corresponding to one of the states. Consider two scenarios:

*

*A made the measurement and B is not aware of it at all. For B would the state still be the superimposed state?

*A made the measurement and B know(s) but is unaware of the result. Would it be ok to say that for B the state of the system is still the same as it was initially?
Are these two scenarios equivalent?

A: It sounds to me like you're asking about "Quantum Bayesianism", or "QBism" as it's called by David Mermin, one of its principal proponents, e.g.,
http://arxiv.org/abs/1311.5253
Or you can google those two terms in quotes for lots more references. Is that what you're talking about? And do their interpretations answer your questions?

A: A measurement is a form of interaction.  A's interaction with the state is information that B is not unaware of.  Which is equivalent to say that A's interaction is information that B cannot use.  Thus, your two statements are equivalent in that the best B can do is use the information about the state that he does have to make a prediction.  A practical example of this makes the situation more clear.
Consider an experiment where A measured the spin of an unpolarized particle to be +1/2 in the z-direction.  B is unaware of A's measurement.  B subsequently measures the z-direction spin and finds it to be +1/2.  This is a reasonable from a prediction using the superimposed state (unpolarized) state with 50% probability of being +1/2 and 50% probability of being -1.2
Now consider the same situation but with B being aware of A's measurement but unaware of the result.  It remains that the best B can do is still make a probabilistic prediction.
Now consider the same experiment repeated over and over again.  On B's measurement after A's measurement, B will see that 50% of the time the particle is +1/2 and 50% of the time the particle is -1/2.  Thus, to B, the state is a superposition as expected.  However, if A were to join B on the subsequent measurement and tell B of his early results, then B could use the collapsed state and predict the correct spin 100% of the time (since A already measured it).  But, both predictions accurately conform to the results of the experiment, however one prediction (A's prediction) contains more knowledge about the system.

A: The relevant issue is not what B knows, but rather whether the content of the measurement result has affected B. If the content of the result has affected B then B will not be able to arrange interference between the different results of that measurement. For example, suppose that the information about the result has been displayed on a computer screen and the light from the screen has interacted with B's skin while his back is turned, then he will not be able to produce interference between the results.
See papers about decoherence such as
C. Jess Riedel, Wojciech H. Zurek, Quantum Darwinism in an Everyday Environment: Huge Redundancy in Scattered Photons, Phys. Rev. Lett. 105, 020404 (2010)
http://arxiv.org/abs/1001.3419.
There is a slight complication. When two systems are entangled the correlations between them are explained by decoherent systems carrying quantum information in observables in such a way that the content of the information doesn't change the expectation values of those observables.  See David Deutsch, Patrick Hayden, 'Information Flow in Entangled Quantum Systems', Proc. R. Soc. Lond. A 456(1999):1759-1774. available at http://arxiv.org/abs/quant-ph/9906007. And also David Deutsch, 'Vindication of quantum locality', Proc. R. Soc. A 468(2012), 531-544. available at http://arxiv.org/abs/1109.6223.

A: It shouldn't make a difference because in both cases the particle is measured.
This kind of question can be rather muddy -  physicists try to stay away from using the words 'observer' and 'measurement' in quantum mechanics because they raise more questions than they answer.
At any rate, most physicists prefer 'interaction with a macroscopic system'.


text:
Q: Working out the Kurtosis
I'm not able to understand how it is that they got from 3E(e^2at)/E(e^at)^2 to the next line where they got rid of the expectation in both the numerator and the denominator and then simplified to get the final answer which I also don't understand how they simplified from the second last line. So essentially I don't understand how they worked out the expectation of the numerator term and the denominator term.
Any help would be much appreciated.

A: HINT
$\alpha_t$ has a normal distribution $\mathcal N (\mu,\,\sigma_{\alpha}^2)$, then $e^{\alpha_t}$ has a log-normal distribution with mean $e^{\mu+\sigma^2_{\alpha}/2}$.


text:
Q: Get Share Count of Public Video with FB API v2.5 The Short Version:
"I can visit the public page without being logged into Facebook and see underneath the post is says "2155 shares" I would like to know how to access that number through the API"
The Details:
I'm trying to use the newest version (v2.5) of the graph HTTP API to determine the total share count for a public video.  The problem is FB seems to have changed the API enough that older posts on SO no longer answer this question.
Looking at the Graph API Documentation it appears that video nodes now have the "sharedposts" edge.  However, calling this route with summary=true only returns a few of the shares and no value for a total count.  This returns counts for comments and likes so I'm not using the endpoints incorrectly or messing up my authorization.
I've also tried to use the URL Node but this doesn't seem to do much with links inside of Facebook.  I simply get a JSON response with an 'id' field with the same url I supplied as a request parameter.  Seems like this route is meant to be used for links to content outside of Facebook.
I've tried the above methods with multiple videos on multiple public pages so I don't think it is due to the group owners restricting access, unless this is the new default.
It seems arbitrary that I would be allowed access to total counts for comments and likes, but not shares.  Is there some legacy way to do this or am I out of luck for now?

A: You should query the Post element containing the Video element.
Each video posted is also contained in a post element.
The post id is then composed of the video id prepended with the posting entities id (user, page etc'), separated with an underscore.
It then looks like: user-id_video-id.
Then using the Graph API to get the share count of a post is straightforward:
GET /v2.5/{post-id}?fields=shares

Example
Lets take a video from the BBC page:
https://www.facebook.com/bbcnews/videos/10153524838517217/
(Please tell me if the link is broken. I'll switch it to something newer :))
Video id : 10153524838517217
Page id (see below): 228735667216
--> Post id: 228735667216_10153524838517217
And the request would be:
GET /v2.5/228735667216_10153524838517217?fields=shares

(open in the Graph API explorer)

Page id
to get the page id, you could query the video element for the from field.
GET /v2.5/10153524838517217?fields=from


text:
Q: How to link paypal for checkout in android I have involved with a serious problem. I want to checkout via paypal in android. I saw this link How to integrate paypal to android app using webview  and run it. I found that paypal page opened but there is written "demo" in the left-bottom.  so i am confused should i used it for my real application?
if yes, What parameters should i need to pass? and how can i do it?
second I run to paypal sdk. and there is a sample demo. i run it and found that it login without internet.  Please any once help me how can i exact use it.
do there any exact source code?
Your help is my great help!
Thank you

A: Jeff here from the PayPal Android SDK.  I'm not sure I fully understand your issue.  Are you using the PayPal Android SDK?  If so, please ensure you're following the readme during your integration.  Naturally, the SDK will allow login without internet in mock mode.


text:
Q: Why are there no quotation marks for a that-clause?
*

*"Bonjour" is a French word meaning "hello."

*In modern Welsh, 'glas' means 'blue'.

But why do we say, for example, the sentence means that the word means "hello," not the sentence means 'the word means "hello"'?

A: You seem to be confused by the use/mention distinction.
When you use a word it is not normally quoted. When you mention a word it is sometimes quoted:

"Apple" has five letters.

Apple is a good filling for a pie.

In the first case we are mentioning the word.  The predicate is about the nature of the word and not about the fruit.
When you talk about the meaning of a word, you mention it.
"Apple" means a type of fruit that grows on a tree.
We are talking about the meaning of the the word, not about the meaning of the fruit.  So we are mentioning the word, and not using it.
So properly one should write

"Bonjour" is a French word meaning "hello"

Here we are comparing the meanings of two words.
Likewise you could say
"Bonjour" is a French word that means "hello".
And the same would go if you are talking about the meaning of a mentioned sentence

"C'est la plume de ma tante." is a French sentence that means "It is my aunt's feather".

There is no particular reason why you can't have embedded words mentioned.  But it all gets a bit silly.
Like the "la plume de ma tante", The examples are grammatically correct, but practically useless.  Nobody ever needs to talk about their aunt's feather, (or their aunt's pen), nor does anyone need to talk about the meanings of sentences that express meanings.
However ...

"« Bonjour » est un mot français qui signifie « hello »." is a French sentence that means "'Bonjour' is a French word that means 'hello'."

Ridiculous, but correct.


text:
Q: understanding derivative of a vector function If I have a vector function $r(t)$ , why is the tangent vector at t
$\lim_{\Delta t \rightarrow 0} (\frac{r(t+\Delta t)-r(t)}{\Delta t})$ and not just simply
$\lim_{\Delta t \rightarrow 0} ({r(t+\Delta t)-r(t)})$..I understand that if we divide it by $\Delta t$ and further simplify it , we will get the derivative of the vector function as the derivative of its individual components but i dont understand why we do so..

A: You can think of it as calculating the velocity of the moving particle $r$ because the direction of its velocity is the same as the direction of the tangent line of its trajectory.
To calculate its velocity, we divide a certain distance that it passes through by the amount of time it takes to pass through that distance.

A: The tangent at $t$ is the limit case of the secant:
$$
\lim_{t' \to t} \frac{r(t') - r(t)}{t' - t}
$$
or $t' = t + \Delta t$ thus
$$
\lim_{\Delta t \to 0} \frac{r(t+\Delta t) - r(t)}{t+\Delta t- t}
$$


text:
Q: Solve $3X =\begin{bmatrix}0&3\\6&9\end{bmatrix}$ for $X$ I've got this question:

Find the variable (hidden) in this expression:
$$3X =\begin{bmatrix}0&3\\6&9\end{bmatrix}$$

I've written down that $X$ equals to
$$X=\begin{bmatrix}0&1\\2&3\end{bmatrix}$$
is my answer wrong or right?
I'm not sure if this is the right place, but if it isn't , what is my mistake?
thanks

A: Your answer is perfect, no mistake at all. Multiplying/dividing matrices by numbers is so easy: we multiply/divide all the elements in the matrix by that number.