text:
Q: Select data within a time period by Sqlite I am trying to count/select the data field within a time period. When using the following format, where I explicit specify the whole timestamp, the query is correct.
SELECT TimeStamp,strftime('%Y',TimeStamp) as "Year",
strftime('%m',TimeStamp) as "Month",
strftime('%d',TimeStamp) as "Day",
strftime('%M',TimeStamp) as "Minute",
strftime('%H', TimeStamp) as "Hours"
FROM temp
WHERE TimeStamp between '2017-12-22T20:50:00' and '2017-12-23T21:00:00'

What I tried to do is select field with timestamp within a certain hours. So I modify my query as:
SELECT TimeStamp,strftime('%Y',TimeStamp) as "Year",
strftime('%m',TimeStamp) as "Month",
strftime('%d',TimeStamp) as "Day",
strftime('%M',TimeStamp) as "Minute",
strftime('%H', TimeStamp) as "Hours"
FROM temp
WHERE strftime('%H', TimeStamp) between 20 and 21

Then the query returns 0 row, where do I do wrong ?
My timestamp format follows the sqlite convention as YYYY-mm-dd HH:MM:SS.3u.
Here is an example for my timestamp: 2017-12-22T20:57:02.188Z

A: SELECT TimeStamp,strftime('%Y',TimeStamp) as "Year",
strftime('%m',TimeStamp) as "Month",
strftime('%d',TimeStamp) as "Day",
strftime('%M',TimeStamp) as "Minute",
strftime('%H', TimeStamp) as "Hours"
FROM temp
WHERE cast(strftime('%H', TimeStamp) as int) between 20 and 21

strftime returns a string, you compare to ints. cast the string as int to solve that

A: Your instruction strftime('%H', TimeStamp) is considered as a string. Thus it can't be compared to integers. You need to explicitly cast it as an int.
CAST(strftime('%H', TimeStamp) AS INT)


text:
Q: Pass connection string to dbcontext for Sqlite I would like to pass the connection string to my dbcontext model.
I'm using the Microsoft.EntityFrameworkCore.Sqlite package.
public void ConfigureServices(IServiceCollection services)
{
    //Adds Entity FrameWork for SqlLite
    var config = Configuration.GetConnectionString("DefaultConnection");
    //How to pass the connection string, AddEntityFrameworkSqlite take no extra parameters
    //services.AddEntityFrameworkSqlite().AddDbContext<ETLDataBase>(opt => opt.????)
    services.AddEntityFrameworkSqlite().AddDbContext<ETLDataBase>();
    services.AddMvc();

    services.AddScoped<IRepository<User>, AccountRepository>();
}

I didn't find a way to access to the ContentRootPath directly in the my dbcontext. I hardcoded the path of my DB in the appsettings.json, but even like this I can't pass the path to my model.
Here's my context model:
public class ETLDataBase: DbContext
{
    public ETLDataBase(DbContextOptions<ETLDataBase> options)
        : base(options)
    {}
    public DbSet<Datasouce> Datasources { get; set; }
    public DbSet<User> Users { get; set; }
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        // I want to get my connection string in here
        //I can't access to the env.ContentRootPath
        var connection = new SqliteConnection(connectionString);

        optionsBuilder.UseSqlite(connection);
    }
}

EDIT
If I do it like this in the Startup.cs:
services.AddEntityFrameworkSqlite().AddDbContext<ETLDataBase>(options=> options.UseSqlite(Configuration["ConnectionStrings:DefaultConnection"]));
And I remove the OnConfiguring function in the ETLDataBase class.
I have this error:
No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions<TContext> object in its constructor and passes it to the base constructor for DbContext.

redpajama_set_name: RedPajamaStackExchange


text:
Q: NodeJs: Whenever checkbox is checked I wanted them to be added to my VerificationData setter I need help on how to add data on my array whenever one/or many of them are checked.
const [data, setData] = useState([]);

{
    verifications.map(record => {
        console.log(verifications)
        return(
            <Col xs={12} md={3} mb={3}>
                <Form.Group key={record.id} className="mb-3" controlId={record.verifyName}>
                      <Form.Check value={record.verifyName} label={record.verifyName} />
                  </Form.Group>
            </Col>

            )
    })
}

Example:
• First Name
• Last Name
• Address
If I checked on first name and address, they will be added to my state setter for data.
Appreciate your help.

A: You need to have an onChange event inside the check input and call setData function to set value. Here an example
const [data, setData] = useState([]);

  useEffect(() => {
    console.log(data);
  }, [data]);

  return (
    <div>
      <input
        type="checkbox"
        value="Rahul"
        name="firstName"
        onChange={e => setData([...data, e.target.value])}
      />
    </div>

A: What works at the moment is this:
<Form.Group
key={record.id}
className="mb-3"
controlId={record.verifyName}>

<Form.Check onChange={e=>{
    const value = e.target.value
    collection.push(value);
    console.log(collection)}}
    tag="verify"
    value={record.verifyName}
    label={record.verifyName} />

</Form.Group>

However, whenever the value is clicked multiple times, it keeps on adding. I've tried to add a conditional statement but doesn't do anything not sure if it's correct.
if(value.checked == true) {
collection.push(value)
}

I guess the reason was because I'm targetting it's value not the object? Any help?


text:
Q: Get an element from a Hashtbl in OCaml I'm quite new in OCaml so it's quite complicated for me to use right now an existing code but I unfortunately need it.
I've got a variable declared as follow:
val var_of_string : (string, int) Hashtbl.t

And I would like to get an element and display it inside a function.
let rec string_of_id n = match DynArray.get id_to_fml n with
    Lit -> (if n land 1 == 0 then
              string_of_int (Hashtbl.find var_of_string string_of_int(n))
            else
              "-" ^ string_of_int (Hashtbl.find var_of_string string_of_int(n))
           )
  | And ids ->
      (match ids with
       [] -> "#true#"
     | _ -> "(" ^ String.concat " & " (List.map string_of_id ids) ^ ")")
  | Or ids ->
      (match ids with
       [] -> "#false#"
     | _ -> "(" ^ String.concat " | " (List.map string_of_id ids) ^ ")")
  | Dia (r, n) -> "<" ^ string_of_int r ^ ">" ^ string_of_id n
  | Box (r, n) -> "[" ^ string_of_int r ^ "]" ^ string_of_id n
  | True -> "true"
  | False -> "false"

Basically, the only important part is :
    Lit -> (if n land 1 == 0 then
              string_of_int (Hashtbl.find var_of_string string_of_int(n))
            else
              "-" ^ string_of_int (Hashtbl.find var_of_string string_of_int(n))
           )

I've got an integer n (that can become a string) and I've got a hashtable string ; int. I would like to be able to get the element at the n-th case of the Hashtable but I don't know how to do this :/
I tried Hashtbl.find var_of_string nby looking at the documentation but I get this error message :
Error: The implementation syntax.ml does not match the interface syntax.cmi:
       Values do not match:
         val var_of_string : (int, string) Hashtbl.t
       is not included in
         val var_of_string : (string, int) Hashtbl.t
       File "syntax.ml", line 55, characters 4-17: Actual declaration

Looks like I do something in a wrong way, but I have no idea how to do it :/
Thanks in advance for your help !

A: It is a bad habit to use (==) for integer comparison. Use (=), the structural comparison instead.  (==) is the physical comparison using pointers. For integers, they are the same, but generally they behave differently. Careless use of (==) will shoot your foot badly one day.
val var_of_string : (string, int) Hashtbl.t  is a table whose keys are string.  You can add/replace/remove/find int values using string keys.  In your code you do opposite: trying to find string values using int keys.  It is wrong.  You need a table, say, string_of_var of type (int, string) Hashtbl.t if you want to query the name of your variable from its id number.
One possible way is to build this reverse table from var_of_string.  It is easily done by iterating the bindings in var_of_string using Hashtbl.iter.  But if you could build string_of_var directly without using var_of_string, it would be better for code clarity and performance.  Without enough background we cannot tell which is the best for you.

A: Your Hashtable has key a string and value an integer.
Hashtable.find has the following signature:
val find : ('a, 'b) t -> 'a -> 'b

see http://caml.inria.fr/pub/docs/manual-ocaml/libref/Hashtbl.html
you are attempting to use Hashtable.find on a value.


text:
Q: Taylor expansion of $\frac{1}{(x^2-2x+17)^2}$ at point $c=1$ Taylor expansion of $$\frac{1}{(x^2-2x+17)^2}$$ at point $c=1$ ?
My attempt: $y = x -c = x-1$ so $x = y +1 $.
When we substitute this we get the expression $\frac{1}{(x^2+16)^2}$. Now, I have the formula $(1+x)^\alpha = \sum_{n=0}^{\infty}{\binom{\alpha}{n}x^n},\lvert x \rvert < 1$
I was wondering if I could write my expression as $4((\frac{x}{4})^2+1)^{-2}$ and apply the formula, or should I take a different approach? Am I even allowed to do that?

A: Let $z=(x-1)$
\begin{eqnarray*}
\frac{1}{(x^2-2x+17)^2}=\frac{1}{(z^2+16)^2} =\frac{1}{16^2} \left(1+\frac{z^2}{16} \right)^{-2}
\end{eqnarray*}
$\left(1+\frac{z^2}{16} \right)^{-2}$ is now ripe to apply the binomial expansion
\begin{eqnarray*}
\left(1+\frac{z^2}{16} \right)^{-2}= 1+(-2) \frac{z^2}{16}+\frac{(-2)(-2-1)}{2!}\left(\frac{z^2}{16} \right)^{-2}+\cdots
\end{eqnarray*}
and so we have
\begin{eqnarray*}
\frac{1}{(x^2-2x+17)^2}=\frac{1}{16^2} \left(1-\frac{(x-1)^2}{8} +\frac{3(x-1)^4}{16^2} +\cdots \right)
\end{eqnarray*}
and this series is valid provided $ \mid x-1 \mid <4$.


text:
Q: Difference between old Nearby and new Sightings? Recently, Pokemon Go released an update featuring a reworked Pokemon detection system -- changing "Nearby" to "Sightings".
Is there any difference between the two?

A: Nearby now shows the pokemon near a pokestop. Sightings shows pokemon that are surrounding you.
As you can see here: How does the nearby tab work in Pokemon Go (after 2nd update)?


text:
Q: Generics with Higher Order Function I want to create a function that returns a constructor function for one of my existing React
components. The return value is a customized class extension of the passed-in function component.
With other words:
The return value of my higher-order function withObservableStream() - it returns another
function - takes an existing React component (which has typed props) and returns a constructor function of a new one
which should be eventually rendered into the DOM. Since I am only extending the passed in component with
an RxJS subscription both components will share identical props.
The type system should:

*

*Complain about a property mismatch

How can I achieve that - who can show me the magic of 'genericism'? Is this possible?
type Props = Triggers & InitialState;

function App(props: Props) {
  return <button
  onClick={(event) => {
    props.onClick(event);
  }}
  >{props.text} (state: {props.counterX})</button>;
}

// still all good here:
const appInstance = App({...triggers, text: "init", counterX: -1});

const WrappedApp = withObservableStream(
  interval(5000).pipe(
    map((o) => ({counterX: o})),
  ),
  {...triggers},
  {
    // counterX: -1,
    text: "XXX",
  },
)(App);
// type sytem should complain meaningful here:
// 2nd & 3rd parameter of observableStream() should match the constructor signature of App (type Props)
// for both new WrappedApp(...) and render(<WrappedApp...)

Full code sample on stackblitz.

A: I modified your code to add the desired type restriction.
Basically you need to add generic types down to the returned functions of withObservableStream:
withObservableStream.tsx
import React from "react";
import Observable from "rxjs";

export default <T extends Observable.Observable<any>, U, V>(observable: T, triggers: U, initialState: V) => {
  type cState = U & V;
  return function(Component: React.ComponentType<cState>) {

    return class extends React.Component<cState, V> {
      private subscription: any;

      constructor(props: cState) {
        console.log("got props", props);
        super(props);

        this.state = {
          ...initialState,
        };
        console.log(this.state);
      }

      public componentDidMount() {
        console.log("Subscribing...");
        this.subscription = observable.subscribe((newState) => {
          console.log("setting a new state...", newState);
          this.setState({ ...newState });
          console.log("state: ", this.state);
        });
      }

      public componentWillUnmount() {
        console.log("Unsubscribing...");
        this.subscription.unsubscribe();
      }

      public render() {
        return (
          <Component {...this.props} {...this.state} {...triggers} />
        );
      }
    }
  };
};

index.tsx
import React from "react";
import { render } from "react-dom";
import { interval } from "rxjs";
import { map } from "rxjs/operators";
import withObservableStream from "./withObservableStream";

type Triggers = {
  onClick(event: React.MouseEvent<HTMLButtonElement>): void,
};

type InitialState = {
  text: string,
  counterX: number,
};

type Props = Triggers & InitialState;

export function App(props: Props) {
  return <button
  onClick={(event) => {
    props.onClick(event);
  }}
  >{props.text} (state: {props.counterX})</button>;
}

const triggers: Triggers = { onClick: () => console.log("clicked!!!") };

const appInstance = App({...triggers, text: "init", counterX: -1});
render(appInstance, document.getElementById("root1"));

const WrappedApp = withObservableStream(
  interval(5000).pipe(
    map((o) => ({counterX: o})),
  ),
  {...triggers},
  {
    counterX: -1,
    text: "XXX",
  },
)(App);

const appInstance2 = new WrappedApp({...triggers, counterX: -1, text: "23"});

render(<WrappedApp {...triggers} counterX={-1} text="23"/>,  document.getElementById("root1"))
document.getElementById("root2"));

