text:
Q: Plugin to set out of stock product image doesn't work I'm creating a plugin to set a different image for each out of stock product everything is displayed in the dashboard only if you set an image it doesn't work can someone help me solve the problem in the code, I would be very grateful
<?php
/**
 * Plugin Name: Out of Stock Image Changer for WooCommerce
 * Plugin URI:
 * Description: Automatically changes the product image when it goes out of stock in WooCommerce
 * Version: 1.0.0
 * Author:
 * Author URI:
 * License:
 */

add_action( 'admin_menu', 'register_product_image_changer_page' );
function register_product_image_changer_page() {
  add_submenu_page( 'edit.php?post_type=product', 'Out of stock images', 'Out of stock images', 'manage_options', 'out-of-stock-images', 'render_product_image_changer_page' );
}

function render_product_image_changer_page() {
  global $wpdb;

  if ( ! current_user_can( 'manage_options' ) ) {
    wp_die( __( 'You do not have sufficient permissions to access this page.', 'woocommerce' ) );
  }

  if ( ! empty( $_POST ) && check_admin_referer( 'update_out_of_stock_images' ) ) {
    $product_ids = isset( $_POST['product_id'] ) ? $_POST['product_id'] : array();
    $out_of_stock_images = isset( $_POST['out_of_stock_image'] ) ? $_POST['out_of_stock_image'] : array();

    foreach ( $product_ids as $index => $product_id ) {
      update_post_meta( $product_id, 'out_of_stock_image', $out_of_stock_images[ $index ] );
    }
  }

  $results = $wpdb->get_results( "SELECT ID, post_title FROM $wpdb->posts WHERE post_type = 'product' AND post_status = 'publish'" );

  ?>

<?php _e( 'Out of stock images', 'woocommerce' ); ?>

    <form method="post">
      <?php wp_nonce_field( 'update_out_of_stock_images' ); ?>

            <?php _e( 'Product', 'woocommerce' ); ?>
            <?php _e( 'Out of stock image URL', 'woocommerce' ); ?>

          <?php foreach ( $results as $result ) : ?>

              <?php echo $result->post_title; ?>

                <input type="hidden" name="product_id[]" value="<?php echo $result->ID; ?>">
                <input type="text" name="out_of_stock_image[]" value="<?php echo get_post_meta( $result->ID, 'out_of_stock_image', true ); ?>" class="widefat">

<?php endforeach; ?>

<input type="submit" name="submit" id="submit" class="button button-primary" value="<?php _e( 'Save Changes', 'woocommerce' ); ?>">

</form>

<?php
}

add_action( 'woocommerce_before_single_product_summary', 'maybe_change_product_image', 9 );
function maybe_change_product_image() {
global $product;

if ( ! $product->is_in_stock() ) {
$out_of_stock_image = get_post_meta( get_the_ID(), 'out_of_stock_image', true );

if ( ! empty( $out_of_stock_image ) ) {
remove_action( 'woocommerce_before_single_product_summary', 'woocommerce_show_product_images', 20 );
add_action( 'woocommerce_before_single_product_summary', 'show_out_of_stock_image', 20 );
}
}
}

function show_out_of_stock_image() {
global $product;

$out_of_stock_image = get_post_meta( get_the_ID(), 'out_of_stock_image', true );

if ( ! empty( $out_of_stock_image ) ) {
echo '';
}
}

everything works in the dashboard, but if an image is set it is not displayed

A: this code worked for me.
/**
 * Plugin Name: Out of Stock Image Changer for WooCommerce
 * Plugin URI:
 * Description: Automatically changes the product image when it goes out of stock in WooCommerce
 * Version: 1.0.0
 * Author:
 * Author URI:
 * License:
 */

add_action( 'admin_menu', 'register_product_image_changer_page' );
function register_product_image_changer_page() {
    add_submenu_page( 'edit.php?post_type=product', 'Out of stock images', 'Out of stock images', 'manage_options', 'out-of-stock-images', 'render_product_image_changer_page' );
}

function render_product_image_changer_page() {
    global $wpdb;

    if ( ! current_user_can( 'manage_options' ) ) {
        wp_die( __( 'You do not have sufficient permissions to access this page.', 'woocommerce' ) );
    }

    if ( ! empty( $_POST ) && check_admin_referer( 'update_out_of_stock_images' ) ) {
        $product_ids         = isset( $_POST['product_id'] ) ? $_POST['product_id'] : array();
        $out_of_stock_images = isset( $_POST['out_of_stock_image'] ) ? $_POST['out_of_stock_image'] : array();

        foreach ( $product_ids as $index => $product_id ) {
            update_post_meta( $product_id, 'out_of_stock_image', $out_of_stock_images[ $index ] );
        }
    }

    $results = $wpdb->get_results( "SELECT ID, post_title FROM $wpdb->posts WHERE post_type = 'product' AND post_status = 'publish'" );

    ?>

<?php _e( 'Out of stock images', 'woocommerce' ); ?>

        <form method="post">
            <?php wp_nonce_field( 'update_out_of_stock_images' ); ?>

                    <?php _e( 'Product', 'woocommerce' ); ?>
                    <?php _e( 'Out of stock image URL', 'woocommerce' ); ?>

                <?php foreach ( $results as $result ) : ?>

                        <?php echo $result->post_title; ?>

                            <input type="hidden" name="product_id[]" value="<?php echo $result->ID; ?>">
                            <input type="text" name="out_of_stock_image[]" value="<?php echo get_post_meta( $result->ID, 'out_of_stock_image', true ); ?>" class="widefat">

                <?php endforeach; ?>

                <input type="submit" name="submit" id="submit" class="button button-primary" value="<?php _e( 'Save Changes', 'woocommerce' ); ?>">

        </form>

    <?php
}

add_action( 'woocommerce_before_single_product', 'maybe_change_product_image', 9 );
function maybe_change_product_image() {
    global $product;

    if ( ! $product->is_in_stock() ) {
        $out_of_stock_image = get_post_meta( $product->get_id(), 'out_of_stock_image', true );

        if ( ! empty( $out_of_stock_image ) ) {
            remove_action( 'woocommerce_before_single_product_summary', 'woocommerce_show_product_images', 20 );
            add_action( 'woocommerce_before_single_product_summary', 'show_out_of_stock_image', 20 );
        }
    }
}

function show_out_of_stock_image() {
    global $product;

    $out_of_stock_image = get_post_meta( $product->get_id(), 'out_of_stock_image', true );

    if ( ! empty( $out_of_stock_image ) ) {
        echo '';
    }
}


text:
Q: Ember + Mirage and relationships i'm working with Ember 2.6 and currently using Mirage for a client hosted static database.
I started using fixtures du provide the sample data, but I cannot make the relationships work.
I have 2 entities : island and spot, with a Many to One relationship
//mirage/models/spot.js
import { Model, belongsTo } from 'ember-cli-mirage';
export default Model.extend({
  island: belongsTo()
});

and
//mirage/models/island.js
import { Model, hasMany } from 'ember-cli-mirage';
export default Model.extend({
  spots: hasMany()
});

and my fixture data
//mirage/fixture/spots.js
export default [
  {id: '1', name: 'test spot', island_id: [1]},
}

and
//mirage/fixture/islands.js
export default [
  {id: '1', name: 'Island 1 Name', permit: null, spot_ids: [1]},
}

my config.js is just a simple getAll
  this.get('/islands', function(schema, request){
    return schema.islands.all();
  });

But when I call it, I got my islands, but the relationships are missing.
Using the default json api adapter.
How to make Mirage return json data with the given relationships ?
I tried to set the relation in both sides and 2 at the same time and neither provides the child entity.
Here is a link of my project on github :
https://github.com/drallieiv/StreetpassTips/tree/feature/showRealDataForIslands/mirage

A: Try it with no underscores between the relationship properties in the fixture files.
For example:
//mirage/fixture/spots.js
export default [
  {id: '1', name: 'test spot', islandId: 1},
}

Also in the models you have to give hasMany and belongsTo a model
Like hasMany('spot') and belongsTo('island')

redpajama_set_name: RedPajamaStackExchange


text:
Q: Vuex Mutation Best Practices - Merging State with Payload I'm trying to avoid the following code with Vuex.
//Product.js
const mutations = {
    SET_PRODUCT_DATA(state, product) {
        state.title = product.title
        state.variantId = product.variantId
        state.handle = product.handle
        state.tags = product.tags
        state.productType = product.productType
        state.featureImage = product.featureImage
        state.vendor = product.vendor
        state.description = product.description
        state.images = product.images
        state.presentmentPrices = product.presentmentPrices
        state.available = product.available
        state.quantity = product.quantity
        state.length = product.length
        state.width = product.width
        state.height = product.height
        state.weight = product.weight
        state.features = product.features
        state.sizeMeta = product.sizeMeta
        state.swatch = product.swatch
    },
}

However if I try to merge the state object with my payload it doesn't work (I believe this is to do with how vue handles reactivity but I don't fully understand that yet).
const mutations = {
    SET_PRODUCT_DATA(state, product) {
        state = { ...state, ...product} //doesn't work
    },
}

I also want to avoid defining an object within my state like 'data' where I would assign this payload. This seams like unnecessary nesting.
const mutations = {
    SET_PRODUCT_DATA(state, product) {
        state.data = product //avoid
    },
}

A: If product object keys will always be the same as modified state properties, you can chose to set each property with set() method, which modify a state root property while preserving reactivity:
import Vue from 'vue'

