text:
Q: NullPointerException in eclipse in Eclipse itself at PartServiceImpl.internalFixContext I have a problem about eclipse IDE, I can't open any file in my work space; if I try to open file, eclipse will alert the following error dialog
"An error has occurred. See error log for more details. java.lang.NullPointerException"

I go to see .log file in .meta at workspace and I see a paragraph in the file like this:
!ENTRY org.eclipse.jface 4 2 2557-04-09 11:40:49.422
!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jface".
!STACK 0
java.lang.NullPointerException
    at org.eclipse.e4.ui.internal.workbench.PartServiceImpl.internalFixContext(PartServiceImpl.java:380)
    at org.eclipse.e4.ui.internal.workbench.PartServiceImpl.bringToTop(PartServiceImpl.java:341)
    at org.eclipse.e4.ui.internal.workbench.PartServiceImpl.showPart(PartServiceImpl.java:1029)
    at org.eclipse.ui.internal.WorkbenchPage.busyOpenEditor(WorkbenchPage.java:3047)
    at org.eclipse.ui.internal.WorkbenchPage.access$22(WorkbenchPage.java:2969)
    at org.eclipse.ui.internal.WorkbenchPage$8.run(WorkbenchPage.java:2951)
    at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70)
    at org.eclipse.ui.internal.WorkbenchPage.openEditor(WorkbenchPage.java:2947)
    at org.eclipse.ui.internal.WorkbenchPage.openEditor(WorkbenchPage.java:2911)
    at org.eclipse.ui.internal.WorkbenchPage.openEditor(WorkbenchPage.java:2902)
    at org.eclipse.ui.ide.IDE.openEditor(IDE.java:655)
    at org.eclipse.ui.ide.IDE.openEditor(IDE.java:614)
    at org.eclipse.jdt.internal.ui.javaeditor.EditorUtility.openInEditor(EditorUtility.java:360)
    at org.eclipse.jdt.internal.ui.javaeditor.EditorUtility.openInEditor(EditorUtility.java:167)
    at org.eclipse.jdt.ui.actions.OpenAction.run(OpenAction.java:249)
    at org.eclipse.jdt.ui.actions.OpenAction.run(OpenAction.java:228)
    at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun(SelectionDispatchAction.java:275)
    at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run(SelectionDispatchAction.java:251)
    at org.eclipse.jdt.internal.ui.packageview.PackageExplorerActionGroup.handleOpen(PackageExplorerActionGroup.java:376)
    at org.eclipse.jdt.internal.ui.packageview.PackageExplorerPart$4.open(PackageExplorerPart.java:538)
    at org.eclipse.ui.OpenAndLinkWithEditorHelper$InternalListener.open(OpenAndLinkWithEditorHelper.java:48)
    at org.eclipse.jface.viewers.StructuredViewer$2.run(StructuredViewer.java:866)
    at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
    at org.eclipse.ui.internal.JFaceUtil$1.run(JFaceUtil.java:49)
    at org.eclipse.jface.util.SafeRunnable.run(SafeRunnable.java:175)
    at org.eclipse.jface.viewers.StructuredViewer.fireOpen(StructuredViewer.java:864)
    at org.eclipse.jface.viewers.StructuredViewer.handleOpen(StructuredViewer.java:1152)
    at org.eclipse.jface.viewers.StructuredViewer$6.handleOpen(StructuredViewer.java:1256)
    at org.eclipse.jface.util.OpenStrategy.fireOpenEvent(OpenStrategy.java:275)
    at org.eclipse.jface.util.OpenStrategy.access$2(OpenStrategy.java:269)
    at org.eclipse.jface.util.OpenStrategy$1.handleEvent(OpenStrategy.java:309)
    at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1053)
    at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4169)
    at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3758)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$9.run(PartRenderingEngine.java:1053)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:942)
    at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:86)
    at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:588)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
    at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:543)
    at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:149)
    at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:124)
    at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:353)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:180)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:629)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:584)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1438)
    at org.eclipse.equinox.launcher.Main.main(Main.java:1414)

How can I solve this problem - any idea?

A: Better you update your eclipse by clicking it on help >> check for updates, also you can start eclipse by entering command in  command prompt eclipse -clean.
Hope this will help you.

A: I have also encountered this error . Just i opened the new window ie Window -> New Window in eclipse .Then , I closed my old window. This solved my problem.

A: There is a bug filed for Eclipse:
https://bugs.eclipse.org/bugs/show_bug.cgi?id=385680
You could try restarting Eclipse, it helped the original poster of the issue there.

A: hi,that maybe the project's problem,
chose the project and setting you eclipse:
project -> clean...

A: After exiting eclipse I moved .eclipse (found in the user's home directory) to .eclipse.old (just in case I may have had to undo). The error does not show up any more and my projects are working fine after restarting eclipse.
Caution: I have a simple setup and this may not be the best for environments with advanced settings.
I am posting this as a separate answer as previously listed methods did not work for me.

A: I faced the same error, but only with files cloned from git that were assigned to a proprietary plugin.
I realized that even after cloning the files from git, I needed to create a new project or import a project in eclipse and this resolved the error.


text:
Q: Count the number of months between two dates Let's assume I have two dates in variables, like :
$dateFrom = '2021/07/20';
$dateTo = '2021/08/10';

I did that but it still doesn't get results:
$from = new \DateTime($dateFrom);
$to = new \DateTime($dateTo);

$interval = $to->diff($from);

$a = $interval->format('%m months');
dd($a); // result : 0 months

I need to calculate the number of months between $dateFrom and $dateTo. I need to get 2.
Is there any way to get it?
Thanks
update: Mine is less than 60 days, less than 2 months. But how to complete 2 months

A: u can use DateTime
$dateFrom = new DateTime('2021-07-20');
$dateTo = new DateTime('2021-08-10');

$interval = $dateTo->diff($dateFrom);

$interval->format('%m months');

A: This may help you:
    $dateFrom = '2021/07/20'; // Suppose dateFrom is older than dateTo
    $dateTo = '2021/08/10';
    $from = new DateTime($dateFrom);
    $to = new DateTime($dateTo);

    $monthsDiff = $to->format('m') - $from->format('m');
    $yearsDiff = $to->format('Y') - $from->format('Y');
    if ($monthsDiff < 0){
       $yearsDiff = $yearsDiff - 1;
    }
    echo ((($monthsDiff + 12) % 12) + 1) + $yearsDiff * 12;

redpajama_set_name: RedPajamaStackExchange


text:
Q: google map api Draggable directions With Laravel I know that there is a cool lib called Googlmapper for using googleMapApi in laravel, but I actually didn't use it before , and I don't know if it has the drag direction option like in google api direction draggable googleMapApi direction draggable ,
I need this , as I'm developing an app in which the admin will be able to draw the directions for buses drivers so that they able to know where they stop to pick up people .the driver will do that as he will have an android app so that he can see the direction that the admin made .
I need for the web app for the admin , the android app is not my responsibility
so I want to know how to make Direction Draggable google map api IN Laravel .
what Lib to use How to use them ,is there any tutorials for that or books any thing will be great


text:
Q: customize BigTextStyle notification with ParsePushBroadcastReceiver I'm trying to override the getNotification() method of Parse ParsePushBroadcastReceiver class to render a BigTextStyle notification with two action buttons at the bottom. Sort of like:
http://developer.android.com/design/media/notifications_pattern_two_actions.png
According to the Parse push notification guide, that's all I need to do:
Here's my code:
public class NotificationReceiver extends ParsePushBroadcastReceiver {

private static final String LOG_TAG = NotificationReceiver.class.getSimpleName();

@Override
protected Notification getNotification(Context context, Intent intent) {
    Log.v(LOG_TAG, "getNotification called");
    Bundle extras = intent.getExtras();
    String jsonData = extras.getString("com.parse.Data");
    String url = "";
    String objectId = null;
    String title = "";
    String alertMsg = "";

    if (jsonData != null){
        try {
            JSONObject data = new JSONObject(jsonData);
            objectId = data.getString("objectId");
        }
        catch(JSONException e){
            Log.e(LOG_TAG, "Error parsing json data", e);
        }
    }
    else{
        Log.w(LOG_TAG, "cannot find notification data");
    }

    Log.v(LOG_TAG, "notification for item with id=" + objectId);

    BucketListItem item = BucketListDao.getInstance().findById(objectId);
    title = "Get ready!";
    alertMsg = item.getSummary() + "\n" + item.getLocation() + "\n" + item.getStartTime();

    Intent detailsIntent = new Intent("com.parse.push.intent.OPEN", Uri.parse(url));
    PendingIntent piDetails = PendingIntent.getService(context, 0, detailsIntent, 0);

    Intent snoozeIntent = new Intent(context, BucketListActivity.class);
    snoozeIntent.setAction("com.stubhublabs.dopamine.SNOOZE");
    PendingIntent piSnooze = PendingIntent.getService(context, 0, snoozeIntent, 0);

    NotificationCompat.Builder builder =
            new NotificationCompat.Builder(context)
                    .setSmallIcon(R.drawable.ic_launcher)
                    .setContentTitle(title)
                    .setContentText(alertMsg)
                    .setContentIntent(piDetails)
                    .setDefaults(Notification.DEFAULT_ALL) // requires VIBRATE permission
                    .setStyle(new NotificationCompat.BigTextStyle()
                            .bigText(alertMsg))
                    .addAction (R.drawable.ic_stat_snooze,
                            context.getString(R.string.notification_snooze), piSnooze)
                    .addAction (R.drawable.ic_stat_details,
                            context.getString(R.string.notification_details), piDetails);

        return builder.build();
    }

    @Override
    protected void onPushOpen(Context context, Intent intent) {
        Log.v(LOG_TAG, "onPushOpen called");

        Intent i = new Intent(context, BucketListActivity.class);
        i.putExtras(intent.getExtras());
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);
    }

    @Override
    protected Class<? extends Activity> getActivity(Context context, Intent intent) {
        Log.v(LOG_TAG, "getActivity called");
        return super.getActivity(context, intent);
    }

    @Override
    protected void onPushReceive(Context context, Intent intent) {
        Log.v(LOG_TAG, "onPushReceive called");
        super.onPushReceive(context, intent);
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.v(LOG_TAG, "onReceive Called");
        super.onReceive(context, intent);
    }
}

The BigTextStyle notification does show up. But clicking on the notification or the action buttons doesn't do anything. And as the log shows, onPushOpen was never invoked:
10-08 15:03:28.776    4021-4021/ V/NotificationReceiver﹕ onReceive Called
10-08 15:03:28.776    4021-4021/ V/NotificationReceiver﹕ onPushReceive called
10-08 15:03:28.776    4021-4021/ V/NotificationReceiver﹕ getNotification called
10-08 15:03:28.776    4021-4021/ V/NotificationReceiver﹕ notification for item with id=yyw00Lh5Ce

