Q: Rest Webservices I am developing a file upload service and using org.glassfish.jersey.media.multipart.FormDataContentDisposition .getFilename
but it gives the filename along with the complete path which fails creating the file.
If I change to use the fileName in debug mode it works.
How to get just the uploaded file name rather than the complete path?
I am using the following dependencies:
    <dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-server</artifactId>
        <version>${jersey2.version}</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-client</artifactId>
        <version>${jersey2.version}</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-multipart</artifactId>
        <version>${jersey2.version}</version>
    </dependency>


Q: Android custom progress bar with .gif file In my app i have a custom progress bar
progress.xml
 <ProgressBar
    android:id="@+id/progressBar1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:progressDrawable="@drawable/loader" />

my gif file

I want to create a progress bar with this image
In other word i want to show this image whenever i download data from server and remove it after downloading the data
or you can say , how to show this image as a progress bar

A: *

*First Conver your Gif image to png Slice image sequence.

*Declare Your Progress bar as Image view.
 <ImageView
     android:id="@+id/main_progress"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_gravity="center"
     android:visibility="visible" />

*Create .xml file in drawable folder using your .png sequence image those are generated from gif. In this case, Loading_web_animation.xml
 <?xml version="1.0" encoding="utf-8"?>
     <animation-list    xmlns:android="http://schemas.android.com/apk/res/android"
     android:oneshot="false">
 <item
     android:drawable="@mipmap/wblod_0"
     android:duration="40" />
 <item
     android:drawable="@mipmap/wblod_1"
     android:duration="40" />
 <item
     android:drawable="@mipmap/wblod_2"
     android:duration="40" />
 <item
     android:drawable="@mipmap/wblod_3"
     android:duration="40" />
 <item
     android:drawable="@mipmap/wblod_4"
     android:duration="40" />
 <item
     android:drawable="@mipmap/wblod_5"
     android:duration="40" />
 <item
     android:drawable="@mipmap/wblod_6"
     android:duration="40" />
 <item
     android:drawable="@mipmap/wblod_7"
     android:duration="40" />
 <item
     android:drawable="@mipmap/wblod_8"
     android:duration="40" />
 <item
     android:drawable="@mipmap/wblod_9"
     android:duration="40" />
 <item
     android:drawable="@mipmap/wblod_10"
     android:duration="40" />
 <item
     android:drawable="@mipmap/wblod_11"
     android:duration="40" />
 </animation-list>