Check out running code here: stackblitz.


text:
Q: Record video in background and also when screen is turned off I'm trying to create a Background Video Recording android application where a video is recorded in background (When app is not in foreground) and also when the screen is turned off. I've found some applications in the PlayStore that can carry out this function, so I believe this is doable.
PlayStore App
I have tried to implement this using a Service and an Activity. The activity has two buttons and a SurfaceView. When I click Start Recording button the service starts recording the video using the MediaRecorder and application gets in background. When I open the application again from background to stop the video recording and click on Stop Recording button then the app crashes with following log. I have searched on here and I have find different code related to this but I couldn't find any solution that helped me with this.
08-13 22:04:50.085 24729-24729/com.meowme.camerarecorder E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.meowme.camerarecorder, PID: 24729
    java.lang.RuntimeException: Unable to stop service com.meowme.camerarecorder.RecorderService@38a64c2: java.lang.IllegalStateException
        at android.app.ActivityThread.handleStopService(ActivityThread.java:3727)
        at android.app.ActivityThread.-wrap27(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1806)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6940)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
     Caused by: java.lang.IllegalStateException
        at android.media.MediaRecorder._stop(Native Method)
        at android.media.MediaRecorder.stop(MediaRecorder.java:1306)
        at com.meowme.camerarecorder.RecorderService.stopRecording(RecorderService.java:164)
        at com.meowme.camerarecorder.RecorderService.onDestroy(RecorderService.java:92)
        at android.app.ActivityThread.handleStopService(ActivityThread.java:3709)
        at android.app.ActivityThread.-wrap27(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1806)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6940)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)

CameraRecorder.java
public class CameraRecorder extends Activity implements SurfaceHolder.Callback {

    private static final String TAG = CameraRecorder.class.getSimpleName();

    public static final int RequestPermissionCode = 7;

    public static SurfaceView mSurfaceView;
    public static SurfaceHolder mSurfaceHolder;
    public static Camera mCamera;
    public static boolean mPreviewRunning;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (CheckingPermissionIsEnabledOrNot()) {
            initializeMainActivity();
        } else {
            RequestMultiplePermission();
        }

    }

    private void initializeMainActivity() {
        setContentView(R.layout.main);

        mSurfaceView = findViewById(R.id.surfaceView1);
        mSurfaceHolder = mSurfaceView.getHolder();
        mSurfaceHolder.addCallback(this);
        mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

        Button btnStart = findViewById(R.id.StartService);
        btnStart.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent(CameraRecorder.this, RecorderService.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startService(intent);
                finish();
            }
        });

        Button btnStop = findViewById(R.id.StopService);
        btnStop.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                stopService(new Intent(CameraRecorder.this, RecorderService.class));
            }
        });

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {

    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
    }

    public boolean CheckingPermissionIsEnabledOrNot() {

        int FirstPermissionResult = ContextCompat.checkSelfPermission(getApplicationContext(), CAMERA);
        int SecondPermissionResult = ContextCompat.checkSelfPermission(getApplicationContext(), RECORD_AUDIO);
        int ThirdPermissionResult = ContextCompat.checkSelfPermission(getApplicationContext(), WRITE_EXTERNAL_STORAGE);

        return FirstPermissionResult == PackageManager.PERMISSION_GRANTED &&
                SecondPermissionResult == PackageManager.PERMISSION_GRANTED &&
                ThirdPermissionResult == PackageManager.PERMISSION_GRANTED;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {

            case RequestPermissionCode:

                if (grantResults.length > 0) {

                    boolean CameraPermission = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                    boolean RecordAudioPermission = grantResults[1] == PackageManager.PERMISSION_GRANTED;
                    boolean ExternalStoragePermission = grantResults[2] == PackageManager.PERMISSION_GRANTED;

                    if (CameraPermission && RecordAudioPermission && ExternalStoragePermission) {

                        Toast.makeText(CameraRecorder.this, "Permission Granted", Toast.LENGTH_LONG).show();
                        // TODO show activity here..
                        initializeMainActivity();
                    }
                     else {
                        Toast.makeText(CameraRecorder.this, "Permission Denied", Toast.LENGTH_LONG).show();
                        finish();
                    }
                }

                break;
        }
    }

    private void RequestMultiplePermission() {

        // Creating String Array with Permissions.
        ActivityCompat.requestPermissions(CameraRecorder.this, new String[]
                {
                        CAMERA,
                        RECORD_AUDIO,
                        WRITE_EXTERNAL_STORAGE,
                }, RequestPermissionCode);

    }

}

RecorderService.java
public class RecorderService extends Service {

    private static final String TAG = "RecorderService";
    private SurfaceView mSurfaceView;
    private SurfaceHolder mSurfaceHolder;
    private static Camera mServiceCamera;
    private boolean mRecordingStatus;
    private MediaRecorder mMediaRecorder;

    @Override
    public void onCreate() {
        mRecordingStatus = false;
        mServiceCamera = CameraRecorder.mCamera;
        mSurfaceView = CameraRecorder.mSurfaceView;
        mSurfaceHolder = CameraRecorder.mSurfaceHolder;

        super.onCreate();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);

        if (mRecordingStatus == false)
            startRecording();

        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        stopRecording();
        mRecordingStatus = false;

