text:
Q: Setting onClickListener to the whole item in onBindViewHolder I have an RecyclerView Adapter and I want to set the onClick to the whole item but this code and when I also tried it with myViewHolder.view.setOnClickListener(..) both still only listened to the click of the checkbox.
How can I set the onClickListener to the whole item ?
public class DeliveryPointSelectionAdapter extends RecyclerView.Adapter<DeliveryPointSelectionAdapter.MyViewHolder> {
    private static final String TAG = MyViewHolder.class.getSimpleName();
    private List<DeliveryPoint> deliveryPointList;

    interface OnItemCheckListener {
        void onItemCheck(DeliveryPoint deliveryPoint);
        void onItemUncheck(DeliveryPoint deliveryPoint);
    }

    @NonNull
    private OnItemCheckListener onItemCheckListener;

    public DeliveryPointSelectionAdapter(List<DeliveryPoint> deliveryPointList, @NonNull OnItemCheckListener onItemCheckListener) {
        this.deliveryPointList = deliveryPointList;
        this.onItemCheckListener = onItemCheckListener;
    }

    @NonNull
    @Override
    public DeliveryPointSelectionAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.dialog_select_deliverypoints_to_change_item, viewGroup, false);
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder myViewHolder, int i) {
        DeliveryPoint deliveryPoint = deliveryPointList.get(i);
        myViewHolder.tvFormattedString.setText(deliveryPoint.domesticAddress.formattedString);
        myViewHolder.checkBox.setChecked(deliveryPoint.isCheckedForLocationUpdate);

        myViewHolder.linearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DeliveryPoint deliveryPoint1 = deliveryPointList.get(myViewHolder.getAdapterPosition());
                if (myViewHolder.checkBox.isChecked()) {
                    deliveryPoint1.setCheckedForLocationUpdate(true);
                    onItemCheckListener.onItemCheck(deliveryPoint1);
                } else {
                    deliveryPoint1.setCheckedForLocationUpdate(false);
                    onItemCheckListener.onItemUncheck(deliveryPoint1);
                }
            }
        });

//        myViewHolder.checkBox.setOnCheckedChangeListener((buttonView, isChecked) -> {
//            DeliveryPoint deliveryPoint1 = deliveryPointList.get(myViewHolder.getAdapterPosition());
//            if (myViewHolder.checkBox.isChecked()) {
//                deliveryPoint1.setCheckedForLocationUpdate(true);
//                onItemCheckListener.onItemCheck(deliveryPoint1);
//            } else {
//                deliveryPoint1.setCheckedForLocationUpdate(false);
//                onItemCheckListener.onItemUncheck(deliveryPoint1);
//            }
//        });
    }

    @Override
    public int getItemCount() {
        return deliveryPointList.size();
    }

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

    public static class MyViewHolder extends RecyclerView.ViewHolder {
        TextView tvFormattedString;
        CheckBox checkBox;
        LinearLayout linearLayout;
        View view;

        MyViewHolder(View view) {
            super(view);
            tvFormattedString = (TextView) view.findViewById(R.id.tv_formatted_string);
            checkBox = view.findViewById(R.id.cb_deliverypoint_checked);
            linearLayout = view.findViewById(R.id.ll_delivery_points_layout);
            this.view = view;
        }
    }
}

Item View Layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/ll_delivery_points_layout"

    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:id="@+id/cb_deliverypoint_checked"/>

        <TextView
            android:id="@+id/tv_formatted_string"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_vertical"
            android:paddingStart="25dp"
            android:paddingTop="15dp"
            android:paddingEnd="25dp"
            android:textColor="@color/gray_text_light"
            android:textSize="18sp"

            tools:ignore="RtlSymmetry" />
    </LinearLayout>
</LinearLayout>

A: Like other users already mentioned myViewHolder.itemView.setOnClickListener to set onClick on the recyclerView holder.
But, correct me if I am wrong, it seems you want your checkbox to be checked/unchecked only by holder click. In that case you need to disable it by adding following codes to your layout xml
               android:clickable="false"
               android:focusable="false"
               android:focusableInTouchMode="false"

Otherwise clicking on checkbox will take its click and not execute the code you wrote for itemview click.
Since you are setting it to checked based on deliveryPoint.isCheckedForLocationUpdate you can notifyItemChanged(position) to update the holder checkbox after click.
See if this helps.
EDIT:
Based on the comments if you are actually trying to toggle your checkbox in the view you should use something like this: also if you create a new object deliveryPoint1 no change is made to the original object you have in the view
myViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (myViewHolder.checkBox.isChecked()) {
                    deliveryPoint.setCheckedForLocationUpdate(false);
                    onItemCheckListener.onItemUncheck(deliveryPoint);
                } else {
                    deliveryPoint.setCheckedForLocationUpdate(true);
                    onItemCheckListener.onItemCheck(deliveryPoint);
                }
            }
        });

A: Firslty create a OnItemClickListener var like so:
public class DeliveryPointSelectionAdapter extends RecyclerView.Adapter<DeliveryPointSelectionAdapter.MyViewHolder> {
    private OnItemClickListener listener;

Then towards the bottom of the class code, implement the setOnItemClickListener method
    public void setOnItemClickListener(OnItemClickListener
                                       listener){
this.listener = listener;

}

Also (towards the end of your class code) you should create a new interface that will describe the data that the on click action will generate. Some thing like this:
public interface OnItemClickListener{
        void OnItemClick(
                int position);

}

Then try setting the on click listener using this method you described in your question myViewHolder.view.setOnClickListener(..)
But inside the MyViewHolder(View view) method.
Something like so:
      view.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               int position = getAdapterPosition();
if(position !=RecyclerView.NO_POSITION&& listener
        !=null){
    listener.OnItemClick(position);
}

A: You are trying to check checkbox, when it is now checked, and uncheck, when it's uncheced. Change thet conditions like by:
            if (myViewHolder.checkBox.isChecked()) {
                deliveryPoint1.setCheckedForLocationUpdate(true);
                onItemCheckListener.onItemCheck(deliveryPoint1);
            } else {
                deliveryPoint1.setCheckedForLocationUpdate(false);
                onItemCheckListener.onItemUncheck(deliveryPoint1);
            }
            notifyItemChanged(myViewHolder.getAdapterPosition());

And remember to call notifyDataSetChanged();on your adapter in your interface method.


text:
Q: How can I ensure that one spring-boot-starter is loaded before another? I'm trying to ensure that one Spring Boot Starter is loaded before another. In this case, I have a custom spring boot starter written by my organization and the spring-boot-starter-data-jpa starter. It's crucial that the custom starter's bean is ran before spring-boot-starter-data-jpa is initialized. An example snippet of the dependencies in pom.xml:
    <dependencies>
        <dependency>
            <groupId>com.example</groupId>
            <artifactId>spring-boot-starter-my-customer-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
    </dependencies>

How would one go about this? The solution I'm currently considering is adding a @Primary annotation to the top of the bean initialized in my company's custom starter, not sure if this would work and looking for best practice here. The bean I'm attempting to load in the custom starter before spring-boot-starter-jpa's beans are loaded is responsible for setting proxy settings, therefore must be loaded first so that traffic to the database can be routed via proxy.

A: Not really sure as to what you are trying to achieve here, but a way of controlling bean creation could be done using the DependsOn annotation.
In you case, since you would like to initialize your custom bean before the actual database connection is made, I think that adding this to your database configuration class should be enough.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Bukkit Check Player's Inventory I'm trying to see if a player has any of the following items in their inventory, and if they do, I want to remove the items and send them a message saying  the item has been removed but I cannot figure out how to do it, this is what I have so far:
    Material[] bannedItems = { Material.DIAMOND_HELMET, Material.DIAMOND_CHESTPLATE, Material.DIAMOND_LEGGINGS, Material.DIAMOND_BOOTS, Material.GOLD_HELMET, Material.GOLD_CHESTPLATE, Material.GOLD_LEGGINGS, Material.GOLD_BOOTS };

@EventHandler
public void onInventoryClick(InventoryClickEvent event) {
    Player player = (Player) event.getWhoClicked();
    if(player.getInventory().contains(bannedItems, 1)){
        player.sendMessage(ChatColor.GRAY + "[" + ChatColor.RED + ChatColor.BOLD + "RPG" + ChatColor.GRAY + "] " + ChatColor.RED + "A has been removed from your possession.");
    }
}

I get an error on the .contains(bannedItems, 1)) line.
Thanks for the help!

A: For every element in the array, you must check it, not just compare the array. Here is a proof of concept:
double[] check = {1.3, 4.2, 4.3}; //A sample double array

for(double d : check) { //Loop thru all elements
    if(4.2 == d) { //If current element is equal to 4.2
        System.out.println("EQUAL!"); //Print "EQUAL!"
    }
}

This loops over the check array one-by-one and compares each element to 4.2. It them reports when they are equal. You can then apply this to this situation:
@EventHandler
public void onInventoryClick(InventoryClickEvent event) {
    Material[] bannedItems = { Material.DIAMOND_HELMET, Material.DIAMOND_CHESTPLATE, Material.DIAMOND_LEGGINGS, Material.DIAMOND_BOOTS, Material.GOLD_HELMET, Material.GOLD_CHESTPLATE, Material.GOLD_LEGGINGS, Material.GOLD_BOOTS };
    Player player = (Player) event.getWhoClicked();

    for(Material m : bannedItems) { //Loop thru all elements
        if(player.getInventory().contains(m, 1)){ //Check if in inventory
            player.sendMessage(ChatColor.GRAY + "[" + ChatColor.RED + ChatColor.BOLD + "RPG" + ChatColor.GRAY + "] " + ChatColor.RED + "A has been removed from your possession.");
            //Remove stuff
        }
    }
}

Now, the event will loop through each element of the bannedItems and check if the user has it in there inventory.
for(Material m : bannedItems)

Is an enhanced for loop that stores the current element in bannedItems in the m variable and then we compare using m, a single material.
I would also use a different event, such as when they pick up an item, and then check, so you can remove it right away.


text:
Q: Play Framework 2.5.x: Inject Environment in a Module Play app contains a custom module that initializes DB/Tables during the app start.
Starting with v2.5.x, the application mode(prod, test, dev) needs to be injected rather than using Current. I tried to apply the following inject parameters in the module code but saw compile errors.
trait MyInit[Environment] {
  val env: Environment
}

class MyInitClass[Environment] @Inject() (
  val env: Environment
) extends MyInit[Environment] {
  initializeDB()

  def initializeDB() = {
    Logger.info("MyINIT: Creating database...")
    MyDBService.createDatabase()
    Logger.info("MyINIT: Creating tables...")
    MyDBService.createTables()
  }
}

class MyModule(environment: Environment,
             configuration: Configuration) extends AbstractModule with ScalaModule {
  def configure() = {
    bind[MyInit[Environment]].to[MyInitClass[Environment]].asEagerSingleton()
  }
}

Is there a prescribed way of looking up Environment/Mode during module initialization in Play 2.5.x (Scala)?

A: I will rewrite your code to remove a small possible confusion here. This is exactly your code with a small rename of the type parameters:
import javax.inject.Inject
import play.api.Logger
import play.api.Environment
import play.api.Configuration
import com.google.inject.AbstractModule

