Q: Re-opening stdout and stdin file descriptors after closing them I'm writing a function, which, given an argument, will either redirect the stdout to a file or read the stdin from a file. To do this I close the file descriptor associated with the stdout or stdin, so that when I open the file it opens under the descriptor that I just closed. This works, but the problem is that once this is done, I need to restore the stdout and stdin to what they should really be.
What I can do for stdout is     open("/dev/tty",O_WRONLY);   But I'm not sure why this works, and more importantly I don't know of an equivalent statement for stdin.
So I have, for stdout
close(1);
if (creat(filePath, O_RDWR) == -1)
{
    exit(1);
}

and for stdin
close(0);
if (open(filePath, O_RDONLY) == -1)
{
    exit(1);
}

A: You should use dup() and dup2() to clone a file descriptor.
int stdin_copy = dup(0);
int stdout_copy = dup(1);
close(0);
close(1);

int file1 = open(...);
int file2 = open(...);

< do your work. file1 and file2 must be 0 and 1, because open always returns lowest unused fd >

close(file1);
close(file2);
dup2(stdin_copy, 0);
dup2(stdout_copy, 1);
close(stdin_copy);
close(stdout_copy);

However, there's a minor detail you might want to be careful with (from man dup):

The  two  descriptors  do  not  share  file  descriptor  flags (the
  close-on-execflag).  The close-on-exec flag (FD_CLOEXEC; see fcntl(2))
  for the duplicate descriptor is off.

If this is a problem, you might have to restore the close-on-exec flag, possibly using dup3() instead of dup2() to avoid race conditions.
Also, be aware that if your program is multi-threaded, other threads may accidentally write/read to your remapped stdin/stdout.

A: I think you can "save" the descriptors before redirecting:
int save_in, save_out;

save_in = dup(STDIN_FILENO);
save_out = dup(STDOUT_FILENO);

Later on you can use dup2 to restore them:
/* Time passes, STDIN_FILENO isn't what it used to be. */
dup2(save_in, STDIN_FILENO);

I am not doing any error checking in that example - you should.

A: You could create a child process, and set up the redirection inside the child only.  Then wait for the child to terminate, and continue working in the parent process.  That way you don't have to worry about reversing your redirection at all.
Just look for examples of code using fork() and wait ().


Q: Remove planes if boolean = true not working I'm trying to remove my planes when the user inputs that they have landed.  This doesn't work.  Can anyone see any problems with my code to why it does not work.
Here is my code:
Plane
static boolean isLanded;
public boolean isLanded() {
        return isLanded;
    }

    public void setLanded(boolean isLanded) {
        this.isLanded = isLanded;
    }

PlaneStore
public void removeLandedPlanes(PlaneStore store)
    {
        if(Plane.isLanded = true)
        {
            airlineMap.remove(store);
        }
    }

MainApp
case 3:
                    System.out.println("Remove Landed Planes.");
                    airlineMap.removeLandedPlanes(airlineMap);
                    airlineMap.print();
                    break;

HashMap declaration in PlaneStore
HashMap<String, TreeMap<String, Plane>> airlineMap;

    public PlaneStore()
    {
        airlineMap = new HashMap<String, TreeMap<String, Plane>>();
    }

And then in main PlaneStore airlineMap = new PlaneStore();
What this seems to have done is make every plane object to have isLanded to false.

A: if(Plane.isLanded = true)

Note that this is assigning the value true to Plane.isLanded. You want to use the comparison operator == instead of =.
if(Plane.isLanded == true)

And since this is a boolean already, you should actually leave out the == true completely:
if(Plane.isLanded)

A: You are assigning to Plane.isLanded, not testing for equality
 if(Plane.isLanded = true)

should be
 if(Plane.isLanded == true)

You could avoid this altogether with simply
if (Plane.isLanded)

or put the constant term on the left
if (true == Plane.isLanded)

which would not have compiled had you made your initial mistake of = instead of ==


Q: how can I display UIImage from image url The code below works fine if I give statically but
imgDescView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:
[NSURL URLWithString:[NSString stringWithFormat:@"http://4cing.com/mobile_app/uploads/pageicon/6.jpg"]]]];

Same code - I am passing the image url name dynamically it's not working
imgDescView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:
[NSURL URLWithString:[NSString stringWithFormat:@"%@",[imagename objectAtIndex:0]]]];

A: NSMutableArray *imagename = [[NSMutableArray alloc] initWithObjects:@"http://4cing.com/mobile_app/uploads/pageicon/6.jpg", nil];
UIImageView *imgDescView = [[UIImageView alloc] initWithFrame:CGRectMake(0,0, 200, 200)];

imgDescView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:
                                            [NSURL URLWithString:[NSString stringWithFormat:@"%@",[imagename objectAtIndex:0]]]]];

it is working ... i think u r not creating array properly.

A: You need to verify the NSArray contents.  Log out the objects of the array:
NSLog(@"imagename = %@",[imagename description]);

Also, a side-note - might want to think about loading that image dynamically.  I wrote a class that makes this pretty painless:
https://stackoverflow.com/a/9786513/585320
The answer is geared toward using in TableViews (where lag would really hurt performance), but you can (and I do) use this for any web image loading.  This keeps the UI fluid and is very fast.