        super.onDestroy();
    }

    public boolean startRecording() {
        try {
            Toast.makeText(getBaseContext(), "Recording Started", Toast.LENGTH_SHORT).show();

            mServiceCamera = Camera.open();
            Camera.Parameters params = mServiceCamera.getParameters();
            mServiceCamera.setParameters(params);
            Camera.Parameters p = mServiceCamera.getParameters();

            final List<Size> listPreviewSize = p.getSupportedPreviewSizes();
            for (Size size : listPreviewSize) {
                Log.i(TAG, String.format("Supported Preview Size (%d, %d)", size.width, size.height));
            }

            Size previewSize = listPreviewSize.get(0);
            p.setPreviewSize(previewSize.width, previewSize.height);
            mServiceCamera.setParameters(p);

            try {
                mServiceCamera.setPreviewDisplay(mSurfaceHolder);
                mServiceCamera.startPreview();
            } catch (IOException e) {
                Log.e(TAG, e.getMessage());
                e.printStackTrace();
            }

            mServiceCamera.unlock();

            mMediaRecorder = new MediaRecorder();
            mMediaRecorder.setCamera(mServiceCamera);
            mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
            mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
            mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
            mMediaRecorder.setOutputFile(Environment.getExternalStorageDirectory().getPath() + "video" + System.currentTimeMillis() + ".mp4");
            mMediaRecorder.setPreviewDisplay(mSurfaceHolder.getSurface());

            mMediaRecorder.prepare();
            mMediaRecorder.start();

            mRecordingStatus = true;

            return true;

        } catch (IllegalStateException e) {
            Log.d(TAG, e.getMessage());
            e.printStackTrace();
            return false;

        } catch (IOException e) {
            Log.d(TAG, e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    public void stopRecording() {
        Toast.makeText(getBaseContext(), "Recording Stopped", Toast.LENGTH_SHORT).show();
        try {
            mServiceCamera.reconnect();

        } catch (IOException e) {
            e.printStackTrace();
        }

        mMediaRecorder.stop();
        mMediaRecorder.reset();

        mServiceCamera.stopPreview();
        mMediaRecorder.release();

        mServiceCamera.release();
        mServiceCamera = null;
    }
}

main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/StartService"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="5dp"
        android:background="#5699e6"
        android:padding="16dp"
        android:text="Start Recording"
        android:textColor="#fff"
        android:textSize="15sp">

    </Button>

    <Button
        android:id="@+id/StopService"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="5dp"
        android:background="#5699e6"
        android:layout_marginBottom="16dp"
        android:padding="16dp"
        android:text="Stop Recording"
        android:textColor="#fff"
        android:textSize="15sp"></Button>

    <SurfaceView
        android:id="@+id/surfaceView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

    </SurfaceView>

</LinearLayout>

It would be really helpful if anyone can just guide me on how I can solve this issue.

A: A quick look at your crash log tells me that most likely, this happens when you close down the service. In "stopRecording()" you call mMediaRecorder.stop() and it looks like it is already stopped, since it throws an IllegalStateException.
Check if the media recorder is running before stopping it.

A: please use this code its work for me
        mMediaRecorder.setOutputFile(
                Environment.getExternalStorageDirectory()+"/"+
                        DateFormat.format("yyyy-MM-dd_kk-mm-ss", new Date().getTime())+
                        ".mp4"
        );


text:
Q: Adding a table line to the row I  have several php generated tables like below, and I tried to add a table line on the 3rd and 4th row but I failed.
What I tried is this:

table.tbc td:nth-child(3) {
  border-bottom: 0.12em solid #000000;
}

    A

    B

    A

    E

How can I do this? I know this is an unusual table structure.

A: If I understand you correctly, you want to add a border between the 3rd and 4th trs. If so, the right selector is table.tbc tr:nth-child(3) td

table.tbc tr:nth-child(3) td {
  border-bottom: 0.12em solid #000000;
}

    A

    B

    A

    E


text:
Q: How to calculate $\lim _{x\to \infty} x^2\int _0 ^x e^{t^3-x^3}dt $ What is $$\lim _{x\to \infty}  x^2\int _0 ^x e^{t^3-x^3}dt $$ I think  $e^{t^3} $ is doesnt have an elenentary antiderivative so Fundamental theorem of calculus is to be used . But its in product with $x^2$ and also its not an indeterminate form so I dont know what to do?

A: Hint. Note that
$$x^2\int _0 ^x e^{t^3-x^3}dt=\frac{\int _0 ^x e^{t^3}dt}{e^{x^3}/x^2}$$
and both numerator and denominator go to infinity as $x\to+\infty$.

A: Put $\;\int e^{t^3}dt=F(t)\;$ , so
$$x^2\int_0^x e^{t^3-x^3}dt=\frac{x^2}{e^{x^3}}\left(F(x)-F(0)\right)$$
and now apply l'Hospital (why can we?):
$$\lim_{x\to\infty}\frac{x^2F(x)}{e^{x^3}}=\lim_{x\to\infty}\frac{2F(x)+x^2e^{x^3}}{3x^2e^{x^3}}=\frac13$$

A: Notice that:
$$\int_0^x e^{t^3}dt=-\frac{x \Gamma \left(\frac{1}{3},-x^3\right)}{3
   \sqrt[3]{-x^3}}-(-1)^{2/3} \Gamma
   \left(\frac{4}{3}\right)$$
So you have:
$$y(x)=-\frac{x^2}{e^{x^3}}\left[\frac{x \Gamma \left(\frac{1}{3},-x^3\right)}{3
   \sqrt[3]{-x^3}}+(-1)^{2/3} \Gamma
   \left(\frac{4}{3}\right) \right]$$
For $x \rightarrow+\infty$ we have: $$\lim_{x \rightarrow + \infty}y(x)=\frac{1}{3}$$


text:
Q: Multer Does not upload files So what i am doing here is
1.Upload file using filrreader and save blob as string in array
const reader=new FileReader()
reader.readAsDataURL(file)

2.pass the array to service
this.postService.onAddPost(
this.form.value.title,
this.form.value.content,
this.imagesObject
)

3.in service append it in formdata
    onAddPost(title:string,content:string,imagesObject:Array<string>){
        const postData=new FormData()
        postData.append("title",title)
        postData.append("content",content)
        for (var i = 0; i < imagesObject.length; i++) {
            // postData.append("images",imagesObject[i])
            postData.append("images",imagesObject[i])
        }
postData.forEach((value, key) => {
            console.log(key, value);
        })
        this.http.post<{message:string,postId:String}>('http://localhost:3000/api/posts',postData)

4.at post express backend trying to save in multer
var upload=multer({storage:storage})
router.post('',upload.fields([{name:'images'}]),(req,res,next)=>{
    const post= new Post({
        title:req.body.title,
        content:req.body.content
    })
    post.save().then(createdPost=>
        res.status(200).json({
            message:'Post added sucessfully',
            postId:createdPost._id,

        })
    )
})

by this the multer should upload the files.
I don't know what i am doing wrong?
Thanks
link to complete project on github
Project Link
Chrome network->formadata


text:
Q: Ajax request works in remote server but not in local server (with Codeigniter) I've a web application wich makes Ajax requests to a server with Codeigniter-php code. The Ajax requests work correctly in local server but not when the application is hosted in remote server.
The console errors are:
XMLHttpRequest cannot load http://localhost/CI-example/index.php/control/controlHome. Origin http://www.page.com is not allowed by Access-Control-Allow-Origin.

Surprisingly, the request is made in the server but not the response.
The URL that I use to Ajax request is:
AJAX_URL = "http://localhost/CI-example/site/index.php/control/controlHome";

But, also I've tried with:
AJAX_URL = "http://www.page.com/CI-example/site/index.php/control/controlHome";

And the next error is captured:
POST http://www.page.com/webdom/site/index.php/control/controlHome 500 (Internal Server Error)

How can I do?
Edit:
www.page.com is a subdomain. Is necessary to do some configuration when a subdomain is used to Ajax request?
And the folders organization is:
/CI-example
---/application/controllers/control.php
---/system
---/site/js/ajaxRequest.js

A: As I am getting here, while you are sending ajax requests to the server than it's returning 500 (Internal Server Error). I'm sure that the error is from server side, and there may be following reason-

*

*If everything is fine in the codes, then may be your base_url is different from what you are requesting. Yes this can cause the problem, for example if you have hosted your web application and your base_url is www.mysite.com and you are requesting for mysite.com.

*Next reason may be, that you have developed your project in windows or any system which is in-case-sensitive but when you will upload to any linux like server than each and every file name will be case-sensitive. For example suppose a model file name you have given is MyModel.php but when you will load the model, it will generate the error like Unable to find  the specific class.

A: You cannot make HTTP POST requests using AJAX to a different domain, unless that page allows you to do so using a special header called "Access-Control-Allow-Origin".
localhost is different to page.com which is why this will not work.

A: Response on the http://www.page.com's url say something has gone wrong during the page execution. Your PHP error log should help you to find what.
Adding the line ini_set('display_errors', 1) might return the error to the ajax request, in the error handler. Don't forget to remove the line after use, you don't want this lying around in production code.

A: The second error is : 500 (Internal Server Error)
This means there was an error on the server side - not a cross-origin policy problem.
This is probably an error in the execution of your PHP script.
Check your error log (e.g : if you use the standard LAMP stack, the error log should be somewhere in /var/log/apache2/)

A: try this,
http://localhost/CI-example/index.php/control/controlHome

instead of
http://localhost/CI-example/site/index.php/control/controlHome

in your ajax URL.
As from your folder structure, there is no need to include "site" in your URL


text:
Q: jQTouch alternative for Android app Ok, I might bite the bullet and try a different framework for an iPhone app that I'm trying to port to Android. Built with jQTouch and Phonegap, it's just so sluggish on Android, with a number of issues such as inconsistent transitions and loading problems on newer Android API levels.
Looking for options for alternative frameworks that are more Android friendly, and importantly, not too much of a mountain to climb to adapt my existing code in to it as easily as possible.
As a jQTouch app, it's built with HTMl5, CSS, jQuery and Javascript with multiple RSS feeds, fixed tabbars, image gallery, Phonegap calendar plug in. jQuery Mobile would seem to be the most obvious choice, but I have found the tababars to be not quite as fixed as they climbed, (although maybe that has improved with the new release?). Are there any better alternatives?

A: Like you said jQuery Mobile is the most obvious choice. You can also look at Sencha Touch, Dojo Mobile, Kendo UI.


text:
Q: The android emulator activate all the sensors I need? I have a problem with an android app. The java files don't have any errors (only some warnings due to variables declared but not used) but when I execute it, in the logcat I have this issue 09-22 09:21:33.310: E/Trace(885): error opening trace file: No such file or directory (2) with the Emulator. With my devices GT-N7100 and Galaxy note II I have another error: Pause GC.
But surfing the internet I found on android developers and Samsung developers that probably is a Samsung bug with KNOX, only for my model. I also found that the error I got with the emulator is due because the emulator can't activate sensors I request for the localization services.
If the problem is the sensor not activated by the emulator, can I solve with rooting my smartphone and installing a ROM not based on official ROM but for example on cyanogenmod?
In this link I also paste all the logcat file: http://pastebin.com/y9xsCsfA


text:
Q: How to return an instance based on its parent using Simple Injector? We have been using Windsor Castle as our DI Container but we are looking around for alternatives. Now I got to the Simple Injector and so far I have been impressed by its simplicity but one scenario I am stuck at right now is when we are using late bound instantiation for some of our components.
My first question is, is it even possible?
With Windsor it is done like this;
Container.Register(Component.For<ILogger>()
    .UsingFactoryMethod(
        (kernel, componentModel, context) => new Logger(
            context.Handler.ComponentModel.Implementation.Name));

Is there a way to do the same with Simple Injector?

A: With Simple Injector, you will just have to either:

*

*Register a Func delegate explicitly using Register<Func<A, B, C>>((a, b) => { ... })

*Create an interface such as ILoggerFactory, creste an implementation and register them.

UPDATE
After reading your question again and looking up the definition of Castle's UsingFactoryMethod I came to the conclusion that I misinterpreted your question. What you are looking for is creating an instance based on its parent type: Context Based Injection.
You can achieve this by implementing the Context Based Injection Extension method that is given as example on the Simple Injector's documentation wiki.
When you add this extension method to your project you can do the equivalent registration as follows:
container.RegisterWithContext<ILogger>(context =>
{
    return new Logger(context.ImplementationType.Name);
});


text:
Q: arm_math matrix multiplication hardfault Not sure how to write this, since I'm very new to embedded systems, but I've been trying to code a state-observer for my graduation project and it needs to estimate 3 states on 2 different axis.
The basic equations I'm trying to solve are:
x_hat[k+1] = (A-L*C)*x_hat[k]+ B*u + L*y

The problem is I'm getting HardFault_Handler() when doing the (A-L*C)*x_hat[k] part for the second axis.
The code works on one of the axis, but it gets this error on the other.
They don't work separately either.
(Only showing code for the problematic axis)
Interrupt code: (800hz interrupts , dt = 1/800)
      placeholder[0]=(int16_t)L3GD20_GetAngularRateY(sensitivity_250,0);
      placeholder[1]=(int16_t)L3GD20_GetAngularRateZ(sensitivity_250,0);
      ydata[1]=placeholder[0]*3.14158/180;
      zdata[1]=placeholder[1]*3.14158/180;
      ydata[0]+=ydata[1]*dt;
      zdata[0]+=zdata[1]*dt;
      status = arm_mat_mult_f32(&Czm, &zdatam, &ZCm);         //C*y(estados)

      status = arm_mat_mult_f32(&ALCzm, &zhatantm, &ALCzantm);  //(A-LC)*yhatant
      status = arm_mat_scale_f32(&Bzm, uz, &Bzuzm);             //By*uy
      status = arm_mat_mult_f32(&Lzm, &ZCm, &Lzcm);             //L*Y(saida);
      status = arm_mat_add_f32(&ALCzantm, &Bzuzm, &ALCBzm);     //(A-LC)*yhatant + By*uy
      status = arm_mat_add_f32(&ALCBzm, &Lzcm, &deltazhatm);    //(A-LC)*yhatant + By*uy + L*Y

      //Integrating to obtain states

      zhat[0] += deltazhat[0]*dt;
      zhat[1] += deltazhat[1]*dt;
      zhat[2] += deltazhat[2]*dt;

      zhatant[0] = zhat[0];
      zhatant[1] = zhat[1];
      zhatant[2] = zhat[2];

      //Generate outputs
      status = arm_mat_mult_f32(&zhatm, &Kzm, &outzm);
      uz = -outz[0];

Initializing the matrices:
      arm_mat_init_f32(&zdatam, 3, 1, (float32_t *) zdata);
      arm_mat_init_f32(&Azm, 3, 3, (float32_t *) Az);
      arm_mat_init_f32(&Bzm, 3, 1, (float32_t *) Bz);
      arm_mat_init_f32(&Czm, 2, 3, (float32_t *) Cz);
      arm_mat_init_f32(&Kzm, 1, 3, (float32_t *) Kz);
      arm_mat_init_f32(&Lzm, 3, 2, (float32_t *) Lz);
      arm_mat_init_f32(&outzm, 1, 1, (float32_t *) outz);
      arm_mat_init_f32(&zhatm, 3, 1, (float32_t *) zhat);
      arm_mat_init_f32(&zhatantm, 3, 1, (float32_t *) zhatant);
      arm_mat_init_f32(&LCzm, 3, 3, (float32_t *) LCz);
      arm_mat_init_f32(&ALCzm, 3, 3, (float32_t *) ALCz);
      arm_mat_init_f32(&ALCzantm, 3, 1, (float32_t *) ALCzant);
      arm_mat_init_f32(&Bzuzm, 3, 1, (float32_t *) Bzuz);
      arm_mat_init_f32(&ZCm, 2, 1, (float32_t *) ZC);
      arm_mat_init_f32(&Lzcm, 3, 1, (float32_t *) Lzc);
      arm_mat_init_f32(&ALCBzm, 3, 1, (float32_t *) ALCBz);
      arm_mat_init_f32(&deltazhatm, 3, 1, (float32_t *) deltazhat);

float32_t ydata[3*1] = {0,0,0};
float32_t zdata[3*1] = {0,0,0};
float32_t placeholder[2*1] = {0,0};
float32_t LCy[3*3];
float32_t LCz[3*3];
float32_t ALCyant[3*1];
float32_t ALCzant[3*1];
float32_t Byuy[3*1];
float32_t Bzuz[3*1];
float32_t YC[2*1];
float32_t ZC[2*1];
float32_t Lyc[3*1];
float32_t Lzc[3*1];
float32_t yhat[3*1];
float32_t zhat[3*1];
float32_t yhatant[3*1];
float32_t zhatant[3*1];
float32_t ALCBy[3*1];
float32_t ALCBz[3*1];
float32_t deltayhat[3*1];
float32_t deltazhat[3*1];
float32_t outy[1*1];
float32_t outz[1*1];
float32_t uy;
float32_t uz;

//Y
const float32_t Ay[3*3] = {0, 1, 0,29.529, 0, 0.17903, -29.529, 0, -29.529};
const float32_t By[3*1] = {0, -3.0396, 4.8226};
const float32_t Cy[3*3] = {1, 0, 0, 0, 1, 0, 0, 0, 0};
const float32_t ALCy[3*3]= {-37.0458, -114.1644, 0, -15.2513, -1535.2383, 0.17903, -3030.1313, -305028.3011, -3030.1313};

//Z
const float32_t Az[3*3] = {0, 1, 0,29.527, 0, 0.17902, -29.527, 0, -29.527};
const float32_t Bz[3*1] = {0, -3.0394, 4.8226};
const float32_t Cz[3*3] = {1, 0, 0, 0, 1, 0};
const float32_t ALCz[3*3]= {-37.4149, -1249.709, 0, -5.5092, -1534.8692, 0.17902, -1140.5251, -330698.2504, -1140.5251};

//system gains
const float32_t Ky[3*1] = {-63.5762, -23.9051, -4.1428};
const float32_t Ly[3*2] = {37.0458, 115.1644, 44.7803, 1535.2383, 3000.6023, 305028.3011};
const float32_t Kz[3*1] = {-63.5806, -23.9066, -4.1424};
const float32_t Lz[3*2] = {37.4149, 1250.709, 35.0362, 1534.8692, 1110.9981, 330698.2504};

A: In this line:
    status = arm_mat_mult_f32(&zhatm, &Kzm, &outzm);

zhatm is a 3x1 matrix and Kzm is a 1x3 matrix. When multiplied together, the result is a 3x3 matrix, but the provided outzm is a 1x1 matrix.
Perhaps you need to swap the parameters as follows:
    status = arm_mat_mult_f32(&Kzm, &zhatm, &outzm);

That will produce a 1x1 matrix in outzm.
If the hard fault occurs earlier in the code, that might be due to the delayed effect of similar errors.


text:
Q: How to get the session object in general from within a class? There is a class :
@Configuration
@ComponentScan("com.ambre.pta")
@EnableTransactionManagement
@PropertySources({
    @PropertySource("classpath:fr/global.properties"),
    @PropertySource("classpath:fr/main.properties"),
    @PropertySource("classpath:fr/admin.properties"),
    @PropertySource("classpath:fr/referentiel.properties"),
    @PropertySource("classpath:fr/departement.properties"),
    @PropertySource("classpath:fr/exercice.properties"),
    @PropertySource("classpath:fr/defi.properties")
})
public class ApplicationContextConfig {

    @Bean
    public static PropertySourcesPlaceholderConfigurer properties() {
        return new PropertySourcesPlaceholderConfigurer();
    }

    @Bean(name = "viewResolver")
    public InternalResourceViewResolver getViewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/views/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }

    @Bean(name = "dataSource")
    public DataSource getDataSource() {

        BasicDataSource bds = new BasicDataSource();

        bds.setDriverClassName("oracle.jdbc.driver.OracleDriver");
        bds.setUrl("jdbc:oracle:thin:@localhost:1521:xe");

        bds.setUsername("pta");
        bds.setPassword("pta");

        return bds;

    }

    @Autowired
    @Bean(name = "sessionFactory")
    public SessionFactory getSessionFactory(DataSource dataSource) {

        LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource);

        sessionBuilder.scanPackages("com.ambre.pta.model");

        return sessionBuilder.buildSessionFactory();

    }

    @Autowired
    @Bean(name = "transactionManager")
    public HibernateTransactionManager getTransactionManager(SessionFactory sessionFactory) {

        HibernateTransactionManager transactionManager = new HibernateTransactionManager(sessionFactory);

        return transactionManager;

    }

    @Autowired
    @Bean(name = "utilisateurDao")
    public UtilisateurDAO getUtilisateurDao(SessionFactory sessionFactory) {
        return new UtilisateurDAOImpl(sessionFactory);
    }

}

We can get the request object within this class by this way :
HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();

So is there a way to get the session ( HttpSession ) object ?

A: Using Controller classes
You can define HttpSession as an argument to your controller methods:
@RequestMapping("/my-path")
public String doStuff(HttpSession session) {
    // do stuff...
}

This is also the recommended way to access the HttpRequest, rather than going through RequestContextHolder, because it's easier to mock out the session for tests.
See the Spring MVC docs for more detail.
Without using controller classes
Another option is to use a @SessionScope bean and mutate it accordingly:
@Component
@SessionScope
public class MySessionScopedBean {
    String attribute;
}

public class MyOtherClass {
    @Autowired
    private MySessionScopedBean myBean;

    public void doStuff() {
        // myBean accesses a bean instance isolated in the user session
        myBean.attribute = "test";
    }

}

A: If you want to access the HttpSession outside a Controller method, there are two possible answers:

*

*Don't do it, it's evil.

*If you really really want to do it (and I have done it in the past, so who am I to blame you), then the easiest way is to write a class to hold the session, and an interceptor to set and unset it. But to make things easier, I will be working with HttpServletRequest objects, from which you can extract the session:
public class RequestHolder {

    private static final ThreadLocal<HttpServletRequest> REQUEST =
                             new ThreadLocal<>();

    public static HttpServletRequest getCurrentRequest() {
        return REQUEST.get();
    }

    public static HttpSession getCurrentSession() {
        HttpServletRequest request = REQUEST.get();
        return request == null ? null : request.getSession();
    }

    public static void setCurrentRequest(HttpServletRequest request) {
        REQUEST.set(request);
    }

    public static void unsetCurrentRequest() {
        REQUEST.remove();
    }

}

public class RequestHolderInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) {
        RequestHolder.setCurrentRequest(request);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView mav) {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e){
        RequestHolder.unsetCurrentRequest();
    }
}