SET_PRODUCT_DATA(state, product) {
    Object.keys(product).forEach(key => {
      Vue.set(state, key, product[key])
    }
},

Also, merging state with the product object, using spread operator does not work due to the fact that it clones the entire state into a new object, which evidently loses the reactivity of the existing state.

A: You can use Object.keys and iterate over them to copy all the values
const mutations = {
    SET_PRODUCT_DATA(state, product) {
        Object.keys(product)
              .forEach(key => {
                state[key] = product[key]
    },
}

A: If you pass an object with already existing state props only then you can use Object.assign:
const mutations = {
    SET_PRODUCT_DATA(state, product) {
        Object.assign(state, product)
    },
}


text:
Q: Find value and copy entire row to another sheet I'm trying to create a vba code but I'm not succeeding.
I want to search on COLUMN "F", for value: "Answered"
then copy row from "COLUM B TO F" and paste on sheet "ControlAnswered" lastrow;

A: Try this,
Sub SpecialCopy()
    Dim targetSh As Worksheet
    Set targetSh = ThisWorkbook.Worksheets("ControlAnswered")
    Dim i As Long
    For i = 1 To Cells(Rows.Count, "F").End(xlUp).Row
        If Cells(i, 6).Value = "Answered" Then
            Range(Cells(i, 2), Cells(i, 6)).Copy Destination:=targetSh.Range("A" & targetSh.Cells(Rows.Count, "A").End(xlUp).Row + 1)
        End If
    Next i
End Sub

I should say that you will not always going to find people that will write code for you


text:
Q: Show that any matrix $A=B' B$ with $B'$ conjugate transpose has real positive eigenvalues I'm working on a linear algebra problem that I just cannot wrap my head around.
1) Show that any $n × n$ matrix $A$ of the form $$A = B'B$$ has eigenvalues that are all real and positive. Here, $B$ is
any invertible $n × n$ matrix with real or complex entries, and $B'$
is its conjugate transpose
Now I know, any Hermitian matrix $A$ has real eigenvalues, and any matrix $A$ of form $$A = B' B$$ is Hermitian, thus its eigenvalues are real. But I just cannot find out why they should be positive as well.
Any help would be great!

A: Hint:
$$\langle x, A x \rangle = \langle x, B' B x \rangle = \langle Bx, Bx \rangle, \quad \forall x \in \mathbb C^n. $$


text:
Q: Magento 2 setting wrong file permissions? I'm adding products to my development website and I've noticed that images are not showing on the front end. After inspecting these, I can see that the chown user and group is correct but the file permissions of these images are set to 666. Is there a way I can make Magento correctly set these to 644 without having to set a cron job up?

A: Magento sets file permissions whenever we write files, like static view files, to the file system. The permissions differ by mode but ownership should always be the web server user.
In developer mode, directories have 770 permissions and files have 660. In production mode, directories have 750 and files have 640.
Ownership is kind of tricky and it confuses people so use this topic to get full details.


text:
Q: Sort an array in Vue.js How can I sort an array by name or sex before displaying it in a v-for loop?
https://jsfiddle.net/rg50h7hx/

{{ array.name }}

// Vue.js v. 2.1.8
var string = new Vue({
  el: '#string',
  data: {
    arrays: [
      { name: 'kano',    sex: 'man' },
      { name: 'striker', sex: 'man' },
      { name: 'sonya',   sex: 'woman' },
      { name: 'sindell', sex: 'woman' },
      { name: 'subzero', sex: 'man' }
    ]
  }
})

Do I have to use a "computed", or whatever?

A: Yes, an easy way to do this can be create a computed property which can return the sortedArray, like following:
computed: {
  sortedArray: function() {
    function compare(a, b) {
      if (a.name  b.name)
        return 1;
      return 0;
    }

    return this.arrays.sort(compare);
  }
}

See working demo.
You can find the documentation of sort here which takes a compareFunction.

compareFunction Specifies a function that defines the sort order. If omitted, the array is sorted according to each character's Unicode code point value, according to the string conversion of each element.

A: This works really cool:
sortFunc: function (){
  return this.arrays.slice().sort(function(a, b){
    return (a.name > b.name) ? 1 : -1;
  });
}

call the function from HTML:

{{ array.name }}

A: with arrow functions es6:
sortedArray(){
    return this.arrays.sort((a, b) => a.name - b.name );
}

A: Html side

{{ array.name }}

Vue js code || Using Lodash
var string = new Vue({
  el: '#string',
  data: {
    arrays: [
      { name: 'kano',    sex: 'man' },
      { name: 'striker', sex: 'man' },
      { name: 'sonya',   sex: 'woman' },
      { name: 'sindell', sex: 'woman' },
      { name: 'subzero', sex: 'man' }
    ]
  },
  methods: {
     sortArrays(arrays) {
            return _.orderBy(arrays, 'name', 'asc');
        }
  }
})

*

*in orderBy function, first argument is array, 2nd argument is key (name / sex) 3rd argument is order (asc / desc)

A: Easy way;
You can use computedArray instead of array
computed: {
computedFonksiyon() {
  this.arrays.sort(function(x, y) {
    return y.name- x.name;
  });
  return this.arrays;
}
}


text:
Q: Developer Mode check box is missing in Google Chrome browser Developer checkbox is missing in my Google Chrome Browser under extensions option..
I try to add a new extension in chrome browser but i am unable to do so because Developer mode is turned off. Check-box which unable developer mode in chrome is missing in my browser.
Any help will be appreciated. Thanks in advance.


text:
Q: Azure Stream Analytics convert array values Very specific question, if I have the following input in my Streaming Analytics component:
 //some input
 "outputs": [
  {
    "name": "output1",
    "unit": "unit1",
    "value": "95813"
  },
  {
    "name": "output2",
    "unit": "unit2",
    "value": "303883"
  }, // and more array values

How can I get a JSON result that would look as follows:
"outputs":[ {
   "output1":95813,
   "output2":303883
   //etc
 }]

So, I don't need the unit value, and to save space, I'd like to use the 'name' as the key, and the 'value' as the value of the key-value array.
This is my current query:
SELECT
input.outputs as outputs
INTO "to-mongodb"
FROM "from-iothub" input

but this of course creates seperate JSON arrays, with the same structure as I do get as my input.
Anyone any idea on how to do this?
In worst case, just filtering out the 'unit' would also already be a great help.
Thanks in advance

A: You could use user-defined functions in Azure Stream Analytics. Please refer to the sample function I tested for you.
UDF:
function main(arg) {
    var array = arg.outputs;
    var returnJson = {};
    var outputArray = [];
    var map = {};
    for(var i=0;i<array.length;i++){
        var key=array[i].name;
        map[key] = array[i].value;
    }
    outputArray.push(map);
    returnJson = {"outputs" : outputArray};
    return returnJson;
}

Query:
WITH
c AS
(
    SELECT
    udf.processArray(jsoninput) as result
    from jsoninput
)
SELECT
    c.result
INTO
    jaycosmostest
FROM
    c

Test Output:

Hope it helps you.


text:
Q: how to get a constant height for a grid container when its children are relatively positioned and have dynamic height I got this grid container which has an item (Item 1) with an image and a caption.
The caption needs to be at a certain position over the image so is relatively positioned.
I need to set a consistent margin between the grid container (blue area on the image) and the next section below see image
But the problem is the height of the Item1 is not the height of the final height, that is, after the caption is positioned, but it is the sum of the height of the caption plus the height of image (the orange part is showing up between blue and yellow from the image above).
it seemed to trickier to use position absolute for the caption.
for now i added grid template row to set the height and make many media query to change the height
please help me with any advice to simplify this
here is Codesandbox


text:
Q: Disable/Enable BroadcastReceiver when needed In my application I need to receive an activation code from SMS when user registered. For that I have a BroadcastReceiver but I don't want in to always enabled and I need it just once when user is registering. How to do that?

A: You can call registerReceiver and unregisterReceiver in your activity. Here is an example of it :
        registerReceiver(receiver, filter);
        unregisterReceiver(receiver);

where receiver is your broadcast receiver class and filter will be
private IntentFilter filter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");

incase of sms receiver.
You can call registerReceiver once you require to receive a sms and call unregisterReceiver to stop listening for incoming sms.

A: For this you need to register the Broadcast Receiver in the activity; it will remain alive only for that instance of activity. Instead of registering it in manifest just register in the activity on runtime when required.


text:
Q: Android hide soft keys on nexus devices I want to hide the soft key bar (home, back, menu) when a user launches my app. I tried using:
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
But unfortunately as soon as the user interacts with my app, the soft key bar shows again. Is there any way to hide it till the user exits my app?

A: This is called immersive mode.
check out: https://developer.android.com/training/system-ui/immersive.html
The code that you were asking for is:
@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    if (hasFocus) {
        getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
    }
}

Happy???


text:
Q: var_dump returns NULL in json_decode I have a variable in Laravel, which is an array, but when I pass it to another view, I can't do "count" or "foreach with it".
It has the following format:
[{
    "imp": 18,
    "cantidad": 2,
    "pre": 379.5,
    "id": 62,
    "preu": "345",
    "marca_id": 4,
    "nombre_item": "zapato",
    "nombre_marca": "marca1",
    "item_codigo": "1234-xxa",
    "nombre_unidad": "NIU"
}, {
    "imp": 18,
    "cantidad": 2,
    "pre": 136.400000000000005684341886080801486968994140625,
    "id": 64,
    "preu": "124",
    "marca_id": 4,
    "nombre_item": "farol",
    "nombre_marca": "marca1",
    "item_codigo": "3434-f",
    "nombre_unidad": "NIU"
}]

I tried:
$detalle = json_decode ($detalle, true);
var_dump($detalle);

But it returns null, I don't know what's going on.

EDIT:
EmailController.php (Here I send the variables of my view through ajax post, I send the variable $detalle that is an array of Eloquent de Laravel.)
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Mail;

class EmailController extends Controller
{

    public function enviaremail(Request $request)
    {

        $this->validate($request, ['email' => 'required|email']);

        $data = array(
            'email' => $request->email,
            "numero" => $request->number,
            "nf" => $request->nf,
            "tienda" => $request->tienda,
            "total" => $request->total,
            "detalle" => $request->detalle,

            "fechae" => $request->fechae,
            "pdf" => $request->pdf
        );

        /* Mail::raw('Text', function ($message) use ($data) {
                $message->to($data['email']);
                $message->subject('Comprobante '.$data['nf'].'-'.$data['numero'].' Factura de '.$data['tienda']);
             $message->from('no-reply@mg.maks.uno', 'Maks.uno');

        }); */

        Mail::send('venta.email', $data, function ($message) use ($data)
        {
            $message->to($data['email']);
            $message->subject('Comprobante ' . $data['nf'] . '-' . $data['numero'] . ' Factura de ' . $data['tienda']);
            $message->from('no-reply@mg.maks.uno', 'Maks.uno');
        });

        return;

    }

}

Here is an excerpt from the view, which sends ajax the variables to EmailController.php
$.ajax({
    type: "POST",
    url: "{{ route('enviaremail') }}",
    data: {
        "_token": "{{ csrf_token() }}",
        "email": email,
        "numero": number,
        "nf": nf,
        "tienda": ti,
        "fechae": fe,
        "total": tt,
        "pdf": pdf,
        "detalle": "{{   $det  }}"
    },
    success: function(response) {
        alert("Tu email fue enviado!")
    }
});

And it is in email.blade.php (the view that renders the EmailController.php variables) where I want to traverse the array or the other variables.
<?php
    var_dump(json_decode($detalle, true));

A: I solved it using "html_entity_decode"
$jsonText = $request->detalle;
$decodedText = html_entity_decode($jsonText);
$myArray2 = json_decode($decodedText, true);


text:
Q: Jetpack Compose: Row of "AndroidView" with dynamic list In a ViewModel I maintain a list of strings. If onAddTag or onRemoveTag will be performed a mutableState will be refresh. Which causes a recomposition.
The problem is that if I remove a element (eg the third) with onRemoveTag the updated list arrivies in my "Custom Composable" (debugged) but the rendering only removes the last item from the list.
Example:

*

*Initial List: 1,2,3,4 -> onRemove(2) -> Updated List: 1,3,4 -> Renders: 1,2,3

*Initial List: 1,2,3,4 -> onRemove(1) -> Updated List: 2,3,4 -> Renders: 1,2,3

In the Documentation of LazyListScope.items there is this key parameter which says:
key - a factory of stable and unique keys representing the item. Using the same key for multiple items in the list is not allowed. Type of the key should be saveable via Bundle on Android. If null is passed the position in the list will represent the key. When you specify the key the scroll position will be maintained based on the key, which means if you add/remove items before the current visible item the item with the given key will be kept as the first visible one.
Maybe the Row does similar things and it can't properly decide which element needs to be remove and which one stays with the positional information only. But how to fix that?
I do not want do use a LazyRow here because I only have a few items to render. Additional to that I want to understand the problem! :)
Code
ViewModel

class MyViewModel : ViewModel() {
   var selectedTags = mutableStateOf(listOf<String>())

   fun onRemoveTag(tag: String) {
      selectedTags.value = selectedTags.value.toMutableList().apply { remove(tag) }
   }

   fun onAddTag(tag: String) {
      selectedTags.value = selectedTags.value.toMutableList().apply { add(tag) }
   }
}

MainScreen
fun MainScreen(viewModel: MyViewModel) {
   val selectedTags by remember { viewModel.selectedTags }

   TagRow(tags = selectedTags)
}

Custom Composable
@Composable
fun TagRow(
    tags: List<String>,
    modifier: Modifier = Modifier
) {
    Row(modifier = modifier) {
        tags.forEach {
            Text(text = it)
        }
    }
}

Hope somebody knows how to fix that!
Regards,
Chris
EDIT
According to @Philip's feedback I prepared a self-contained example:
@Composable
fun StackOverflowPreview() {
    val tags = remember { mutableStateListOf("1", "2", "3") }

    Row {
        tags.forEach {
            AndroidView(factory = { context ->
                EmojiTextView(context).apply {
                    textAlignment = View.TEXT_ALIGNMENT_CENTER
                    setTextColor(android.graphics.Color.BLACK)
                    layoutParams =
                        LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)
                    text = it
                }
            })
        }
    }

    LaunchedEffect(key1 = tags) {
        delay(2000)
        tags.remove("1")

        delay(2000)
        tags.remove("2")

        delay(2000)
        tags.remove("3")
    }
}