trait MyInit[T] {
  val env: T
}

class MyInitClass[T] @Inject() (val env: T) extends MyInit[T] {
  initializeDB()

  def initializeDB() = {
    Logger.info("MyINIT: Creating database...")
    MyDBService.createDatabase()
    Logger.info("MyINIT: Creating tables...")
    MyDBService.createTables()
  }
}

I renamed the type parameters to avoid confusion with play.api.Environment. I have the felling that this is not what you want, since MyInitClass does not actively receive an play.api.Environment anywhere.
If you want to do some initialization, why not go with something more simple and direct like this:
import com.google.inject.AbstractModule
import play.api.{Configuration, Environment, Mode}

class DatabaseInitializerModule(
  environment: Environment,
  configuration: Configuration
) extends AbstractModule {

  def configure() = {
    environment.mode match {
      case Mode.Dev =>
        // Start dev database
      case Mode.Test =>
        // Start test database
      case Mode.Prod =>
        // Start prod database
    }
  }
}

Edit:
A more idiomatic and recommended way to replace GlobalSettings.onStart is described at the docs:

GlobalSettings.beforeStart and GlobalSettings.onStart: Anything that needs to happen on start up should now be happening in the constructor of a dependency injected class. A class will perform its initialisation when the dependency injection framework loads it. If you need eager initialisation (because you need to execute some code before the application is actually started), define an eager binding.

So, we can rewrite your code to be something like this:
import javax.inject.Inject

import play.api.{Environment, Mode}
import com.google.inject.AbstractModule

class DatabaseInitializer @Inject()(environment: Environment) {
  environment.mode match {
    case Mode.Dev =>
    // Start dev database
    case Mode.Test =>
    // Start test database
    case Mode.Prod =>
    // Start prod database
  }
}

class DatabaseInitializerModule extends AbstractModule {
  override def configure() = {
    bind(classOf[DatabaseInitializer]).asEagerSingleton()
  }
}

Notice how I've removed the trait since it is not adding any value here.


text:
Q: Create a package of products as one Item in woocommerce? How can we create a package of items as one product?
Example (Keyboard, mouse and Screen) as one product with one price for all of them and the user can't change the quantity of any of them.
I tried the group product but the user can change the quantity.

A: My suggestion would be for you to add a new product with the correct price including all 3 pieces, with images of all 3 products.
Then you could create a tab or a section further down on the product page that lists the products that the bundle includes. So when the user purchases the product they know which parts they would be getting for that price.
If the different components could also be sold seperately you could make a product loop further down the page with links to the product pages of the components.
Another option would be for you to try the woocommerce plugin https://woocommerce.com/products/product-bundles/ which would let you create this functionality out of the box with a product type called "Bundled Product".
Hope this helps.


text:
Q:  inside  gets blue border

IE8 highlights the image with a blue border. I'm not sure what CSS is relevant here, is it just border? Can I use a single CSS style to turn it off, like:
a img {
  ...
}

A: Use this css:
a img {
 border:none;
}

A: a img{
    border-width: 0;
}

Find further reference at https://developer.mozilla.org/en/CSS/border
I suggest you test your site in other browsers. In this case, you would have noticed that it's not an IE8 issue.

A: Yes, you can:
a img { border: 0; }

You can use 0 for 0px width, or none for no border overall, same effect...they both work cross-browser.

A: Have you tried setting the image border to 0?

A: You can also use this

However Sarfaraz' answer above is a better approach.


text:
Q: PHP SUM() function incorrect computation I'm using slim framework, what i want to do, is to compute a certain amount of a specific user ..
here's my table
load_up_id   user_id   amount
1            1         1000
2            1         1000
3            1         2000
4            2         3000
5            2         1000

i want to get the total amount of user_id no. 1, but instead of 4000 , it gives me 2000
here's my code
$loadups = $this->loadupPayment->where('user_id', $this->auth->user()->user_id)->get();

$total_loadup = $this->loadupPayment->select(db::raw('sum(amount) as total_loadup'))->groupBy('user_id')->get();

Thank you in advance guys! :D

A: So you want a specific user's ID ? Try this one instead:
$total_loadup = $this->loadupPayment->select(db::raw('sum(amount) as total_loadup'))->where('user_id', $this->auth->user()->user_id)->get();

A: I think rather than grouping by user id, you need to use the user id as a CASE in a sum statement. This is in essence a where cause in the SUM calculation, so you can say when the user id is the user id i want (in this case 1) add the value if not just ignore it.
Try something like this
$total_loadup = $this->loadupPayment->select(db::raw('SUM(CASE WHEN user_id = 1 THEN amount ELSE 0 END) as total_loadup'))->get();

You may want to parameterze the user id value in the above.
Hope this helps!


text:
Q: How can I sort this array of objects alphabetically in node js? I have a question about how to order this array of objects alphabetically, knowing that some of the elements of the array are in lowercase and others have special characters.
The array is:
  Product { id: 1, name: 'TV Samsung MP45', price: 325.9, units: 8 },
  Product { id: 2, name: 'Ábaco de madera (nuevo modelo)', price: 245.95, units: 15 },
  Product { id: 3, name: 'impresora Epson', price: 55.9, units: 8 },
  Product { id: 4, name: 'USB Kingston 16GB', price: 5.95, units: 45 }

I must sort alphabetically with this shape:
   Product { id: 2, name: 'Ábaco de madera (nuevo modelo)', price: 245.95, units: 15 },
   Product { id: 3, name: 'impresora Epson', price: 55.9, units: 8 },
   Product { id: 1, name: 'TV Samsung MP45', price: 325.9, units: 8 },
   Product { id: 4, name: 'USB Kingston 16GB', price: 5.95, units: 45 }

But the result is the following:
  Product { id: 1, name: 'TV Samsung MP45', price: 325.9, units: 8 },
  Product { id: 2, name: 'Ábaco de madera (nuevo modelo)', price: 245.95, units: 15 },
  Product { id: 3, name: 'impresora Epson', price: 55.9, units: 8 },
  Product { id: 4, name: 'USB Kingston 16GB', price: 5.95, units: 45 }

To order the array, I use the sort function like this:
orderByName(){
    return this.products.sort((a,b) => a.name - b.name);
        return a.name - b.name;
}

I have tried many things to get it to order with some words with special characters and some are lowercase.
Does anyone know any solutions?

A: You can call String#normalize on both names before comparing them with localeCompare:

const arr = [
{ id: 1, name: 'TV Samsung MP45', price: 325.9, units: 8 },
{ id: 2, name: 'Ábaco de madera (nuevo modelo)', price: 245.95, units: 15 },
{ id: 3, name: 'impresora Epson', price: 55.9, units: 8 },
{ id: 4, name: 'USB Kingston 16GB', price: 5.95, units: 45 }
];

arr.sort((a, b) => a.name.normalize().localeCompare(b.name.normalize()));
console.log(arr);


text:
Q: Write Kinect joint positions to txt on button click I would like to write joint positions to a txt file.
I have a method to get the X,Y,Z positions of one joint.
  public void positions(Skeleton skeleton)
    {
        // get the joint
        Joint rightHand = skeleton.Joints[JointType.HandRight];

        // get the individual points of the right hand
        double rightX = rightHand.Position.X;
        double rightY = rightHand.Position.Y;
        double rightZ = rightHand.Position.Z;
    }

and I have my click method
  private void stoji_Click(object sender, RoutedEventArgs e)
    {

           File.AppendAllText(@"E:\skuska.txt", rightX + ", " + rightY + ", " +rightZ + Environment.NewLine);

    }

But obviously the rightX, rightY and rightZ cannot be seen from onclick method. And if I add the code from positions method to onclick method, it does not recognize "skeleton".
Thank you

A: Make rightX, rightY, rightZ instance variables of your class.
public class MyKinect
{
   private double rightX;
   private double rightY;
   private double rightZ;

   public void positions(Skeleton skeleton)
   {
      // get the joint
      Joint rightHand = skeleton.Joints[JointType.HandRight];

      // get the individual points of the right hand
      rightX = rightHand.Position.X;
      rightY = rightHand.Position.Y;
      rightZ = rightHand.Position.Z;
   }

   private void stoji_Click(object sender, RoutedEventArgs e)
   {
      File.AppendAllText(@"E:\skuska.txt", rightX + ", " + rightY + ", " +rightZ + Environment.NewLine);
    }
}


text:
Q: Parsing a query in coldfusion I have a query as below  which
 <cfquery name="qryGetXXX" datasource="#sDataSource#">
     SELECT        COUNT(*) AS TotalCount,Quality.Qualitydesc
        FROM          QualityCheck INNER JOIN Quality
        ON QualityCheck.QualityID = Quality.qualityID
        WHERE DATEDIFF(d,DueDate,GETDATE()) >= 90
        GROUP BY quality.qualityDesc
  </cfquery>

will result in

1) *total count* 21 *QualityDesc*   IO
2) *total count* 1  *QualityDesc*   Max
3) *total count* 1  *QualityDesc*   Min
4) *total count* 1  *QualityDesc*   Other
5) *total count* 3  *QualityDesc*   Reg

In order to get the first row I am using,
<cfif #qryGetXXX.RecordCount# gt 0  >
   <cfloop query="qryGetXXX" startrow="1" endrow="1">
      <cfset XXXTimeTotal =#qryGetXXX.TotalCount# >
   </cfloop>
 <cfelse>
    <cfset XXTotal = 0 >
 </cfif>

which is checking for the first the recordcount of the whole query but is there any way I can check whether the first row (i.e. startrow 1 and endrow 1) is has a value and then if the startrow 2 and endrow 2 has a value and so on? Can I put the results in  an array and will that be easier?
Frank,
You are correct, i am new to coldfusion, hence all the confusion.The query provides me with the results i.e i have the result set as explained above, however i cannot figure out a way to check every row individually. For example i have to check if there are results for the first row and if it does i have to pass that value to my output, and if doesnot i have to put in no value was entered or '0'. I need to do this for the five rows and there will always only be 5 rows of results, which is why i was using start and endrow, however start and endrow donot allow me the flexibility to check for empty row values. In essence i would like to check the row as something like below.


text:
Q: Is there a way to capture scroll events on a List-View in NativeScript I'm using a grid layout for a List View for a simple RSS reader, and want to reload the list if the user scrolls past the top (standard Android design pattern).
From the ui/gestures module I've tried the swipe and pan gestures, but I haven't been able to determine the scroll position from those. for example:
XML
<ListView pan="myFunc"items="{{ myItems }}">
    <ListView.itemTemplate>
        <GridLayout columns="*,3*" rows="*,2*">
            ...
        </GridLayout>
    </ListView.itemTemplate>
</ListView>

JS
function myFunc(args){
    if(args.deltaY > 0 && args.deltaX > -10 && args.deltaX < 10){
        console.log('swiping down');
    }
}

invokes myFunc and I can determine deltaY, but I'm not sure how to find the vertical offset from it's args object to tell if the user is trying to scroll past the top.
I saw the ui/scroll-view module, but I don't know how that will interact with my GridLayout and ListView.
New to this project, and it feels like I'm overlooking something simple.
Would be grateful for any insight. Thanks!