text:
Q: Avoid session id reuse asp.net I am using cookie based session by using FormsAuthentication.SetAuthCookie.
Is there an easy go so that I can set the reuse of expired sessionId and each time when the session expires ASP.NET creates a new session id.
Thanks.

A: You have to deal with a couple of different cases.  The first is when someone clicks on the logout button.  The second is when the session itself has expired (but no user action has occured).
In the second instance, forms authentication will automatically send you to the login page that you have defined in your web.config.
You could do something like the following
    [AllowAnonymous]
    public ActionResult Login()
    {
        Response.Cookies.Add(CreateExpiredBlankCookie("ASP.NET_SessionId"));
        return View();
    }

    private HttpCookie CreateExpiredBlankCookie(string name)
    {
        var cookie = new HttpCookie(name, "");
        cookie.Expires = DateTime.Now.AddDays(-1);
        return cookie;
    }

A: You can use Session.Abandon() to prevent session reuse.
Because HTTP is stateless, there's no way you can know when the user has closed the browser.  But, you can put a logout button on every page and as part of your handling for the button, call Session.Abandon to prevent a third-party from reusing it.
Beyond that, require HTTPS and make sure your cookies also require HTTPS.


text:
Q: Arduino serial communication working strange I am writing a C# program that has to communicate with an Arduino. Basically it sends data to it and I should be able to read in the serial monitor.
C# code:
if (errCheck[i].IsChecked.GetValueOrDefault() == true)
    err = "1"+err;