Here you can see that I use EmojiTextView. If I replace that view with a basic Text composable. It works like expected. With the EmojiTextView the items will always remove from right to left.
EDIT 2
I was able to narrow down my problem to the AndroidView-integration:
@Preview
@Composable
fun StackOverflowPreview() {
    val tags = remember { mutableStateListOf("1", "2", "3") }

    Row {
        tags.forEach { tag ->
            // does NOT work
            // AndroidView(factory = { TextView(it).apply { text = tag } })

            // works
            AndroidView(factory = { TextView(it) }, update = { v -> v.text = tag })
        }
    }

    LaunchedEffect(key1 = tags) {
        delay(2000)
        tags.remove("1")

        delay(2000)
        tags.remove("2")

        delay(2000)
        tags.remove("3")
    }
}

A: In the MainScreen Composable, you are wrapping the val assignment with remember. It causes the list to not be updated on recompositions, so remove that remember over there. Then, you have also used a not-so-good approach in the initialization of the selectedTags variable in the viewmodel. You can directly use delegation inside that, as you have used in your main activity (or composable, as it seems). In your viewmodel, you can initialise the variable as val selectedTags by mutableStateOf(listOf<String>()), and then there's no need for using the .value prefix everywhere. Rest assured that recompositions will be triggered still. You just need to initialise with mutableStateOf().
Also, a better approach of declaring mutable lists, as of Compose 1.0.1, is to use the pre-defined mutableStateListOf(...) with which you so not require to use delegation (the 'by' keyword), and can use it just like a regular list object, without any .value calls.
Just implement these and you should be fine

A: To finish up this thread here is an working example.
@Preview
@Composable
fun StackOverflowPreview() {
    val tags = remember { mutableStateListOf("1", "2", "3") }

    Row {
        tags.forEach { tag ->
            AndroidView(factory = { TextView(it) }, update = { v -> v.text = tag })
        }
    }

    LaunchedEffect(key1 = tags) {
        delay(2000)
        tags.remove("1")

        delay(2000)
        tags.remove("2")

        delay(2000)
        tags.remove("3")
    }
}

As @Philip mentioned in the comments the AndroidView will be just instantiated once and needs a way to update its internal state on recomposition.


text:
Q: How to determine http method of any controller path when fetch paths from route.rb in in sitemap.rb? I want to generate a sitemap of a website with more than 300 URL path. Therefore using a sitemap generator, I am fetching URL path from routes.rb file. Now I don't want SEO to crawl through my post url. So, I wanted to determine the Http-method type of controller paths in sitemap.rb. How to do that?
I have tried to fetch http-method with route.path.spec.left.memo.request_method_match, but NoMethodError occue.

A: Request method is also called verb, so you can do following:
Rails.application.routes.routes.collect do |route|
  "#{route.name} = #{route.defaults} = #{route.verb}"
end

Different version of rails might have it slightly different, but once you have your route look for verb. (check documentation: https://www.rubydoc.info/docs/rails/4.1.7/ActionDispatch/Journey/Route)
I think this gives you enough info to continue.


text:
Q: Return a diff between two objects
Possible Duplicate:
Difference in JSON objects using Javascript/JQuery

How do I return properties that have changed (diff) between two objects?
In my code, I have set a global variable products_diy to store data. When I change the values of the filters on the page, values in products_diy will change accordingly. I would want to get the values that changed (diff) between the original and the current values of products_diy.
too hard for me to write this comparing function. any one helps?
function obj_diff(o2, o1) {
    var obj = {};
    for (var i in o1) {
        var item_type = typeof o2[i];
        if (item_type != 'undefined') {
            //...
        }
    }
    return obj;
}

var products_diy1 = {
    'zone': [1, 2],
    'category': {
        'c0': '1'
    },
    'fitler': {
        'price': {
            'switcher': 'true',
            'price_start': '30',
            'price_end': '50'
        }
    }
}
var products_diy2 = {
    'zone': [1, 2, 3],
    'category': {
        'c0': '1'
    },
    'fitler': {
        'price': {
            'switcher': 'true',
            'price_start': '30',
            'price_end': '80'
        }
    }
}
/* -------
compare 2 objects
if the item in o2 is not the same with the o1,
join item to returned obj

obj_diff = {
    'zone': [1, 2, 3],
    'fitler': {
        'price': {
            'switcher': 'true',
            'price_start': '30',
            'price_end': '80'
        }
    }
}

------- */


text:
Q: Show that a power series is equivalent to a Taylor series. I have the following exam Question:

Consider the power series
$$P_\infty(x) = \sum_{k=1}^{\infty} \dfrac{-(x-1)^k}{2k}$$

*

*Examine $P_\infty(x)$ for convergence.

*Determine the Taylor polynomial $T_{2}(x)$ of the function $f : \mathbb{R}_{\lt2} \to \mathbb{R}$ with $f(x) = \ln{\sqrt{2 - x}}$ and
  $x_0 = 1$

*Show that $P_\infty(x)$ is the Taylor series of function $f$ at point $x_0 = 1$

Some verification for steps 1 and 2 would be nice, however as the title indicates, my main query concerns part 3.
----
Progress so far:
For part 1, it seems that this could be achieved via application of the ratio test. Here I am seeking verification that my application of this is correct, and the limit can be calculated as follows:
\begin{align*}
L &= \lim_{k\to\infty} \Big| \dfrac{\frac{-(x-1)^{k+1}}{2(k+1)}}{\frac{-(x-1)^{k}}{2k}} \Big| \\
\vdots \\
&= |1 - x| \\
~ \\
\end{align*}
Thus, $f$ can be said to be convergent if $|x - 1| < 1$, $\hspace{0.4 cm}$ or $\hspace{0.4 cm} 0 < x < 2$.

For part 2, I based my calculations off the formula provided by this link:
$$T_2(x) = f(x_0) + f'(x_0)(x - x_0) + \dfrac{f''(x_0)}{2!} \cdot (x-x_0)^2$$
After checking my answer on Wolfram, I concluded that
$$T_2(x) = \dfrac{(1-x)}{2} - \dfrac{(x-1)^2}{4} $$

For part 3, I have tried to copy the method which was provided in this related question (namely, calculate furter terms of the Taylor polynomial until they can be generalized). After calculating the next term of the polynomial to be $f^3(x_0) = -\frac{1}{2}$, I concluded that $f^k(x_0) = -\frac{1}{2}$. Give this, we should have all the ingredients from the Taylor Polynomial to generalize these as the given power series, that is to say the factorial that occurs will be represented in our sum as
$\frac{1}{k!} = \sum\limits_{k=1}^{\infty} \frac{1}{k}$
and the part $(x-1)^k$ is already contained.
I just don't know how to present this in a mathematical way. Can someone please provide some assistance in formalizing my solution?

A: For part $3$ you may consider the following approach.
$$\ln \sqrt {2-x} =(1/2) \ln (2-x) = -1/2 \int _1 ^x \frac {dt}{2-t} $$
$$ \frac {1}{2-t} = \frac {1}{1-(t-1)} = 1+(t-1)+(t-1)^2+(t-1)^3+...$$
Upon integration you get the desired infinite power series about $x_0=1$
Now you apply the uniqueness of Taylor Series to get the result.


text:
Q: how to Sync HP ALM Status field with TFS State field with HP ALM Synchronizer 12.53 I'm having issues to Sync HP ALM Status field with TFS State field with HP ALM Synchronizer 12.53, this is the issue that I'm getting Update conflicted records:

threw an exception,skipping this entity and moving to the next,
  exception:update: general error AutomationException: AdapterException:
  Error in method TfsComEntityManager.UpdateWorkItemState , Unknown
  exception occurred. Cannot update State field with value:Closed .

A: thank you for using HPE ALM Synchronizer.
For syncing between ALM and TFS, we need pay attention to TFS workflow.
Generally speaking, when you saw some errors about change the state, you can manually change TFS record to ALM values (state and reason) by using Team Explorer or browser. If you couldn't do this in TFS client, means the workflow are not allow the transition.
We saw some customer didn't map reason in Synchronizer some times. It's not recommended, because both state and reason are very important in TFS workflow.
Best practice is making ALM and TFS has same rules of state/reason transition.
Last, Synchronizer is very smart to change state & reason, it can find any possible combination to reach the final state in 12.53. However, we faced some bugs in 12.50 to 12.52. So its recommended to update to 12.53.


text:
Q: Converting Scientific Notation to float (string to float) in SQL (Redshift) I am trying to convert/cast a string of scientific notation (for example, '9.62809864308e-05') into a float in SQL.
I tried the standard method: CONVERT(FLOAT, x) where x = '9.62809864308e-05', but it returns the error message: Unimplemented fixed char conversion function - bpchar_float8:2585.
What I'm doing is very straightforward. My table has 2 columns: ID and rate (with rate being the string scientific notation that I am trying to cast to float). I added a 3rd column to my table and tried to populate the 3rd column with the float representation of x:
UPDATE my_table
SET 3rd_column = CONVERT(FLOAT, 2nd_column)

Data type of 2nd_column is CHAR(20)
Furthermore, not every string float is in scientific notation -- some are in normal float notation. So I'm wondering if there is a built in function that can take care of all of this.
Thank you!

A: Turns out that for any string representation of a float x, so let's say x = '0.00023' or x = '2.3e-04'
CONVERT(FLOAT, x) will Convert the data type of x from char (string) to float.
The reason why it didn't work for me was my string contained white spaces.


text:
Q: Ionic cordova build android command failed | Ubuntu I'm relatively new to ubuntu and I'm currently working in an ionic project. When I give this command sudo ionic cordova build android , it fails. Below is the log
> cordova build android
Android Studio project detected

ANDROID_HOME=/usr/lib/android-sdk
JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64
Reading build config file: /home/tel/Desktop/AnimalTrackerApp/UserApplication/build.json

            studio
            (node:6766) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Could not find an installed version of Gradle either in Android Studio,
            or on your system to install the gradle wrapper. Please include gradle
            in your path, or install Android Studio

            [10:57:23]  lint finished in 2.01 s

But the thing is I have already set my gradle path but it shows this strange error.
gradle -v
    ------------------------------------------------------------
    Gradle 4.6
    ------------------------------------------------------------

    Build time:   2018-02-28 13:36:36 UTC
    Revision:     8fa6ce7945b640e6168488e4417f9bb96e4ab46c

    Groovy:       2.4.12
    Ant:          Apache Ant(TM) version 1.9.9 compiled on February 2 2017
    JVM:          1.8.0_162 (Oracle Corporation 25.162-b12)
    OS:           Linux 4.4.0-116-generic amd64

path for gradle:  /home/tel/.sdkman/candidates/gradle/current
Why is this error coming ? Please help me out.


text:
Q: How to solve $\{ x \in \mathbb N_0 \mid x \cdot416 \equiv 1696 \pmod {2208} \}$? How to solve $\{ x \in \mathbb N_0 | x \cdot416 \equiv 1696 \pmod {2208}\}$?
Since $416$ is not invertible in $2208$ I have cancelled everything by $\gcd(416, 2208, 1696)= 32$.
That gives:
$\{ x \in \mathbb N_0 \mid x \cdot13 \equiv53  \pmod {69} \}$.
So I have calculated $13^{-1} $ mod $69 = 16$.
That is the wrong result. The correct answer would be $20$.
Question: What is the way to solve that task?


text:
Q: Weird Namespacing context behavior with JS in Dynamics 365 Ribbon button I have following Javascript code written for my Dynamics 365 Ribbon button click event.
var SampleNamespace = SampleNamespace || {};
SampleNamespace = {
 someVariable : 'xyz',
 clickMeFromRibbon: function(){
  // this = window in classic UI | this.iWillDoSomething() - Error
  // this = SampleNamespace in Modern UUI | this.iWillDoSomething() - Works fine
 },
 iWilDoSomething : function(){
  // Doing some other helper operations
 }
}

in Ribbon button click I have specified following function to be called
SampleNamespace.clickMeFromRibbon

any idea why reference of this is different and how can we solve that with the effective namespacing working in both the environment?
PS : I have tried multiple types of different namespacing available in javascript but all resulted into same issue.

A: You can use different way working with namespaces that works fine for me:

var SampleNamespace = (function(){
    var someVariable = "xyz";

    function clickMeFromRibbon(){
        //you can call iWilDoSomething from here without using namespaces
    }

    function iWilDoSomething(){
    }

    return {
        clickMeFromRibbon: clickMeFromRibbon,
        iWilDoSomething: iWilDoSomething
    };
})();

//Also SampleNamespace.clickMeFromRibbon and SampleNamespace.iWilDoSomething are available externally


text:
Q: How do I find the path to a deeply nested unique key in an object and assign child objects accordingly? With a given flat list:
let list = [
    {
        key: 1,
        parent: null,
    },
    {
        key: 2,
        parent: 1,
    },
    {
        key: 3,
        parent: null,
    },
    {
        key: 4,
        parent: 1,
    },
    {
        key: 5,
        parent: 2,
    }
]

How do I create a nested object like the one below?
let nest = {
    children: [
        {
            key: 1,
            children: [
                {
                    key: 2,
                    children: [
                        {
                            key: 5,
                            children: []
                        }
                    ]
                },
                {
                    key: 4,
                    children: []
                }
            ]
        },
        {
            key: 3,
            children: []
        }
    ]
}

I'm not sure how to approach this. The solution I have in mind would have to iterate over the list over and over again, to check if the object's parent is either null, in which case it gets assigned as a top-level object, or the object's parent already exists, in which case we get the path to the parent, and assign the child to that parent.
P.S.
I don't think this is a duplicate of any of the below

*

*this checks for a key in a flat object.

*this doesn't show anything that would return a path, given a unique key.

A: For building a tree, you could use a single loop approach, by using not only the given key for building a node, but using parent as well for building a node, where the dendency is obviously.
It uses an object where all keys are usesd as reference, like

{
    1: {
        key: 1,
        children: [
            {
                /**id:4**/
                key: 2,
                children: [
                    {
                        /**id:6**/
                        key: 5,
                        children: []
                    }
                ]
            },
            {
                /**id:8**/
                key: 4,
                children: []
            }
        ]
    },
    2: /**ref:4**/,
    3: {
        key: 3,
        children: []
    },
    4: /**ref:8**/,
    5: /**ref:6**/
}

The main advantage beside the single loop is, it works with unsorted data, because of the structure to use keys and parent information together.

var list = [{ key: 1, parent: null, }, { key: 2, parent: 1, }, { key: 3, parent: null, }, { key: 4, parent: 1, }, { key: 5, parent: 2, }],
    tree = function (data, root) {
        var r = [], o = {};
        data.forEach(function (a) {
            var temp = { key: a.key };
            temp.children = o[a.key] && o[a.key].children || [];
            o[a.key] = temp;
            if (a.parent === root) {
                r.push(temp);
            } else {
                o[a.parent] = o[a.parent] || {};
                o[a.parent].children = o[a.parent].children || [];
                o[a.parent].children.push(temp);
            }
        });
        return r;
    }(list, null),
    nest = { children: tree };

console.log(nest);
.as-console-wrapper { max-height: 100% !important; top: 0; }


text:
Q: Saving a SQLite database in Android tablet internal memory (API 23) I am an abject novice in Android app development. However, my current project requires me to make an app that records field observations (am a research scientist), save them to a SQLite database - these will be sent to a central location for processing. The app will be used on tablets.
Currently, I am using Android Studio, and when I emulate the app functions, everything works as planned and using DB Browser for SQLite, I can see that the values are being recorded correctly in the database.
Doing research (an example is the answer here), I am aware that the the database (.db) file is saved in the directory path:
/data/data/<your.app.package>/databases/foo.db
Of course, this is accessible in Android Studio, but my understanding is that unless the device is rooted, these files are inaccessible in an actual device. For various reasons, this is not an option for the work that I am involved with.
In researching, I came across a method to back up the database, and save the back up database to an SD card, as in the answer to the question Backup/restore sqlite db in android [duplicate] and the duplicate target Android backup/restore: how to backup an internal database?.
Saving to external storage devices such as SD cards in APIs of 23 and above now require considerable more permissions to write to external sources (above and beyond what has always been required in the Manifest). For many reasons, this option is not optimal.
In this answer, the backup is saved on the SD card:
final String inFileName = "/data/data/<your.app.package>/databases/foo.db";
File dbFile = new File(inFileName);
FileInputStream fis = new FileInputStream(dbFile);

String outFileName = Environment.getExternalStorageDirectory()+"/database_copy.db";

// Open the empty db as the output stream
OutputStream output = new FileOutputStream(outFileName);

// Transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer))>0){
    output.write(buffer, 0, length);
}