text:
Q: How to set the IsSelected property for a treeview which contains a Textblock I created a TreeView and inside of the TreeView is a Textblock located:
 <TreeView x:Name="tvBelege" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Row="3" Grid.ColumnSpan="2" MinHeight="200" MaxHeight="300" Margin="5,5,5,5" SelectedItemChanged="TvBelege_SelectedItemChanged">
        <TreeView.ItemTemplate>
            <HierarchicalDataTemplate DataType="local:Beleg" ItemsSource="{Binding Projektphasen}">
                <TextBlock Text="{Binding DisplayName}"/>
            </HierarchicalDataTemplate>
        </TreeView.ItemTemplate>
 </TreeView>

After loading the Dialog an item should be selected automatically  like this:

But there is no property or function like select or IsSelected to set. How can i do this?

A: Add an IsSelected property to your Beleg class and define an ItemContainerStyle that binds the IsSelected property of the TreeViewItem container to it:
<TreeView x:Name="tvBelege" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Row="3" Grid.ColumnSpan="2" MinHeight="200" MaxHeight="300" Margin="5,5,5,5" SelectedItemChanged="TvBelege_SelectedItemChanged">
    <TreeView.ItemTemplate>
        <HierarchicalDataTemplate DataType="local:Beleg" ItemsSource="{Binding Projektphasen}">
            <TextBlock Text="{Binding DisplayName}"/>
        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
    <TreeView.Resources>
        <Style TargetType="{x:Type TreeViewItem}">
            <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
        </Style>
    </TreeView.Resources>
</TreeView>

You then set the property of the Beleg object to be selected in your view model.


text:
Q: Exactness of a short sequence of quotient modules Suppose R is a commutative ring with 1, I $\subset R$ is an ideal.
We have R-Modules A, B and C with C being flat, as well as a short exact sequence
$0 \rightarrow A \rightarrow B \rightarrow C \rightarrow 0$
Consider the induced sequence
$0 \rightarrow A/IA \rightarrow B/IB\rightarrow C/IC\rightarrow 0$
How do I prove that this sequence is exact? I have no idea how the flatness of C could come into play, or to be more specific, how I can use the exactness of $C\otimes\_$ (this is the only definition of flatness we have so far).
Any advice in the right direction would be appreciated.

A: If $0 \to A \to B \to C \to 0$ is exact, then apply $R/I \otimes_R -$ to get the exact $$\operatorname{Tor}(R/I, C) \to R/I \otimes A \to R/I \otimes B \to R/I \otimes C \to 0.$$ Since $C$ is flat Tor(−,C) = 0, and $R/I \otimes M = M/IM$, you get exactly what you asked for.
Alexander Thumm's answer is basically including a zig-zag lemma to prove Tor is "balanced".  In other words, we have by definition that Tor(C,−) = 0, as in, if we tensor with C then there is no "extra term" on the left, but I sneakily used that Tor(−,C) = 0 too, so I can tensor things ending with C and keep exactness.
You might try proving your original question directly for abelian groups.  This is a fairly literal translation of "torsion" (as in nx = 0) into the "torsion functor" (as in Tor(−,C)).

A: Hint: Why is the following diagram exact/commutative?
$$\array{
&&&&&&0& \\
&&&&&&\downarrow& \\
 && A \otimes I & \to & B \otimes I & \to & C \otimes I & \to & 0 \\
&&\downarrow&&\downarrow&&\downarrow&& \\
0 & \to & A \otimes R & \to & B \otimes R & \to & C \otimes R & \to & 0 \\
&&\downarrow&&\downarrow&&\downarrow&& \\
 && A \otimes R/I & \to & B \otimes R/I & \to & C \otimes R/I & \to & 0 \\
&&\downarrow&&\downarrow&&\downarrow&& \\
&&0&&0&&0&& \\
}$$
Now try to prove, that the map $A \otimes R/I \to B \otimes R/I$ is a monomorphism.
For completeness of the answer I'll add the diagrammatic yoga, but you should first try to solve this yourself. Here you go:

 Let $a'' \in A\otimes R/I$ with $a'' \mapsto 0 \in B\otimes R/I$ and $a \in A \cong A \otimes R$ with $a \mapsto a''$. Now let $b \in B \cong B\otimes R$ be the image of $a$ under the map $A \otimes R \to B \otimes R$. By commutativity of the diagram, we have $b \mapsto 0 \in B \otimes R/I$. By exactness, there is a $b' \in B \otimes I$ with $b' \mapsto b$. Now let $c' \in C  \otimes I$ be the image of $b'$ under the map $B\otimes I \to C \otimes I$. By exactness and commutativity we have $c' \mapsto 0$ by $C\otimes I \to C \otimes R$. Again by ecaxtness (the map $C\otimes I \to C \otimes R$ is a monomorphism) we have $c' = 0$, so there is a $a' \in A \otimes I$ with $a' \mapsto b'$ by $A\otimes I \to B \otimes I$. Let $\tilde a \in A \otimes R$ be the image of $a'$ under the map $A\otimes I \to A \otimes R$. By commutativity we have $\tilde a \mapsto b$. By exactness ($A\otimes R \to B \otimes R$ is a monomorphism) we have $\tilde a = a$, so by exacness $a'' = 0$, since $a' \mapsto \tilde a = a \mapsto a''$.

A: Note that $A/IA \cong A\otimes _R (R/I)$.  Now apply the functor $-\otimes R/I$ to your short exact sequence.  You get a long exact sequence, because $\otimes$ is not exact, but flatness implies that any tor groups involving $C$ vanish.


text:
Q: Issues with parallelizing processing of numpy array I am having an issue with my attempt in speeding up the computation of my program. In the serialized python version of my code, I'm computing the values of a function f(x), which returns a float, for sliding windows of the NumPy array as can be seen below:
a = np.array([i for i in range(1, 10000000)]) # Some data here
N = 100
result = []
for i in range(N, len(a)):
    result.append(f(a[i - N:i]))

Since the NumPy array is really large and f(x) runtime is high, I've tried to apply multiprocessing to speed up my code. Through my research, I found that charm4py might be a great solution and it has a Pool feature, which breaks up an array in chunks and distributes work between spawned processes. I've implemented charm4py's multiprocessing example and then, translated it to my case:
# Split an array into subarrays for sequential processing (takes only 5 seconds)
a = np.array([a[i - N:i] for i in range(N, len(a))])
result = charm.pool.map(f, a, chunksize=512, ncores=-1)
# I'm running this code through "charmrun +p18 example.py"

The issue that I've encountered is that code was running a lot slower, despite being executed on a more powerful instance (18 physical cores vs 6 physical cores).
I've expected to see ~3x improvement, but it didn't happen. While searching for solutions I've learned that there is some overhead for expensive deserialization/spinning up new processes, but I am not sure if this is the case.
I would really appreciate any feedback or suggestions on how one can implement fast parallel processing of a NumPy array (assuming that function f(x) is not vectorized, takes a pretty long time to compute, and internally makes a large number of specific/individual calls that cannot be parallelized)?
Thank you!

A: Here's an example based off of your code snippet that uses Ray to parallelize the array computations.
Note that the best way to do this will depend on what your function f looks like.
import numpy as np
import ray
import time

ray.init()

N = 100000

a = np.arange(10**7)
a_id = ray.put(a)

@ray.remote
def f(array, index):
    # Do processing
    time.sleep(0.2)
    return 1