else
    err = "0"+err;
_serialPort.Write("<16,"+ Convert.ToUInt32(err,2) + ">");

Arduino code:
void parseData() {      // split the data into its parts

    char * strtokIndx; // this is used by strtok() as an index

    //strtokIndx = strtok(tempChars,",");      // get the first part - the string
    //strcpy(messageFromPC, strtokIndx); // copy it to messageFromPC

    strtokIndx = strtok(tempChars, ","); // this continues where the previous call left off
    integerFromPC = atoi(strtokIndx);     // convert this part to an integer

    switch (integerFromPC) {
        //all cases
        case 16: //managing errors
            delay(10);
            strtokIndx = strtok(NULL, ",");
            uint32_tFromPC = atoi(strtokIndx);
            errors=uint32_tFromPC;
            Serial.print("errors Updated" );

When the last checkbox is checked (so my binary string is 1 and 31 0's) the serial monitor reads 7F FF FF FF instead of 80 00 00 00.
I have tried using ulong but it doesn't seem to work either, any ideas?

A: Why do you want to convert the String to int32 and then back to String??
Simply do this:
if (errCheck[i].IsChecked.GetValueOrDefault() == true)
    err = "1"+err;
else
    err = "0"+err;
_serialPort.Write("<16,"+ err + ">");

Even Uint32 can't take 32 digits!
And in your arduino code you are using atoi too. Handle it as a String. Why do u need it as a integer?
Btw thing about using enums for bitwise operations for examples look here:
http://www.alanzucconi.com/2015/07/26/enum-flags-and-bitwise-operators/


text:
Q: Specialized template method with derived classes as argument With a template method, that is specialized for a specific class A, is there a way to call the specialized code for the classes deriving from A ?
The minimal example
#include <iostream<

class A
{};

class B : public A
{};

class Templator
{
public :
    template <class T>
    void dance(T *argument);
};

template <class T>
void Templator::dance(T *argument)
{
    std::cout << "General implementation" << std::endl;
}

template<>
void Templator::dance<A> (A* )
{
    std::cout << "Specialized implementation" << std::endl;
}

int main()
{
    A a;
    B b;

    Templator tt;
    tt.dance(&a);
    tt.dance(&b);

    return 0;
}

Corresponding output

Specialized implementation
General implementation

In other words, I would like the two outputs to be :

Specialized implementation
Specialized implementation

A: In C++11 you can use std::enable_if and std::is_base_and_derived:
class Templator{
public :
    template <class T>
    typename std::enable_if<!std::is_base_and_derived<A, T>::value, void>::type
    dance(T *argument) {
       std::cout << "General implementation" << std::endl;
    }
    template <class T>
    typename std::enable_if<std::is_base_and_derived<A, T>::value, void>::type
    dance(T *argument) {
       std::cout << "Specialized implementation" << std::endl;
    }
};

You can do the same thing in C++03 using either boost::enable_if_c and boost::is_base_of or std::tr1::is_base_of and writing enable_if yourself (see here)

A: You just need to cast &b to a A*.
If you change this code
tt.dance(&a);
tt.dance(&b);

To this code
tt.dance(&a);
tt.dance((A*)&b);

The output becomes
Specialized implementation
Specialized implementation

A: This should be possible using a boost::enable_if in conjunction with boost::is_base_of.


text:
Q: Removing imported CSS on component end I have many components that import hosted css files as follows:
<style scoped>
  @import 'https://test.com/path/to/my-stylesheets/styles.css';
</style>

What I am wanting is a way to remove these imported stylesheets on an end lifecycle hook such as beforeDestroy.
Is this possible?

A: What you're trying to do depends on vue-loader (if you're using webpack) and it looks like a counter intuitive. So, there's no reason for styles to be removed from document. What you can do is to define your CSS classes in stylesheets or as a data variable in viewmodel and assign/remove those classes during Vue component's lifecycle like beforeCreate/beforeDestroy etc. if you like.


text:
Q: List child pages of current page but limit to specific year I have an old site that has sooo many child pages that I'd like to limit the return of child pages on a current page to just a specific year so that I can pull each year into an accordion.
I am currently using the following and it returns the pages I want listed, I just want to limit the returns to specific years.
  global $id;
  wp_list_pages("title_li=&child_of=$id&show_date=modified&date_format=$date_format");

What can I add to this statement to return only pages published in a specific year?

A: Due to wp_list_pages() leveraging get_pages() to actually retrieve the Page posts, and because get_pages() implements it's own query logic independent of WP_Query's, it's not possible to use arbitrary query variables which are not directly supported by get_pages(), including year, mothnum, day, date_query, etc.
In order to continue using wp_list_pages() to this end, I think the most elegant solution would be to implement a custom Walker_Page class which you might pass to wp_list_pages() as an argument in order to customize the generated HTML.
As an added benefit, this solution continues to use a single get_pages() query instead of one query per year, and can fluidly handle grand-children pages and continue to scale as more years are added.
Tailored Walker_Page
In WordPress "Walkers" are classes which are designed to take lists representing hierarchical or tree-like data like that of a like of hierarchical post-types, taxonomies, or navigation menu items and turn them into markup for display.
wp_list_pages() provides a parameter to pass a custom Walker to it in place of the Walker_Page class it uses by default, allowing you to customize the markup the function produces.
// mytheme/lib/class-year-accordion-walker-page.php
// (or functions.php, or some other theme library code location)

/**
 * A Walker_Page customized to additionally group first-level pages into lists based
 * on their publication year.
 **/
class Year_Accordion_Walker_Page extends Walker_Page {
  /**
   * Creates the opening markup for a year's accordion group.
   *
   * @param string  &$output The string to append output to.
   * @param int     $year The year which to build group markup for.
   * @param boolean $is_active If this year matches the publication date for the current page, as indicated by "child_of".
   * @param array   $args Any additional arguments passed to `walk()`.
   **/
  public function start_accordion_group( &$output, $year, $is_active = false, $args = [] ) {
    // Setup HTML classes to be added to various parts of the markup.
    $container_classes = [];
    $header_classes    = [ 'ui-accordion-header' ];
    $content_classes   = [ 'ui-accordion-content' ];

    if( $is_active ) {
      $container_classes[] = 'current_page_ancestor';
      $header_classes[]    = 'ui-accordion-header-active';
      $content_classes[]   = 'ui-accordion-content-active';
    }

    // Add this accordion group's opening markup to the output, joining each line with the configured indentation.
    $output .= implode(
      "\n\t",
      [
        '
',
        '
' . $year . '
',
        '
',
      ]
    );
  }

  /**
   * Creates the closing markup for a year's accordion group.
   *
   * @param string  &$output The string to append output to.
   * @param int     $year The year which to build group markup for.
   * @param boolean $is_active If this year matches the publication date for the current page, as indicated by "child_of".
   * @param array   $args Any additional arguments passed to `walk()`.
   **/
  public function end_accordion_group( &$output, $year, $is_active = false, $args = [] ) {
    $output .= implode(
      "\n",
      [
        "\t
", // Close the accordion group's page list.
        '
', // Close the accordion group's container li.
      ]
    );
  }

  /**
   * Display array of Pages, grouped by the topmost pages' publication year.
   *
   * $max_depth = 0 means display all levels.
   * $max_depth > 0 specifies the number of display levels.
   *
   * @param array $pages An array of WP_Post items.
   * @param int   $max_depth The maximum hierarchical depth.
   * @param mixed ...$args Optional additional arguments.
   * @return string Markup representing $pages grouped by publication year.
   **/
  public function walk( $pages, $max_depth = 0, ...$args ) {
    $output = '';

    // Invalid parameter or nothing to walk.
    if ( $max_depth < 0 || empty( $pages ) )
      return $output;

    $options                 = $args[0]; // When used with `walk_page_tree()` this is an assoc array of any additional arguments.
    $current_page_id         = $args[1]; // When used with `walk_page_tree()` this is the current post ID.
    $active_page_year        = null; // Keep track of which year the current_page_id Page was published in for custom classes, etc.
    $parent_field            = $this->db_fields['parent']; // Inherited from `Walker_Page` - will always be `ID`.
    $parent_id               = isset( $options['child_of'] ) ? $options['child_of'] : 0; // The ID of the top-level common parent, if any.
    $top_level_pages_by_year = []; // A mapping of year => top-level pages (parent is $parent_id, or no parent if $parent_id is not set).
    $child_pages_by_parent   = []; // A mapping of parent_id => pages, collecting all pages whose parent is not $parent_id (or who have a parent, if $parent_id is not set)

    // Split $pages into $child_pages_by_parent and $top_level_pages_by_year.
    foreach( $pages as $page ) {
      $year = date( 'Y', strtotime( $page->post_date ) );

      if( $page->ID === $current_page_id )
        $active_page_year = $year; // If this is the current page, record the year in which it was published.

      // If this is a grandchild page, we don't care about it's publish date - just add it to the map of parent_id => child pages.
      if( ( empty( $parent_id ) && ! empty( $page->$parent_field ) ) || ( ! empty( $parent_id ) && $page->$parent_field !== $parent_id ) ) {
        if( ! isset( $child_pages_by_parent[ $page->$parent_field ] ) )
          $child_pages_by_parent[ $page->$parent_field ] = [];

        $child_pages_by_parent[ $page->$parent_field ][] = $page;
        continue;
      }

      if( ! isset( $top_level_pages_by_year[ $year ] ) )
        $top_level_pages_by_year[ $year ] = [];

      $top_level_pages_by_year[ $year ][] = $page; // Add the top level page to it's respective year list.
    }

    // Build the markup, one year at a time.
    foreach( $top_level_pages_by_year as $year => $pages ) {
      // Build the opening markup for this year's accordion group.
      $this->start_accordion_group( $output, $year, $year == $active_page_year, $args );

      // Add each top-level page in the group's child tree markup as per usual.
      foreach( $pages as $page )
        $this->display_element( $page, $child_pages_by_parent, $max_depth, 1, $args, $output );

      // Close this year's accordion group.
      $this->end_accordion_group( $output, $year, $year == $active_page_year, $args );
    }

    return $output;
  }
}

With the above class available, wp_list_pages() can be called to utilize it as such:
// Template file
wp_list_pages(
  [
    'title_li'    => '&',
    'child_of'    => $id,
    'show_date'   => 'modified',
    'date_format' => $date_format,
    'walker'      => new Year_Accordion_Walker_Page,
  ]
);

Finishing Touches
For the icing on the cake, you might even create a "template tag" function to load and leverage this class when necessary:
// functions.php
// (or other library file loaded by functions.php)

/**
 * Display pages in an accordion, grouped by year. Loads the customized
 * Walker_Page if it's not already available.
 *
 * @param array $args Array of wp_list_pages() arguments.
 **/
function wpse390524_page_year_accordion( $args = [] ) {
  if( ! class_exists( 'Year_Accordion_Walker_Page' ) )
    require_once get_stylesheet_directory() . '/lib/class-year-accordion-walker-page.php';

  $args['walker'] = new Year_Accordion_Walker_Page;

  wp_list_pages( $args );
}

// Template file
wpse390524_page_year_accordion(
  [
    'title_li'    => '&',
    'child_of'    => $id,
    'show_date'   => 'modified',
    'date_format' => $date_format,
  ]
);


text:
Q: How to use django unit tests with elasticsearch? I use django unit tests to test my application. It worked very well until today.
I integrated elasticsearch to the project with the 2 modules django_elasticsearch_dsl and django_elasticsearch_dsl_drf.
Since then, almost none of my unit tests are working.
I got the same trace for all failed tests:
Traceback (most recent call last):
  File "/home/aurelien/dev/gsport/accounting_bo/tests.py", line 66, in setUp
    club = create_club()
  File "/home/aurelien/dev/gsport/dashboard/tests.py", line 38, in create_club
    club.save()
  File "/home/aurelien/dev/gsport/clubs/models.py", line 81, in save
    super().save(*args, **kwargs)
  File "/home/aurelien/dev/gsport/venv/lib/python3.10/site-packages/django/db/models/base.py", line 739, in save
    self.save_base(using=using, force_insert=force_insert,
  File "/home/aurelien/dev/gsport/venv/lib/python3.10/site-packages/django/db/models/base.py", line 787, in save_base
    post_save.send(
  File "/home/aurelien/dev/gsport/venv/lib/python3.10/site-packages/django/dispatch/dispatcher.py", line 180, in send
    return [
  File "/home/aurelien/dev/gsport/venv/lib/python3.10/site-packages/django/dispatch/dispatcher.py", line 181, in <listcomp>
    (receiver, receiver(signal=self, sender=sender, **named))
  File "/home/aurelien/dev/gsport/venv/lib/python3.10/site-packages/django_elasticsearch_dsl/signals.py", line 58, in handle_save
    registry.update(instance)
  File "/home/aurelien/dev/gsport/venv/lib/python3.10/site-packages/django_elasticsearch_dsl/registries.py", line 141, in update
    doc().update(instance, **kwargs)
  File "/home/aurelien/dev/gsport/venv/lib/python3.10/site-packages/django_elasticsearch_dsl/documents.py", line 225, in update
    return self._bulk(
  File "/home/aurelien/dev/gsport/venv/lib/python3.10/site-packages/django_elasticsearch_dsl/documents.py", line 202, in _bulk
    return self.bulk(*args, **kwargs)
  File "/home/aurelien/dev/gsport/venv/lib/python3.10/site-packages/django_elasticsearch_dsl/documents.py", line 151, in bulk
    response = bulk(client=self._get_connection(), actions=actions, **kwargs)
  File "/home/aurelien/dev/gsport/venv/lib/python3.10/site-packages/elasticsearch/helpers/actions.py", line 410, in bulk
    for ok, item in streaming_bulk(
  File "/home/aurelien/dev/gsport/venv/lib/python3.10/site-packages/elasticsearch/helpers/actions.py", line 329, in streaming_bulk
    for data, (ok, info) in zip(
  File "/home/aurelien/dev/gsport/venv/lib/python3.10/site-packages/elasticsearch/helpers/actions.py", line 256, in _process_bulk_chunk
    for item in gen:
  File "/home/aurelien/dev/gsport/venv/lib/python3.10/site-packages/elasticsearch/helpers/actions.py", line 195, in _process_bulk_chunk_error
    raise error
  File "/home/aurelien/dev/gsport/venv/lib/python3.10/site-packages/elasticsearch/helpers/actions.py", line 240, in _process_bulk_chunk
    resp = client.bulk(*args, body="\n".join(bulk_actions) + "\n", **kwargs)
  File "/home/aurelien/dev/gsport/venv/lib/python3.10/site-packages/elasticsearch/client/utils.py", line 347, in _wrapped
    return func(*args, params=params, headers=headers, **kwargs)
  File "/home/aurelien/dev/gsport/venv/lib/python3.10/site-packages/elasticsearch/client/__init__.py", line 472, in bulk
    return self.transport.perform_request(
  File "/home/aurelien/dev/gsport/venv/lib/python3.10/site-packages/elasticsearch/transport.py", line 417, in perform_request
    self._do_verify_elasticsearch(headers=headers, timeout=timeout)
  File "/home/aurelien/dev/gsport/venv/lib/python3.10/site-packages/elasticsearch/transport.py", line 606, in _do_verify_elasticsearch
    raise error
  File "/home/aurelien/dev/gsport/venv/lib/python3.10/site-packages/elasticsearch/transport.py", line 569, in _do_verify_elasticsearch
    _, info_headers, info_response = conn.perform_request(
  File "/home/aurelien/dev/gsport/venv/lib/python3.10/site-packages/elasticsearch/connection/http_urllib3.py", line 280, in perform_request
    raise ConnectionError("N/A", str(e), e)
elasticsearch.exceptions.ConnectionError: ConnectionError(<urllib3.connection.HTTPConnection object at 0x7f4be02be6e0>: Failed to establish a new connection: [Errno 111] Connection refused) caused by: NewConnectionError(<urllib3.connection.HTTPConnection object at 0x7f4be02be6e0>: Failed to establish a new connection: [Errno 111] Connection refused)

I think the cause of the problem is that I use the following code to populate ES automatically when the postgresql database is:
@registry.register_document
class ClubDocument(Document):
    class Index:
        # Name of the Elasticsearch index
        name = 'clubs'
        # See Elasticsearch Indices API reference for available settings
        settings = {'number_of_shards': 1,
                    'number_of_replicas': 0}

    class Django:
        model = Club # The model associated with this Document

What should I do to either ignore ES during unit tests or better integrate an ES instance during these tests?


text:
Q: Error in Cisco Expect script I wrote a basic Cisco expect script. After ssh connection, I want to detect Cisco error output when I send a command line from a file, for example:
SPAIN#sow crypto isakmp sa
       ^
% Invalid input detected at '^' marker.

I want to catch "% Invalid", in my loop and stop the programm.
foreach line $data {
    expect "*#"
    send "$line\r"
    expect {
        "% Invalid*" { send_user "\n Command [ $line ] Failed. \n"; exit 252 }
    }

I get these errors in the output:
SPAIN>enable
Password:
SPAIN#sow crypto isakmp sa
   ^
% Invalid input detected at '^' marker.

SPAIN#invalid command name "sow crypto isakmp sa"
while executing
"$line "
invoked from within
"expect {
     "% Invalid*" { send_user "\n Command [ $line ]  Failed. \n"; exit 252}
}"
("foreach" body line 4)
invoked from within
"foreach line $data {
    expect "*#"
    send "$line\r"
    expect {
        "% Invalid*" { send_user "\n Command [ $line ] Failed. \n"; exit 252}
    }
}"

thanks

A: The problem is that [] has a special meaning in Tcl; to execute a command and return the result.
Change this:
expect {
    "% Invalid*" { send_user "\n Command [ $line ] Failed. \n"; exit 252 }
}

To:
expect {
    "% Invalid*" { send_user "\n Command \[ $line \] Failed. \n"; exit 252 }
}

See Evaluation & Substitutions 3: Grouping arguments with [] in the Tcl manual for more information.


text:
Q: WPF Merged ResourceDictionary with resource that binds to resource in another Dictionary not working I have created a simple project that demonstrates the issue I am having where I get the error:
'Provide value on 'System.Windows.Markup.StaticResourceHolder' threw an exception.' Line number '6' and line position '9'.
The project layout is very simple and I have uploaded it to dropbox:
https://www.dropbox.com/s/451b5zkw8oqgcld/StyleTest1.zip?dl=0
MainWindow.xaml
<Window x:Class="StyleTest1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Dictionary1.xaml" />
                <ResourceDictionary Source="Dictionary2.xaml" />
            </ResourceDictionary.MergedDictionaries>
            <Style x:Key="ButtonStyle1" TargetType="{x:Type Button}">
                <Setter Property="Background" Value="{DynamicResource Button.Static.Background}"/>
            </Style>
        </ResourceDictionary>
    </Window.Resources>
    <Grid>
        <Button x:Name="button" Content="Button" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Style="{DynamicResource ButtonStyle1}">

        </Button>
    </Grid>
</Window>

Dictionary1.xaml
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:po="http://schemas.microsoft.com/winfx/2006/xaml/presentation/options"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <GradientStopCollection po:Freeze="true" x:Key="ButtonBackgroundStops">
        <GradientStop Color="#2d2d2f"/>
        <GradientStop Color="#2d2d2f" Offset="1"/>
    </GradientStopCollection>

    <LinearGradientBrush
        po:Freeze="true"
        x:Key="ButtonBackgroundBrush"
        GradientStops="{StaticResource ButtonBackgroundStops}"
        StartPoint="0.5,-0.05"
        EndPoint="0.5,0.66" />

</ResourceDictionary>

Dictionary2.xaml
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <LinearGradientBrush
        x:Key="Button.Static.Background"
        GradientStops="{Binding Source={StaticResource ButtonBackgroundBrush}, Path=GradientStops}"
        StartPoint="{Binding Source={StaticResource ButtonBackgroundBrush}, Path=StartPoint}"
        EndPoint="{Binding Source={StaticResource ButtonBackgroundBrush}, Path=EndPoint}"/>

</ResourceDictionary>

And that's it... if I run that program I get the error:
'Provide value on 'System.Windows.Markup.StaticResourceHolder' threw an exception.' Line number '6' and line position '9'.
However, if I alter MainWindow.xaml to the following I no longer get the issue:
Here is the dropbox link for the modified version:
https://www.dropbox.com/s/ceikh5b8cfecdkw/StyleTest2.zip?dl=0
MainWindow.xaml
<Window x:Class="StyleTest2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:StyleTest2"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Dictionary1.xaml" />
                <ResourceDictionary Source="Dictionary2.xaml" />
            </ResourceDictionary.MergedDictionaries>
            <LinearGradientBrush
                x:Key="Button.Static.Background"
                GradientStops="{Binding Source={StaticResource ButtonBackgroundBrush}, Path=GradientStops}"
                StartPoint="{Binding Source={StaticResource ButtonBackgroundBrush}, Path=StartPoint}" />
            <Style x:Key="ButtonStyle1" TargetType="{x:Type Button}">
                <Setter Property="Background" Value="{DynamicResource Button.Static.Background}"/>
            </Style>
        </ResourceDictionary>
    </Window.Resources>
    <Grid>
        <Button x:Name="button" Content="Button" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Style="{DynamicResource ButtonStyle1}">

        </Button>
    </Grid>
</Window>

Which would suggest it is a problem with the LinearGradientBrush in Dictionary2.xaml binding to the ButtonBackgroundBrush resource that is located in Dictionary1.xaml.
Can anyone tell me what I am doing wrong here and what is the correct way to have a resource in one dictionary reference a resource in another dictionary?
Thanks for your time,
codeOwl

A: *

*Use DynamicResource in-place of StaticResource in Dictionary2,
or

*Merge Dictionary 1 in Dictionary2, then there won't be any issues.
Dictionary2 will look like :
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="Dictionary1.xaml"/>
    </ResourceDictionary.MergedDictionaries>

    <LinearGradientBrush
        x:Key="Button.Static.Background"
        GradientStops="{Binding Source={StaticResource ButtonBackgroundBrush}, Path=GradientStops}"
        StartPoint="{Binding Source={StaticResource ButtonBackgroundBrush}, Path=StartPoint}"
        EndPoint="{Binding Source={StaticResource ButtonBackgroundBrush}, Path=EndPoint}"/>

</ResourceDictionary>


text:
Q: Выполнится ли хранимая функция в mongodb Подключаюсь к mongodb из nodejs посредством mongoose. В коллекции db.system.js имеется хранимая функция, которую я запускаю из nodejs. Она достаточно объемная, она апдейтит много данных и выполняется асинхронно неизвестное количество времени.  И вот если в монгусе я отключусь от монги, сама функция в ней продолжит отрабатывать, или тоже завершится?
UPDATE:
Действительно, никак. Я мог вытаскивать функцию таким образом:
var Schema = mongoose.Schema;
var test = mongoose.model('System.js', new Schema({ "_id" : { type : String, default : "" }, "value" : { type : String, default : "" } }));
test.find( { '_id' : '_test' }, function( err, res ) {
        //
});

И почему-то подумал, что мог бы ее выполнить. Я ошибся. Хорошо, тогда по-другому. Допустим, я из терминала вызову функцию командой:
mongo testdb --eval "db.system.js.findOne({ _id : '_test' }).value()"

Функция выполняется. И если я оборву выполнение в терминале, функция прервется в mongodb? )


text:
Q: Program to make vowels in string uppercase and change letters to next letter in alphabet(i.e. a->b) not working how can I solve this. It is supposed to make all vowels in str capitalized and to change each letter in the alphabet to the next letter in the alphabet(i.e. a -> b, or z->a). It keeps returning "str.join is not a function". Any Help? By the way, it's JavaScript.
function LetterChanges(str) {

  str = str.split("");//split() string into array
  for(var i=0;i<str.length;str++){//for loop that checks each letter
    if(str[i]===/[^a-y]/){
      str=str[i].fromCharCode(str[i].charCodeAt(0) + 1);
        }else if(str[i]==='z'){
          str[i] = 'a';
        }
    if(str[i] === 'a'||'e'||'i'||'o'||'u'){
       str[i] = str[i].toUpperCase();
       }

  }

  //modifies letter by adding up in alphabet
  //capitalizes each vowel
  //join() string

  return str.join();
}

// keep this function call here
// to see how to enter arguments in JavaScript scroll down
LetterChanges(readline());

A: Ok, you need to read a bit on JavaScript.
This is doesn't do what you think str[i]===/[^a-y]/. You should use str[i].match(/[a-y]/i).
This doesn't do what you think: str[i] === 'a'||'e'||'i'||'o'||'u'. It'll always return true. You'll want this str[i].match(/[aeiou]/i).

A: There are several logical errors in your code, as described in @Simon Boudrias answer.
However just for self-learning here is an alternative solution for your problem:
str.replace(/[a-z]/g, function(c) {
    return 'aeiou'.indexOf(c) > -1
        ? c.toUpperCase()
        : String.fromCharCode(Math.max(c.charCodeAt(0) % 122 + 1, 97));
});


text:
Q: Git - How to Stop This Type of Merge Conflict <<<<<<< HEAD

=======
>>>>>>> master
COPY image/entrypoint.sh /entrypoint.sh
RUN chmod o+x /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]

<<<<<<< HEAD

=======
>>>>>>> master

As you can see, there is no real merge conflict here.
I know that both branches have the same exact code there, but the placement is a few lines off.
I've already tried git merge -Xignore-all-space but this is actually the result of it.
Any ideas on how to avoid these weird merge conflicts?

A: Given the little information available, my best bet is that there's a conflict on whitespace.
Check commits on both branches with git show -R which should highlight trailing whitespaces that can be missed with a regular "forward" git diff/git show.
If it helps, my git version is 2.31.0.


text:
Q: GPU optimization with Keras I am running Keras on a Windows 10 computer with a GPU. I have gone from Tensorflow 1 to Tensorflow 2 and I now feel that fitting is much slower and hope for your advice.
I am testing whether Tensorflow sees the GPU with the following statements:
from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())

K._get_available_gpus()

giving the response
[name: "/device:CPU:0"
device_type: "CPU"
memory_limit: 268435456
locality {
}
incarnation: 17171012743200670970
, name: "/device:GPU:0"
device_type: "GPU"
memory_limit: 6682068255
locality {
  bus_id: 1
  links {
  }
}
incarnation: 5711519511292622685
physical_device_desc: "device: 0, name: GeForce GTX 1070, pci bus id: 0000:01:00.0, compute capability: 6.1"

So, that seems to indicate that the GPU is working?
I am training a modified version of ResNet50 with up to 10 images (257x257x2) as input. It has 4.3M trainable parameters. Training is very slow (could be several days). Part of the code is shown here:
import os,cv2,sys
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
import scipy.io
import h5py
import time
from tensorflow.python.keras import backend as K
from tensorflow.python.keras.models import load_model
from tensorflow.python.keras import optimizers
from buildModelReduced_test import buildModelReduced
from tensorflow.keras.utils import plot_model

K.set_image_data_format('channels_last') #set_image_dim_ordering('tf')
sys.setrecursionlimit(10000)

# Check that gpu is running
from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())
K._get_available_gpus()

# Generator to read one batch at a time for large datasets
def imageLoaderLargeFiles(data_path, batch_size, nStars, nDatasets=0):
---
---
---
yield(train_in,train_target

# Repository for parameters
nStars = 10
img_rows = 257
img_cols = 257
bit_depth = 16
channels = 2
num_epochs = 1
batch_size = 8
data_path_train = 'E:/TomoA/large/train2'
data_path_validate = 'E:/TomoA/large/validate2'
nDatasets_train = 33000
nDatasets_validate = 8000
nBatches_train = nDatasets_train//(batch_size)
validation_steps = nDatasets_validate//(batch_size)
output_width = 35;
runSize = 'large'
restartFile =  ''

#%% Train model

if restartFile == '':

    model = buildModelReduced(nStars,img_rows, img_cols, output_width,\
               batch_size=batch_size,channels=channels, use_l2_regularizer=True)
    model.summary()
    plot_model(model, to_file='model.png', show_shapes=True)

    all_mae = []

    adam=optimizers.Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=None,
                         decay=0.0, amsgrad=False)

    model.compile(optimizer='adam',loss='MSE',metrics=['mae'])

history = model.fit_generator(imageLoaderLargeFiles(data_path_train,batch_size,nStars,nDatasets_train),
                    steps_per_epoch=nBatches_train,epochs=num_epochs,
                    validation_data=imageLoaderLargeFiles(data_path_validate,batch_size,nStars,nDatasets_validate),
                    validation_steps=validation_steps,verbose=1,workers=0,
                    use_multiprocessing=False, shuffle=False)

print('\nSaving model...\n')
if runSize == 'large':
    model.save(runID + '_' + runSize + '.h5')

When I open Windows task manager and look at the GPU, I see that the memory allocation is 6.5GB, copying activity less than 1%, and CUDA about 4%. Disk activity is low, I read a cache of 1000 data sets at a time from an SSD. See screen clip below. I think that shows that the GPU is not working well. The CPU load is 19%. I use a batch size of 8, if I go higher, I get an resource exhausted error.
Any ideas on how to proceed or where to find more information? Any rules of thumb on how to tune your run to exploit the GPU well?

A: It seems there is a bottleneck somewhere on a training operation that we can not detect by looking at Task Manager. It can be caused by I/O, GPU, or CPU. You should detect which part of the processing is slow with using an advanced tool.
You can use TensorFlow Profiler to inspect all processes of the TensorFlow. Also, it gives suggestions that how you can speed up your processes. Here is a simple video tutorial about it.


text:
Q: Must provide source or customer stripe live mode this is my first time using stripe and I am getting an error Must provide source or customer. once I went live. In the test mode I used "tok_mastercard" as my source but clearly when I went live it isn't valid. What am I missing here please help.
This is my POST request in the backend
  stripe.charges
    .create({
      amount: req.renter.rent * 100,
      currency: "usd",
      source: req.body.token,
      application_fee_amount: req.renter.rent * 0.05 * 100,
      transfer_data: {
        //the destination needs to not be hard coded it needs to
        //come from what property the renter is in
        destination: req.renter.stripeConnectId,
        // destination: "acct_1GOCMqDfw1BzXvj0",
      },
    })
    .then((charge) => {
      console.log(req.renter);
      res.send(charge);
    })
    .catch((err) => {
      console.log(err);
    });
});

this is my two functions in the frontend using react-native and node
  handleCardPayPress = async () => {
    try {
      this.setState({ loading: true, token: null });
      const token = await stripe.paymentRequestWithCardForm({
        // Only iOS support this options
        smsAutofillDisabled: true,
        requiredBillingAddressFields: "full",
        prefilledInformation: {
          billingAddress: {
            name: "",
            line1: "",
            line2: "",
            city: "",
            state: "",
            country: "US",
            postalCode: "",
            email: "",
          },
        },
      });

      this.setState({ loading: false, token });
    } catch (error) {
      this.setState({ loading: false });
    }
  };

  makePayment = async () => {
    try {
      //Mate the payment
      const response = await unitApi.post("/payments", {
        data: {
          amount: this.state.renter.rent,
          currency: "usd",
          token: this.state.token,
        },
      });
      Alert.alert("Success!", `Confirmation ID: ${response.data.id}`, [
        { text: "Done" },
      ]);
      console.log(response.data);
      // navigate("Home");
    } catch (err) {
      //failiur and showing the error message
      console.log(err);
      Alert.alert("Failed!", "Card declined.", [{ text: "Declined" }]);
    }
  };

A: Odds are pretty good that this.state.token doesn't contain what you think it does in the unitApi.post() function call; I'd recommend logging that and seeing if that helps, and also logging req.body.token server-side.


text:
Q: Is GPS EXIF data available client-side when selecting on an iPhone? I'm using the excellent jquery.exif.js library as per this StackOverflow post.
However, when selecting an image using an iPhone (Safari), on iOS 7.0.4, the exifObject.GPSLatitude and and exifObject.GPSLatitude fields are not present client-side. By contrast, if I do a traditional full upload sent to the server, GPS EXIF data is correctly present in the image file.
Can anyone point me to a definitive statement as to whether client-side (i.e. FileReader) support for iOS reading GPS EXIF data should work?


text:
Q: Three.js - setting background color of side with SVG texture applied using canvg I'm using r71 of three.js and canvg library. I'm using canvg to display the SVG but it comes up with the following error.
Failed to load resource: the server responded with a status of 404 (Not Found)
Here is the following code in question:
    var imageCanvas2 = document.createElement("canvas");
    canvg(imageCanvas2, 'https://upload.wikimedia.org/wikipedia/commons/a/a3/WikiProject_Zoo_Logo.svg');

        var texture1 = new THREE.Texture(imageCanvas2);

        //FOUR - TETRAHEDRON
        var loaderFour = new THREE.JSONLoader( true );
        var materialsArray = [];
        materialsArray.push(new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture(texture1)}));
        texture1.needsUpdate = true;
        materialsArray.push(new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture("./resources/images/Alerts.png")}));
        materialsArray.push(new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture("./resources/images/IPT.PNG")}));
        materialsArray.push(new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture("./resources/images/action-item-tracking.png")}));

        for(var i = 0; i <= 3; i++) {
            materialsArray[i].map.minFilter = THREE.LinearFilter;
        }

        loaderFour.load("./resources/json/tetra.json", function (model) {
                var materialFour = new THREE.MeshFaceMaterial(materialsArray);
                four = new THREE.Mesh(model, materialFour);//issue according to three.js
                four.translateY(1);
                four.scale.set(3, 3, 3);
                meshFour = THREE.SceneUtils.createMultiMaterialObject(four, materialFour);
                for( var i = 0; i < model.faces.length; i++ )
                { model.faces[i].materialIndex = i; }
                scene.add(four);
            });