// Close the streams
output.flush();
output.close();
fis.close();

But, my question (possibly a brain-fart type) is - is it possible to have the backup saved to an internal file of the device (e.g. Documents folder), and would the permissions still be required?

A: It's not complicated to achieve the pemission's flow. Here is a class that I created for help. You have to extend your MainActivity from this, and then you can call:
verifyStoragePermissions(new Runnable() {
    @Override
    public void run() {
        //backup your db here...
    }
});

It works for all Android versions using android support library.


text:
Q: Add Delay to Mouseover using Javascript I'm using the following script for all my image mouseovers:
loadImage1 = new Image();
loadImage1.src="1.jpg";
staticImage1 = new Image();
staticImage1.src="1-roll,jpg";

How can I simply add, say, a second or two delay before it executes the mouseover?
Thanks in advance for your help!
---UPDATE---
Thanks for the replies. Excuse my ignorance when it comes to Javascript. How can I include the timeout piece in the following script?

Do I wrap the timeout piece in it's own script tag? Thanks for the quick help!

A: You can use setTimeout(), an example:
var img1 = document.getElementById('my-img');
img1.onmouseover = function() {
  setTimeout(function() {
    this.src = 'my-img-2.png';
  }, 1000); // 1000ms = 1s delay
};

First of all, your code have some mistakes:

*

*Always write HTML tags in lowercase, not

Because we preload the /img/heavy-img.png we can directly see the heavy-img if me mouse over the first-img. If we don't preload the img, it will be loaded when we mouse over.
Instead of using an onmouseover attribute we use the onmouseover event + callback in the JS file. Now we can add a delay:


text:
Q: Best way to get the count of data in big data table using SQL I have a table with 12 millions of data and I want to get a count of data which matches my criteria.  Table is well indexed and when I want to test the worst case of get the count of all the records in table will take hours to get the data using
SELECT count(id)
FROM big_table
WHERE date > xxx
  AND date < yyy

Does anyone have any better idea to get the count in java using SQL?

A: I am investigating the very same problem and I've found a possible solution in this article:
https://www.citusdata.com/blog/2016/10/12/count-performance/#dup_counts
The suggested solution is Postgres specific and provides an estimation of the rows affected by a specific query - not the exact count.


text:
Q: extract string from inside an attribute I need to write a function like this:
var width=getWidth( $(this).attr("ows_MetaInfo"));

where $this is pointing to the xml row   .
in the getWidth(meta){} function I need to find the text vti_lastheight and do some split and stuff and grab the numeric height value which is 250. How do i do this in javascript or jquery??
<z:row ows_Title='We are together!' ows_ImageSize='620'
            ows_MetaInfo='16;#vti_parserversion:SR|14.0.0.6120

            vti_lastheight:IW|250
vti_lastwidth:IW|620

            vti_description:SW|Lorem ipsum dolor sit volutpat.' />

Update: I found that someone had written a function to grab the description value from vti_description. Can someone explain to me how this function is able to extract the description portio of text "lorem ipsum' part and how I can make use of it to extract the lastheight value? Please?
function getDescription(metaInfo)
    {
        var description="";
        if(metaInfo!=null)
        {
            metaParts=metaInfo.split("\n");
            if(metaParts!=null && metaParts.length>0)
            {
                var i=0;
                do
                {
                    if(metaParts[i].indexOf("vti_description")>-1)
                    {
                        var descParts=metaParts[i].split("|");
                        if(descParts!=null && descParts.length>1)
                        {
                            description=descParts[1];
                        }
                    }
                    i++;
                } while (i<metaParts.length && description=="" );
            }
        }
        return description;
    }

A: I believe you should use a regular expression.
function getWidth(str) {
    str = str.replace(/(\r\n|\n|\r)/gm, "");
    str = str.match(/vti_lastwidth:(.*?(?=vti))/);
    str = parseInt(str[1].split('|')[1]);
    console.log(str);
    return str;;
}

Supposing your data will always have this formation.
DEMO:http://jsfiddle.net/pavloschris/3gdd5/
With a minor tweak you could use this function for any attribute.

A: getWidth is a function. You don't need a function for this simply:
 var width=$(this).attr("ows_MetaInfo");

ows_ImageSize is an attr of this xml row. So calling above should work and it will return whatever is set in ows_ImageSize in this case that is 620. So i would test it first by making sure this is returning a number:
console.info(width);

If it is then you'll know that part works and you can tackle getting getWidth(meta){} to work.
 getWidth(width);