result_ids = []
for i in range(len(a) // N):
    result_ids.append(f.remote(a_id, i))

results = ray.get(result_ids)

A: It sounds like you're trying to parallelize this operation with either Charm or Ray (it's not clear how you would use both together).
If you choose to use Ray, and your data is a numpy array, you can take advantage of zero-copy reads to avoid any deserialization overhead.
You may want to optimize your sliding window function a bit, but it will likely look like this:
@ray.remote
def apply_rolling(f, arr, start, end, window_size):
    results_arr = []
    for i in range(start, end - window_size):
        results_arr.append(f(arr[i : i + windows_size])
    return np.array(results_arr)

note that this structure lets us call f multiple times within a single task (aka batching).
To use our function:
# Some small setup
big_arr = np.arange(10000000)
big_arr_ref = ray.put(big_arr)

batch_size = len(big_arr) // ray.available_resources()["CPU"]
window_size = 100

# Kick off our tasks
result_refs = []
for i in range(0, big_arr, batch_size):
    end_point = min(i + batch_size, len(big_arr))
    ref = apply_rolling.remote(f, big_arr_ref, i, end_point)
    result_refs.append(ref)

# Handle the results
flattened = []
for section in ray.get(result_refs):
    flattened.extend(section)

I'm sure you'll want to customize this code, but here are 2 important and nice properties that you'll likely want to maintain.
Batching: We're utilizing batching to avoid starting too many tasks. In any system, parallelizing incurs overhead, so we always want to be careful and make sure we don't start too many tasks. Furthermore, we are calculating batch_size = len(big_arr) // ray.available_resources()["CPU"] to make sure we use exactly the same number of batches as we have CPUs.
Shared memory: Since Ray's object store supports zero copy reads from numpy arrays, calling ray.get or reading from a numpy array is pretty much free (on a single machine where there are no network costs). There is some overhead in serializing/calling ray.put though, so this approach only calls put (the expensive operation) once, and ray.get (which is implicitly called) many times.
Tip: Be careful when passing arrays as parameters directly into remote functions. It will call ray.put multiple times, even if you pass the same object.


text:
Q: Calculate Total Price with Symfony (Solved) I have the following problem with shopping cart. I don't know where to place the calculation, so it can update total price dynamically (Such when the cart item is removed, or the quantity updated). Because I need to call updateTotalPrice()  method almost everywhere, but I don't want to repeat the code that many times
So far it look like this

CartService
class CartService extends AbstractController
{

    private CartRepository     $cartRepository;
    private ManagerRegistry    $managerRegistry;
    private CartItemRepository $cartItemRepository;

    public function __construct(CartItemRepository $cartItemRepository, CartRepository $cartRepository, ManagerRegistry $managerRegistry)
    {
        $this->cartItemRepository = $cartItemRepository;
        $this->cartRepository = $cartRepository;
        $this->managerRegistry = $managerRegistry;
    }

    /**
     * Get Cart by ID
     *
     * @return Cart|null
     */
    public function getCartByUserId(): ?Cart
    {
        /**
         * @var User $user
         */
        $user = $this->getUser();

        return $this->cartRepository->findOneBy(['customer' => $user->getId()]);

    }

    /**
     * Create Cart for Customer
     *
     * @return Cart|null
     */
    public function createNewCart(): ?Cart
    {
        $entityManager = $this->managerRegistry->getManager();
        $cart = new Cart();
        /**
         * @var User $user
         */
        $cart->setCustomer($this->getUser());
        $entityManager->persist($cart);
        $entityManager->flush();

        return $cart;
    }

    /**
     * @param Cart $cart
     * @param Product $product
     * @return CartItem|null
     */
    public function isProductInCart(Cart $cart, Product $product): ?CartItem
    {
        return $this->cartItemRepository->findOneBy(['product' => $product->getId(), 'cart' => $cart->getId()]);
    }

    /**
     * Add new product to cart
     *
     * @param Cart $cart
     * @param Product $product
     * @param int $quantity
     * @return void
     */
    public function insertProduct(Cart $cart, Product $product, int $quantity): void
    {
        $entityManager = $this->managerRegistry->getManager();

        $insertProduct = new CartItem();
        $insertProduct->setCart($cart)
                      ->setCart($cart)
                      ->setQuantity($quantity)
                      ->setProduct($product);
        $cart->addCartItem($insertProduct);
        $cart->setTotalprice($cart->getTotalprice() + $insertProduct->getQuantity() * $insertProduct->getProduct()->getPrice());
        $entityManager->persist($insertProduct);
        $entityManager->flush();
    }

    /**
     * Update item's quantity
     *
     * @param CartItem $cartItem
     * @param int $quantity
     * @return void
     */
    public function updateCartItemQuantity(CartItem $cartItem, int $quantity): void
    {
        $entityManager = $this->managerRegistry->getManager();
        $cartItem->setQuantity($quantity);
        $entityManager->persist($cartItem);
        $entityManager->flush();
    }

    /**
     * Remove specific product from cart
     *
     * @param int $id
     * @return void
     */
    public function removeProductFromCart(int $id): void
    {
        $product = $this->cartItemRepository->findOneBy(['product' => $id]);
        $entityManager = $this->managerRegistry->getManager();
        $entityManager->remove($product);
        $entityManager->flush();
    }

    /**
     * Set or update total price
     *
     * @param Cart $cart
     * @param float $totalprice
     * @return void
     */
    public function updateTotalPrice(Cart $cart, float $totalprice): void
    {
        $entityManager = $this->managerRegistry->getManager();
        $cart->setTotalprice($cart->getTotalprice() + $totalprice);
        $entityManager->persist($cart);
        $entityManager->flush($cart);
    }

    /**
     * Add Product to Cart
     *
     * @param Product $product
     * @param $cartItem
     * @return void
     */
    public function addOrUpdateProduct(Product $product, $cartItem): void
    {
        $cart = $this->getCartByUserId();

        if (!$cart instanceof Cart) {
            $cart = $this->createNewCart();
        }

        $isProductInCart = $this->isProductInCart($cart, $product);

        //If product doens't exist, insert it inside cart. If exist, update quantity and add message
        if (!$isProductInCart) {
            $this->insertProduct($cart, $product, $cartItem->getQuantity());
            $this->addFlash('productAdded', 'Product added to Cart');
        } else {
            $this->updateCartItemQuantity($isProductInCart, $cartItem->getQuantity() + $isProductInCart->getQuantity());
            $this->updateTotalPrice($cart, $cartItem->getQuantity() * $cartItem->getProduct()->getPrice());
            $this->addFlash('productAdded', 'Product already in cart. Quantity Updated');
        }
    }

OrderController (That's the cart)
<?php

namespace App\Controller;

/**
 * @IsGranted("IS_AUTHENTICATED_FULLY")
 */
#[Route('/cart', name: 'cart.')]
class OrderController extends AbstractController
{

    /**
     * Show current Cart
     *
     * @param CartService $cartService
     * @return Response
     */
    #[Route('/', name: 'show_cart')]
    public function showCart(CartService $cartService): Response
    {
        $cart = $cartService->getCartByUserId();

        return $this->render('cart/index.html.twig', [
            'cart' => $cart,
        ]);
    }

    /**
     * Update existing cart item quantity
     *
     * @param CartItem $cartItem
     * @param int $quantity
     * @param CartService $cartService
     * @return Response
     */
    #[Route('/updatecartquantity/{id}/{quantity}', name: 'updatequantity')]
    public function updateCartQuantity(CartItem $cartItem, int $quantity, CartService $cartService): Response
    {
        $cartService->updateCartItemQuantity($cartItem, $quantity);

        return $this->redirect($this->generateUrl('cart.show_cart'));
    }

    /**
     * Remove product from cart
     *
     * @param CartService $cartService
     * @param int $id
     * @return Response
     */
    #[Route('/removeitem/{id}', name: 'removefromcart')]
    public function removeFromCart(CartService $cartService, int $id): Response
    {
        $cartService->removeProductFromCart($id);
        return $this->redirect($this->generateUrl('cart.show_cart'));
    }

}

Product Controller (Shows the product -> After choosing quantity can be inserted inside cart
#[Route('/product', name: 'product.')]
class ProductController extends AbstractController
{

    /**
     * Show Product, and add to cart
     *
     * @param Product $product
     * @param CartService $cartService
     * @param Request $request
     * @return Response
     */
    #[Route('/showproduct/{id}', name: 'showproduct')]
    public function showProduct(Product $product, CartService $cartService, Request $request): Response
    {
        $form = $this->createForm(CartItemType::class);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $item = $form->getData();
            $item->setProduct($product);

            $cartService->addOrUpdateProduct($product, $item);
        }

        return $this->render('product/showproduct.html.twig', [
            'product' => $product,
            'form' => $form->createView()
        ]);
    }
}

A: I solved by adding showCart() method, which instead inserts and updates values in database, it runs only, when I want to display Cart.
    public function showCart(): ?Cart
    {
        $cart = $this->getCartByUserId();
        $cartItem = $this->cartItemRepository->findBy(['cart' => $cart]);
        $totalprice = 0;
        foreach ($cartItem as $carti) {
            $totalprice += $carti->getQuantity() * $carti->getProduct()->getPrice();
        }
        $cart->setTotalprice($totalprice);

        return $cart;
    }


text:
Q: Managing concurrent connections in IIS7 I'm having an issue with my hosting provider (winhost.com). My app is built on ASP.NET 4 MVC 3. Up until a few days ago, everything was running fine. All of a sudden I've started getting 503 errors when trying to access my site (wikipediamaze.com). It doesn't happen all the time, just most of the time.
When someone starts playing the game a request is made to wikipedia.org to get the contents of the page for the current step in the puzzle. Basically I'm screen scraping wikipedia.org, injecting some html and then displaying the results. All of my web requests are closed immediately after receiving the data.
What winhost is telling me is that there are connections remaining open and causing any additional requests to the site to get the 503 Service Unavailable Error. What I can see from my end is that only 1 request is ever allowed to be made to wikipediamaze.com at a time. If you keep refreshing the page you'll eventually get the HTML but all subsequent requests (css,images,js) all get the 503 error. Even pages that don't ever call out to wikipedia.org.
If it was an issue with connection throttling in IIS, do both incoming and outgoing (requests made internally) fall in to the same bucket? If I'm sure all of my connections are being closed (and I've never had this issue before) what else could cause this?
It's a hosted environment so my hands are kind of tied, and I know all of this is pertty vague, but if someone had any insight, it would be much appreciated.

A: My first suggestion is to make sure that you're closing your connections (preferably using Using statements) when you're done with them because then they can be re-used. I know you've said that you're closing them already but sometimes you have to dispose of them.
In addition to this you can change the number of connections that your server will make to other servers by putting the following in your web.config file.
<system.net>
    <connectionManagement>
        <add address="*" maxconnection="48" />
    </connectionManagement>
</system.net>


text:
Q: How to split 4 columns, one row into 2 columns, two rows? I am using SSRS 2008R2 and SSMS 2008R2 and I am trying to split 4 columns, one row into two rows, 2 columns.  How can I do this?
Here is some sample data:
create table #foo
(col1 int, col2 int, col3 int, col4 int)
insert #foo values(1,2,3,4)
insert #foo values(5,6,7,8)
insert #foo values(9,10,11,12)
select * from #foo

But I want to transform this data to look like this:
create table #goo (col1 int, col2 int)
insert #goo values(1,2)
insert #goo values(3,4)
insert #goo values(5,6)
insert #goo values(7,8)
insert #goo values(9,10)
insert #goo values(11,12)
select * from #goo

How can I do this?

A: As simple as:
create table #foo(col1 int, col2 int, col3 int, col4 int);
insert #foo values(1,2,3,4),(5,6,7,8),(9,10,11,12);

SELECT col1, col2
FROM #foo
UNION ALL
SELECT col3, col4
FROM #foo;

LiveDemo
First 2 columns UNION ALL with 3rd and 4th columns.
If you need to store in #goo use:
SELECT col1, col2
INTO #goo
FROM #foo
UNION ALL
SELECT col3, col4
FROM #foo;

SELECT * FROM #goo;

A: I imagine it would look something like this
SELECT CONCAT_WS(" ", col1, col2) FROM #foo UNION ALL
SELECT CONCAT_WS(" ", col3, col4) FROM #foo;

Breakdown
concat_ws - Combines two columns with a word separator. In this case a space.
Union All - Merges with another selector to create multiple rows.
SQLFiddle
http://sqlfiddle.com/#!9/ca24df/3/0


text:
Q: Right structure to place files in a web-project I am extremely extremely new to learning web-development. I am using head-first java and while following its first chapter, I am completely stuck at one problem. So, straight to the problem:
I am using Apache-tomcat-7.0.55. In the webapps folder I have created my project, and the folder structure it has is as follows:
    /path_to/apache-tomcat-7.0.55/webapps
                   --  /ch1/`my project folder`
                        --WEB-INF/ --web.xml
                            --classes/ --Ch1servlet.class

and my web.xml is as follows :
 <?xml version="1.0" ?>
 <web-app xmlns="http://java.sun.com/xml/ns/j2ee"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
              http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
          version="2.4"
 >
<servlet>
    <servlet-name>Chapter1 Servlet</servlet-name>
    <servlet-class>Ch1servlet</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>Chapter1 Servlet</servlet-name>
    <url-pattern>/Serv1</url-pattern>
</servlet-mapping>

and the Ch1servlet.java file is as follows:
     public class Ch1servlet extends HttpServlet{
     public void doGet(HttpServletRequest request, HttpServletResponse response) throws
     IOException{
             PrintWriter out = response.getWriter();
             java.util.Date today = new java.util.Date();
              out.println("" +
                              "" +
                                 "
HF\'s Chapter1 Servlet
" +
                                     "
" + today +   "" + "");
               }
       }

When I start the server and run try to fire URL http://localhost:8080/ch1/Serv1 using my browser, I always get resource not found error. Why is that so? I feel I have followed all the steps specified in the book well?

A: You should put servlet classes in a java package. Whether packageless servlets works depend on the specific combination of an older Tomcat and JVM version. Here I can see you are using a fairly new Tomcat version and also if you see this example in a book/tutorial, then it is surely outdated.

package com.example;

// ...

public class Ch1Servlet extends HttpServlet {
  // ...
}

And your web.xml should be like this:

<? xml version="1.0" encoding="UTF-8" ?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns: xsi="http://www.w3.org/2001/XMLSchema-instance" xsi: schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <servlet>
    <servlet-name>Chapter1 Servlet
      </servlet-name>
      <servlet-class>com.example.Ch1Servlet</servlet-class>
    </servlet>
    <servlet-mapping>
      <servlet-name>Chapter1 Servlet</servlet-name>
      <url-pattern>/Serv1</url-pattern>
    </servlet-mapping>
</web-app>

have a try and see. I believe your problem is with the package.


text:
Q: R lubridate interval class for labeling axis This is my "old" method of creating a label vector for labeling the axis of a plot.
require(lubridate)
require(dplyr)

#old
version <- "201710"
endDate = as.Date(paste0(version,"01"), "%Y%m%d")
startDateString = paste0(as.integer(substr(version, 1, 4)) - 3,substr(version, 5, 6))
startDate = as.Date(paste0(startDateString,"01"), "%Y%m%d")
datehv <- format(seq(startDate, endDate, "3 months"), "%Y-%m")

zeitbereich = c()
for(i in 1:(length(datehv)-1)) {
  zeitbereich = c(zeitbereich, datehv[i], "", "")
}
  zeitbereich = c(zeitbereich, datehv[length(datehv)])
labels <- substr(zeitbereich,1,7)

Below is the new version. The idea is to use lubridate and dplyr for better readability and a simpler syntax
#new
version2 <- "201710"
endDate2 = ymd(paste0(version,"01"))
startDate2 = endDate2 - dyears(3)
zeitbereich2 <- interval(startDate2, endDate2)

How can I get the vector "labels" as in the old code to be generated from the new time interval?
a) ignoring the "" spots in the labels vector of #old
b) incorporating empty "" in the labels vector

A: I would keep dates as dates.  Use the seq.Date function to add quarterly information, then change the format at the end.
I wouldn't change your loop, from what I can see it's the best solution for adding blanks, that said, I would assess why you need these blanks, there's probably a better way that doesn't require them.
st <- as.Date("20140101", "%Y%m%d")
en <- as.Date("20170101", "%Y%m%d")

quarters <- seq.Date(from = st, to = en, "quarter")

readable <- format(quarters, as.character("%Y-%m"))

zeitbereich = c()
for(i in 1:(length(readable)-1)) {
  zeitbereich = c(zeitbereich, readable[i], "", "")
}
zeitbereich = c(zeitbereich, readable[length(readable)])

A: So in the end I did.
df2 <- data.frame(
  date = seq(Sys.Date(), len=100, by="1 day")[sample(100, 50)],
  price = runif(50)
)
df2 <- df2[order(df$date), ]

st2 <- ymd("19960101")
en2 <- ymd("20000201")
months2 <- seq.Date(from = st2, to = en2, by = "month")

mutate(df2, date=months2)

b <- ggplot(df, aes(x=date, y=price)) + geom_line()
b + scale_x_date(date_breaks = "2 months")

The datecolumn needs to be date class for scale_x_date to work. But like that it is possible to set the date brekas to whatever needed ("3 years" for example).


text:
Q: Match column names with records in text file Using UFT/QTP I have this table of info in text file:
CurrentOdometerReading PreviousOdometerReading GallonsOfGas GasPrice  MPG     TotalCost
500                    200                     15           2.55      20      $38.25
600                    350                     18           2.55      13.89   $45.90
700                    510                     17           2.55      11.18   $43.35
800                    443                     9            2.55      39.67   $22.95
950                    801                     8            2.55      18.63   $20.40
10000                  8043                    99           2.55      19.77   $252.45
11000                  5004                    150          2.55      39.97   $382.50

The first line actually contains the column names.The next lines represent the data matching to the column name. I am having really hard time to print(loop) this data in below manner in UFT/QTP:

*

*CurrentOdometerReading = 500

*PreviousOdometerReading = 200

*Gallons = 15

*GasPrice = 2.55

*MPG = 20

*TotalCost = 38.25

If anyone had similar experience, I would REALLY appreciate your opinions.
So far I wrote this:
Set Fso=createobject ("scripting.filesystemobject")

set txtfile=fso.OpenTextFile filepath

var1=txtfile.ReadAll

var1=split(var1,vblf)
numarray= ubound(var1)
 For i = 0 To numarray

content=split(var1(i)," ")
numlinearr=ubound(content)

print content(i)

'For Iterator = 1 To numlinearr
'bol=split(content(Iterator)," ")
'print content(i)&" = "& bol(Iterator)

'Next
next

A: Seems you have a nice beginning. Though what you miss is an specific array for your data definition. And it's better not to keep the same variable name for different uses(as you do with Var1)
Something like :
fileFull = txtFile.ReadAll
fileLines = Split(fileFull, vblf)
fileDataNames = Split(fileLines(0), " ")
numArray = UBound(fileLines)
numData = UBound(fileDataNames)

For LineNumber = 1 To numArray
    content = ""
    localDatas = Split(fileLines, " ")
    For dataNumber = 0 to numData
        content = content & fileDataNames(dataNumber) & " = " & localDatas(dataNumber)
    Next
    Print content
Next

The base idea is to store the first line elsewhere, as you're going to use it several times. That's why the first loop starts from 1, and not from 0(the base for any tabled created by the split function) : the line zero is something else.


text:
Q: LEFT JOIN Excel VBA ADODB not working I am trying to merge the data from two worsheets in in one workbook.
I have succesfully queried the data into two diffrent recordsets like so:
SELECT F1,F5,F12,F13,F37,F38 FROM [KAP$] WHERE F8 LIKE 'klima'

and
SELECT F1, F2, F3, F4, F5, F6, F7, F8 FROM [Klima$A3:H899] WHERE F1 IS NOT NULL

Unfortunatly I have not found a way to "merge" the two recordsets.
However I noticed that the better way to archieve this would be to just query the two sheets at once using a left join. However I just can't get the syntax right. My last try was this:
SELECT
[KAP$].F1,
[KAP$].F5,
[KAP$].F12,
[KAP$].F13,
[KAP$].F37,
[KAP$].F38,
[Klima$].F1,
[Klima$].F2,
[Klima$].F3,
[Klima$].F4,
[Klima$].F5,
[Klima$].F6,
[Klima$].F7,
[Klima$].F8
FROM [KAP$] WHERE [KAP$].F8 LIKE 'Klima' LEFT JOIN [Klima$A3:H899] ON [KAP$].F1=[Klima$].F1

But as I have noticed there is more than one thing wrong with it... Any help is apreciated, I have been looking for a proper excel vba adodb guide for hours without success....
Thank you!
Edit: Here is some sample data:
KAP:
ID1  Info1  Info2  KAPinfo1  KAPinfo2  KAPinfo3
ID2  Info1  Info2  KAPinfo1  KAPinfo2  KAPinfo3
ID3  Info1  Info2  KAPinfo1  KAPinfo2  KAPinfo3
ID4  Info1  Info2  KAPinfo1  KAPinfo2  KAPinfo3
ID5  Info1  Info2  KAPinfo1  KAPinfo2  KAPinfo3
ID6  Info1  Info2  KAPinfo1  KAPinfo2  KAPinfo3

Klima:
ID1 Info1  Info2  Klima3  Klima4  Klima5  Klima6  Klima7  Klima8
ID2 Info1  Info2  Klima3  Klima4  Klima5  Klima6  Klima7  Klima8
ID3 Info1  Info2  Klima3  Klima4  Klima5  Klima6  Klima7  Klima8
ID6 Info1  -  -   Klima3  Klima4  Klima5  Klima6  Klima7  Klima8

The merged tables should look like this:
ID1 Info1  Info2  Klima3  Klima4  Klima5  Klima6  Klima7  Klima8  KAPinfo1  KAPinfo2  KAPinfo3
ID2 Info1  Info2  Klima3  Klima4  Klima5  Klima6  Klima7  Klima8  KAPinfo1  KAPinfo2  KAPinfo3
ID3 Info1  Info2  Klima3  Klima4  Klima5  Klima6  Klima7  Klima8  KAPinfo1  KAPinfo2  KAPinfo3
ID4 Info1  Info2  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  KAPinfo1  KAPinfo2  KAPinfo3
ID5 Info1  Info2  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  KAPinfo1  KAPinfo2  KAPinfo3
ID6 Info1  Info2  Klima3  Klima4  Klima5  Klima6  Klima7  Klima8  KAPinfo1  KAPinfo2  KAPinfo3

Basically I want to overwrite the columns Info1 and Info2 in the right table (Klima) with the information from the left table (KAP) while keeping extra columns in the right table (Klima)

A: if you need  a left join  the sintax for join should be :
SELECT
[KAP$].F1,
[KAP$].F5,
[KAP$].F12,
[KAP$].F13,
[KAP$].F37,
[KAP$].F38,
[Klima$A3:H899].F1,
[Klima$A3:H899].F2,
[Klima$A3:H899].F3,
[Klima$A3:H899].F4,
[Klima$A3:H899].F5,
[Klima$A3:H899].F6,
[Klima$A3:H899].F7,
[Klima$A3:H899].F8
FROM [KAP$]
LEFT JOIN [Klima$A3:H899]   ON ([KAP$].F1=[Klima$A3:H899].F1)
WHERE   [KAP$].F8 LIKE 'Klima%'

assuming that [Klima$A3:H899] is a valid  table  or equivalent

A: Try this query:
SELECT [KAP$].F1,
       [KAP$].F5,
       [KAP$].F12,
       [KAP$].F13,
       [KAP$].F37,
       [KAP$].F38,
       [Klima$].F1,
       [Klima$].F2,
       [Klima$].F3,
       [Klima$].F4,
       [Klima$].F5,
       [Klima$].F6,
       [Klima$].F7,
       [Klima$].F8
FROM
    (SELECT F1,F5,F12,F13,F37,F38 FROM [KAP$] WHERE F8 LIKE 'klima') AS [KAP$]
LEFT JOIN
    (SELECT F1, F2, F3, F4, F5, F6, F7, F8 FROM [Klima$A3:H899] WHERE F1 IS NOT NULL) AS [Klima$]
ON [KAP$].F1 = [Klima$].F1


text:
Q: Is the DWG graphics file format a bitmap or vector? Is the DWG graphics file format a bitmap format or a vector format?  Or can it be either?
DWG wikipedia article

A: DWG is a cad file extension and contains the data to mathematically describe the object(s) being modeled.
Cad programs use the data contained in the DWG file to dynamically generate different views (images) of the model.  DWG files by themselves are neither bitmap or vector images.

A: It's not really an image file.  It stores information about CAD models.  See this page to learn about the complicated interior:
http://libdwg.sourceforge.net/en/index.html

A: I'll restate what has already been written below, in layman's terms:
DWG stores 3D geometry, not images. Geometry is described in terms of points, lines, polygons, etc.
While a 2D vector image can also be described in terms of points, lines and polygons (aka "shapes"), a file format for 3D geometry is never used for storing 2D vector images.
As for bitmaps, they are a completely different kettle of fish and DWG is definitely not related to that.
Thanks for the suggestion to put this in an answer, Rob!


text:
Q: Kubernetes spark-submit on ADLS Gen2 error: Class org.apache.hadoop.fs.azurebfs.SecureAzureBlobFileSystem not found I am trying to submit a Pyspark job on ADLS Gen2 to Azure-Kubernetes-Services (AKS) and get the following exception:
Exception in thread "main" java.lang.RuntimeException: java.lang.ClassNotFoundException: Class org.apache.hadoop.fs.azurebfs.SecureAzureBlobFileSystem not found
    at org.apache.hadoop.conf.Configuration.getClass(Configuration.java:2595)
    at org.apache.hadoop.fs.FileSystem.getFileSystemClass(FileSystem.java:3269)
    at org.apache.hadoop.fs.FileSystem.createFileSystem(FileSystem.java:3301)
    at org.apache.hadoop.fs.FileSystem.access$200(FileSystem.java:124)
    at org.apache.hadoop.fs.FileSystem$Cache.getInternal(FileSystem.java:3352)
    at org.apache.hadoop.fs.FileSystem$Cache.get(FileSystem.java:3320)
    at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:479)
    at org.apache.spark.deploy.DependencyUtils$.resolveGlobPath(DependencyUtils.scala:191)
    at org.apache.spark.deploy.DependencyUtils$.$anonfun$resolveGlobPaths$2(DependencyUtils.scala:147)
    at org.apache.spark.deploy.DependencyUtils$.$anonfun$resolveGlobPaths$2$adapted(DependencyUtils.scala:145)
    at scala.collection.TraversableLike.$anonfun$flatMap$1(TraversableLike.scala:245)
    at scala.collection.IndexedSeqOptimized.foreach(IndexedSeqOptimized.scala:36)
    at scala.collection.IndexedSeqOptimized.foreach$(IndexedSeqOptimized.scala:33)
    at scala.collection.mutable.WrappedArray.foreach(WrappedArray.scala:38)
    at scala.collection.TraversableLike.flatMap(TraversableLike.scala:245)
    at scala.collection.TraversableLike.flatMap$(TraversableLike.scala:242)
    at scala.collection.AbstractTraversable.flatMap(Traversable.scala:108)
    at org.apache.spark.deploy.DependencyUtils$.resolveGlobPaths(DependencyUtils.scala:145)
    at org.apache.spark.deploy.SparkSubmit.$anonfun$prepareSubmitEnvironment$6(SparkSubmit.scala:365)
    at scala.Option.map(Option.scala:230)
    at org.apache.spark.deploy.SparkSubmit.prepareSubmitEnvironment(SparkSubmit.scala:365)
    at org.apache.spark.deploy.SparkSubmit.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:894)
    at org.apache.spark.deploy.SparkSubmit.doRunMain$1(SparkSubmit.scala:180)
    at org.apache.spark.deploy.SparkSubmit.submit(SparkSubmit.scala:203)
    at org.apache.spark.deploy.SparkSubmit.doSubmit(SparkSubmit.scala:90)
    at org.apache.spark.deploy.SparkSubmit$$anon$2.doSubmit(SparkSubmit.scala:1030)
    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:1039)
    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
    Caused by: java.lang.ClassNotFoundException: Class org.apache.hadoop.fs.azurebfs.SecureAzureBlobFileSystem not found
    at org.apache.hadoop.conf.Configuration.getClassByName(Configuration.java:2499)
    at org.apache.hadoop.conf.Configuration.getClass(Configuration.java:2593)
    ... 27 more