A: Hi create url in this manner
[NSURL URLWithString:[[NSString stringWithFormat:@"%@",[imagename objectAtIndex:0]] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]

i think it will work and will resolve ur problem.


Q: What's wrong with following google ecommerce analytics code I have waited for more than 72 hours but ecommerce data is not tracked. Tracking is enabled in the analytics account.
 <script type="text/javascript">
       var _gaq = _gaq || [];
       _gaq.push(['_setAccount', 'UA-xxxxx-1']);
       _gaq.push(['_setDomainName', '.welcome.com']);
       _gaq.push(['_trackPageview']);
       _gaq.push(['_trackPageLoadTime']);

       _gaq.push(['_addTrans',
                '650',            // order ID - required
                'bags',  // affiliation or store name
                '19.99',           // total - required
                '0',
                '4.0',           // shipping
                'Anchorage',        // city
                'Alaska',      // state or province
                'USA'
              ]);
        //Add each items in the order
        _gaq.push(['_addItem',
                '650',  // order ID - necessary to associate item with transaction
                '29',           // SKU/code - required
                'bags set of 4',        // product name
                'Cleaning Supplies',   // category or variation
                '15.99',          // unit price - required
            '1'
              );
        //Now submit the transaction
        _gaq.push(['_trackTrans']); //submits transaction to the Analytics server

       (function() {
        var ga = document.createElement('script');
        ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' :
                              'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(ga, s);
       })();
    </script>

  </body>

A: I think you are missing a closing bracket:
//Add each items in the order
    _gaq.push(['_addItem',
            '650',  // order ID - necessary to associate item with transaction
            '29',           // SKU/code - required
            'bags set of 4',        // product name
            'Cleaning Supplies',   // category or variation
            '15.99',          // unit price - required
        '1'
          ]); //right here, missing closing bracket


Q: Solve equation with radicals. Solve equation :  $\left(x-\dfrac{1}{6} \right)\sqrt{4x+1}+\left(x+\dfrac{1}{6} \right)\sqrt{1-2x}+\dfrac{7x+2}{x+2}=\left(x+1 \right)^{2}$.

A: Assuming the validity of calculations of @chubakeno (thanks) and implicitly assuming that the tag algebra-precalculus implies that we are interested in real roots, the solution of equation can be fond. $x=0$ is root. Now we have $-\frac{1}{4}\leq x\leq\frac{1}{2}$. Using the Sturm's sequences which is correct for integer coefficients we obtain, that this polynomial (not considering $0$) has exactly $1$ root in the intervals $(-1/4,-1/8), (-1/8,-1/10),(1/4,1/3),(1/3,1/2)$. We can localize the roots more precisely if it is needed. Substituting back into the original equation we can decide (taking into account of error bounds) which one is root. If my (and computer :-) ) calculations are correct, then the only real solution is $0$.

A: When you expand your equation to an ordinary polynomial, you get a quite ugly 10-degree expansion. I don't have any proof that says that this is irreducible, if I come up with some I will post it here. But meanwhile the only solutions given by WA are
$$x=0,\approx-3.05781-0.688252 i,\approx-3.05781+0.688252 i$$
The last two solutions come from the acceptable roots(to your equation) of the polynomial
$$36x^{10}+432x^9+2736x^8+8924x^7+15588x^6+22952x^5+26057x^4-17480x^3-1400x^2+800x+80 $$


Q: Изменяется текст и у всех объектов цикла при отправке post запроса на ajax Есть такой скрипт (Лайк к посту):

    $('a.like').click(function(e) {
      e.preventDefault();
      $.post('{% url "images:image_like" %}', {
          id: $(this).data('id'),
          csrfmiddlewaretoken: '{{ csrf_token }}'
        },
        function(data) {
          if (data['status'] == 'like') {
            $('i.like-text').text('favorite');
          } else {
            $('i.like-text').text('favorite_border');
          }
          previous_like_count = parseInt($('li.image_like_counts').text());
          if (data['status'] == 'like') {
            $('li.image_like_counts').text(previous_like_count += 1)
          } else {
            $('li.image_like_counts').text(previous_like_count -= 1)
          }
        }
      )
    })

          {% if request.user in image.users_like.all %} favorite {% else %} favorite_border {% endif %}

При нажатии на который `POST-запрос` отправляется как надо, к одному конкретному объекту. Но текст изменяется на всех объектах цикла. Как быть?

{% for image in images %}

{{ image.author.username }}

              {{ image.created }}

    {% if image.url %}

    {% else %}

        {% endif %}

                            {% if request.user in image.users_like.all %} favorite {% else %}    favorite_border {% endif %}

{{ image.users_like.count }}

        {% endfor %}

A: Уточняйте селекторы по id, например:
var id = $(this).data(`id`);
$(`li.image_like_counts[data-id=${id}]`)

Но, возможно, лучше вам использовать $(this). Тогда найти нужные элементы можно так
$('a.like').click(function (e) {
    e.preventDefault();

    var parent = $(this).closest('.media-body');
    var like_text = parent.find('i.like-text');
    var image_like_counts = parent.find('li.image_like_counts');

    $.post('{% url "images:image_like" %}',
        {
            id: $(this).data('id'),
            csrfmiddlewaretoken: '{{ csrf_token }}'
        },
        function (data) {
            if (data['status'] == 'like') {
                like_text.text('favorite');
            } else {
                like_text.text('favorite_border');
            }
            previous_like_count = parseInt(image_like_counts.text());
            if(data['status'] == 'like') {
                image_like_counts.text(previous_like_count += 1)
            } else {
                image_like_counts.text(previous_like_count -= 1)
            }
        }
    )
})


Q: Derivation in ray optics How to derive the formula for magnification in spherical mirrors and thin spherical lenses?
I already know the relationship between image distance (v), object distance (u) and focal length (f), in both the cases.
I also know the formulas for magnification (m) in both the cases, but i don't know how to derive them (for both the cases- spherical mirrors and spherical thin lenses).
Can someone please help?

A: For real pictures you know $s_1/s_2=S_1/S_2$
s beging the distances, S the sizes of object and picture Of cause magnification is the ratio of picture size to object size.

A: Consider the ray through the center of the lens (assumed thin). o and i are object and image distances; h and h' are object and image heights. From similar triangles, h'/i = h/o so h'/h = i/o.


Q: Why numeric enums can be assigned to any number in typescript? I want to know why numeric enums can be assigned to any number. what's different between numeric enums and string-based enums?
enum TYPES {
  False = 0,
  True = 1,
  UnKnow = 2,
}

type IType = {
  type: TYPES
}

const demo1: IType = {
  type: 9    // works, hope error: Type 9 is not assignable to type TYPES
}

enum COLORS {
  GREEN = 'green',
  RED = 'red',
  YELLOW = 'yellow',
}

type IColor = {
  color: COLORS;
}

const demo2: IColor = {
  color: 'blue'   // error: Type '"blue"' is not assignable to type 'COLORS'.ts(2322)
}


Q: How to get the six week sunday's weekno in SQL server 2008 r2? I want to get the six week sundays weekno using the SQL Server 2008.For example i have the November month, date 18, year 2012. The WeekNo of the  November month 18 th date is "47".

A: Try this:
SELECT DATEPART(week,'18-nov-2012')


Q: How can i put my searchbox and navbar at the same line? I'm trying to make my search box in the same line with the "home, about, contact..." stuff but it doesn't seem to worrk, i guess my CSS just not enough to make that, can anyone help me to make them stand in the same line? Thank you so much!
This is css:
.container{

    background-color: #A3318A;
}

.container ul{
    display: inline block;

}

.container ul li {

    display: inline;
    padding:15px;
    font-size: 1.5rem;
    color: white;

}

This is my html:
<!DOCTYPE html>

    <title></title>
    <link rel="stylesheet"  href="style.css">

Home

About

News

Contact

        <form>
            <input class="input" type="text" placeholder="Search here...">

        </form>

A: Make form with display: inline-block:
.container form, /* added */
.container ul{
  display: inline-block; /* fixed */
}


Q: Notification Builder action not working on API 31 (Android 12) I'm stuck while dealing with this api 31. i made a chat app. When I create an action button to receive a phone call it works on android below API 31 or below Android 12, but it doesn't work on Android 12 (only work if the notification is not has action). maybe someone here can help me in finding a solution to this problem?
FirebaseService.java
@Override
public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
    super.onMessageReceived(remoteMessage);

    boolean cancelNotification = false;

    Intent intent = new Intent(this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    Map<String, String> params = remoteMessage.getData();
    JSONObject data = new JSONObject(params);

    PendingIntent pendingIntent;
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
        pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_MUTABLE);
    }
    else {
        pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
    }

    String channel_id = getNotificationData(data, "channel");

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channel_id)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle(getNotificationData(data, "title"))
            .setContentText(getNotificationData(data, "body"))
            .setAutoCancel(true)
            .setContentIntent(pendingIntent);

    if(channel_id.equals("cll2") && getNotificationData(data, "call_action").equals("open")){
        playCallSound(this);

        if(WindowUtil.isAppOnBackground(this) || isScreenOff()){
            ArrayList<String> par = new ArrayList<>();

            par.add("call_channel");
            par.add("call_type");
            par.add("call_token");
            par.add("call_peer");

            String callType = getNotificationData(data, "call_type");

            if(callType.equals("3") || callType.equals("4")){
                par.add("call_group_name");
                par.add("call_group_caller");
            }

            Intent receiveCallAction = new Intent(this, CallReceiver.class);
            receiveCallAction.putExtra("action", "ANSWER");

            Intent cancelCallAction = new Intent(this, CallReceiver.class);
            cancelCallAction.putExtra("action", "DECLINE");

            for (String s : par) {
                receiveCallAction.putExtra(s, getNotificationData(data, s));
                cancelCallAction.putExtra(s, getNotificationData(data, s));
            }

            notificationBuilder.setOngoing(true);

            receiveCallAction.setAction("RECEIVE_CALL");
            cancelCallAction.setAction("CANCEL_CALL");

            PendingIntent receiveCallPendingIntent = PendingIntent.getBroadcast(this, 1200, receiveCallAction, PendingIntent.FLAG_UPDATE_CURRENT);
            PendingIntent cancelCallPendingIntent = PendingIntent.getBroadcast(this, 1201, cancelCallAction, PendingIntent.FLAG_UPDATE_CURRENT);

            notificationBuilder
                    .addAction(R.drawable.ic_baseline_call_24_green, "Answer", receiveCallPendingIntent)
                    .addAction(R.drawable.ic_baseline_call_red_24, "Decline", cancelCallPendingIntent);
        }else{
            cancelNotification = true;
        }
    }if(channel_id.equals("cll2") && getNotificationData(data, "call_action").equals("end_timeout")){
        stopRinging();
    }else if(channel_id.equals("ntf1")){
        if(UserUtil.IS_CHAT_ACTIVITY){
            cancelNotification = true;
        }

        if(!cancelNotification){
            playNotificationSound(this);
        }
    }

    if(!cancelNotification){
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            notificationBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
            NotificationChannel channel = new NotificationChannel(channel_id,
                    getString(R.string.app_name), NotificationManager.IMPORTANCE_HIGH);
            channel.enableLights(true);
            channel.enableVibration(true);
            mNotificationManager.createNotificationChannel(channel);
        }

        mNotificationManager.notify(1000, notificationBuilder.build());
    }
}

CallReceiver.java (Broadcast Receiver)
@Override
public void onReceive(Context context, Intent intent) {
    if (intent != null && intent.getExtras() != null) {
        String action = intent.getStringExtra("action");

        // Perform the action
        performClickAction(context, action, intent.getExtras());

        // Close the notification after the click action is performed.
        NotificationManager mNotificationManager = (NotificationManager)
                context.getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.cancel(1000);

        // Stop the ringtone
        stopRinging();
    }
}

on my AndroidManifest.xml
<service
        android:name=".services.FirebaseService"
        android:exported="true">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>

    <receiver
        android:name=".receiver.CallReceiver"
        android:exported="false"
        android:enabled="true">
        <intent-filter>
            <action android:name="CALL_RECEIVER" />
        </intent-filter>
    </receiver>

Thank you

A: i solve this problem by this code
 PendingIntent receiveCallPendingIntent;
        PendingIntent cancelCallPendingIntent;

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
            receiveCallPendingIntent = PendingIntent.getBroadcast(this, 1200, receiveCallAction, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);
            cancelCallPendingIntent = PendingIntent.getBroadcast(this, 1201, cancelCallAction, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);
        }else{
            receiveCallPendingIntent = PendingIntent.getBroadcast(this, 1200, receiveCallAction, PendingIntent.FLAG_UPDATE_CURRENT);
            cancelCallPendingIntent = PendingIntent.getBroadcast(this, 1201, cancelCallAction, PendingIntent.FLAG_UPDATE_CURRENT);
        }

also add this permission for force Android 12^ (AndroidManifest.xml)
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /><receiver
        android:name=".receiver.CallReceiver"
        android:exported="false"
        android:enabled="true"
        android:permission="android.permission.RECEIVE_BOOT_COMPLETED" >

        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </receiver>


Q: add_filter hook not working in plugin's php file I am developing a plugin and it works fine when I call my code from my plugin's main php file but I want to run only once My external file is called in the plugin. I mean I want to place my function inside includes folder and in a file living there. like plugin folder/includes/file.php ... here is my code
 add_filter('wp_nav_menu_items',',my_custom_function');
 function my_custom_function ($nav){
 return $nav."
Icon
";
}

Kindly let me know how can I make it work, it works in side plugin's main php file but does not work from other php files inside plugin includes folder.

A: It should work if you include your file from the plugins main file, just make sure it is included correctly.
include plugin_dir_path( __FILE__ ) . 'includes/file.php;

This would include a file in an includes folder in your custom plugin folder, and would include an file named: "file.php". If you want to know if its been loaded correctly, just add an die() statement in the included file:
die('my include file has been loaded correctly');

Just remove the die() statement after you have an confirmation that its working :) Lastly you need to copy your callback function code and paste it in your included file. If your hook still does not work, then it might be something wrong with your callback function.
The documentation for the filter hook you are using:
https://developer.wordpress.org/reference/hooks/wp_nav_menu_items/


Q: Automating setterm I've GNU/linux Debian 10 (sid) net install with no x11 on a HP Pavilion dv6. I can keep the monitor on alway with:
setterm -blank 0

Then have the monitor shut off after 10 minutes of inactivity with the:
setterm -blank 10.

What I would like to do is have the screen go off at 23:00 every night and come back on every morning at 06:00. I have tried several things in cron and via systemctld.
What I have tried in both is:
setterm -blank 10
setterm -term bash -blank 10
setterm -term fish -blank 10
setterm -term /dev/tty1 -blank 10
setterm -term linux -blank 10
$TERM=linux setterm -blank 10
$TERM=bash setterm -blank 10
$TERM=fish setterm -blank 10
$TERM=/dev/tty1 setterm -blank 10

I have also made a bash script with all of those variations. To no avail. Is it even possible to run setterm in cron or as a systemctld event?
As a secondary note I'm utilizing fish as my shell, also I have to detach from GNU/screen to actually get setterm to work.

A: For some options, setterm works by sending a sequence of characters to stdout. Normally, when you are on the console these are therefore read by the console driver and interpreted. Other options do ioctls on stdin similarly.
If you use these commands from cron or a systemd unit, you would need to redirect the output or input to/from the console. For example, from cron, as root, try
setterm -term linux -blank 0 >/dev/console

Or for something using ioctl, set the stdin
setterm -term linux -powersave on </dev/console

If you use the bash shell in cron you can say <>/dev/console to open for in and out.


