text:
Q: Native module in React Native: function returns "undefined" So, I am practicing making native modules in Java that can have functions exposed to the JavaScript code of React Native. For that, I decided to go for a simple demo math library. My code is as follows.
MathOpsModule.java
package com.mb_rn_poc;

import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;

public class MathOpsModule extends ReactContextBaseJavaModule {

  @Override
  public String getName() {
    return "MathOps"; // Name of the Native Modules.
  }

  @ReactMethod
  public int add(int a, int b) {
    return (a + b);
  }
}

MathOpsPackage.java
package com.mb_rn_poc;

import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class MathOpsPackage implements ReactPackage {

@Override
public List<ViewManager> createViewManagers(
  ReactApplicationContext reactContext
) {
    return Collections.emptyList();
}

@Override
public List<NativeModule> createNativeModules(
      ReactApplicationContext reactContext
) {
    List<NativeModule> modules = new ArrayList<>();
    // Register the MathOps module
    modules.add(new MathOpsModule());
    return modules;
  }
}

MainApplication.java
package com.mb_rn_poc;

import android.app.Application;
import android.content.Context;
import com.facebook.react.PackageList;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.soloader.SoLoader;
import java.lang.reflect.InvocationTargetException;
import java.util.List;

public class MainApplication extends Application implements ReactApplication {

  private final ReactNativeHost mReactNativeHost =
      new ReactNativeHost(this) {
        @Override
        public boolean getUseDeveloperSupport() {
          return BuildConfig.DEBUG;
        }

        @Override
        protected List<ReactPackage> getPackages() {
          @SuppressWarnings("UnnecessaryLocalVariable")
          List<ReactPackage> packages = new PackageList(this).getPackages();
          // Packages that cannot be autolinked yet can be added manually here, for example:
          // packages.add(new MyReactNativePackage());
          packages.add(new MathOpsPackage());
          return packages;
        }

        @Override
        protected String getJSMainModuleName() {
          return "index";
        }
      };

  @Override
  public ReactNativeHost getReactNativeHost() {
    return mReactNativeHost;
  }

  @Override
  public void onCreate() {
    super.onCreate();
    SoLoader.init(this, /* native exopackage */ false);
    initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
  }

  /**
   * Loads Flipper in React Native templates. Call this in the onCreate method with something like
   * initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
   *
   * @param context
   * @param reactInstanceManager
   */
  private static void initializeFlipper(
      Context context, ReactInstanceManager reactInstanceManager) {
    if (BuildConfig.DEBUG) {
      try {
        /*
         We use reflection here to pick up the class that initializes Flipper,
        since Flipper library is not available in release mode
        */
        Class<?> aClass = Class.forName("com.mb_rn_poc.ReactNativeFlipper");
        aClass
            .getMethod("initializeFlipper", Context.class, ReactInstanceManager.class)
            .invoke(null, context, reactInstanceManager);
      } catch (ClassNotFoundException e) {
        e.printStackTrace();
      } catch (NoSuchMethodException e) {
        e.printStackTrace();
      } catch (IllegalAccessException e) {
        e.printStackTrace();
      } catch (InvocationTargetException e) {
        e.printStackTrace();
      }
    }
  }
}

Now, on the React Native side of things, I have these two files -
MathOps.js
import { NativeModules } from 'react-native';

const MathOps = NativeModules.MathOps;

export const add = (a, b) => {
    return MathOps.add(a, b);
}

MainApp.js
import React, { useEffect, useState } from 'react';
import { SafeAreaView, Text, View } from 'react-native';
import { add } from "./NativeWrapper/MathOps";

const MainApp = () => {

    const [state, setState] = useState(0);

    useEffect(() => {
        let sum = add(10, 12);
        console.log({ sum });
        setState(sum);

    }, [])

    return (
        <SafeAreaView>
            <View>
                <Text>
                    {state}
                </Text>
            </View>
        </SafeAreaView>
    );
}

export default MainApp;

The problem is, the add function is returning undefined. As such, nothing gets printed on the screen. Any idea what I might be doing wrong?

A: Calls to native methods are asynchronous, so they cannot return values directly.
You can either use a callback (as you figured out yourself), or a Promise to allow for the more elegant async / await syntax (and more):
@ReactMethod
public void add(Double a, Double b, Promise promise) {
    Double sum = a + b;
    promise.resolve(sum);
}

import { NativeModules } from 'react-native';

const { MathOps } = NativeModules;

export const add = async (a, b) => {
    return await MathOps.add(a, b);
}

A: Not sure what the issue with this is, but there is a workaround - using Callbacks, as described in https://reactnative.dev/docs/native-modules-android. I made the following modifications -
@ReactMethod
public void add(Double a, Double b, Callback cb) {
    Double sum = a + b;
    cb.invoke(sum);
}

import { /* ... */ NativeModules } from 'react-native';
const { MathModule } = NativeModules;

// ...
// ...

MathModule.add(10, 20, (sum) => {
    alert(sum);
})

And it does what I expect it to - alerts "30".

A: React Native bridge is asynchronous. We can pass data from Native Side to Javascript in following ways:-
1) Promise: When the last parameter of a native module Java/Kotlin method is a Promise, its corresponding JS method will return a JS Promise object.
In Module.java->
@ReactMethod
public void add(Double a, Double b, Promise promise) {
        Double sum = a + b;
        promise.resolve(sum);
}

This is how you will then access in Javascript->
import { NativeModules } from 'react-native';
const { MathOps } = NativeModules;

export const add = async (a, b) => {
    return await MathOps.add(a, b);
}

2. Callback: They can also be used to asynchronously execute JavaScript from the native side.
In Module.java->
@ReactMethod
public void add(Double a, Double b, Callback cb) {
        Double sum = a + b;
        cb.invoke(sum);
}

This is how you will then access in Javascript->
import { NativeModules } from 'react-native';
const { MathOps } = NativeModules;

useEffect(() => {
  MathOps.add(10, 12, (sum) => {
    setState(sum);
  });
}, [])

3. isBlockingSynchronousMethod (Not Recommended due to performance penalties and threading-related bugs to your native modules): You can pass isBlockingSynchronousMethod = true to a native method to mark it as a synchronous method.
@ReactMethod(isBlockingSynchronousMethod = true)
public Double add(Double a, Double b){
    Double sum = a + b;
    return sum;
}

In js file:
import { NativeModules } from 'react-native';
const { MathOps } = NativeModules;

export const add = async (a, b) => {
    return await MathOps.add(a, b);
}

4. Emitting Events: haven't explored it much.


text:
Q: Combination of Canvas.TransparentColor and Canvas.Draw with Opacity i want to draw a bitmap on a canvas with opacity where the bitmap has a transparent color.

*

*i could create a bitmap with transparent color and draw it to a

*canvas i could create a bitmap and draw it to a canvas with opacity

but i couldn't combine it. if i combine it the opacity is ignored.
here is the code i wrote:
procedure TForm1.FormPaint(Sender: TObject);
var b1,b2:TBitmap;
begin
  // Example how it opacity works:
  b1 := TBitmap.Create;
  b1.SetSize(20,20);
  b1.Canvas.Brush.Color := clBlue;
  b1.Canvas.Rectangle(0,0,20,20);
  Canvas.Draw(10,10,b1,$ff);  // Works
  Canvas.Draw(40,10,b1,$66);  // Works

  // I need it in combination with TransparentColor:
  b2 := TBitmap.Create;
  // next 3 lines are different from above
  b2.Transparent := true;
  b2.TransparentColor := clFuchsia;
  b2.Canvas.Brush.Color := clFuchsia;
  b2.SetSize(20,20);
  b2.Canvas.Brush.Color := clBlue;
  b2.Canvas.Ellipse(0,0,20,20);
  Canvas.Draw(10,40,b2,$ff);  // Works (full opacity)
  Canvas.Draw(40,40,b2,$66);  // Ignores the $66 Opacity

  b1.Free;
  b2.Free;
end;

produces:

how could i draw (f.e. a blue circle) with transparent background and just 40% opacity?
i would prefere a solution without direct winapi (like bitblt, ...) if possible.
i tried a few hacks like bitshifting a alpha channel to a TColor value but it didn't work.
here i what i tried:
procedure TForm1.FormPaint(Sender: TObject);
var b:TBitmap;
begin
  b := TBitmap.Create;
  b.PixelFormat := pf32bit;
  b.AlphaFormat := afDefined;

  b.Canvas.Brush.Color := 0 and ($ff shl 32);  // Background Transperency
  b.SetSize(20,20);
  b.Canvas.Brush.Color := clBlue + (($ff-$66) shl 32);
  b.Canvas.Ellipse(0,0,20,20);
  Canvas.Draw(10,10,b);

  b.Free;
end;

produces:

thanks in advance!
EDIT: my system: delphi xe 5 on windows 7 64bit (but using the 32bit compiler)

A: What happens can be seen in procedure TBitmap.DrawTransparent in the unit Graphics.
If the property of the image is set to transparent as show for b2 in your example the Bitmap will be drawn with
Graphics.TransparentStretchBlt which is using StretchBlt with differnt masks to draw the image and is not able to use the alpha channel.
A not tranparent Bitmap , your b1, will be draw with
AlphaBlend.
To reach your goal you might use another bitmap b2, set the Alphachannel to 0, paint b2 with opacity $66 on b3, set set the Alphachannel to 255 for every pixel which is clFuchsia in b2 and then paint this bitmap with the desired opacity

type
  pRGBQuadArray = ^TRGBQuadArray;
  TRGBQuadArray = ARRAY [0 .. 0] OF TRGBQuad;
  TRefChanel=(rcBlue,rcRed,rcGreen);

procedure SetBitmapAlpha(ABitmap: TBitMap; Alpha: Byte);
var
  pscanLine32: pRGBQuadArray;
  nScanLineCount, nPixelCount : Integer;
begin
  with ABitmap do
  begin
    PixelFormat := pf32Bit;
    HandleType := bmDIB;
    ignorepalette := true;
    alphaformat := afDefined;
    for nScanLineCount := 0 to Height - 1 do
    begin
      pscanLine32 := Scanline[nScanLineCount];
      for nPixelCount := 0 to Width - 1 do
        with pscanLine32[nPixelCount] do
         begin
          rgbReserved := Alpha;
        end;
    end;
  end;
end;

procedure AdaptBitmapAlpha(ABitmap,TranspBitmap:TBitmap);
var
  pscanLine32,pscanLine32_2: pRGBQuadArray;
  nScanLineCount, nPixelCount : Integer;
begin
  with ABitmap do
  begin
    PixelFormat := pf32Bit;
    HandleType := bmDIB;
    ignorepalette := true;
    alphaformat := afDefined;
    for nScanLineCount := 0 to Height - 1 do
    begin
      pscanLine32 := Scanline[nScanLineCount];
      pscanLine32_2 := TranspBitmap.Scanline[nScanLineCount];
      for nPixelCount := 0 to Width - 1 do
        with pscanLine32[nPixelCount] do
         begin
          // all picels with are not clFuchsia in the transparent bitmap
          if NOT ((pscanLine32_2[nPixelCount].rgbBlue=255) AND (pscanLine32_2[nPixelCount].rgbRed=255) AND (pscanLine32_2[nPixelCount].rgbGreen=0)  ) then
             begin
             rgbReserved := 255;
             end
          else
             begin
               rgbBlue := 0;
               rgbRed := 0;
               rgbGreen := 0;
             end;
        end;
    end;
  end;