*In Main Activity set the code like,
 private AnimationDrawable animationDrawable;
 private ImageView mProgressBar;
 mProgressBar.setBackgroundResource(R.drawable.loading_web_animation);
 animationDrawable = (AnimationDrawable)mProgressBar.getBackground();
 mProgressBar.setVisibility(View.VISIBLE);
 animationDrawable.start();
 mProgressBar.setVisibility(View.GONE);
 animationDrawable.stop();`

A: I think I'm late to answer this, But you can try this also.

XML

<FrameLayout
                android:id="@+id/progress_container"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true">
                <ProgressBar
                    android:id="@+id/circular_progress"
                    android:layout_width="100dp"
                    android:layout_height="100dp"
                    android:indeterminateDrawable="@drawable/my_progress_indeterminate"
                    />
                <TextView
                    android:id="@+id/circular_progress_counter"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:textSize="@dimen/text_size_big"
                    android:textColor="@color/white"
                    android:text="10"/>
            </FrameLayout>

my_progress_indeterminate.xml

<?xml version="1.0" encoding="utf-8"?>
<animated-rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:drawable="@drawable/process_icon"
    android:pivotX="50%"
    android:pivotY="50%" />

In Java File login to show Timer. here I used 10 second timer.
private void progressTimer() {
        handler = new Handler();

        if (maxCount >= 0) {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    /*
                    Logic to set Time inside Progressbar
                     */

                    mCircularProgressCounter.setText(maxCount+"");

                    maxCount = maxCount - 1;
                    pickupTimer();

                }
            }, 1000);
        }
    }

Result

A: Put your gif image in /res/raw folder
In your class declare mProgressDialog
TransparentProgressDialog mProgressDialog;

then use following code to show progress dialog
if (mProgressDialog == null)
    mProgressDialog = new TransparentProgressDialog(this);
if (mProgressDialog.isShowing())
    mProgressDialog.dismiss();
    mProgressDialog.setTitle(getResources().getString(R.string.title_progress_dialog));
    mProgressDialog.setCancelable(false);
    mProgressDialog.show();

Create a class TransparentProgressDialog where .gif can be loaded using Glide library.
public class TransparentProgressDialog extends Dialog {

private ImageView iv;

public TransparentProgressDialog(Context context) {
    super(context, R.style.TransparentProgressDialog);
    WindowManager.LayoutParams wlmp = getWindow().getAttributes();
    wlmp.gravity = Gravity.CENTER_HORIZONTAL;
    getWindow().setAttributes(wlmp);
    setTitle(null);
    setCancelable(false);
    setOnCancelListener(null);
    LinearLayout layout = new LinearLayout(context);
    layout.setOrientation(LinearLayout.VERTICAL);
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    iv = new ImageView(context);
    GlideDrawableImageViewTarget imageViewTarget = new GlideDrawableImageViewTarget(iv);
    Glide.with(context).load(R.raw.gif_loader).into(imageViewTarget);

    layout.addView(iv, params);
    addContentView(layout, params);
}

@Override
public void show() {
    super.show();
}

}

A: I solved it before on this post easily:
Custom progress bar with GIF (animated GIF)

Use an ImageView that shows an Animated GIF and when need to show waiting make it visible and when works all will be done, make it Gone!

A: My solution is to use an Animated icon.
1°) Create an XML  "animated" in Drawable :
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/micro_1" android:duration="200" />
    <item android:drawable="@drawable/micro_2" android:duration="200" />
    <item android:drawable="@drawable/micro_3" android:duration="200" />
    <item android:drawable="@drawable/micro_4" android:duration="200" />
    <item android:drawable="@drawable/micro_3" android:duration="200" />
    <item android:drawable="@drawable/micro_2" android:duration="200" />
</animation-list>

2°) Put an imageview in your layout
3°) Put the following code in your activity :
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {
    ProgressDialog progressBar;
    private int progressBarStatus = 0;
    private Handler progressBarHandler = new Handler();
    private ImageView micButton;
    //-- for testing progress bar
    private long fileSize = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //-- declare animation
        final AnimationDrawable[] rocketAnimation = new AnimationDrawable[1];
        final ImageView micButton = findViewById(R.id.mic_button);
        micButton.setBackgroundResource(R.drawable.micro_1);
        //-- button listener
        micButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //-- init button with animation
                micButton.setBackgroundResource(R.drawable.mic_image);
                rocketAnimation[0] = (AnimationDrawable) micButton.getBackground();
                startprogress(rocketAnimation[0]);
            }
        });
    }

    public void startprogress(final AnimationDrawable rocketAnimation) {
         rocketAnimation.start();
        progressBar = new ProgressDialog(MainActivity.this);
         //--reset filesize for demo
        fileSize = 0;
        //-- thread for demo
        new Thread(new Runnable() {
            public void run() {
                while (progressBarStatus < 100) {
                    // process some tasks
                    progressBarStatus = doSomeTasks();
                    // your computer is too fast, sleep 1 second
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    // Update the progress bar
                    progressBarHandler.post(new Runnable() {
                        public void run() {
                            progressBar.setProgress(progressBarStatus);
                        }
                    });
                }

                // ok, file is downloaded,
                if (progressBarStatus >= 100) {
                    // sleep 2 seconds, so that you can see the 100%
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    // close the progress bar dialog
                    progressBar.dismiss();
                    if(rocketAnimation.isRunning()){
                        rocketAnimation.stop();
                    }
                }
            }
        }).start();

    }

    // file download simulator... a really simple
    public int doSomeTasks() {

        while (fileSize <= 1000000) { //1000000

            fileSize++;

            if (fileSize == 100000) {
                return 10;
            } else if (fileSize == 200000) {
                return 20;
            } else if (fileSize == 300000) {
                return 30;
            } else if (fileSize == 400000) {
                return 40;
            } else if (fileSize == 500000) {
                return 50;
            } else if (fileSize == 600000) {
                return 60;
            }
        }

        return 100;
    }
}


Q: LINQ GroupBy Count I've got table which contains of EmployeeID, ProductID and ProductName. The table is called EmployeeProduct and I'd like to make query (which I'll bind to DataGrid) which will get me a result like this:
Employee ID| ProductID | Name | Count(ProductID)
   1       |     2     | XYZ  | 3
   1       |     5     | ZXY  | 2
   2       |     2     | XYZ  | 1

I tried to get sth like this by this query, but it doesn't take a result...
// UPDATED - Now I try to do this this way, but still have no result... //
(Home.xaml.cs)
public class ProductCount
{
    public int ProductNumber { get; set; }
    public int EmployeeNumber { get; set; }
    public int CountProducts { get; set; }
}

public IQueryable<ProductCount> CountProducts()
{
    var data = from b in _employ.EmployeeProduct
        group b by new { b.EmployeeID, b.ProductID } int z
        select new ProductCount { EmployeeNumber = z.Key.EmployeeID, ProductNumber = z.Key.ProductNumber, CountProducts = z.Count()};
    return data.AsQueryable();
}

and later in code I'd like to bind this to my datagrid, but unfortunately it don't causes error but if I do this:
dg.ItemsSource = CountProducts();

it doens't show anything ...

A: Here's a couple of way to do this:
var employeeProducts = new List<EmployeeProduct>();
employeeProducts.Add(new EmployeeProduct(1, 2, "XYZ"));
employeeProducts.Add(new EmployeeProduct(1, 5, "ZXY"));
employeeProducts.Add(new EmployeeProduct(2, 2, "XYZ"));

var way1 = employeeProducts.Select(
    ep => new ProductCount
                {
                    ProductNumber = ep.ProductID,
                    EmployeeNumber = ep.EmployeeID,
                    CountProducts = employeeProducts.Count(epc => epc.ProductID == ep.ProductID)
                });

var way2 = employeeProducts
    .GroupBy(ep => ep.ProductID)
    .SelectMany(epg => epg.Select(
        ep => new ProductCount
                    {
                        ProductNumber = ep.ProductID,
                        EmployeeNumber = ep.EmployeeID,
                        CountProducts = epg.Count()
                    }));

A: I'm thinking the query will look something like this
  EntityQuery<EmployeeProduct> query = from c in _employ.CountProduct()
                                         group c by new {c.UserId, c.ProductId, c.Name}
                                         into g
                                         select new {
                                            g.UserId,
                                            g.ProductId,
                                            g.Name,
                                            Count = g.Count()
                                         }


Q: options.remove(); doesn't work, weird behaviour I've got a paypal select, where I have different options. I want to choose just one option and erase the rest of them. To do so I've got this piece of code:
var selectobject=document.getElementById("os0"); //this is the select
        for (var i=0; i<selectobject.length; i++){
        if (selectobject.options[i].value != <?php echo $people; ?> ){
            selectobject.remove(i);
            alert(i);
        }
    }

And here is the select from paypal,
<input type="hidden" name="on0" value="people">people

<select name="os0" id="os0">
    <option id="1" value="1">1 €123,97 EUR</option>
    <option id="2" value="2">2 €249,94 EUR</option>
    <option id="3" value="3">3 €371,91 EUR</option>
    <option id="4" value="4">4 €495,88 EUR</option>
    <option id="5" value="5">5 €619,85 EUR</option>
    <option id="6" value="6">6 €743,82 EUR</option>
    <option id="7" value="7">7 €867,79 EUR</option>
    <option id="8" value="8">8 €991,76 EUR</option>
    <option id="9" value="9">9 €1.115,73 EUR</option>
    <option id="10" value="10">10 €1.239,70 EUR</option>
</select>

So what happens is super weird, it erases just tha paar numbers, and just counts until 5 or 6, the result if I send for example 1 persons is:

*

*1 €123,97 EUR

*3 €371,91 EUR

*5 €619,85 EUR

*7 €867,79 EUR

*9 €1.115,73 EUR

and if I choose 2 people:

*

*2 €249,94 EUR

*4 €495,88 EUR

*6 €743,82 EUR

*8 €991,76 EUR

*10 €1.239,70 EUR

I've got also an alert to tell me where is "i" and it just goes up to 5 or 4, don't understand.

A: When you remove the option at i, you're shuffling all the other options down; so now, the next option is at i. But then because you're using a for loop, you're incrementing i — and you never looked at the option after the option you removed.
Instead, use a while loop and only increment i if you don't remove the option.
var selectobject = document.getElementById("os0"); //this is the select
var i = 0;
while (i < selectobject.length) {
    if (selectobject.options[i].value != <?php echo $people; ?> ){
        selectobject.remove(i);
        alert(i);
    } else {
        ++i;
    }
}

Live Example using 3 (and without the alert):

var people = 3;
var selectobject = document.getElementById("os0"); //this is the select
var i = 0;
while (i < selectobject.length) {
    if (selectobject.options[i].value != people){
        selectobject.remove(i);
    } else {
        ++i;
    }
}
<select name="os0" id="os0">
    <option id="1" value="1">1 €123,97 EUR</option>
    <option id="2" value="2">2 €249,94 EUR</option>
    <option id="3" value="3">3 €371,91 EUR</option>
    <option id="4" value="4">4 €495,88 EUR</option>
    <option id="5" value="5">5 €619,85 EUR</option>
    <option id="6" value="6">6 €743,82 EUR</option>
    <option id="7" value="7">7 €867,79 EUR</option>
    <option id="8" value="8">8 €991,76 EUR</option>
    <option id="9" value="9">9 €1.115,73 EUR</option>
    <option id="10" value="10">10 €1.239,70 EUR</option>
</select>

A: When you remove items while iterating over them, the element currently processed in i will be offset each time an item is removed.
If you remove them in reverse you shouldn't have the issue. See example below if element with value 9 was desired.

document.addEventListener('DOMContentLoaded', function() {

  var selectobject = document.getElementById("os0"); //this is the select
  for (var i = selectobject.length - 1; i >= 0; i--) {
    if (selectobject.options[i].value != 9) {
      selectobject.remove(i);
    }
  }
}, false);
<input type="hidden" name="on0" value="people">people

  <select name="os0" id="os0">
    <option id="1" value="1">1 €123,97 EUR</option>
    <option id="2" value="2">2 €249,94 EUR</option>
    <option id="3" value="3">3 €371,91 EUR</option>
    <option id="4" value="4">4 €495,88 EUR</option>
    <option id="5" value="5">5 €619,85 EUR</option>
    <option id="6" value="6">6 €743,82 EUR</option>
    <option id="7" value="7">7 €867,79 EUR</option>
    <option id="8" value="8">8 €991,76 EUR</option>
    <option id="9" value="9">9 €1.115,73 EUR</option>
    <option id="10" value="10">10 €1.239,70 EUR</option>
</select>


Q: QWidget with doubleclick I want to be able to double click a QPushbutton instead of a single click.
What I tried:
connect(pb, SIGNAL(doubleClicked()), this, SLOT(comBtnPressed()));

Error says "QObject::connect: No such signal QPushButton::doubleClicked()"
I chose QPushButton initially, but for my purpose, you can suggest change to other object if it can make a doubleclick event. Not necessarily be a push button.
Thank you Masters of Qt and C++.

A: A simple solution is to create our own widget so we overwrite the mouseDoubleClickEvent method, and you could overwrite paintEvent to draw the widget:
#ifndef DOUBLECLICKEDWIDGET_H
#define DOUBLECLICKEDWIDGET_H

#include <QWidget>
#include <QPainter>

class DoubleClickedWidget : public QWidget
{
    Q_OBJECT
public:
    explicit DoubleClickedWidget(QWidget *parent = nullptr):QWidget(parent){
        setFixedSize(20, 20);
    }

signals:
    void doubleClicked();
protected:
    void mouseDoubleClickEvent(QMouseEvent *){
        emit doubleClicked();
    }
    void paintEvent(QPaintEvent *){
        QPainter painter(this);
        painter.fillRect(rect(), Qt::green);
    }
};

#endif // DOUBLECLICKEDWIDGET_H

If you want to use it with Qt Designer you can promote as shown in the following link.
and then connect:
//new style
connect(ui->widget, &DoubleClickedWidget::doubleClicked, this, &MainWindow::onDoubleClicked);
//old style
connect(ui->widget, SIGNAL(doubleClicked), this, SLOT(onDoubleClicked));

In the following link there is an example.


Q: How can I create recipe in calibre to fetch full content from xml instead webpage? I  have a xml rss feed like below,
http://www.prajavani.net/rss.xml
where description contains body of news/article and also contains image. when i create recipe in calibre, it fetches content from web page using link in xml, but it doesnt fetch correctly and doesnt read image. But xml contains all content need title, image, body(description), image. How can i make recipe to fetch every thing from xml itself instead downloading from each webpage.
hope understood my situation.
Regards , Abdul

A: Just got answer.
Set
use_embedded_content = True


Q: Email template font not working on tablet and phone devices Agency FB font works fine on desktop view on my email template when I send it out but in the device view it reverts back to the PT-sans.
I have applied the Agency FB font anywhere it says font family and I included the url link too. I use MailChimp to send the emails out, any ideas?

A: MailChimp's docs state that support for custom fonts in emails is limited.

Elements to Avoid > Custom Fonts
MailChimp’s Drag and Drop Editor provides web-safe fonts only. Most email clients don’t support CSS properties like @font-face, @import, and that import custom fonts into web pages. For consistent display, use web-safe fonts.
Or use images to display custom-font headlines, and include the body content as text. Without this balance of text and images, spam filters can flag your campaign.

from Limitations of HTML Email
Perhaps they are trying to protect you from seeing a preview different than what most of your users will see.  However it does seem you can override this default with a custom template:

Note
If you’re comfortable with coding or if you have access to a developer, you can design custom coded templates that contain HTML elements with limited email client support, but we don’t always recommend it. Keep in mind that MailChimp support agents won’t be able to help you troubleshoot issues with your custom code.

Update: In the custom template docs (see Experimenting with Web Fonts), they do discourage use, but claim <link>, @import, @font-face, etc will work as expected in mail clients whose browsers do support custom fonts.

A: well, I think is more matter of what email client (or browser) you are using on mobile device, unfortunately it's highly possible that on older devices etc, you won't be able to get your font, especially in old mail mobile clients,
here is something what I consider as a quite ok solution ( yep, not the best one probably ), but if your mail looks good in Outlook 2010 on your desktop, then it should be ok in most of the other clients/browsers,
Outlook 2010 is could be such a pain, that if you make things work in it, that should cover the other environments


Q: UIAlertView with UITextField I was adding UITextfield to the UIAlertView as shown:
UIAlertView *addingBookAlert=[[UIAlertView alloc]initWithTitle:@"Enter Note" message:NULL delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
    addingBookAlert.tag=kAddNoteAlertTag;

    myTextField = [[UITextField alloc] initWithFrame:CGRectMake(12.0, 45.0, 260.0, 25.0)];
    myTextField.placeholder=@"Book Mark";
    [myTextField becomeFirstResponder];
    [myTextField setBackgroundColor:[UIColor whiteColor]];
    myTextField.textAlignment=UITextAlignmentCenter;
    myTextField.delegate=self;
    CGAffineTransform myTransform = CGAffineTransformMakeTranslation(0, 60);
    [addingBookAlert setTransform:myTransform];
    [addingBookAlert addSubview:myTextField];
    [addingBookAlert show];

I Portrait its showing with textfield,cancel and ok button.But in Landscape its appearing only textfield,cancel and ok button not appearing.
How to resolve this...
Thanks in Advance.

A: Use alertview like this
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Enter  Name" message:@"" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Submit", nil];
    alert.alertViewStyle=UIAlertViewStylePlainTextInput;
    UITextField *textField=[alert textFieldAtIndex:0];
    textField.delegate=self;
    [alert show];
    [alert release];

And access the value of textfield like this
#pragma mark alert button view button
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{

    if(buttonIndex==1)
    {
        UITextField *textField=[alertView textFieldAtIndex:0];
}
}

A: In iOS 8 UIAlertview has been deprecated. UIAlertController is used instead of that.
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Add Fruit" message:@"Type to add a fruit" preferredStyle:UIAlertControllerStyleAlert];
    [alert addTextFieldWithConfigurationHandler:^(UITextField *textField){
        textField.placeholder = @"Fruit";
}];

UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK"
                                                   style:UIAlertActionStyleDefault
                                                 handler:^(UIAlertAction *action) {
                                                     UITextField *textFiel = [alert.textFields firstObject];
                                                     [fruits addObject:textFiel.text];
                                                 }];
[alert addAction:okAction];

[self presentViewController:alert animated:YES completion:nil];


Q: PHP check if today is in between two dates Consider following code:
$today = date("d/m/Y");

$start_date = '20/11/2014';
$time1 = strtotime($start_date1);
$start_date1 = date('d/m/Y',$time1);

$end_date = '20/01/2015';
$time2 = strtotime($end_date1);
$end_date1 = date('d/m/Y',$time2);

if( $start_date1 <= $today && $end_date1 >= $today)
    echo "yes";
else
    echo 'no';

Even though $today is in between those start and end date, I get "no" in return. What might be the problem here? I just wanna check if today is in between those dates. Start date and end date are saved as string in DB.

A: Try this:
<?php

    $now = new DateTime();
    $startdate = new DateTime("2014-11-20");
    $enddate = new DateTime("2015-01-20");

    if($startdate <= $now && $now <= $enddate) {
        echo "Yes";
    }else{
        echo "No";
    }

?>


Q: How to dm all moderators in discord by discord.py, not only one? I have this code:
async def report(ctx, member: discord.Member,  *, arg):
    role = ctx.guild.get_role(9999999999999) # Imagine that 9999999999999 is moderator role id
    members = ctx.guild.members
    await ctx.channel.send('Your complaint was sent to moderators!', delete_after=10)
    for i in role.members:
        await i.send(f'{ctx.author.mention} sent a complaint on {member.mention} with reason:\n**{arg}**')
        await ctx.message.delete()

The problem is that when I write $report @user reason, only one moderator receives this report in private messages, not all. There are 3 moderators on the server, and for some reason only one receives a message in the DM, and not all 3 moderators.
How to fix this? I would be very grateful for help.

A: Put the await ctx.message.delete() out of your for loop. If a message is deleted and you're trying to delete it again it will throw an error.


Q: Remove next character jQuery (no html elements given) Suppose the following markup:

      link [ some text here
      link [ some more text here

Is there anyway to use jQuery to remove the ' [ ' from the top line but not the bottom one?
Note: I don't have the access to the markup, but I can add elements, divs etc. using jQuery if I wanted to. BUT jQuery does not need to target the string of ' ] ' in particular - it can be something like "remove next 3 characters after uniqueLink1.

A: jQuery doesn't really help much with manipulating text nodes, but here it is:
var tn = $('a[name="uniqueLink1"]')[0].nextSibling;
tn.nodeValue = tn.nodeValue.replace('[', '');

Demo

$()[n] is a shorthand for $().get(n), so [0] will return a reference to the first matched DOM element inside the jQuery object, the uniqueLink1 anchor.
nextSibling, as the name implies, grabs the next sibling node. In this case, the text node that follows the given anchor element.
nodeValue gets and sets the content of the text node.
String.replace() given a string as the first argument replaces only the first occurrence, thus this should be enough enough given the DOM structure is similar to the posted one.

A: This will filter the textnodes, and remove a [ from the first on it finds:
var textNode = $('body').contents().filter(function() {
    return this.nodeType == 3;
}).eq(1);
textNode.replaceWith(document.createTextNode(textNode[0].textContent.replace('[','')));

Example fiddle


Q: Ordering the results of an file with ArrayList and compareTo I have to order an arrayList that contains lines from a file by account ID and then by salary to get this result:
CuentaAhorro   : 11111111A (Alicia)   Saldo  111,11
CuentaAhorro   : 12345678A (Lucas)    Saldo 5100,00
CuentaCorriente: 22222222B (Peio)     Saldo  222,22
CuentaAhorro   : 33333333C (Isabel)   Saldo 4433,33
CuentaCorriente: 33333333C (Isabel)   Saldo 3333,33
CuentaAhorro   : 87654321A (Asier)    Saldo 3000,00

My arrayList calls the compareTo method from Bank.java.

 public void ordenarCuentas() {

            Collections.sort(cuentas);

        }

The call is to the method compareTo in an abstract class called Account with the comparable interface:
   @Override
   public int compareTo(Cuenta unaCuenta) {

      Cliente unTitular = unaCuenta.titular;

      if(unTitular.toString().equals(unaCuenta.titular.toString()) == true) {
            return 0;
//         if(saldo < unaCuenta.saldo) {
//             return -1;
//          } else if (saldo > unaCuenta.saldo) {
//             return 1;
//          } else {
//             return 0;
//          }
      }
        return -1;
}

I need to check if the object 'Cuenta unaCuenta' passed as a parameter has the same account number as another and then sort by the amount of money in the account, however I am not sure how to get the condition right, as you can see, with the commented if I get the salary in the right descending order but not the account IDs.
The object Cuenta unaCuenta contains titular which contains account number and name.
The object Cliente unTitular contains the account number and name.
Could somebody lend me a hand please?

A: I am not able understand it very clearly because of language barrier
But if you have a arraylist you can call sort method on it an pass a comparator to get the desired sorting , something like below.
It is just to give you an idea
 ArrayList<String> list = new ArrayList<>();
     list.sort(new Comparator() {

        @Override
        public int compare(Object o1, Object o2) {

            if(o1.account.equals(o2.account)) return 0;
            return o1.amount - o2.amount;
        }

     });

as Lambda
ArrayList<String> list = new ArrayList<>();
     list.sort((o1,o2) ->
                          if(o1.account.equals(o2.account)) return 0;
                          return o1.amount - o2.amount;
     });

A: Thank you everyone for the comments. Next time i'll translate the Spanish code to English. I'll post my solution incase someone comes across this question.
(in my case I had to use a comparable interface and a compareTo method).
 @Override
   public int compareTo(Account anAccount) {

        String b = this.title.toString();
        Client aTitle = anAccount.title;
        String c = aTitle.toString();

        if(b.compareTo(c) == 0) {
            if(balance == anAccount.balance) {
               return 0;
            } else if (balance < anAccount.balance) {
               return 1;
            } else {
               return -1;
            }
           }
            return b.compareTo(c);

         }

As stated, I had to compare both object values first, if they are the same I then check the condition of the balance to change the order.
-1 = object is less than the parameter.
0 = when both objects are the same.
1 = the object is more than the parameter.

And I called the method from the Bank.java class with:
Collections.sort(cuentas);

Where cuentas is the ArrayList.


Q: C# Powershell BeginInvoke Completed Event not Fired This is a sample code to test a functionality, it has no use in itself.
I want to fire the completed event of the PSDataCollection object.
I found in Microsoft that the CloseAll method in C++ should be called to let BeginInvoke know that there are no commands left, I'm not sure that this concept applies in C#, I cannot find this method anywhere.  The code works because I used the Completed state from InvocationStateChanged. I do not understand why this one is fired and not the other. I searched for days for an answer but there's not much to find.
Thanks
Jean
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Management.Automation;
using System.Management.Automation.Runspaces;

namespace PSAsync
{
    public partial class Form1 : Form
    {
        RunspacePool RSPool;
        StringBuilder stringBuilder;
        PowerShell Ping1;
        IAsyncResult Ping1AsyncResult;
        PSDataCollection<PSObject> Output;

        public Form1()
        {
            InitializeComponent();
            RSPool = RunspaceFactory.CreateRunspacePool(1, 4);
            RSPool.Open();
            stringBuilder = new StringBuilder();
        }

    private void btnPing1_Click(object sender, EventArgs e)
    {
        Ping1 = PowerShell.Create();
        //Instead we rely on the InvocationStateChanged event
        lblPing1.Text = "Status:" + Ping1.InvocationStateInfo.State.ToString();
        Ping1.InvocationStateChanged += Ping1_InvocationStateChanged;

        Ping1.RunspacePool = RSPool;
        Ping1.AddCommand("ping").AddArgument("192.168.1.1");

        Output = new PSDataCollection<PSObject>();
        Output.Completed += Test_Completed;//never gets fired
        Output.DataAdded += Output_DataAdded;
        Ping1.Streams.Error.DataAdded += Error_DataAdded;

        Ping1AsyncResult = Ping1.BeginInvoke<PSObject, PSObject>(null,Output);

    }

    private void Error_DataAdded(object sender, DataAddedEventArgs e)
    {
        throw new NotImplementedException();
    }

    private void Output_DataAdded(object sender, DataAddedEventArgs e)
    {
        PSDataCollection<PSObject> myp = (PSDataCollection<PSObject>)sender;

        Collection<PSObject> results = myp.ReadAll();
        foreach (PSObject result in results)
        {
            this.Invoke((MethodInvoker)delegate
            {
                // Show the current time in the form's title bar.
                this.txtOutput.Text = txtOutput.Text + result.ToString()+Environment.NewLine;
            });
        }
    }

    private void Test_Completed(object sender, EventArgs e)
    {
        throw new NotImplementedException();
    }

    private void Ping1_InvocationStateChanged(object sender, PSInvocationStateChangedEventArgs e)
    {
        Console.WriteLine("Invocation State Changed:"+e.InvocationStateInfo.State.ToString());
        this.Invoke((MethodInvoker)delegate
        {
            this.lblPing1.Text = "Status:"+e.InvocationStateInfo.State.ToString();
        });
        if (e.InvocationStateInfo.State == PSInvocationState.Completed)
        {
            this.Invoke((MethodInvoker)delegate
            {
                this.txtOutput.Text = txtOutput.Text +"Status:" + e.InvocationStateInfo.State.ToString();
            });
        }
    }

    private void btnQuit_Click(object sender, EventArgs e)
    {
        RSPool.Close();
        this.Close();
    }
}

}


Q: Custom number to binary? I'm learning C# and im trying to get a custom number to convert to binary. I've looked up several forms here on stack overflow and they have similar code to this, but it doesn't work. Any ideas?
Console.WriteLine("You have chosen binary, input a number then it will be converted to binary.");
string num1input = Console.ReadLine();
double num1 = double.Parse(num1input);
var binary = Convert.ToString(num1, 2);
Console.WriteLine("{0} converted to binary is {1} " ,num1, binary);

A: It's not clear from your question if you are trying to convert an integer or a floating point value to a binary string representation.
For an integer, use this code:
void Main()
{
    Console.WriteLine("You have chosen binary, input a number then it will be converted to binary.");
    string num1input = Console.ReadLine();
    int num1 = int.Parse(num1input);

    var binary = Convert.ToString(num1, 2);

    Console.WriteLine("{0} converted to binary is {1} ", num1, binary);
}

For a double, this code might be what you want:
void Main()
{
    Console.WriteLine("You have chosen binary, input a number then it will be converted to binary.");
    string num1input = Console.ReadLine();
    double num1 = double.Parse(num1input);

    long bits = BitConverter.DoubleToInt64Bits(num1);

    var binary = Convert.ToString(bits, 2);

    Console.WriteLine("{0} converted to binary is {1} ", num1, binary);
}

A: I found this exercise interesting, so here is what I did :
public IEnumerable<char> ConvertToBase2(int myNumber) {
    while(myNumber != 0) {
        var returnValue = (myNumber%2 == 0) ? '0' : '1';

        myNumber = (myNumber % 2 == 0) ? myNumber / 2 :
            (myNumber - 1) / 2;

        yield return returnValue;
    }
}
Console.Write(String.Concat(
    ConvertToBase2(9).Reverse()
));

It works only for integers. I don't remember exactly how floating points numbers are implemented.
By the way, this is a better answer ;-)


Q: Changing main form button visibility from the subform I've been trying to make a button disappear when a new insert is made and one of the fields is empty, problem is the field is on a subform (data sheet view) and the button on the main form I've been trying the following code with no success.
If Me.Produto = "" Then
        [Orçamentos]!Comando33.Visible = False
        [Orçamentos]!Comando47.Visible = False
        Me.Descrição.Visible = False
 End If

Any advice?

A: Assuming Me is the sub form, and Orçamentos is the main form:
If Me.Produto = "" Then
    Me.Parent!Comando33.Visible = False
    Me.Parent!Comando47.Visible = False
    Me.Descrição.Visible = False
End If


Q: dynamically load images from server in jtinder i am using jtinder for creating tinder like effect. here is the library.
  https://github.com/do-web/jTinder

i want to add images dynamically when users are on 4th image out of 5 images loaded when page was called first time.
here is the javascript someone used to make dynamic call but i am not getting how to call  data from server as pattern and name of all images will be different everytime.
      $.fn[ pluginName ] = function (options) {
    this.each(function () {

        if (!$.data(this, "plugin_" + pluginName)) {
            $.data(this, "plugin_" + pluginName, new Plugin(this, options));
        }
        else {
            $.data(this, "plugin_" + pluginName).bindNew(this);
        }

    });

    return this;
};

any help to make jquery/ajax call to server after 4th image is swiped will be great help

A: Add a destroy method to the plugin prototype in jTinder.js:
destroy: function(element){
    $(element).unbind();
    $(this.element).removeData();
}

like so:
     init: function (element) {

        container = $(">ul", element);
        panes = $(">ul>li", element);
        pane_width = container.width();
        pane_count = panes.length;
        current_pane = panes.length - 1;
        $that = this;

        $(element).bind('touchstart mousedown', this.handler);
        $(element).bind('touchmove mousemove', this.handler);
        $(element).bind('touchend mouseup', this.handler);
    },

    destroy: function(element){
        $(element).unbind();
        $(this.element).removeData();
    }

    showPane: function (index) {
        panes.eq(current_pane).hide();
        current_pane = index;
    },

And then create a function, addcard() where you first fetch the data you want from a JSON source, add it to the main  under the tinderslide, delete and then reinitialize the jTinder event.
function addcard(){
    $.getJSON("example.json",function(data){
        //assign the data
        var elem="<li>"+data+"</li>";
        //delete existing jTinder event
        $("#tinderslide").data('plugin_jTinder').destroy();
        //reinitialize new jTinder event
        $("#tinderslide").jTinder({
            onDislike:function(){
                doSomething();
            }
            onLike:function(){
                doSomethingElse();
            }
        });
    });
}

And call addcard() whenever you need to add a new card.


Q: How to debug django web application using specific port & localhost in visual studio code? I want to debug django web application using visual code for that I have found solution that I have to edit launch.json for debugging django web application.
launch.json
"name": "Python: Django",
            "type": "python",
            "request": "launch",
            "program": "${workspaceFolder}\\web_app_test\\manage.py",
            "port": "8005",
            "address" : "192.168.1.195",

I have implemented above code in launch.json but still I am not able to start my web application on above port it automatically running on default port & localhost.

A: Have you tried using 0.0.0.0? that will map it to your local IP, and you will be able to access it within your network if you know your IP.

A: Yes I am able to debug it finally using below code after lots of search on google.
we have to define them into args using ipaddress & port.
"args": [
                "runserver",
                "--noreload",
                "192.168.1.195:8005",
            ],


Q: Connecting Hyperledger Composer to Fabric: Error trying install composer runtime While following the tutorial on this link, I encontered the following error under the section "Deploy to the running Hyperledger Fabric". My Hyperledger Fabric is not running and I do not know why. The error I get is shown below:
tom@tom:~/hyperledger/my-network/dist$ composer network deploy -a my-network.bna -p hlfv1 -i PeerAdmin -s randomString
Deploying business network from archive: my-network.bna
Business network definition:
    Identifier: my-network@0.1.6
    Description: My Commodity Trading network

✖ Deploying business network definition. This may take a minute...

Error: Error trying deploy. Error: Error trying install composer runtime. Error: Connect Failed
Command failed

When I use docker ps -a, no hyperledger containers are shown to have run. Where could I have gone wrong?

A: I just realized I needed to install docker-compose which deals with running multiple docker containers instead of just using docker client.
For docker-compose installation, I consulted the manual

A: I think you did not start your fabric, if you are developing locally. Please look at https://hyperledger.github.io/composer/installing/development-tools.html for the environment setup and the scripts you need to run inorder to have a local fabric.
When you run docker ps you should see something like this docker list of containers


Q: Get id of element on button and auto click using jquery I need to autosubmit a single button on a page that may have a selection of multiple buttons. The challenge is that the buttons do not have a name or ID reference, and rather, each input element uses a "tabindex=n" ID. The quick and easy would have been to add a unique Name or ID to the form, but we do not have access to the server side code so it must all be done client side.
I've tried various approaches but none seem to help so here's the form code...

    Node..

    Node2...

    Node3...

A: if you want to autosubmit say button 2 then you would want to use following selector:
$('div[tabindex=2]').click();

try around here:
http://jsfiddle.net/85h3gtnj/1/
actually to make sure you hit no other divs you should add the class selector
$('div.dp[tabindex=2]').click();

as fiddled here:
http://jsfiddle.net/85h3gtnj/3/

A: If the tabindex is the attribute that is set reliably on the page, you can use that to call the click() event:
$.each('div', function() {
    if ($(this).attr('tablindex') == 4) {
        $(this).click(); //makes it submit
    }
});

you can also call the div using the nth-child selector:
$('#container div:nth-child(4)').click();

Info on nth-child can be found here: https://api.jquery.com/nth-child-selector/
Hope that helps!

A: is that what u need? FIddle: https://jsfiddle.net/288er5td/
CODE:

            <input data-input-field='' type='text' val ='val1' />
    Node..

      <input data-input-field='' type='text' val ='val2' />
    Node2...

            <input data-input-field='' type='text' val ='val3' />
    Node3...

$(document).ready(function(){
    t = function(elem){
        var $this = elem;
        var $tab = $this.closest('.dp');
        var tabindex = $tab.attr('tabindex');
        var i_val = $this.val();
        alert(tabindex);
        alert(i_val);
    }
    $(document).on('click', '[data-input-field]', function(){
        t($(this));

    });
    $(document).on('keypress', '[data-input-field]', function(event){
        if ((event.keyCode == 32) || (event.keyCode == 13)){
            t($(this));
        }
    });
});


Q: Remove duplicate lines with 1 command There is any Linux command that deletes duplicates of lines in a file but not the first appearance of the line that is duplicate.
For example, we have a file that has the following lines:
Test Line
Another line
Test
4th line
Test
Test Line

And I want after I run the command, the lines that should remain in the file are:
Test Line
Another Line
Test
4th line


Q: PPT Text x,y,width,height - openxml I tried following this Presentation ML inheritance chain:
Slide <-- SlideLayout <-- SlideMaster <-- default styles in SlideMaster
to obtain x,y,width,height properties of text content in a PPT Slide but I am not sure whether I am getting correct value. Can you please tell if I am doing the right thing ? Can you also please tell me how to uniquely identify this text object in Slide, SlideLayout & SlideMaster ?
-Thank you

A: Refer to the following Answer to determine the Height and Width of Text properties.
For determining if you have the right text, Enter unique text into your slide and use the Open XML Productivity Tool to find it.  You can use the tool to search for your unique string in your slide and reflect the code to generate it.
Lastly, to understand the Presentation Slide XML, I recommend reading the free e-book Open XML Explained to give an explanation of how a correct Presentation document is formed to help you better understand where things should be.

A: If you have powerpoint installed from Microsoft office. You can do the following, though this is not programmatic, but can help you to get the job done.
Steps:

*

*Open ppt

*Click on your chart or whatever object you like.

*Right click and select or use shortcut CMD + SHIFT + 1

*Click on 3rd icons select Size Position, and you can see the following

Note:
I'm demoing with Microsoft Powerpoint for Mac Version 2018.
Hope it helps.


Q: Vuetify v-chip in v-data-table array I am new to vuetify, and I would like to know how to make a v-chip to a specific value in my table.
example :
<v-data-table
    class="page__table"
    :headers="headers"
    :items="references"
  >
  <v-chip
  v-for="reference in references"
  :key="reference.id"
  :color="color"
  > {{reference.department}}
  </v-chip>

and my code (composition api)
const mappedCatalog: ComputedRef<Record<string, any>> = computed(() => catalogStore.fullCatalog.map(reference => {
      return {
        ...reference,
        departments: reference.departments
return {
      references: ref(mappedCatalog),

can you help me please

A: Check this codesanbox I made: https://codesandbox.io/s/stack-71649799-v-chip-data-table-item-slow-z7p2db?file=/src/components/Example.vue
You can use the item slot of the data table. Some vuetify components comes with special sections for easier customization called slots, in this case the item slot of the data table let you customize individual colums content like this:
<v-data-table
    :headers="headers"
    :items="desserts"
    :items-per-page="5"
    class="elevation-1"
>
    <template #item.calories="{ item }">
        <v-chip dark color="red darken-2">{{ item.calories }}</v-chip>
    </template>
    <template #item.fat="{ item }">
        <v-chip dark color="orange darken-2">{{ item.fat }}</v-chip>
    </template>
</v-data-table>

If you're using es-lint you might encounter a warning mention something about the valid-v-slot rule, this is a known false positive that you can read more about in this GitHub issue thread, I personally just turn that es-lint rule off.
For more info about data table slots, check the vuetify documentation page.


Q: How to get different count of key php array to table and $array[1] = array("Name1"=> array("2"=>"1460","3"=>"1868","4"=>"2158","5"=>"2537","6"=>"2915","8"=>"3673"));
$array[2] = array("Prod2"=> array("3"=>"3079","4"=>"3625","5"=>"4172","6"=>"4718","8"=>"5811"));
$cnt = 0;
for ($x = 0; $x < 100; $x++) {
    $product = $array[$x]; // dynamic all product`s - $name
    foreach ($product as $good =>$massiv) {
        $name = key($product);      // prod name
        $proklkadok = array_keys($massiv);  // prod prokladok
        foreach ($massiv as $inner_key =>$price) {
            echo "
". $name. "	";
            $pr_val = array_keys($massiv);
            echo "".$pr_val[0]. "	";
            echo "".$price."
\r\n"; // product price
        }
    }
}

