text:
Q: Unable to print the following basic pattern I want to print This pattern.
1 2 3 4
1 2 3
1 2
1
So I implement this
 x = int(input("Enter number of row:\n"))

 for i in range(1,x+1):

     for j in range(1,x+1):

         print(j,end=" ")

     print()

but I don't get as showed in question
I know that no. of column have to decreased by one but how ever I can not managed to do that.
please tell me what I have to do in order to solve the question.

A: This is how i would do it:
x = int(input("Enter number of row:\n"))
for i in range(1,x+1):
    print(*range(1,x+1))
    x-=1


text:
Q: How do i fill the missing part in this picture using OpenCV (python)? I have to generate a new image such that the missing portion of the black ring is shown
For Example, consider this image
As we can see , a sector of the inner black ring is missing, and my task is to identify
where to fill in. I have to take a plain white image of same dimensions as the input image and predict
(marked by black color) the pixels that i'll fill in to complete the black outer ring. A
pictorial representation of the output image is as follows:
Please help me out...i'm new to OpenCV so please explain me the steps as detailed as possible.I am working in python, so i insist on a python solution for the above problem

A: You can find a white object (sector) whose centroid is at the maximum distance from the center of the picture.
import numpy as np
import cv2

img = cv2.imread('JUSS0.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
w,h=gray.shape
thresh=cv2.threshold(gray, 253, 255, cv2.THRESH_BINARY )[1]
output = cv2.connectedComponentsWithStats(thresh, 4, cv2.CV_32S)
num_labels = output[0]
labels = output[1]
centroids = output[3]
polar_centroids_sq=[]
for i in range(num_labels):
    polar_centroids_sq.append((centroids[i][0]-w/2)**2+(centroids[i][1]-h/2)**2)
idx=polar_centroids_sq.index(max(polar_centroids_sq))
out=np.uint8(255*(labels==idx))

cv2.imshow('sector', out)
cv2.imwrite('sector.png', out)

A: This is one of many possible approaches.

*

*make every pixel that is not black into white, so your image is black and white. This means your processing is simpler, uses less memory and has only 1 channel to process instead of 3. You can do this with cvtColor() to get greyscale and then cv2.threshold() to get pure black and white.

*repeatedly construct (imaginary) radial lines until, when checking the pixels along the lines, you have 2 black stretches. You now have the inner and outer radius of the inner, incomplete circle. You can get the coordinates of points along a line with scikit-image line function.

*draw that circle in full in black with cv2.circle()

*subtract that image from your initial black and white image so that only the differences (missing part) shows up in the result.
Of course, if you already know the inner and outer radius of the incomplete black ring, you can completely omit the second step above and do what Yves suggested in the comments.
Or, instead of second step above, run edge detection and HoughCircles to get the radii.

Another approach might be to call cv2.warpPolar() to convert your circular image to a long horizontal one with 2 thick black lines, one of them discontinuous. Then just draw that line across the full width of the image and warp back to a circle.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Generate and plot different solutions with NDSolve with different conditions in one line I have a set of equations pdes and some initial/boundary conditions bcs. These conditions depend on some parameters, which I can group as n sets,bcsi labeled by i where i=1,...,n.
When solving the equations (for one single set of conditions) I write
sols=NDSolveValue[{pdes,bcs},{y1[x],y2[x],...,yN[x]},{x,xi,xf}]

If I want to plot the solution, lets say y1[x], I write
ploty1=Plot[First@sols,{x,xi,xf}]

Now, if I want to solve the equations for each set of conditions, and then to plot, for example, y1[x] again, I would do the following
sol1=NDSolveValue[{pdes,bcs1},{y1[x],y2[x],...,yN[x]},{x,xi,xf}]
sol2=NDSolveValue[{pdes,bcs2},{y1[x],y2[x],...,yN[x]},{x,xi,xf}]
...
soln=NDSolveValue[{pdes,bcsn},{y1[x],y2[x],...,yN[x]},{x,xi,xf}]

and make plots in the same way, etc, and do the following
Plot[{First@sol1,...,First@soln},{x,xi,xf}]

to get the solutions for y1[x] depending on each set of conditions. Is there a way to construct this plot not solving for each set separately but as a List or Table, in such a way that just doing
Plot[First@solutions,{x,xi,xf}],

where solutions is the set of solutions for each condition, allows to see how y1 changes when I change the conditions?

A: First put the conditions in a table
bcst={bcs1,...bcsn}

As suggested above, to solve the equations together
sols=Table[NDSolveValue[{pdes,bcst[[i]]},{y1[x],...,yN[x]},{x,xi,xf}],{i,1,n}]

to plot the curves for y1[x] for each condition, we write
Plot[Evaluate[Table[First@sols[[i]],{i,1,n}]],{x,xi,xf}]

Since we have n plots, one can give colors to each curve by setting n color inside PlotStyle


text:
Q: Firebase fail receiving notification from php I can succesfully recive notifications from Firebase console, but when I call the PHP function to do it, doesn't recive anything. As I saw on internet, this is more less how I can send these notifications. And what I don't understand what is different when I switch to Firebase console (because it works from there). I don't think the problem is from my app, because I send a request to their server and then they should send to my device. It is very possible to make a mistake, please don't be too rude. I am still a beginner. Thank you for your wise answers!
PHP function
function push_notification_android($device_id,$message){

    //API URL of FCM
    $url = 'https://fcm.googleapis.com/fcm/send';

    $api_key = 'MY_KEY';

    $fields = array (
        'to' => $device_id,
        'data' => array(
                "message" => $message,
                "id" => '1',
        ),
    );

    //header includes Content type and api key
    $headers = array(
        'Content-Type:application/json',
        'Authorization: key='.$api_key
    );

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
    $result = curl_exec($ch);

    curl_close($ch);
    echo $result;
    return $result;
}

{"multicast_id":7370520341381062896,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1611404485967655%6b34551f6b34551f"}]}

A: By documentation you can send two types of messages to clients:
Notification messages - handled by the FCM SDK automatically.
Data messages - handled by the client app.
If you want to send data message implement your FirebaseMessagingService like this (this is only example what to do, you can use it but improve it with your needs and also test all possible solution to understand how that works)
public class MyFirebaseMessagingService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        if (remoteMessage.getData().size() > 0) {
            handleDataMessage(remoteMessage.getData());
        }else if (remoteMessage.getNotification() != null) {
            //remove this line if you dont need or improve...
            sendNotification(100, remoteMessage.getNotification().getBody());
        }
    }

    private void handleDataMessage(Map<String, String> data) {
        if(data.containsKey("id") && data.containsKey("message")){
            String message = data.get("message");
            int id;
            try {
                id = Integer.parseInt(data.get("id"));
            }catch (Exception e){
                e.printStackTrace();
                id = 1; // default id or something else for wrong id from server
            }

            sendNotification(id, message);
        }
    }

    private void sendNotification(int id, String messageBody) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 , intent, PendingIntent.FLAG_ONE_SHOT);
        String channelId = "appChannelId"; //getString(R.string.default_notification_channel_id);
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this, channelId)
                        .setSmallIcon(R.drawable.icon) //TODO set your icon
                        .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.iconpro_round)) //TODO set your icon
                        .setContentTitle("MyApp")
                        .setContentText(messageBody)
                        .setAutoCancel(true)
                        .setSound(defaultSoundUri)
                        .setContentIntent(pendingIntent);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) notificationBuilder.setPriority(NotificationManager.IMPORTANCE_HIGH);
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelId, "MyApp", NotificationManager.IMPORTANCE_DEFAULT);
            if (notificationManager != null) {
                notificationManager.createNotificationChannel(channel);
            }
        }
        if (notificationManager != null) {
            notificationManager.notify(id, notificationBuilder.build());
        }
    }
}

A: @adnandann's answer explains the reason indeed: you're sending a data message, while the Firebase console always sends a notification message (which is automatically displayed by the operation system).
So you have two options:

*

*Display the data message yourself, which @adnandann's answer shows how to do.

*Send a notification message from your PHP code, which you can do with:
$fields = array (
    'to' => $device_id,
    'notification' => array(
      "title" => "New message from app",
      "body" => $message
    ),
);


text:
Q: Primefaces commandButton inside a DataGrid I have a datagrid and its element is a panel and some components including a commandbutton, i load the data from the bean but the actionlistning of the commandbutton is not firing even in eclipse debug mode it does not reach the method.

        <h:form>

            <f:facet name="left">

</f:facet>

                    <f:facet name="left">

                    </f:facet>
                    <f:facet name="right">

                    </f:facet>

        </h:form>

is the problem related to the form ?

A: It should be nested from p:column, it worked fine


text:
Q: Firebase Email/Password sign up not working So I have a sign up function in my app, what it does is ask for an email and password and then  creates an account with those parameters.
Then the app logs the user with the newly created account and requests the email and uid that Firestore created, and puts it in a collection.
For whatever reason, the app crashes when I try to retrieve the account details from Firebase and when I check it, no account was ever created and no collection was made (Tho it never got to that point so I guess yeah).
What am I doing wrong?
This is the code (And no, for this project I don't need any username):
public class Register extends AppCompatActivity {
    EditText RegisterEditTextEmail, RegisterEditTextPassword, RegisterEditTextPasswordAgain;
    Button RegisterButton;
    FirebaseAuth auth = FirebaseAuth.getInstance();
    FirebaseFirestore db = FirebaseFirestore.getInstance();
    boolean emailGood = false, passwordGood = false, passwordMatch = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        RegisterButton = findViewById(R.id.RegisterButton);
        RegisterEditTextEmail = findViewById(R.id.RegisterEditTextEmail);
        RegisterEditTextPassword = findViewById(R.id.RegisterEditTextPassword);
        RegisterEditTextPasswordAgain = findViewById(R.id.RegisterEditTextPasswordAgain);
        RegisterButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String email = RegisterEditTextEmail.getText().toString();
                String password = RegisterEditTextPassword.getText().toString();
                String passwordAgain = RegisterEditTextPasswordAgain.getText().toString();

               ........
               checking if the email and password are good
               ........

                if (emailGood && passwordGood && passwordMatch) {
                    auth.createUserWithEmailAndPassword(RegisterEditTextEmail.getText().toString(), RegisterEditTextPassword.getText().toString())
                            .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                                @Override
                                public void onComplete(Task<AuthResult> task) {
                                    if(task.isComplete()){
                                        FirebaseUser user = auth.getCurrentUser();
                                        Map<String, Object> map = new HashMap<>();
                                        map.put("email", user.getEmail()); <---- crashes here
                                        map.put("uuid", user.getUid());
                                        db.collection("users")
                                                .document(user.getUid().toString())
                                                .set(map)
                                                .addOnSuccessListener(new OnSuccessListener<Void>() {
                                                    @Override
                                                    public void onSuccess(Void unused) {
                                                        Intent intent = new Intent(Register.this, MainActivity.class);
                                                        startActivity(intent);
                                                    }
                                                }).addOnFailureListener(new OnFailureListener() {
                                            @Override
                                            public void onFailure(@NonNull Exception e) {
                                                Toast.makeText(Register.this, e.getMessage().toString(), Toast.LENGTH_LONG);
                                            }
                                        });
                                    }
                                }
                            });

                }
            }
        });
    }
}