If I don't use my extended ParsePushBroadcastReceiver class, or if I use my ParsePushBroadcastReceiver class but not overriding the getNotification method, the standard would render and clicking on it does open the intended activity.
I can't find any tutorial or example of extending ParsePushBroadcastReceiver to get custom notification. Am I missing anything?

A: You set your content intent to:
Intent detailsIntent = new Intent("com.parse.push.intent.OPEN", Uri.parse(url));
PendingIntent piDetails = PendingIntent.getService(context, 0, detailsIntent, 0);

This is the intent that is called when your notification is clicked. However, the ParsePushBroadcastReceiver is a BroadcastReceiver. If you want to reuse the infrastructure provided by Parse, you need to use PendingIntent.getBroadcast() rather than PendingIntent.getService().
Of course, you could just use PendingIntent.getActivity() and use the Intent you built in onPushOpen() and bypass that indirection completely.


text:
Q: number_format numbers according to decimal values I have number from database where the column type is set to string. I have no control of the database since I am just consuming it as an api. What I need is to convert and format it according to its decimal values(not count)
So
37.2348 should be 37.24

What I tried
number_format(37.2348, 2) -> 37.23
round(37.2348, 2) -> 37.23

There's no need to convert the result from string to decimal, as I noticed the Php built in number_format function can automatically convert and format it.
Any Ideas ?


text:
Q: SSL error from AWS server in us-west-1 to eu-west-1 Server's in us-west-1 region while tryin to connect https://elasticloadbalancing.eu-west-1.amazonaws.com/ in eu-west-1 region  curl: (35) OpenSSL SSL_connect: SSL_ERROR_SYSCALL.
This is happening with all base images of Ubuntu only. If we run this on amazon link, this issue is not happening
ubuntu@-172:~$ curl -I https://elasticloadbalancing.eu-west-1.amazonaws.com/
curl: (35) OpenSSL SSL_connect: SSL_ERROR_SYSCALL in connection to elasticloadbalancing.eu-west-1.amazonaws.com:443
ubuntu@172:~$

This is happening from us-west-1 region only.

A: We seemed to have a similar problem, after looking over the sysctl settings for amazon linux and ubuntu, we discovered that changing this seems to solve the problem:
sysctl net.ipv4.ip_default_ttl=255

this was just looking at the sysctl network items between the amazon linux and our ubuntu nodes.


text:
Q: Applications of Geometry of Numbers What are the applications of Geometry of Numbers? I think it proves the following things:

*

*Fermat's Christmas Theorem

*Lagrange 4-square Theorem

*Finiteness of Class Group

*Dirichlet's Unit Theorem

would love to hear about more.

A: Have you reviewed this: http://alpha.math.uga.edu/~pete/geometryofnumbers.pdf ?
There are also several books on the topic and a Wiki page with references too.
-A


text:
Q: Firebase admin SDK FCM error I am using version 6.0.0 of firebase admin in Dialogflow fulfilments to send fcm notification.
admin.messaging().send({
    "message": {
        "notification": {
            "title": "Portugal vs. Denmark",
            "body": "great match!"
        },
        "token": user_info.device_id
    }
})
.then((response) => {
    // Response is a message ID string.
    console.log('Successfully sent message:', response);
})
.catch((error) => {
    console.log('Error sending message:', error);
});

This is the error I am getting
Error: Exactly one of topic, token or condition is required
at FirebaseMessagingError.Error (native)
at FirebaseMessagingError.FirebaseError [as constructor] (/user_code/node_modules/firebase-admin/lib/utils/error.js:39:28)
at FirebaseMessagingError.PrefixedFirebaseError [as constructor] (/user_code/node_modules/firebase-admin/lib/utils/error.js:85:28)
at new FirebaseMessagingError (/user_code/node_modules/firebase-admin/lib/utils/error.js:241:16)
at validateMessage (/user_code/node_modules/firebase-admin/lib/messaging/messaging.js:320:15)
at Messaging.send (/user_code/node_modules/firebase-admin/lib/messaging/messaging.js:461:9)
at snapshot.forEach (/user_code/index.js:130:19)
at /user_code/node_modules/firebase-admin/node_modules/@firebase/database/dist/index.node.cjs.js:4255:20
at /user_code/node_modules/firebase-admin/node_modules/@firebase/database/dist/index.node.cjs.js:3669:24
at LLRBNode.inorderTraversal (/user_code/node_modules/firebase-admin/node_modules/@firebase/database/dist/index.node.cjs.js:2606:13)

A: Your JSON has "message" as its top level key:
{
    "message": {
        "notification": {
            "title": "Portugal vs. Denmark",
            "body": "great match!"
        },
        "token": user_info.device_id
    }
}

That's not valid.  "notification" and "token" should be top-level keys:
{
    "notification": {
        "title": "Portugal vs. Denmark",
        "body": "great match!"
    },
    "token": user_info.device_id
}

Please refer to the documentation for valid samples.


text:
Q: php using if and else if statement I am trying to create this page that gives different comments when different values of mass (of cats :3) are submitted by using if and else if. However the comment does not show up when I hit submit and I could not figure out the problem.
This is my code:
<?
if ($_POST['subBtn']) {
$mass = $_POST['theMass'];
$colour = $_POST['theColour'];
$name = $_POST['theName'];
$comment = $_POST['theComment'];
echo "
 The name of the cat is " . $name . ", the colour is  " . $colour . ", the mass is " . $mass . "." . $comment . "
";}
?>

<?
if ($_POST['subBtn']) {
$mass = $_POST['theMass'];

if ($mass <= 0 AND NULL ) {
$comment = "INVALID";

} else if ($mass >= 0 AND $mass <=2.5) {
$comment = "Skin and bones!!!";

} else if ($mass > 2.5 AND $mass<=5) {
$comment = "Small but healthy";

} else if ($mass > 5 AND $mass<=10) {
$comment = "Getting a little heavy!";

} else if ($mass >10 AND $mass<=15) {
$comment = "You may wanna hide the food!";

} else if ($mass >15 AND $mass<=20) {
$comment = "Are you sure this is a cat?";

} else if ($mass >20) {
$comment = "Need another job too feed your cat!
'Comment: OMG'
";

} else {
$comment = "
Nothing specific to comment...sorry try again
";

}
}
?>

<form action="crazy-cats.php" method="post">
Colour of the Cat:
<select name="theColour">
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
<option value="black">Black</option>
</select>

Mass: <input type="text" name="theMass" value="" />

Name: <input type="text" name="theName" value="" />

<input type="submit"name="subBtn" value="submit"/></input>

</form>

A: A few minor things wrong, including your PHP tags and a missing space on the submit input. You are also missing your theComment input. Try this
<?php

if (isset($_POST['subBtn'])) {
    $mass = $_POST['theMass'];
    $colour = $_POST['theColour'];
    $name = $_POST['theName'];
    $comment = $_POST['theComment'];
    echo "
 The name of the cat is " . $name . ", the colour is  " . $colour . ", the mass is " . $mass . "." . $comment . "
";

    $mass = $_POST['theMass'];

    if ($mass <= 0 AND NULL ) {
        $comment = "INVALID";

    } else if ($mass >= 0 AND $mass <=2.5) {
        $comment = "Skin and bones!!!";

    } else if ($mass > 2.5 AND $mass<=5) {
        $comment = "Small but healthy";

    } else if ($mass > 5 AND $mass<=10) {
        $comment = "Getting a little heavy!";

    } else if ($mass >10 AND $mass<=15) {
        $comment = "You may wanna hide the food!";

    } else if ($mass >15 AND $mass<=20) {
        $comment = "Are you sure this is a cat?";

    } else if ($mass >20) {
        $comment = "Need another job too feed your cat!
'Comment: OMG'
";

    } else {
        $comment = "
Nothing specific to comment...sorry try again
";

    }
echo "my comment on mass is ". $comment;
}
?>

<form action="test.php" method="post">
    Colour of the Cat:
    <select name="theColour">
        <option value="red">Red</option>
        <option value="green">Green</option>
        <option value="blue">Blue</option>
        <option value="black">Black</option>
    </select>

    Mass: <input type="text" name="theMass" value="" />

    Name: <input type="text" name="theName" value="" />

    <input type="hidden" name="theComment" value="<?= $comment ?>" />

    <input type="submit" name="subBtn" value="submit"/></input>

</form>

Granted, you should really consider validating your POST variables.

A: *

*Check the $_POST with isset.

*Delete $_POST['theComment'] line.

*Put your first PHP code below the second one.
Worked for me!


text:
Q: Position of subview in UIScrollview on zoom I have UIScrollView with image on background, which can zoom in and out. I've also added subview with image inside scrollview. I've added it on [50,50] coordinates.
But when I zoom UIScrollView, second image moved from it position (looks like real coordinates mess with scrollview zoom somehow). How to keep second on its place (visually) when I zoom?
before zoom
after zoom


text:
Q: Error when using chrome.notifications.create "Uncaught TypeError: Cannot read property 'create' of undefined" Hi I get an error when calling chrome.notifications.create from inside a function in the js of a chrome app. Can be used fine from outside a function but when within a function I get the following error:

Uncaught TypeError: Cannot read property 'create' of undefined

Here is the code:
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('submit').addEventListener('click', submit);
});
function submit() {
  var options = {
    type:"basic",
    title:"nameVal",
    message:"msgVal",
    iconUrl:"icon.png",
  };
  //notification options set
  chrome.notifications.create(options,callback);
  //notification set
}
function callback() {
  console.log("Notification succesfull");
  //notification confirmed
}

Thanks, I'm a noob when it comes to js and chrome apps so any help is appreciated :)

A: There are 2 possible causes.

*

*You are trying to use this from a content script. You can't: content scripts are very limited in what Chrome APIs they can call.

However, content scripts have some limitations. They cannot:
Use chrome.* APIs, with the exception of:
extension ( getURL , inIncognitoContext , lastError , onRequest , sendRequest )
i18n
runtime ( connect , getManifest , getURL , id , onConnect , onMessage , sendMessage )
storage

In that case, you need to delegate this call to a background script: send a message from the content script, get it in a background script and execute the action.

*You are trying to call it from an extension script, but did not declare the "notifications" permission.
In that case the fix is trivial - just add the permission.