end;

procedure TAForm.FormPaint(Sender: TObject);

var b1,b2,b3:TBitmap;
BF: TBlendFunction;
begin
  // Example how it opacity works:
  b1 := TBitmap.Create;
  b1.SetSize(20,20);
  b1.Canvas.Brush.Color := clBlue;
  b1.Canvas.Rectangle(0,0,20,20);
  Canvas.Draw(10,10,b1,$ff);  // Works
  Canvas.Draw(40,10,b1,$66);  // Works

  // I need it in combination with TransparentColor:
  b3 := TBitmap.Create;
  b3.PixelFormat := pf32Bit;

  b2 := TBitmap.Create;
  b2.PixelFormat := pf32Bit;
  // next 3 lines are different from above
  b2.Transparent := true;
  b2.TransparentColor := clFuchsia;
  b2.Canvas.Brush.Color := clFuchsia;
  b2.SetSize(20,20);
  b2.Canvas.Brush.Color := clBlue;
  b2.Canvas.Ellipse(0,0,20,20);

  Canvas.Draw(10,40,b2,$ff);  // Works (full opacity)

  b3.SetSize(20,20);
  SetBitmapAlpha(b3,0);
  b3.Canvas.Draw(0,0,b2,$66);
  AdaptBitmapAlpha(b3,b2);
  Canvas.Draw(40,40,b3,$66);

  b1.Free;
  b2.Free;
  b3.Free;
end;

A: thanks to bummi (accepted answer)!
i put his solution in a class helper. here is the code if anybody need it:
unit uBitmapHelper;

interface

uses
  Vcl.Graphics;

type
  TBitmapHelper = class Helper for TBitmap
  private
  type
    TRgbaRec = packed record
      r,g,b,a:Byte;
    end;
    PRgbaRec = ^TRgbaRec;
    PRgbaRecArray = ^TRgbaRecArray;
    TRgbaRecArray = array [0 .. 0] of TRgbaRec;
  public
    procedure TransparentMaskedDraw(ACanvas:TCanvas;AX:Integer;AY:Integer;AMask:TColor;AOpacity:Byte);
  end;

implementation

{ TBitmapHelper }

procedure TBitmapHelper.TransparentMaskedDraw(ACanvas:TCanvas;AX,AY:Integer;AMask:TColor;AOpacity:Byte);
var i,j:Integer;
    line1,line2:PRgbaRecArray;
    mask:PRgbaRec;
    tmp:TBitmap;
begin
  mask := @AMask;
  tmp := TBitmap.Create;
  tmp.SetSize(self.Width,self.Height);
  tmp.PixelFormat := pf32Bit;
  tmp.HandleType := bmDIB;
  tmp.IgnorePalette := true;
  tmp.AlphaFormat := afDefined;
  for i := 0 to tmp.Height - 1 do begin
    line1 := tmp.Scanline[i];
    for j := 0 to tmp.Width - 1 do begin
      line1[j].a := 0;
    end;
  end;
  tmp.Canvas.Draw(0,0,self,AOpacity);
  for i := 0 to tmp.Height - 1 do begin
    line1 := tmp.ScanLine[i];
    line2 := self.ScanLine[i];
    for j := 0 to tmp.Width - 1 do begin
      if not((line2[j].r = mask.r) and (line2[j].g = mask.g) and (line2[j].b = mask.b)) then begin
        line1[j].a := $ff;
      end else begin
        line1[j].r := 0;
        line1[j].g := 0;
        line1[j].b := 0;
      end;
    end;
  end;
  ACanvas.Draw(AX,AY,tmp,AOpacity);
  tmp.Free;
end;

end.

A: The oldest answer is fine, please find some easy reshuffle.
This example also shows how to put one png-image with opacity on another by respecting the transparency.

procedure TForm2.FormCreate(Sender: TObject);
//define your own transparent color by setting RGB-values
const cTransR=255; cTransG=255; cTransB=255;
      clTrans= $10000*cTransB + $100*cTransG + cTransR;

var bmp1,bmp2:TBitmap;
    pngTemp: TPngImage;
    I:integer;

    procedure SetAlphaTransparent(VAR LBitmap:TBitmap);
    type   TRGBQuadArray = ARRAY [0..0] OF TRGBQuad;
    var    I, J: integer;
           LscanLine32:^TRGBQuadArray;
    begin
        // I found no other way than scanning pixel by pixel to recover default opacity
        for I := 0 to LBitmap.Height - 1 do begin
          LscanLine32:=LBitmap.ScanLine[I];
          for J := 0 to LBitmap.Width - 1 do
            with LscanLine32[J] do
              if NOT((rgbRed=cTransR)AND(rgbGreen=cTransG)AND(rgbBlue=cTransB)) then
                rgbReserved := 255; // make pixel visible, since transparent is default
        end;
    end;

    Procedure SetAlphaProperty(Var LBitmap:TBitmap; LWidth, LHeight:integer);
    begin
        // You will need a different format Bitmap to allow alpha values
        LBitmap.PixelFormat := pf32Bit;
        LBitmap.HandleType  := bmDIB;
        LBitmap.alphaformat := afDefined;
        LBitmap.Canvas.Brush.Color := clTrans;
        LBitmap.SetSize(LWidth,LHeight);
    end;

begin
  // create any background on your Form, by placing IMG:Timage on the From
  pngTemp := TPngImage.Create;
  pngTemp.LoadFromFile( GetCurrentDir()+'\figure1.png' );
  IMG.Canvas.Draw((IMG.Width-pngTemp.Width) div 2,  // fit png into the center
                  (IMG.Height-pngTemp.Height) div 2,pngTemp);
  pngTemp.Free;

  // First example how it opacity works with transparency
  bmp1 := TBitmap.Create;
  SetAlphaProperty(bmp1,35,35);
  // a circle has a surrouding area, to make transparent
  bmp1.Canvas.Brush.Color := clBlue;
  bmp1.Canvas.Ellipse(5,5,30,30);
  SetAlphaTransparent(bmp1);
  // show some circles with different opacity
  for I := 0 to 7 do
      IMG.Canvas.Draw(I*40-30,10,bmp1,(8-I)*32);
  bmp1.Free;

  // Another example using a different png-file
  bmp2 := TBitmap.Create;
  SetAlphaProperty(bmp2,Img.Width,Img.Height);
  // load a transparent png-file and put it into the alpha bitmap:
  pngTemp := TPngImage.Create;
  pngTemp.LoadFromFile( GetCurrentDir()+'\figure2.png' );
  pngTemp.Transparent := true;
  bmp2.Canvas.Draw((bmp2.Width-pngTemp.Width) div 2,// fit png into the center
                   (bmp2.Height-pngTemp.Height) div 2,pngTemp);
  pngTemp.Free;
  // draw the second image with transparancy and opacity onto the first one
  SetAlphaTransparent(bmp2);
  IMG.Canvas.Draw(0,0,bmp2,$66);
  bmp2.Free;
end;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python - Main() loop not executing repeatedly (New to Python and trying my best)
This program runs, and the buttons do the right things.  But the MAIN() procedure block doesn't work.  I'm wanting main() to keep looping until the user closes the program.  Within the loop is a simple decision about a time comparison and if 10 seconds have elapsed the 3 buttons will get a light grey background.
I tried some print statements within the main() area and they don't print at all.  Where am I going wrong?
Thanks a bunch
from guizero import App, Text, TextBox, PushButton
import RPi.GPIO as GPIO
import sys
import time
import datetime
from datetime import timedelta
from datetime import datetime

# This procedure will watch three inputs and lock in the team that calls in first for 5seconds
# Change the colors of the buttons to show which team pressed in first.

def action1(dunno):
        # Team1 button pressed
        global SetCurrTime
        if datetime.now() > SetCurrTime + timedelta(seconds=5):
                # Mark Team 1 as the buzzer beater
                team1_btn.bg="green"
                team2_btn.bg="red"
                team3_btn.bg="red"
                SetCurrTime = datetime.now()
                txtButtons_Hit.value = "Team1 was hit: " + str(SetCurrTime)

def action2(dunno):
        # Team2 button pressed
        global SetCurrTime
        if datetime.now() > SetCurrTime + timedelta(seconds=5):
                # Mark Team 2 as the buzzer beater
                team1_btn.bg="red"
                team2_btn.bg="green"
                team3_btn.bg="red"
                SetCurrTime = datetime.now()
                txtButtons_Hit.value = "Team2 was hit: " + str(SetCurrTime)

def action3(dunno):
        # Team3 button pressed
        global SetCurrTime
        if datetime.now() > SetCurrTime + timedelta(seconds=5):
                # Mark Team 3 as the buzzer beater
                team1_btn.bg="red"
                team2_btn.bg="red"
                team3_btn.bg="green"
                SetCurrTime = datetime.now()
                txtButtons_Hit.value = "Team3 was hit: " + str(SetCurrTime)

def main():
        #reset board when 5seconds has elapsed from SetCurrTime
        app.display()
        global SetCurrTime
        print ("Here")
        while True:
                txtButtons_Hit.value = "Current Time: " + str(datetime.now())
                print ("here")
                if datetime.now() > SetCurrTime + timedelta(seconds=5):
                        # clear the board
                        team1_btn.bg="light grey"
                        team2_btn.bg="light grey"
                        team3_btn.bg="light grey"