text:
Q: db journaling vs fs journaling SQLite has a pragma for journal_mode, which I assume is available across other sql database programs (MySQL, PostgreSQL, MS-SQL, etc.) so this question would also apply to all those database programs which offer journaling mode like SQLite does.
Most modern file-systems (BtrFS, Ext4, NTFS, etc) use journaling.  As databases are typically stored upon a journaling file-system, is it not redundant for the database program to also be journaling?
When SQLite journal_mode is enabled, large numbers of updates and/or inserts take an extraordinarily long time to complete compared to journal_mode being disabled.

A: SQLite's pragmas are specific to SQLite; you won't find them (or indeed the PRAGMA statement) in other engines.
As for database "journalling", that's just SQLite's name for its transaction log (see the entry for journal_mode in SQLite's reference). The transaction log is a very different thing to the file-system journal and generally not something you want to disable. Without a transaction log you won't be able to rollback transactions and (as the linked documentation notes): "If the application crashes in the middle of a transaction when the OFF journaling mode is set, then the database file will very likely go corrupt."
The file-system journal helps ensure that the file-system is consistent (shortly) after a crash; but that says nothing about whether the internal structure of files in that file-system is consistent from the point of view of an application (e.g. SQLite).
In other words: no, it's not redundant and most other databases don't provide any option to disable the transaction log. I'd suggest if your inserts and updates are going slowly, there's probably other reasons (how many changes are made per transaction, etc.)
Journaling is critical to enabling databases to provide the ACID (Atomic, Consistent, Isolated, Durable) guarantees they promise.
SQL-ite supports modes:  DELETE, TRUNCATE, PERSIST, MEMORY, WAL, OFF

*

*DELETE, TRUNCATE, PERSIST specify different ways of handling the journal file after each transaction commit.

*WAL - Write-Ahead Logging allows the database file to be updated in-place.

*MEMORY, OFF - Allow inconsistent state on crash, although OFF "allows the database file to be corrupted using ordinary SQL"
For performance, Write-Ahead Logging (WAL) can sometimes be helpful, or using a database designed for multiple concurrent writers.


text:
Q: Angular - *ngFor: Passing i from index in ts file I'm trying to pass the index from a ngFor to a my ts file without any success. I actually don't know how to do that.
Can someone tell me how to pass the index value from the html to the ts file?
I thought using a @Input would be te solution but nothing happen...
Thanks.
My HTML:

{{question.libelle}}

                <input type="checkbox" [(ngModel)]="reponse.Selected"/>
                {{reponse.libelle}}

      {{i}}

My TS:
@Injectable()

@Component({
  selector: 'app-java',
  templateUrl: './java.component.html',
  styleUrls: ['./java.component.sass']
})
export class JavaComponent implements OnInit {
  @Input()  i : any;
  questions :any = [];
  reponses :any = [];
  constructor(private questionnaireService: QuestionnaireService) { }

  ngOnInit() {
    this.questions = this.questionnaireService.getQuestion();
    this.reponses = this.questionnaireService.getReponse(this.i);
  }

}

A: you seem to have a basic misunderstanding of the index variable context and how observables will work.  What could help here and clear things up is dividing your component into two components, one for managing and displaying the overall list and one for managing and displaying the child lists
The parent (app-java):
HTML:

{{question.libelle}}

    <app-java-child [i]="i"></app-java-child>

  {{i}}

TS:
@Component({
  selector: 'app-java',
  templateUrl: './java.component.html',
  styleUrls: ['./java.component.sass']
})
export class JavaComponent implements OnInit {
  questions :any = [];
  constructor(private questionnaireService: QuestionnaireService) { }

  ngOnInit() {
    this.questions = this.questionnaireService.getQuestion();
  }

}

and the child:
HTML:

            <input type="checkbox" [(ngModel)]="reponse.Selected"/>
            {{reponse.libelle}}

TS:
@Component({
  selector: 'app-java-child',
  templateUrl: './java-child.component.html',
  styleUrls: ['./java-child.component.sass']
})
export class JavaChildComponent implements OnInit {
  @Input()  i : any;
  reponses :any = [];
  constructor(private questionnaireService: QuestionnaireService) { }

  ngOnInit() {
    this.reponses = this.questionnaireService.getReponse(this.i);
  }

}

This way you take the index from the initial ngFor and feed it to the child as input so the children can be in charge of building their own response arrays.

A: You can achieve these with 3 steps

*

*Keep the currentIndex in ts file

*Set the currentIndex from the html

*Call getter method from the *ngFor

in ts
@Injectable()
@Component({
  selector: 'app-java',
  templateUrl: './java.component.html',
  styleUrls: ['./java.component.sass']
})
export class JavaComponent implements OnInit {
  @Input()  i : any;
  questions :any = [];
  reponses :any = [];
  constructor(private questionnaireService: QuestionnaireService) { }

  ngOnInit() {
    this.questions = this.questionnaireService.getQuestion();
  }

   //Track the current Index
   public currentIndex;

   //Current Index Setter
   setCurrentIndex(index){
       this.currentIndex = index;
   }

  //Getter for response which will use currentIndex
  get responses(){
    return this.questionnaireService.getReponses(this.currentIndex)
  }

}

in html

{{question.libelle}}

            {{setCurrentIndex(i)}} <-- Set the current Index -->

                    <input type="checkbox" [(ngModel)]="reponse.Selected"/>
                    {{reponse.libelle}}

          {{i}}

Note : since you are using async pipe make sure all your results are Observable.

A: normally
 will be enough to pass the ii, however, in my case there is a *ngIf in sub , so that messed up the count and made it undefined. I endup make the *ngIf on the top level above *ngFor.


text:
Q: zbar not working on netcat video stream from raspberry pi read using OpenCV I am streaming video feed from raspberry pi using netcam to my PC and using zbar to read qr codes i the feed.
I am reading the named pipe using ffmpeg:
FFMPEG_BIN = "ffmpeg"
command = [ FFMPEG_BIN,
    '-i', 'fifo264',             # fifo is the named pipe
    '-pix_fmt', 'gray',      # opencv requires bgr24 pixel format.
    '-vcodec', 'rawvideo',
    '-an','-sn',              # we want to disable audio processing (there is no audio)
    '-f', 'image2pipe', '-']
pipe = sp.Popen(command, stdout = sp.PIPE, bufsize=10**8)

zbar is showing no output in this case.
Complete code:
import cv2
import subprocess as sp
import numpy
import zbar
from PIL import Image

FFMPEG_BIN = "ffmpeg"
command = [ FFMPEG_BIN,
        '-i', 'fifo264',             # fifo is the named pipe
        '-pix_fmt', 'gray',      # opencv requires bgr24 pixel format.
        '-vcodec', 'rawvideo',
        '-an','-sn',              # we want to disable audio processing (there is no audio)
        '-f', 'image2pipe', '-']
pipe = sp.Popen(command, stdout = sp.PIPE, bufsize=10**8)

while True:
    # Capture frame-by-frame
    raw_image = pipe.stdout.read(1920*1088)
    # transform the byte read into a numpy array
    image =  numpy.fromstring(raw_image, dtype='uint8')
    image = image.reshape((1088,1920))          # Notice how height is specified first and then width
    if image is not None:
        cv2.imshow('Video', image)
        image = Image.fromarray(image)
        width, height = image.size
        zbar_image = zbar.Image(width, height, 'Y800', image.tostring())

        # Scans the zbar image.
        scanner = zbar.ImageScanner()
        scanner.scan(zbar_image)

        # Prints data from image.
        for decoded in zbar_image:
            print(decoded.data)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
    pipe.stdout.flush()

cv2.destroyAllWindows()


text:
Q: I need to compare and retain multiple values from a Java Stream I'm rewritting a method using Stream, but I kinda stuck. For the short story, it's a method used to retrieve available skills for a player. The whole list of skills is stored into a player template (getTemplate(), list reachable with getTemplate().getSkills()). The player also owns its own already known skills, stored into a Map (in this case I only use getSkillLevel, which simply send back the skill level if known or -1 if unknown).
It must be filtered by some conditions, such as :

*

*The template skill must be "learnable" by the player, according current player level (it's the filter content)

*The template skill is added on the list if the player doesn't know yet the skill (result of getSkillLevel == -1) or if the current player skill level is lower than the template skill.

A GeneralSkillNode is a container holding following informations :

*

*skill id (named getId())

*skill level (named getValue())

*minimum level to learn it (named getMinLvl())

getTemplate().getSkills() is the whole learnable skills this player can learn (each skill entry is listed here no matter the level), which is a List.
The problem comes than it currently register ALL skills level range. Let's say there are 18 levels for a given skill id (1-1-5, 1-2-5, 1-3-5,... 1-18-80), it will add the 18 GeneralSkillNode for skill id 1. I need to filter by skill id and retain ONLY, for each skill id, the biggest possible level (which can be tested, if you followed my explanations, using getValue()). If I use a Comparator with .max(, it will only retrieve the maximum level for a single skill.
I search the most elegant way to do it. Thanks in advance for any help !
Here is my current result :
/**
 * @return a {@link Collection} of all available {@link GeneralSkillNode}s (being general or autoGet) of maximal level for this {@link Player}.
 */
public Collection<GeneralSkillNode> getAllAvailableSkills()
{
    final List<GeneralSkillNode> result = new ArrayList<>();

    getTemplate().getSkills().stream().filter(s -> s.getMinLvl() <= getLevel()).forEach(s ->
    {
        final int playerSkillLevel = getSkillLevel(s.getId());
        if (playerSkillLevel == -1 || playerSkillLevel < s.getValue())
            result.add(s);
    });
    return result;
}

Edit : Thanks for helping me, the final version looks like that now :
    /**
 * @return a {@link Collection} of all available {@link GeneralSkillNode}s (being general or autoGet) of maximal level for this {@link Player}.
 */
public Collection<GeneralSkillNode> getAllAvailableSkills()
{
    final List<GeneralSkillNode> result = new ArrayList<>();

    getTemplate().getSkills().stream().filter(s -> s.getMinLvl() <= getLevel()).collect(Collectors.groupingBy(s -> s.getId(), Collectors.maxBy(Comparator.comparing(s -> s.getValue())))).forEach((i, s) ->
    {
        final int playerSkillLevel = getSkillLevel(i);
        if (playerSkillLevel == -1 || playerSkillLevel < s.get().getValue())
            result.add(s.get());
    });
    return result;
}

A: To get the maximum level for each skill, you can do a groupingBy to separate each skill, then a maxBy to get the highest level per skill.
getTemplate().getSkills().stream().filter(s -> s.getMinLvl() <= getLevel())
                         .collect(Collectors.groupingBy(s -> s.getId(),
                                  Collectors.maxBy(Comparator.comparing(s -> s.getValue()))));


text:
Q: Empty Constructor exception in DeviceAdminReceiver E/AndroidRuntime(27856): java.lang.RuntimeException: Unable to instantiate receiver com.inc.statusbar.Statusbar$DeviceAdminSampleReceiver: java.lang.InstantiationException: can't instantiate class com.inc.statusbar.Statusbar$DeviceAdminSampleReceiver; no empty constructor

I already tried to call the default constructor of DeviceAdminReceiver class but no avail.Removing the constructor also gives the same error.
DeviceAdminSampleReceiver Class Defination -
public class DeviceAdminSampleReceiver extends DeviceAdminReceiver
{

    public DeviceAdminSampleReceiver()
    {
        super();
    }

    @Override
    public void onEnabled(Context context, Intent intent) {
        super.onEnabled(context, intent);
    }

    @Override
    public CharSequence onDisableRequested(Context context, Intent intent) {
        super.onDisabled(context, intent);
        return "admin_receiver_status_disable_warning";
    }

    @Override
    public void onDisabled(Context context, Intent intent) {
        super.onDisabled(context, intent);
    }

}


text:
Q: How do I make Razor read UTF-8 files without BOM? We have separated teams for front end and back end work. The front end is using a large diversity of editors to edit the CSHTML and most of them save UTF-8 without a byte order mark. The problem is, Razor expects a BOM to be present. If it's not present it will read the file using the current code page and we get encoding problems.
How would I make Razor to accept the UTF-8 files without a BOM? Apparently the only solution would be to implement an own VirtualPathProvider and thus also a VirtualFile. Unfortunately, the current used VirtualPathProvider is MapPathBasedVirtualPathProvider, which is an internal class. So I'd have to re-create a lot of functionality.

A: Following How to force ASP.NET MVC to read .cshtml files as UTF-8?, try to add this in Web.config:
<system.web>
    <globalization fileEncoding="utf-8" />
</system.web>


text:
Q: Side of TableViewCell gets cut off when applying a gradient mask My tableView sits within a blank content view with constraints holding it in place. The table will function properly in the container by itself, but as soon as I apply a gradient using the code below, the gradient works perfectly, except the right hand side of my tableViewCells get cut off. It only happens when the gradient is applied. Any recommendations would be appreciated.
Before Gradient is added, table view looks like this:
TableView with full TableViewCells
After the gradient is added, the table view looks like this:
TableView with cut TableViewCells
This is the code I am using to apply the gradient.
        let gradientLayerMask = CAGradientLayer()
    gradientLayerMask.frame = gradientMask.bounds
    gradientLayerMask.colors = [UIColor.clear.cgColor, UIColor.white.cgColor, UIColor.white.cgColor, UIColor.clear.cgColor]
    gradientLayerMask.locations = [0.0,0.1,0.9,1.0]

    gradientMask.layer.mask = gradientLayerMask

    exerciseTable.contentInset = UIEdgeInsets(top: 15, left: 0, bottom: 0, right: 0)

A: Put some delay for gradient code
func delay(time: Double, closure:
    @escaping ()->()) {

    DispatchQueue.main.asyncAfter(deadline: .now() + time) {
        closure()
    }

}

Use this way.
delay(time: 0.2) {
    //gradient code
}

I hope it's work for you.


text:
Q: Dojo: Programatically setting checkbox label for adding on TableContainer after some hours of checking out documentation, I am somewhat desperate:
Basically I need to populate a TabContainer with some TextBoxes, and some Checkboxes. All theses neatly arranged: Labels to the left, fields to the right.
To have this done I use a TableContainer that I add to the TabContainer, create the TextFields and add them to the TableContainer. All is rendered ok. But when it comes to a checkbox, I can't find the trick to have a label displayed at all.
If I:
- add a label-attribute to creation statement say:
     var text8 = new dijit.form.CheckBox({
     id:"zuschauer_" + i,  value: "zuschauer", label:"fritt"});
Firefox comes up with a "containerNode is null" - Error

*

*try to add a  tag: Nothing is shown (no error, but alas: no label):
var text9 = dojo.create('<label>');
dojo.attr(text9,"for","zuschauer_" + i);
dojo.attr(text9,"content","fritt");

*try to add a div or somewhat else on the tablecontainer (disabled Labels): Firefox comes up whith:
Error: uncaught exception: [Exception... "Component returned failure code: 0x80004003 (NS_ERROR_INVALID_POINTER) [nsIDOMHTMLDivElement.appendChild]"  nsresult: "0x80004003 (NS_ERROR_INVALID_POINTER)"  location: "JS frame :: ...

*same is for created TextNodes...
So how the hack:
- Would I generate a label to a checkbox programatically (no html template possible, I've seen the code around, creating a checkbox but having a 'label for' on the html before. This would not be helpful, as I don't know how many checkboxes I need at designtime. These are to be genereated completly at runtime.
- Would I have this very simple design done programatically, Must be easy, this is not rocket sience. Do I really need the TableContainer to have this done?

*

*Can I create static text in a TableContainer?

A: I would suggest creating an HTML string then setting it as content of a ContentPane. If you need to build the form programatically, you might make your own widget that extends ContentPane and takes the data as you get it, and generates the right innerHTML. That' going to end up being simpler than trying to cobble this together out of existing widgets.

A: In such cases you may want to use the input/widget inside an anonimous LABEL (HTML) tag. You can put the text before or after the input/widget, and probably position it using style/dir attributes. This will allow some more flexibility, as you don't need an ID at parse time. Just create a label tag and throw in your form widget. It is pure HTML and should be supported since HTML 4.01.
http://www.w3.org/TR/html401/interact/forms.html#h-17.9
See also:
Making checkbox and radio labels clickable


text:
Q: Finding incomplete solutions of second order ODE system For a smooth, 1-periodic, positive function $c:\mathbb{R}\rightarrow (0,\infty)$ consider the following second order ODE system for the curve $\gamma(t)= (x(t),y(t),z(t)):\mathbb{R}\rightarrow \mathbb{R}^3$ (note that I will denote the derivative of $c$ by a prime and the derivatives of the curve components $x,y,z$  by dots).
\begin{align}
(i) \hspace{15mm} \ddot{x}(t)+ \frac{c'(z(t))}{c(z(t))}~ \dot{x}(t)\dot{z}(t)=0 \\
(ii) \hspace{14mm} \ddot{y}(t) +\frac{c'(z(t))}{c(z(t)))}~\dot{y}(t)\dot{z}(t)=0 \\
(iii) \hspace{16mm} \ddot{z}(t)-c'(z(t)) ~ \dot{x}(t)\dot{y}(t)=0
\end{align}
My question: I'm interested in finding a function $c$ as described above such that the system has "incomplete" solutions, i.e. solutions $\gamma:\mathbb{R}\rightarrow \mathbb{R}^3$ which are not defined for all times $t\in\mathbb{R}$. Or alternatively I want to show that for all $c$ as above there are no incomplete solutions.
Background: the background to this problem is a geometric one: I have a family of metrics $\{g_c\}$ given on $\mathbb{R}^3$ (where $c$ is as described above) and I'm asking myself if all those metrics are geodasically complete. Solving the geodesic equation for those metrics gives the above system of ODEs.

A: The equation system has the following first integrals:
$$c(z)^2\left(\dot x^2+\dot y^2\right)=I_1=const$$
$$c(z)\left(y\dot x-x\dot y\right)=I_2=const$$
If $c_{MIN}<c(z)<c_{MAX}$, then $\dot x$ and $\dot y$ are bounded:
$$|\dot x|<\frac{\sqrt{I_1}}{c_{MIN}}$$
$$|\dot y|<\frac{\sqrt{I_1}}{c_{MIN}}$$
Assuming that $c'(z)$ is a bounded smooth function, $\ddot z(t)$ is also bounded. This means that there are no singular solutions (such that $x$, $y$ or $z$ reach infinity for finite $t$). Also, existence theorem guarantees existence of solution to the initial value problem in the neighborhood of every $t=t_0$, so there are no incomplete solutions.


text:
Q: Can you accelerate to almost the speed of light on a smooth, curved path? So, many of the time dilation thought experiments have periods of accelerating away from the origin, stopping, turning around, and returning, which precipitates an observable time differential between the traveler and those remaining behind.

*

*Is there a requirement that the path be straight line?

*Is is possible to accelerate to almost the speed of light (or a large fraction thereof) along a curved path (say a circle or ellipse) rather than "out and back"?

I'm happy to put aside the realities of the movement of the universe (the planet won't be in the same place to return to later on) for this thought experiment insofar as it simplifies the question.
My intuition says it must be straight, but I cannot articulate why, my physics is rusty.

A: An element of acceleration takes a body from one inertial frame to another.  With some assumptions, widely accepted, all the relativistic effects are simply the differences in Lorentz contraction, time dilation and relativity of simultaneity between the two frames.
Conventionally, the starting frame is the rest frame.
An observer in a frame moving relative to that 'rest' frame, where that relative motion is not in line with the acceleration, will see the accelerating object follow a curved path.
Things change again if the accelerating observer's acceleration changes direction.

A: The path does not have to be a straight line. Any smooth curve in 4-dimensional spacetime can be decomposed into a number of arbitrarily small segments, each of which is a straight line in the limit when the number of segments approaches infinity. So the full effects of such a motion can be calculated by integrating over these segments.

A: If one wishes to nitpick (and I do), any acceleration is a curved path in four-dimensional space-time. If there is curvature in an object's path in three-dimensional space, that means there is a component of acceleration perpendicular to the object's path.
It certainly is possible to accelerate perpendicular to one's path, but the curvature that results is proportional the acceleration divided by the square of velocity. This means that for an object traveling close to light speed, the acceleration need for even a modest amount of curvature would be massive.
How massive? Well, the event horizon of a black hole consists of the surface such that if a light ray were traveling along it, it would be kept on that surface by the force of gravity. So, basically, if you have an object that's going close to light speed, then to keep it in a circle, you need a force comparable to a that of a black hole whose event horizon is the same size as that circle.

A: To create the effect illustrated by the twin paradox, there is no requirement for the relative motion to be linear, or, for that matter, for it to be limited to smooth acceleration. However, the more complicated the motion, the more complicated the calculations, so linear motion is is often considered as it is the simplest case to model and may be the simplest to envisage.


text:
Q: Unable to add 4th Fragment to my Tabbed bar in my Tabbed Activity Project i try to add a new fragment to my Tabbed Bar and did the following like i did for the Fragments before:
1. I created a Fragment and the layout for that
2. I added the Fragment name in my MainActivity:
 public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class below).
        switch (position) {
            case 0:
                locations_fragment loc = new locations_fragment();
                return loc;
            case 1:
                qr_code qra = new qr_code();
                return qra;
            case 2:
                HTW_Fragment htw = new HTW_Fragment();
                return htw;
            case 3:
                Events_Fragment pre = new Events_Fragment();
                return pre;
            default:
                return null;

        }
    }

    @Override
    public int getCount() {
        // Show 3 total pages.
        return 3;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "Locations";
            case 1:
                return "QR Code Scanner";
            case 2:
                return "HTW";
            case 3:
                return "Events";
        }
        return null;
    }
}

if i try to start my App it shows only the first three Fragment in my Tab Bar.

A: The reason is actually simple. You said to adapter there is only 3 pages.
 :)