Q: touchesBegan in custom UITableViewCell, touchesEnded in UIView I am trying to mimic a drag n drop of an image from a UITableView to a UIView. Both the UITableView and UIView are on the same view, side by side.
My approach:
is to fire the touchesBegan event inside the UITableView (i.e. when a cell is touched/selected) and fire the touchesEnded event when the touch ends in the UIView.
The problem:
So I created a custom UITableViewCell that contains a UIImageView and a couple of UILabels. And I set the User Interaction Enabled for this UIImageView. Then to receive the touchesBegan event, I did override the touchesBegan method inside the custom UITableViewCell class; and now I am able to receive the touchesBegan event from the cell.
The problem is
I am not getting the touchesEnded event when the touch ends on the UIView. Note that I already implemented the touchesEnded method inside the view controller class (not in the custom class); and if I start and stop a touch within this UIView, I see the touchesEnded being fired.
Is there anything I am missing here?
Using Xcode 4.6 (4H127), testing on iPad 2 with iOS 6.1.3

A: This will not work that way. You will need to utilize the touch methods on the parent view that contains both of your subviews. Could look abstractly like this:
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    if ([self touchOnCell:touches]) { //check to see if your touch is in the table
        isDragging = YES;             //view cell
    }
}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    //do your dragging code here
}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {

    if (isDragging && [self touchOnDropView:touches]) {
        //do your drop code here
    }
}

now if this doesnt work like that alone you might want to implement the hitTest on the tableView and if the touch is in the dragging object's region, then return the parent view.
hope this helps


Q: How can I lazyLoad large model outputs that have been saved using saveRDS? I have a few hundred large model outputs (8 Gb), each saved as a list containing many elements (and sub elements). To do further work on all these outputs it is not possible to load all 100 8 Gb files  at once into the environment and I came across lazyLoad as a possible solution here, here, and here. But have not succeeded in making the code work for me yet!
I suspect the problem might be coming from the data being saved using saveRDS() instead of save() (if I try load() a file saved with saveRDS() it gives an error) but I'm not certain.
I have two questions:
1) Is lazyLoad the correct way to deal with large outputs for indexing and loading individual levels of the data structure when called rather than storing everything in memory?
2) What am I doing wrong?
I have made several attempts along the lines of this:
e = local({readRDS("path/to/file.RData"); environment()})
tools:::makeLazyLoadDB(e, "path/to/file")
lazyLoad("path/to/file")

But the final line (lazyLoad("path/to/file") gives NULL as a result.
Since this is a general problem I haven't created a fake data structure as a reproducible example but can do so if required.
I thank you!

A: 1) readRDS requires assignment unlike load, so this works:
e = local({df <- readRDS("path/to/file.RData"); environment()})
tools:::makeLazyLoadDB(e, "path/to/file")
lazyLoad("path/to/file")

I should be saving my files according to convention using .rds as an extension when saving data using saveRDS.
2) Probably not the right approach in this case as indexing any element of the "promise" loads the whole file not just the indexed element.


Q: Issues connecting via SSH to GCE instance in us-central1 Is anyone else having issues connecting via SSH to their GCE instances in us-central1? I'm not able to connect since last night Feb 23 2021 ~5pm PST.
I'm using Google managed keys and using their GCE console-based SSH utility (click the SSH button from my instance in GCE). I've also tried connecting via SSH in Cloud Shell, and that is also timing out.
It tries and tries and always ends up timing out with "cannot connect due to an error. try again later (#15)".
Last night around the same time https://status.cloud.google.com had a yellow banner at the top stating "GCE instance connectivity issues due to Live Migrations". So I figured it was widespread.
Tried again this morning, GCP status page no longer had the banner, and SSH connection attempts still time out. Ironically the GCP status page now says "February 24, 2021 Multiple services reporting issues" - so I'm thinking I can't be the only one unable to connect to my instances.
This is especially critical for me right now as I was about to take something live to production, but I need to make a change to the server before then. It could not be worse timing - I've even had to postpone a marketing campaign.
Please if anyone can confirm it's not just me I'd really appreciate it.
Note I've also called Google support but don't have a paid plan, so they were limited in their ability to help me. Would appreciate any feedback/input from the community.

A: GCP always encourages their customers to distribute their resources across several zones in order to have availability.
You can create a snapshot of your instance and deploy it in a new zone:
You will need to create a Snapshot to backup your data in your VM instance and use the snapshot to create new instance so that you can still access your data in your newly created instance.
To create snapshot, please follow the steps below:
1. Go to Compute Engine page
2. Look for the snapshot then click it.
3. Click "Create Snapshot" button.
4. Look for the source disk this is the disk of your VM instance that you want to create snapshot.
5. Check the other settings like name etc and once you are done, please click "Create" button.

To create new instance using the new created snapshot, please follow the steps below:
1. Go to Compute Engine page > then select Snapshot.
2. Click the name of the Snapshot you created.
3. Select "CREATE INSTANCE" button.
4. Please check all your settings and don't forget to choose your instance neew zone.
5. Once you're done, please click "Create" button.

Also you could try changing the instance form zone, let me provide you with the instructions for you to do so:
1.Go to Google Cloud Platform >>> Compute Engine
2.Go to Snapshots >>> create a snapshot >>> Select your Compute Engine instance
3.Once snapshot is completed click on snapshot.
4.Under "snapshot details". There, on the top, just click create instance. Here you are basically creating an instance with a copy of your disk.
5.Select your new zone setup previous setting, create new name.
6.Click create, at this point your image should now be running in the new zone


Q: Convert pixel to percentage for big monitors I developed a web page with 1000px width. But it is look very small in big monitor(We have 2560x1600 monitor). My questions are

*

*How to convert a (or any) website to big screen using percentage instead of pixels ?

*Any conversion method for pixel to percentage?

I tried width: 100%,.... But it is not for all(padding, margins, line-height,...)
any suggestions?
Thank you...

A: Have you tried Media Queries?
Check out: http://www.w3.org/TR/css3-mediaqueries/
You can detect the screen size (or intervals of sizes) and apply different CSS to it, regarding element size in your page.


Q: Ruby: Convert memory address string format to bytes for shellcode I have found a program that leaks the address of it's buffer. I can capture that by sending a socket.get_once but it's in a string format. So when I go to pass it to pack it doesn't want a string value. How can I convert a memory address in string format to an address that I can put in shellcode?
Example Address captured: 0x7fffffffdfc0
Using string.pack('Q') it throws an error that it's not an integer. So I tried using a loop to break up the sections into pairs like so:
string.scan(/../).reverse_each { |x| buf += [x.to_i].pack('S')}
I know this is probably a simple solution but for some reason I can't wrap my head around it.

A: It was easy...
buf += [string.to_i(16)].pack('Q')


Q: Is it possible to reuse the UIScrollView scrolling physics for a custom scrolling view? I have a custom view with some complex scrolling behaviour. I’d like the scrolling to have the same physics as UIScrollView, both the inertia and the edge bouncing. Is it possible to somehow reuse the physics code from UIScrollView to save effort and offer a consistent user experience?

A: It’s sort of a hack, but it can be done. The solution is nicely explained in the WWDC 2012 Session #223: Enhancing User Experience with Scroll Views. The main trick is to place a regular UIScrollView over your content, watch for the offset changes reported by the scrollViewDidScroll: delegate call and adjust your custom view’s content accordingly. The only catch is accepting other touch input (as the scroll view covers your real content view and swallows the input), but even this is reasonably easy to solve, as shown in the WWDC video.


Q: Probability of getting two heads in k tosses You toss a fair coin until you get a total of two heads. What is the probability that you made
k tosses?
My answer was $P(2h, K) = Pr_{2}^K/Vr_{2}^K$
$P(2h, K) = \frac{P_{K}}{(K-2)!2!}/2^k$
$P(2h, K) = \frac{K!}{(K-2)!2!}/2^k$
But the teacher told me it was wrong. What am I not seeing?

A: Your answer isn't quite right, as the teacher wants the probability that you got the second head on toss $k$. You worked out the probability that among the first $k$ tosses, exactly two are heads.

To solve the question, just note that

*

*The $k$-th toss must be heads, which has probability $1/2$.

*Exactly one of the first $k-1$ throws is heads.

The latter event has probability $(k-1)\cdot(1/2)^{k-1}$, so the final answer is $\frac{k-1}{2^k}$.


Q: PHP - How to avoid Parse errors on older servers when using new functions When I use an anonymous function ( but see also note below ) like :
$f = function() use ($out) {
                echo $out;
            };

It produces an parse error on servers where PHP is older than 5.3.0.
My software needs to be compatible with unknown servers , but in the same time , I want also to use new functions, so I thought I will add some kind of a version check,
if (o99_php_good() != true){
            $f = function() use ($out) {
                echo $out;
            };
        }

where the o99_php_good() is simply
function o99_php_good(){
    // $ver= ( strnatcmp( phpversion(),'5.3.0' ) >= 0 )? true:false;
    $ver= ( version_compare(PHP_VERSION, '5.3.0') >= 0 )? true:false;
return $ver;
}

But still the error is produced .
Is there a way to somehow "isolate" that part of the code ?
I thought of doing a conditional include() based on a version check , which would probably work, but it will be absurd to make a separate file every time I need to use a function...
Any creative ( or trivial ) solution for that ?
Note : the example here is just a Lambda function, but the problem can occur in every other function which is a new feature and/or  might not be supported on some servers ..
Edit I after comment .
Adding a "minimum requirements" list is always good, but it does not resolve the problem.
If one does not want to loose users (not all customers are happy or can upgrade   their servers every time I will update a new function ) it will just force me to "fork" my software into 2 (or possibly more ) unmanageable versions..