A: Have you added the chrome notifications permissions to your manifest.json?
adding permissions: ["notifications",//other permissions here]
The permissions deals with what is and isnt loaded in your extension, and what you have access too.

A: I have one case for this undefined question when I use chrome.notifications.
var options = {
            type: "basic",
            title: "Extention Title",
            message: 'Extention Message",
            iconUrl: "images/icon_86.png" // My Case:Error in iconUrl
        };

But my 'icon_86.png' is not in the images folder.
Solution: It will be ok when I use my correct iconUrl.
('icon_86.png', it is in my project root directory)


text:
Q: Is there a way to add paths to an already rendered path TL;DR - I would like to add a Path or a Shape ? to an existing Shape and would like to know if I can somehow use path.addPath(...) See image for a visual of what I mean

I posted a question earlier about this but don't think I phrased it well and very possibly went about it the wrong way. All I would like to do is to add shapes to an existing shape. I see that Path has a method addPath(:) that lets us add one path to another.. and that would be perfect if I could figure out where to do it at. Here is my current attempt:
import SwiftUI

struct ContentView: View {
    @State private var path = Path()
    var body: some View {
        VStack {
            MyShape()
                .stroke(lineWidth: 3)
                .padding()
            HStack {
                AddHorizontalLineView()
                AddVerticalLineView()
                AddSquareView()
                AddDiagonalLineView()

            }
        }
    }

    private func addBoxToPath(_ path: Path) -> Path { <-- No where to call this
        var workingPath = path
        workingPath.addRect(workingPath.boundingRect)
        return workingPath
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

struct MyShape: Shape {
    func path(in rect: CGRect) -> Path {
        var path = Path()
        path.addRect(rect)
        return path
    }
}

struct AddHorizontalLineView: View {

    var body: some View {
        Button(action: {}){
            Rectangle()
                .stroke()
                .overlay(
                    HorizontalWire()
                        .stroke()
                        .padding()

                )
        }.frame(width: 50, height: 50)
    }

}

struct AddVerticalLineView: View {

    var body: some View {
        Button(action: { }){
            Rectangle()
                .stroke()
                .overlay(
                    VerticalWire()
                        .stroke()
                        .padding()
                )
        }.frame(width: 50, height: 50)
    }
}

struct AddSquareView: View {
    var body: some View {
        Button(action: {

        }){
            Rectangle()
                .stroke()
                .overlay(
                    Rectangle()
                        .stroke()
                        .padding()
                )
        }.frame(width: 50, height: 50)
    }
}

struct AddDiagonalLineView: View {
    var body: some View {
        Button(action: {}){
            Rectangle()
                .stroke()
                .overlay(
                    DiagonalWire()
                        .stroke()
                        .foregroundColor(.red)
                        .padding()
                )
        }
        .frame(width: 50, height: 50)
    }
}

struct DiagonalWire: Shape {
    func path(in rect: CGRect) -> Path {
        var path = Path()
        path.move(to: CGPoint(x: rect.minX, y: rect.minY))
        path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY))
        return path
    }
}

struct VerticalWire: Shape {
    func path(in rect: CGRect) -> Path {
        var path = Path()
        path.move(to: CGPoint(x: rect.midX, y: rect.minY))
        path.addLine(to: CGPoint(x: rect.midX, y: rect.maxY))
        return path
    }
}

struct HorizontalWire: Shape {
    func path(in rect: CGRect) -> Path {
        var path = Path()
        path.move(to: CGPoint(x: rect.minX, y: rect.midY))
        path.addLine(to: CGPoint(x: rect.maxX, y: rect.midY))
        return path
    }
}

Can paths be added dynamically like this or the entire setup needs to be done beforehand in path(in:) method of every type that conforms to Shape
I hope my question makes more sense now..

A: You can pass the Path into MyShape (although it really has very little point then -- you could just render the Path itself).
Here's a simple example (with some of your buttons removed since it'll be a very amount of work to hook up all of the logic). I also had to add an additional rect to the Path to start with, since your addBoxToPath depends on there being something in the Path so that the boundingBox isn't just a 0x0 rect:
struct ContentView: View {
    @State private var path = Path()
    var body: some View {
        VStack {
            MyShape(path: path)
                .stroke(lineWidth: 3)
                .padding()
            HStack {
                Button(action: {
                    path = addBoxToPath(path)
                }) {
                    Text("add")
                }
            }
        }.onAppear {
            path.addRect(CGRect(origin: .zero, size: CGSize(width: 200, height: 200)))
        }
    }

    private func addBoxToPath(_ path: Path) -> Path {
        var workingPath = path
        workingPath.addRect(workingPath.boundingRect.insetBy(dx: -5, dy: -5))
        return workingPath
    }
}

struct MyShape: Shape {
    var path : Path

    func path(in rect: CGRect) -> Path {
        return path
    }
}


text:
Q: Query optimisation postgres I have one partitioned table and I have some performance issues.
Here is DB fiddle with schema and query: https://www.db-fiddle.com/f/u3YABXJXUyAbkx54M3Fnjf/0
Some comments about explain this select.
I don't understand why Postgres iterate through indexes that cannot have data for each OR clause.
Ex for partitioned table (by site) digested_sales_1003 it checks:
((site_id = 1004) AND (archive_sequential_id >= 451) AND (archive_sequential_id <= 451))

This check is useless because it contains site_id from another partition.

Maybe there is another way to write this select? At the moment it takes a lot of time to run it because there exist many OR clauses.
Update 1
I added explain for this query:
https://drive.google.com/file/d/19E0RwRsPd18rKE3grYSBdq5TQidrmYa5/view?usp=sharing
Update 2:
I was able to optimize this select by using the union:
SELECT
    t."product_id" AS "productId",
    round(COALESCE(sum(t.qty), 0), 0) AS "totalItems",
    COALESCE(sum(t.final_amount_with_tax), 0) AS "finalAmountWithTax",
    COALESCE(sum(t.final_amount_without_tax), 0) AS "finalAmountWithoutTax",
    COALESCE(sum(t.final_amount_with_tax) - sum(t.initial_amount_with_tax), 0) AS "amountDiscountWithTax",
    COALESCE(max(t.product_price), 0) AS "productPrice",
    COALESCE(max(t.price), 0) AS "price"
FROM (
SELECT
  "product_id",
  qty,
  final_amount_with_tax,
  final_amount_without_tax,
  initial_amount_with_tax,
  product_price,
  price
FROM
  "digested_sales" AS "Sales"
WHERE
  "site_id" = 1003
  AND "archive_sequential_id" >= 681
  AND "archive_sequential_id" <= 682
  AND "receipt_status" IN ('blank', 'opened', 'accounted', 'closed')
  AND "content_type" = 'item'

UNION ALL

SELECT
  "product_id",
  qty,
  final_amount_with_tax,
  final_amount_without_tax,
  initial_amount_with_tax,
  product_price,
  price
FROM
  "digested_sales" AS "Sales"
WHERE
  "site_id" = 1004
  AND "archive_sequential_id" >= 451
  AND "archive_sequential_id" <= 451
  AND "receipt_status" IN ('blank', 'opened', 'accounted', 'closed')
  AND "content_type" = 'item'
  ...
) t
    GROUP BY
        "product_id"
    ORDER BY
        "totalItems" DESC
LIMIT 10

But this requires a lot of modifications in codebase.
Perhaps anyone else can give another solution without such drastic changes.
Update 3:
I tried to create custom statistic but no result:
CREATE STATISTICS IF NOT EXISTS digested_sales_s1 (mcv) ON archive_sequential_id, site_id
FROM digested_sales;

Maybe rewrite somehow the where clause or some configuration for Postgres to use partitions smarter.
Thx!


text:
Q: Xamarin "BindableProperty propertyChanged" does not fired when "RaisePropertyChanged" I use MvvmCross with Xamarin Form.
Therefore, I use RaisePropertyChanged to notify View.
However, RaisePropertyChanged does not fire propertyChanged in ViewA.
I do not know where to start to debug or check local variables...
Flow
If I change Data.Value somewhere, flow is like below.

*

*event Data.ValueChanged invoked.

*ModelA.OnValueChanged calls OnPropertyChanged

*ViewModelA.OnModelPropertyChanged calls RaisePropertyChanged

*expect ViewA.OnChanged called, but fail...

XAML
I run and check if XAML binding is working.
<DataTemplate x:Key="ViewB">
    <ViewB Data="{Binding Data}" />
</DataTemplate>

View
I defined BindableProperty as below.
// this class is abstract!
public abstract class ViewA : MvxContentView
{
        public static readonly BindableProperty DataProperty =
            BindableProperty.Create(
                propertyName: "Property",
                returnType: typeof(Data),
                declaringType: typeof(ViewA),
                defaultValue: null,
                propertyChanged: OnChanged);
        static void OnChanged(BindableObject bindable, object oldValue, object newValue)
        {
            if (newValue is null) { return; }

            // some codes
        }
}

// actual class

public partial class ViewB : ViewA
{
        public ViewB()
        {
            InitializeComponent();
        }
}

ViewModel
// this is also abstract!
public abstract class ViewModelA<T> : MvxViewModel<T>
{
        protected T _model;
        public Data Data
        {
            get => _model.Data;
        }

        public T Model
        {
            get => _Model;
            set
            {
                if (SetProperty(ref _model, value))
                {
                    // Register event handler
                    _model.PropertyChanged += OnModelPropertyChanged;
                }
            }
        }

        private void OnModelPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            switch (e.PropertyName)
            {
                case "DataChanged":
                    {
                        // I expect this will fire 'propertyChanged' of BindableProperty.
                        // But it is not fired...
                        RaisePropertyChanged(() => Data);
                    }
                    break;
            }
        }
}

// actual class
public class ViewModelB : ViewModelA<ModelA>
{
        public ViewModelB() : base()
        {

        }
}

Model
public class LayerModel : INotifyPropertyChanged
{
        public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        private Data _data;
        public Data Data
        {
            get
            {
                return _data;
            }
            set
            {
                if (_data != value)
                {
                    _data = value;
                    _data.ValueChanged += OnValueChanged;
                    OnPropertyChanged("DataChanged");
                }
            }
        }

        private void OnValueChanged(object sender, EventArgs e)
        {
            OnPropertyChanged(""DataChanged"");
        }
}

Data
public class Data
{
        private int _value;
        public int Value
        {
            get => _value;
            set
            {
                if(_value != value)
                {
                    // 2020.07.06 Edited
                    var evetArg = new DataChangedArgs
                    {
                        OldData = _value;
                        NewData = value;
                    };
                    _value = value;
                    ValueChanged?.Invoke(this, evetArg);
                }
            }
        }

        public event EventHandler ValueChanged;
}

2020.07.06 Added
public class DataChangedArgs : EventArgs
{
    public int OldData { get; set; }
    public int NewData { get; set; }
}