The error I get:
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.clockin, PID: 3607
    java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getEmail()' on a null object reference
        at com.example.clockin.Register$1$1.onComplete(Register.java:74)
        at com.google.android.gms.tasks.zzj.run(com.google.android.gms:play-services-tasks@@17.2.0:4)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)

Edit:
Someone suggested a NullPointer solution, I guess I failed to elaborate further.
My problem isn't that the account is returned as null, my problem is that for whatever reason, FirebaseAuth refuses to create an account in the first place. And as a result, the account is null.
Why won't FirebaseAuth make an account?
Edit 2:
Apparently my API key in Google Cloud is expired, I tried looking around for a fix but didn't manage to find one, anyone knows how to fix it?

A: The problem is in this snippet:
auth.createUserWithEmailAndPassword(RegisterEditTextEmail.getText().toString(), RegisterEditTextPassword.getText().toString())
    .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(Task<AuthResult> task) {
            if(task.isComplete()){
                FirebaseUser user = auth.getCurrentUser();
                Map<String, Object> map = new HashMap<>();
                map.put("email", user.getEmail());

When a Task completes it can either be successful or unsuccessful and you need to handle both case separately. Only when the task is successful will auth.getCurrentUser() have a value.
So you should only try to access that (and its getEmail) when the task is successful:
public void onComplete(Task<AuthResult> task) {
    if(task.isSuccessful()){ //  Change this test
        FirebaseUser user = auth.getCurrentUser();
        Map<String, Object> map = new HashMap<>();
        map.put("email", user.getEmail());

When the task failed, you can learn more about why it failed by logging the exception it contains. So:
public void onComplete(Task<AuthResult> task) {
    if(task.isSuccessful()){ //  Change this test
        FirebaseUser user = auth.getCurrentUser();
        Map<String, Object> map = new HashMap<>();
        map.put("email", user.getEmail());
        ...
    }
    else {
        Log.e("AUTH", "Creating user failed", task.getException()); //
    }


text:
Q: How to assign values to objects in numpy-array using vectorize I'm a beginner with python and I wrote this code to create a bidimensional numpy-array of objects to simulate a physical lattice.
    import numpy as np

    class Site:
       def __init__(self, label, status):
          self.l = label
          self.s = status

     vSite = np.vectorize(Site(0,2), otypes=[object])
     init_array = np.arange(25).reshape((5,5))
     lattice = np.empty((5,5), dtype=object)
     lattice[:,:] = vSite(init_array)

but I have errors in output
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-2-0c0dfed8eab8> in <module>()
      9 init_array = np.arange(25).reshape((5,5))
     10 lattice = np.empty((5,5), dtype=object)
---> 11 lattice[:,:] = vSite(init_array)

~/.local/lib/python3.5/site-packages/numpy/lib/function_base.py in __call__(self, *args, **kwargs)
   2753             vargs.extend([kwargs[_n] for _n in names])
   2754
-> 2755         return self._vectorize_call(func=func, args=vargs)
   2756
   2757     def _get_ufunc_and_otypes(self, func, args):

~/.local/lib/python3.5/site-packages/numpy/lib/function_base.py in _vectorize_call(self, func, args)
   2823             res = func()
   2824         else:
-> 2825             ufunc, otypes = self._get_ufunc_and_otypes(func=func, args=args)
   2826
   2827             # Convert args to object arrays first

~/.local/lib/python3.5/site-packages/numpy/lib/function_base.py in _get_ufunc_and_otypes(self, func, args)
   2770                 ufunc = self._ufunc
   2771             else:
-> 2772                 ufunc = self._ufunc = frompyfunc(func, len(args), nout)
   2773         else:
   2774             # Get number of outputs and output types by calling the function on

TypeError: function must be callable

Someone could help me?

A: The np.vectorize() function must take a function as first argument, not a common variable. The function it is called upon will then be able to be called on a numpy array to apply it on every element of the array.
If you want to initialize a 3D numpy array, you should use the np.empty(dim) function as follow :
a=np.empty((n,m,l), dtype=object)

This array will have n * m * l values.
You can then iterate through the matrix with a loop to fill it :
for i in np.ndindex(a.shape):
    a[i] = Site(1,1)

A: I've found that np.frompyfunc is the best tool for creating arrays of custom classes.  Your use of np.vectorize also works, since you specify the otypes, but frompyfunc already returns objects, and is a bit more direct and faster.
In [667]: class Site:
     ...:        def __init__(self, label, status):
     ...:           self.l = label
     ...:           self.s = status
     ...:        def __repr__(self):   # to improve display
     ...:            return f'Site({self.l},{self.s})'
     ...:
In [668]: f = np.frompyfunc(Site, 2,1)
In [669]: f(np.zeros((2,3),int), np.ones((2,3),int)*2)
Out[669]:
array([[Site(0,2), Site(0,2), Site(0,2)],
       [Site(0,2), Site(0,2), Site(0,2)]], dtype=object)
In [670]: f(np.arange(3),np.array(['a','b','c']))
Out[670]: array([Site(0,a), Site(1,b), Site(2,c)], dtype=object)

I should warn you though that accessing those Site objects will also require the use of frompyfunc.  Arrays of objects do not take full advantage of numpy computational speed. numpy computation is fastest when working with numbers, not objects.


text:
Q: SQLite UNION right only if left is empty In SQLite there is no such function to UNION only if left expression results empty set.
Consider these as two base tables test and test2:
create table test(
  id integer not null primary key,
  val integer not null
);

insert into test values(1, 10);
insert into test values(2, 20);
insert into test values(3, 30);

create table test2(
  id integer not null primary key,
  val integer not null
);

insert into test2 values(1, 100);
insert into test2 values(2, 200);
insert into test2 values(3, 300);

I have this simple query:
select * from test
union
select * from test2;

I want this to always query the first select and the second if (and only if) the first gives empty result.
To illustrate:
select * from test
union
select * from test2;

This shall return all rows from test, and then quit: don't touch test2 at all.
Another sample:
select * from test where val > 50
union
select * from test2;

First query gives empty results, move on and do the second select, shall result all rows from test2.
I want this to be as fast as possible => therefore I don't want to add a subquery for the second select.
Here is the playground.

A:
I don't want to add a subquery for the second select.

Well, the two queries are functionally independent in the query, and there is no way for the second query to tell that the first one came up empty, unless you use a subquery.
So, you would typically use a not exists condition in the second query, with a subquery that matches the first query.
So:
select * from test
union all
select * from test2 where not exists (select 1 from test)

Or if there is a where clause in the first query:
select * from test where val > 50
union all
select * from test2 where not exists (select 1 from test where val > 50)

A: A SQL SELECT is declarative. It expresses what you want, not how to obtain it. It is up to the db engine to convert it to a query plan. Some SQL dialects allow to hint the engine to do things a certain way, but not SQLite.
The only solution is to query the two part from an imperative language (python, java, C#, ...) that allows you to implements the do something first and check result then do something else


text:
Q: Pandas, get elements in an specific order I have a pandas dataframe
col1    col2
Apple     70
Lemon     80
Banana    90

and I have a list with the elements of col1 in a specific order:
my_list = ['Banana', 'Apple', 'Lemon']

I need to get the values of col2 following the order of my_list
result = [90, 70, 80]

How could I achieve that?
Thanks
PS: I see several solutions to my problem, so maybe I oversimplified it, because some of the solutions will not be efficient for my real problem (my fault for oversimplifying).
The problem is a little more complex, my dataframe has more columns and a lot of rows.
col1    col2   col3
Apple     70   red
Lemon     80   red
Banana    90   red
Lemon     2    blue
Apple     3    blue
Banana    4    blue
Lemon     67   green
Banana    68   green
Apple     69   green

Basically the values of col1 repeat for each value of col3 (but the order might be different!)
What I need is for each value of col3 to get a vector of values from col2 but always with the same order.
So I obtain my_list by doing:
my_list = np.unique(df['col2'])

and then I iterate for each element of col3 obtaining the simplyfied example that I posted.
This doesn't change the answers, but I might pick one or another taking in account the whole picture.

A: Use reindex if unique values of col1:
a = df.set_index('col1').reindex(my_list)['col2'].values.tolist()
print (a)
[90, 70, 80]

Or ordered categoricals:
from pandas.api.types import CategoricalDtype
cat_type = CategoricalDtype(categories=my_list, ordered=True)

df['col1'] = df['col1'].astype(cat_type)

df = df.sort_values('col2', ascending=False)
print (df['col2'].tolist())
[90, 80, 70]

df['col1'] = pd.Categorical(df['col1'], my_list, ordered=True)

df = df.sort_values('col2', ascending=False)
print (df['col2'].tolist())
[90, 80, 70]

A: Pandas 0.15 introduced Categorical Series
df = ...
my_list = ['Banana', 'Apple', 'Lemon']

df['col1'] = pd.Categorical(df['col1'], my_list )
df.sort("col1")

result = df['col2']

A: You can create a series and use map. This should be more efficient than sorting, using pd.Categorical, or list comprehensions.
s = df.set_index('col1')['col2']
res = list(map(s.get, my_list))

print(res)

[90, 70, 80]

A: pandas has "Built-in" sorting methods, try this:
df['column'].sort_values(ascending=False)


text:
Q: How to call a variable from another class First off, do you guys know of any good tutorial sites or books to learn how to code for iOS6?
Now to the problem at hand, I have an AppDelegate class and a ViewController class.
I am using the AppDelegate class to find my current location and save it as an NSString.
I have a label in my ViewController class where I want to display my location.
In java I would usually just do something like this
label.text = AppDelegate.myLocationString;

But I am fairly new to objective c and I don't know how to do the equivalent. To be honest I'm not even sure if I am taking the correct approach for this language. Is there another way to approach this problem in objective c?
I've tried searching around for how to do it but I'm not even sure that I'm phrasing my searches correctly so I don't know if I'm searching in the right direction.
Any help that could be offered would be very much appreciated
My code as it is now:
AppDelegate.h
#import <UIKit/UIKit.h>

#import CoreLocation/CoreLocation.h

@class BIDViewController;

@interface BIDAppDelegate : UIResponder <UIApplicationDelegate, CLLocationManagerDelegate>

@property (strong, nonatomic) UIWindow *window;

@property (strong, nonatomic) BIDViewController *viewController;

@property (strong, nonatomic) CLLocationManager *locationManager;

@property (strong, nonatomic) NSString *myPosition;

@end

LocationManager class from AppDelegate.m
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    NSDate *eventDate = newLocation.timestamp;
    NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
    if (abs(howRecent) < 15) {

        //if it is within the last 15 seconds, use it. Else do nothing.

        if (newLocation.horizontalAccuracy < 35.0) {

            //location seems pretty accurate so we will use it

            NSLog(@"latitude: %+.6f, longitude: %+.6f\n", newLocation.coordinate.latitude, newLocation.coordinate.longitude);
            NSLog(@"Horizontal accuracy: %f", newLocation.horizontalAccuracy);

            int latDegrees = newLocation.coordinate.latitude;
            int lonDegrees = newLocation.coordinate.longitude;

            double latDecimal = fabs(newLocation.coordinate.latitude - latDegrees);
            double lonDecimal = fabs(newLocation.coordinate.longitude - lonDegrees);

            int latMinutes = latDecimal * 60;
            int lonMinutes = lonDecimal * 60;

            double latSeconds = ((latDecimal * 3600) - (latMinutes * 60));
            double lonSeconds = ((lonDecimal * 3600) - (lonMinutes * 60));

            _myPosition = [NSString stringWithFormat:@"Lat: %d, %d, %1.4f, Lon: %d, %d, %1.4f", latDegrees, latMinutes, latSeconds, lonDegrees, lonMinutes, lonSeconds];

        }
    }
}

ViewController.h
#import <UIKit/UIKit.h>

@interface BIDViewController : UIViewController

@property (weak, nonatomic) IBOutlet UILabel *positionLabel;

@end

ViewController.m
#import "BIDViewController.h"
#import "BIDAppDelegate.h"

@interface BIDViewController ()

@end

@implementation BIDViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

    //I have tried setting the label's text here but to no avail so far, I have been
    //able to set it as "blah" with the following line:
    //
    //    positionLabel.text = @"blah";
    //
    //and I have tried things such as the following to populate the label with the
    //myPosition variable:
    //
    //    positionLabel.text = _myPosition;
    //            or
    //    positionLabel.text = AppDelegate._myPosition;
}

- (void)viewDidUnload
{
    [self setPositionLabel:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

@end

A: In your ViewController
BIDAppDelegate *appDelegate = (BIDAppDelegate *)[UIApplication sharedApplication].delegate;
[positionLabel setText:appDelegate.myPosition];

A: To reference the App Delegate from your view controller, first import its definition (which you've ready done):
#import "BIDAppDelegate.h"

and then in code get the delegate:
BIDAppDelegate *appDelegate = (BIDAppDelegate *)[[UIApplication sharedApplication] delegate];

and then get the location from the delegate:
CLLocation *location = appDelegate.locationManager.location;

and then call whatever method you like on the location object:
NSString *descr = location.description;

Or get the pre-calculated position with:
NSString *position = appDelegate.myPosition;

A:
How to call a variable from another class?

Assume you are in ClassB
ClassA *aObj=... ; //create an object of ClassA
aObj.propertyName=...;//set the property or ivar
NSString *string=aObj.propertyName;//retrieve it

do you guys know of any good tutorial sites or books to learn how to
  code for iOS6?

http://www.lynda.com/Apple-training-tutorials/106-0.html
http://www.raywenderlich.com/tutorials


text:
Q: Does std::string {} = "hi"; induce temporary materialization? Motivated by What does the expression std::string {} = "..." mean?;
Does the left hand side of the std::string {} = "hi"; induce temporary materialization and if it does, which of the mentioned scenarios below does it fall within?

Temporary materialization occurs in the following situations:

*

*1- when binding a reference to a prvalue;

*2- when performing a member access on a class prvalue;

*3- when performing an array-to-pointer conversion
or subscripting on an array prvalue;

*4- when initializing an object of type std::initializer_list from a braced-init-list;

*5- when typeid is applied to a prvalue

*6- when sizeof is applied to a prvalue

*7- when a prvalue appears as a discarded-value
expression.

I would expect that std::string {} induces temporary materialization since we create an object that is temporary, but couldn't find which scenario would fit here.

A: The expression is transformed (after overload resolution) to std::string{}.operator=("hi") by [over.match.oper]/2, at which point temporary materialization applies per the second point in the list. (In standardese, [expr.ref]/2 says that . expects its first operand to be a glvalue, and [basic.lval]/7 applies the temporary materialization conversion whenever a prvalue appears in such a context.)


text:
Q: Upload Image/Video to FTP Swift 3.0 I am using below code to upload Image/Video to FTP. The complete image is not getting uploaded. Lowe part of the image is getting cut. At the end of the upload process, the complete data is said to be uploaded but the image is getting cut. I am able to upload small images and videos. The issue is for large images and videos. Kindly let me know the changes I need to do in the below code.
    let buf     = movieData?.bytes.assumingMemoryBound(to: UInt8.self)
    let buf2    = movieData?.bytes.assumingMemoryBound(to: UInt8.self)
    let buf3    = UnsafeMutablePointer<UInt8>.allocate(capacity: (movieData?.length)!)

    var leftOverSize        = movieData?.length
    let bytesFile           = movieData?.length
    var totalBytesWritten   = 0
    var bytesWritten        = 0

    let ftpUrl = NSURL(string: "FTP_URL")
    let stream      = CFWriteStreamCreateWithFTPURL(nil,ftpUrl!).takeUnretainedValue()
    let cfstatus    = CFWriteStreamOpen(stream) as Bool
    // connection fail
    if !cfstatus {
        print("Not connected")
    }

    repeat{
        // Write the data to the write stream
        bytesWritten = CFWriteStreamWrite(stream, buf, leftOverSize!)
        print("bytesWritten: \(bytesWritten)")
        if (bytesWritten > 0) {
            totalBytesWritten += bytesWritten
            // Store leftover data until kCFStreamEventCanAcceptBytes event occurs again
            if (bytesWritten < bytesFile!) {
                leftOverSize = bytesFile! - totalBytesWritten
                memmove(buf3, buf2! + bytesWritten, leftOverSize!)
            }else{
                leftOverSize = 0
            }

        }else{
            print("CFWriteStreamWrite returned \(bytesWritten)")
            break
        }

        if !CFWriteStreamCanAcceptBytes(stream){
            sleep(1)
        }
    }while((totalBytesWritten < bytesFile!))

    CFWriteStreamClose(stream)

A: try LxFTPRequest Framework to upload a file to FTP server
Save Data locally
extension Data {

    func save(withName name: String) -> String{
        let fileManager = FileManager.default
        let paths = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent(name)
        print(paths)
        fileManager.createFile(atPath: paths as String, contents: self, attributes: nil)
        return paths
    }
}

FTP Request
    guard let data = UIImageJPEGRepresentation(image, 0.5) else {
        return
    }

    let filePath = data.save(withName: yourfileName)
    let uploadUrl = URL(string: ftpBaseUrl + imageName)

    request = LxFTPRequest.upload()
    request.serverURL = uploadUrl
    request.localFileURL = URL(fileURLWithPath: filePath)
    request.username = username
    request.password = password

    request.successAction = { (resultClass, result) in
        // success ...
    }

    request.failAction = { (domain, error, errorMessage) in
        //Fail ....
    }

    request.progressAction = {(_ totalSize: Int, _ finishedSize: Int, _ finishedPercent: CGFloat) -> Void in

    }

    request.start()


text:
Q: Resharper - Issue with App_GlobalResources I've got an issue when I try to use App_GlobalResources/Common.resx in views.
I write, for example:
@Resources.Common.Yes

The solution builds without issues however reshaper shows an error.
Reshaper tries to use Common from a different project and that one is internal.
Regards


text:
Q: Oledb skips the first column of excel file I have a problem when I try to save an Excel file into a DataTable on C# using OLEDB.
The DataTable doesn't have the first column of my Excel file but have an extra empty column as last column. I don't know what I'm doing wrong. If my Excel file have something like this:
ID, Name, Adress
The DataTable columns are:
Name, Adress, F3(empty)
Here is my function:
    public DataTable GetExcel(string[] files, string sheetName, string pathName)
    {
        for (int i = 0; i < files.Length; i++)
        {
            string strConn = string.Empty;
            if (string.IsNullOrEmpty(sheetName)) { sheetName = "Sheet1"; }
            FileInfo file = new FileInfo(files[i]);
            if (!file.Exists) { throw new Exception("Error, file doesn't exists!"); }
            string extension = file.Extension;
            switch (extension)
            {
                case ".xls":
                    strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + file + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
                    break;
                case ".xlsx":
                    strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + file + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'";
                    break;
                default:
                    strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + file + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
                    break;
            }
            OleDbConnection cnnxls = new OleDbConnection(strConn);
            OleDbDataAdapter oda = new OleDbDataAdapter(string.Format("select * from [{0}$]", sheetName), cnnxls);
            oda.Fill(dataTable);
        }
        return dataTable;
    }

Thank you!

A: In the end the problem was the Excel file, I just copied everything to another Excel file using another computer and worked. I don't know what was wrong.
I hope I can help someone else.
Thanks for your answers.

A: I don't know whether this is what happened to you or not, but I can hopefully help someone else.
When I had this bug it was because my csv file had a whitespace at the start of it which made Excel ignore everything after it - which was the entire string that I wanted to use (For some reason, Excel ignores everything that comes after a whitespace in C#).
You can either use Trim, or if you want to be safer, use this Regex to target only words, numbers, and a few more characters:
string s = file.ToString().Trim();
string s = new Regex(@"(\w|[0-9]|\\|\/|\.|\:)+").Match(file.ToString()).Value;

A: It worked after writing one value on the first column of the excel. Looks like it skips them when no data is found on the first columns.


text:
Q: The concept of 'sending' data to the GPU in OpenGL ES Having only used Direct3D and OpenGL on desktop computer, I have this concept in my head that whenever buffers need to be updated you need to send this data to the GPU with calls such as glBufferData()/glBufferSubData(), and that this type of thing should be minimised at all costs.
Since OpenGL ES works with embedded systems such as phones, and the devices I don't think have dedicated GPU RAM, I was wondering if such an API call does completely different things if compiled on one device (Android) vs on another device (Windows desktop computer). The calls seem the same or similar whether on OpenGL or OpenGL ES, and I was wondering if I write my program on Windows it'll work on a mobile device. My guess is that on a mobile device these function calls will load data onto the system RAM whereas on a desktop it will be sent to the GPU RAM, if a GPU is available.
If this is the case, then is it an advantage for the mobile device in that data is only kept in one place and never sent anywhere else (ie., to the GPU)?

A: The only significant difference is that in one case there is a DMA transfer over PCIe (desktop), in the other case it's just a memcpy to a driver-owned buffer in system RAM (mobile).
In both cases it can be relatively expensive (e.g. memory allocation, data copy, and possibly a need for cache maintenance on some systems), so it should still be minimized whenever possible. It's far more efficient to upload resources to wherever they need to be at the start of a game level and then just reference them from then onwards.


text:
Q: MAMP .htaccess loop I'm facing some troubles on my new MacBook, which I use for coding websites, locally. I've bought a license for MAMP Pro, cause I want to run locally. I've set up my .htaccess like this:
RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteCond %{REQUEST_URI} !/$
RewriteRule (.*) $1\.php [L]

RewriteCond %{HTTP_HOST} !^http://localhost:8888/$ [NC]
RewriteRule ^(.*)$ http://localhost:8888/$1 [L,R=301]

I want the URL to be like http://localhost:8888/index instead of http://localhost:8888/index.php.
I've tried this before, when I was editing the code directly from the remote server, but now, whenever I'm trying to reach the webpage, .htaccess are creating some kind of loop.. Someone who know what to do?
EDIT:
Ok, I somehow got it to work (almost) with the following code:
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteCond %{REQUEST_URI} !/$

RewriteCond %{HTTP_HOST} !^localhost$ [NC]
RewriteRule ^(.*)$ http://localhost:8888/$1 [L,R=301]

But now, when I am entering a folder eg. http://localhost:8888/new-folder/ then the URL changes to localhost:8888/localhost:8888/new-folder/ and tells me that the requested URL wasn't found on the server..

A: This is because this rule is wrong:
RewriteCond %{HTTP_HOST} !^http://localhost:8888/$ [NC]
RewriteRule ^(.*)$ http://localhost:8888/$1 [L,R=301]

since %{HTTP_HOST} matches only the domain name part not http:// OR port number.
It should be like this:
RewriteEngine On
RewriteBase /

RewriteCond %{HTTP_HOST} !^localhost$ [NC]
RewriteRule ^(.*)$ http://localhost:8888/$1 [L,R=301]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteCond %{REQUEST_URI} !/$
RewriteRule (.*) $1.php [L]


text:
Q: Error while trying to generate Image using base64_decode I am trying to generate an image using base64_decode with png extension, but generated png image is wrong, it is showing "invalid image".
my code is below
$base_64 = $this->input->post('base_64');
$decoded_base_64 = base64_decode($base_64);
$result = file_put_contents('directory/toSaveImage/' . $id . '.png', $decoded_base_64);

While searching for the solution i also tried adding before the $result variable.
    header("Content-type: image/png");

I also did try this line though
    $decoded_base_64 = base64_decode(base64_encode($base_64));

Can anyone please help me?

A: Here's your answer:
<?php
    $base64 = $this->input->post('base_64');
    $base64 = str_replace('data:image/png;base64,', '', $base64);
    file_put_contents("directory/toSaveImage/{$id}.png", base64_decode($base64));

You weren't removing data:image/png;base64,


text:
Q: ERROR TypeError: fetchImpl.bind is not a function (React Native on ios ) I currently stumbled on an issue when i tried to run a react native project using an Xcode simulator (iPhone 11 Pro, OS 16.0).
` ERROR  TypeError: fetchImpl.bind is not a function. (In 'fetchImpl.bind(global)', 'fetchImpl.bind' is undefined)`
[here is a screenshot of the error on my simulator](https://i.stack.imgur.com/MSMNi.png).
**NOTE** I Don't experience this error when i try it on an android emulator.
Please does anyone know how to resolve this issue?
What I have tried to resolve this issue but not luck so far :
- deleted and reinstalled node_modules
- deleted and reinstalled pod.lock file
- run yarn start using the `yarn start --reset-cache` command to clear cache in metro
- I have also tried running the react native project directly using the Xcode app (v14.1)


text:
Q: Bash parse log file value and timestamp two rows underneath I have file with the following format:
[2019-11-03 02:23:16] DEBUG : [COST METRICS] Found 10927 cost entries to copy.
[2019-11-03 02:23:16] DEBUG : [COST METRICS] Copying relevant cost data over via query: [..sql query here...]
[2019-11-03 02:25:13] DEBUG : [REVENUE METRICS] Fetching count of groups to be updated...
--
[2019-11-03 02:45:09] DEBUG : [COST METRICS] Found 4970 cost entries to copy into new table A_294472
[2019-11-03 02:45:09] DEBUG : [COST METRICS] Copying relevant cost data over via query: [..sql query here..]
[2019-11-03 02:45:15] DEBUG : [REVENUE METRICS] Fetching count of groups to be updated

The above format repeats several times in the file.
What I'd like to get, is the number number of cost entries to update, the timestamp of that log line, as well as the timestamp two lines underneath (which is when the query would have finished and the script moved to the next task. So my desired output here would be:
Number   Start      Finish
10927    02:23:16   02:25:13

Perhaps even a timing column showing 00:01:57 for this scenario if possible.
I am trying to accomplish this with grep and egrep, but not really getting anywhere as I cannot reuse the value and echo it to a file.

A: something like this will work, may not be robust enough for all cases since your sample input is very limited...
$ awk '{for(i=1;i<=NF;i++)
           if($i=="Found") {t=$2; sub("]","",t); v=$(i+1); n=NR; next}}
   t && NR==n+2 {sub("]","",$2); print v,t,$2; t=""}' file

10927 02:23:16 02:25:13

A: This I think will accomplish what you are looking for using egrep and awk
egrep -A2 "^\[[0-9]{4}-[0-9]{2}-[0-9]{2}\s[0-9]{2}:[0-9]{2}:[0-9]{2}\].*\[COST METRICS\] Found" test.txt | grep -v '\-\-' | awk '{ORS="\n"} NR==1 {print "Number  Start     Finish" }; {ORS=""} NR%3==1 {print $8"   "substr($2,0,8)} NR%3==0 {print "  "substr($2,0,8)"\n" }'

Where test.txt is your log file
Sample output:
Number  Start     Finish
10927   02:23:16  02:25:13
10927   02:25:16  02:25:16
55097   02:28:16  02:29:13
66927   02:29:16  02:30:15
77927   02:31:16  02:31:18


text:
Q: Angular: Creating questions using a directive I'm learning Angular and to try to get a grasp of directives I'm trying to create one for the generation of a multiple-choice question. Here's what I want to get working:
<question type="multiple-choice"
          content="Hard tacos or soft tacos?"
          options="{{ [
            'Hard tacos!',
            'Soft tacos!',
            'Porque no los dos?'] }}"></question>

I don't think Angular will understand that I'm trying to pass an object for the options attribute of the question directive.
Here's what my directive is looking like so far:
app.directive("question", function() {
  return {
    restrict: 'E',
    scope: {
      content: '@',
      options: '&'
    },
    templateUrl: function(elem, attrs) {
      return "partials/question-" + attrs.type + ".html";
    }
  }
}

And here is my template (question-multiple-choice.html):

  <input type="radio" ng-value="option">

I am getting the following error though, and I don't know how to proceed:
Syntax Error: Token '[' is unexpected, expecting [:] at column 4 of the expression [{{ [
   'Hard tacos!',
   'Soft tacos!',
   'Porque no los dos?'] }}].

A: Remove the interpolation {{}}, within your options attribute:
DEMO
<question type="multiple-choice"
          content="Hard tacos or soft tacos?"
          options="[
            'Hard tacos!',
            'Soft tacos!',
            'Porque no los dos?']"></question>

Furthermore, there is a typo in your templateUrl callback attr.type should be attrs.type
Update:
Since you want to have an an attribute as the model of your radio buttons, why not add an ng-model attribute itself using the = scope notation.
UPDATED DEMO
question-multiple-choice.html

      <input ng-model="$parent.ngModel" type="radio" ng-value="option" name="option">

directive
app.directive("question", function() {
  return {
    restrict: 'E',
    scope: {
      content: '@',
      options: '&',
      ngModel: '='
    },
    templateUrl: function(elem, attrs) {
      return "question-" + attrs.type + ".html";
    }
  }
});

Note that I used $parent.ngModel in the template because the ng-repeat creates a child scope.

A: Use "=" instead of "&" (which is for passing functions) for the options attribute.
Then when you use the directive, remove the curly braces from the expression.
The "=" says you want to do two-way binding with the value, in this case an array.


text:
Q: How to switch between EPSG in Geopandas (Plotting and adding background map) I am trying to draw some "station" coordinates on the NYC map. I use Geopandas(gpd) to create a GeoDataFrame and create a NYC map from gpd.datasets with EPSG of 4326.
In addition, I wanted to add a background image to my map following the Geopandas tutorial (https://geopandas.org/gallery/plotting_basemap_background.html). However, this works on EPSG of 3857. Is there any way to maintain the information and change the EPSG?
Here is my codebase
# Creating GeoDataFrame
gdf = gpd.GeoDataFrame(stations, geometry=gpd.points_from_xy(stations.Longitude, stations.Latitude))
# Find the NYC Borough map from contextily pkg
nyc = gpd.read_file(gpd.datasets.get_path('nybb')).to_crs(epsg=4326)
ax = nyc.plot(figsize=(10,10), alpha=0.3, edgecolor="k")

# Contextily adding background image
def add_basemap(ax, zoom, url='http://tile.stamen.com/terrain/tileZ/tileX/tileY.png'):
    xmin, xmax, ymin, ymax = ax.axis()
    basemap, extent = ctx.bounds2img(xmin, ymin, xmax, ymax, zoom=zoom, url=url)
    ax.imshow(basemap, extent=extent, interpolation='bilinear')
    # restore original x/y limits
    ax.axis((xmin, xmax, ymin, ymax))

add_basemap(ax, zoom=10, url='http://tile.stamen.com/toner-lite/tileZ/tileX/tileY.png')
# nyc.to_crs(epsg=4326)
gdf.plot(ax=ax, color="red")
ax.set_axis_off()

A: Yes there is. You can usually pass the EPSG information of your data to the add_basemap() function of contextily, by
add_basemap(ax, crs=nyc.crs.to_string(), zoom=10, url='...')

The only thing required is, that you have set a proper CRS on your data.
In your case you probably should add the contextily.wrap_tiles() function.
tr_basemap, tr_extent = ctx.wrap_tiles(basemap, extent, t_crs='EPSG:4326')

This should give you, what you want.
For further reading you can look here:
https://contextily.readthedocs.io/en/latest/warping_guide.html#Convert-the-tiles-to-your-data%E2%80%99s-CRS
https://contextily.readthedocs.io/en/latest/reference.html


text:
Q: Can I uninstall Totem? In my opinion, VLC is a much better and much faster player than Totem, and plays everything without having to need all of the extra junk Totem comes with. My question is, can you safely uninstall Totem? I'm trying to reduce the amount of junk on my computer, and since I'm using VLC for all my movie/video objectives, I see no need to have Totem.
Thanks

A: Yes, I've just uninstalled it like this:
sudo apt-get remove totem


text:
Q: Node.js SyntaxError: Unexpected identifier 'boolean' in ANTLR4 JavaScript Lexer Node.js version:
jj5@orac:~/test/antlr4-js$ node --version
v5.10.1

Java version:
jj5@orac:~/test/antlr4-js$ java -version
java version "1.7.0_91"
OpenJDK Runtime Environment (IcedTea 2.6.3) (7u91-2.6.3-1~deb8u1)
OpenJDK 64-Bit Server VM (build 24.91-b01, mixed mode)

ANTLR4 version:
jj5@orac:~/test/antlr4-js$ java -jar ./antlr-4.5.3-complete.jar | head -n 1
ANTLR Parser Generator  Version 4.5.3

My test script:
jj5@orac:~/test/antlr4-js$ cat run.sh
#!/bin/bash
cd "`dirname $0`"
rm ECMAScript????* 2>/dev/null
export CLASSPATH=".:`pwd`/antlr-4.5.3-complete.jar"
java -jar ./antlr-4.5.3-complete.jar -Dlanguage=JavaScript -visitor ECMAScript.g4
node antlr4/run.js

The error occurs on the last line node antlr4/run.js where Node.js runs run.js:
jj5@orac:~/test/antlr4-js$ ./run.sh
[irrelevant warnings elided]
/home/jj5/repo/svn/pcrepo/jj5-test/antlr4-js/ECMAScriptLexer.js:881
    private boolean strictMode = true;
            ^^^^^^^

SyntaxError: Unexpected identifier
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:387:25)
    at Object.Module._extensions..js (module.js:422:10)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)
    at Module.require (module.js:367:17)
    at require (internal/module.js:16:19)
    at Object.<anonymous> (/home/jj5/repo/svn/pcrepo/jj5-test/antlr4-js/antlr4/run.js:2:1)
    at Module._compile (module.js:413:34)
    at Object.Module._extensions..js (module.js:422:10)

So ANTLR4 seems to have generated some "strong typed" JavaScript and Node.js chokes on it. How can I resolve this issue..?
Note: if you have Node.js and Java installed you can reproduce like this:
cd /tmp
svn co https://www.progclub.org/svn/pcrepo/jj5-test/trunk/antlr4-js/
antlr4-js/run.sh

A: The problem was because the ECMAScript.g4 grammar that I was using was designed for use in Java, not JavaScript. I created a new file to support JavaScript, you can get the details here.


text:
Q: Is tension always constant throughout a massless rope in equilibrium? Let's say we have a meter stick with a single rope attached to it. One end of the rope is attached to one end of the meter stick, the other end of the rope is attached to the opposite end of the meter stick. By hanging the rope from a beam in the center of the rope, the meter stick (which is attached to the rope) balances perfectly flat in equilibrium as it hangs from the rope. Now, say the rope is not hung perfectly in its center, and as a result the meter stick accelerates from its perfectly horizontal position to an almost vertical position. (Does this make sense so far?) At this point where the meter stick is now at rest at an angle which is at a diagonal (the actual angle is irrelevant, we could say perhaps 5 degrees off the vertical, just to clarify to the reader), is the tension in the rope still constant among the two halves of  the rope? How can it be, when it appears that so much more of the meter stick's weight is being held up by one end of the rope?

A: I'd like to put forth an answer which directly addresses the title of your post, but not the particular situation in which you put forth with the meter stick and rope.
Consider instead a massive rope hanging vertically from a ceiling.
Give the rope a total mass of, say, $M$. Then use Newton's second law on the lower half of the rope to find the tension at the midpoint. Compare this value to the tension at the top of the rope by using Newton's second law for the entire rope. This should let you answer your question.

A: I believe the situation you are describing is this:

The ruler is the big blue line; the rope is the green line, and the forces on the ruler due to the rope are shown as colored vectors.
Now there can be no net horizontal force on the ruler, so the two red vectors must be equal and opposite. The tension has to point along the rope, so the direction of the total force is given (black dashed vector). This means that the tension in the part of the rope that is more vertical must be greater.

A: If the ruler has uniform mass(mass acts in the centre), and the rope is light and inextensible, then yes, the tension is equal throughout.
Take moments about A, to find the tension of the rope at B, or take moments about B, to find the tension of the rope at A. Either way you should get the same result, since the ruler is in equilibrium, so no resultant torque about any point. The tension should be half mg.
The angle that the ruler is balanced at is irrelevant, even when the ruler is vertical. Although for this to happen the rope has to pass through the ruler, which it won't, so at near vertical, things change as the rope bends around the ruler's edges.

A: Let's suppose the tension is not constant through out . Let it be T1 at point A , and T2 at point B , so then the net force on element AB is F=(T1-T2) , this causes a net acceleration F/m ( let m be the mass of the element AB).
But since AB is massless in a massless string, a=F/m becomes infinitely large. Which is neither observed , nor is it intuitive  .
So our assumption is wrong and T1 =T2 as a=0.
Also if it is an accelerating system T1 approaches T2 ( practically same).
I hope my answer quantitatively deals with query.

A: No.
The rope has mass, so tension varies, as one bit has to carry the other bits. The space elevator is a good example. No tension at the surface of the earth, and LOTS 5000 km up as that rope has to carry the weight of all 5000 km below it.


text:
Q: Doxygen - Could NOT find FLEX (missing: FLEX_EXECUTABLE) I know there are very similar worded questions on here, but I could not find an answer to my question there, so here we go:
I'm trying to see which of my C++ methods are called by others so I found Doxygen after googling.
On their page the installation seems pretty straightforward:

If you have the necessary build tools installed (i.e. g++, python,
  cmake, flex, bison), you should do the following to get the initial
  copy of the repository:
git clone https://github.com/doxygen/doxygen.git
cd doxygen
mkdir build
cd build
cmake -G "Unix Makefiles" ..
make

Until cmake -G "Unix Makefiles" .. everything goes well, then on that command following error occurs:
test@test-VirtualBox:~/doxygen/build$ cmake -G "Unix Makefiles" ..
CMake Error at /usr/share/cmake-3.5/Modules/FindPackageHandleStandardArgs.cmake:148 (message):
  Could NOT find FLEX (missing: FLEX_EXECUTABLE)
Call Stack (most recent call first):
  /usr/share/cmake-3.5/Modules/FindPackageHandleStandardArgs.cmake:388 (_FPHSA_FAILURE_MESSAGE)
  /usr/share/cmake-3.5/Modules/FindFLEX.cmake:230 (FIND_PACKAGE_HANDLE_STANDARD_ARGS)
  CMakeLists.txt:84 (find_package)

I thought: No big deal, why should anything work out of the box...seems I have to install flex.
So I do:
sudo apt-get update
sudo apt-get install flex
sudo apt autoremove (because after installation the command line recommended me to do this)
Now it seems to me that flex has been installed, I try cmake -G "Unix Makefiles" .. again...same error. I close the command line, start it up again, try it again - same error...
So now I'm slowly gettin' pissed and turn to Stack Overflow for help :D
What am I doing wrong???
And because I saw someone asking this in the other question's comment, here's the output of flex:
test@test-VirtualBox:~/doxygen/build$ flex
The program 'flex' can be found in the following packages:
 * flex
 * flex-old
Try: sudo apt install <selected package>

A: It seems like apt autoremove really removed the package I just installed in the previous step.
So what worked for me was:
git clone https://github.com/doxygen/doxygen.git
cd doxygen
mkdir build
cd build

These are new:

sudo apt-get install flex
sudo apt-get install bison

cmake -G "Unix Makefiles" ..
make

...but of course the horror wouldn't end there, see my next question :D


text:
Q: Submit Application to spark cluster I'm having trouble trying to submit an application (job) to a spark (1.0.0) cluster, I already setup the master and attached a worker to it (or at least that's what the WebUI says) following this guide http://spark.apache.org/docs/latest/spark-standalone.html with a pre-builded version that I downloaded from the site... the thing is that when I try to submit an application to the cluster I get the following error:
Exception in thread "main" java.lang.ClassNotFoundException: org.apache.spark.examples.JavaWordCount.java
   at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
   at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
   at java.security.AccessController.doPrivileged(Native Method)
   at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
   at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
   at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
   at java.lang.Class.forName0(Native Method)
   at java.lang.Class.forName(Class.java:270)
   at org.apache.spark.deploy.SparkSubmit$.launch(SparkSubmit.scala:289)
   at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:55)
   at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)

now this is the script I'm using, just as it says here http://spark.apache.org/docs/latest/submitting-applications.html:
./bin/spark-submit --verbose --master spark://roman-XPS-L501X:7077 --class org.apache.spark.examples.JavaWordCount.java JavaWordCount.jar

I exported the jar myself and it's in place, also the app is one of the examples given so I assume that nothing is wrong with it. I appreciate any help and I thank you in advance. Also if somebody could explain to me what is the "driver program" that appears and what is its function in the cluster, as you could imagine I'm having a bit of trouble understanding this.

A: First, the driver program is the calling application (i.e. the one that creates the Spark context and defines the operations to be performed).
Second, you are designating the class argument with ".java", which is not the way a fully-qualified class name should be referenced.  Your command should be:
./bin/spark-submit --verbose --master spark://roman-XPS-L501X:7077 --class org.apache.spark.examples.JavaWordCount JavaWordCount.jar


text:
Q: REGEX for 4 decimal places I want REGEX to allow only 4 decimal places no more and no digits. Requirement is at least 1 decimal and up to 4.
This is what i have:
REGEX(TEXT(Won_Lost_By_How_Much__c),"\\.[0-9][0-9]?[0-9]?[0-9]?")

It allows 1.99999 though.

A: REGEX returns true when the pattern matches. Validation rules need true when the validation rule should trigger. As such, you need to invert the result with NOT. Also, I would expect there to always be a leading 0, so you'll need to account for that:
NOT(REGEX(TEXT(Won_Lost_By_How_Much__c),"^0?\\.\\d{1,4}$"))


text:
Q: Calculate Average value for multidimensional array I have an example array. It contains a day and a number of failures of builds.
 var array = [["2014-08-13",3],
              ["2014-08-13",3],
              ["2014-08-14",4],
              ["2014-08-12",2],
              ["2014-08-13",3],
              ["2014-08-12",2]];

I want to iterate through the array and get an array which holds for each day the average value of number of failures. I tried out some things but couldn't find a proper solution.
The target array should look like this:
 var targetArray = [["2014-08-13",3],
                    ["2014-08-14",4],
                    ["2014-08-12",2]];

what I got so far is to make an array which holds the three dates:
Array.prototype.contains = function(obj) {
    var i = this.length;
    while (i--) {
        if (this[i] == obj) {
            return true;
        }
    }
    return false;
}

var array = [
    ["2014-08-13", 3],
    ["2014-08-13", 3],
    ["2014-08-14", 4],
    ["2014-08-12", 2],
    ["2014-08-13", 3],
    ["2014-08-12", 2]];

var targetArray = [];
for (var i = 0; i < array.length; i++) {
    var temporaryArr = [];

    var current = array[i];
    var currentDate = current[0];
    var currentValue = current[1];

    console.log("current: " + current);

    if (!targetArray.contains(currentDate)) {
        temporaryArr[0] = currentDate;
        targetArray[targetArray.length] = temporaryArr;
    }

}

console.log(targetArray);

A: Code below:
var array = [
    ["2014-08-13", 3],
    ["2014-08-14", 4],
    ["2014-08-13", 3],
    ["2014-08-12", 2],
    ["2014-08-13", 3],
    ["2014-08-12", 2]
];

function average(array) {
    var ret = {}, retArr = [], tmp, time, value;
    for(var i=0, len=array.length; i < len; i++) {
        tmp = array[i];
        time = tmp[0];
        value = tmp[1];
        if(time in ret) {
            ret[time].push(value)
        } else {
            ret[time] = [value];
        }
    }
    for(var p in ret) {
        var total = 0;
        ret[p].forEach(function(val) {
            total += val;
        });
        retArr.push([p, total / ret[p].length]);
    }
    return retArr;
}

average(array);

A: First, your dates need to be strings or you'll start getting some really weird output:
var arr = [
  ['2014-08-13', 3],
  ['2014-08-13', 3],
  ['2014-08-14', 4],
  ['2014-08-12', 2],
  ['2014-08-13', 3],
  ['2014-08-12', 2]
];

Create a new object. We're going to use its keys to store our dates and values to store the failures and number of times that day has appeared.
var obj = {};

Loop over the array. If the key/date doesn't exist add it to the object and set the value to an array containing the number of failures and set the current count to 1. If the key/date does exist, add the number of fails to the fail total and increment the count.
for (var i = 0, l = arr.length; i < l; i++) {
  var el = arr[i];
  var date = el[0];
  var fails = el[1];
  if (!obj[date]) {
    obj[date] = [fails, 1]
  } else {
    obj[date] = [obj[date][0] + fails, obj[date][1] + 1]
  }
}

Finally loop over the object and push the date and average back to a new array.
var out = [];
for (var date in obj) {
  out.push([date, obj[date][0] / obj[date][1]])
}

DEMO

A: var myArray = [["2014-08-13", 3],
              ["2014-08-13", 3],
              ["2014-08-14", 4],
              ["2014-08-12", 2],
              ["2014-08-13", 3],
              ["2014-08-12", 2]];

function getAverage(arr) {
  var dates = [];
  var values = [];

  for(i=0; i<arr.length; i++){
    var index = dates.indexOf(arr[i][0]);
    if(index == -1){
       dates.push(arr[i][0]);
       values.push([arr[i][1]]);
    }else{
       values[index].push(arr[i][1]);
    }
  }

  for(d=0; d<dates.length;d++){
    var dateTotal = 0;
    for(a=0;a<values[d].length;a++){ dateTotal += values[d][a] }
    dates[d] = [dates[d], (dateTotal / values[d].length)]
  }

  return dates
};

getAverage(myArray);


text:
Q: Bug in Site Analytics/Traffic Sources? I just grabbed this picture from Site Analytics/Traffic Sources of Economics Stack Exchange:

What strikes me as peculiar is that visits from all sites except Google are either 274 or a multiple of it (274 \times 3 =822).
Is this a default value when traffic is too low or non-existent? Or...?


text:
Q: Text cut off after the character  in TinyMCE I use the latest version of wordpress (v3.9.2, Taiwan Chinese Traditional), and found it can not display this Chinese word , but other Chinese words can be displayed normally.
I just use this word on a post, and all the content after it is lost (became blank, this word disappeared too), after I saved the post to draft. What should I do?

A: This might be a limitation of JavaScript.  is U+2A1C6 in Unicode, and codepoints above U+FFFF (which need four bytes) are coded via UTF-16 surrogates. And that … sucks.
The canonical bug for that in WordPress is #13590 Inserting a 4-byte UTF-8 character truncates data. It was closed as maybe later, because fixing it would require a change in the database encoding that WordPress' current schema just cannot handle.
You could try the plugin TinyMCE Chinese Convert and switch to Simplified Chinese to get around that.


text:
Q: individual characters treated as string in javascript arguments I need to write a function that retrieves the last parameter passed into the function. If it's just arguments, it should return the last element. If it's a string, it should return the last character. Arrays should return the last element of the array. My code works for arrays, strings and arguments as long as they are not all strings.
function last(list){
  var arr;
  if(list instanceof Array){
    return list[list.length-1];
  }
  if(typeof list === 'string' || list instanceof String){
    arr = list.split("");
    return arr[arr.length-1];
  }

  return arguments[arguments.length-1];
}

This works for almost every case, but I have a problem when the input is a bunch of string arguments.
Test.assertEquals(last('a','b','c','z'), 'z');

returns 'a'
Why are disjoint strings evaluating to true when testing if the arguments are arrays or strings and how can I universaly access the last value of arbitrary parameters?

A: Something like this should do that
function last(){
    var a = arguments;
    return (a.length > 1 ? [].slice.call(a) :
            typeof a[0] === 'string' ? a[0].split('') : a[0]).pop();
}

FIDDLE

A: Change your function call to Test.assertEquals(last(['a','b','c','z']), 'z');
Whereas before you were passing four different arguments to last(), this passes a single argument, a list containing four characters.

A: Change your last function like this:
function last(list){
  var arr;
  if(list instanceof Array){
    return list[list.length-1];
  }
  if((typeof list === 'string' || list instanceof String) && (arguments.length == 1)){
    arr = list.split("");
    return arr[arr.length-1];
  }

  return arguments[arguments.length-1];
};


text:
Q: Activate a python virtual environment using activate_this.py in a fabfile on Windows I have a Fabric task that needs to access the settings of my Django project.
On Windows, I'm unable to install Fabric into the project's virtualenv (issues with Paramiko + pycrypto deps). However, I am able to install Fabric in my system-wide site-packages, no problem.
I have installed Django into the project's virtualenv and I am able to use all the "> python manage.py" commands easily when I activate the virtualenv with the "VIRTUALENV\Scripts\activate.bat" script.
I have a fabric tasks file (fabfile.py) in my project that provides tasks for setup, test, deploy, etc. Some of the tasks in my fabfile need to access the settings of my django project through "from django.conf import settings".
Since the only usable Fabric install I have is in my system-wide site-packages, I need to  activate the virtualenv within my fabfile so django becomes available. To do this, I use the "activate_this" module of the project's virtualenv in order to have access to the project settings and such. Using "print sys.path" before and after I execute activate_this.py, I can tell the python path changes to point to the virtualenv for the project. However, I still cannot import django.conf.settings.
I have been able to successfully do this on *nix (Ubuntu and CentOS) and in Cygwin. Do you use this setup/workflow on Windows? If so Can you help me figure out why this wont work on Windows or provide any tips and tricks to get around this issue?
Thanks and Cheers.

REF:

*

*http://virtualenv.openplans.org/#id9 | Using Virtualenv without
bin/python

Local development environment:

*

*Python 2.5.4

*Virtualenv 1.4.6

*Fabric 0.9.0

*Pip 0.6.1

*Django 1.1.1

*Windows XP (SP3)

A: After some digging, I found out that this is an issue with the activate_this.py script. In it's current state, virtualenv<=1.4.6, this script assumes that the path to the site-packages directory is the same for all platforms. However, the path to the site-packages directory differs between *nix like platforms and Windows.
In this case the activate_this.py script adds the *nix style path:
VIRTUALENV_BASE/lib/python2.5/site-packages/
to the python path instead of the Windows specific path:
VIRTUALENV_BASE\Lib\site-packages\
I have created an issue in the virtualenv issue tracker which outlines the problem and the solution. If you are interested, you may check on the issue here: http://bitbucket.org/ianb/virtualenv/issue/31/windows-activate_this-assumes-nix-path-to-site
Hopefully the fix will be made available in an upcomming release of virtualenv.

If you need a fix for this problem right now, and the virtualenv package has not yet been patched, you may "fix" your own activate_this.py as shown below.
Edit your VIRTUALENV\Scripts\activate_this.py file. Change the line (17 ?):
site_packages = os.path.join(base, 'lib', 'python%s' % sys.version[:3], 'site-packages')

to
if sys.platform == 'win32':
    site_packages = os.path.join(base, 'Lib', 'site-packages')
else:
    site_packages = os.path.join(base, 'lib', 'python%s' % sys.version[:3], 'site-packages')

With this in place, your activate_this.py script would first check which platform it is running on and then tailor the path to the site-packages directory to fit.
Enjoy!

A: You will have to execute the activate this, from within the fab file. Altho' I have not tested it, I believe following should work:
activate_this = '/path/to/env/bin/activate_this.py'
execfile(activate_this, dict(__file__=activate_this))


text:
Q: Fatal Exception: NSInternalInconsistencyException Delegate must be cleared before release Hi I am developing an IOS application. I do not understand the cause of crash was too much for a reason. How to find the cause of this crash and I can solve. thanks
Crash Report ; http://crashes.to/s/6aac7c4f9f2


text:
Q: SoapClient manage error / exception I'm using a soap service that is unavailable today. It's returning a 403 Forbidden code, and then I got this message :
 Uncaught SoapFault exception: [WSDL] SOAP-ERROR: Parsing WSDL: Couldn't load from...[MY URL]

How can I catch this SoapFault ?
Here is my code :
$client = new SoapClient($myurl);

I also tried to use the 2nd cosntructor argument with trace and exception(s) (with and without s, saw the two versions on the net. Can't find the doc).
I tried to catch the thrown error using
catch (SoapFault $exception) {
    wtf($exception->getMessage());
}

or
 catch (Exception $e){
    wtf($e->getMessage());
}

(As seen in official doc comments)
Nothing works. Still this Fatal Error and SoapFault uncaught.
I also tried @ before new SoapClient,
and catch with and without backslash (because i'm in a namespace).
At this point, I don't know what to do to handle this error properly.
Maybe a chicken sacrifice.

A: Resolved, the right way is in fact
['exceptions' => true]

And the exception must be caught with
catch (\SoapFault $exception) {
    wtf($exception);
}


text:
Q: Bootstrap 4 Dropdown dropdown-item with link on left and button on the right I am using bootstrap 4 and using a dropdown.
I need to have a list where the list item text / anchor is as usual...on the left and on the same line on each have a button on the right
This is what I've done but it's not right. Here's the current code:

Item 1

          <button class="btn"></button>

Item 2

          <button class="btn"></button>

How is this done the correct way in Bootstrap 4?

A: You don't need floats for this (floats shouldn't be used with flex in general). Just use the proper flex properties on the item element, and remove horizontal padding.
You can probably simplify further by removing the divs from around the anchors and buttons. I've done so in the second item to demonstrate.

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous">

  <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Dropdown button
  </button>

Item 1

        <button type="button" class="btn btn-primary">Primary</button>

      Item 2
      <button type="button" class="btn btn-primary">Primary</button>

A: Bad styling aside, with the floats what is missing is the button at the top and the dropdown wrapper.

    <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Dropdown button
    </button>

I also added text to the image alt="item1" so you could actually see something (a good practice generally)
Please see the first example in the reference: https://getbootstrap.com/docs/4.6/components/dropdowns/

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous">

  <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Dropdown button
  </button>

Item 1

        <button class="btn"></button>

Item 2

        <button class="btn"></button>


text:
Q: Javascript - Google Maps v3 - Get positions of markers Thanks to this site and your help, I have almost finished my Googlemaps script. There is one more thing, I need your help with:
I have multiple markers on my map.
I would like to:
-save each marker position in a variable
-make external links below the map which link to the markers
-change mapcenter on click of these links (described above)
Here is my script so far:
   <script type="text/javascript">
    var offender_locations = [
        ["10001", "Title 2", "icon.png"],
        ["10002", "Title 3", "icon.png"],
        ["10010", "home", "icon.png"]
    ];

    var myOptions = {
        zoom: 12,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("results_map"), myOptions);
    var latlng = new google.maps.LatLng(0, 0);

    for (i = 0; i < offender_locations.length; i++) {
        var infowindow = new google.maps.InfoWindow(),
            geocoder_map = new google.maps.Geocoder(),
            address = offender_locations[i][0],
            icon_img = offender_locations[i][2];
        (function(addr, img, i) {
            geocoder_map.geocode({
                'address': addr
            }, function(results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    map.setCenter(results[0].geometry.location);
                    var marker = new google.maps.Marker({
                        map: map,
                        position: map.getCenter(),
                        icon: img
                    });
                    google.maps.event.addListener(marker, 'click', (function(marker, i) {
                        return function() {
                            infowindow.setContent(offender_locations[i][1]);
                            infowindow.open(map, marker);
                        }
                    })(marker, i));

                } else {
                    alert("error!");
                }
            });
        }(address, icon_img, i));
    }

    function zoomin() {
        map.setZoom(15);
    };

    function zoomout() {
        map.setZoom(15);
    }
</script>

The last two small functions are for the click even of the external links. at this moment they only change the zoom level and do not change the map center.

A: Try pushing your markers to an array so you can look at them later.
At the beginning do var markers = [];
Then after each marker declaration markers.push(marker);.

A: You can also use object to store your markers or other layers in case you want to access them later by primary key:
var markers = {};

markers['car_1'] = marker;

//change the position of 'car_1'
markers['car_1'].setPosition(x,y);

//you also can create much more complex structure like this
marker['car_2'] = {'title': 'Car 1', _ref: marker};

//change the position of 'car_2'
markers['car_2']._ref.setPosition(x,y);

Attention: make sure your object keys(in our case: car_1, car_2) are not the same(primary key).


text:
Q: Change field value before save using Editor Datatables I am trying to change the values of a field salary before save on database.
I am using the code below on PHP events:
->on( 'preCreate', function ( $editor, $values ) {
    $editor->field( 'salary' )->setValue( $editor->field( 'salary' ) / 100 );
} )
->on( 'preEdit', function ( $editor, $id, $values ) {
    $editor->field( 'salary' )->setValue( $editor->field( 'salary' ) / 100 );
} )

I need to divide the value by 100.
But it's not work.
Any help?


text:
Q: PowerBI running in efficiency mode but cannot disable and is affecting users performance User updated to the newest version of Win11 earlier today, and they are a heavy PowerBI user. Since this update they have noticed that the application is running in efficiency mode and is impacting performance.
There is no way to disable efficiency mode through task manager, the efficiency mode button is greyed out and cannot be selected, nor the context menu when you right click.
The registry changes I've found that refer to efficiency mode all refer to an edge setting and doesn't affect the windows process.
Has anyone come across this, google-fu returns nothing but trying to walk me through the task manager way and If Efficiency Mode is showing greyed out, then that particular process is a core Windows process and you can't apply efficiency mode for that.
Just either need to turn efficiency mode off completely, or find a way to disable it on that specific process.
Thanks for any help


text:
Q: Dynamic decision networks I was wondering if anybody had some good references on dynamic decision networks,
is there a nice recent survey on this topic?
Thanks in advance.

A: I have been reading this books on BN and DDN and they  are very usefull.
Just follow the link and you will find more .
Enjoy!
"Artificial Intelligence: Modern Approach" textbook by Russell and Norvig


text:
Q: Button in Discord Bot (c#) - D# I am a novice programmer and I am trying to create a bot. I acted on the lessons at https://www.youtube.com/watch?v=9ooZ0_IkPVk, and used D# to develop
I have a question - how to add buttons to a post via embed?
Here's my code for example
var joinGames = new DiscordEmbedBuilder
            {
                ImageUrl = "bla bla,
                Title = "bla bla bla",
                Color = DiscordColor.Blue,
                Description = ":bla bla bla \n" +
                              "bla bla"
            };

This is where I want to add buttons, how do I do that? Are they supposed to be displayed as a message?
await ctx.Channel.SendMessageAsync(embed: joinGames).ConfigureAwait(false)

But my button doesn't connect
var myButton = new DiscordButtonComponent(ButtonStyle.Primary, "my_custom_id", "This is a button!");

Very please advice or solutions, maybe there are books and articles that I should read to understand how best to attach what? Sorry for the mistakes in the text, my native language is not English


text:
Q: How to get previous object value after changing its name using django reversion? In How to add django-reversion to an app developed using django and django-rest framework I have added the below function to get history of objects
from django.http import HttpResponse
from reversion.models import Version
import json

def history_list(request):
   history_list = Version.objects.all().order_by('-revision__date_created')

data = []
for i in history_list:
    data.append({
        'date_time': str(i.revision.date_created),
        'user': str(i.revision.user),
        'object': i.object_repr,
        'type': i.content_type.name,
        'comment': i.revision.comment
    })

data_ser = json.dumps(data)
return HttpResponse(data_ser, content_type="application/json")

In the urls.py of How to add django-reversion to an app developed using django and django-rest framework I have added a route to history.
When I visit 127.0.0.1:8000/history I get the json data as
[{"object": "someobject", "user": "someuseruser", "type": "sometype", "comment": "Changed name.", "date_time": "2015-03-02 18:04:58.368650+00:00"}]

execution flow: When I visit 127.0.0.1:8000/admin and change the value of above object to "otherobject". when I refresh 127.0.0.1:8000/history. I get one more json field
[{"object": "otherobject", "user": "someuseruser", "type": "sometype", "comment": "Changed name.", "date_time": "2015-03-02 18:04:58.368650+00:00"}]

below is the area I got stuck to add one more additional field to history function:
I would like to  include one more field to above iteration in history function. like previous_object: " " to get the object name before its changed even after changing name.
for instance:-
from 127.0.0.1:8000/admin
I changed object name from "apple" to "orange".
When I visit the history route 127.0.0.1:8000/history
[{"object": "apple", "object_before_changed": ""null": "someuseruser", "type": "sometype", "comment": "Changed name.", "date_time": "2015-03-02 18:00:58.368650+00:00"}]

I should be able to see as below
[{"object": "orange", "object before_changed": ""apple": "someuseruser", "type": "sometype", "comment": "Changed name.", "date_time": "2015-03-02 18:04:58.368650+00:00"}]

A: You just need to setup a variable to hold to previous item and insert it into the dictionary as required. note that this uses getattr as a way to get the object_repr of previous_object and safely provide a default if there is none (as would be the case for the first iteration).
data = []
previous_object = None
for i in history_list:
    data.append({
        'date_time': str(i.revision.date_created),
        'user': str(i.revision.user),
        'object': i.object_repr,
        'previous_object': getattr(previous_object,'object_repr',None),
        'type': i.content_type.name,
        'comment': i.revision.comment
    })
    previous_object = i


text:
Q: R networkD3: click action to show information from node data frame I have this code:
library(networkD3)

# Load data
data(MisLinks)
data(MisNodes)

new.nodes <- MisNodes
new.nodes$var1 <- runif(nrow(MisNodes),1,2)
new.nodes$var2 <- runif(nrow(MisNodes),1,2)

# Some script to show the node index in the new.nodes data frame
script <- 'alert("row: " + (d.index + 1));'

# Plot
forceNetwork(Links = MisLinks, Nodes = new.nodes,
             Source = "source", Target = "target",
             Value = "value", NodeID = "name",
             Group = "group", opacity = 0.8,
             clickAction = script)

I figured out to get the row number of the node data frame by asking for d.index + 1. However I want to show a table containing all the node info, like so (perhaps nicer formatted):
    name group size     var1     var2
1 Myriel     1   15 1.501311 1.053062

This would require the JavaScript to have access to the node data frame, as I only have little knowledge of JavaScript I cannot figure out how to request this data.

A: The reason this happens is that the forceNetwork function strips out all the unnecessary variables/columns in the data frame that it passes to JavaScript, which is advantageous usually, but not in this case. You can work around it by saving the htmlwidget object that forceNetwork creates, then add back in the variable you need to access, and then 'print'/display it.
library(networkD3)

data(MisLinks)
data(MisNodes)

MisNodes$var1 <- runif(nrow(MisNodes),1,2)

script <- 'alert("var1: " + (d.var1));'

fn <- forceNetwork(Links = MisLinks, Nodes = new.nodes, Source = "source",
                   Target = "target", Value = "value", NodeID = "name",
                   Group = "group", opacity = 0.8, clickAction = script)

fn$x$nodes$var1 <- MisNodes$var1

fn

This could be done with/for multiple variables as well, for example...
library(networkD3)

data(MisLinks)
data(MisNodes)

MisNodes$var1 <- runif(nrow(MisNodes),1,2)
MisNodes$var2 <- runif(nrow(MisNodes),1,2)

script <- 'alert("var1: " + d.var1 + "\\n" + "var2: " + d.var2);'

fn <- forceNetwork(Links = MisLinks, Nodes = new.nodes, Source = "source",
                   Target = "target", Value = "value", NodeID = "name",
                   Group = "group", opacity = 0.8, clickAction = script)

fn$x$nodes$var1 <- MisNodes$var1
fn$x$nodes$var2 <- MisNodes$var2

fn

A: Unfortunately, I think it is not easily done if not impossible. It appears that only the used the arguments of forceNetwork relating to the nodes are initialized in the underlying code:
Consider for example:
script <- 'alert("row: "     + (d.index + 1) +
                 ", name: "  + d.name +
                 ", group: " + d.group +
                 ", size: "  + d.nodesize +
                 ", var1: "  + d.var1)'

# Plot
d3 <- forceNetwork(Links = MisLinks, Nodes = new.nodes,
             Source = "source", Target = "target",
             Value = "value", NodeID = "name",
             Nodesize = "size",
             Group = "group", opacity = 0.8,
             clickAction = script)

print(d3)

As you can see when clicking a node below, the var1 is undefined. Note I added the Nodesize argument to the function call which now can be accessed through the script d.nodesize (and not d.size). The group variable and argument, in this case, are named identically so the distinction is lost here. However, the NodeID is apparently accessed by the stated name which I find inconsistent.

You can see the generated source by saving:
saveNetwork(d3, file = "test.html")

You can notice by looking at it, that the values you intend to output are not stored in the file.
Edit:
By your own suggestion, this comes somewhat close as a workaround:
new.nodes$newname  <- with(new.nodes, paste(", name: ", name, ", group: ", group,
                                ", size: ", size, ", var1: ", var1,
                                ", var2: ", var2))

newscript <- 'alert("row: " + (d.index + 1) + d.name)'

forceNetwork(Links = MisLinks, Nodes = new.nodes,
             Source = "source", Target = "target",
             Value = "value", NodeID = "newname", Nodesize = "size",
             Group = "group", opacity = 0.8, opacityNoHover = 0,
             clickAction = newscript)

So, it is just a matter of formatting the string as you'd like it displayed. The downside is that name/NodeIDs are very long. And as you can see, the NodeID is just always called name on the JS side.


text:
Q: How to catch the url that cause SSL certificate_verify_failed in python? I'm trying to access the google sheets api with python within corporate network, that uses firewall.  Then, I need to discover all the url/domains google sheets api requests to send IT team unlock the access for theses url's.
I am using the pygsheets library for connect with google api.

A: In order for users on your network to access Google Drive and Google Docs editors, your firewall rules should connect to the following hosts and ports. Otherwise, users may be blocked or denied access from these services.
For the following hosts, [N] means any single decimal digit and * means any string not containing a period.
Oauth server

*

*accounts.google.com:443/HTTPS

API stuff

*

*apis.google.com:443/HTTPS

**.clients[N].google.com:443/HTTPS

**.googleapis.com:443/HTTPS

*script.google.com:443/HTTPS

Other

*

*www.google.com:443/HTTPS

*googledrive.com:443/HTTPS

*drive.google.com:443/HTTPS

**.drive.google.com:443/HTTPS

*docs.google.com:443/HTTPS

**.docs.google.com:443/HTTPS

**.c.docs.google.com:443/HTTPS

*sheets.google.com:443/HTTPS

*slides.google.com:443/HTTPS

*talk.google.com:5222/XMPP (needed only for Backup and Sync or the legacy - version, Drive for Mac/PC)

*takeout.google.com:443/HTTPS

*gg.google.com:443/HTTPS

*ssl.google-analytics.com:443/HTTPS

*video.google.com:443/HTTPS

*s.ytimg.com:443/HTTPS

**.googleusercontent.com:443/HTTPS

**.gstatic.com:443/HTTPS

*lh[N].google.com:443/HTTPS

*[N].client-channel.google.com:443/HTTPS

*clients[N].google.com:443/HTTPS

Ripped from Google Drive firewall and proxy settings
Some of theses are for google drive the web application and others are for google drive api, sheets api and the oauth servers.   I could probably wittle it down a little but wasnt sure if you wanted that.  It may be best that they just open most of them and go from there.


text:
Q: Where to place a question about Google Maps algorithm for arranging tiles and its artifacts? This question doesn't seem to be very welcome in stackoverflow despite there exist the tags google-maps and satellite-image, so I am guessing where should I place it:
Weird regions in lagoon water ripples pattern (Google Maps)
Is gis.SE a better place, regarding the answer could be related to an algorithm artifact, a mathematical surface mapping issue, less probably a physical phenomenon...?

A: In general questions about Google Maps are on-topic at the GIS Stack Exchange.
Your question looks like it is about Remote Sensing rather than GIS but the community there generally places it under the same umbrella.
However, I recommend revising your question to make clearer what the single question you wish to ask is before you post it there.

Since you posted Weird regions in lagoon water ripples pattern (Google Maps) at GIS SE it has received two answers so far.


text:
Q: Meaning of the phrase "at least initially" What does the phrase "at least initially", as used in these examples, mean?

The attention, at least initially, surprised them.
At least initially, few donors seemed to agree.
But the real gold, at least initially, is water.

Please, no insults!

A: "Initially" is an adverb meaning "at the beginning" or "at first." The word "least" adds the idea that the circumstance (surprise, non-agreemnent, "gold") while not permanent, was true for some time in the beginning, and possibly for longer. "Least" is a word that hedges accuracy. "She is at least 30" means the speaker is not sure of her age, but is giving an estimate that is very likely within the correct range.
The third sentence is somewhat hard to parse because "the real gold...is water" is a comparison between two very different physical substances, and has to be considered as a metaphor.


text:
Q: How to make a child thread sleep without freezing UI thread in WPF application? I have a WPF application and I have individual threads running to accomplish tasks and I would like to have the current thread to go to sleep something like,

Thread.CurrentThread.Sleep(10000)

I do see it in Java but not in C#. I do know that I only have only one UI thread, so if I use Thread.Sleep(10000) my UI thread will be block. I am using async and await from .NET 4.5.

var words = await Task.Factory.StartNew(() => {
  StringMgr.TextToUniqueWords(File.ReadAllText(filename));
// I want to be able to sleep this thread for 10 seconds, without the UI freezing
});

So how do I put a child thread to sleep without freezing the UI thread in a WPF application?
Thanks!

A: Since you're already using async, you can just do it the asynchronous way:
var words = await Task.Run(async () =>
{
  StringMgr.TextToUniqueWords(File.ReadAllText(filename));
  await Task.Delay(TimeSpan.FromSeconds(10));
});

However, I suspect that sleeping is the wrong solution for the actual problem you're trying to solve. If you'd like to post another question with your actual problem, you may find a better solution.

A: Have you tried it? Sleeping thread inside a Task won't freeze your GUI but it will make the current background thread to go in sleep mode and your UI will remain responsive always -
        Task.Factory.StartNew(() =>
            {
                Thread.Sleep(5000000); // this line won't make UI freeze.
            });
        Thread.Sleep(5000000); // But this will certainly do.


text:
Q: Find number of files deleted I want to know how many files deleted thru batch script. I found a script and modified it but it does not work. Any idea how to fix it.
set-location d:\testing -ErrorAction stop               # Change directory
$files = get-childitem -File                                   # Get all
the files in this directory
$folders = get-childitem -directory                            # Get all
the folders in this directory

$count = ($files|measure).count                                #
($files|measure).count gives how
                                                           # many files
are in this collection.
$countfo = ($folders|measure).count                            #
($files|measure).count gives how
                                                           # many files
are in this collection.

Start-Sleep -s 5

write-host "There are $($count) files to be deleted."          # Write
that to the screen.
$files | remove-item                                           # remove
the files

write-host "There are $($countfo) folders to be deleted."      # Write
that to the screen.
$folders | remove-item                                         # remove
the files

$files = get-childitem -File                                   # Get all
the files in this directory
                                                           # after the
delete to find out how
                                                           # how many
remained.

$folders = get-childitem -directory                              # Get all
the folders in this directory
                                                           # after the
delete to find out how
                                                           # how many
remained.

$count2 = ($files|measure).count                               #
$countfinal = $count-$count2

$countfo2 = ($folders|measure).count
$countfofinal = $countfo-$countfo2

write-host "$($count2) files remained. " -NoNewline            #
write-host "$($countfinal) files were deleted. "               #

write-host "$($countfo2) folders remained. " -NoNewline        #
write-host "$($countfofinal) folders were deleted. "           #

Start-Sleep -s 5

A: You can use the following script to delete all files in the folder specified at the top of the script. The -erroraction stop is there in case the folder does not exist, the script aborts rather than to delete all files in the current folder.
set-location d:\testing -ErrorAction stop               # Change directory
$files = get-childitem -File                            # Get all the files in this directory

$count = ($files|measure).count                         # ($files|measure).count gives how
                                                        # many files are in this collection.
write-host "There are $($count) files to be deleted."   # Write that to the screen.
$files | remove-item                                    #remove the files

$files = get-childitem -File                            # Get all the files in this directory
                                                        # after the delete to find out how
                                                        # how many remained.
$count2 = ($files|measure).count                        #
$countfinal = $count-$count2
write-host "$($count2) files remained. " -NoNewline     #
write-host "$($countfinal) files were delted. "         #