A: I had exactly the same problem and solved it using eval function :
if (version_compare(PHP_VERSION, '5.3.0') >= 0) {
eval('
function osort(&$array, $prop)
{
    usort($array, function($a, $b) use ($prop) {
        return $a->$prop > $b->$prop ? 1 : -1;
    });
}
');
} else {
    // something else...
}

A: Anonymous functions came with PHP 5.3.0.
My first thing to do would be to replace with one of the following:
$my_print_r = "my_print_r";
$my_print_r();

or
$my_print_r = create_function('$a','print_r($a);');

UPDATE:
i would go with the first method... It would give me enough control for creating my own function versions and in much easier procedure than create_function, regardless of PHP version. I never had any problems with that approach. In fact i once built a whole multidimensional array of functions, that was easily manageable and able to add/remove functions, think of that.. That system was also used by other users, they were able to add their functions too in a way.

A: The only thing I can think of is to make a build script which people will have to run to make it compatible with lower versions.
So in case of anonymous methods, the script will loop through all the PHP files, looking for anonymous methods:
$f = function($a) use($out) {
    echo $a . $out;
};

and replace them with create_function for < 5.3:
$f = create_function('$a', '
    global $out;
    echo $a . $out;
');

A: use include
if (o99_php_good() != true){
include 'new_func.php';
        }

new_func.php:
        $f = function() use ($out) {
            echo $out;
        };


Q: nested_attributes fields not showing up In my current rails app, I have a User model which has_one :user_detail. Currently, I cannot get the form to display the fields for the nested attribute unless I already have it seeded with the seeds.rb file.
Here is my User model
class User < ActiveRecord::Base
  has_one :user_detail, :dependent => :destroy
  accepts_nested_attributes_for :user_detail
  attr_accessible :email, :password, :password_confirmation, :access_level, :first_name, :last_name, :user_detail_attributes
  has_secure_password
end

and my UserDetail model
class UserDetail < ActiveRecord::Base
  belongs_to :user
end

and my form
<%= form_for [:admin, @user] do |f| %>

<%= f.text_field(:name, :placeholder => 'Name')%>

<%= f.label(:email) %>

<%= f.email_field(:email, :placeholder => 'Your Email')%>

<%= f.password_field(:password, :placeholder => 'Choose a password') %>

<%= f.password_field(:password_confirmation, :placeholder => 'Confirm Password') %>

    <%= f.fields_for :user_detail do |u| %>

<%= u.text_field(:country, :placeholder => 'Country') %>

<%= u.text_field(:state, :placeholder => 'State') %>

<%= u.text_field(:city, :placeholder => 'City') %>

<%= u.text_field(:phone, :placeholder => 'Phone') %>

    <% end %>

<%= submit_tag("Add Owner") %>

The fields won't show up, until I seed them with this
seeds.rb
UserDetail.delete_all
owner1detail = UserDetail.create(:zip => "84770",
                              :country => "US",
                              :state => "Ut",
                              :city => "St. George",
                              :user_id => owner1.id
                             )

and I run rake db:seed. Once I do this and I edit an existing user, the fields show up, all filled in. However, when creating a user they don't show up. Any ideas why?

A: I moved the build to my controller like so and it worked
def new
  @user = User.new
  @user.build_user_detail
end

A: Try to prebuild it.
<%= form_for [:admin, @user] do |f| %>

<%= f.text_field(:name, :placeholder => 'Name')%>

<%= f.label(:email) %>

<%= f.email_field(:email, :placeholder => 'Your Email')%>

<%= f.password_field(:password, :placeholder => 'Choose a password') %>

<%= f.password_field(:password_confirmation, :placeholder => 'Confirm Password') %>

    <% @user.user_detail.build if @user.user_detail.nil? %>

    <%= f.fields_for :user_detail do |u| %>

<%= u.text_field(:country, :placeholder => 'Country') %>

<%= u.text_field(:state, :placeholder => 'State') %>

<%= u.text_field(:city, :placeholder => 'City') %>

<%= u.text_field(:phone, :placeholder => 'Phone') %>

    <% end %>

<%= submit_tag("Add Owner") %>


Q: How to know how many objects will be created with the following code? I am bit confused in case of objects when it comes to Strings, So wanted to know how many objects will be created with following code, with some explanation about String objects creation with respect to String pool and heap.
 public static void main(String[] args) {

    String str1 = "String1";

    String str2 = new String("String1");

    String str3 = "String3";

    String str4 = str2 + str3;

    }

A: 4 objects will be created.
Two notes:

*

*new String("something") always creates a new object. The string literal "something" creates only one object for all occurrences. The best practice is to never use new String("something") - the instantiation is redundant.

*the concatenation of two strings is transformed to StringBuilder.append(first).append(second).toString(), so another object is created here.

A: each of the str1, str2, str3, str4 are String objects .
str1 : "String1" is a string literal and Java creates a String object whenever it encounters a string literal.
str2 : as you are using the new keyword and constructor of the class String a String object is created
str3 : similar to str1
str4 : concatenated string literal, similar to str1
edit : http://download.oracle.com/javase/tutorial/java/data/strings.html


Q: Passing a location.search parameter to a Jasmine (Karma) test I have a javascript file that uses location.search for some logic. I want to test it using Karma. When I simply set the location (window.location.search = 'param=value' in the test), Karma complains I'm doing a full page reload. How do I pass a search parameter to my test?

A: Without seeing some code it's a little tricky to know what you exactly want, however it sounds like you want some sort of fixture/mock capability added to your tests. If you check out this other answer to a very similar problem you will see that it tells you to keep the test as a "unit".
Similar post with Answer
What this means is that we're not really concerned with testing the Window object, we'll assume Chrome or Firefox manufacturers will do this just fine for us. In your test you will be able to check and respond to your mock object and investigate that according to your logic.
When running in live code - as shown - the final step of actually handing over the location is dealt with by the browser.
In other words you are just checking your location setting logic and no other functionality. I hope this can work for you.


Q: Styled Components & Typescript type error I've set up styled-components successfully in react-native, but I'm now using react-native-web and can't get styled-components to work on the web in this very simple example:
import * as React from 'react';
import styled from 'styled-components';

export default class View extends React.PureComponent {
  public render() {
    return (
      <Container>

Hey

      </Container>
    );
  }
}

const Container = styled.div;

I'm getting this error:
Type error: JSX element type 'StyledComponentClass<DetailedHTMLProps<HTMLAttributes<HTMLHeadingElement>, HTMLHeadingElement>, a...' is not a constructor function for JSX elements.
Property 'render' is missing in type 'StyledComponentClass<DetailedHTMLProps<HTMLAttributes<HTMLHeadingElement>, HTMLHeadingElement>, a...'.  TS2605
> 11 |       <Container>

This is my tsconfig.json:
"target": "es6",
"jsx": "preserve",
"module": "esnext",
"sourceMap": true,
"outDir": "dist",
"types": [
  "react",
  "react-native",
  "jest"
],
"skipLibCheck": true,
"lib": [
  "es2015.promise",
  "esnext",
  "dom"
],
"alwaysStrict": false,
"downlevelIteration": true,
"strict": false,
"strictNullChecks": false,
"allowJs": true,
"esModuleInterop": false,
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": true,
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true

And my package.json:
...
"devDependencies": {
  ...
  "@types/react": "^16.7.20",
  "@types/react-dom": "^16.7.20",
  "@types/react-native": "^0.52.25",
  "typescript": "^2.9.2"
},
"dependencies": {
  ...
  "react": "16.3.1",
  "react-dom": "^16.7.0",
  "styled-components": "^3.4.5",
}

I've tried to rm -rf node_modules; rm package-lock.json; npm install to no avail.
Probably missing something simple here, but anyone have any ideas? Not sure what other information I can provide.

A: You'll want to use the React Native component instead of standard HTML tags.
Instead of styled.div, you'll use styled.View. Also you have to use react native's Text component in replace of standard HTML tags that would hold textual data such as
.
So, this is what your code should translate to
import * as React from 'react'
import { Text } from 'react-native'
import styled from 'styled-components/native'

export default class View extends React.PureComponent {
    render() {
        return(
            <Container>
                <Text>Hey</Text>
            </Container>
        )
    }
}

const Container = styled.View


Q: Serializing object for sending inside Intent on Android I want to pass objects between Activities and Services on Android. The straight forward way to do this is to make your objects implement Serializable or Parcelable.

*

*Serializable it's relatively bad performance.

*Parcelable on the other hand requires me to implement and maintain the serialization myself i.e. always to remember to update it in the future.

I was thinking about using Jackson Json serializer for this task.
It's faster than Java built in serialization and does not require me write and maintain serializtion code.
What you think?

A: I believe both the methods have its own importance.

*

*Parcelable is a good choice. But using parcelable you will have to write code for serialization yourself. This method is not encouraged when you are having large number of data members in your class, whose object you want to send.

*On the other hand serialization is for sure bulky operation but I think easy to implement.
You will have to make your class implements serializable.

But still there is one more option, which you can use. You can make your object static and access it from other Activity. if object is not a lot bulky, then this is also good choice.

A: If performance is important, then you really should go with Parcelable. JSON will be relatively slow because it is less efficient than Parcelable which was specifically implemented in Android for improving performance when packaging data for Inter-Process Communication.


Q: Program Data in a POSIX environment? I'm a little confused on how/where program data should be stored in a Posix envronment, Debian Linux specifically. I understand that user specific data should be kept in $home, and looking at this question it looks like data common to all users should be in /var/lib/myProgram/ but how does myProgram get granted the access to read and write data there? I'm a little lost and I'm still a newcomer to linux, I'd appreciate any insights!


Q: Graphing Segments in R I want to plot segmented data in R. That is, say I have data of the form
| Product               | Date   | Origination | Rate | Num | Balance   |
|-----------------------|--------|-------------|------|-----|-----------|
| DEMAND DEPOSITS       | 200505 | 198209      | 0    | 1   | 2586.25   |
| DEMAND DEPOSITS       | 200505 | 198304      | 0    | 1   | 3557.73   |
| DEMAND DEPOSITS       | 200505 | 198308      | 0    | 1   | 14923.72  |
| DEMAND DEPOSITS       | 200505 | 198401      | 0    | 1   | 4431.67   |
| DEMAND DEPOSITS       | 200505 | 198410      | 0    | 1   | 44555.23  |
| MONEY MARKET ACCOUNTS | 200505 | 198209      | 0.25 | 2   | 65710.01  |
| MONEY MARKET ACCOUNTS | 200505 | 198211      | 0.25 | 2   | 41218.41  |
| MONEY MARKET ACCOUNTS | 200505 | 198304      | 0.25 | 1   | 61421.2   |
| MONEY MARKET ACCOUNTS | 200505 | 198402      | 0.25 | 1   | 13620.17  |
| MONEY MARKET ACCOUNTS | 200505 | 198408      | 0.75 | 1   | 281897.74 |
| MONEY MARKET ACCOUNTS | 200505 | 198410      | 0.25 | 1   | 5131.33   |
| NOW ACCOUNTS          | 200505 | 198209      | 0    | 1   | 142744.35 |
| NOW ACCOUNTS          | 200505 | 198303      | 0    | 1   | 12191.6   |
| SAVING ACCOUNTS       | 200505 | 198301      | 0.25 | 1   | 96936.24  |
| SAVING ACCOUNTS       | 200505 | 198302      | 0.25 | 2   | 21764     |
| SAVING ACCOUNTS       | 200505 | 198304      | 0.25 | 1   | 14646.55  |
| SAVING ACCOUNTS       | 200505 | 198305      | 0.25 | 1   | 20909.7   |
| SAVING ACCOUNTS       | 200505 | 198306      | 0.25 | 1   | 66434.56  |
| SAVING ACCOUNTS       | 200505 | 198309      | 0.25 | 1   | 20005.56  |
| SAVING ACCOUNTS       | 200505 | 198404      | 0.25 | 2   | 16766.56  |
| SAVING ACCOUNTS       | 200505 | 198407      | 0.25 | 1   | 47721.97  |

I want to plot on the Y-axis a line per 'Product' type by 'Balance'. On the X-axis, I want to put the 'Origination'. I would ideally also like to set colors to distinguish between the lines. The data is not currently in data.frame form so let me know if I need to change back to that.
I haven't been able to find an informative solution online for this, even though I'm sure there is.
Thanks,

A: As @zx8754 menitioned, you should provide reproducible data.
Without having tested the code (because there's no reproducible data), I would suggest the following, assuming that the data is in the data.frame 'data':
all_products <- unique(data$Product)
colors_use <- rainbow(length(all_products))

plot(y = data[data$Product == all_products[1],"Balance"],
    x = data[data$Product == all_products[1],"Origination"],
    type = "l",
    col = colors_use[1],
    ylim = c(min(data$Balance, na.rm = T),max(data$Balance, na.rm = T)),
    xlim = c(min(data$Origination, na.rm = T),max(data$Origination, na.rm = T)))

for(i_product in 2:length(all_products)){
    lines(y = data[data$Product == all_products[i_product],"Balance"],
        x = data[data$Product == all_products[i_product],"Origination"],
        col = colors_use[i_product])
}

A: I have not enough reputation to comment, so I write it as an answer. To make @tobiasegli_te's answer shorter, the first plot can be plot(Balance~Origination,data=data,type='n') and then make the subsequent lines done for i_product in 1:length(all_products). That way you need not worry about ylim. Here is an example using the Grunfeld data.
z <- read.csv('http://statmath.wu-wien.ac.at/~zeileis/grunfeld/Grunfeld.csv')
plot(invest~year,data=z,type='n')
for (i in unique(as.numeric(z$firm))) lines(invest~year,data=z,
    subset=as.numeric(z$firm)==i, col=i)

Also note that your Origination is not equally spaced. You need to change it to a Date or similar.

A: I guess you want something like the following:
df <- as.data.frame(df[c('Product', 'Balance', 'Origination')])
head(df)

Product  Balance Origination
1  DEMAND DEPOSITS         2586.25      198209
2  DEMAND DEPOSITS         3557.73      198304
3  DEMAND DEPOSITS        14923.72      198308
4  DEMAND DEPOSITS         4431.67      198401
5  DEMAND DEPOSITS        44555.23      198410
6  MONEY MARKET ACCOUNTS  65710.01      198209

library(ggplot2)
library(scales)
ggplot(df, aes(Origination, Balance, group=Product, col=Product)) +
         geom_line(lwd=1.2) + scale_y_continuous(labels = comma)

A: I am not sure what you my want, is that what you re looking for?

Assuming you put your data in data.txt, removing the pipes and replacing the spaces in the names by '_'
d = read.table("data.txt", header=T)

prod.col = c("red", "blue", "green", "black" )
prod = unique(d$Product)

par(mai = c(0.8, 1.8, 0.8, 0.8))
plot(1, yaxt = 'n', type = "n", axes = TRUE, xlab = "Origination", ylab = "", xlim = c(min(d$Origination), max(d$Origination)), ylim=c(0, nrow(d)+5) )
axis(2, at=seq(1:nrow(d)), labels=d$Product, las = 2, cex.axis=0.5)
mtext(side=2, line=7, "Products")

for( i in 1:nrow(d) ){
myProd = d$Product[i]
myCol = prod.col[which(prod == myProd)]
myOrig  = d$Origination[i]
segments( x0 = 0, x1 = myOrig, y0 = i, y1 = i, col = myCol, lwd = 5 )
}
legend( "topright", col=prod.col, legend=prod, cex=0.3, lty=c(1,1), bg="white" )


Q: Unable to Edit template any object In visual studio 2015 Unable to Edit template any object In visual studio 2015. I try with blend But I can't do that.
please help me? If you don't know, please make a edit template for Button and post it here.
Thanks.

A: I couldn't solve question completely But I found something useful for default template of controls in Windows 8.1.
Windows 8.1 default XAML templates and styles


Q: Is it possible to send email along with form details in php using wamp Hai Friends iam trying for an online form submission .whenever i try to submit form it redirects me to MS OUTLOOK but my my form values are not included in that why?
 Is it possible or does it require ftp credentials or something.
Give me suggestions..

A: It redirects you to outlook mostly because you click on mailto: link. You can connect to smtp server to send e-mail via php.
Here you will find how to do it
You don't need FTP which is file transfer protocol you need connection to SMTP which is Simple  Mail Transfer Protocol.
Also check PHP manual
If you doesn't want to use PHP and you want send it via your client for example outlook you need do something like this:
<form enctype="text/plain" method="get" action="mailto:webdesign@aboutguide.com">
Your First Name: <input type="text" name="first_name">

Your Last Name: <input type="text" name="last_name">

Comments: <textarea rows="5" cols="30" name="comments"></textarea>
<input type="submit" value="Send">
</form>

Code from this page. However, I don't recommend this solution. Connecting to SMTP via PHP is better.


Q: Spring Integration NotSerializableException on jdbc inbound-channel-adapter update query I have a jdbc inbound-channel-adapter which is defined as shown below. I'm using a MySQL dataSource. I want to update the status of rows that have been polled. I'm trying to follow this document: spring integration ref. mannual . My understanding is that the :id should map to the set of all id's returned by the SELECT query.
<int-jdbc:inbound-channel-adapter
    channel="targetChannel" data-source="dataSource"
    query="SELECT * FROM mytable WHERE status=''" row-mapper="myRowMapper"
    max-rows-per-poll="500"
    update="UPDATE mytable SET status='IN_PROGRESS' WHERE id in (:id)">
    <int:poller fixed-delay="60000" />
</int-jdbc:inbound-channel-adapter>

The SELECT query executes fine and I have ensured that all the resulting rows are mapped by the RowMapper as expected, however while it tries to update using the given UPDATE query, I get the following exception:
2016-09-23 14:57:29.361 ERROR 15580 --- [task-scheduler-1] o.s.integration.handler.LoggingHandler   : org.springframework.dao.TransientDataAccessResourceException: PreparedStatementCallback; SQL [UPDATE mytable SET status='IN_PROGRESS' WHERE id in (?)]; Invalid argument value: java.io.NotSerializableException; nested exception is java.sql.SQLException: Invalid argument value: java.io.NotSerializableException
at org.springframework.jdbc.support.SQLStateSQLExceptionTranslator.doTranslate(SQLStateSQLExceptionTranslator.java:108)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:73)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:81)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:81)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:649)
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:870)
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:894)
at org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate.update(NamedParameterJdbcTemplate.java:287)
at org.springframework.integration.jdbc.JdbcPollingChannelAdapter.executeUpdateQuery(JdbcPollingChannelAdapter.java:181)
at org.springframework.integration.jdbc.JdbcPollingChannelAdapter.poll(JdbcPollingChannelAdapter.java:173)
at org.springframework.integration.jdbc.JdbcPollingChannelAdapter.receive(JdbcPollingChannelAdapter.java:149)
at org.springframework.integration.endpoint.SourcePollingChannelAdapter.receiveMessage(SourcePollingChannelAdapter.java:209)
at org.springframework.integration.endpoint.AbstractPollingEndpoint.doPoll(AbstractPollingEndpoint.java:245)
at org.springframework.integration.endpoint.AbstractPollingEndpoint.access$000(AbstractPollingEndpoint.java:58)
at org.springframework.integration.endpoint.AbstractPollingEndpoint$1.call(AbstractPollingEndpoint.java:190)
at org.springframework.integration.endpoint.AbstractPollingEndpoint$1.call(AbstractPollingEndpoint.java:186)
at org.springframework.integration.endpoint.AbstractPollingEndpoint$Poller$1.run(AbstractPollingEndpoint.java:353)
at org.springframework.integration.util.ErrorHandlingTaskExecutor$1.run(ErrorHandlingTaskExecutor.java:55)
at org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:50)
at org.springframework.integration.util.ErrorHandlingTaskExecutor.execute(ErrorHandlingTaskExecutor.java:51)
at org.springframework.integration.endpoint.AbstractPollingEndpoint$Poller.run(AbstractPollingEndpoint.java:344)
at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54)
at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:81)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(Unknown Source)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.sql.SQLException: Invalid argument value: java.io.NotSerializableException
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:963)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:896)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:885)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:860)
at com.mysql.jdbc.PreparedStatement.setSerializableObject(PreparedStatement.java:3829)
at com.mysql.jdbc.PreparedStatement.setObject(PreparedStatement.java:3559)
at com.mysql.jdbc.JDBC42PreparedStatement.setObject(JDBC42PreparedStatement.java:68)
at org.springframework.jdbc.core.StatementCreatorUtils.setValue(StatementCreatorUtils.java:440)
at org.springframework.jdbc.core.StatementCreatorUtils.setParameterValueInternal(StatementCreatorUtils.java:235)
at org.springframework.jdbc.core.StatementCreatorUtils.setParameterValue(StatementCreatorUtils.java:150)
at org.springframework.jdbc.core.PreparedStatementCreatorFactory$PreparedStatementCreatorImpl.setValues(PreparedStatementCreatorFactory.java:292)
at org.springframework.jdbc.core.PreparedStatementCreatorFactory$PreparedStatementCreatorImpl.createPreparedStatement(PreparedStatementCreatorFactory.java:244)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:627)
... 25 more
Caused by: java.io.NotSerializableException: java.lang.Object
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at com.mysql.jdbc.PreparedStatement.setSerializableObject(PreparedStatement.java:3818)
... 33 more