how to print $pr_val unique in table td cell ?
This code is wrong, bad table prints the output:
Name1   2   1138    or wrong output too ...   Name1  2,3,4,5,6,8    1138
Name1   2   1868    or wrong output too ...   Name1  2,3,4,5,6,8    1868
Name1   2   2158    or wrong output too ...   Name1  2,3,4,5,6,8    2158
Prod2   3   3079    or wrong output too ...   Prod2  2,3,4,5,6,8    3079
Prod2   3   3625    or wrong output too ...   Prod2  2,3,4,5,6,8    3625
Prod2   3   4718    or wrong output too ...   Prod2  2,3,4,5,6,8    4718
Prod2   3   5811    or wrong output too ...   Prod2  2,3,4,5,6,8    5811

Correct output must be in HTML TABLE
Name1   2   1138
Name1   3   1868
Name1   4   2158
Name1   5   2537
Name1   6   2915
Name1   8   3673

Prod2   3   3079
Prod2   4   3079
Prod2   5   3625
Prod2   6   4718
Prod2   8   5811

pls help me, I can't count and output different count of array keys in the table output

A: The bug is at
$pr_val = array_keys($massiv);
echo "".$pr_val[0]. "	";

array_key($massiv) returns all keys of massiv and $pr_val[0]always returns the first of them (which happens to be the smallest of them).
Try
foreach($product as $good =>$massiv) {

    foreach($massiv as $inner_key =>$price) {
        echo "
". $good. "	";

        echo "".$inner_key. "	";
        echo "".$price."
\r\n"; // product price
    }
}