My spark-submit looks like this:
$SPARK_HOME/bin/spark-submit \
--master k8s://https://XXX \
--deploy-mode cluster \
--name spark-pi \
--conf spark.kubernetes.file.upload.path=file:///tmp \
--conf spark.kubernetes.authenticate.driver.serviceAccountName=spark \
--conf spark.executor.instances=2 \
--conf spark.kubernetes.container.image=XXX \
--conf spark.hadoop.fs.azure.account.auth.type.XXX.dfs.core.windows.net=SharedKey \
--conf spark.hadoop.fs.azure.account.key.XXX.dfs.core.windows.net=XXX \
--py-files abfss://data@XXX.dfs.core.windows.net/py-files/ml_pipeline-0.0.1-py3.8.egg \
abfss://data@XXX.dfs.core.windows.net/py-files/main_kubernetes.py

The job runs just fine on my VM and also loads data from ADLS Gen2 without problems.
In this post java.lang.ClassNotFoundException: Class org.apache.hadoop.fs.azurebfs.SecureAzureBlobFileSystem not found it is recommended to download the package and add it to the spark/jars folder. But I don't know where to download it and why it has to be included in the first place, if it works fine locally.
EDIT:
So I managed to include the jars in the Docker container. And if I ssh into that container and run the Job it works fine and loads the files from the ADLS.
But if I submit the job to Kubernetes it throws the same exception as before.
Please, can someone help?
Spark 3.1.1, Python 3.8.5, Ubuntu 18.04