@Override
public int getCount() {
    // Show 3 total pages.
    return 3;
}

Replace it with return 4; and enjoy your 4-th page displayed.


text:
Q: Gulp: copy files ending with .html or exclude .js? Gulp: see below as an example

*

*How to copy files ending with .html in a directory and its subdirectories?

*How to copy files that not ending with .js in a directory and its subdirectories.

--dirA
  --dirB
    --b.html
    --b.js
  --dirC
    --c.html
--index.html

A: If I am not totally mistaken:
gulp.task('copyHTML', function() {
  return gulp.src('directory/**/*.html')
    .pipe(gulp.dest('copied/html'));
});

That code will copy any file ending in .html in any directory beneath the directory directory.

A: Like jacmoe answered, if you need to get specific files in gulp, use that kind of syntax:
'/directory/*.fileextension' //Get all files in directory with .extension
'!/directory*.fileextension' //Ignore files with .extension
'/directory/**/*.fileextension' //Get all files in directory AND all subdirectories with .extension

And remember that gulp paths support arrays so you can write something like that:
['!/directory/**/*.js', '/directory/**/*'] //Get all files except .js files

Or if needed only specific files:
['/directory/**/*.html'] //Get all .html files


text:
Q: Is the inducing signal weakened to the extent it induces a signal in the receiving antenna? Silly question ...
An antenna is necessary to receive a transmitted signal from atmosphere, or otherwise. The transmitted signal weakens as it travels through the atmosphere. When the signal encounters an antenna (subject to antenna gain) a corresponding signal is induced in the antenna.
Is the inducing signal weakened to the extent it induces a signal in the receiving antenna?