That should output exactly what you desire.

A: This code will output what you desire as the correct output in an HTML table
$array[1]=array("Name1"=> array("2"=>"1460","3"=>"1868","4"=>"2158","5"=>"2537","6"=>"2915","8"=>"3673"));
$array[2] =array("Prod2"=> array("3"=>"3079","4"=>"3625","5"=>"4172","6"=>"4718","8"=>"5811"));
echo "
" . PHP_EOL;
foreach($array as $product) {
    foreach($product as $name =>$massiv) {
        foreach($massiv as $inner_key => $price) {
            echo "
". $name. "	";
            echo "".$inner_key. "	";
            echo "".$price."
" . PHP_EOL; // product price
        }
    }
}
echo "
" . PHP_EOL;

A: $array = array();
$array[0] = array("Name1"=> array("2"=>"1460","3"=>"1868","4"=>"2158","5"=>"2537","6"=>"2915","8"=>"3673"));
$array[1] = array("Prod2"=> array("3"=>"3079","4"=>"3625","5"=>"4172","6"=>"4718","8"=>"5811"));
echo '
';
foreach($array as $v) {
    foreach($v as $name => $ar) {
        foreach($ar as $v1 => $v2) {
            echo sprintf('
%s	%s	%s
'."\r\n",
                $name, $v1, $v2);
        }
    }
}
echo '
';