A: So I managed to fix my problem. It is definitely a workaround but it works.
I modified the PySpark Docker container by changing the entrypoint to:
ENTRYPOINT [ "/opt/entrypoint.sh" ]

Now I was able to run the container without it exiting immediately:
docker run -td <docker_image_id>

And could ssh into it:
docker exec -it <docker_container_id> /bin/bash

At this point I could submit the spark job inside the container with the --package flag:
$SPARK_HOME/bin/spark-submit \
  --master local[*] \
  --deploy-mode client \
  --name spark-python \
  --packages org.apache.hadoop:hadoop-azure:3.2.0 \
  --conf spark.hadoop.fs.azure.account.auth.type.user.dfs.core.windows.net=SharedKey \
  --conf spark.hadoop.fs.azure.account.key.user.dfs.core.windows.net=xxx \
  --files "abfss://data@user.dfs.core.windows.net/config.yml" \
  --py-files "abfss://data@user.dfs.core.windows.net/jobs.zip" \
  "abfss://data@user.dfs.core.windows.net/main.py"

Spark then downloaded the required dependencies and saved them under /root/.ivy2 in the container and executed the job succesfully.
I copied the whole folder from the container onto the host machine:
sudo docker cp <docker_container_id>:/root/.ivy2/ /opt/spark/.ivy2/

And modified the Dockerfile again to copy the folder into the image:
COPY .ivy2 /root/.ivy2

Finally I could submit the job to Kubernetes with this newly build image and everything runs as expected.


text:
Q: Call mock methods instead of the library ones I am using a C library called BFciLib.h which has only definitions of methods that look
like this one:
 tCIRC  CiVFGopen(
        tCIU32          devNdx,     //!< from CiSysVFGinfo()
        tCIU32          modeFlags,  //!< access mode flags
        tCIp            *cip        //!< access token
        );

This method (and others) is called from the methods of a class that i implemented called FGrabber, something like this:
 EXIT_ON_ERROR(CiVFGopen(deviceIndex, tCIboardOpenEnums::kCIBO_exclusiveWrAccess, &interface));

I have mocked CiVFGopen method to do what i want it to do (created a C wrapper and calling my implemented behavior) but i have no idea how to link it in my FGrabber class.
tCIRC CiVFGopen(tCIU32 devNdx, tCIU32 modeFlags, tCIp *interface)
{
       std::cout<<"entered the mock method";
       return tCIerrorCode::kCIEnoErr;
}

Because of this, i am getting an error: multiple definition of CiVFGopen
I am not allowed to edit FGrabber, it has to stay with its production form, and just find a way to link my mock method to be used instead of the original one.
I have found namespaces, but i do not think this is what i need, since it will require me to modify FGrabber class is it not?

A: I didn't understand exactly what you want to do, but the error exists probably because you don't use the inline on the function definitions.
Try:
inline tCIRC  CiVFGopen(
        tCIU32          devNdx,     //!< from CiSysVFGinfo()
        tCIU32          modeFlags,  //!< access mode flags
        tCIp            *cip        //!< access token
        );


text:
Q: How can I make new line string of Props used in react? I'm having trouble with new line breaks in strings.
parent
<SampleComponent title="One \n Two \n Three">

children
type SampleComponentProps = {
  title: string;
};

export const SampleComponent: FC<SampleComponentProps> = ({
  title,
}) => {

  return (

{title}

  );
};

display
One \n Two \n Three

I would expect
One
Two
Three

A: The following code should work
return ({title.split("\\n").map((line, index) => (
    <React.Fragment key={index}>
      {line}

    </React.Fragment>
  ))})

A: You can solve this problem by setting HTML directly from React, just using html and css, no using JS regex, or convert string to array then output.

this is the result

Reference link: dangerously set innerHTML


text:
Q: How to correctly add new line to the file when multiple lines are added in parallel? I have to fill file with thousands of new lines, which i do with a simple command:
echo line1 >> allLines &
echo line2 >> allLines &
echo line3 >> allLines &
echo line4 >> allLines &

With an output:
cat allLines
line1
line2
line3
line4

However, rarely but regularly error slips in, where new line is concatenated to an existing one, producing a following output:
cat allLines
line1
line2line3
line4

How to avoid such error?

A: I simply put all files in one folder and stacked them without parallelisation


text:
Q: How do I submit the data of a form to an external url in Fancybox? I have a form like this;
<form action="https://www.exampleurl.com" method="post" id="postForm">
    @Html.HiddenFor(x => x.hiddenField)
    <button type="submit" id="btnSubmit">Submit</button>
</form>

This url "https://www.exampleurl.com" only allow POST..
When I click the btnSubmit I want to show datas on fancybox (http://fancyapps.com/fancybox/) which datas return from "https://www.exampleurl.com"..
I try a lot of things and I get this error; "localhost is not allowed by Access-Control-Allow-Origin."

A: You've got a two-part issue here:
1) Since you're doing a form post, IF the form submitted correctly the user would be directed away from your site to https://www.exampleurl.com. You'd never catch the response, because the user will now be on whatever page is served by exmapleurl.com. If you'd like to be able to catch the response and keep the user on your site, you should use $.post to post data via ajax.
2) Many sites will not allow cross-domain posts for security reasons, hence the Access-Control error you're getting. If you either control the destination site or are working with an administrator there, you can ask them to update the access control policy on the web server to allow posts from your domain. If you have no ability to influence the other site's policy, then you're not going to be able to do what you're attempting no matter what.


text:
Q: Why restart-computer command takes longer than timeout value when restarting remote computers? I am using following PowerShell command to restart a remote  computer Restart-Computer -ComputerName Host123 -Force -Wait -Timeout 300. Even though I specify 5 min timeout it takes 13-15min for timeout to occur.
Can someone please explain why PowerShell won't respect timeout in this case and how can I achieve the correct timeout?


text:
Q: Blinking LED effect using FillEllipse I want to use the FillEllipse & DrawEllipse function to act like a LED display. But I was not able to click on the button to disable the blinking again since the subroutine is still running. Any recommendation?
    bool alert = false;
    bool blink = false;

    private void blinking()
    {
        Graphics pb = pictureBox1.CreateGraphics();
        SolidBrush red = new SolidBrush(Color.Red);
        SolidBrush green = new SolidBrush(Color.LightGreen);
        while (blink == true)
        {
            pictureBox1.Refresh();
            if (alert == true)
            {
                pb.FillEllipse(red, 20, 20, 50, 50);
                alert = false;
            }
            else
            {
                //pb.FillEllipse(green, 20, 20, 50, 50);
                pb.DrawEllipse(Pens.Red, 20, 20, 50, 50);
                alert = true;
            }
            Thread.Sleep(timer1.Interval);
        }

    }

    private void blink_btn_Click(object sender, EventArgs e)
    {
        if (blink == false)
        {
            blink = true;
        }
        else
        {
            blink = false;
        }
        blinking();

    }