# Pin setup
GPIO.setmode(GPIO.BCM) # Broadcom pin-numbering scheme
GPIO.setup(16, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(20, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(21, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.add_event_detect(16, GPIO.RISING, callback=action1, bouncetime=1800)
GPIO.add_event_detect(20, GPIO.RISING, callback=action2, bouncetime=1800)
GPIO.add_event_detect(21, GPIO.RISING, callback=action3, bouncetime=1800)

SetCurrTime = datetime.now() + timedelta(seconds=-5) #init this at the start of the program

app = App(title="A07 DSS Tri-State - Jeopardy", width=700)
blank1 = Text(app, text="")
welcome_message = Text(app, text="This..      is..       Jeopardy!!", size=30, font="Times New Roman", color="blue")

blank2 = Text(app, text="")
blank3 = Text(app, text="")

team1_btn = PushButton(app, text="Team Black & Blue", command = lambda:action1(1))
team1_btn.bg="light grey"
blank4 = Text(app, text="")
team2_btn = PushButton(app, text="Team Holiday Spirit", command=lambda:action2(2))
team2_btn.bg="light grey"
blank5 = Text(app, text="")
team3_btn = PushButton(app, text="Team Creamsicle", command=lambda:action3(3))
team3_btn.bg="light grey"
blank6 = Text(app, text="")
delay_timer = Text(app, text="0")
delay_timer.visible=False
blank7 = Text(app, text="")
txtButtons_Hit = Text(app, text="Current Time: " + str(SetCurrTime))

main()

A: Try putting this in the program
if __name__ == '__main__':
    main()


text:
Q: Cannot set 100% height of div as height resets to 0px I'm trying to set the div height of the separate parent columns (and their children) to 100% but it doesn't seem to be working because the div height mysteriously just resets to 0.
The first column has two child boxes (if I'm describing it correctly) which would take 50% (separately) of the page height. The second and third have one child box each which would both take 100% of the page height.
In addition to this I want to add a place holder for the logo on the top left of the page and a footer at the bottom of the page. With all of the above it seems a bit daunting. Would appreciate your advice.
In the end it should look like this:

I've uploaded it here: http://jsfiddle.net/methuselah/qtmJW/

A: Use height: 100%; on #wrapper
Note : Also remove overflow: hidden; from #wrapper
My fiddle
Edit : New Fiddle


text:
Q: Jquery addClass() , removeClass() functions does not work $('.push').each(function(){
  if($(':first-child',this).hasClass( "activex" )){
    $(this).off().off('click').on('click',function(){
      var a = $(this).attr('id');
      $.ajax({
        type: "POST",
        url: "includes/rcart.php",
        data:{'pid': a},
        success: function(data){
          var a= parseInt($('.cart').text());
          if((data.indexOf("2")) >= 0){
            console.log(data);
            console.log('not removed');
          }else{
            a--;
            console.log('removed');
            $(this).children().removeClass('activex');
            $('.cart').text(a);
          }
        }
      });
      console.log(a);
    });
  }else{
    $(this).on('click',function(){
      var a = $(this).attr('id');
      $.ajax({
        type: "POST",
        url: "includes/cart.php",
        data:{'pid': a},
        success: function(data){
          console.log(data);
          var a= parseInt($('.cart').text());
          if((data.indexOf("2")) >= 0){
            console.log('done');
          }else{
            a++;
            $('.cart').text(a);
            $(this).children().addClass('activex');
          }
        }
      });
      console.log(a);
    });
  }
});

I am trying to remove the class activex whenever the button with class push has been clicked but its not working and  there's no error in the code and it's not removing the class. If i remove the class manually in the chrome console with  class .push it works.
I am trying to remove the class activex whenever the button with class push has been clicked but its not working and  there's no error in the code and it's not removing the class. If i remove the class manually in the chrome console with  class .push it works.

A: Here is your updated code, just i have removed children() from your code.
let me know if it helped or not.
$('.push').each(function(){

      if($(':first-child',this).hasClass( "activex" )){
          $(this).off().off('click').on('click',function(){
        var a = $(this).attr('id');
                $.ajax({

    type: "POST",
    url: "includes/rcart.php",
    data:{'pid': a},
    success: function(data){

     var a= parseInt($('.cart').text());

     if((data.indexOf("2")) >= 0){
          console.log(data);
         console.log('not removed');
     }
     else {
     a--;
     console.log('removed');
     $(this).removeClass('activex');
     $('.cart').text(a);
     }
    }

    });

        console.log(a);
    });

      }

      else {

    $(this).on('click',function(){
        var a = $(this).attr('id');
                $.ajax({

    type: "POST",
    url: "includes/cart.php",
    data:{'pid': a},
    success: function(data){

    console.log(data);
     var a= parseInt($('.cart').text());

     if((data.indexOf("2")) >= 0){
         console.log('done');
     }
     else {
     a++;
     $('.cart').text(a);
     $(this).addClass('activex');
     }
    }

    });

        console.log(a);
    });
      }

});


text:
Q: How to make auto sizing container in android studio enter image description here
here is the link to the image.
There is a container that stores photos, and it can automatically expand and reduce depending on the number of photos.
How to implement such a container in android.
Maybe there is some kind of built-in View?


text: Q: Convert seconds into days ,hours, minutes, and seconds in python how can i convert 200 seconds  into  in days, hours, minutes, seconds in python (the output should be single line containing like D,H,M,S print only  the non zero values


text:
Q: Malformed Info.plist causes macOS crash By accident, I added the line <array></array> to my applications' Contents/Info.plist file. When launching the app in the Xcode debugger, the computer appears to crash and reboot. Is this considered a security relevant issue?
Steps to reproduce on macOS Sierra 10.12.6 and Xcode 8.3.3:
(1) create and build a default Cocoa App in Xcode
(2) using a text editor, add the line <array></array> to the end of the <plist> block in your <app>/Contents/Info.plist; here are the last 3 lines of my Info.plist:
</dict>
<array></array>
</plist>
(3) do not build but just run the app in the Xcode debugger; the app crashes, a gray screen appears and your machine reboots

A: I have a feeling that something else is going on here. You are one major OS version behind (two if you could betas), and I have a feeling that if you were to open a bug with Apple, they'll just tell you to install the latest stuff. But I have the latest, so I'll try.
I'm running 10.14, and I tried what you suggested. I went in and manually disabled code-signing, which is required with Xcode 10 (and 9 think). When I follow your tests, the app just fails to launch. launchd produces an error to the effect of "Invalid property list".
So, could this be a bug in an older OS, for sure. And why not open a bug with Apple. Just include what you have here. But, I suspect that something else is up on your machine, which triggers the panic. You might be able to dig into logs to figure that out.
update
I followed the instructions to just modify TextEdit.app, and insert the <array><\array>. I was able to reproduce the panic on 10.13, but not on 10.11 or 10.14 (the only machines I have handy).
*** Panic Report ***
panic(cpu 0 caller 0xffffff8012515e80):  initproc exited -- exit reason namespace 2 subcode 0x4 description: none

I'm fairly sure this means that launchd crashed. I believe that when that happens, the kernel just panics. Interestingly, I tried a modification that invalidates the signature but does not make the Info.plist invalid. Those seem to not causes the panic. That just does what all the other OSes do, which is cause the process to crash with:
Application Specific Information:
dyld: launch, running initializers
/usr/lib/libSystem.B.dylib
Sandbox registration failed: The code signature is not valid: The operation couldn't be completed. (OSStatus error -67030.)

That's exactly what I would have expected on 10.13. And I was able to make it happen in certain circumstances. But, not with this specific change.


text:
Q: Why does apache drill return Null pointer exception when querying a parquet file with a optional Null column? I am writing to parquet file using protobuf (or Avro). my proto file looks like this:
message Log  {
    optional string date = 1;
    optional string url = 2;
}

it is a reduced version of my problem. Now when writing to a parquet file (Non-hadoop), I want to have a case in which for one of the column there is no data at all (I am working on schema evolution). so I am just writing value for 'date' column in parquet file. File is created successfully but when I am trying to query it by apache drill, It throws a nullpointer exception. If at least for one of written records, I set 'url' field, then it is ok and all other 'url' value can be null and drill can query it. But I need the case in which in a parquet file, a whole column is null (but other parquet files have values for that column). please help me guys.
my parquet version is : 1.6.0rc7 and apache drill version is 0.8.0
here is the code: LogClass is the class compiled from proto file
MessageType parquetSchema = new   ProtoSchemaConverter().convert(LogClass.Log.class);`

ProtoWriteSupport writeSupport = new  ProtoWriteSupport(LogClass.Log.class);

CompressionCodecName compressionCodecName = CompressionCodecName.SNAPPY;

int blockSize = 128 * 1024 * 1024;
int pageSize = 64 * 1024;

Path outputPath = new Path("./my.parquet");

ParquetWriter parquetWriter = new ParquetWriter(outputPath,    writeSupport, compressionCodecName, blockSize, pageSize);`

LogClass.Log.Builder log = LogClass.Log.newBuilder();
log.setUrl("www.x.com");

for (int i=0; i < 20; i++)
    parquetWriter.write(log);
parquetWriter.close();


text:
Q: how to print javascript text into a form using a button I'm attempting to combine my limited knowledge of HTML and JavaScript for practice and can't seem to get past this snag. I'm trying to make it so when I click the button the random cards appear in the form above the button. Is there may be a better way to do this?

function randomCards() {
  const cards = ['diamond', 'spade', 'heart', 'club'];
  let currentCard = ''
  while (currentCard != 'spade') {
    currentCard = cards[Math.floor(Math.random() * 4)];
  }
}
<form>
  Cards:

  <input type='text' name="Card Slot">
</form>
<button onclick='randomCards()'>Get Cards</button>

A: You have to set the value received to the input. Use document.querySelector to get the input element and using .value, set the value of the input

function randomCards() {
  document.querySelector('#a').value = "";
  const cards = ['dimond', 'spade', 'heart', 'club'];
  let currentCard = ''
  while (currentCard != 'spade') {
    currentCard = cards[Math.floor(Math.random() * 4)];
    document.querySelector('#a').value += currentCard +
      " "
  }
}
<form>
  Cards:

  <input type='text' name="Card Slot" id="a">
</form>
<button onclick='randomCards()'>Get Cards</button>

A: Here is an answer with minimal changes to your HTML structure:

<form>
  Cards:

  <input type='text' name="Card Slot">
</form>
<button onclick='randomCards()'>Get Cards</button>

A:

function randomCards() {
    const cards = ['dimond', 'spade', 'heart', 'club'];
    let currentCard = ''
    while(currentCard != 'spade') {
        currentCard = cards [Math.floor(Math.random()*4)];
    }
    console.log(currentCard);
    $('#test3').val(currentCard);
}

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

<form>
  Cards:

  <input type='text' id="test3" name="Card Slot">
</form>

<button onclick= 'randomCards()'>Get Cards</button>

here while(currentCard != 'spade') {
            currentCard = cards [Math.floor(Math.random()*4)];
        }

will always gives spade, if you want random you can remove while and put currentCard = cards [Math.floor(Math.random()*4)];


text:
Q: How to implement full advertisement using greystrip sdk? I want to display a full advertisement in my application. I don't know how to implement it. I know this is possible using greystrip sdk. Can you give me advice?

A: Well, the basic documentation with examples can be found at: http://wiki.greystripe.com/index.php/Greystripe_SDK
You should start there and then ask more specific questions when you hit problems.


text:
Q: Nautilus window opens after device usb connection Nautilus window opens after device usb connection. But this is not a storage device. It's even not mounted. It just takes some power supply via USB.
How to disable automatic window opening after not mounting?

A: GUI
Bring up a terminal window, then install dconf-editor package.
sudo apt-get install dconf-editor && dconf-editor

Navigate to org > gnome > desktop > media-handling, uncheck automount-open option on the key list.

Command line
No need to install anything, simply run following command.
gsettings set org.gnome.desktop.media-handling automount-open false


text:
Q: Should I put index.php outside of public folder in Zend Framework? I am on shared hosting server and I am going to place zend application there but I can not touch httpd.conf file to make a virtual host as it is shared hosting and they do not allow me to do it.
If I keep index.php file and .htaccess in the public folder I have to make a virtual host to hide the public from the url.
So, I though that I can put the public folder files (index.php, .htaccess) in the site root thus I don't need to create a virtual server for this and my site is accessible without the need of public in url.
Is there anything make my site unsafe if I put index.php file out of public folder?
I speak English not well, so sorrry. Somethings i copied from other posts to describe things i want to explain.
I have tried this way but it still doesn't work, when i type localhost/public/zend/, it returns "Object not found"
Directory structure:
zend/
    application/
    library/
    public/
           index.php
           .htaccess
.htaccess

content of .htaccess in public folder:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]

content of .htaccess in root folder:
SetEnv APPLICATION_ENV development

RewriteEngine On
RewriteRule ^\.htaccess$ - [F]
RewriteCond %{REQUEST_URI} =""
RewriteRule ^.*$ /public/index.php [NC,L]
RewriteCond %{REQUEST_URI} !^/public/.*$
RewriteRule ^(.*)$ /public/$1
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^.*$ - [NC,L]
RewriteRule ^public/.*$ /public/index.php [NC,L]

A: Well you wont be able to access index.php in that case. If you cant put things not in the web root then the best bet is to configure ZF to use a folder other than public as your doc root so your layout might look like:
application/
library/
modules/
public_html/
  index.php
  js/
  css/
  images/

A: The "public" folder is an important key feature of the Zend Framework because it confines Apache to only read files in that directory. You should not have anything else than the public folder accessible via HTTP and moving the index file introduces easy threat of being vulnerable to exploits.
Check this out this link it might be helpful.
And if you are using Cpanel this here might be useful.

A: Is possible to have .htaccess and index.php without any kind of problems in the Apache's htdocs dir.
It's not mandatory to have a folder called "public", just to have the public part (public directory( and application part (the rest of project files) in different directories. The application part must not being accesible from the user's browser (so place it outside of the Apache document root)

A: There are many ways to make ZF work without having the ability to map the virtual host to a public folder.
This answer highlights many of them.
Personally, when I'm stuck with shared hosting and I am unable to remap, I tend to do the following :

*

*Keep the contents of the public folder (index.php, .htaccess, public assets like css, js, img, etc) up at the host-provided doc root, and

*Push the rest of the application down into a folder like _zf to which I add a Deny All directive in an .htaccess file. Then I modify the APPLICATION_PATH setting in index.php to point to _zf/application.
That's it.
Full details here.


text:
Q: Is there a 64 bit equivalent to GetLastInputInfo / LASTINPUTINFO? We use GetLastInputInfo and calculate the difference from the result of GetTickCount64 to determine idleness. However, the tick count returned by GetLastInputInfo is written into a the member dwTime of LASTINPUTINFO, which is a DWORD and therefore an unsigned 32 bit integer, with a maximum value of and its maximum value of 4294967295, which is equivalent to ~49 days. On machines with uptimes longer than that, this of course leads to the function reporting an incorrect value.
Apparently there is no function called GetLastInputInfo64, but maybe a function under a different name?

A: There is a workaround that we use.
Only use the result of GetLastInputInfo() to detect if the dwTick has changed without caring how much it changed.
Do this periodically.
When the tick has changed (the value is not the same as it was the previous reading) start your own timer and use that to detect when the input has became idle for for instance 30 seconds.
You will never need to deal with wraparounds using this approach.

A: @Anders:
public class IdleDetection
{
    private struct LASTINPUTINFO
    {
        public uint cbSize;
        public uint dwTime;
    }

    [DllImport("user32.dll")]
    private static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);

    private readonly Timer _idleTimer;
    private double _idleSeconds = 0;
    private uint _previousLastInput = 0;
    private DateTime _idleStart = DateTime.Now;
    private object _lock = new object();

    public IdleDetection()
    {
        _idleTimer = new Timer(TimerCallback, null, 1000, Timeout.Infinite);
    }

    public TimeSpan IdleTime
    {
        get {
            lock (_lock)
            {
                return TimeSpan.FromSeconds(_idleSeconds);
            }
        }
    }

    private void TimerCallback(object state)
    {
        lock (_lock)
        {
            var lastInput = GetLastInputInfoValue();

            if (lastInput == _previousLastInput)
            {
                _idleSeconds = (DateTime.Now - _idleStart).TotalSeconds;
            }
            else
            {
                _idleSeconds = 0;
                _idleStart = DateTime.Now;
            }

            _previousLastInput = lastInput;
        }
        _idleTimer.Change(1000, Timeout.Infinite);
    }

    private static uint GetLastInputInfoValue()
    {
        LASTINPUTINFO lastInPut = new LASTINPUTINFO();
        lastInPut.cbSize = (uint)Marshal.SizeOf(lastInPut);
        GetLastInputInfo(ref lastInPut);
        return lastInPut.dwTime;
    }
}


text:
Q: How to insert a div between two divs? I have two small divs at the two left and right corners of my page. There is a lot of space between them. I want to occupy all that space with another div.
Here is the CSS code:
.signatureBox{
    border-radius: 5px;
    border-width: 1px;
    border-style: solid;
    border-color: rgb(128, 128, 128);
    min-width: 200px;
    min-height: 65px;
    padding: 3px;
    display: block;'
}

and the HTML code:

            employee

            Role

            employee

            Role

             Master

A: If you are trying to remove the space between them, you should simply set float to left on every one of them.

        employee

        Role

        employee

        Role

         Master


text:
Q: mysql if then else update procedure i want upgrade statement in procedure:
DROP PROCEDURE IF EXISTS `update` $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `update`
     (IN mobile VARCHAR(20), IN registered BOOLEAN, IN charge BOOLEAN, IN debit_mon INT)
BEGIN
 DECLARE chargeTime Datetime;
 DECLARE lastdayNow Integer;
 DECLARE lastdayNext Integer;

 SET lastdayNow =  DAY(now());
 SET lastdayNext =  DAY(LAST_DAY(now() + interval 1 month));

 IF lastdayNow > lastdayNext then
   SET chargeTime = LAST_DAY(now() + interval 1 month);
 ELSE
   SET chargeTime = now() + interval 1 month;
 END IF;

 UPDATE `chat_acc` SET
     `registered` = registered,
     `charge` = charge,
     `debit_mon` = debit_mon,
     CHARGE_TIME = chargeTime
   WHERE `phone` =mobile;
END $$

i want add case check field source:
if  source = 'A' or source = 'B' then set Charge Time = now() + interval 1 week

Thank any your help

A: Assuming the field name is source.
Try to add this in your stored procedures:
IF [source] = 'A' OR [source] = 'B' then
  SET chargeTime = now() + interval 1 week
END IF;

A: Just guessing here, but if source is a column in chat_acc you can do something like this in your UPDATE statement:
UPDATE `chat_acc` SET
   `registered` = registered,
   `charge` = charge,
   `debit_mon` = debit_mon,
   CHARGE_TIME =
      CASE WHEN chat_acc.source IN ('A', 'B') THEN now() + interval 1 week
      ELSE chargeTime
      END
WHERE `phone` =mobile;


text:
Q: Is it possible to secure the Android KeyChain with an HSM? For security reasons I want to store my private key in the HSM and then share the private key with another app via the KeyChain. The KeyStore mentions that it can be backed by the HSM but I haven't found any documentation that states it's possible with the KeyChain.
Based on the KeyChain documentation, the KeyChain is the proper way to share between apps:

Use the KeyChain API when you want system-wide credentials. When an
app requests the use of any credential through the KeyChain API, users
get to choose, through a system-provided UI, which of the installed
credentials an app can access. This allows several apps to use the
same set of credentials with user consent.

So, is it possible to secure the Android KeyChain with an HSM?

A: After a lot of searching, I finally found that the answer is yes, it is possible.
The Android 4.3 changelog seems to be the only place that documents it:

Android also now supports hardware-backed storage for your KeyChain
credentials, providing more security by making the keys unavailable
for extraction. That is, once keys are in a hardware-backed key store
(Secure Element, TPM, or TrustZone), they can be used for
cryptographic operations but the private key material cannot be
exported. Even the OS kernel cannot access this key material.

I tested this with code and it seems that once you import a KeyPair into the KeyChain it is automatically put into secure hardware. This is the Kotlin code that I ran to test:
GlobalScope.launch {
    context?.let { it1 ->
        val privKey = KeyChain.getPrivateKey(it1, "device_certificate")
        Log.d("App", privKey.toString()) // Shows that this is an AndroidKeyStoreRSAPrivateKey
        val keyFactory: KeyFactory = KeyFactory.getInstance(privKey?.algorithm, "AndroidKeyStore")
        val keyInfo: KeyInfo = keyFactory.getKeySpec(privKey, KeyInfo::class.java)
        if (keyInfo.isInsideSecureHardware()) {
            Log.d("App", "The key is in secure hardware!")
        }
        else {
            Log.d("App", "The key is not in secure hardware!")
        }
    }
}

which printed "The key is in secure hardware!".


text:
Q: Bash: handling "[[ statement ]] || echo problem found ; exit 1" logic In the statement in the title, there is a problem that even if the statement is true, it will still exit with status 1 because, as I understand it:
[[ statement ]] || echo problem found ; exit 1

Evaluates to if the statement is false, echo problem found.  Exit with status 1.  Even if the statement evaluates true, the exit 1 still happens because it is separate.  I thought to fix this by running it in a subshell like so:
[[ statement ]] || (echo problem found ; exit 1)

This seems to do what I want, but is it an acceptable way to handle this?

A: You must use
[[ statement ]] || { echo problem found ; exit 1; }

The difference is that the brace syntax doesn't create a subshell, which means the exit 1 applies to the current shell.  If you use (exit 1) the subshell exits but the current shell continues running.

A: You need to use syntax like this :
[[ statement ]] || { echo problem found ; exit 1; }

and more accurate send standard error
[[ statement ]] || { echo >&2 "problem found"; exit 1; }

A: Don't try to be clever. Remember that debugging is twice as hard as writing, so when you're writing a program, be only half as clever as you can be.
if ! [[ statement ]]; then
  echo problem found
  exit 1
fi


text:
Q: When is the Kullback–Leibler divergence continuous? For two probability measures $P,Q$, if $P\ll Q$, then the Kullback–Leibler divergence (or the relative entropy) is defined as:
$$D_{KL}(P||Q)=\int\log\bigg(\frac{dP}{dQ}\bigg)dP.$$
It is well known that for any two measures $P$ and $Q$, $D_{KL}$ is lower semicontinuous in $P,Q$. My question is: what are the conditions on $P,Q$ that make $D_{KL}$ continuous in the weak topology?


text:
Q: Cassandra policies configuration with CassandraAutoConfiguration When using CassandraAutoConfiguration how the yml configuration should look like to configure  Class<? extends ...> fields e.g. reconnectionPolicy: com.datastax.driver.core.policies.ConstantReconnectionPolicy
with delayMs=3000

A: So it seems providing a ClusterBuilderCustomizer with custom properties is the only option.
  @Bean
public ClusterBuilderCustomizer clusterBuilderCustomizer(CassandraBaseProperties properties) {
    return builder -> builder.withReconnectionPolicy(
            new ConstantReconnectionPolicy(properties.getReconnectionPolicyConstantDelayMs()));
}


text:
Q: Upload a file programmatically to a servlet I need to call a servlet via another Java file not via UI.  I need to send a csv file along with the request. How can I send the file along with the request which I can access in the servlet.
        File myFile = new File("c:\\myfile.csv");
        String strFormURL = "http://localhost:8080/Forms/MyFacesServlet/";
        url = new URL(strFormURL);

        HttpURLConnection httpURLConnection = (HttpURLConnection) url
                .openConnection();

        httpURLConnection.setDoOutput(true);
        httpURLConnection.setRequestMethod("POST");

Please advice how the file (myFile) can be passed along with the servlet call. So that I can access the file in Servlet and call a service to validate the file content.


text:
Q: MongoDB/Mongoose advanced search with $unwind, $sort & $group..? I have documents which are product groups, like this:
[
  {
    options: [],
    products: [
      {
        sku: '123',
        name: 'Product name 1'
      }, {
        sku: '476',
        name: 'Product name 2'
      }
    ]
  }, {
    options: [],
    products: [
      {
        sku: '265',
        name: 'Product name 3'
      }, {
        sku: '789',
        name: 'Product name 4'
      }
    ]
  }
]

What I need to do is an advanced query which includes sorting not only the product groups, but also the product arrays within.
The method I'm trying at the moment is to use aggregate() with $unwind and $sort, then to try to put the group back together (after the $unwind has broken the products array out).
Products.aggregate([
  { $unwind: '$products' },
  { $sort: {
    'products.sku': -1
  } },
  { $group: {
    '_id': '$_id',
    something: { $push: '$$ROOT' }
  } }
]).exec()

It's obviously the $group that's not right. I'm using '_id': '$_id' to put the original MongoDB _id back, but I don't know how to say:
"group by the product group id, and include all original fields"
So really I'm trying to $unwind and $sort the products array, then I want to  $wind_it_back_up_again... :-)
How can I achieve this..?
Update: This question is about keeping all fields while grouping.

A: Maybe I'm wrong but as I know there is no option to keep all fields while grouping, you have to manually define all properties. This is the code you're looking for, it sorts product groups by "products.sku" key, sorts inner "products" array by "sku" key, and keeps all fields during $group and $project stages.
db.test.aggregate([
    {$unwind: "$products"},
    {$sort: {"products.sku": -1}},
    {$group: {
        _id: {_id: "$_id", options: "$options"}, products: {$push: "$products"}
    }},
    {$project: {
        _id: "$_id._id",
        options: "$_id.options",
        products: "$products"
    }},
    {$sort: {"products.sku": -1}}
]).pretty();


text:
Q: How to redirect to a particular previous state of my page using $_GET varialble So,
I am currently on a page.
adminpanel.php?type=pdetail&id=1&op=edit

each of my variables create a some part of my page by echoing out HTML tags.
I want my page to redirect to
adminpanel.php?type=edit

(my type variable was already defined as "pdetail" I want it to modified to "edit")
if($op == 'edit')
{
    $id = $_GET['id'];
    echo("Testing IF condition");
    header("location:adminpanel.php?type=edit");
}

A: As I mentioned in comments, you're outputting before headers (see "References" below). There should not be any output before that, including one or more spaces before the opening <?php tag, HTML, cookies, etc., or anything that would cause an error.
This is covered in the link I have provided for you below, under "References".

*

*Remove the "echo" statement.

Whether you saw my comment or not is unknownst to me, and am submitting the following answer.
If error reporting were set/on on your server, you would be receiving a warning similar to this:

Warning: Cannot modify header information - headers already sent by (output started at /var/user/you/folder/adminpanel.php:12) in /var/user/you/folder/adminpanel.php on line x

Tested with the following and added some code that you left out in your question, proved to be successful.
<?php
$op = $_GET['op'];

    if($op == 'edit')
    {
        $id = $_GET['id'];
        header("location:adminpanel.php?type=edit");
        exit;
    }

Sidenote: It's best to add exit; after header, should there be more code following that. Otherwise, your code may want to continue executing.

References:

*

*http://php.net/manual/en/function.error-reporting.php

*How to fix "Headers already sent" error in PHP

*http://php.net/manual/en/function.header.php

Error reporting:
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

// rest of your code

Sidenote: Error reporting should only be done in staging, and never production.


text:
Q: How do you find out what Joomla components are being used from frontend? Trying to find out what component this website is using for its appointment scheduling.
Any way to find that out as a user from the front end? Somewhere in the developer's console perhaps?

A: If you click on Schedule Appointment on the top menu, I'm sure you might have seen that it redirects you to https://www.mindbodyonline.com.
This is the 3rd party appointment scheduling system but it's not a Joomla component

A: The scheduling part of the site, is not built in joomla. It uses asp, and Microsoft technologies.
As for the rest of the site doen't seem to be built in something special (it is just articles).


text:
Q: notifyItemRangeInserted not refresh 0 items I have RecyclerView.Adapter<RecyclerView.ViewHolder> with pagination button(Load More)
Load More button in RecyclerView like Footer. Each request get 20 rows and if I get <20 items I need disable this button:
 @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof ViewHolder) {
            ...
        } else if (holder instanceof FooterViewHolder) {
            ...
            viewHolder.loadMore.setEnabled(isVisibleLoadButton);
        }
    }

public void addData(List<TransactionItem> opcTransactions) {
        final int positionStart = transactionItems.size()+1;
        isVisibleLoadButton = opcTransactions.size() >= 20;
        transactionItems.addAll(opcTransactions);
        notifyItemRangeInserted(positionStart, opcTransactions.size());
    }

If I get opcTransactions with 1 or more items isVisibleLoadButton  set false and my load More button set disable. But If I get emty list opcTransactions size = 0 - load More button not diasbled.
@Override
    public int getItemCount() {
        if (transactionItems == null) {
            return 0;
        }

        if (transactionItems.size() == 0) {
            //Return 1 here to show nothing
            return 1;
        }

        // Add extra view to show the footer view
        return transactionItems.size() + 1;
    }

A: Problem is in this line .
final int positionStart = transactionItems.size()+1;

positionStart should point to last item of your list . and indexing starts form ZERO. Use it as .
final int positionStart = transactionItems.size();


text:
Q: Codeigniter email is not being sent I have a Codeigniter form like the following:

When I click on the green check sign for "Approve" or the red cross sign for "Reject" , an email is supposed to be sent to certain addresses. But I've checked that the mail was never sent.
For better understanding, here are some of my codes:
View:

                <?php
                $edit_text = (ACTION_BUTTON_TEXT_SHOW) ? 'Approve' : ' ';
                echo anchor('staff_requisitions/update_approve/' . $row['id'],"", $edit_text, array('class' => 'edit_button', 'title' => 'Approve'));
                ?>

                <?php
                $edit_text = (ACTION_BUTTON_TEXT_SHOW) ? 'Reject' : ' ';
                echo anchor('staff_requisitions/update_reject/' . $row['id'],"", $edit_text, array('class' => 'edit_button', 'title' => 'Reject'));
                ?>

Controller:
function __construct()
{
    parent::__construct();
    $this->load->database();
    $this->load->model('Staff_requisition');
    $this->load->helper('url');
    $this->load->helper('html');
    $this->load->helper('form');
    $this->load->library('email');
    $this->output->enable_profiler(false);
}

function update_approve(){
    $id = $this->uri->segment(3);
    $this->Staff_requisition->update_approve($id);
    //$data['list_of_emails'] = $this->Staff_requisition->get_list_of_emails($id);
    $this->email->from('joshamee_gibbs@example.com', 'Joshamee');
    $this->email->to('capn_jack_sparrow@example.com');
    $this->email->cc('william.turner1724@example.com');
    $this->email->subject('Email Test');
    $this->email->message('Testing the email class. Your requisition approved.');
    $this->email->send();
    echo $this->email->print_debugger();
    $this->session->set_flashdata('message', 'The requisition request has been approved');
    redirect('staff_requisitions/index');
}

function update_reject(){
    $id = $this->uri->segment(3);
    $this->Staff_requisition->update_reject($id);
    //$data['list_of_emails'] = $this->Staff_requisition->get_list_of_emails($id);
    $this->email->from('joshamee_gibbs@example.com', 'Joshamee');
    $this->email->to('capn_jack_sparrow@example.com');
    $this->email->cc('william.turner1724@example.com');
    $this->email->subject('Email Test');
    $this->email->message('Testing the email class. Your requisition rejected.');
    $this->email->send();
    echo $this->email->print_debugger();
    $this->session->set_flashdata('message', 'Sorry, the requisition request has been rejected');
    redirect('staff_requisitions/index');
}

Model:
function __construct()
{
    parent::__construct();
}

function update_approve($rid){
        $this->db->query("UPDATE `staff_requisitions` SET `is_approve` = 1 WHERE `id` = $rid ");
}

function update_reject($rid){
    $this->db->query("UPDATE `staff_requisitions` SET `is_approve` = 0 WHERE `id` = $rid ");
}

function get_list_of_emails($id){
    $q = $this->db->query("SELECT * FROM `requisition_emails` WHERE `req_id` = $id")->result_array();
    return $q;
}

What am I missing/doing wrong?
N.b. I'm running this application in localhost.

A: Use this setting
public $smtp = array(
  'transport' => 'Smtp',
  'from' => 'your_mail@gmail.com',
  'host' => 'ssl://smtp.gmail.com',
  'port' => 465,
  'timeout' => 30,
  'username' => 'your_mail@gmail.com',
  'password' => '*****'
)


text:
Q: Possible solutions to different types of differential equations Here are some EE exam questions. Very similar questions.

*

*What are two necessary conditions that need to be fulfilled so there's only one solution to: $y'=f(x,y)$ which satisfies $y(x_0)=y_0$ (initial condition)and $f:D \to R$,   $D⊆R^2$, $(x_0,y_0)∈D$

-$f$ and $ df/dy$ are continous. Any other?

*Prove non-existence of 3rd order differential equation $y'''=f(x,y,y',y'')$  that fulfills theorem of existence and uniqueness of solutions and which 2 solutions are $\varphi_1(x)=x,  \varphi_2(x)=\sin x$.

-if it was a homogeneous linear with constant coefficients, then I would know there are 4 solutions and you need 4th order equation. What am I missing from the theorem?

A: About question 1.
I have several comments here:

*

*It is strange for me to request necessary conditions. I would rather ask for sufficient conditions. In particular if you have in mind to apply Picard–Lindelöf theorem. For example the IVP problem $$y^\prime=1+y^{\frac{2}{3}}, y(0)=0$$ is such that $\frac{\partial f}{\partial y}$ doesn't exist at the origin. However it has a unique local solution.

*Continuity of $f$ and of $\frac{\partial f}{\partial y}$ is sufficient to apply Picard–Lindelöf theorem...

*But that gives only the existence and unicity of a local solution! Which means that the solution might not exist in all $D$.

About question 2.
Suppose that $$y^{\prime \prime \prime}=f(x,y,y^\prime,y^{\prime \prime})$$ is a 3rd order differential equation satisfying for example the Picard–Lindelöf theorem. Then you have a unique solution $y(x)$ (at least in the neighborhood of $0$) such that $$y(0)=y_0, y^\prime(0)=y_1,y^{\prime \prime}(0)=y_2.$$ However, we have $$\varphi_1(0)=\varphi_2(0)=0, \varphi_1^\prime(0)=\varphi_2^\prime(0)=1, \varphi_1^{\prime \prime}(0)=\varphi_2^{\prime \prime}(0)=0$$ but $\varphi_1 \neq \varphi_2$ for any neighborhood of $0$. So $\varphi_1, \varphi_2$ cannot be two solutions of our 3rd order differential equation.


text:
Q: Adding swagger to existing aws lambda (API Gateway) Does anyone know of a link to a useful documentation on how to add swagger documentation to an existing aws lambda (API Gateway)? Some sort of a noob tutorial as I am totally new to swagger.
I have found some links, such as the following, which were not so useful or not specific to lambda:
https://blog.cloudboost.io/adding-swagger-to-existing-node-js-project-92a6624b855b
https://github.com/swagger-api/swagger-node

A: I have only used Swagger with API Gateway with the old v0.5 version of serverless framework as there was a plugin that supported this easily.
However, when serverless matured into v1.0 and up, at that time, there were no good plugins for Swagger integration.
Here are links you can check:
Serverless Github Issue: Swagger Integration
Reckon-Limited/serverless_swagger
doapp-ryanp/serverless-plugin-swag
I don't personally use the above though as my big serverless projects are now using GraphQL (where API documentation is part of the standard tooling :-) instead of REST.

A: In my backend team we do the documentation using a tool that smart bear makes available, the swagger inspector and through it we finish adjusting the doc with the swagger hub.
Swagger inspector makes a request on your endpoint and basically extracts the necessary documentation, but some things you need to adjust, it is not the best solution, but it helps ...


text:
Q: Symfony runs SQL INSERT INTO twice i have a symfony application with two entities CONTEXT and USER, that are associated twice per many to many association:
class User

/**
 * @ORM\ManyToMany(targetEntity="Context", inversedBy="members")
 */
private $contexts;

/**
 * @ORM\ManyToMany(targetEntity="Context", inversedBy="managers")
 * @ORM\JoinTable(name="manager_context")
 */
private $managerOfContexts;

class Context

/**
 * @ORM\ManyToMany(targetEntity="User", mappedBy="contexts")
 */
private $members;

/**
 * @ORM\ManyToMany(targetEntity="User", mappedBy="managerOfContexts")
 */
private $managers;

When i add a new user and add a context to the user i always get the following error:
An exception occurred while executing 'INSERT INTO user_context
(user_id, context_id) VALUES (?, ?)' with params [5, 1]:

2 SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry
'2-1' for key 'PRIMARY'

It seems that the SQL command
DEBUG - INSERT INTO user_context (user_id, context_id) VALUES (?, ?)
DEBUG - INSERT INTO user_context (user_id, context_id) VALUES (?, ?)

is performed twice.
I just can't figure out why.
I already cleared the symfony cache, created the database new and also cleared the browsers cache.
Thank you for any help!

Here is the code where i persist the user entity:
/**
 * @Route("/admin/user/new", name="admin_user_new")
 */
public function newAction(Request $request)
{
    // 1) build the form
    $user = new User();

    $form = $this->createForm(UserType::class, $user, array('is_mode' => 'save','contexts' => null));

    // 2) handle the submit (will only happen on POST)
    $form->handleRequest($request);
    if ($form->isSubmitted() && $form->isValid()) {
        // 3) Encode the password (you could also do this via Doctrine listener)
        $password = $this->get('security.password_encoder')
            ->encodePassword($user, $user->getPlainPassword());
        $user->setPassword($password);

      $user->addContext($this->getDoctrine()
        ->getRepository('AppBundle:Context')
        ->find(1));

     $user->setActiveContext($this->getDoctrine()
        ->getRepository('AppBundle:Context')
        ->find(1));

        // 4) save the User!
        $em = $this->getDoctrine()->getManager();
        $em->persist($user);

        $folder = new Folder();
        $folder->setPrivate($user);
        $em->persist($folder);
        $em->flush();

        // ... do any other work - like send them an email, etc
        // maybe set a "flash" success message for the user

        return $this->redirectToRoute('tasklist');
    }

    return $this->render('/admin/user/new.html.twig',
        array('form' => $form->createView())
    );
}


text:
Q: writing iteration in MIPS I am writing this program in MIPS to calculate 2 to a power given by me and sum the sequential powers down to 0. For example, if I put 4 in $a0 like in the code below, I want it to calculate (4^2)+(3^2)+(2^2)+(1^2) which should come out to be 15. It should stop before it reaches zero. This is what I have written so far
main:
addi $a0, $zero, 4    #put k in $a0 in this case
addi $a1, $zero, 0    #put 0 in current sum
addi $v1, $v1, 0      #tally the total in $v1
for:
lw $10, $a0           #load k into reg $10
lw $11, $a1           #load sum into $11
    addi $10, $10, -1     #subtracts 1 from k
    li $9, 0              #sets i in for loop ($9) to 0

done:
    li $v0, 10
    syscall

I'm new to MIPS and could use a lot of help on finishing this, I know I want to use a for loop, but I don't know how to go through it while subtracting 1 from k and also calculating the sum. How would I bring 2 to a power of k, because I guess there is no power operation in mips. At this point in the course I can only use add, sub, and, or, slt, addi, j, beq, lw, sw, and sll. Can you not use a constant when using sub? Thank you for any help

A: A power is a multiplication, and a multiplication is a sum. So you can write a function that does a multiplication by adding, and another function that does power by multiplicating. For example, the multiplication function:
multiply: # $a0 first factor, $a1 second factor, $v0 result of multiplication
    or $t0, $zr, $zr
    or $t1, $a1, $a1
    or $t3, $zr, $zr
loop:
    beq $t1, $zr, end
    add $t0, $t0, $a0
    addi $t1, $t1, -1
    j loop
    nop
end:
    or $v0, $t0, $0
    jr $ra
    nop

(Please note I haven't tested this, and this will not work with negative numbers)
As a side note, you have MUL instruction as well, but I don't know if you saw that already.

A: I think the concept your instructor is trying to show you is that sll, in effect, multiplies by 2. You've got to think in binary. For example, let's start with 1:
0000 0000 0000 0000 0000 0000 0000 0001

Do a 'sll' on that, and what do you end up with? 0010 = 2. sll again and you get 0100 = 4. And so on, until you shift all the way over and have 0x80000000.
So the answer to the question, "How would I bring 2 to a power of k?", is simpler than you might have thought: you shift 1 by k.
# $t0 contains 'k', the amount we want to shift by
addi $t1, $zero, 1
sllv $t3, $t1, $t0

Note: I had to double-check that you can shift by a variable amount, but this link says sllv is valid. However, since it's not in your list of allowed functions, you'll have to do sll $t1, $t1, 1 in a loop. (Be sure to put your check at the start of the loop, in case the amount you want to shift by is zero!)

A: Quick question:
Are you doing 2^4+2^3.. etc? or 4^2+3^2 etc?
Just a quick note:
2^4+2^3+2^2+2^1+2^0 = 15.

4^2+3^2+2^2+2^1 != 15.

(If it is the first, you do need 2^0 because you need to contemplate for odd numbers, 2^0 = 1. This is how we get odd numbers in binary.)
In this case, the answer about left shift (lls) is correct. When you left shift a binary number you increase the exponent of base 2 by 1.
so:
0001 = 1
0010 = 2
0100 = 4
1000 = 8

These summed give you 15.
So you could shift left, and add the result of each shift to a register.


text:
Q: SSH to a computer that will then SSH to another computer
Possible Duplicate:
How to configure a shortcut for an SSH connection through a SSH tunnel

I have a situation where I would like to have SSH/SFTP access from my workstation to a server that is not directly accessable from my workstation.  I do have ssh access to a computer that is on the network which can then ssh to the server in question.
How can I accomplish this?

A: Use ssh tunnels, of course.

A: You can also do:  ssh -t remotelyaccsbl ssh notremotelyaccsbl

A: Use the ProxyCommand ssh config variable.
Host inaccessible
ProxyCommand ssh accessible nc -w1 %h %p

This post even explains a way to use a generic config so ssh host1/host2 automatically jumps hosts for you.
Update: Fixed the hostnames in the config snippet as per toppledwagon's comment.

A: I think this answer might be what you are looking for:
How to configure a shortcut for an SSH connection through a SSH tunnel

A: *

*Open tunnel:
ssh -qTfnN -D 4040 -C login@remotely-accessible-host

*Set up SOCKS5 on localhost with 4040 port in cyberduck

*Connect to computer you want access to

*

*q - quiet

*T - without tty

*f - move to background

*N - not execute remote commands

*n - redirect input to /dev/null.

A: WinSCP directly supports connection through an ssh tunnel.
Perhaps one of the MacOS clients also provide such functionality?

A: If SSH tunnels are not available to you (they can be disabled server-side), then could you reverse the FTP connection?
If your local machine can be seen via SSH on a publicly routable IP address and the inaccessible machine can see the outside world then

*

*SSH to remotelyaccessible

*from there SSH to notaccessible

*from there use the command-line SCP/SFTP clients to pick up files on your local filesystem

This probably isn't something you are going to be able to automate easily though, so if you have tunnels available use that method instead.

A: Thanks for all the leads.  After playing around with a few options the following setup seems to be the easiest:

*

*Downloaded a really nice program call SSHTunnel (highly recommended)

*Setup my known host in the Servers section of SSHTunnel

*Setup my desired ports in the Services section

*Green light shows up letting me know the tunnel is up

*Use SFTP client (Cyberduck or Fugu) to connect to 127.0.0.1 using the local port set in the Services of SSHTunnel

A: An alternative solution: port forwarding using socat
On the accessible machine, install socat if it is not already installed, and run it like this:

% socat tcp4-listen:1111,fork tcp4:inaccessible:2222

This is basically a port forward. You connect to accessible machine at port 1111 and it will connects you to port 2222 on inaccessible machine. fork will keep socat spawn new process for each connection.


text:
Q: WCF Service with Net.TCP Binding unable to write to event log I have a service hosted in IIS 7 over net.tcp which throws an error when writing to the Application event log because of invalid permissions:
Message: Requested registry access is not allowed.
Which account do I need to give permission to and where do I need to do it?


text:
Q: UIBarButton missing in DetailViewController Workflow design:

Swift 4.0, Xcode 9.2
The "Item" UIBarButton is missing when I run the below application. It is visible in storyboard though. Here's what I did:

*

*Created a Master-Detail app from scratch

*Embedded a TabBarController in the detail view

*Removed the Segue from MasterViewController into NavigationController of the DetailViewController

*Added a UIBarButton by dragging a UIBarButton into the first Tab view formed from the DetailViewController

A: Cocoa doesn't handle embedding a tabbar controller inside a navigation controller well (explained e.g. here).
You'll have to reverse the containment: Try to embed the detail VC in a navigation controller, and the navigation controller inside the tabbar controller, like this:
TabVC -> NavC -> DetailVC

For every additional tab you'll have to add a navigation controller. This way every tab can have it's own bar button items.


text:
Q: org.hibernate.HibernateException: No Session found for current thread with tx:advise I am using spring 3.2 with hibernate 4. I want to use spring to control the transactions.
However with the configuration mentioned below I get the
'Servlet.service() for servlet spring threw exception: org.hibernate.HibernateException: No Session found for current thread'
exception:
<aop:config>
    <aop:pointcut id="serviceMethods"
        expression="execution(* com.locator.service.impl.ServiceTypeService.*(..))" />
    <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethods" />
</aop:config>

<tx:advice id="txAdvice" transaction-manager="hbTransactionManager">
    <tx:attributes>
        <tx:method name="*" propagation="REQUIRED" />
    </tx:attributes>
</tx:advice>

<!-- Hibernate session factory -->
<bean id="hbSessionFactory"
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource">
        <ref bean="dataSource" />
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
            <prop key="hibernate.show_sql">true</prop>
        </props>
    </property>

    <property name="mappingResources">
        <list>
            <value>../spring/model/ServiceType.hbm.xml</value>
        </list>
    </property>

</bean>

<bean id="hbTransactionManager"
    class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="hbSessionFactory" />
</bean>

<bean id="serviceTypeService" class="com.locator.service.impl.ServiceTypeService">
    <property name="serviceTypeDao" ref="serviceTypeDao"></property>
</bean>

<bean id="serviceTypeDao" class="com.locator.dao.impl.ServiceTypeDao">
    <property name="sessionFactory" ref="hbSessionFactory"></property>
</bean>

The code for the Dao layer and the Service is as follows:
public class ServiceTypeDao implements IServiceTypeDao{

    private static final Log log = LogFactory.getLog(ServiceTypeDao.class);

    private SessionFactory sessionFactory;

    public SessionFactory getSessionFactory(){
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory){
        this.sessionFactory = sessionFactory;
    }

    public ServiceType findById(int id) {
        log.debug("getting ServiceType instance with id: " + id);
        try {
            Session session = getSessionFactory().getCurrentSession();
            ServiceType instance = (ServiceType)  session.get("com.locator.model.ServiceType", id);
            if (instance == null) {
                log.debug("get successful, no instance found");
            } else {
                log.debug("get successful, instance found");
            }

            instance.setName(instance.getName()+"0");
            session.saveOrUpdate(instance);

            return instance;
        }catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }
}

public class ServiceTypeService implements IServiceTypeService{

    private ServiceTypeDao serviceTypeDao;

    public void setServiceTypeDao(ServiceTypeDao serviceTypeDao){
        this.serviceTypeDao = serviceTypeDao;
    }

    public ServiceType getServiceTypeById(int id){
        return serviceTypeDao.findById(id);
    }
}

Replacing getSessionFactory().getCurrentSession() with getSessionFactory().openSession() will resolve the above issue however, it will mean that the developer will then be responsible for the session open/close rather than spring. Therefore, please advise how this can be resolved using spring.

A: I was able to resolve the issue. It was occurring due to the following problems:

*

*The Service class had not been Auto wired into the controller i.e. the @Autowired annotation was missing.

*The configuration for the web.xml had to be modified with the listener class 'org.springframework.web.context.ContextLoaderListener' and the context-param was added.


text:
Q: Ruby's ri command returns "Nothing known about Array" edit: Question answered by @FrederickCheung . I needed to reinstall ruby this time passing an argument to include docs:
brew install ruby --with-doc

Question:
I'm new to ruby and trying to get the ri command to work in Terminal (iTerm2 on OSX Yosemite). Here's what I've tried so far (everything is pasted from the terminal):
ri Array
Nothing known about Array

So I google around and tried:
gem install rdoc-data

Fetching: rdoc-data-4.0.1.gem (100%)
rdoc-data is only required for C ruby 1.8.7 or 1.9.1.

rdoc-data is required for JRuby.

To install ri data for RDoc 4.0+ run:

rdoc-data --install

Successfully installed rdoc-data-4.0.1
Parsing documentation for rdoc-data-4.0.1
Installing ri documentation for rdoc-data-4.0.1
Done installing documentation for rdoc-data after 0 seconds
1 gem installed

Tried it again:
ri Array
Nothing known about Array

Then I tried:
rdoc-data --install
Your ruby version 2.2.0 is not supported, only 1.8.7, 1.9.2, 1.9.3, 2.0.0

I googled around but the only results I get are for people using rvm or trying to disable the docs for rails installations. I installed ruby via homebrew if that means anything. I'm not really sure where to go from here, but I'd really like to be able to access the docs via ri.

A: Brew defaults to disabling installation of documentation.
If you check the formula you can see that unless you pass --with-doc to brew install ruby, it will pass --disable-install-doc to the ruby configure script.


text:
Q: where should I extract android ndk to on a mac? Sorry if this sounds like a no-brainer. I would like to know if I have to extract the Android NDK to any particular folder on my Mac or if can be extracted any where?

A: Yes, it can be extracted anywhere. Almost anywhere. Avoid paths with spaces, e.g. /Users/N Sologistic.

A: to ~/
~/ is your home directory i.e. /Users/yourShortName/
Thats automatically searches for libraries.


text:
Q: When fetching FB Insights in Ad Account, data like ad_name, ad_id, adset_id, adset_name are Empty Using facebook/php-ads-sdk 2.11
Why can't I retrieved ad_id, adset_id, adset_name even though I included
them in my fields to fetch?
Sample Code
$account = new AdAccount('act_' . $this->account_id);
    $fields = array(
        'spend',
        'clicks',
        'impressions',
        'campaign_name',
        'campaign_id',
        'inline_link_clicks',
        'actions',
        'ad_name',
        'ad_id',
        'adset_id',
        'adset_name',
        'account_id',
        'account_name',
    );

    $param = $this->filters;
    $param['level'] = 'campaign';

    $cursor = $account->getInsights($fields, $param);


text:
Q: Java - Concurrent Modification Exception I am getting a concurrent modification exception on the following code:
        for(Iterator<Tile> iter = spawner.activeTiles.iterator(); iter.hasNext();) {
            Tile tile = iter.next();
            canvas.drawRect(tile, tile.getColor());
        }

I understand that concurrent modification happens when it is changed while it is iterating(adding/removing inside of the iteration). I also understand that they can happen when multithreading which is where I think my problem is.
In my game I have a few timers that run on threads. I have a spawner, which adds values to activeTiles on each tick. I then have a 2 timers, one for fading in and one for fading out. Without giving away my game, the tile is basically removed from the list when the fade out has finished, or when the player taps the tile. So there are a few instances where the tiles are removed from the list of tiles:
for(Iterator<Tile> iter = spawner.activeTiles.iterator(); iter.hasNext();) {
                Tile tile = iter.next();

                if(tile.contains(x, y) && tile.equals(spawner.activeTiles.get(0))) {
                    vibrator.vibrate(50);

                    tile.setBroken(true);
                    score ++;
                    spawner.setTileDelayInfo();
                    iter.remove();

and before each new spawn, it removes all of the failed tiles:
private void removeFailedTiles() {
    for(Iterator<Tile> iter = activeTiles.iterator(); iter.hasNext();) {
        Tile tile = iter.next();

        if(tile.isFailed()) {
            iter.remove();
        }
    }
}

It almost seems to happen randomly. So I think it has to do something with timing, but I am new to this kind of exception and don't really know what to look for or why this is happening.

A: The good news: you nailed the root cause of the problem in your question - you can't have multiple threads accessing a list at the same time unless they're all just reading.
You can address this in one of two ways, depending on how the rest of your code operates.  The most 'correct' way is steffen's answer: any list access should be guarded with a synchronized block, and that includes holding the lock for the full duration of any list iterations.  Note that if you do this, you want to do as little work as possible while holding the lock - in particular, it's a bad idea to do any sort of listener callbacks while holding a lock.
Your second option is to use a CopyOnWriteArrayList, which is thread-safe and doesn't require any external synchronization - but any modifications to the list (add/remove/replace calls) become significantly more expensive.

A: Multithreading can be a source of ConcurrentModificationExceptions.  It can happen when one thread is modifying the structure of the collection while another thread has an Iterator iterating over it.  This can lead to unexpected states in your application when the state of the collection changes when a section of code needs a consistent view of the data.  This is needed when you're iterating over a collection of Tiles.
You need to syncrhonize access to the activeTiles collection.  Anything that modifies this collection structurally (add or remove), or iterates over it, must synchronize on this collection.
Add a synchronized (activeTiles) block around all code that iterates or structuraly modifies activeTiles.  This includes all 3 code snippets you've provided here.
Alternatively, you can make the 3 methods corresponding to your code snippets synchronized.
Either way, no other Thread can execute any of the synchronized blocks until another Thread is finished with its syncrhonized section, preventing the ConcurrentModificationException.

A: It's not safe to remove elements with an Iterator that supports element-removal, when you're iterating the collection in another thread.
Acquire a Lock in all threads on activeTiles before iterating them.

A: You might want to make your list thread-safe. Use Collections.synchronizedList().
threadSafeActiveTiles = Collections.synchronizedList(activeTiles);

Mind that you must synchronize on that list when iterating over it:
synchronized (threadSafeActiveTiles) {
    for (Iterator<Tile> it = threadSafeActiveTiles.iterator(); it.hasNext();) {
        Tile tile = it.next();
        // ...
    }
}

You then can safely have multiple threads modifying the list, which seems to be your case.
The list returned by Collections.synchronizedList() saves you from having to use the synchronized block (above) in single operations on that list, like add(e), size(), get(i) and so on...


text:
Q: cerrar Bootstrap modal popup Estoy tratando de cerrar una ventana modal de bootstrap con una url retornada desde al ActionResult, pero por alguna razón no me esta funcionando:
Este es mi script:
    $('form').submit(function () {
    var $form = $(this);
    $.ajax({
        url: this.action,
        type: this.method,
        contentType: this.enctype,
        data: $(this).serialize(),
        success: function (result) {
            if (result.success) {
                $('#myModal').modal('hide');
                //Refresh
                //location.reload();
                $('#replacetarget').load(result.url);
            } else {
                $('#myModalContent').html(result);
                //bindForm();
            }
        }
    });
});

Este es mi ActionResult:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateForCategory(MaterialViewModel material, HttpPostedFileBase upload)
{

    material.Status = Status.Activo;
    material.FechaRegistro = DateTime.Today.Date;

    var materialDomain = Mapper.Map<MaterialViewModel, Material>(material);

    if (upload != null && upload.ContentLength > 0)
    {
        var imagen = new Imagen
        {
            Nombre = System.IO.Path.GetFileName(upload.FileName),
            TipoContenido = upload.ContentType
        };

        using (var reader = new System.IO.BinaryReader(upload.InputStream))
        {
            imagen.Contenido = reader.ReadBytes(upload.ContentLength);
        }

        materialDomain.Imagen = imagen;
    }

    _materialRepository.Create(materialDomain);

    string url = Url.Action("MaterialesPorCategoriaIndex", "CategoriaMateriales");

    return Json(new { success = true, url = url }, JsonRequestBehavior.AllowGet);
}

Al momento de retornar el valor json se muestra una vista en blanco con este texto:
{"success":true,"url":"/CategoriaMateriales/MaterialesPorCategoriaIndex"}
Este es mi vista principal:
@model CategoriaMaterialViewModel
@{
    ViewBag.Title = "CategoriaMaterial";
}
<link href="~/Content/css/blockingwindow.css" rel="stylesheet" />

    @Styles.Render("~/Content/MiBundle")
    @Styles.Render("~/Content/toastr")

                        Lista de Materiales de: @Html.DisplayFor(x => x.Descripcion)

Inicio

Lista de Materiales

                    @Html.HiddenFor(x => x.CategoriaId, new { @id = "categoriaId" })
                    <form class="form-horizontal">

                                Agregar Material
                                Regresar a Categorías

                    </form>

@section Scripts {

    @Scripts.Render("~/bundles/toastr")
    @Scripts.Render("~/Content/MyScripts")
    @Scripts.Render("~/Content/TableScripts")
    @Html.Partial("_Toastr")
}

Esta es mi vista Modal:
@model MaterialViewModel

@{
    ViewBag.Title = "Nuevo material";
    Layout = null;
}

<link href="~/Content/css/fileUpload.css" rel="stylesheet" />

<link href="~/Content/popup/popupstyle.css" rel="stylesheet" />

        xxxxx
        <button type="button" class="close panelTitleTxt glyphicon glyphicon-remove landing-icon" data-dismiss="modal" aria-hidden="true"></button>

@using (Html.BeginForm("CreateForCategory", "CategoriasMateriales", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()

        @Styles.Render("~/Content/toastr")

            @Html.HiddenFor(x => x.CategoriaId)
            @Html.ValidationSummary(true, "", new {@class = "text-danger"})

                @Html.LabelFor(model => model.CategoriaId, htmlAttributes: new {@class = "control-label col-sm-3 popup-labelfont"})

                    @Html.DropDownListFor(x => x.CategoriaId, Model.CategoriasMaterialViewModel, new {@class = "form-control", @disabled = "disabled"})
                    @Html.ValidationMessageFor(model => model.CategoriaId, "", new {@class = "label label-danger"})

                @Html.LabelFor(model => model.Descripcion, htmlAttributes: new {@class = "control-label col-sm-3 popup-labelfont"})

                    @Html.EditorFor(model => model.Descripcion, new {htmlAttributes = new {@class = "form-control", maxlength = "200"}})
                    @Html.ValidationMessageFor(model => model.Descripcion, "", new {@class = "label label-danger"})

                @Html.Label("Imagen", htmlAttributes: new {@class = "control-label col-sm-3 popup-labelfont"})

                        <input type="text" class="form-control image-preview-filename" disabled="disabled">

                            <button type="button" class="btn btn-danger image-preview-clear" style="display: none;">
                                 Clear
                            </button>

                                Browse
                                <input type="file" accept="image/png, image/jpeg, image/gif" name="upload" />

                    <input class="btn btn-success" id="btnSave" type="submit" value="Guardar"/>
                    <input aria-hidden="true" class="btn btn-md btn-warning" data-dismiss="modal" id="btncancel" type="button" value="Cancelar"/>

                @Scripts.Render("~/bundles/toastr")
                @Html.Partial("_Toastr")

}

Si alguien tiene alguna idea como solucionar esto les agradecería demasiado su apoyo.

A: Olvidaste pasar el parámetro dataType, el cuál determina el tipo de datos que estás esperando como respuesta, en este caso el valor es json.
Así quedaría el código:
$('form').submit(function () {
  var $form = $(this);
  $.ajax({
    url: this.action,
    type: this.method,
    contentType: this.enctype,
    dataType: 'json',
    data: $(this).serialize(),
    success: function (result) {
        if (result.success) {
            $('#myModal').modal('hide');
            //Refresh
            //location.reload();
            $('#replacetarget').load(result.url);
        } else {
            $('#myModalContent').html(result);
            //bindForm();
        }
    }
  });
});

Documentación de jQuery:

dataType (default: Intelligent Guess (xml, json, script, or html))
Type: String
The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).

A: Intenta hacer un result = JSON.parse(result) antes de hacer el if(result.success).


text:
Q: Parse and Play a .pls file in Android can anybody help me how to parse and play this .pls file in android
 [playlist]
 NumberOfEntries=1
 File1=http://stream.radiosai.net:8002/

A: A quick search resulted in this very basic PlsParser from the NPR app that, by the looks of it, will simply parse the .pls file and return all embedded URLs in a list of strings. You'll probably want to take a look at that as a starting point.
After that, you should be able to feed the URL to a MediaPlayer object, although I'm not completely sure about what formats/protocols are supported, or what limitations might apply in the case of streaming. The sequence of media player calls will look somewhat like this.
MediaPlayer mp = new MediaPlayer();
mp.setDataSource("http://stream.radiosai.net:8002/");
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.prepare(); //also consider mp.prepareAsync().
mp.start();

Update: As far as I can tell, you can almost literally take the referenced code and put it your own use. Note that the code below is by no means complete or tested.
public class PlsParser {
        private final BufferedReader reader;

        public PlsParser(String url) {
            URLConnection urlConnection = new URL(url).openConnection();
            this.reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
        }

        public List<String> getUrls() {
            LinkedList<String> urls = new LinkedList<String>();
            while (true) {
                try {
                    String line = reader.readLine();
                    if (line == null) {
                        break;
                    }
                    String url = parseLine(line);
                    if (url != null && !url.equals("")) {
                        urls.add(url);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return urls;
        }

        private String parseLine(String line) {
            if (line == null) {
                return null;
            }
            String trimmed = line.trim();
            if (trimmed.indexOf("http") >= 0) {
                return trimmed.substring(trimmed.indexOf("http"));
            }
            return "";
        }
}

Once you have that, you can simply create a new PlsParser with the url of the .pls file and call getUrls afterwards. Each list item will be a url as found in the .pls file. In your case that'll just be http://stream.radiosai.net:8002/. As said, you can then feed this to the MediaPlayer.


text:
Q: Doing the actual integration in the error-function. I got a question. The error-function is defined as:
$erfc(z)=\frac{2}{\sqrt{\pi}}\int_0^zdw\exp(-w^2)$.
How do I do the actual integration? I can't simply say that
$\frac{2}{\sqrt{\pi}}\int_0^zdw\exp(-w^2)=\frac{2}{\sqrt{\pi}}[-\frac{1}{2w}\exp(-w^2)]_0^z$, right? Because I can't evaluate it at w=0.
In my workbook there's a hint to look at it as a line integral, but I don't know how to approach it with that.
The general form of a line integral is $\int_\mathbb{C}f(z)dz=\int_a^bf(r(t))|r'(t)|dt$, but what would be my $r(t)$ in this case?
Any help would be appreciated.


text:
Q: How to use js to detect html width more than viewport width? My question is I am designing a responsive website. Used a slider plugin, but have a problem which is when I resize the window from more than 561px to less than 561px will be appear the viewport width more than 100%. I think it is a plug-in bugs, but the plug-in is useful. So I have an idea that is detect the resize event "if($(window).width() < 561)" plus check the viewport width is more than 100% (that's mean appear vertical scroll bar), then run reload whole page function.
Can you guys give me tips about detect viewport width more than 100% then do somethings?
Here is my web page which has this issue: click here

A: Not sure if I understand completely, but if you just need to know when the body is wider than the html, just watch window.scrollMaxX:
if (window.scrollMaxX > 0) {
    // do something
}

Like so: https://codepen.io/anon/pen/pPqMGe

A: This little script checks if the current width is less then 561 and document width is bigger than the viewport width.
if (document.body.clientWidth < 561 &&
    document.body.clientWidth > window.outerWidth) {

    // do reload
}


text:
Q: Changing backlink URL in Devise Mails When the user requests a reset-link sent to his email using Devise views, he receives an email  with this content:

Hello example@gmail.com!
  Someone has requested a link to change your password. You can do this through the link below.
  Change my password
  (which points to)
  localhost:3000/users/password/edit?reset_password_token=some_token
  If you didn't request this, please ignore this email.
  Your password won't change until you access the link above and create a new one.

Now, this is all cool and dandy, except when I host the rails server on a different port, say
rails server -p 5678

Then the link still points to localhost:3000.
I know about request.ip and request.port, but I cannot find out where to change the Devise mailer objects. The relevant part of the mail-template used for this mail is
<%= link_to 'Change my password', edit_password_url(@resource, reset_password_token: @token) %>

After debugging, it seems @resource is a User-object and this contains no URL.
Long story short: How can I make the url (ip/port part) of Devise mails be dynamic?


text:
Q: Using the same algorithm twice with no new caption number I'm trying to do something similar to "Using the same figure twice with no new number", but with the algorithm2e package.
Therefore I wrote the following code.
\newcommand{\repeatAlgoCaption}[2]{%
    \renewcommand{\thealgocf}{\ref{#1}}% modify the displayed label
    \captionsetup{list=no}% not displayed in the list of algorithms
    \caption{#2 (repeated from page~\pageref{#1})}% page reference of the original algorithm
    \addtocounter{algocf}{-1}% the next figure after the repeat gets the right number
}

Using this code with hyperref produces the following error
! Argument of \reserved@a has an extra }.
<inserted text>
              \par

I have no clue how to get this to work, any suggestion is appreciated.
This is my working MWE (without hyperref)
\documentclass{article}

\usepackage{caption}
\usepackage{algorithm2e}

% from https://tex.stackexchange.com/questions/200211/
\newcommand{\repeatAlgoCaption}[2]{%
    \renewcommand{\thealgocf}{\ref{#1}}% modify the displayed label
    \captionsetup{list=no}% not displayed in the list of algorithms
    \caption{#2 (repeated from page~\pageref{#1})}% page reference of the repeted algorithm
    \addtocounter{algocf}{-1}% the next figure after the repeat gets the right number
}

% \usepackage{hyperref}% The one guilty

% arara: pdflatex
% arara: pdflatex
\begin{document}

\begin{algorithm}[H]
\caption{my caption}\label{alg:mylabel}
\end{algorithm}

\begin{algorithm}[H]
\caption{my other caption}
\end{algorithm}

\begin{algorithm}[H]
\repeatAlgoCaption{alg:mylabel}{my caption}
\end{algorithm}

\begin{algorithm}[H]
\caption{my other caption}
\end{algorithm}

\end{document}

The output is

A: One could save the contents of \thealgoc (using an extra macro) instead of using \ref (or \ref*), for example:
\documentclass{article}

\usepackage{caption}
\usepackage{algorithm2e}

\makeatletter
\newcommand\saveAlgoCounter[1]{%
    \expandafter\xdef\csname saveAlgoCounter@#1\endcsname{\thealgocf}}% save \thealgocf
\newcommand{\repeatAlgoCaption}[2]{%
    \expandafter\let\expandafter\thealgocf\csname saveAlgoCounter@#1\endcsname% use saved \thealgocf
    \captionsetup{list=no}%
    \caption{#2 (repeated from page~\pageref{#1})}% page reference of the repeted algorithm
    \addtocounter{algocf}{-1}% the next figure after the repeat gets the right number
}
\makeatother

\usepackage[hypertexnames=false]{hyperref}% The one guilty
% "hypertexnames=false" prevents the warning "destination with the same identifier (name{algocf.1}) has been already used, duplicate ignored"

% arara: pdflatex
% arara: pdflatex
\begin{document}

\begin{algorithm}[H]
\caption{my caption}\label{alg:mylabel}
\saveAlgoCounter{alg:mylabel}
\end{algorithm}

\begin{algorithm}[H]
\caption{my other caption}
\end{algorithm}

\begin{algorithm}[H]
\repeatAlgoCaption{alg:mylabel}{my caption}
\end{algorithm}

\begin{algorithm}[H]
\caption{my other caption}
\end{algorithm}

\end{document}