What am I doing wrong here?

A: Found my mistake, thanks to Artem Bilan. I assumed that :id would map to "id" among the column names in the SELECT's result set and not to getId() on the POJOs. My RowMapper was mapping the "id" into "requestId" in the POJO. That was the mistake.


Q: How to run application E2E test after argocd deployment? I would like to know how can we run application E2E(UI or API) test after successful deployment of any micro services using ArgoCD.
Current Setup: I have CI pipeline setup with github-actions. Upon completion on CI build for any microservices, it updates the docker image version in helm values which resides in one of the github repo. This repo is than polled by ArgoCD for any change, and deploys in Kubernestes cluster if there is change exists.
Intent: I want to run the application E2E( UI & API ) test once argocd synced any micro-services deployment object defined in the Helm charts. But I am unsure what should be the trigger point in github actions for that. How E2E test github actions workflow will know argocd has deployed the microservices without any issue and service is ready to be consumed by the automated test.

A: Here is the full solution to the problem statement.
apiVersion: batch/v1
kind: Job
metadata:
  name: api-test-trigger
  annotations:
    argocd.argoproj.io/hook: PostSync
    argocd.argoproj.io/hook-delete-policy: HookSucceeded
spec:
  template:
    metadata:
      labels:
        name: api-test
    spec:
      containers:
      - name: api-test
        args:
            - /bin/sh
            - -ec
            - "curl -X POST -H \"Accept: application/vnd.github.v3+json\" -H \"Authorization: token ${GITHUB_TOKEN}\" ${GITHUB_URL} -d '{\"ref\":\"main\"}'"
        env:
          - name: GITHUB_URL
            value: "https://api.github.com/repos/<your org>/<your repo>/actions/workflows/<workflow id>/dispatches"
          - name: GITHUB_TOKEN
            value: <your PAT>
        image: curlimages/curl