A: Besides that you are blocking the UI with your blinking() method, you're not drawing correctly anyway. You should only draw when handling a Paint event. Also, there's not really a good reason to use a PictureBox if all you're going to do is draw something yourself. Just put a Panel, or even make a custom control.
But, sticking with the "draw into the PictureBox" approach, this is what your code really ought to look like:
First, it looks like you already have a Timer attached to the form. Why you're not already using that is beyond me, but you should. Hook up a handler to the Tick event:
private void timer1_Tick(object sender, EventArgs e)
{
    alert = !alert;
    pictureBox1.Invalidate();
}

Add your handler for the PictureBox.Paint event:
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    Brush brush = alert ? Brushes.Red : Brushes.LightGreen;

    e.Graphics.FillEllipse(brush, 20, 20, 50, 50);
}

Finally, use your button Click handler to toggle the timer:
private void blink_btn_Click(object sender, EventArgs e)
{
    timer1.Enabled = !timer1.Enabled;
}

Add code as necessary to draw differently (the above just toggles between the red and green ellipse), to reset the appearance when the timer's not active, etc.


text:
Q: why is pymunk not letting me import it and saying "no module named "_cffi_backend"" i am making a hard version of atari breakout
so when i import pymunk because I wanted to make the ball then it will say "no module named "_cffi_backend"
i have asked people on Youtube and reddit but nobody answered the questions
i have tried uninstalling cffi and pymunk, downgrading python and more
can anybody fix this problem
(and also i use microsoft visual studio 2019 and pyglet and python 3.9)
https://i.stack.imgur.com/sBY1O.png

A: Can it be because of something fishy with Visual Studio? Otherwise I cant think of much..
To validate if Pymunk can work on your computer you can try to install a fresh Python and Pymunk through conda, which will give you a completely separate installation of Python.

*

*Download and install Miniforge: https://github.com/conda-forge/miniforge (If you get the option, dont set this new miniforge Python as your default Python)

*Open the miniforge command line prompt and run conda install pymunk

*When installed, run python -m pymunk.tests

*Add the output here :)

Secondly, you can try to run your project from the command line instead of from within VS.

*

*First you need to find out the folder where you have the files. In VS you can right-click on the file and use "Open Containing Folder" to go to the file in Explorer. You can also use "Copy full path" to copy the path.

*Next, open the command prompt (or Windows Terminal in case you have it installed).

*Navigate to the folder with the file. cd long-path-to-folder

*Run the "main" file, I guess its atari.py in your case, but Im not really sure.


text:
Q: Select Case Structure My question is the following, the following "Select Case", Range is between A1:A100. After I try the following code I only get one result for the 100 progress results I need.  Code Listed below:
Private Sub CommandButton1_Click()

Dim score As Integer, result As String
 score = Range("A1").Value

Select Case score
    Case Is >= 80
    result = "very good"
    Case Is >= 70
    result = "good"
    Case Is >= 60
    result = "sufficient"
    Case Else
    result = "insufficient"
End Select

    Range("B1").Value = result

End Sub

A: If you specify that you want to perform the same function on every cell in the range you've defined, you can do a FOR EACH loop like so:
Private Sub CommandButton1_Click()

Dim score As range, result As String
 set score = Range("A1:a100")

for each c in score.cells

Select Case c.value
    Case Is >= 80
    result = "very good"
    Case Is >= 70
    result = "good"
    Case Is >= 60
    result = "sufficient"
    Case Else
    result = "insufficient"
End Select

    c.offset(0,1) = result  'specifies the cell 1 column to the right of the current cell

next c
End Sub

A: This is what I'd do.  It's fairly strait forward using a For ... Next loop to cycle through the cells in the column A range listed and then placing the value from the Select Case statement in the cell adjacent in column B
Private Sub CommandButton1_Click()
    Dim score As Integer
    Dim result As String
    Dim xlCell As Range
        For Each xlCell In Range("A1:A100")
            score = xlCell
            Select Case score
                Case Is >= 80
                    result = "very good"
                Case 70 To 79
                    result = "good"
                Case 60 To 69
                    result = "sufficient"
                Case Is < 60
                    result = "insufficient"
            End Select
            xlCell.Offset(0, 1) = result
        Next xlCell
End Sub

A: I personally wouldn't use a loop here, it's much faster to do it this way than looping a cell at a time:
Sub CommandButton1_Click()
With Range("B1:B100")
    .Formula = "=IF(A1>79,""very good"",IF(A1>69,""good"",IF(A1>59,""sufficient"",""insufficient"")))"
    .Calculate
    .Copy
    .PasteSpecial xlPasteValues
End With
End Sub

It puts a formula in to calculate the results, then it forces a calculate (only needed if calculation is set to manual otherwise you can delete this line), then it copies and pastes back as values.
If this is for a school assignment and you have been told to use a loop or case statement then yes use the statements you were told but otherwise I would advise to avoid looping when you can.


text:
Q: How to check if "verify app" is enabled or disabled programmatically I've a security requirement to alert users if google's "verify app" is disabled on app launch. The problem is that I dont know any way to check whether "verify app" is disabled or not.
I tried to use the code below, but it's always returning 1.
        int verifierInt = -1;
        if (Build.VERSION.SDK_INT >= 17) {
            verifierInt = Settings.Global.getInt(context.getContentResolver(), "package_verifier_enable", -1);
        } else if (Build.VERSION.SDK_INT >= 14) {
            verifierInt = Settings.Secure.getInt(context.getContentResolver(), "verifier_enable", -1);
        } else {
            // No package verification option before API Level 14
        }
        boolean isVerifyAppEnabled = verifierInt == 1;

Also, as a requirement, want user to be navigated to the "verifiy app" settings if this feature is disabled.

A: You should check like this:
Settings.Global.getInt(context.getContentResolver(), "verifier_verify_adb_installs", -1);

A: Reading preferences, won't help anymore as android don't update preferences now. So basically reading preferences value for google Verify won't work.
Please use below SaftyNet callbacks to verify google protect.
SafetyNet.getClient(context)
                .isVerifyAppsEnabled()
                .addOnCompleteListener(new OnCompleteListener<SafetyNetApi.VerifyAppsUserResponse>() {
                    @Override
                    public void onComplete(@NonNull Task<SafetyNetApi.VerifyAppsUserResponse> task) {
---
}
});


text:
Q: ionic does not reflect the changes done in src folder I have an open source project : https://github.com/moodlehq/moodleapp
I have downloaded it and change images in asset and it reflect, but when I change in the lang files or colors it does not
I tried ionic build and ionic serve many times, but still does not work


text:
Q: Angular 2 import shared operator for Observable I am trying to use the shared operator for Observers but it doesnt works:
My ts code:
import { Injectable } from '@angular/core';
import { Observer } from 'rxjs/observer';
import { Observable } from 'rxjs/observable';
import 'rxjs/add/operator/share';

@Injectable()
export class LoadingService {
    private _observer: Observer<string>;
    loading$: Observable<string>;
    constructor() {
        this.loading$ = new Observable<string>(
            observer => this._observer = observer).share();
    }

    toggleLoadingIndicator(name) {
        if (this._observer) {
            this._observer.next(name);
        }
    }
}

When I invoke the .share(); I get the error: TypeError: (intermediate value).share is not a function.
In other case I importing successfully for example the map operator, and using normally like this:
import 'rxjs/add/operator/map';
this._http.get(this._url, {
    headers: this._headers
}).map(r => r.json()).subscribe(json => {
    console.log(json);
    this.isValid = true;
});

So, even if I try to use the map operator, to proof the import, in the first scenario this.loading$ = new Observable<string>(observer => this._observer = observer).map(n => n); I get the same error.

A: iuristona's answer works, but only because you're importing the entire library with:
import { Observable } from 'rxjs/Rx';

By importing from only the 'rxjs/Observable' module, you're only importing a few of the methods. Mobile users will appreciate only importing the methods you need rather than the entire library. You can do this with:
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/debounceTime';  // added method
import 'rxjs/add/operator/map';           // added method

Hope that helps.

A: So, I dont know why, but when I import from 'rxjs/Rx', it works:
import { Observable, Observer } from 'rxjs/Rx';


text: Q: function $f\notin L^{\infty}(\Omega)$, but $f\in L^p(\Omega)$ for all $1\le p <\infty$ I'm searching for a function $f\notin L^{\infty}(\Omega)$, but $f\in L^p(\Omega)$ for all $1\le p <\infty$. And it has to be $|\Omega |<\infty$. I tried $f(x)=\frac{1}{2\sqrt{x}}$ and $\Omega= (0,1)$ and something like that, but it is $f\notin L^p(\Omega)$ for all $1\le p <\infty$. Could you help me?


text:
Q: Is there a universal way to get the name of a component field? when I work with different plugins, I often want to change a specific value in a component from that plugin. And it is always a lengthy trial and error phase until I find out, how to address the value.
Example
Currently, I'm working with the Dreamteck Splines plugin.
One of the components is the Spline Positioner which has under the headline Tracing a expandable section called Motion in which is the headline Position which has the sub headline Offset and in it is the field "X" which I want to change.
So, I tried it with ...
GetComponent<SplinePositioner>().offset.x
GetComponent<SplinePositioner>().offsetX
GetComponent<SplinePositioner>().position.offset.x

and so on ... but everything is wrong.
In a perfect world, I could hover over any field in the inspector and a tooltip is shown with the way, I can address this specific field. But this isn't the perfect world ;)
So, how you deal with that, when you you don't find it in the documentation of the plugin?
Thank you!

A: I found it through the suggestion list of Visual Studio code after typing in GetComponent<SplinePositioner>(). First, this list felt a little generic, but after looking through it, entry for entry, I found my way. It was GetComponent<SplinePositioner>().motion.offset.x in the end.
Thank you @derHugo for getting me in the right direction :)


text:
Q: Rotate SCNText Node around center of itself (Swift - Scenekit) I am trying to rotate some 3D text in place. How do I rotate it around the center of itself, not the left edge? I've tried setting the text alignment to center and that didn't help either.
let titleText = SCNText(string: "My Title", extrusionDepth: 0.8)
let titleNode = SCNNode(geometry: titleText)

titleNode.position = SCNVector3(x: 0, y: 0, z: 0)
titleNode.runAction(SCNAction.rotateByX(0, y: 5, z: 0, duration: 2.5))
scene.rootNode.addChildNode(titleNode)

A: you can set the node's pivot property to half its width and height (see getBoundingBoxMin:max:)

A: Setup pivot of the SCNText is a bit tricky (look here for more details)
Bellow is the code to setup pivot and rotate the text:
let geoText = SCNText(string: "Hello", extrusionDepth: 1.0)
geoText.font = UIFont (name: "Arial", size: 8)
geoText.firstMaterial!.diffuse.contents = UIColor.red
let textNode = SCNNode(geometry: geoText)

let (minVec, maxVec) = textNode.boundingBox
textNode.pivot = SCNMatrix4MakeTranslation((maxVec.x - minVec.x) / 2 + minVec.x, (maxVec.y - minVec.y) / 2 + minVec.y, 0)
scnView.scene?.rootNode.addChildNode(textNode)