by Prizma


Q: BootStrap Modal: Multiple modal open, and when last modal cancelled it hangs the page Sorry I don't get this but I have 2 modals

@lang('pagetexts.client_view_models.upload_file')

                <button type="button" id="closeUploadModal" class="close" data-target="#uploadFileModal" data-dismiss="modal" aria-label="Close"> × </button>

                        <form action="/initial-document-upload" class="dropzone" id="dropzoneUpload" method="POST" enctype="multipart/form-data">
                            @csrf
                            <input type="hidden" value="{{$client_data->id}}" id="clientid" name="clientid"/>
                        </form>

 @lang('pagetexts.client_view_models.file_accept_are')

                <button type="button" id="can-upl-btn" data-target="#uploadFileModal1" data-dismiss="modal" class="btn btn-secondary">@lang('pagetexts.client_view_models.cancel')</button>

Modal 2

@lang('pagetexts.client_view_models.upload_file')

                <button type="button" class="close" data-dismiss="modal" aria-label="Close"> × </button>

                            @lang('pagetexts.client_view_models.document_title')
                            <input type="text" class="form-control" id="Titlex" value="">

                            @lang('pagetexts.client_view_models.notes')
                            <textarea class="form-control" id="Notesx" rows="3"></textarea>

                        @lang('pagetexts.client_view_models.apply_tags')

                            <input type="checkbox" class="custom-control-input" id="customCheck1x">
                            @lang('pagetexts.client_view_models.share_with_client')

                <input type="hidden" value="" id=documentid" name="documentid"/>
                <button type="button" id="can-file-upd" data-target="#uploadFileModal2" data-dismiss="modal" class="btn btn-secondary" >@lang('pagetexts.client_view_models.cancel')</button>
                <button type="button" class="btn btn-primary">@lang('pagetexts.client_view_models.save_changes')</button>

The action is when the first modal successfully uploads a file it should open modal 2 , and then should submit the form to update the details for the upload in the 1st one. This is how I trigger the transition
this.on('success', function(event, response) {
                    $('#uploadFileModal').modal('hide');
                    $('#uploadFileModal2').modal('show');
                })

When I submit the modal 2 to the form it successfully updates the data, HOWEVER, when I cancel MODAL 2, nothing in the page is usable, I can't click anywhere, any idea as to why ?

A: Multiple open modals are not supported by Bootstrap. You have to remember that .modal() is asynchronous, so the next .modal() is going to run before the previous completes. So, you probably have an overlay covering your page, even though the styles it's given prevent you from seeing it.
This might work:
this.on('success', function(event, response) {

    $('#uploadFileModal')
        .on('hidden.bs.modal', function(){
            $('#uploadFileModal2').modal('show');
        })
        .modal('hide');
});

This will delay the second modal from being triggered until the first modal has completed it's hide transition.


Q: WARN Test results in Robot Framework I have multiple test cases that need to be tested. With every release, I get some new test cases as well as some old ones.
My problem is for old test cases which are failed I have already created a problem ticket in JIRA and in the next release this ticket number is added in [Documentation] Field of the .robot
Now what I want is next time on a new release if the bug is already raised in Jira meaning the documentation section of the robot will contain the ticket number, If the test fails I will label it as WARN in Yellow instead of marking it as Failure.
I have searched a lot and found this thread but according to it I can't do it- Github Issue is there any other way?

A: You will need to process the Documentation of the test to see if it has a JIRA issue number, if so, then add a Tag (for example TagName) to it. When launching tests with robotframework version 4.0, you call them by passing the option --skiponfailure TagName. You will have those tests marked as SKIPPED.
The parsing of Documentation would be needed to parse before running the actual tests (in a helper test run).


Q: Milliseconds to HH:MM:SS time format I'm trying to add the timestamp of a video frame to its own frame name like "frame2 00:00:01:05", using CAP_PROP_POS_MSEC I'm getting the current position of the video file in milliseconds, what I want is to change those milliseconds to the time format "00:00:00:00:".
My code currently assigns the name like: "frame2 1.05" but ideally I would have the name like: "frame2 00:00:01:05".
Is there a library that can help me achieve this milliseconds to HH:MM:SS conversion?
import cv2
vidcap = cv2.VideoCapture('video.mp4')
success,frame = vidcap.read()
cont = 0
while success:
  frame_timestamp = (vidcap.get(cv2.CAP_PROP_POS_MSEC))/(1000)
  cv2.imwrite(f'frame{cont} '+str((format(frame_timestamp,'.2f')))+'.jpg',frame)
  success,frame = vidcap.read()
  cont+=1

Thanks!

A: Just use divmod. It does a division and modulo at the same time. It's more convenient than doing that separately.
seconds = 1.05 # or whatever

(hours, seconds) = divmod(seconds, 3600)
(minutes, seconds) = divmod(seconds, 60)

formatted = f"{hours:02.0f}:{minutes:02.0f}:{seconds:05.2f}"

# >>> formatted
# '00:00:01.05'

And if you need the fraction of seconds to be separated by :, which nobody will understand, you can use (seconds, fraction) = divmod(seconds, 1) and multiply fraction * 100 to get hundredth of a second.


Q: grouping foreign objects (javascript merge) I'm writing a small userscript to recieve an object from a xhr request and send parts of it to another website. The recieved json looks like this
{"result": [
{"id":"1234","title":"Gartenzwerg","description":"Strom unter Kunst","lat":153.558356,"lng":50.205637,"city":"Citü","state":"XY","day":"1970-01-01","order":0,"imageUrl":"https://cool.page","nextUpgrade":false,"upgraded":false,"status":"WITHDRAWN"},
{"id":"56789","title":"Weizenähre","description":"Strom unter Kunst","lat":153.590972,"lng":50.235216,"city":"Citü","state":"XY","day":"1971-01-01","order":1,"imageUrl":"https://cooler.page","nextUpgrade":true,"upgraded":true,"status":"NOMINATED"},
{...}],
"message":null,
"code":"OK",
"errorsWithIcon":null,
"fieldErrors":null,
"errorDetails":null,
"version":"4.0.10",
"captcha":false}

I use Add a "hook" to all AJAX requests on a page to get the informations and then send each result-part by it's own to my page with a fetch-function
    var data = JSON.parse(this.responseText).result;
    for (let i=0; i<Object.keys(data).length; i++) {
        sendDataToPage(data[Object.keys(data)[i]]);
        await sleep(500);
    }

Now it's very ineffective to send each by it's own, so i'd like to groupe f.e. 10 elements before I send them.  With Object.assign I only get the last element. Do I have to use another function to merge or how do I use it the right way?


Q: Remove line number option from grep I use an alias for grep, that adds line numbers to the output:
alias grep="grep -n -I --color"

For a certain command I'd like to remove the -n from the grep command. I could not find a "Do not add line numbers"-flag. Is something like this available or do I have to add an extra alias without linenumbers?

A: Just use a backslash, as it will revert to the default grep command and not your alias:
\grep -I --color

A: You could use command to remove all arguments.
command grep -I --color

A: I realize this is an older question, but I've been running up against the same problem. This solution works, but isn't the most elegant:
# Not part of your original question, but I learned that if an alias
# contains a trailing space, it will use alias expansion. For the case
# of 'xargs', it allows you to use the below grep aliases, such as the
# 'chgrep' alias defined below:
#   grep -l 'something' file1 file2 ... | xargs chgrep 'something else'
alias xargs='xargs '

export GREP_OPT='-n'
# Note the $(...) INSIDE the 'single quotes'
alias grep_='\grep --color=auto -I $(echo "$GREP_OPT")'
# Due to alias expansion, the below aliases benefit from the 'GREP_OPT' value:
alias cgrep='grep_ -r --include=\*.{c,cc,cpp}'
alias hgrep='grep_ -r --include=\*.{h,hh,hpp}'
alias chgrep=cgrep_ --include=\*.{h,hh,hpp}' # Not sure if there's a way to combine cgrep+hgrep
...
alias pygrep='grep_ -r --include=\*.py'

In the situations where you want a non-numbered output, unset GREP_OPT (or remove -n from it, like if you're using it to include other flags).
I've used grep_ instead of grep in the above example just to show that aliases will happily chain/use alias expansion as needed all the way back to the original command. Feel free to name them grep instead. You'll note that the original grep_ uses the command \grep so the alias expansion stops at that point.
I'm totally open to suggestions if there is a better way of doing this (since setting/unsetting the GREP_OPT isn't always the most elegant).


Q: When are ready the new feature "cards" in the API? Youtube has a new feature called "Cards", but i can't find information in the API about of this, i need to know when are ready to be able to be used like programmer, thanks!


Q: How to Backup a Meteor Mongo Database? To create a backup of my mongo database, I am trying mongodump from my meteor console. The command successfully completes, but creates an empty folder under the dump folder. I use the command
mongodump -h 127.0.0.1 --port 3001 -d meteor