A: I suggest you to simplify some classes. You created a custom event named ValueChanged, its basically the same INotifyPropertyChanged. It's recommend you to use the interface, there are a class MvxNotifyPropertyChanged (in MvvmCross) that implement the previous interface.
Here is an approximation (This ViewModel does not inherit from MvxViewModel but as I said, it's an approximation).
***EDIT Question update: The class Data can't be modified.
You are trying to bind Data with a BindableProperty, in this case the Data should implement the INotifyPropertyChanged to notify the changes. I recommend you to read about  BindableObject.
In this case I propose the following solution:

*

*Create a class inheriting from Data: it will implement the INotifyPropertyChanged to notify the value changes.

The structure should look similar to:
...
public class MainPageViewModel : MvxNotifyPropertyChanged
{
    public Data Data => _model?.Data;

    private LayerModel _model;
    public LayerModel Model
    {
        get => _model;
        set
        {
            SetProperty(ref _model, value, () =>
            {
                RaisePropertyChanged(nameof(Data));
            });
        }
    }
}

public class LayerModel : MvxNotifyPropertyChanged
{
    private Data _data;

    public Data Data
    {
        get => _data;
        set => SetProperty(ref _data, value);
    }
}

public class Data
{
    private int _value;
    public int Value
    {
        get => _value;
        set
        {
            if (_value == value)
                return;
            var eventArgs = new DataChangedEventArgs(_value, value);
            _value = value;
            ValueChanged?.Invoke(this, eventArgs);
        }
    }
    public event EventHandler<EventArgs> ValueChanged;
}

public class DataChangedEventArgs : EventArgs
{
    public DataChangedEventArgs(int oldData, int newData)
    {
        OldData = oldData;
        NewData = newData;
    }

    public int OldData { get; }
    public int NewData { get; }
}

public class NotificationData : Data, INotifyPropertyChanged
{
    public static NotificationData FromData(Data data)
    {
        return new NotificationData {Value = data.Value};
    }

    public NotificationData()
    {
        ValueChanged += delegate
        {
            OnPropertyChanged(nameof(Value));
        };
    }

    public event PropertyChangedEventHandler PropertyChanged;

    [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}
...

The following is an demo with an abstract view, and a child view consuming the MainPageViewModel.
The abstract view should look similar to
public abstract class ViewA : ContentPage
{
    public Data ModelA
    {
        get => (Data)GetValue(ModelAProperty);
        set => SetValue(ModelAProperty, value);
    }

    public static readonly BindableProperty ModelAProperty =
        BindableProperty.Create(
            propertyName: nameof(ModelA),
            returnType: typeof(Data),
            declaringType: typeof(ViewA),
            defaultValue: null,
            propertyChanged: OnChanged);
    static void OnChanged(BindableObject bindable, object oldValue, object newValue)
    {
        if (newValue is null) { return; }

        // some codes
    }
}

*The child view.

Code behind:
...
public partial class MainPage : ViewA
{
    private int _counter = 10;
    private MainPageViewModel ViewModel => (MainPageViewModel) BindingContext;

    public MainPage()
    {
        InitializeComponent();

        //--example initialization
        var data = new Data
        {
            Value = _counter
        };
        ViewModel.Model = new LayerModel
        {
            Data = NotificationData.FromData(data)
        };
    }

    private void Button_OnClicked(object sender, EventArgs e)
    {
        ViewModel.Model.Data.Value = ++_counter;
    }
}
...

XAML:
<?xml version="1.0" encoding="utf-8" ?>
<xamstack:ViewA xmlns="http://xamarin.com/schemas/2014/forms"
       xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
       xmlns:d="http://xamarin.com/schemas/2014/forms/design"
       xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
       xmlns:xamstack="clr-namespace:xamstack;assembly=xamstack"
       mc:Ignorable="d"
       x:Class="xamstack.MainPage"
       ModelA="{Binding Data}">
    <ContentPage.BindingContext>
        <xamstack:MainPageViewModel/>
    </ContentPage.BindingContext>

    <StackLayout Padding="20">
        <Button Text="Increment" Clicked="Button_OnClicked"/>

                <FormattedString>

                </FormattedString>

    </StackLayout>
</xamstack:ViewA>

I hope it match your case.


text:
Q: How do you name i18n text? When I work on web application with my colleges. The name of i18n text are given quite freely.
It's like each one has his own rule of naming.
Take an example, we have a text "Create a new item", it is used for a link.

*

*A names the key in resources file like: CreateANewItem, which puts all word together.

*B prefers to name it like this: CreateLinkText, which describes it's usage in the application.

*C, however, wants to use: CreateItemText, which summarizes it's literal meaning.

When some text is longer or containing format of dynamic content. Naming varies a lot and agreement is hard to be met.
So I wonder whether there's a good naming rule or convention for the i18n text in different cases: short, long, with format, vulnerable to change, etc. Or how do you do this in your project? With this convention, maintenance can be easy and code is more readable.
Thanks a lot.

A: It's not something that I have seen so far in coding conventions. I guess it matters a lot less than other issues when it comes to coding standards.  That said, I don't know what platform you are using, but if it's .NET there is a very short page on naming conventions for resource identifiers here: http://msdn.microsoft.com/en-us/library/vstudio/ms229037%28v=vs.100%29.aspx


text:
Q: TF 2.1 installed in conda env. but TF2.3 imported. even TF2.1 env is activated Python version is 3.7.7
Anaconda env name is "py37tf21"
env "py37tf21" is installed tensorflow2.1
but, if I import tensorflow, the version is 2.3
what is the problem?
I attached anaconda console image below

A: You installed tensorflow-gpu 2.1 (which is just adds GPU support) but the actual tensorflow is tf-nightly 2.3 (nightly means that it's updated every night).
Try
conda uninstall tf-nightly
conda install tensorflow=2.1


text:
Q: SSIS: Working package fails after upgrade to SQL Server 2012 I have a SSIS package that was running fine on SQL2008R2 using Environmental Variables pointing to a configuration file for connection strings. Using VS2010 Shell, I upgraded the package for our SQL Server 2012 database. The package is still in package deployment model. The ProtectionLevel of the package is set to DontSaveSensitive. Run64BitRuntime = False. When I try and execute the package in VS, I am getting the following errors:

[OLE DB Destination [2]] Error: SSIS Error Code DTS_E_CANNOTACQUIRECONNECTIONFROMCONNECTIONMANAGER.  The AcquireConnection method call to the connection manager "DB_Connection" failed with error code 0xC0202009.  There may be error messages posted before this with more information on why the AcquireConnection method call failed.**
[SSIS.Pipeline] Error: OLE DB Destination failed the pre-execute phase and returned error code 0xC020801C.**

With full logging on, I see the first failure here:

Diagnostic,[ComputerName],OFFICE\username,DB_Connection,{5AD75239-D546-4AAF-963E-E195FC2F0C1E},{9EC48106-DDBD-40E9-8FBB-942BCF025EEE},3/26/2013 10:35:21 AM,3/26/2013 10:35:21 AM,0,(null),ExternalRequest_post: 'ITransactionJoin::JoinTransaction failed'. The external request has completed.**

The part that is really throwing me is that earlier in the package, the same "DB_Connection" manager is used successfully in a number of Execute SQL Tasks. So, it seems the connection strings are being read from the configurations correctly.
I have tried deleting\recreating the Connection Manager. I have verified that DTC is configured properly on both my local and the server. I have other packages connecting to the same SQL2012 DB using the same configuration method using Data Flow Tasks without a problem.
Any help anyone can give to point me in the right direction will be much appreciated. I would prefer to not have to move to a project deployment model at this time if I do not have to.

A: I was able to get my package to run locally. While I had checked the TransactionOption on my tasks to make sure they were set to Supported, it turned out that one of my sequence containers was set to Required. Not sure why this worked in SQL2008R2, but not in SQL2012. I changed my container to Supported and the package runs now.


text:
Q: Get waterfall plot values of a feature in a dataframe using shap package I am working on a binary classification using random forest model, neural networks in which am using SHAP to explain the model predictions. I followed the tutorial and wrote the below code to get the waterfall plot shown below
With the help of Sergey Bushmanaov's SO post here, I managed to export the waterfall plot to dataframe. But this doesn't copy the feature values of the columns. It only copies the shap values, expected_value and feature names. But I want feature names as well. So, I tried the below
shap.waterfall_plot(shap.Explanation(values=shap_values[1])[4],base_values=explainer.expected_value[1],data=ord_test_t.iloc[4],feature_names=ord_test_t.columns.tolist())

but this threw an error

TypeError: waterfall() got an unexpected keyword argument
'base_values'

I expect my output to be like as below. I have used background of 1 point to compute base value. But you are free to use background 1,10 or 100 as well. In the below output, I have stored the values and feature in one column called Feature. This is something similar to LIME. But not sure whether SHAP has this flexibility to do this?

update - plot

update code - kernel explainer waterfall to dataframe
masker = Independent(X_train, max_samples=100)
explainer = KernelExplainer(rf_boruta.predict,X_train)
bv = explainer.expected_value
sv = explainer.shap_values(X_train)

sdf_train = pd.DataFrame({
    'row_id': X_train.index.values.repeat(X_train.shape[1]),
    'feature': X_train.columns.to_list() * X_train.shape[0],
    'feature_value': X_train.values.flatten(),
    'base_value': bv,
    'shap_values': sv.values[:,:,1].flatten()   # i changed this to pd.DataFrame(sv).values[:,1].flatten()
})

A: Try following:
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import load_breast_cancer
from shap import TreeExplainer, Explanation
from shap.plots import waterfall

import shap
print(shap.__version__)

X, y = load_breast_cancer(return_X_y=True, as_frame=True)
model = RandomForestClassifier(max_depth=5, n_estimators=100).fit(X, y)
explainer = TreeExplainer(model)
sv = explainer(X)
exp = Explanation(sv.values[:,:,1],
                  sv.base_values[:,1],
                  data=X.values,
                  feature_names=X.columns)
idx = 0
waterfall(exp[idx])

0.39.0

Then:
pd.DataFrame({
    'row_id':idx,
    'feature': X.columns,
    'feature_value': exp[idx].values,
    'base_value': exp[idx].base_values,
    'shap_values': exp[idx].values
})

#expected output
row_id  feature feature_value   base_value  shap_values
0   0   mean radius -0.035453   0.628998    -0.035453
1   0   mean texture    0.047571    0.628998    0.047571
2   0   mean perimeter  -0.036218   0.628998    -0.036218
3   0   mean area   -0.041276   0.628998    -0.041276
4   0   mean smoothness -0.006842   0.628998    -0.006842
5   0   mean compactness    -0.009275   0.628998    -0.009275
6   0   mean concavity  -0.035188   0.628998    -0.035188
7   0   mean concave points -0.051165   0.628998    -0.051165
8   0   mean symmetry   -0.002192   0.628998    -0.002192
9   0   mean fractal dimension  0.001521    0.628998    0.001521
10  0   radius error    -0.021223   0.628998    -0.021223
11  0   texture error   -0.000470   0.628998    -0.000470
12  0   perimeter error -0.021423   0.628998    -0.021423
13  0   area error  -0.035313   0.628998    -0.035313
14  0   smoothness error    -0.000060   0.628998    -0.000060
15  0   compactness error   0.001053    0.628998    0.001053
16  0   concavity error -0.002988   0.628998    -0.002988
17  0   concave points error    0.000140    0.628998    0.000140
18  0   symmetry error  0.001238    0.628998    0.001238
19  0   fractal dimension error -0.001097   0.628998    -0.001097
20  0   worst radius    -0.050027   0.628998    -0.050027
21  0   worst texture   0.038056    0.628998    0.038056
22  0   worst perimeter -0.079717   0.628998    -0.079717
23  0   worst area  -0.072312   0.628998    -0.072312
24  0   worst smoothness    -0.006917   0.628998    -0.006917
25  0   worst compactness   -0.016184   0.628998    -0.016184
26  0   worst concavity -0.022500   0.628998    -0.022500
27  0   worst concave points    -0.088697   0.628998    -0.088697
28  0   worst symmetry  -0.026166   0.628998    -0.026166
29  0   worst fractal dimension -0.007683   0.628998    -0.007683

RandomForest is a bit special, this is why. When something fails with the new plots API, try to feed Explanation object.
UPDATE
To explain a 1 class datapoint vs a single 0 background datapoint:
back_id = 10
exp_id = 20
explainer = TreeExplainer(model, data=X.loc[[back_id]])
sv = explainer(X.loc[[exp_id]])
exp = Explanation(sv.values[:,:,1], sv.base_values[:,1], data=X.loc[[back_id]].values, feature_names=X.columns)
waterfall(exp[0])

Finally, as you asked for everything in the suggested format:
from shap.maskers import Independent
from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)

model = RandomForestClassifier(max_depth=5, n_estimators=100).fit(X_train, y_train)

masker = Independent(X_train, max_samples=100)
explainer = TreeExplainer(model, data=masker)
bv = explainer.expected_value[1]
sv = explainer(X_test, check_additivity=False)

pd.DataFrame({
    'row_id': X_test.index.values.repeat(X_test.shape[1]),
    'feature': X_test.columns.to_list() * X_test.shape[0],
    'feature_value': X_test.values.flatten(),
    'base_value': bv,
    'shap_values': sv.values[:,:,1].flatten()
})

but I'd definitely not show this to my mom.


text:
Q: javascript async sweetAlert So i have to try to create an async function that waits for a user input before returning, however, I am not quite sure how to do it:
  async createAlert() {
      return await swal({
          title: 'Are you sure?',
          text: "You won't be able to revert this!",
          type: 'warning',
          showCancelButton: true,
          confirmButtonText: 'Yes, delete it!',
          cancelButtonText: 'No, cancel!',
          reverseButtons: true
      }).then(function (result) {
          //user has answered we want to return the result
      })
  }

this jquery creates the following popup:

When the user presses either button the (then) part of the code is executed and here i want to return that result
Can anyone point me in the right direction?

A: Try it like that:
async createAlert() {
    try{
      let result = await swal({
          title: 'Are you sure?',
          text: "You won't be able to revert this!",
          type: 'warning',
          showCancelButton: true,
          confirmButtonText: 'Yes, delete it!',
          cancelButtonText: 'No, cancel!',
          reverseButtons: true
      });
      // SUCCESS
      return result;
    }catch(e){
        // Fail!
        console.error(e);
    }
}


text:
Q: Linq: filtering a list by time spans in another list I have two lists of objects. One list has a value and a datetime. The other list has a start and end time. I want to build a new list containing the objects in the first list that fall between any object in the second list's start time and end time plus 8 hours.
I was thinking I could just loop through the list with time spans and use linq to pull out the relevant items in the first list, check for duplicates and if the new list doesn't contain the value add it. That would work but it seems like there should be a way to do this just by using Linq.
Would anyone have an idea on how to do this with just linq?

A: Something like this?
values.Where(v => times.Any(t => v.DateTime >= t.StartTime
                              && v.DateTime <= t.EndTime)
            )


text:
Q: Почему получаю detached head? Команда git branch -a выводит вот такое
aleksey@aleksey:~/Downloads/NTZ/FittingRoom$ git branch -a
* develop
master
remotes/origin/HEAD -> origin/master
remotes/origin/develop
remotes/origin/master

после того как переключаюсь на ветку develop в репазитории origin:
$ git checkout origin/develop

получаю вот такой вывод через git branch -a
aleksey@aleksey:~/Downloads/NTZ/FittingRoom$ git branch -a
* (detached from origin/develop)
develop
master
remotes/origin/HEAD -> origin/master
remotes/origin/develop
remotes/origin/master

Так вот я тут почитал, что состояние detached получаем вот так

Оно характеризуется тем, что HEAD указывает не на вершину ветки, а просто на коммит. HEAD всегда должен указывать только на вершину какой-либо ветки!

Почему тогда я получаю detached если это моя ветка?? Это ж не просто коммит...
ПРАВКА
При переключении на удаленную ветку develop получаю такое сообщение
aleksey@aleksey:~/Downloads/NTZ/FittingRoom$ git checkout    origin/develop
Note: checking out 'origin/develop'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again.   Example:

git checkout -b new_branch_name

HEAD is now at ee16cd4... service

A: *

*
HEAD всегда должен указывать только на вершину какой-либо ветки!

Ветка в git — это плавающий указатель на коммит. у указателя нет и не может быть никакой «вершины».
Специальный указатель HEAD вполне может указывать и не на ветку, а на конкретный коммит (т.н. detached head). как в вашем случае.
Это просто «нестандартная» ситуация, которая может понадобиться в особых случаях.

*
Почему тогда я получаю detached если это моя ветка?

origin/develop — это ветка не из вашего локального хранилища. Насколько я понимаю из предыдущих ваших вопросов, к этой ветке «привязана» ваша локальная ветка develop. После полной синхронизации между ними (git pull+git push) обе они будут указывать на один и тот же коммит, и, следовательно, распакованные из этого коммита деревья файлов/каталогов будут полностью идентичны.
Потому вам, скорее всего, требуется
$ git checkout develop

а не
$ git checkout origin/develop

Ответы на дополнительные вопросы, заданные в комментарии:

1) Если я хочу переключиться на удаленную ветку develop, то почему я получаю сообщение про detached head?

Краткий ответ: потому что так задумано.
Более длинный ответ требует захода очень издалека. Попробую.
Как вы (надеюсь) знаете из толстых руководств, каждый коммит содержит в себе привязку к другому, родительскому коммиту (есть два исключения: самый первый в хранилище коммит не имеет такой привязки, а т.н. коммиты слияния (merge commits) могут содержать два и более родительских коммита). Посмотреть эту информацию можно, например, так:
$ git cat-file -p хэш-коммита
...
parent хэше-родительского-коммита
...

Как программа git «узнаёт», что туда подставить (при вызове git commit)? Она черпает информацию из файла HEAD в корне хранилища (.git/HEAD).
Если этот файл содержит хэш коммита (т.н. «состояние detached head), то этот коммит и есть родительский.
А если этот файл содержит ссылку на ветку («нормальное состояние») — ref: refs/heads/ветка — то хэш родительского коммита берётся из соответствующего файла — .git/refs/heads/ветка.
Саму процедуру создания коммита (её «технический» аспект) я описывать не буду («на полях слишком мало места» © пьер ферма), но упомяну про действие в финале этого процесса:
Если файл HEAD содержит хэш коммита («состояние detached head), то в этот файл записывается новое содержимое — хэш только что созданного коммита.
А если этот файл содержит ссылку на ветку («нормальное состояние»), то хэш вновь полученного коммита записывается в файл, на который указывает эта ссылка — .git/refs/heads/ветка. вот так и реализуется механизм «плавающего указателя на коммит» (которым и является ветка в git).
Возвращаемся к вопросу. Содержимое файла HEAD изменяется командой checkout. Так почему же, если мы укажем команде локальную ветку, она запишет в этот файл ref: refs/heads/ветка, а если укажем ветку удалённого хранилища, то она запишет в файл хэш коммита, на который указывает эта ветка (создав «состояние detached head), вместо, например ref: refs/remotes/хранилище/ветка?
А давайте посмотрим, что выйдет в таком случае.
Запишем руками в файл .git/HEAD, например, ref: refs/remotes/origin/master, внесём изменение в какой-нибудь файл в рабочем каталоге и сделаем git commit.
Хэш этого коммита будет вписан в указанный нами файл — .git/refs/remotes/origin/master. Вроде бы (пока) всё в порядке.
Но. если мы выполним команду fetch (действия, выполняемые ею, совершаются и в начале исполнения команды pull), то содержимое файла .git/refs/remotes/origin/master будет перезаписано информацией из удалённого хранилища! И наш новый коммит «сгинет» где-то в недрах нашего локального хранилища: на него не будет ссылок ни с помощью веток, ни с помощью меток (tags — это тоже указатели на коммит, но, в отличие от веток, «фиксированные», а не «плавающие»), ни с помощью строки parent хэш в каком-либо другом коммите. Да, конечно, этот бесхозный коммит можно будет посмотреть, помня его хэш, но и только.
Вот (в частности) чтобы не создавать такой «бардак», checkout и не запишет в файл HEAD ссылку на удалённую ветку.
Другая причина (по-моему, более веская) — неопределённость действий git при командах pull/push в нашей искусственно созданной ситуации. Да, в текущей реализации git откажется что-либо делать, выдав по простыне сообщений об ошибках. Но если реализовывать какое-то поведение в такой ситуации, то каким оно должно быть? Я лично затрудняюсь с ответом. Вполне вероятно, что и у разработчиков программы такая же проблема. Вот при git checkout удалённая-ветка они и решили записывать в HEAD хэш коммита (создавая «состояние detached head»), а не ссылку на удалённую ветку (создавая неопределённость).

2) Я перешел на локальную develop, сделал пуш в удаленный develop, потом сделал пул, и все равно когда переключаюсь на удаленый develop, он пишет detached from origin/develop - это нормально или нет?