text:
Q: What will be the output of the following SQL Transaction ? Identify the output for the following Code
PRINT 'Before Transaction'
SELECT @@TRANCOUNT
BEGIN TRAN T1
PRINT 'After transaction T1 starts'
/* Value of @@TranCount is 1 */
SELECT @@TRANCOUNT
BEGIN TRAN T2 save TRAN T2
--save tran T2
PRINT 'After transaction T2 starts'
/* Value of @@TranCount is 2 */
SELECT @@TRANCOUNT
ROLLBACK TRAN T2
PRINT 'After transaction T2 roll backs'
/* Value of @@TranCount is still 2 as the rollback failed due to a error */
SELECT @@TRANCOUNT ---------[IT SHOUD BE 1,BUT WHY RESULT IS COMING AS 2?]
ROLLBACK TRAN T1
PRINT 'After transaction T1 roll backs'
/* Value of @@TranCount is 0 */
SELECT @@TRANCOUNT

What will be the reason for the improper Output ?

A: From MSDN

ROLLBACK TRANSACTION decrements @@TRANCOUNT to 0, except for
  ROLLBACK TRANSACTION       savepoint_name, which does not affect
  @@TRANCOUNT.

You have transaction T2 save so ROLLBACK has no effect on @@TRANCOUNT.
If you use ROLLBACK on transaction T1 , @@Trancount will be reset to ZERO