So basically I am trying to backup my database for reactionecommerce.  My question is how to backup a meteor mongodb that is running locally? Thanks for any guidance of help.

A: The issue was with the mongo version 2.6.10. I installed the latest 3.4.4 in my Ubuntu 64 machine following the instructions https://docs.mongodb.com/master/tutorial/install-mongodb-on-ubuntu/  Now I am able to dump the data without any problem.


Q: Overwrite postgresql onupdate with sqlalchemy Original problem
I'm using sqlalchemy in our project. I registered few event listeners for my model like so.
@event.listens_for(Post, 'after_update')
@event.listens_for(Post, 'after_insert')

Somewhere else in the code I update the view_counter property of my model.
post.view_counter += 1
DBSession.flush()

Now, since view_counter is not something I regard as content update, I want to supress firing of after_update event in sqlalchemy for this specific update. Is there a way to do it via ORM or is the only way to just do raw SQL update bypassing ORM entirely?
EDIT
After some poking around I realized there is another problem, the property is set by Postgresql itself
date_last_updated = Column(SA_DateTime, default=DateTime.now, onupdate=DateTime.now, nullable=False, index=True)

Problem
So the question is, how to update a sqlalchemy model without triggering Postgresql update.

A: If you're able to make changes to the decorated function, it should be possible to use the passed arguments to determine which fields were modified, albeit through a little bit of a workaround. I'm afraid I haven't been able to test this yet, but I hope it helps!
@event.listens_for(Post, 'after_update', raw=True)
@event.listens_for(Post, 'after_insert', raw=True)
def myfunc(mapper, connection, target):
    # Values have been modified
    if target.session.is_modified(target, include_collections=False):
        # view_counter is the only modified value, the hook can be aborted
        if set(target.dict.keys()) - target.unmodified == {'view_counter'}:
            return
    <...the rest of the function...>


Q: Test rig exited abnormally with code 134 with OCMock verify on iOS 4 I'm trying to add OCMock to my iOS 4 project. To test it out, I have a class Person with one method, -hello. When I run this test:
- (void) testMock {
    id mock = [OCMockObject mockForClass:[Person class]];
    [[mock expect] hello];

    [mock hello];

    [mock verify];
}

Everything is fine, and the build succeeds. If I take away the hello call, like this:
- (void) testMock {
    id mock = [OCMockObject mockForClass:[Person class]];
    [[mock expect] hello];

    [mock verify];
}

I'd expect to get an error message telling me that my expected method wasn't called on the mock. Instead I get a cryptic message about the test rig crashing:
/Developer/Tools/RunPlatformUnitTests.include:451:0 Test rig '/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.0.sdk/Developer/usr/bin/otest' exited abnormally with code 134 (it may have crashed).

Is this crash normal when an expected method isn't called? Do I have a bad configuration?

A: You don't have a bad configuration, it's a bug that Apple introduced in the simulator SDK when they released iOS4.  Basically, if code invoked using an NSInvocation object throws an exception, then that exception is uncatchable.  I wrote about the issue when it first appeared here:
http://pivotallabs.com/users/adam/blog/articles/1302-objective-c-exceptions-thrown-inside-methods-invoked-via-nsinvocation-are-uncatchable
Unfortunately, this bug affects OCMock and Apple hasn't show much interest in fixing it.  Many people have filed bug reports, but to no avail.
I realize this is little comfort, but you will get slightly better error messages when using Cedar for testing (I believe the same is true for GTM).

A: I'd say it's a bug. Verify should report a useable result, even if it fails.

A: I have found that this bug is still around with Xcode 4/SDK 4.3 in April of 2011.  For example, Test A passes, Test B crashes the test rig.
Test A:
- (void)testAcceptsAndVerifiesExpectedMethods
{

    id mock = [OCMockObject mockForClass:[NSString class]];

    [[mock expect] lowercaseString];
    [mock lowercaseString];

    [mock verify];
}

Test B:
- (void)testAcceptsAndVerifiesExpectedMethods
{

    id mock = [OCMockObject mockForClass:[NSString class]];

    [[mock expect] lowercaseString];
    //[mock lowercaseString];

    [mock verify];
}

A: A workaround I've found is to wrap the [mockObject expect] and [mockObject verify] calls with XCTAssertNoThrow, e.g.:
XCTAssertNoThrow([[mockTaskVC expect] showAlertWithTitle:containsString(@"Error") message:OCMOCK_ANY completion:OCMOCK_ANY], @"threw up exception");

This will catch the exception and fail the text rather than crashing.
Credit to author here: http://www.mulle-kybernetik.com/forum/viewtopic.php?f=4&t=315&p=710&hilit=unexpected+method+was+not+invoked+exception#p710


Q: Limiting resultset from Magento SOAP query How can you specify a max result set for Magento SOAP queries?
I am querying Magento via SOAP API for a list of orders matching a given status. We have some remote hosts who are taking too long to return the list so I'd like to limit the result set however I don't see a parameter for this.
$orderListRaw = $proxy -> call ( $sessionId, 'sales_order.list', array ( array ( 'status' => array ( 'in' => $orderstatusarray ) ) ) );

I was able to see that we do get data back (6 minutes later) and have been able to deal with timeouts, etc. but would prefer to just force a max result set.

A: It doesn't seem like it can be done using limit, (plus you would have to do some complex pagination logic to get all records, because you would need know the total number of records and the api does not have a method for that) See api call list @ http://www.magentocommerce.com/api/soap/sales/salesOrder/sales_order.list.html
But what you could do as a work around is use complex filters, to limit the result set base on creation date. (adjust to ever hour, day or week base on order volume).
Also, since you are using status type (assuming that you are excluding more that just cancel order), you may want to think about getting all order and keep track of the order_id/status locally (only process the ones with the above status) and the remainder that wasn't proceed would be a list of order id that may need your attention later on
Pseudo Code Example
$params = array(array(
        'filter' => array(
            array(
                'key' => 'status',
                'value' => array(
                    'key' => 'in',
                    'value' => $orderstatusarray,
                ),
            ),
        ),
        'complex_filter' => array(
            array(
                'key' => 'created_at',
                'value' => array(
                    'key' => 'gteq',
                    'value' => '2012-11-25 12:00:00'
                ),
            ),
            array(
                'key' => 'created_at',
                'value' => array(
                    'key' => 'lteq',
                    'value' => '2012-11-26 11:59:59'
                ),
            ),
        )
    ));

    $orderListRaw = $proxy -> call ( $sessionId, 'sales_order.list', $params);

Read more about filtering @ http://www.magentocommerce.com/knowledge-base/entry/magento-for-dev-part-8-varien-data-collections


Q: Numpy hybrid type Matrix astype I'm trying to cast a numpy matrix that I have already defined:
    matrix = numpy.array([['name','23','45','1'],
                         ['name2','223','43','5'],
                         ['name3','12','33','2']])

resulting in this:
array([['name1', '23', '45', '1'],
       ['name2', '223', '43', '5'],
       ['name3', '12', '33', '2']],
      dtype='|S5')

I would like to name and cast each column of my matrix to the following types:
dt = numpy.dtype({'names':['name','x','y','n'],'formats': ['S10', 'S10', 'S10', 'S10']})

For now, I will consider matrix all strings because it doesn't work, but what was expected a format like this 'formats': ['S10', 'f3', 'f3', 'i']
and do something like this:
matrix.astype(dtype=dt,casting='safe')

Result:
array([[('name', 'name', 'name', 'name'), ('23', '23', '23', '23'),
        ('45', '45', '45', '45'), ('1', '1', '1', '1')],
       [('name2', 'name2', 'name2', 'name2'), ('223', '223', '223', '223'),
        ('43', '43', '43', '43'), ('5', '5', '5', '5')],
       [('name3', 'name3', 'name3', 'name3'), ('12', '12', '12', '12'),
        ('33', '33', '33', '33'), ('2', '2', '2', '2')]],
      dtype=[('name', 'S10'), ('x', 'S10'), ('y', 'S10'), ('n', 'S10')])

What am I missing? How can I define types for each matrix columns using numpy module?

A: Creating/filling a structured array is a little tricky.  There are various ways, but I think the simplest to remember is to use a list of tuples:
In [11]: np.array([tuple(row) for row in matrix], dtype=dt)
Out[11]:
array([('name', '23', '45', '1'),
       ('name2', '223', '43', '5'),
       ('name3', '12', '33', '2')],
      dtype=[('name', 'S10'), ('x', 'S10'), ('y', 'S10'), ('n', 'S10')])

The result is 1d array, with the dtype fields replacing the columns of the original 2d array.  Each element of the new array has the same type - as specified by dt.
Or you can create an empty array of the desired dtype, and fill it, row by row or field by field:
In [14]: arr = np.zeros((3,),dt)
In [16]: arr[0]=tuple(matrix[0,:])  # tuple of row
In [17]: arr['name']=matrix[:,0]    # field

In [18]: arr
Out[18]:
array([('name', '23', '45', '1'),
       ('name2', '', '', ''),
       ('name3', '', '', '')],
      dtype=[('name', 'S10'), ('x', 'S10'), ('y', 'S10'), ('n', 'S10')])

With a compatible dt1, view would also work
dt1 = numpy.dtype({'names':['name','x','y','n'],'formats': ['S5', 'S5', 'S5', 'S5']})
matrix.view(dt1)

This doesn't change the data; it just interprets the bytes differently.

converting the strings to numbers is easy with the list of tuples
In [40]: dt2 = numpy.dtype({'names':['name','x','y','n'],'formats': ['S5', 'f', 'f', 'i']})

In [41]: np.array([tuple(row) for row in matrix], dtype=dt2)Out[41]:
array([('name', 23.0, 45.0, 1),
       ('name2', 223.0, 43.0, 5),
       ('name3', 12.0, 33.0, 2)],
      dtype=[('name', 'S5'), ('x', '<f4'), ('y', '<f4'), ('n', '<i4')])


Q: How to find the second lowest value in a tensorflow array I am writing a clustering algorithm and for part of it I calculate a euclidean distance matrix for each cluster of points. (FYI all of this is in Tensorflow). each cluster is a list of 8 dimensional vectors, which I then turn into one M*8 matrix. For each point in each cluster, I want to find the distance between it and its closest neighbor. I believe the most efficient way to do this would be to do compute pairwise distance between points for each cluster, and then find the second smallest value in each row of the resulting M*M matrix (because the smallest value in each row will always be 0, the distance between a given point and itself).
Here is the code I use to create the euclidean distance matrix for each cluster:
    partitionedData = tf.dynamic_partition(inputs, pred, num_classes)
    for partition in partitionedData:
        N = tf.to_int32(partition.get_shape()[0])
        qexpand = tf.expand_dims(partition,1)
        qTexpand = tf.expand_dims(partition,0)
        qtile = tf.tile(qexpand,[1,N,1])
        qTtile = tf.tile(qTexpand,[N,1,1])
        deltaQ = qtile - qTtile
        deltaQ2 = deltaQ*deltaQ
        d2Q = tf.reduce_sum(deltaQ2,2)