Да, это нормально. см. выше.

3) Почему куда бы я не переключался, мой хед всегда стоит на месте remotes/origin/HEAD -> origin/master?

Эта строка в выдаче команды branch появляется благодаря наличию в хранилище файла refs/remotes/origin/HEAD, содержащего в вашем случае:
$ cat .git/refs/remotes/origin/HEAD
ref: refs/remotes/origin/master

Вы можете абсолютно безболезненно удалить этот файл. тогда эта строчка пропадёт из вывода команды branch.
Файл этот был создан во время клонирования и содержит информацию о том, какая именно ветка была распакована при этом в ваш рабочий каталог. Если бы вы клонировали с опцией --bare (git clone --bare url-хранилища), то этот файл не был бы создан (как и рабочий каталог с распакованными из хранилища файлами).
«Ваш» же файл HEAD, находится непосредственно в корне хранилища: .git/HEAD.


text:
Q: Error al enviar correo con PHPMailer y Gmail Buen día, hace poco la empresa donde trabajo migro sus cuentas de correo contratando el servicio de google workspace. Antes de hacerlo, estaban en localhost y los formularios de la página enviaban sin errores utilizando PHPMailer 5.2.24
Se que la versión es antigua, pero aún así funcionaba correctamente hasta que se migró a gmail y eso sólo tiene 1 mes aproximadamente.
Pueden orientarme para decirme que puede estar fallando, este es mi archivo mailer.php
<?php
    if(isset($_POST['name'])) {
        /// ===================================
        /// Retreive variables
        /// ===================================
        $name = isset($_POST['name']) ? stripcslashes($_POST['name']) : '';
        $phone = isset($_POST['phone']) ? stripcslashes($_POST['phone']) : '';
        $email = isset($_POST['email']) ? stripcslashes($_POST['email']) : '';
        $city = isset($_POST['city']) ? stripcslashes($_POST['city']) : '';
        $message = isset($_POST['message']) ? stripcslashes($_POST['message']) : '';

        /// ===================================
        /// Message Body
        /// ===================================
        $message = "
            <html>

            <head>
            <title>Contact Form</title>
            </head>

            <body>
            Mi mensaje
            </body>
            </html>
        ";
        $altMessage = "Informaci贸n de Contacto
        ----
        Name: $name
        ----
        Phone: $phone
        ----
        Email: $email
        ----
        Ciudad: $city
        ----
        Mensaje: $message
        ----";
        /// ===================================
        /// Sending Message
        /// ===================================
        /// The PHPMailer instance is created
        require 'PHPMailer/PHPMailerAutoload.php';
        $mail = new PHPMailer;
        /// PHPMailer Settings
        $mail->isSMTP();
        $mail->SMTPAuth = true;
        $mail->SMTPSecure = 'tls';
        $mail->Port = 587;
        $mail->Host = 'smtp.gmail.com';
        $mail->Username = 'email@gmail.com';
        $mail->Password = 'pass';
        /// The headers are setted
        $mail->setFrom('email@gmail.com', 'Email');
        $mail->addReplyTo('email@gmail.com', 'Email');
        /// Indicate that the email contains HTML data and UTF-8 characters
        $mail->CharSet = 'UTF-8';
        $mail->isHTML(true);
        /// The content is setted
        $mail->Subject = "Formulario de Contacto";
        $mail->Body    = $message;
        $mail->AltBody = $altMessage;
        /// The mail is sent and the result is translated to a status number
        if($mail->send()) $status = "ok";
        else $status = "fail";

        echo $status;
        //header("Location: index.php?sent=" . $status);
        exit();
    }