A: Answer lies in your code,  as you have used save TRAN T2, Transaction T2 get saved and rollback doesn't affect @@TRANCOUNT value
Try to run below query multiple times in SQL Server....you will see value of @@TRANCOUNT gets increased by 1, every time you execute this query.
SELECT @@TRANCOUNT
BEGIN TRAN T2 save TRAN T2
PRINT 'After transaction T2 starts'
SELECT @@TRANCOUNT
ROLLBACK TRAN T2
PRINT 'After transaction T2 roll backs'
SELECT @@TRANCOUNT


text:
Q: How to avoid long-running tasks when doing Spark cube Imagine a weblog where each event is attributed with multiple dimensions (siteID, countryID, pageID, etc.) and also has a visitor ID:
eventID | siteID | countryID | pageID | visitorID

The goal is to count unique visitors for each combination of dimensions including totals (i.e. cube). It can be expressed as the following Spark SQL query:
SELECT
  COUNT(DISTINCT(visitorID))
FROM weblog
   GROUP BY siteID, countryID, pageID WITH CUBE

Assuming that all dimension fields have relatively high cardinality, this sort of aggregation can be efficiently done by Spark because each combination of dimensions will receive a relatively small number of visitor IDs.
CUBE operation, however, creates heavy tasks that correspond to groupings like
... GROUP BY siteID, countryID
... GROUP BY siteID
etc.