let loop = SCNAction.repeatForever(SCNAction.rotateBy(x: 0, y: 5, z: 0, duration: 2.5))
textNode.runAction(loop)


text:
Q: consecutive grouped ID list R If I have a df and want to do a grouped ID i would do:
df <- data.frame(id= rep(c(1,8,4), each = 3), score = runif(9))
df %>% group_by(id) %>% mutate(ID = cur_group_id())

following(How to create a consecutive group number answer of @Ronak Shah).
Now I have a list of those dfs and want to give consecutive group numbers, but they shall not start in every lists element new. In other words the ID column in listelement is 1 to 10, and in list two 11 to 15 and so on (so I can´t simply run the same code with lapply).
I guess I could do something like:
names(df)<-c("a", "b")
df<- mapply(cbind,df, "list"=names(df), SIMPLIFY=F)
df <- do.call(rbind, list)
df<-df %>% group_by(id) %>% mutate(ID = cur_group_id())
split(df, list)

but maybe some have more direct, clever ways?

A: A dplyr way could be using bind_rows as group_split (experimental):
library(dplyr)

df_list |>
  bind_rows(.id = "origin") |>
  mutate(ID = consecutive_id(id)) |> # If dplyr v.<1.1.0, use ID = cumsum(!duplicated(id))
  group_split(origin, .keep = FALSE)

Output:
[[1]]
# A tibble: 9 × 3
     id  score    ID
  <dbl>  <dbl> <int>
1     1 0.187      1
2     1 0.232      1
3     1 0.317      1
4     8 0.303      2
5     8 0.159      2
6     8 0.0400     2
7     4 0.219      3
8     4 0.811      3
9     4 0.526      3

[[2]]
# A tibble: 9 × 3
     id  score    ID
  <dbl>  <dbl> <int>
1     3 0.915      4
2     3 0.831      4
3     3 0.0458     4
4     5 0.456      5
5     5 0.265      5
6     5 0.305      5
7     2 0.507      6
8     2 0.181      6
9     2 0.760      6

Data:
set.seed(1234)

df1 <- tibble(id = rep(c(1,8,4), each = 3), score = runif(9))
df2 <- tibble(id = rep(c(3,5,2), each = 3), score = runif(9))

df_list <- list(df1, df2)

Or using cur_group_id() for the group number, this approach, however, gives another order than you expect in your question:
library(dplyr)

df_list |>
  bind_rows(.id = "origin") |>
  mutate(ID = cur_group_id(), .by = "id") |> # If dplyr v.<1.1.0, use group_by()-notation
  group_split(origin, .keep = FALSE)

Output:
[[1]]
# A tibble: 9 × 3
     id  score    ID
  <dbl>  <dbl> <int>
1     1 0.187      1
2     1 0.232      1
3     1 0.317      1
4     8 0.303      6
5     8 0.159      6
6     8 0.0400     6
7     4 0.219      4
8     4 0.811      4
9     4 0.526      4

[[2]]
# A tibble: 9 × 3
     id  score    ID
  <dbl>  <dbl> <int>
1     3 0.915      3
2     3 0.831      3
3     3 0.0458     3
4     5 0.456      5
5     5 0.265      5
6     5 0.305      5
7     2 0.507      2
8     2 0.181      2
9     2 0.760      2


text:
Q: How to set multiple items as selected in JList using setSelectedValue? I have a jList that is populated dynamically by adding to the underlying listModel. Now if I have three Strings whose value I know and I do
for(i=0;i<3;i++){
    jList.setSelectedValue(obj[i],true);//true is for shouldScroll or not
}

only the last item appears to be selected...If this can't be done and I have to set the selection from the underlying model how should I go about it???
Also please note the jList has selection mode:
  jList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

Thanks in Advance

A: jList.addSelectionInterval(0,2);

A: Note that all xxSelectedValue methods are convenience wrapper methods around the selectionModel (which supports index-based selection access only) on the JList. Setting multiple selections per value is not supported. If you really want it, you'll have to implement a convenience method yourself. Basically, you'll have to loop over the model's elements until you find the corresponding indices and call the index-based methods, something like:
public void setSelectedValues(JList list, Object... values) {
    list.clearSelection();
    for (Object value : values) {
        int index = getIndex(list.getModel(), value);
        if (index >=0) {
            list.addSelectionInterval(index, index);
        }
    }
    list.ensureIndexIsVisible(list.getSelectedIndex());
}

public int getIndex(ListModel model, Object value) {
    if (value == null) return -1;
    if (model instanceof DefaultListModel) {
        return ((DefaultListModel) model).indexOf(value);
    }
    for (int i = 0; i < model.getSize(); i++) {
        if (value.equals(model.getElementAt(i))) return i;
    }
    return -1;
}

A: Although StanislasV answer is perfectly valid, i would prefer to avoid adding one selection interval to another. Instead, you should prefer to call the JList associated ListSelectionModel#setSelectionInterval(int, int) method like this :
jList.getSelectionModel().setSelectionInterval(0, 3)

If you want your list selection to be disjoint, you'll moreover have to write your own ListSelectionModel.


text:
Q: EXTJS 6.5: External properties file with variables to use in Index.html I have an EXTJS6.5 application. I want to use variables in my index.html that come from a properties file. However the change of the values of these variables should not require a new build of the application.  This means that the variable can be changed if required (Without the need to build the extjs code).
Can someone please help with this?
I have already gone thru other threads where index.html can have placeholders, but do not seem to have a concrete example.
This is my properties file (Runtime.js)
{
    "appUrl": "http://myappurl.com",
    "appId": "10"
}

Then I want to use these variables in my index.html as such:

This is my index.html
<!DOCTYPE HTML>

    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=10, user-scalable=yes">
    <meta name="description" content="MyApp">

    <title>MyApp</title>

    <link rel="icon" type="image/png" href="myicon.png">
    <link rel="stylesheet" href="resources/dist/myapp-resources.min.css">

Will this work this way? Or pls suggest any better way to do this..thank you very much.

A: Given Runtime.js file has a syntax error. Is not valid javascript file.
Runtime.js should be:
window.appUrl="http://myappurl.com";
window.appId="10";

And you can use these variables like window.appUrl/window.appid in script block, not in html block.
You can do workaround to resolve the problem: You can generate includes from Runtime.js.
Example:
index.html
<!DOCTYPE HTML>

    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=10, user-scalable=yes">
    <meta name="description" content="MyApp">

    <title>MyApp</title>

    <link rel="icon" type="image/png" href="myicon.png">
    <link rel="stylesheet" href="resources/dist/myapp-resources.min.css">

Runtime.js
window.appUrl="http://myappurl.com";
window.appId="10";

var script = document.createElement("script")
script.type = "text/javascript";
script.src = window.appUrl+"/configuration/MyConstants.js";

var script2 = document.createElement("script")
script2.type = "text/javascript";
script2.src = window.appUrl+"/resources/mycharts/mycharts.js";

var script3 = document.createElement("script")
script3.type = "text/javascript";
script3.src = window.appUrl+"/resources/ckeditor/ckeditor.js";

document.getElementsByTagName("body")[document.getElementsByTagName("body").length-1].appendChild(script);
document.getElementsByTagName("body")[document.getElementsByTagName("body").length-1].appendChild(script2);
document.getElementsByTagName("body")[document.getElementsByTagName("body").length-1].appendChild(script3);

Updated 2019-07-17:
If you want to require script before application launches you must add reference to script in app.json in js block (Which can't be done because you want to personalize the source of scripts).
Second option is change in app.js you can do Ext.Loader.loadScript like:
Ext.Loader.loadScript({
    url: 'my.js',
    onLoad: function(){
        Ext.application({
            name: 'Fiddle',
            extend: 'Fiddle.Application',
            autoCreateViewPort: false
        });
    },
    onError: function(){
        console.log('error');
    }
});`


text:
Q: AngularJS Input type=date is not showing date on chrome for string value When Json object comes from Server, date is always stored as string.
We need to show that date value in Input box to allow Edit/Update of object. But
<Input type="date>

only understands date object (rightly so), henceforth, we need to convert date string to date object, after receiving json from AJAX call. There are couple of threads on SO, trying to achieve same, but I found accepted answers on those thread not working (not even plunker).
Convert AJAX date to Javascript date for use with ng-model
angularjs | date input not showing ng-model value

*

*I don't want to let go type="date" (don't want to loose dtPicker of mobile browsers).

*I don't want to write a line everywhere on controller, converting a date string value to date. Though it does work, but I will keep it as last resort.

I tried to solve my problem using directive, and created following directive.
I am trying to induce  date object via ngModel.$formatters. Console.log inside jsonStrToDate prints str as empty string.
It is not working, What is wrong with my directive here?) :-
.html
   <input type="date" name="dateOfReading" class="form-control" id ="dateOfReading"
    ng-model="bpReport.dateOfReading"
    json-string-to-date
    min="1970-01-01" max="2099-12-31"  required />
.js
    window.angular.module('myApp.directives', [])
      .directive('jsonStringToDate', function(){
    return {
            restrict: 'A',
            require: 'ngModel',
            link: function(scope, element, attr, ngModel) {
              console.log('directive linking called');
              function jsonStrToDate(str) {
                console.log('input str value' + str + ', and typeof is ' + typeof str);
                var d= new Date(str);
                console.log(d);
                return d;
              }
              ngModel.$formatters.push(jsonStrToDate);
              ngModel.$parsers.push(function(value) {
                console.log("value from parser method:- "+ value);
                return value;
              });

            }
          };
        });

Right now I am using AngularJS 1.3.0 RC1
Version 1.2.20 also had same issue.


text:
Q: Função que retorne a resolução da tela Preciso de uma função Java que retorne a resolução do meu dispositivo Android.

A: Pode usar desta forma à partir da API 13:
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;

Coloquei no GitHub para referência futura.
Para as versões anteriores:
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height = displaymetrics.heightPixels;
int wwidth = displaymetrics.widthPixels;

Coloquei no GitHub para referência futura.
Você precisa estar em uma Activity para usar desta forma, mas provavelmente está. Se não estiver o código precisará ser mudado para pegar o contexto.

A: Você pode utilizar o DisplayMetrics:
DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
int height = displayMetrics.heightPixels;
int widht = displayMetrics.widthPixels;

Nota: o heightPixels retorna o tamanho total de sua tela junto com sua status bar. Caso você queira ignorar o tamanho da status bar (útil para operações de animações etc), você simplesmente:
public int getStatusBarHeight() {
    int result = 0;
    int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
    if (resourceId > 0) {
        result = getResources().getDimensionPixelSize(resourceId);
    }
    return result;
}


text:
Q: Haskell finding mean of cubes of odd members Any ideas? Please find the mean of cubes of odd members of given list of Int type.
Try to use  (.), ($), map, filter or foldl (You should use at least one of them).

A: I would give you some hints to get you started up:

*

*Use filter function to get the odd members of the given list.

*Cube the resultant list using map function.

*Find the mean of them by summing the list and dividing it by the length of the list.

A: The only thing I would add to the other comments and answers is the use of fromIntegral to convert the Int type to Fractional for using the (/) operator.