?>

Estos son los logs de error que me arroja
[08-Mar-2022 17:53:08 UTC] PHP Deprecated:  __autoload() is deprecated, use spl_autoload_register() instead in /home/public_html/lib/PHPMailer/PHPMailerAutoload.php on line 45
[08-Mar-2022 17:53:08 UTC] PHP Warning:  Use of undefined constant console - assumed 'console' (this will throw an Error in a future version of PHP) in /home/public_html/lib/mailer.php on line 89

Gracias por su ayuda.


text:
Q: ProcessBuilder does not work with argument I'm writing a program, one of the functions it clicking on a cell in the table with the name of the computer of a user, in the command line, a external program is called to connect to the computer remotely. The command looks like this:
"C:\Program Files\Vnc\MegaVNC\vncviewer.exe" /user vncadmin /password xxxxxx /server comp-01

"C:\Program Files\Vnc\MegaVNC\vncviewer.exe" is the location of the file, and "/ user vncadmin /password xxxxxx /server comp-01" argument. Please note that argument is written without quotes.
When you call this command from the command line, everything works.
My code with ProcessBuilder:
ProcessBuilder pb = new ProcessBuilder("C:/Program Files/Vnc/MegaVNC/vncviewer.exe ",  "/user vncadmin /password xxxxxx /server comp-01").start();

But it does not work. If you remove the argument, the called program is opened. But when initializing with an argument, the program itself hangs on the argument and the connection crashes.
I tried the following:
ProcessBuilder pb = new ProcessBuilder("C:/Program Files/Vnc/MegaVNC/vncviewer.exe", "/user vncadmin ", "/password xxxxxx ", "/server comp-01").start();

It does not work either. I guess that the problem is in the wrong interpretation compiler of the slash or spaces. Any thoughts?

A: You should pass all command line arguments as separate parameters to the process builder. Otherwise, they are internally quoted and therefore interpreted as a single argument by the called program.
ProcessBuilder pb = new ProcessBuilder("C:/Program Files/Vnc/MegaVNC/vncviewer.exe", "/user", "vncadmin", "/password", "xxxxxx", "/server", "comp-01").start();

I created a stupid batch "C:/Temp/test.bat":
@echo off
set argCount=0
for %%x in (%*) do (
   set /A argCount+=1
   echo %%x
)
echo Number of processed arguments: %argCount%

With new ProcessBuilder("C:/Temp/test.bat", "a b").start();, I got result:
"a b"
Number of processed arguments: 1

With new ProcessBuilder("C:/Temp/test.bat", "a", "b").start();, I got result:
a
b
Number of processed arguments: 2