You can create the PAT from github settings and provide the PAT as a secret.

A: ArgoCD provides a feature called resource hooks. Hooks are ways to run scripts before, during, and after a sync operation. A use case for hooks from the official documentation:

Using a PostSync hook to run integration and health checks after a deployment.

Hooks can be any type of Kubernetes resource kind, but tend to be Pod, Job, or Argo Workflows.

Per the GitHub actions documentation, you can send a POST request to the Github API in PostSync hooks template to run the workflow run.


Q: Accessing array attributes from other classes with setter/getter I'm new to Java and was wondering how to access attributes from other classes with setter/getter if they are arrays.
Currently, I have one date class that sets a date with parameters for month/day/year. I need to make another class that uses the date class to set a date of hire to store as an attribute, alongside others.
My code currently looks like this:
public class DateClass {

    private int month;
    private int day;
    private int year;

    // MONTH
    public int getMonth() {
        return month;
    }

    public void setMonth(int month) {
        this.month = month;
    }

    // DAY
    public int getDay() {
        return day;
    }

    public void setDay(int day) {
        this.day = day;
    }

    // YEAR
    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }

    // FULL DATE
    public void setDate(int month, int day, int year) {
        setMonth(month);
        setDay(day);
        setYear(year);
    }

    public int[] getDate() {
        return new int[] { month, day, year };

    }

}

This is the second class:
public class EmployeeClass {

private int[] dateOfHire;

public void setDateOfHire(int[] dateOfHire) {
    dateOfHire.setDate(dateOfHire);
}

public String[] getDateOfHire() {
    return dateOfHire.getDate(dateOfHire);
}

}

The error says: Cannot invoke setDate(int[]) on the array type int[]
How can I fix this? Thanks!

A: You need to do a couple of changes. First your EmployeeClass should have a DateClass attribute instead of int[] and the setDateOfHire() method must call the setDate() method that is available in the DateClass that has 3 parameters:
public class EmployeeClass {
    private DateClass dateOfHire;

    public void setDateOfHire(int[] dateOfHire) {
        this.dateOfHire.setDate(dateOfHire[0], dateOfHire[1], dateOfHire[2]);
    }

    public int[] getDateOfHire() {
        return dateOfHire.getDate();
    }
}

This would work, but I would suggest you review your class design. Having int arrays defining dates is a really bad practice.

A: You're declaring an array of integer primitives private int[] dateOfHire;
To declare an array of DateClass simply use private DateClass[] dateOfHire
The primitive or class defined before the [] is what determines the type of array that is initialized
You can use this
as a reference

A: You will need to create a DateClass object to use its methods. Consider changing your EmployeeClass like so:
public class EmployeeClass {

private int[] dateOfHire; // not sure of the purpose of this array
private DateClass dateClassObject; // your variable name is up to you

public EmployeeClass () { // Constructor for this class

    dateClassObject = new DateClass(); // created a new DateClass in the constructor

}

public void setDateOfHire(int[] dateOfHire) {
        // this dateOfHire array is the array that is passed in when
        // method is called. Do not confuse it the array declared as a property.
        int day = dateOfHire[0] // assuming the day is in index 0 of the array
        int month = dateOfHire[1] // assuming the month is in index 1 of the array
        int year = dateOfHire[2] // assuming the year is in index 2 of the array
        dateClassObject.setDate(month, day, year);  // changed to dateClassObject. Also changed setDate to pass correct parameters
    }

public int[] getDateOfHire() { // changed String[] to int[] because returned value of getDate() is a int array.
        return dateClassObject.getDate(); // changed to dateClassObject. Removed the parameter.
}

}

A: In setDateOfHire just set the value instead of calling a method on it:
public void setDateOfHire(int[] dateOfHire) {
    this.dateOfHire = dateOfHire;
}

Compare it with the way you implements the setters in the DateClass.


Q: Insert Row if cell contains "&" Probably something simple I've missed, but I need to run down a column, and copy-insert any rows that have a "&" in the cell.
I've managed to get it to here, but it's now just getting stuck on the very first cell with a "&", and won't move past it.
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Working")

Dim rng As Range

On Error Resume Next

ws.Range("A2").Select

Do Until ActiveCell.Offset(1, 0) = Empty
    If InStr(ActiveCell, "&") <> 0 Then GoTo InsertRow Else
    ActiveCell.Offset(1, 0).Select
Loop

InsertRow:
    Set rng = ActiveCell.Rows
    rng.Rows.Select
    Selection.Copy
    Selection.Insert Shift:=xlDown
    ActiveCell.Offset(2, 0).Select
    Resume Next

There could be blanks in the column, but I can edit that later, so long as the macro can actually run past the first cell, we'll be fine. There are no error messages, as it just sticks to the first cell that contains a "&".

That's the before and after, the second image shows the rows being copied out.

A: *

*no Select, Activate, ActiveCell, etc

*no OnError

*no Resume

*iterate from bottom to top

Option Explicit
Sub dupAmps()
    Dim WS As Worksheet, C As Range
    Dim LR As Long
    Dim I As Long
Set WS = Worksheets("sheet1")
With WS
    LR = .Cells(.Rows.Count, 1).End(xlUp).Row
End With

For I = LR To 2 Step -1
    Set C = WS.Cells(I, 1)
    If InStr(C, "&") > 0 Then
        C.EntireRow.Insert shift:=xlDown
        C.EntireRow.Copy C.Offset(-1, 0)
    End If
Next I

End Sub


Q: How to get react URL in php for creating API? I want to get a URL which is coming from a React rout.
URL is like: http://localhost:3001/users/[member_username]
In which member_username will be dynamic as per the user name.
So for example if a url hit like http://localhost:3001/users/gray then a variable will get gray or url hit like http://localhost:3001/users/john then a variable will get john
Now i need to get that url into WordPress php file to create an API.
I have tried this solution but did not getting the exact solution that is fit to my problem.
Here is my API code that in which i need to get URL.
function get_user_id(){
$server_name = $_SERVER['SERVER_NAME'];
$user_name = basename("http://".$server_name."/users/admin");

// For now i have set the username as static, so it should be a dynamic as user hit the url.

  $users = get_user_by('login', $user_name);

  if( !empty($users) ){

    foreach ($users as $key => $user) {
      $user_name = new stdClass();
      $user_name->id = $user->ID;
      $user_name->user_login = $user->user_login;
      $user_name->user_nicename = $user->user_nicename;
      $user_name->user_email = $user->user_email;
      return $user_name;
    }
  }

}
/*
 *
 * Add action endpoint building
 *
 */
add_action( 'rest_api_init', function () {
    register_rest_route( 'rest-endpoints/v1', '/userid', array(
            'methods' => 'GET',
            'callback' => 'get_user_id'
    ));
});

A: Could you let me know why that solution not fit for your problem?
seems is ok to get the username.
however, maybe you can try this
<?php
$url = parse_url('http://localhost:3001/users/yourname',PHP_URL_PATH);
$url = str_replace("/users/","",$url);
echo $url;
?>

A: You can use:
$url_path = parse_url('http://localhost:3001/users/a13/abc',PHP_URL_PATH);
$url = preg_replace("/\/(?:[^\/]*\/)*/","",$url_path);
echo $url;

output:
abc

demo: https://regex101.com/r/19x7ut/1/
or this regex:
\/(?:[^\/\s]*\/)*

demo: https://regex101.com/r/19x7ut/3/
both should work fine.


Q: What are the correct min and max values for Gluon maps zooming? I am trying out Gluon maps.  As I understand it, Gluon maps uses OpenStreetMap which has a zoom range of 0 to 20 (but this value is not mentioned in the MapView javadoc).  I create this code:
public class MapTest2 extends Application
{
    MapView mapView = new MapView();
    MapPoint mapPoint = new MapPoint(51.509865d,-0.118092d);    // London, England

    @Override
    public void start(Stage stage) throws Exception {
        StackPane sp = new StackPane();
        sp.getChildren().add(mapView);

        mapView.setCenter(mapPoint);
        mapView.setZoom(42.8);          // ? and -1.1 works but -1.3 fails

        Scene  scene = new Scene(sp, 500, 300);
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        MapTest2.launch(MapTest2.class, args);
    }
}

where I can set the positive zoom value far higher than 20.  Some considerable zooming out on the mouse wheel returns me to a reasonable view.  A zoom value of -1.1 works but -1.3 fails with:
Exception in thread "main" java.lang.RuntimeException: Exception in Application start method
:
Caused by: java.lang.ArrayIndexOutOfBoundsException: Index -2 out of bounds for length 20
    at com.gluonhq.impl.maps.BaseMap.loadTiles(BaseMap.java:347)
    at com.gluonhq.impl.maps.BaseMap.layoutChildren(BaseMap.java:490)
:

What are the real minimum and maximum zoom ranges, and should I use only integer values for zoom as there seems to be some rounding going on?


Q: Assume n is an even integer. For an odd integer m, a sequence of m sets S1,...,Sm ⊆ [n] is a graceful chain of length m if... Assume $n$ is an even integer. For an odd integer $m$, a sequence of $m$ sets $S_1, \dots, S_m \subseteq [n]$ is a graceful chain of length $m$ if:

*

*$S_1 \subset S_2 \subset \dots \subset S_m$

*For every $1 \le i \le m − 1$ we have $|S_{i+1}| = |S_i| + 1$

*$|S_m| + |S_1| = n$.

Show that it is possible to decompose the $2^n$ subsets of $[n]$ using $\binom{n}{\frac{n}2}$ graceful chains.
Note: Of course, the chains do not have to be of the same length. Also, recall that by decomposition we mean that each of the $2^n$ sets $S \subseteq [n]$ should appear in exactly one of the graceful chains.


Q: Confirmation about one simple inequality Suppose A & B are sets of reals.Then is it true that inf{A+B}$\leq$inf{A}+inf{B}.I consider all the cases like A contains all positive and B contains all positive,then alternate positive and negative combinations, and it seems true to me.Is it true?