The resulting matrix might look something like this (Note: this is a matrix of squares of distances):
[[  0.   8.   2.  18.]
 [  8.   0.  10.   2.]
 [  2.  10.   0.  20.]
 [ 18.   2.  20.   0.]]

for an input matrix of:
[[2,3],[4,5],[1,4],[5,6]]

What I would like to get in the end is the second smallest value in each row, in this case 2,2,2, and 2. Additionally, if there is a better way to find the distance to the nearest neighbor in tensorflow for every point in a cluster that is computationally efficient, that would be extremely helpful.

A: To find k-th element in TF you need tf.nn.top_k. If you need smallest you search not in X, but in -X.
In your case you do not even need it. If your matrix is a distance, the diagonal is always 0 and this screws things up for you. So just create change the diagonal of your matrix with tf.matrix_set_diag, where your diagonal is a vector of size of your X, where each value is tf.reduce_max.
Writing a code for this is trivial.


Q: Agent in JADE behaviour not working I'm trying to create a game where JADE Agents are the 'enemies' and they chase a player around a maze.
So far I have:
MazeView.java (uses Swing to paint various things on the screen, and lets the user interact through button presses)
Enemy.java (a JADE agent that will have behaviours like search, pursue, etc.)
And a few other classes doing things like generating the actual maze data structure etc.
My problem is that, while I can instantiate an Agent and paint it on the screen, for some reason I can't add any behaviours. For example, if I wanted something like this (in Enemy.java):
protected void setup() {
    // Add a TickerBehaviour that does things every 5 seconds
    addBehaviour(new TickerBehaviour(this, 5000) {
        protected void onTick() {
            // This doesn't seem to be happening?
            System.out.println("5 second tick... Start new patrol/do something?");
            myAgent.addBehaviour(new DoThings());
        }
    }); // end of addBehaviour
    System.out.println("End of setup()...");
} // end of setup

When I run the code, no errors are thrown, and I can see "End of setup()..." displayed in console. So for some reason it's just not going into the addBehaviour() method at all. Even if the DoThings() behaviour didn't work (right now it just prints a message), it should at least display the "5 second tick" message before throwing an error. What is going wrong here?
I think it could be something to do with the fact that currently there is no concept of 'time' in my maze. The user presses a key, and THEN processing happens. So having an agent that does things every 5 seconds might not work when there is no real way to facilitate that in the maze? But I'm still confused as to why it just skips addBehaviour() and I don't get an error.
A possible solution might be to re-implement my maze as a constant loop that waits for input. Would that allow a concept of 'time'? Basically I'm not sure how to link the two together. I am a complete beginner with JADE.
Any ideas would be appreciated. Thanks!

A: I've never used Jade, but my first thought was that you are adding behaviors and then assuming that Jade will decide to run them at some point. When you say that you never see your behaviors activate, it strengthened that hypothesis.
I looked at the source and sure enough, addBehaviour() and removeBehaviour() simply add and remove from a collection called myScheduler. Looking at the usages, I found a private method called activateAllBehaviours() that looked like it ran the Behaviours. That method is called from the public doWake() on the Agent class.
I would guess that you simply have to call doWake() on your Agent. This is not very apparent from the JavaDoc or the examples. The examples assume that you use the jade.Boot class and simply pass the class name of your agent to that Boot class. This results in the Agent getting added to a container that manages the "waking" and running of your Agents. Since you are running Swing for your GUI, I think that you will have to run your Agents manually, rather than the way that the examples show.

I got more curious, so I wrote my own code to create and run the Jade container. This worked for me:
Properties containerProps = new jade.util.leap.Properties();
containerProps.setProperty(Profile.AGENTS, "annoyer:myTest.MyAgent");

Profile containerProfile = new ProfileImpl(containerProps);

Runtime.instance().setCloseVM(false);
Runtime.instance().createMainContainer(containerProfile);

This automatically creates my agent of type myTest.MyAgent and starts running it. I implemented it similar to your code snippet, and I saw messages every 5 seconds.
I think you'll want to use setCloseVM(false) since your UI can handle closing down the JVM, not the Jade container.


Q: PHP Laravel are DB function results cached? Noob question. I'm working on a project which involves interacting with some legacy software and the database is not compatible with regular Laravel Relationships.
If I'm defining things in a constructor like this:
public function __construct(array $attributes = array())
{
parent::__construct($attributes);

$this->vatpercentage = $this->customer()->vatpercentage;
$this->vatcode = $this->customer()->vatcode;
$this->partrevision = $this->part()->revision;
$this->unitprice = $this->part()->unitprice;
}

public function part(){
    return Part::findOrFail($this->partnum);
}

public function customer(){
    $traderid = Order::where('id', $this->orderid)->value('traderid');
    return Customer::where('id', $traderid)->where('tradertype', 'C')->first();
}

I need to reference customer(), part() and other similar functions many times in the constructor. Is the DB getting queried every time I reference $this->customer(), etc or is the result cached the first time I reference it and then used for all the other times following? Basically am I doing a lot of unnecessary DB calls by coding in this way rather than setting $this->customer = $this->customer() and grabbing the values like $this->customer->example?

A: No database query or method call is going to be cached automatically in your application, nor should it.  Laravel and PHP aren't going to know how you want to use queries or methods.
Everytime you call customer(), you're building up and executing a new query.  You could easily cache the result in a property if that's what you want, but you'd have watch the value of the $orderid property:
protected $customerCache;

public function customer()
{
    if ($customerCache) return $customerCache;

    $traderid = Order::where('id', $this->orderid)->value('traderid');
    return $customerCache = Customer::where('id', $traderid)->where('tradertype', 'C')->first();
}

You're also performing too much in your constructor.  I would highly recommend not performing queries in any constructors, constructors should be used to pass dependencies.  The way you have it designed would make it very hard to unit test.

A: In Laravel 4.* there was a remember() method handling the cache in queries. It was removed from 5.1 with a valid reason that it's not the responsibility of Eloquent neither the query Builder to handle cache. A very very simplified version of a decorator class that could handle the caching of your queries:
final class CacheableQueryDecorator
{
    private $remember = 60; //time in minutes, switch to load from config or add a setter
    private $query = null;

    public function __construct(Builder $builder)
    {
        $this->query = $builder;
    }

    private function getCacheKey(string $prefix = ''):string
    {
        return md5($prefix . $this->query->toSql() . implode(',', $this->query->getBindings()));
    }

    public function __call($name, $arguments)
    {
        $cache = Cache::get($this->getCacheKey($name), null);
        if ($cache) {
            return $cache;
        }
        $res = call_user_func_array([$this->query, $name], $arguments);
        Cache::put($this->getCacheKey($name), $res, $this->remember);
        return $res;
    }
}

Using it:
$results = (new CacheableQueryDecorator($query))->get()


Q: QT4 get base char without diacritics I am trying to create an index from a list of QString, getting the first char for each word in the list. I would like to remove all diacritics from this first char, fe: á -> a, ü -> u, 木 -> 木. I mean, the index for abeja, ala, árbol should be the same: 'a'.
EDIT:
I have found the QString normalized ( NormalizationForm mode ) const method:
QString s = "á";
QString sWithoutDiacritic = s.normalized(QString::NormalizationForm_D).at(0);

Maybe this will do the trick, I'll try later.

A: Collation (sorting order according to natural language) might be what you're looking for
The ICU Library provides such:
http://userguide.icu-project.org/collation/api


Q: How to add class to block under position: sticky I have a block with position: sticky and a block under it. Is there any way to track the moment when the sticky block sticks to the top and add a class to the bottom block?

I think I should use $(window).scroll() but don't know how.

A: There is no "official" way of telling an element is being stuck with sticky positioning as I know of right now. But you could use a IntersectionObserver.
It works by observing changes in an elements position related for example to a viewport, in the case of this code sample it checks for at least a 1px difference (threshold: 1).
const el = document.querySelector(".stickyElement")
const observer = new IntersectionObserver(
  ([e]) => document.querySelector(".elementThatShouldUpdate").classList.toggle("desired-class", e.intersectionRatio < 1),
  { threshold: [1] }
);

observer.observe(el);

You should also update your CSS for the sticky element to account for the 1px difference:
top: -1px;

And also account for this extra offset, so you should add either a border or a padding to this element:
padding-top: 1px;

Let me know if this helps.


Q: ChoiceBox with custom Item in a TableView I have a
private TableView<Indicators> tableviewIndicators;

with column
private TableColumn<Indicators, WindowsItem> tablecolumnFrame;

public static class WindowsItem {

    CustomInternalWindow chrt;

    private WindowsItem(CustomInternalWindow _chrt) {
        chrt = _chrt;
    }

    public String toString() {
        return chrt.getTitle();
    }

}

private Indicators(String tl, WindowsItem chrt, String pne, Boolean sel) {
        this.tool_col = new SimpleStringProperty(tl);
        if (chrt == null) {
            this.chart_col = new SimpleStringProperty("");
        } else {
            this.chart_col = new SimpleStringProperty(chrt.toString());
        }
        this.pane_col = new SimpleStringProperty(pne);
        this.on_col = new SimpleBooleanProperty(sel);
        this.chrt   = chrt;

    }

    public String getTool() {
        return tool_col.get();
    }

    public void setTool(String tl) {
        tool_col.set(tl);
    }

    public WindowsItem getChart() {
        return chrt;
    }

    public void setChart(WindowsItem _chrt) {
        System.out.println("Indicators::setChart "+chrt.toString());
        chrt = _chrt;
    }

    public String getPane() {
        return pane_col.get();
    }

    public void setPane(String pne) {
        pane_col.set(pne);
    }

    public Boolean getOn() {
        return on_col.get();
    }

    public void setOn(boolean sel) {
        on_col.set(sel);
    }

    public SimpleBooleanProperty onProperty() {
        return on_col;
    }

    public SimpleStringProperty toolProperty() {
        return tool_col;
    }

    public SimpleStringProperty chartProperty() {
        return chart_col;
    }

    public SimpleStringProperty paneProperty() {
        return pane_col;
    }
}
tablecolumnFrame.setCellValueFactory(new PropertyValueFactory<Indicators, WindowsItem>("chart"));