text:
Q: rails undefined method `id' for nil:NilClass with belongs to relationship This is my item model:
class Item < ActiveRecord::Base
    has_many :props
end

This is my prop model ( porp is short from property)
class Prop < ActiveRecord::Base
  belongs_to :item
end

I have this problem.
When I create prop I require item_id.
But if there is no item with this id
I will get an error here:
<%= @prop.item.id %>

    <%= @prop.item.name %>

What do I do?
UPD:I can check its existence like <%= @prop.item.try(:name) %>  What are my other options?

A: I suggest use NullObject.
class Item
  def self.null
    Item.new(name: 'null')
  end
end

@item = @prop.item || Item.null

Then this code will not raise error:
<%= @item.id %>

<%= @item.name %>


text:
Q: Rails 4: Devise.secret_key was not set This seems to be a popular issue, since I found many similar questions on Stack Overflow:

*

*Devise Token Auth error: Devise.secret_key was not set

*Devise Secret Key was not set

*Mina and Devise.secret_key was not set
However, none of the above seems to help fix my problem.
Here is my situation:

*

*I installed Font Awesome with the font-awesome-rails gem, and it was working locally, but whenever I deployed to Heroku, Font Awesome icons were no longer appearing.

*So, I looked for answers to fix this problem, and found out that I needed to run RAILS_ENV=production bundle exec rake assets:precompile to make things work.

*However, when I run this command, I get the following error in Terminal:

rake aborted!
Devise.secret_key was not set. Please add the following to your Devise initializer:
config.secret_key = '—— MY_SECRET_KEY_HERE ———'
Please ensure you restarted your application after installing Devise or setting the key.
As per the solutions offered in the questions mentioned at the beginning of my question, I do haveconfig.secret_key = ENV['DEVISE_SECRET_KEY'] if Rails.env.production? in devise.rb
Also, as recommended here, I did run heroku config:set DEVISE_SECRET_KEY='—— MY_SECRET_KEY_HERE ———' -- app name_of_my_app_here.
Because I was not sure, I also ran heroku config:set DEVISE_SECRET_KEY=—— MY_SECRET_KEY_HERE ——— -- app name_of_my_app_here (without single quotes around my secret key).
But none of these things worked.
I keep getting the same error.
What am I doing wrong?

A: I found a solution to this problem.
Instead of keeping on struggling with the font-awesome-rails gem, I uninstalled it and replaced it with font-awesome-sass, which is the official Font Awesome gem for rails.
Following the guidelines offered here (section: EASY: SASS Ruby Gem), I then ran bundle and added:
@import "font-awesome-sprockets";
@import "font-awesome";

to my application.scss file.
I also removed the old @import "font-awesome.css"; line from the very same file.
Now, Font Awesome works both locally and on Heroku.


text:
Q: Android webview with popup window force closed I am working with an android app for web view.It contains an image button. On clicking the image button,it will shows a popup window over web view.The popup window contains edit text fields.On clicking submit button the edit text values are send as a mail and the popup will be dismissed. The problem I faced is I cant read edit text values.When it used the app is force closed..How to solve this problem please help me and thanks.
here is my code
        public class WebViewExample extends Activity {
   private WebView mWebView;
   private ImageView image;
   String str5;
    private PopupWindow mpopup;
    ProgressBar progressBar;
    Context context;
    /** Called when the activity is first created. */

     @Override
       public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.main);
    this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    if(isNetworkStatusAvialable (getApplicationContext())) {
        mWebView = (WebView) findViewById(R.id.webview);
         progressBar = (ProgressBar) findViewById(R.id.progressBar1);
         image =(ImageView)findViewById(R.id.image);

            mWebView.getSettings().setJavaScriptEnabled(true);
            mWebView.setWebViewClient(new wapWebViewClient());
            mWebView.loadUrl("http://facebook.com//");

            mWebView.setWebChromeClient(new WebChromeClient() {
                @Override
                public void onProgressChanged(WebView view, int progress)
                   {
                   if(progress < 100 && progressBar.getVisibility() == View.GONE){
                       progressBar.setVisibility(View.VISIBLE);

                   }
                   progressBar.setProgress(progress);
                   if(progress == 100) {
                       mWebView.setVisibility(View.VISIBLE);
                       progressBar.setVisibility(View.GONE);
                   }
                   }
               });

         } else {
                 Toast.makeText(getApplicationContext(), "internet is not avialable ", Toast.LENGTH_LONG).show();

            }
              ImageButton   imageButton1 = (ImageButton) findViewById(R.id.imageButton1);
             ImageButton    imageButton2 = (ImageButton) findViewById(R.id.imageButton2);

       imageButton1.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {

               Intent feedbackEmail = new Intent(Intent.ACTION_SEND);

             feedbackEmail.setType("text/email");
             feedbackEmail.putExtra(Intent.EXTRA_EMAIL, new String[] {"prince@gmail.com"});
              feedbackEmail.putExtra(Intent.EXTRA_SUBJECT, "Feedback");
             startActivity(Intent.createChooser(feedbackEmail, "Send Feedback:"));
        }
       });

          imageButton2.setOnClickListener(new OnClickListener() {

             public void onClick(View v) {
               View popUpView = getLayoutInflater().inflate(R.layout.popup, null); // inflating popup layout
               mpopup = new PopupWindow(popUpView, LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, true); //Creation of popup

                 mpopup.showAtLocation(mWebView, Gravity.CENTER, 0, 0);    // Displaying popup
                ImageButton Sub = (ImageButton) popUpView.findViewById(R.id.submit);
                 EditText t1=(EditText)findViewById(R.id.editText1);
                 EditText t2=(EditText)findViewById(R.id.editText2);
                 EditText t3=(EditText)findViewById(R.id.editText3);

                String str1=t1.getText().toString();
                String str2=t2.getText().toString();
                String str3=t3.getText().toString();
                String str4=t3.getText().toString();
                 str5="name:"+str1+"  "+"email:"+str2+"  "+"number:"+str3+"  "+"idea:"+str4;
                Sub.setOnClickListener(new OnClickListener() {

                public void onClick(View v) {

                    Intent email = new Intent(Intent.ACTION_SEND);

                    email.setType("text/email");
                    email.putExtra(Intent.EXTRA_EMAIL, new String[] {"prince@gmail.com"});
                     email.putExtra(Intent.EXTRA_SUBJECT, "I have an Idea");
                     email.putExtra(Intent.EXTRA_TEXT, str5);
                       startActivity(Intent.createChooser(email,"Send Your Idea"));

                     mpopup.dismiss();

                }
             });
         }
         });

     }

      private void incrementPercentage(){
       int mProgressStatus=0;
       mProgressStatus++;//i declared it as a private Integer on the activity class.
       progressBar.setProgress(mProgressStatus);
     }

       public static boolean isNetworkStatusAvialable (Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
             if (connectivityManager != null)
       {
            NetworkInfo netInfos = connectivityManager.getActiveNetworkInfo();
            if(netInfos != null)
            if(netInfos.isConnected())
               return true;
        }
       return false;
   }

        private class wapWebViewClient extends WebViewClient {

     @Override
       public boolean shouldOverrideUrlLoading(WebView view, String url) {
     // view.loadUrl(url);
          return false;
      }

     @Override
        public void onPageFinished(WebView view, String url) {
      // when the page loaded splash screen has been invisible
     // mWebView.setVisibility(View.VISIBLE);
      progressBar.setVisibility(View.GONE);
      image.setVisibility(View.GONE);

     }

        @Override
        public void onReceivedError(WebView view, int errorCode,
               String description, String failingUrl) {
          // if any error occured this message will be showed
             Toast.makeText(WebViewExample.this, "Error is occured, please try again..." + description, Toast.LENGTH_LONG).show();
       }
     }

      @Override
         public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
          // setting of back button
      mWebView.goBack();
             return true;
           }
           return super.onKeyDown(keyCode, event);
          }
        }

here is y xml
  <?xml version="1.0" encoding="utf-8"?>
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:background="#ffffff"
android:layout_height="match_parent"
android:orientation="vertical" >

    <EditText
    android:id="@+id/editText1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:hint="@string/name"
    android:layout_alignLeft="@+id/editText2"
    android:layout_alignParentTop="true"
    android:layout_marginTop="42dp"
    android:ems="10" />

   <EditText
    android:id="@+id/editText2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/editText1"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="20dp"
    android:ems="10"
    android:hint="@string/email" />

    <EditText
    android:id="@+id/editText3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/editText2"
    android:layout_below="@+id/editText2"
    android:layout_marginTop="19dp"
    android:ems="10"
    android:hint="@string/phone" />

   <EditText
    android:id="@+id/editText4"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/editText3"
    android:layout_below="@+id/editText3"
    android:layout_marginTop="34dp"
    android:ems="10"
    android:hint="@string/idea"
    android:inputType="textMultiLine" />

   <TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_alignRight="@+id/submit"
    android:layout_marginRight="16dp"
    android:layout_marginTop="15dp"
    android:text="@string/hading" />

   <ImageButton
    android:id="@+id/submit"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/editText4"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="43dp"
    android:background="@null"
    android:src="@drawable/submit" />

  </RelativeLayout>

new xml
    <?xml version="1.0" encoding="utf-8"?>
  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:background="#ffffff"
android:layout_height="match_parent"
android:orientation="vertical" >

    <EditText
    android:id="@+id/editText1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/textView1"
    android:hint="@string/name"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="48dp"
    android:ems="10" />

   <EditText
    android:id="@+id/editText2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:hint="@string/email"
    android:layout_alignLeft="@+id/editText1"
    android:layout_below="@+id/editText1"
    android:layout_marginTop="30dp"
    android:ems="10" />

<EditText
    android:id="@+id/editText3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:hint="@string/phone"
    android:layout_alignLeft="@+id/editText2"
    android:layout_below="@+id/editText2"
    android:layout_marginTop="30dp"
    android:ems="10" />

<EditText
    android:id="@+id/editText4"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/editText3"
    android:hint="@string/idea"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="31dp"
    android:ems="10"
    android:inputType="textMultiLine" />

<ImageButton
    android:id="@+id/submit"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@null"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="51dp"
    android:src="@drawable/submit" />

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="72dp"
    android:text="@string/hading" />

     </RelativeLayout>

A: Mistakes I could get from code:
Replace
EditText t1=(EditText)findViewById(R.id.editText1);
EditText t2=(EditText)findViewById(R.id.editText2);
EditText t3=(EditText)findViewById(R.id.editText3);

with

EditText t1=(EditText)popUpView.findViewById(R.id.editText1);
EditText t2=(EditText)popUpView.findViewById(R.id.editText2);
EditText t3=(EditText)popUpView.findViewById(R.id.editText3);

You are getting null in those edittexts. ecause those views are in popu and you are trying to get them from main activity.
And the values of edittexts should be retrieved in strings in onClick of dialog's submit as:
Sub.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {

        String str1=t1.getText().toString();
        String str2=t2.getText().toString();
        String str3=t3.getText().toString();
        String str4=t3.getText().toString();
        str5="name:"+str1+"  "+"email:"+str2+"  "+"number:"+str3+"  "+"idea:"+str4;

        //Email intent goes here...
    }
});

Hope this helps.


text:
Q: HTML/CSS tables don't allign, text in tables still pad I have a problem where everything is just messed up. I've tried a couple of solutions, but my Profile Page won't align as it should. I Want everything to be in the center and be clean. Here's an example of what it looks like: https://imgur.com/t0OzF35 Also, how do I add a right border AKA add a border between Username: and Edmin.

                    Change profile picture

                        <input type="file" class="form-control" id="image" placeholder="Image" name="multipartFile" required="required"/>
                        Profile picture can be up to 32 MBs

                        E-mail:

                        Name:

                        Username:

                        Age:

A: EDITED
table {
  border-spacing: 0;
  margin:0 auto;
  padding: 0;
  border-collapse: collapse;
  width: 50%;
  table-layout: fixed;
}
table, th, td {
  padding: 0;
  border: 3px solid black;
  border-collapse: collapse;
}

A: Use one table containing multiple rows.
Don't put every row in a table of its own.
(And don't use th elements for data cells, use td for that. Use th only for heading cells).


text:
Q: how to generate a java class code from a sqlite database for ORMLite Given a sqlite database as input, I want to know how can i can generate an ORMLite java class that map with the associated database.  Many thanks.

A: You could try Telosys Tools, an Eclipse plugin for code generation
working from an existing database with customizable Velocity templates
See: https://sites.google.com/site/telosystools/
A set of templates is available on GitHub for JPA :
//github.com/telosys-tools-community/jpa-templates-TT206-v2
A Java class for JPA is very near to ORMLite so it's possible to adapt the templates
in oder to generate ORMLite java classes
A global tutorial for Spring MVC and JPA :
//sites.google.com/site/telosystutorial/springmvc-jpa-springdatajpa
(you can just consider the JPA bundle)

A: I am new to ORMLite and also have the same need.
For SQLite, I read and parse the SQL statement in the field "sql" of table "sqlite_master".
Although it works well with tables, I had to find an other way to deal with views; now I use Excel to load data from views into ADO objects and parse fields' properties to generate Java POJO class definition text, then paste it onto IDE.
It's not perfect, saved me a lot of time though.

A: This is not something that ORMLite can do itself -- you are going to have to help it.  If you want to edit your question and include your SQLite schema, I'll edit my answer to include some of the necessary object.
For example, here are some field mappings:

*

*INTEGER -> int

*VARCHAR -> String

*BOOLEAN -> boolean

*TIMESTAMP -> Date

*BIGINT -> long
...

I would suggest creating a class and using the TableUtils.getCreateTableStatements(ConnectionSource, Class<T>) method to see what schema is dumped out and how it compares to your existing schema.  Then add or modify the fields until you get as close a match as possible.


text:
Q: Graph theory exercise 6 I've just started learning about graph theory and I am doing some exercises online.
This is the question I'm currently on:
What is the minimum number of edges in a graph with 6 vertices, when there is also a cycle which includes all the vertices of the graph?

What is a cycle and what is the best approach to take for working this out?

A: A cycle of length $n$ (i.e. having $n$ edges) includes exactly $n$ vertices (why?), so if you want all $6$ vertices to be included, you would need a cycle of length $6$, so you need at least $6$ edges.
Now is $6$ edges attainable? Consider a hexagon.


text:
Q: What is the minimum current a current transformer can sense? Datasheet of AS-100 mentions a maximum current it can sense before saturation, but what is the minimum current it can sense.
For instance, if I put 10 mA 50Hz through a conductor passing through the sensor AS-100 (1:50 ratio), will it produce 0.2mA through a 50 Ohm (suggested) terminal resistance on it's secondary?

A: If you look at the data sheet, the secondary DC resistance is 0.6 ohms.  The recommended load resistance is 50 ohms. As the data sheet says, this value was selected to give a 1 volt output for 1 ampere flowing through the primary.  As a check, 1 ampere in the primary will yield (for a 50:1 ratio) 20 ma in the secondary.  With 20 ma through it, the 50 ohm load resistor will indeed produce 1 volt of output.  With that said, the minimum current that can be sensed is probably limited by the noise level of your sensing circuit.  With 10 ma in the primary the secondary level will be 0.2 ma which will yield 10 millivolts across the 50 ohm load resistor.  This should be well above any electronic noise in your sensing circuit.

A: Sensing is not performed by the transformer -- it is performed by the circuitry attached to the secondary. The minimum amount is determined by the equipment measuring it -- the load it places on the secondary, significant digits of precision and the reference voltage.

A: Current transformers are like any other transformers and obey the laws of Faraday and Lenz.  What is important to understand are the sources of error and how real world materials act.  Before a transformer can actually transmit energy, the poles in the magnetic molecules must be first aligned in the same direction.  This is the initial magnetizing current.  Additional losses based upon degree of saturation are also present.  These IR losses are also subtracted from the potential output.  The material of the core chosen and its size determine the amount of these losses.  For the application chosen, AS-100, the CT will produce a non-linear output and probably will not give the expected signal, as the magnetizing current from the wire through the hole is not enough to excite the core enough to transmit energy through the core.  A different CT should be chosen, one with a highly specialized core that is designed to excite with a minimum of excitation current.  Core such as nickel and the new nanocrystal cores would provide a much better result.  Please refer to this treatise that explains fully the model of a CT - http://www.crmagnetics.com/assets/technical-references/analysis_of_ct_error.pdf


text:
Q: Using Kafka without RabbitMQ I am testing MassTransit with Kafka without RabbitMQ
I need a IBusControl, can i use bus.UsingInMemory()?
Is it safe to use for Kafka ITopicProducers?
Does features like scheduling/sagas will work with Kafka or with InMemory bus?

A: You can use an in-memory bus with Kafka, but realize that the in-memory bus is not durable. The only reason you would want to use it is because you want to consume/produce Kafka messages without using an accompanying broker.
Sagas work with Kafka just fine, since sagas are a type of consumer.
Scheduling is not supported with Kafka, since it isn't a broker. Using scheduling with in-memory is not recommended outside of unit tests.


text:
Q: Taylor series $ \sqrt{\frac{t}{t+1}}$ Could someone tell me how to calculate
 $ \sqrt{\frac{t}{t+1}}$
it should be   $ \sqrt t - \frac{t^{\frac{3}{2}}}{2} +O(t^{\frac{5}{2}}) $

A: $$\frac{t}{1+t}=t(1-t+t^2-\ldots)\implies\sqrt\frac{t}{1+t}=\sqrt{t\left(1-t+t^2-\ldots\right)}=$$
$$=\sqrt t\,\sqrt{1-t+\ldots}=\sqrt t\left(1-\frac{t}{2}-\frac{t^2}{4}+\ldots\right)=\sqrt t-\frac{t^{3/2}}{2}+\mathcal O(t^{5/2})$$
since
$$\sqrt {1-x}=1+\frac{x}{2}-\frac{1}{4}x^2+\ldots$$

A: Simple:
$$
\sqrt{\frac{t}{1 + t}}
   = \sqrt{t} \cdot (1 + t)^{-1/2}
$$
Now use the binomial theorem:
$$
(1 + t)^{-1/2} = \sum_{n \ge 0} \binom{-1/2}{n} t^n
$$
Now:
$$
\binom{-1/2}{n} = (-1)^{n - 1} 2^{-2n} \binom{2n}{n}
$$


text:
Q: Url rewrite not working for first segment of url Here is the rule I use in my .htaccess :
RewriteCond %{HTTP_HOST} ^domaina.com
RewriteRule ^(.*) http://domainb.com/$1 [P]

For some reason this works perfectly for everything such as http://domaina.com/something-here but fails miserably only for requests to http://domaina.com
Can anyone shed some light as to why that is ?
Thank you.
EDIT
Problem solved, I had forgotten the http:// part! However, this brought about a new problem: http://domaina.com/john doesn't work, but http://domaina.com/john/doe does...

A: Try adding L (last) flag:
RewriteCond %{HTTP_HOST} ^domaina\.com$ [NC]
RewriteRule ^(.*)$ http://domainb.com/$1 [P,L]

A: As it turns out, it was a matter of placement :
Other rewrite rules I had were on top of the new ones and therefore overriding what I was trying to create.


text:
Q: Error while passing an array to a component (React - TypeScript) Trying to describe inputs for Component 2 but receiving an error. Please advise how to pass and describe arrays input properly.
Model:
interface IIncident {
    id: string,
    title: string
}

Component 1:
interface IncidentManagerProps {
}

interface IncidentManagerState {
    incidents: IIncident[]
}

class IncidentManager extends Component<IncidentManagerProps, IncidentManagerState> {
    constructor(props: IncidentManagerProps) {
        super(props);
        this.state = {
            incidents: []
        }
    }

    render = () => {
        const {incidents} = this.state;

        return (

All Incidents

                    //Error displayed here
                    <Incidents incidents={incidents}/>

        );
    }
}

Component 2: incidents any type resolve the issue but that's is not a good way
interface Incidents {
    incidents: IIncident[]
}

const Incidents = (props: Incidents) => props.incidents.map((inc: IIncident) => (
   <Incident key={inc.id} title={inc.title}/>
));

Error message:
JSX element type 'Element[]' is not a constructor function for JSX elements.
  Type 'Element[]' is missing the following properties from type 'Element': type, props, key  TS2605

A: render() cannot return elements array, just a single element. Try wrapping your 2nd component output to any element like this:
const Incidents = (props: {incidents: IIncident[]}) => <>
  {props.incidents.map(inc =>
    <Incident key={inc.id} title={inc.title}/>
  )}
</>;


text:
Q: Motion in affine geometry $V$ is a finite euclidean vectorspace and $\sigma:V->V$ is a motion, this means that $d(\sigma(a_i),\sigma(a_j))=d(a_i,a_j)$ for an affine coordinate system $a_0,...,a_n$
I know the following two things: $\sigma^2=id_V$ and $A:=\{v\in V:\sigma(v)=v\}$
I already proved that A is an affine subspace, but I would like to know why A is non-empty.
My second question is, why $\sigma$ is identical to a reflection $\sigma_A(v):=\sigma_{V_A}(v-a)+a$ where $\sigma_{V_A}$ is an orthogonal reflection on $V_A$ and $a\in A$ is arbitrary.

A: I assume that $\sigma$ is an affine map, and $V$ is endowed by a scalar product.
In this case, $\sigma(x)=Mx+b$ for some $M:V\to V$ linear map and $b=\sigma(0)\in V$. Since $\sigma(b)=\sigma(\sigma(0))=0$, we have $Mb+b=0$, so the midpoint of $0$ and $b$, $b/2$ will be in $A$. (Check it!)
(Actually, over a field of characteristic $2$, we can have that $A$ is empty, for example by any translation..)
For the second question, reduce it to the case when $0\in A$, ie. $\sigma$ is actually linear. Then, using that it keeps the distances of a basis, you could prove that it keeps all distances (keeps norm), using the following identity:
$$||x-y||^2=||x||^2+||y||^2-2\langle x,y\rangle .$$
(By hypothesis, and assuming $a_0=0$ we have that $||\phi(a_i)||=||a_i||$ and $||\phi(a_i-a_j)||=||a_i-a_j||$ for all $i,j$.)
So we also have that $\sigma$ keeps the scalar product: $\sigma\in O(V)$, that is, fixing an orthonormal basis, its matrix will be an orthonormal matrix, satisfying $\sigma^2=id$, hence having $\pm 1$ as eigenvalues, ...


text:
Q: Is it possible to create a debug logfile in code-only with Log4net Since it's for debugging purpose only I don't want to edit the app.config and the solution I've found online start by editing it. Is it possible to create a debug logfile only in code with Log4net?

A: You can try the following option.
((log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository()).Root.Level = Level.Debug;
((log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository()).RaiseConfigurationChanged(EventArgs.Empty);

You can find more details here


text:
Q: How to bulk edit documents via firestore console I'm wondering if there is a way to bulk update documents in firestore via the Firestore console. I'm aware that I am able to do this via code, as shown in answers such as this one and this one, but I'm mainly looking for a way to do this via the Firestore console/UI.
At the moment, I am able to update one document at a time, but is there a way for me to update all documnts (matching a filter for example) at the same time to have the same update?:

I find that I often want to do this when I'm prototyping, and having to write code just to do a bulk update adds additional time to something I would think would be simple to do via the UI. I'm currently on the free spark plan, so I also can't use cloud-functions, meaning I have to spin up a server to do the bulk update via the admin SDK. Is there a way to bulk update documents via the firestore console or some other UI?

A: Currently Cloud firestore supports editing single documents via console. but not in bulk. The only way to edit documents in bulk is either using Batch writes or Transactions. If it is necessary for you to use console, you can raise feature request here


text:
Q: Modified Binary Search Array EDIT: included improved code.
My current logic is incorrect. I want to have a binary search that will find the integer "wantToFind", and if it is not in the array will subtract 1 from wantToFind until it is found.
I have subtracted this from a larger program, that guarantees that the 1st item in the array will be the lowest wantToFind (the value we want to find) can ever be.
However, despite following binary search conventions the program is still getting stuck when looking for higher numbers such as 88.
float list[15] = {60,62,64,65,67,69,71,72,74,76,77,79,81,83,84};

// binary search
int wantToFind = 88; //other tests are 65, 61, 55
bool itemFound = false;

int current = 0;
int low = 0;
int high = 14;

current = (low+high)/2;
//int previousCurrent = -1;

do {
    do {
        //if 61 < 72
        if (wantToFind < list[current])
        {
            //smaller
            //previousCurrent = current;
            high = current - 1;
            current = (low+high/2);
        }
        else if (wantToFind > list[current])
        {
            //bigger
            //previousCurrent = current;
            low = current + 1;
            current = (low+high/2);
        }
        else{
            if(wantToFind == list[current])
            {
                itemFound = true;
            }
        }

    } while (low >= high);

    if (itemFound == false)
    {
        wantToFind--;
    }
} while (itemFound == false);

printf("\n%d", wantToFind); //which will be a number within the list?
    return 0;

A: Your exit condition should be low >= high. Then you will find the first value, that's either smaller or bigger than the targeted one (or of course the one, you're actually searching). Then you don't need this if-statement any more: if (current < 0 || current > 14) but you have to check/adjust the result after the loop.

A: I can't imagine why you'd want while (low >= high). This will cause the loop to terminate the first time through. I'm pretty sure you want while (low <= high).
Also, when the item isn't found, there are three possibilities:

*

*wantToFind is smaller than the smallest item in the list.

*wantToFind is larger than the largest item in the list.

*wantTofind would be located somewhere in the list.

In cases 2 and 3, the value of current when the inner loop exits will be one more than the index that contains the first item smaller than wantToFind.
In case 1 above, current will be equal to 0.
The point is that there's no need for the outer loop. When the binary search fails, the value of current tells you the insertion point.
Also, you probably want to early-out when the item is found.
Finally, do yourself a favor and turn that do...while into a while loop. That is:
while (!itemFound && low <= high)

You'll find that a lot easier to reason about.


text:
Q: Delete button with dialogOK in Grid Im trying to implement delete button in GRID, same as with CRUD. I found dialogOK (http://agiletoolkit.org/blog/introduction-to-dialog-integration/), but guess i don't know how to use it right.
My code:
$gridC=$this->add('Grid');
$gridC->setModel('Campaign');
$gridC->addcolumn('Button', 'Delete')->js('click', $this->js()->univ()->dialogOK('Yey','Some custom javascript action here',$this->delete()));

//test only
$gridC->addcolumn('Button', 'Deletex')->js('click')->univ()->dialogOK('Are you sure?','This will take you to other page',$this->js()->univ()->page($this->api->getDestinationURL('admin')));

...

function delete(){
  ...
}

When i click on the button the delete() function starts right away, before i click ok. Also modal window is started :(
Any suggestions, i searched but couldn't find any good example..
NEXT DAY:
I checked the thing again, im almost shure i did it the right way, but i think i found a bug i dialogOK (http://agiletoolkit.org/blog/introduction-to-dialog-integration/)
I i re-create this example on any normal page:
$button = $this->add('Button');
$button->js('click')->univ()->dialogOK('Are you sure?','This will take you to other page',
  $button->js()->univ()->page($this->api->getDestinationURL('index'))
);

The page redirects to index page, it doen't wait for OK button clicked. Insted it opens the dialogOK, but in the background redirects to index page..
I'm using atk 4.2.5 from master branch..

A: OK, that webpage has some bugs :( I would really appreciate if you could edit it and send in pull request in Github atk4-web.
Some tips to get you on road:

*

*Try to use dialogConfirm() method not dialogOK(). Is it working then?

*Try to add ->_enclose() after ->page(). That'll enclose JS expression in function.

*If dialogConfirm() works and similar dialogOK() does not work, then I guess there is small bug in dialogOK() method. There should be close: if(fn)fn(), instead of close: fn, in atk4_univ.js file dialogOK method.

Can you try these tips and tell me what works for you? Sorry I didn't do that myself - I'm really out of time now :(


text:
Q: APNS certificates: Changing servers - new IP Address but same domain I'm about to change VPS providers for the server which keeps my APNS push notifications. The domain name will remain the same but the IP address is changing.
Can I just copy my APNS certificates from the old server to new server or do I have to recreate them?
Thanks for your help

A: You don't need to regenerate APNS certificates until the certificate has not expired.
Certificates works on all serveurs, and are not generated for a server in particulary.