A: I believe so, but I can't give you any authoritative information.  I am working on a similar problem with ferrite rod antennas and experimentally I've confirmed that the induced current in the antenna also re-radiates.
Current in an antenna has no idea how it "got there". Current flowing in a conductor will create a magnetic field around that conductor.  I am seeking confirmation that this field opposes the incoming signal.
If we had a perfect lossless resonant antenna, the signal would induce a current which would slosh back and forth in the antenna. Subsequent carrier cycles would add more current. Without some limiting mechanism, the current could become infinite over a long time..  Obviously that doesn't happen.  Resistive losses, other parasitic losses, and re-radiated energy combine to achieve an equilibrium.  This takes time, which ends up expressing as the "Q" of the antenna.  Our imaginary perfect antenna would have infinite Q. Real antennas don't.


text:
Q: char * и const char * Решил вернуться к СИ и прочитать книгу K&R, и вот опять споткнулся на теме указателей, по логике вроде все понятно, но вот именно с char * и const char * какие-то проблемы.
Давайте я приведу код и покажу что мне все такие не ясно!
Пример 1:
char *pstr = "Hello, world";
*pstr = 'D'; /// При запуске приложения на этом месте вылетит сбой не понятно!
printf(pstr); /// Ну и конечно ничего не выведет, измененную строку я не получу, ой точнее массив из символов

Пример 2:
const char *pstr = "Hello, world";
*pstr = 'D'; /// Сбоя не будет и программа вообще не скомпилируется т.к компилятор сообщит что мы не можем изменять наш константный объект
printf(pstr); /// До сюда дело не дойдет

Пример 3:
char str[] = "Hello, world";
char *pstr = str;
*pstr = 'D'; /// Все ок мы успешно поменяем наш первый элемент массива
printf(pstr); /// Мы получим это: "Dello, world"

Подведем черту над всеми этими примерами:
Почему я не могу в первом примере поменять отдельно каждый литерал? (Я же не объявлял объект константным как во втором примере)
P.S Третий пример привел для общей картины чтобы показать что все работает если ввести дополнительный параметр

A: Согласно стандарту языка C (6.4.5 String literals)

7 It is unspecified whether these arrays are distinct provided their
  elements have the appropriate values. If the program attempts to
  modify such an array, the behavior is undefined.

То есть вы не можете менять строковые литералы, несмотря на то, что они имеют типы не константных символьных массивов. То, что в C строковые литералы имеют тип неконстантных массивов, это сделано для обратной совместимости программ на C.
Поэтому в этом предложении
char *pstr = "Hello, world";

строковый литерал, используемый в качестве инициализатора указателя pstr, неявно преобразуется в указатель с типом char *, а не в указатель типа const char *, который указывает на первый символ литерала.
В С++ строковые литералы имеют тип константных символьных массивов, что позволяет избежать недоразумения.
В третьем примере
char str[] = "Hello, world";
char *pstr = str;
*pstr = 'D';

указатель pstr имеет уже дело не со строковым литералом, а с определенным пользователем символьным массивом. Строковый литерал лишь используется для инициализации элементов символьного массива своими символами. Так как массив объявлен как не константный, то его элементы можно изменять.

A: с не достаточно типобезопасен и допускает присваивание неконстантным указателям адрес строкового литерала. То, что в левой части указатель не является константным отнюдь не значит, что можно менять то, на что он указывает. Присваивание указателю не создаёт дополнительного объекта под строку и не копирует в неё правую часть.
Т.о. Ваш код вида:
char *pstr = "Hello, world";
*pstr = 'D';

по сути эквивалентен такому (более очевидному для демонстрации варианту):
"Hello, world"[0] = 'D';

В таком виде даже gcc сообщает соответствующим предупреждением:

warning: assignment of read-only location '"Hello, world"[0]'

Стандарт с однозначно утверждает, что попытка модифицировать строковый литерал приводит к неопределённому поведению (6.4.5/7):

If the program attempts to modify such an array, the behavior is
  undefined.

A: В первом и втором случае вы работаете напрямую со строковым литералом.
В языке С у вас нет никакого контроля над const-квалификацией типа строкового литерала. Эта const-квалификация однозначно определяется языком. Тип строкового литерала в C - char [N]. И несмотря на то, что тип строкового литерала формально не содержит квалификатора const, строковый литерал тем не менее является неизменяемым (немодифицируемым) объектом. Попытки изменения строкового литерала, как и любого другого немодифицируемого объекта, ведут к неопределенному поведению.
Как вы объявляли свой указатель pstr - c const или без - на тип и свойства строкового литерала никакого влияния не оказывает. Ваш указатель не имеет никакого отношения к строковому литералу, как таковому. Ваш указатель - это не более чем путь доступа (access path) к реальному объекту. Константность пути доступа - это не более чем элемент самодисциплины, который в общем случае не связан с константностью объекта, к которому этот путь ведет. Язык С предоставляет вам средства для легального создания как константных путей доступа к модифицируемым объектам, так и неконстантных путей доступа к немодифицируемым объектам
int a = 42;
const int *pa = &a;   // константный путь доступа к модифицируемому объекту

const int b = 5;
int *pb = (int *) &b; // неконстантный путь доступа к немодифицируемому объекту

В конечном итоге возможность легальной модификации объекта определяется именно и только модифицируемостью самого объекта и никак не зависит от константности пути доступа к нему (ибо последняя легко устранима).
Учитывая, что литерал является неизменяемым объектом, указывать на строковые литералы неконстантным указателем (как в вашем первом примере) никакого смысла нет, даже если язык и позволяет формально это делать.
В третьем варианте вы не работаете со строковым литералом напрямую, а создаете собственный модифицируемый массив, который только инициализируется значением строкового литерала. Т.е. ваш массив содержит самостоятельную копию значения строкового литерала. Это ваш собственный массив и вы можете модифицировать его как угодно.

A: Строковый литерал является константным по определению. Он может быть вообще помещен в память "только для чтения". Например, VC++ в первом примере код пропустит, сбоев не будет - но при выполнении строка не изменится.


text:
Q: Attach library DLL cannot be loaded by application I am doing bytecode manipulation in java, but it is being done on an external, running JAR file. For this reason, I am using the attach API.
My current problem is that the attach API cannot load a DLL I have in a separate folder. I have proviously had problems with file location but I fixed those and so I know it can see the file, it just can't load it.
My stack trace is as follows:
java.lang.UnsatisfiedLinkError: Can't load library: C:\Users\Jamie\Desktop\Test Rainbow 51\Rainbow Tester\plugins_mod\Natives\64\windows\attach.dll
    at java.lang.ClassLoader.loadLibrary(Unknown Source)
    at java.lang.Runtime.load0(Unknown Source)
    at java.lang.System.load(Unknown Source)
    at RainbowBans.MyPlugin.getAttachProvider(MyPlugin.java:299)
    at RainbowBans.MyPlugin.onStartup(MyPlugin.java:96)
    at joebkt._JoeUtils.LoadPlugins(_JoeUtils.java:2415)
    at joebkt._JoeUtils.Startup(_JoeUtils.java:2502)
    at joebkt.DedicatedServer.startServerConsoleHandler(DedicatedServer.java:44)
    at net.minecraft.server.MinecraftServer.run(MinecraftServer.java:483)
    at java.lang.Thread.run(Unknown Source)

And here is my source code:
    package RainbowBans;

//Just a few imports
import java.awt.Desktop;
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
//Required when used to start premain by command line.
//import java.lang.ProcessBuilder.Redirect;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.*;

import sun.tools.attach.BsdAttachProvider;
import sun.tools.attach.LinuxAttachProvider;
import sun.tools.attach.SolarisAttachProvider;
import sun.tools.attach.WindowsAttachProvider;
import net.minecraft.server.MinecraftServer;

import com.mojang.authlib.GameProfile;
import com.sun.tools.attach.AgentInitializationException;
import com.sun.tools.attach.AgentLoadException;
import com.sun.tools.attach.AttachNotSupportedException;
import com.sun.tools.attach.VirtualMachine;
import com.sun.tools.attach.spi.AttachProvider;

import joebkt.BannedPlayers;
import joebkt.CmdBan;
import joebkt.CmdKick;
import joebkt.PlayerList;
import joebkt._PermMgr;
import PluginReference.*;