A: Actually, we have
$$\inf(A+B)=\inf A+\inf B \qquad\text{(and likewise for the supremum)}.$$
Indeed, let $a\in A,\; b\in B$. By definition ofthe infimum, we have $\inf A\le a$, $\;b\le\in B$, whence $\;\inf A+\inf B \le a+b$,and be definition of the infimum, we deduce instantly
$$\inf A+\inf B\le\inf(A+B) .$$
Conversely, consider $a\in A, b\in B$; we have $\inf(A+B)\le a+b$. I'll denote $m=\inf(A+B)$.
Thus $m-a\le b$, and by definition of the infimum, $m-a\le \inf B$, so $\;m-\inf B \le a$, and, again by definition
$$m-\inf B\le \inf A,\quad\text{whence }m=\inf(A+B)\le \inf A+\inf B.$$


Q: Java- Using if statement inside a loop I wrote a small code :
System.out.println("Please enter a number");
int number = scan.nextInt();

if(number == 1) {
    System.out.println("Number is 1");
} else if(number == 2) {
    System.out.println("Number is 2");
} else {
    System.out.println("Invalid selection");
}

When the user enters a number different than 1 and 2, user gets "Invalid selection" message and then code terminates. I don't want it to terminate, I want it to run again until user writes 1 or 2. I tried do-while loop but it become an infinite loop. What are your suggestions?

A: You can use while loop here
 Scanner scanner = new Scanner(System.in);
 boolean status = true;
 while (status) { // this runs if status is true
    System.out.println("Please enter a number");
     int number = scanner.nextInt();
     if (number == 1) {
        System.out.println("Number is 1");
        status=false; // when your condition match stop the loop
     } else if (number == 2) {
        System.out.println("Number is 2");
        status=false;// when your condition match stop the loop
     } else{
        System.out.println("Invalid selection");
     }
 }

A: Try this...
int number;
do{
    System.out.println("Please enter a number");
    number = scan.nextInt();
  if(number == 1)
    {
      System.out.println("Number is 1") ;
    }

  else if(number == 2)
   {
      System.out.println("Number is 2") ;
    }
  else
   {
      System.out.println("Invalid selection") ;
    }
 }while(number!=1 && number!=2);

A: I recommend you check if there is an int with Scanner.hasNextInt() before you call Scanner.nextInt(). And, that makes a nice loop test condition if you use it in a while loop.
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a number");
while (scan.hasNextInt()) {
    int number = scan.nextInt();
    if (number == 1) {
        System.out.println("Number is 1");
        break;
    } else if (number == 2) {
        System.out.println("Number is 2");
        break;
    } else {
        System.out.println("Invalid selection");
    }
}
// ...

A: @Dosher, reposting @Raj_89's answer with correction in while loop condition. Please notice While loop condition
int number = 0;
        do{
            System.out.println("Please enter a number");
            Scanner scan = new Scanner(System.in);
            number = scan.nextInt();
          if(number == 1)
            {
              System.out.println("Number is 1") ;
            }

          else if(number == 2)
           {
              System.out.println("Number is 2") ;
            }
          else
           {
              System.out.println("Invalid selection") ;
            }
         }while(number==1 || number==2);


Q: Archiving MSSQL Database and Retrieving the archived data for reporting I am still an amateur when it comes to MS SQL Server.
I have been tasked with Archiving our Production Database which is growing daily.  Mainly I am looking at the transactions tables, simply because they are the ones that generate the most data (average of a million records per day).
I understand that the tables from which they pull data from might need to be archived as well for referential integrity purposes.
I also need a way to be able to query this archived data whenever needed as quickly as possible if there's a report needed. Any advice?

A: It sounds like whatever application is feeding this database is dumping tons of records in there if as you say there are 1 million transactions a day.  See if whatever is feeding this database has a retention feature.  If you have 1 million + records a day you are going to run out of space quickly.
There are a lot of factors involved in this type of process.  Size of the database, number of transactions, network speeds, storage space, etc...
If I were in your shoes at this moment I would restore a copy of your backup either to another instance or to the same instance if you have room.  I would truncate out all data that is not needed.  I would then create a SQL agent job that will insert the data into the new database tables with the GetDate() function and whatever offset time is needed and do it in a batch function of maybe 1000 per batch.
Here is a sample of one that I use.  It can be an insert or delete batch:
SET NOCOUNT ON;
DECLARE @r INT;
SET @r = 1;
WHILE @r > 0
    BEGIN
        BEGIN TRANSACTION;
        --This could be an INSERT or DELETE etc.
        DELETE TOP (1000)
        FROM dbo.application_log
        WHERE(DATEADD(MM, -6, GETDATE()) > date_created);
        SET @r = @@ROWCOUNT;
        COMMIT TRANSACTION;
    END;

After that is completed, then run a delete batch to remove the data from the primary database, which will purge the old data.
Keep in mind this is a very simplistic model of a data transfer and purge.  There are many ways to accomplish this, but require a greater knowledge of SQL and would take much longer to explain than we have time for here.
Hope that helps.


Q: Unable to query for default vendor from RPM: Error while executing process. while running streamsets I just followed the following tutorials for latest streamset 2.6.6 with flume as datacollector, https://github.com/streamsets/datacollector/blob/master/BUILD.md
At the time of making the build i have faced the following error:

[ERROR] Failed to execute goal
  org.codehaus.mojo:rpm-maven-plugin:2.1.2:attached-rpm
  (generate-sdc-streamsets-datacollector-aws-lib-rpm) on project
  streamsets-datacollector-aws-lib: Unable to query for default vendor
  from RPM: Error while executing process. Cannot run program "rpm":
  error=2, No such file or directory -> [Help 1]


Q: dropdown box with entry I have a list of some entries I want to sort the entries by entering some keyword.
from tkinter import *
from ttkwidgets.autocomplete import AutocompleteCombobox

root = Tk()
root.geometry("100x100")

Phone_no = ["apple", "ball", "cat", "dog", "elephant"]
new_list = []

def selected_list(event):
    match = [i for i in Phone_no if entry.get() in i]
    print(match)
    new_list.clear()

    # this for add data to the listbox
    for c in match:
        new_list.append(c)

    entry.config(completevalues=new_list)

def printer(event):
    print(entry.get())

entry = AutocompleteCombobox(root, width=15, font=('Times', 10), completevalues=Phone_no)
entry.place(x=10, y=10)

print_button = Button(root, text="Print")
print_button.bind("<Button-1>", printer)
print_button.place(x=10, y=20)

# Execute Tkinter
root.mainloop()

after the keyrelease the list was not updating and selectlist method is not calling ,
how to fix , advance thanks


Q: R How to read in a function I'm currently implementing a tool in R and I got stucked with a problem. I looked already in the forums and didn't found anything.
I have many .csv files, which are somehow correlated with each other. The problem is I don't know yet how (this depends on the input of the user of the tool). Now I would like to read in a csv-file, that contains an arbitrary function f, e.g. f: a=b+max(c,d), and then the inputs, e.g. a="Final Sheet", b="Sheet1", c="Sheet2", d="Sheet3". (Maybe I didn't explained it very well, then I will upload a picture).
Now my question is, can I somehow read that csv file in, such that I can later use the function f in the programm? (Of course the given function has to be common in R).
I hope you understand my problem and I would appreciate any help or idea!!

A: I would not combine data files with R source. Much easier to keep them separate. You put your functions in separate script files and then source() them as needed, and load your data with read.csv() etc.
"Keep It Simple" :-)
I am sure there's a contorted way of reading in the source code of a function from a text file and then eval() it somehow -- but I am not sure it would be worth the effort.


Q: $y = \ln x$ with their $x$ coordinates as $1,2$ and $t$ respectively Let A,B,P be the points on the curve $y = \ln x$ with their $x$ coordinates as $1,2$ and $t$ respectively.
Find  $$\lim_{t\to\infty} (\cos \angle{BAP})$$
My try :

I am unable to apply limit.

A: It's easier to find the tangent of the angle: the slope of the line $AB$ is
$$
\frac{\ln2-\ln1}{2-1}=\ln2
$$
and the slope of the line $AP$ is
$$
\frac{\ln t-\ln 1}{t-1}=\frac{\ln t}{t-1}
$$
If $f(t)$ denotes the measure of the angle $BAP$, then
$$
\tan f(t)=\frac{\ln2-\dfrac{\ln t}{t-1}}{1+\ln2 \dfrac{\ln t}{t-1}}
$$
which is essentially what you did. Therefore
$$
\lim_{t\to\infty}\tan f(t)=\ln 2
$$
Now recall that, for an acute angle $\alpha$,
$$
\cos\alpha=\frac{1}{\sqrt{1+\tan^2\alpha}}
$$
and apply theorems on limits.


Q: How one can make the boundary of the regionplot smaller or bigger? Suppose we have a regionplot as follows:
mpion = 0.137;
meta = 0.548;
metap = 0.958;
con1 = Sqrt[meta^2 + w1^2 + w2^2 - 2  mpion^2 + 2 Sqrt[w1^2 - mpion^2]  Sqrt[w2^2 - mpion^2]];
con2 = Sqrt[meta^2 + w1^2 + w2^2 - 2  mpion^2 -2 Sqrt[w1^2 - mpion^2]  Sqrt[w2^2 -mpion^2]];

RegionPlot[
 Re[con2] < metap - w1 - w2 < Re[con1], {w1, .13, .27}, {w2, .13, .27},
 BoundaryStyle -> Directive[Red, Thick], FrameLabel -> {"w1", "w2"},
 PlotStyle -> None, BaseStyle -> FontSize -> 16]

Which we can plot it in x-y plane (x and y are defined as w1 and w2 functions):
 Q = metap - meta - 2*mpion;
solw = Solve[x == Sqrt[3]/Q*(w1 - w2) && y == -(2 + meta/mpion)/Q*(w1 + w2) -
      1 +  (2 + meta/mpion)/Q*(metap - meta), {w1, w2}];
w1funxy = w1 /. solw[[1]];
w2funxy = w2 /. solw[[1]];

RegionPlot[(Re[con2] < metap - w1 - w2 < Re[con1]) /.
   w1 -> w1funxy /. w2 -> w2funxy, {x, -1.4, 1.4}, {y, -1.1, 1.2},
 BoundaryStyle -> Directive[Blue, Thick], FrameLabel -> {"x", "y"},
 BaseStyle -> FontSize -> 16, PlotStyle -> None]