How can I add a combobox or choicebox in tablecolumnFrame?
The following code
tablecolumnFrame.setCellFactory(new Callback<TableColumn<Indicators, WindowsItem>, TableCell<Indicators, WindowsItem>>() {
        @Override
        public TableCell<Indicators, WindowsItem> call(TableColumn<Indicators, WindowsItem> param) {
            TableCell<Indicators, WindowsItem> cell = new TableCell<Indicators, WindowsItem>() {
                @Override
                public void updateItem(WindowsItem item, boolean empty) {
                    super.updateItem(item, empty);
                    if(empty){
                        return;
                    }

                    if (item != null) {
                        //final ChoiceBox<WindowsItem> choice = new ChoiceBox<>();
                        final ComboBox<WindowsItem> choice = new ComboBox<>();
                        int itemsInTab = chartsInTab.getChildren().size();// dimensione del contenuto del tab, compreso il pane
                        CustomInternalWindow winItem;
                        //
                        for (int i = 0; i < itemsInTab; i++) {
                            if (chartsInTab.getChildren().get(i) instanceof CustomInternalWindow) {
                                winItem = (CustomInternalWindow) chartsInTab.getChildren().get(i);
                                choice.getItems().add(new WindowsItem(winItem));
                                //choice.getItems().add(winItem.toString());
                                System.out.println("winItem.toString() "+winItem.toString());
                            }
                        }

return this error
SEVERE: javafx.scene.control.Control loadSkinClass Failed to load skin 'StringProperty [bean: TableRow[id=null, styleClass=cell indexed-cell table-row-cell], name: skinClassName, value: com.sun.javafx.scene.control.skin.TableRowSkin]' for control TableRow[id=null, styleClass=cell indexed-cell table-row-cell]

A: Why do you need special property? You can create ListView with ComboBox quite easily:
    ObservableList<WindowsItem> windowsItems = FXCollections.observableArrayList();
    ObservableList<WindowsItem> data = FXCollections.observableArrayList();

    final ListView<WindowsItem> listView = new ListView<>(data);
    listView.setEditable(true);

    listView.setItems(data);
    listView.setCellFactory(ComboBoxListCell.forListView(windowsItems));


Q: how to determine if variable is undefined in another question on SO, I was determining how to toggle off a function, and the working solution is this:
I place var disabledFlag = true; in the head section of my page and before calling shell.js, then in shell.js I have:
/*******************************/
/*  TOGGLE BUTTON
/*******************************/
var toggleBlock = function() {
    console.log(disabledFlag);
    if(!disabledFlag){
      var windowsize = $(window).width(),
      isDesktop = windowsize > 765;
      $("#quicksearch").toggleClass("collapse in", isDesktop);
      $("#quicksearch").toggleClass("collapse out", !isDesktop);
      $("#sidebar").toggleClass("collapse in", isDesktop);
      $("#sidebar").toggleClass("collapse out", !isDesktop);
    }
    else {
      $("#quicksearch").addClass("collapse out");
      $("#sidebar").addClass("collapse out");
    }
}
$(document).ready(toggleBlock);
$(window).on("resize.showContent", toggleBlock);
toggleBlock();

shell.js is an common file that is shared with other sites and may not have the variable defined. how do I check if the variable is defined, and if not assign it to false and then execute the code above?

A: try
if (typeof disabledFlag === 'undefined')
    disabledFlag = false;

A: There are easier ways to do it than using ternaries or if else statements.
As far as your specific function goes, you could do something like this:
var toggleBlock = function() {
    var disabledFlag = disabledFlag||false;

    if(!disabledFlag){
    //etc.

undefined is falsy, so it works with the logical || operator.  That || operator makes the new var disabledFlag be set to disabledFlag (if it exists), and if not, it will set the var to false
This same concept is used in many different contexts.  For example:
Situation 1 -
var obj = {hello: 'world'};

function fn(object) {
    var object = object || {foo: 'bar'};

    return object;
}

fn(obj)  //  ==> {hello: 'world'}

Situation 2 -
function fn(object) {
    var object = object || {foo: 'bar'};

    return object;
}

fn(objectThatDoesntExist); //  ==> {foo: 'bar'}

In JavaScript libraries and module-pattern projects, this concept is used quite frequently in many different ways.

A: You don't need typeof
if (window.disabledFlag === undefined) window.disabledFlag = false;

A: you can check if a variable is undefined with the typeof keyword, like this:
if(typeof neverDeclared == "undefined") //no errors

if(neverDeclared == null) //throws ReferenceError: neverDeclared is not defined

take a look here for more info on typeof


Q: Clang undefined behavior checker link error Upon trying to compile a C++ source file with clang 3.5 with the undefined behavior checker
 clang++-3.5 -std=c++11 -fsanitize=undefined main.cpp

I am getting the following error upon linking:
Undefined symbols for architecture x86_64:
  "typeinfo for __cxxabiv1::__class_type_info", referenced from:
      __ubsan::checkDynamicType(void*, void*, unsigned long) in libclang_rt.ubsan_osx.a(ubsan_type_hash.o)
      isDerivedFromAtOffset(__cxxabiv1::__class_type_info const*, __cxxabiv1::__class_type_info const*, long) in libclang_rt.ubsan_osx.a(ubsan_type_hash.o)
      findBaseAtOffset(__cxxabiv1::__class_type_info const*, long) in libclang_rt.ubsan_osx.a(ubsan_type_hash.o)
  "typeinfo for __cxxabiv1::__si_class_type_info", referenced from:
      isDerivedFromAtOffset(__cxxabiv1::__class_type_info const*, __cxxabiv1::__class_type_info const*, long) in libclang_rt.ubsan_osx.a(ubsan_type_hash.o)
      findBaseAtOffset(__cxxabiv1::__class_type_info const*, long) in libclang_rt.ubsan_osx.a(ubsan_type_hash.o)
  "typeinfo for __cxxabiv1::__vmi_class_type_info", referenced from:
      isDerivedFromAtOffset(__cxxabiv1::__class_type_info const*, __cxxabiv1::__class_type_info const*, long) in libclang_rt.ubsan_osx.a(ubsan_type_hash.o)
      findBaseAtOffset(__cxxabiv1::__class_type_info const*, long) in libclang_rt.ubsan_osx.a(ubsan_type_hash.o)
ld: symbol(s) not found for architecture x86_64

Do I need to link with an additional library?

A: It seems you are missing libc++abi. Try adding
-lc++abi

to your link command.


Q: How to check open ports using powershell? I would like to write a script to check radom IP or hostname to see if ports are open. Here is what I have so far. The scripts name is checkports.
foreach ($xhost in $computername){
    Write-Host $xhost
    foreach ($port in $ports) {
        $Socket = New-Object System.Net.Sockets.TCPClient
        $Connection = $Socket.BeginConnect($xhost,$port,$null,$null)

        $Connection.AsyncWaitHandle.WaitOne(5000,$false) | out-null

        if ($Connection -eq $true)
            { write-host = "$xhost port $port is open" }
        else
            { write-host = "port $port is closed" }

        $Socket.EndConnect($Connection)
        $Socket.Close()
   }
}

I would like to input values in the following way:
.\checkport '192.186.1.5'
or
'192.168.1.5', '192.168.1.105', 192.168.1.110' | checkport
It doesn't seem to be reading IP address or displaying results.
I was wondering if anyone could point out there could show me what I am doing wrong in with this script?

A: I've been able to use the 'Test-Port' function from Boe Prox for similar scan/ reporting functions, the code is available on PoshCode:
http://poshcode.org/2514
When I needed to test ports for Directory health, I built a csv with 'port' and 'protocol' columns, then added the port number/ protocol for each port to check. This was used in the following script:
. .\test-port.ps1

$computersToCheck = get-content .\computers.txt
$portList = Import-CSV .\portList.csv

foreach($entry in $portList)
{
    $testPortParams = @{
        port = $($entry.port)
    }
    if( $($entry.protocol) -eq "tcp")
    { $testPortParams += @{ TCP = $true } }
    else
    { $testPortParams += @{ UDP = $true } }

    $outLog = "portTest-$($entry.port)-$($entry.protocol).txt"

    $computersToCheck |
        Test-Port @testPortParams |
        Sort-Object -Property open,name -descending |
        format-table -auto -outVariable status
    Add-Content -path $outLog -value $status
}

You could certainly build a feeder script to build the range of IP addresses and ports to scan.


Q: Why does my code not iterate over each line? There is a key error "\n" despite stripping off(.txt input fed in using .read()) I have a .txt file of DNA sequences in the format shown below:
>seq1
ATATAT
>seq2
GGGGG
>seq3
TTTTT

Using re.sub, I have removed the lines with ">seq" numbers like this, to have an input of just lines of DNA bases A, G, C and T like this, and then stripped the "\n" as follows:
ATATAT
GGGGG
TTTTT

import re
test = re.sub('\ |1|2|3|4|5|6|7|8|9|0|>|s|e|q|:', "", holder)
newone = test.rstrip("\n")

I would then like to use this as input into my one hot encoder, which is encased within an if statement (there is an if statement to check if any unexpected letters are present in the DNA sequence). So far it looks like this:
for line in newone:

#if undesirable letters are present in sequence, an error message is displayed
    if (bool(result)) == True:
        print("The input sequence is invalid.")

#if sequence is in the correct format, proceed with one hot encoding

    else:
     #mapping of bases to integers as a dictionary
        bases = "ATCG"
        base_to_integer = dict((i, c) for c, i in enumerate(bases))

    #encoding input sequence as integers
        integer_encoded = [base_to_integer[y] for y in newone]

    #one hot encoding
        onehot_encoded = list()
        for value in integer_encoded:
            base = [0 for x in range(len(bases))]
            base[value] = 1
            onehot_encoded.extend(base)
        print(onehot_encoded)

I can see this error in the shell, but I am not sure why, because I think I have indicated in my code that "\n" needs to be stripped:
Traceback (most recent call last):
  File "C:\Users\Agatha\Documents\testtt.py", line 38, in <module>
    integer_encoded = [base_to_integer[y] for y in newone]
  File "C:\Users\Agatha\Documents\testtt.py", line 38, in <listcomp>
    integer_encoded = [base_to_integer[y] for y in newone]
KeyError: '\n'

I would like my program to iterate the code over each line of my input file, but I am not sure if my for loop ("for line in newone") will achieve this if the \n is stripped, and I cannot work out how I could rearrange this to make it work.
I am aiming to have my output in this kind of format, where each one-hot-encoded sequence is displayed on a separate line, e.g:
[1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0
0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1]

I would appreciate any advice on what the source of this error is and how I could go about fixing it.

A: If I were you, I would use the .split() method to create a list from the text you read.
test = re.sub('\ |1|2|3|4|5|6|7|8|9|0|>|s|e|q|:', "", holder)
newone = test.split("\n")

at this point newone will look like ['', 'ATATAT', '', 'GGGGG', '', 'TTTTT', ''] so to strip out the extra spaces:
newone = [x for x in newone if x != '']

Now to the error you are receiving, it is because you in your list comprehension (line 38 of your code) you are using newone instead of line. Each letter of line is an key of your dictionary base_to_integer but the KeyError you get is because \n is not a Key in the dictionary. Even after making the change I suggest above you will get an error:
KeyError: 'ATATAT'

So you should change this line to:
integer_encoded = [base_to_integer[y] for y in line]

Fixing this gives me:
[1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0]
[0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1]
[0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0]

Hope this helps.