public class MyPlugin extends PluginBase{

public static MC_Server server = null;
String pluginDir = "plugins_mod" + File.separatorChar;
String folderDir = pluginDir + "RainbowBans" + File.separatorChar;
String rainbowDir =   RainbowBans.MyPlugin.class.getProtectionDomain().getCodeSource().getLocation().toExternalForm();
String OS = "Unknown!";

public void onStartup(MC_Server svr){
    System.out.println("Plugin starting! Lets hope this works! :)");
    System.out.println("plugins_mod folder located at:" + new File(pluginDir).getAbsolutePath());
    System.out.println("RainbowBansTransAgent is located at: " + new File(pluginDir + "RainbowBansTransAgent.jar").getAbsolutePath());
    server = svr;
    System.out.println("Creating files now!");
    File file = new File(folderDir);
    if(file.isDirectory()) System.out.println("Directory already exists!");
    else {
        System.out.println("Creating plugin directory");
        file.mkdir();
    }
    File errorfile = new File(folderDir + File.separatorChar +     "Rainbowbanserrors.txt");
    if(errorfile.isFile()) System.out.println("File errorfile already exists");
    else
        try {
            System.out.println("Creating stack trace file!");
            errorfile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

    File banfile = new File(folderDir + File.separatorChar + "banmessage.txt");
    if(banfile.isFile()) System.out.println("Banfile already exists!");
    else
        try {
            banfile.createNewFile();
            BufferedWriter writer = new BufferedWriter(new FileWriter(banfile));
            writer.write("You are banned.");
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    File logfile = new File(folderDir + File.separatorChar + "Rainbowbanstransagentlog.txt");
    if(logfile.isFile()) System.out.println("Logfile already exists!");
    else try{
        logfile.createNewFile();
    }catch(IOException e){
    e.printStackTrace();
    }
    JFrame frame = startDialog();
    JMenuBar menu = createMenu();
    frame.setJMenuBar(menu);
    VirtualMachine vm;
    try {

        AttachProvider.setAttachProvider(getAttachProvider());
        vm = VirtualMachine.attach(String.valueOf(Thread.currentThread().getId()));
        String realArch = architecture();
        if(realArch == "64"){
            System.setProperty("java.library.path", new File(folderDir + "Natives" + File.separator + "64" + File.separator + OS + File.separator).getAbsolutePath());
        }else if(realArch == "32"){
            System.setProperty("java.library.path", new File(folderDir + "Natives" + File.separator + "32" + File.separator + OS + File.separator).getAbsolutePath());
        }

            vm.loadAgent(new File(".").getAbsolutePath());
    } catch (AttachNotSupportedException | IOException  | AgentLoadException | AgentInitializationException e) {
        e.printStackTrace();
    }
    //Before using the attach agent, this is how I started the premain in the external JAR (RainbowBansTransAgent.jar)//
    /*File transagent = new File(pluginDir + File.separatorChar + "RainbowBansTransAgent.jar");
    ProcessBuilder pb = new ProcessBuilder("java", "-javaagent:" + transagent.getAbsolutePath(), "RainbowBansTransAgent/TransAgent");
    pb.redirectError(Redirect.appendTo(errorfile));
    pb.redirectOutput(Redirect.appendTo(logfile));
    try{
        pb.start();
    }catch(IOException e){
        e.printStackTrace();
    }
    */
}

private JMenuBar createMenu() {
    JMenuBar menu = new JMenuBar();
    JMenuItem i = new JMenuItem("See message");
    i.addActionListener(getActionListenerForMessage(i));
    menu.add(i);
    JMenuItem w = new JMenuItem("Go to project page");
    w.addActionListener(getActionListenerForWebsites("http://www.project-    rainbow.org/site/index.php?board=9.0"));
    menu.add(w);
    JMenuItem k = new JMenuItem("Go to download page");
    k.addActionListener(getActionListenerForWebsites("http://www.project-    rainbow.org/site/index.php?action=downloads;cat=3"));
    menu.add(k);
    return menu;
}
//I got the code from http://stackoverflow.com/questions/10967451/open-a-link-in-browser-with-java-button
private void openWebsite(String url){
    Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
    if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) {
        try {
            desktop.browse(new URL(url).toURI());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
private ActionListener getActionListenerForWebsites(String url) {
    ActionListener al = new ActionListener(){

        @Override
        public void actionPerformed(ActionEvent e) {
            openWebsite(url);
        }

    };
    return al;
}
private ActionListener getActionListenerForMessage(JMenuItem i) {
    ActionListener al = new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent e) {
                try {
                    BufferedReader reader = new BufferedReader(new FileReader(new File(folderDir + File.separatorChar + "banmessage.txt")));
                    String message = reader.readLine();
                    i.setText(message);
                    Timer timer = new Timer();
                    timer.schedule(getTimerTask(i), 5000);
                    reader.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }

    };
    return al;
}
private TimerTask getTimerTask(JMenuItem i) {
    TimerTask task = new TimerTask(){
        @Override
        public void run() {
            i.setText("See message");
        }
    };
    return task;
}
private JFrame startDialog() {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JOptionPane.YES_NO_OPTION);
    frame.setVisible(true);
    frame.setSize(800, 600);
    frame.setAlwaysOnTop(false);
    frame.setBackground(java.awt.Color.yellow);
    return frame;
}
//Copied from CodeCrafter's MultiWorld project.
private AttachProvider getAttachProvider() {
    String os = System.getProperty("os.name").toLowerCase();
    if (os.contains("win") && !os.contains("darwin")) {
        OS = "windows";
        if(architecture() == "64")System.load(new File(pluginDir + "Natives" + File.separator + "64" + File.separator + "windows" + File.separator + "attach.dll").getAbsolutePath());
        else if (architecture() == "32")System.load(new File(pluginDir + "Natives" + File.separator + "32" + File.separator + "windows" + File.separator + "attach.dll").getAbsolutePath());
        else{}
        return new WindowsAttachProvider();
    }
    else if ((os.contains("nix")) || (os.contains("nux")) || (os.indexOf("aix") > 0)) {
        OS = "linux";
        if(architecture() == "64")System.load(new File(pluginDir + "Natives" + File.separator + "64" + File.separator + "linux" + File.separator + "libattach.so").getAbsolutePath());
        else if(architecture() == "32") System.load(new File(pluginDir + "Natives" + File.separator + "64" + File.separator + "linux" + File.separator + "libattach.so").getAbsolutePath());
        else{}
    return new LinuxAttachProvider();
    }
    else if (os.contains("mac")) {
        OS = "mac";
        System.load(new File(pluginDir + "Natives" + File.separator + "64" + File.separator + "mac" + File.separator + "libattach.dylib").getAbsolutePath());
        return new BsdAttachProvider();
    }
    else if (os.contains("sunos")) {
        OS = "solaris";
        if(architecture() == "64")System.load(new File(pluginDir + "Natives" + File.separator + "64" + File.separator + "solaris" + File.separator + "libattach.so").getAbsolutePath());
        else if(architecture() == "32")System.load(new File(pluginDir + "Natives" + File.separator + "64" + File.separator + "solaris" + File.separator + "libattach.so").getAbsolutePath());
    return new SolarisAttachProvider();
    }
    else{
        return null;
    }
}
//Copied from StackOverflow
private String architecture() {
    String arch = System.getenv("PROCESSOR_ARCHITECTURE");
    String wow64Arch = System.getenv("PROCESSOR_ARCHITEW6432");

    String realArch = arch.endsWith("64")
                  || wow64Arch != null && wow64Arch.endsWith("64")
                      ? "64" : "32";
    return realArch;
}
}

A: It turns out my problem was that I didn't add my DLL to the java.library.path. Problem solved.


text:
Q: Regex to get part of a String String str is set to:
{"query":{"count":1,"created":"2012-02-26T21:38:27Z","lang":"en-US","results":{"title":"Google Search"}}}

I want to use Regex to get Google Search. The 2012-02-26T21:38:27Z and en-US are variable.
This is going to happen in Javascript.
Thanks.

A: That is a JSON string, so you don't want to use a regex. Instead:
var obj = window.JSON.parse(str);
var title = obj.query.results.title;

A: I think you would find it much easier using a JSON parser to get the information that you want. As mentioned by others here, you could use something like the following to get what you're after.
JSON.parse(str).query.results.title

If for some reason you absolutely have to use a RegExp though, you could try something like:
function parseStr(str) {
    var re, matches;
    re = /"results":{"title":"([^"]*)"}/;
    matches = str.match(re);
    if (matches && matches.length > 1) {
        return matches[1];
    }
}

A: This is a JSON string, so parse it as such:
JSON.parse(str).query.results.title


text:
Q: What is the best way to increase the performance of this code? Slow because of orderby syntax in linq I want to write linq faster. Why is it so slow when orderby? When calling the api, dataUsn takes 0.3 seconds and regDt takes 1.2 seconds.
Changing the orderby statement to dataUsn is much faster than using regDt.
 var crsCmplt = context.TblGoOnEduEduCrsCmplt.AsNoTracking()
    var lctreNWrtng = context.TblGoOnEduLctreNWrtng.AsNoTracking();
    var qlfctnObn = context.TblGoOnEduQlfctnObn.AsNoTracking();
    var etc = context.TblGoOnEduEtc.AsNoTracking();

      `  var goEdu = crsCmplt
                        .Union(lctreNWrtng)
                        .Union(qlfctnObn)
                        .Union(etc);   <<---  800,000rows`

`
var t = (from a in goEdu
        orderby a.RegDt descending  <<- Removing orderby here will give you much better performance
        join b in context.TblUsrBasicInfo on a.UsrUsn equals b.UsrUsn
                     select new GoEduUnionModel
                     {
                         DataUsn = a.DataUsn,   <-- type decimal
                         Gbn = a.Gbn,
                         BaseDt = a.BaseDt,
                         Subject = a.Subject,
                         OrgNm = a.OrgNm,
                         NameKr = b.NameKr,
                         UsrGbn = b.UsrGbn,
                         Phone = b.MphoneNo,
                         Brthday = b.Brthday,
                         CnfmDt = a.CnfmDt,
                         AdmitCredit=a.AdmitCredit,
                         ApplCredit = a.ApplCredit,
                         RegDt = a.RegDt,  <-- dateTime
                         UsrUsn = a.UsrUsn,
                     });

`


text:
Q: Add Metadata, headers (Expires, CacheControl) to a file uploaded to Alicloud OSS using the Laravel 5 I am trying to find out how to add in Metadata or headers (Expires, CacheControl etc. I want to have global defaults with headers, this works in Laravel 5 and S3 Amazon, only change config/filesystems.php file like so:
's3' => [
   'driver' => 's3',
   'key' => env('AWS_KEY'),
   'secret' => env('AWS_SECRET'),
   'region' => env('AWS_REGION'),
   'bucket' => env('AWS_BUCKET'),
   'source' => env('S3_SOURCE'),
   'options' => ['CacheControl' => 'max-age=604800, public', 'Expires' => gmdate('D, d M Y H:i:s \G\M\T', strtotime('+7 day'))]
]

'oss' => [
   'driver' => 'oss',
   'key' => env('OSS_ACCESS_KEY_ID'),
   'secret' => env('OSS_ACCESS_KEY_SECRET'),
   'endpoint' => env('OSS_ENDPOINT'),
   'bucket' => env('OSS_BUCKET'),
   'region' => env('OSS_REGION'),
   'source' => env('OSS_SOURCE')
   'options' => ['CacheControl' => 'max-age=604800, public', 'Expires' => gmdate('D, d M Y H:i:s \G\M\T', strtotime('+7 day'))]
]

and this code it's not work in Alicloud OSS(Object Storage Service)


text:
Q: How do I declare a Multidimensional Array of a given size in Typescript I have the following...
export class Puzzle {
  pieces : Piece[];
  orderedPieces : Piece[][];
  constructor(width: number, height: number){
    this.height = height, this.width = width;
    let total : number = width * height;
    this.pieces = new Array<Piece>(total);
    this.orderedPieces = new Piece[height][width]; // Doesn't work what do I put here?
  }
  ...
}

How would I declare something like this in Typescript?
Error is...

Cannot read property '2' of undefined

A: There's no way (that I'm aware of) to instantiate a multidimensional array in javascript in one line.
You'll have to actually create all of the arrays yourself, something like:
this.orderedPieces = new Array(this.height);

for (let i = 0; i < this.height; i++) {
    this.orderedPieces[i] = new Array(this.width);
}


text:
Q: Drupal: if I enable CSS files optimization my website layout changes So, this is funny.
If I Enable to Optimize CSS files, my website is stuck to the left of the browser window.
If I disable it, it is in the middle.
What's the reason of this behavior ? Are some CSS files badly merged or what ?
Update:
/* safari only */
@media screen and (-webkit-min-device-pixel-ratio:0){
.list-add-to-cart {
    line-height:6px;
}

A: It appears that some files are cached and you get the wrong cached versions.
Clear the Drupal cache and your browser's cache and try again.

A: Yes, it sounds like the merging isn't working correctly. Usually this is caused by bad CSS. I'd start by running it through the CSS Validator.