How can I make the boundary of the region in x-y plane smaller? just like this graph (The blue and green boundaries). I need the points in blue and green regions around x=y=0 point.
I couldn't change the inequality equation of the region in the way that it gives what I want.

A: you mean this？
balabala……
Manipulate[
   RegionPlot[Evaluate[(Re[con2] < metap - w1 - w2 < Re[con1]) /.
   w1 -> w1funxy /. w2 -> w2funxy /. {x -> ratio x,
    y -> ratio y}], {x, -1.4, 1.4}, {y, -1.1, 1.2},
  BoundaryStyle -> Directive[Blue, Thick], FrameLabel -> {"x", "y"},
BaseStyle -> FontSize -> 16, PlotStyle -> None], {ratio, 1, 5}]


Q: Save all values in Uppercase Laravel 5+ What would be the best way to save all values in the database as uppercase. So before saving convert all strings to uppercase. I see options to use Events or a trait would probably be best but not quite sure how to achieve this. I do not want to create accessors & mutators for each of my fields.
Got this from : https://laracasts.com/discuss/channels/eloquent/listen-to-any-saveupdatecreate-event-for-any-model
trait Trackable {
public static function bootTrackable()
{
    static::creating(function ($model) {
        // blah blah
    });

    static::updating(function ($model) {
        // bleh bleh
    });

    static::deleting(function ($model) {
        // bluh bluh
    });
}
}

Im not sure how I would be able to get the actual request values to convert them to uppercase?

A: As @Louwki said, you can use a Trait to do that, in my case I did something like this:
trait SaveToUpper
{
    /**
     * Default params that will be saved on lowercase
     * @var array No Uppercase keys
     */
    protected $no_uppercase = [
        'password',
        'username',
        'email',
        'remember_token',
        'slug',
    ];

    public function setAttribute($key, $value)
    {
        parent::setAttribute($key, $value);
        if (is_string($value)) {
            if($this->no_upper !== null){
                if (!in_array($key, $this->no_uppercase)) {
                    if(!in_array($key, $this->no_upper)){
                        $this->attributes[$key] = trim(strtoupper($value));
                    }
                }
            }else{
                if (!in_array($key, $this->no_uppercase)) {
                    $this->attributes[$key] = trim(strtoupper($value));
                }
            }
        }
    }
}

And in your model, you can specify other keys using the 'no_upper' variable. Like this:
// YouModel.php
protected $no_upper = ['your','keys','here'];

A: Was a lot easier than I through. Solution that is working for me using traits, posting it if anyone also run into something like this.
<?php

namespace App\Traits;

trait SaveToUpper
{
    public function setAttribute($key, $value)
    {
        parent::setAttribute($key, $value);

        if (is_string($value))
            $this->attributes[$key] = trim(strtoupper($value));
        }
    }
}

UPDATE:
For Getting values as upper case you can add this to the trait or just add it as a function in the model:
public function __get($key)
{
    if (is_string($this->getAttribute($key))) {
        return strtoupper( $this->getAttribute($key) );
    } else {
        return $this->getAttribute($key);
    }
}


Q: Why does the TCP handling mechanism in the OS wait for an ACK from client before sending Im observing the below behavor in a TCP connection between a server application and a client which run on two different red hat machines.
Example 1

*

*Client acks everything until now (ACK with WND = 1424)

*Server sends 296 bytes to TCP layer and it is sent to the client(PUSH/ACK)

*Server sends 296 bytes to TCP layer and it is sent to the client(PUSH/ACK)

*Server sends 296 bytes to TCP layer and it is sent to the client(PUSH/ACK)

*Server sends/tries to send 239 bytes to TCP layer but: either one of the following two happens

*

*the OS waits ~30ms until ACK from client is received before sending these bytes (this x bytes send will be referred as delayed message below)

*the tcp send call returns EWOULDBLOUCK or EAGAIN (I think this is not possible because 239+239+239+239 < 1424. Please correct me if I'm wrong

Example 2

*

*Client acks everything until now (ACK with WND=1424)

*Server sends 239 bytes to TCP layer and it is sent to the client

*Server sends/tries to send 239 bytes to TCP layer and one of the two things in the above happens

The problem I want to understand is why the server application or the OS waits until the ACK when window size for the client is big enough? Is this something I can tune in the OS level. Can I force server to send all bytes until the window of the client is filled?
As per my understanding there are two possible reasons

*

*Server application does not pass the 'delayed message' to TCP level becuase the send system call returned EWOULDBLOUCK or EAGAIN.

*Application does pass the message to TCP layer, but the operating system does not send it until an ACK from the client is received.

In all the delayed message scenarios, there is an ACK from the client before the SEND of the delayed message. Also the working logic of the application suggests that it does pass the message to the TCP layer.
Can you please suggest where I should focus on the troubleshooting of this.

*

*Is it some OS level setting I can set in either the client or server side

*Is this somehow a fault in the application server?

*Am I wrong in assuming OS doesn't return EWOULDBLOCK until messages fill up the window


Q: Webview causes infinite scrollable white space I have a layout which contained Webview inside NestedScrollview,
<?xml version="1.0" encoding="utf-8"?>
<com.app.swipetofinish.SwipeDownLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/postContainer"
android:descendantFocusability="blocksDescendants"
xmlns:app="http://schemas.android.com/apk/res-auto">

<android.support.design.widget.CoordinatorLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/postDetails"
        android:background="?attr/backgroundColor">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:adjustViewBounds="true"
                android:scaleType="fitXY"
                android:id="@+id/postFeaturedImage"/>

            <com.app.customizeviews.Lato_Bold_TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textSize="20sp"
                android:textColor="?attr/primaryTextColor"
                android:letterSpacing="0.02"
                android:lineSpacingExtra="6sp"
                android:layout_marginStart="16dp"
                android:layout_marginTop="20dp"
                android:layout_marginEnd="16dp"
                android:id="@+id/postTitle"
                android:layout_below="@+id/postFeaturedImage"/>

            <com.app.customizeviews.Lato_Regular_TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/postDate"
                android:textColor="?attr/secondaryTextColor"
                android:textSize="14sp"
                android:layout_below="@+id/postTitle"
                android:layout_marginTop="8dp"
                android:layout_marginStart="16dp" />

            <WebView
                android:id="@+id/webView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/postDate"
                android:layout_marginTop="12dp"/>

            <ProgressBar
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="50dp"
                android:id="@+id/progressBar"
                android:layout_centerHorizontal="true"/>

        </RelativeLayout>

    </android.support.v4.widget.NestedScrollView>

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="?actionBarSize"
        app:layout_anchorGravity="bottom"
        app:layout_anchor="@id/postDetails"
        android:elevation="25dp"
        android:background="@drawable/bottom_post_card">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_ext_link_enabled"
            android:id="@+id/sourceLink"
            android:layout_marginStart="20dp"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"/>

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_share_dark_article"
            android:id="@+id/postShare"
            app:layout_constraintStart_toEndOf="@id/sourceLink"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toStartOf="@id/postLike"/>

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_like_article_unselected"
            android:id="@+id/postLike"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintEnd_toStartOf="@id/postBookmark"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toEndOf="@id/postShare"/>

        <TextSwitcher
            android:id="@+id/likesCount"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_toStartOf="@+id/postBookmark"
            android:clipToPadding="false"
            android:inAnimation="@anim/slide_up"
            android:outAnimation="@anim/fade_out"
            android:layout_marginEnd="5dp"
            app:layout_constraintStart_toEndOf="@id/postLike"
            app:layout_constraintBottom_toBottomOf="@id/postLike"
            app:layout_constraintTop_toTopOf="@id/postLike" />

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_bookmark_article_unselected"
            android:layout_centerVertical="true"
            android:layout_marginEnd="20dp"
            android:layout_alignParentEnd="true"
            android:id="@+id/postBookmark"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"/>

    </android.support.constraint.ConstraintLayout>

</android.support.design.widget.CoordinatorLayout>

and this working perfectly, but from last day it start causing infinite blank space after the web content ends, like this

All the white blank space is caused by Webview after the main contents of Webview.This happens only when I open this layout in a fragment with ViewPager but not if layout open in layout with a single page activity.
And also this working perfectly until yesterday from 2-3 months but from yesterday I'm getting this issue.
Code for loading contents in Webview :
mWebView.getSettings().setLoadWithOverviewMode(true);
        mWebView.getSettings().setUseWideViewPort(true);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setLoadsImagesAutomatically(true);
        mWebView.setVerticalScrollBarEnabled(false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WebView.setWebContentsDebuggingEnabled(true);
        }
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mWebView.setNestedScrollingEnabled(false);
        } else {
            mParentView.setNestedScrollingEnabled(false);
        }
 mWebView.loadDataWithBaseURL(
                            "file:///android_asset/",
                            content,
                            "text/html",
                            "utf-8",
                            null);

A: try to use wrap_content to RelativeLayout height attribute inside NestedScrollView like below code
  <android.support.v4.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/postDetails"
    android:background="?attr/backgroundColor">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"> //change here

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:adjustViewBounds="true"
            android:scaleType="fitXY"
            android:id="@+id/postFeaturedImage"/>

        <com.app.customizeviews.Lato_Bold_TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="20sp"
            android:textColor="?attr/primaryTextColor"
            android:letterSpacing="0.02"
            android:lineSpacingExtra="6sp"
            android:layout_marginStart="16dp"
            android:layout_marginTop="20dp"
            android:layout_marginEnd="16dp"
            android:id="@+id/postTitle"
            android:layout_below="@+id/postFeaturedImage"/>

        <com.app.customizeviews.Lato_Regular_TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/postDate"
            android:textColor="?attr/secondaryTextColor"
            android:textSize="14sp"
            android:layout_below="@+id/postTitle"
            android:layout_marginTop="8dp"
            android:layout_marginStart="16dp" />

        <WebView
            android:id="@+id/webView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/postDate"
            android:layout_marginTop="12dp"/>

        <ProgressBar
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="50dp"
            android:id="@+id/progressBar"
            android:layout_centerHorizontal="true"/>

    </RelativeLayout>

</android.support.v4.widget.NestedScrollView>


Q: Como compartir el estado del usuario (profile) en toda mi aplicación usando NGXS Un cordial saludo, mi duda se basa en como compartir el valor del profile en diferentes partes de mi app, ejemplo: Un usuario inicia sesión y la propiedad profile se rellena con los datos del usuario, pero luego en otros componentes de mi app (chat, setting, ...) quiero obtener dicho profile, debería crear un selector nuevo en cada class state? debería heredar de AuthState? cual es el flujo mas conveniente para compartir el profile en toda mi aplicación sabiendo que cada parte de este tendrá su propio estado (chatState, settingState,...). Muchas gracias.