These tasks receive a very high number of IDs (and task that computes the grand total receives all IDs in the entire log). It seems that Spark 2.2 is not able to parallelize it, so the job runtime is bounded by these long-running tasks.
How to optimize this sort of queries?

A: Short answer is don't use COUNT(DISTINCT(_)). You just cannot have a cake and eat it to. You can either have exact results, which can result in skews and failures, or reasonable approximations with bounded precision and predictable performance.
Instead use approximate counts distinct using sketch.
SELECT approx_count_distinct(visitorID)
FROM ...
GROUP BY ... WITH CUBE


text:
Q: Rails normalization of models I'm wondering how I can normalize my tables in rails, say I've got a table containing id, username, email and an optional field (often left blank). I would like to move out this optional field into a separate table but still use it as a attribute in the model. Is this possible?

A:
class Something
  belongs_to :other
  delegate :other_field, :to => :other, :allow_nil => true
end

Look at delegation: http://www.simonecarletti.com/blog/2009/12/inside-ruby-on-rails-delegate/


text:
Q: Netbeans code completion for a recordset Having declared a query in PHP and fetched a row
eg
$query=$db->query("select name,address from people where postcode like 'SO%'");
$row=$query->fetch_object();

is it possible to set up code completion so that when I type
$row->

I get a dropdown list of the fields in the query (ie name and address). Code completion works well for lots of other things, including inside SQL statements, so I thought this would be a nice feature (I'm hoping someone will tell me it's already there!)

A: $row is to design time, not filled with values. This value is only set at the Runtime, with a database query.
Only a workaround if you absolutely want mydata-> .
The advantage of the function setProps(), the values can be validated.
[...]
define(val1, "name");
define(val2, "address");

$query = "SELECT ".val1.", ".val2." from people where postcode like 'SO%'";
$result = mysql_query($query);

if (!$result) {
    $message  = 'invalid query: ' . mysql_error() . "\n";
    $message .= 'query: ' . $query;
    die($message);
}

while($rows[]=mysql_fetch_array($result,MYSQL_ASSOC));

class MyArrayObject extends ArrayObject {
        public $name;
        public $address;

        public function setProps($name) {
            if (isset($name[val1])) {$this->name = $name[val1]; }
                               else {$this->name = 'n/a';}
            if (isset($name[val2])) {$this->address = $name[val2]; }
                               else {$this->address = 'n/a';}
        }
}

$mao = new MyArrayObject($rows,ArrayObject::ARRAY_AS_PROPS);
$iterator = $mao->getIterator();
while ($iterator->valid()) {
    $mao->setProps($iterator->current());
    echo  "
\n";
    echo $mao->name . "
\n" ;
    echo $mao->address ;
    $iterator->next();
}

mysql_close($link);
[...]

code completion

A: There is no any code completion for this.
You only can autocomplete for existng class with vdoc.
$query=$db->query("select name,address from people where postcode like 'SO%'");
$row=$query->fetch_object();
/* @var $row \Existing\Class */
$row->


text:
Q: ArangoDB error for List type I am encountering an issue on a .Net object property with List<Int>. There is no problem to save the record but when retrieving it will throw an error message as seen below:

{"The value \"1\" is not of type \"System.Int32\" and cannot be used in this generic collection.\r\nParameter name: value"}

Can anyone help? Thanks.

A: For those who wants to get the latest patch by Yojimbo87, you may refer to https://github.com/yojimbo87/ArangoDB-NET/issues/15