Q: I'm Confused with Java NIO I'm confused with java nio buffers and Files.write if I can write with buffers and channels on file why do I need Files class.
What's difference between both of these working code examples.
String newData = "New String to write to file..." + System.currentTimeMillis();

Path path = Paths.get("C://data/nio-data2.txt");
try {
    Files.write(path,newData.getBytes());
} catch (IOException e) {
    e.printStackTrace();
}

and
try {
    RandomAccessFile aFile = new RandomAccessFile("C://data/nio-data.txt", "rw");
    FileChannel channel = aFile.getChannel();
    ByteBuffer buf = ByteBuffer.allocate(48);
    buf.clear();
    buf.put(newData.getBytes());

    buf.flip();

    while(buf.hasRemaining()) {
        channel.write(buf);
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

EDIT
i want to ask one more question, is Channels.newOutputStream interrupt the thread when write to file or worked as a non-blocking

A: Version with Files shorter and easier to understand.
Other version is more flexible. It is not very useful when you have only one file to write, but if you have many files in different storages it can save you some resources.
EDIT
Here is Files.write source code:
public static Path write(Path path, byte[] bytes, OpenOption... options)
    throws IOException
{
    // ensure bytes is not null before opening file
    Objects.requireNonNull(bytes);

    try (OutputStream out = Files.newOutputStream(path, options)) {
        int len = bytes.length;
        int rem = len;
        while (rem > 0) {
            int n = Math.min(rem, BUFFER_SIZE);
            out.write(bytes, (len-rem), n);
            rem -= n;
        }
    }
    return path;
}

As you can see it doesn't use NIO inside, only good old OutputStream.
EDIT 2
In fact Files.newOutputStream don't return FileOutputStream as I expected. It returns OutputStream defined in Channels.newOutputStream which use NIO inside.

A: *

*Files.write(...) use OutputStream instead of RandomAccessFile.getChannel(). it some different mechanisms, so better to google it for understand

*Files.write(...) much shorter and incapsulate logic of writting to file

*When you use such 'low' code, you need to look after many things. For example, in your example you didn't close your channel.
So, in conclusion, if you need to just write – better to use Files or another high-level API. If you need some 'additional' features during read/write, you need to use RandomAccessFile or InputStream/OutputStream


Q: Print dataframe to console during intermediate steps in dplyr chain While debugging dplyr chains in a function, I often want to be able to print intermediate changes to a data.frame to the console. How would I do this?
For example:
data(cars)
cars %>% group_by(speed) %>%
  summarize(dist_mean = mean(dist)) %>%
  [insert printing function] %>%
  group_by(speed > 10) %>%
  summarize(dist_mean = mean(dist_mean)) %>%
  [insert printing function]

Is there something I can do to replace [insert printing function] to print the current state of the dataframe to the console, while still continuing the chain uninterrupted?

A: Try the T-pipe: %T>%.
From documentation:

Pipe a value forward into a function- or call expression and return the original value instead of the result. This is useful when an expression is used for its side-effect, say plotting or printing.

There is a good example of it here along with the other two less common pipe commands.
Inserting back into your original context:
data(cars)
cars %>% group_by(speed) %>%
  summarize(dist_mean = mean(dist)) %T>%
  print() %>%
  group_by(speed > 10) %>%
  summarize(dist_mean = mean(dist_mean)) %T>%
  print()

Edit: As per @Ritchie Sacramento's comment the pipes are part of the magrittr package. They also appear to be re-exported by dplyr. If they don't work after calling library(dplyr) then you will need to call library(magrittr) to access them.


Q: how to change the color of an element that is in front of a background image in css? I put a background image in the body. I also have a different color for my menu box. I don't want to see the image in the menu box, how can I do that in CSS? Below is my code.
Thank you,
Avi
body{
    font-family: sans-serif;
    background-image: url("coffee_beans.jpeg");
    background-repeat: no-repeat;
    background-attachment: fixed;
    background-size: cover;
}
.menu{
    position: relative;
    border: 2px solid red;
    max-width: 613px;
    width: 100%;
    margin: auto;
    background-color: rgba(255, 189, 109, 0.395);
}

A: Maybe you can try to remove the background-color alpha, it will not become transparent background.
.menu{
    background-color: rgb(255, 189, 109);
}

If you must keep the background-color for transparent, you may create one more layer on the .menu div

body{
    font-family: sans-serif;
    background-image: url("https://dl.fujifilm-x.com/global/products/cameras/x-t3/sample-images/ff_x_t3_002.JPG");
    background-repeat: no-repeat;
    background-attachment: fixed;
    background-size: cover;
}

.menub{
  position: relative;
    border: 2px solid red;
    max-width: 613px;
    width: 100%;
    height:100px;
    margin: auto;
    background-color: white;
}

.menu{
    width: 100%;
    height:100px;
    background-color: rgba(255, 189, 109,0.382);
}


Q: Reuse Other Company's Content For Same Client Here's the scenario: a client of mine (lets call them Company A) had a website built by someone else (let's call them Company B).  They then asked me (Company C) to configure a third party framework to look and feel exactly the same as what Company B built for them.
Would it be legitimate for me to use content (including images, CSS, and even HTML) from the site Company B built for Company A?
It's worth mentioning Company A's name is in the copyright notice in the footer of the site Company B made for Company A.

A: If Company A owns the copyright (this is usually the case in works-for-hire of this sort, and the copyright notice backs this up), then it's perfectly legitimate to use those assets in other projects for Company A.  Company A owns the rights to those assets, so can do what they like with them.

A: IANAL, but it should be okay. Even if Company B really does hold the copyright (and say Company A modified/added the copyright notice without authorization) unless Company A actually stole it, they should at least have the right to use and modify it. If you hire someone to create a work, even if it's not technically a work for hire under copyright law, you certainly should have the ordinary use you hired them to get the benefit of. That would include the right to use and maintain the work. Web sites are always in flux, so modification should be considered part of ordinary use.
Most likely, the copyright notice is correct and your client holds the copyright. But you may want to find a subtle way to confirm with your client that there are no copyright issues that they're aware of. It's possible they hired you specifically because they know there's a problem and then 'forgot' to tell you about the problem.


Q: Printing bits of a byte I am using "lahf" to store the flags in ah. I would like to output these values (1s and 0s) to see my flags, but I have no idea how. My Holder label in the code below outputs a decimal, is there a way to output a binary number instead? or should I go about this in a different way?
lahf                 ;moves flags to ah
mov [flagg], ah      ;moves flags to label "flagg" in .bss (reserved 1 dword)

;later on...
mov eax,[flagg]      ;moves the flag values into eax
push eax             ;pushes eax onto stack
push Holder          ;Holder is a label in .data ( "%d",0 )
call printf          ;prints to screen
add esp, 8

A: You can't print binary with printf. You could print hex which is quite easy to relate to its binary representation (with %02X e.g.).
If you insist on printing binary, you would have to write a function for it. The function would be quite simple. If you have n bits, you could loop n times, do a shift by 1 and based on the carry either print 0 or 1. A bit more efficiently, you could store the result in a buffer and then print it all at once with %s.
Depending on how much memory you have (since it's x86 it's unlikely (impossible?) that it's embedded, so you probably do have a lot of memory), you can also store a table with the '0'-'1' representations of the bytes. That table would take 256*(8+1) bytes (one for '\0' if you use %s) for 8-bit values and you would need to hard-code it (perhaps generate with another program).
So far, I told you the two extremes: calculate all vs store all. The first can be slow and the second take a lot of space (and also tedious to generate).
To get the best of both worlds, you can have a table that stores the '0'-'1' representations of nibbles (4 bits). That table would be a mere 16*(8+1) bytes. Printing a byte would then be printing first its most significant and then its least significant nibble.
In C, this would look like this:
const char *bit_rep[16][5] = {
    [ 0] = "0000", [ 1] = "0001", [ 2] = "0010", [ 3] = "0011",
    [ 4] = "0100", [ 5] = "0101", [ 6] = "0110", [ 7] = "0111",
    [ 8] = "1000", [ 9] = "1001", [10] = "1010", [11] = "1011",
    [12] = "1100", [13] = "1101", [14] = "1110", [15] = "1111",
};

void print_byte(uint8_t byte)
{
    printf("%s%s", bit_rep[byte >> 4], bit_rep[byte & 0x0F]);
}


Q: Wrong section ref in the header with leftmark, twocolumn article I am trying to make a reference to the leftmark (last defined title) in header of a twocolumn article. The reference though keeps refering to the rightmark (last defined title. I have included the latex bug fixer package (\usepackage{fixltx2e}) and this did not help the problem.
I have searched high and low for an old answer that could fix my problem, so I hope someone knows the answer.
Here is an example with the nessesary part of my code to illustrate my problem:
\documentclass[twocolumn]{article}

\usepackage{fixltx2e}
\usepackage{fancyhdr}
\usepackage{lastpage}

% HEADER AND FOOTERS %

\pagestyle{fancy}
\fancyhf{}
\fancyhead[RO,RE]{\small\bfseries\leftmark}
\fancyfoot[RO,RE]{\bfseries \thepage / \pageref{LastPage}}
\fancyfoot[RO,RE]{\bfseries \thepage / \pageref{LastPage}}
\renewcommand{\headrulewidth}{0.02pt}
\renewcommand{\footrulewidth}{0pt}
\rhead{\nouppercase{\leftmark}}
%
\newlength\FHleft \setlength\FHleft{13cm}
\newlength\FHright \setlength\FHright{0cm}
\newbox\FHline
\setbox\FHline=\hbox{\hsize=\paperwidth
    \hspace*{\FHleft}
    \rule{\dimexpr\headwidth-\FHleft-\FHright\relax}{\headrulewidth}\hspace*{\FHright}}
\renewcommand\headrule{\vskip-.7\baselineskip\copy\FHline}

\fancypagestyle{plain}{%
    \fancyhf{} %
    \fancyfoot[R]{\bfseries \thepage / \pageref{LastPage}}
    \renewcommand{\headrulewidth}{0pt}
    \renewcommand{\footrulewidth}{0pt}}

\usepackage{lipsum}

\begin{document}

\section{Test1}
\lipsum[1-8]

\section{Test2}
\lipsum[6]

\section{Test3}
\lipsum[7]

\section{Test4}
\lipsum[8]

\section{Test5}
\lipsum[9]

\end{document}

I hope i did this right - first time :)

A: If you want the first section title of the page in your header, there are two possibilities. (1) if you don't need the subsection titles in your headers or footers, you can use
\renewcommand\sectionmark[1]{\markboth{#1}{#1}}
\renewcommand\subsectionmark[1]{}

and then use \rightmark instead of \leftmark.
The second possibility, that leaves the subsction titles still available is to use:
\usepackage{extramarks}

and then use \firstleftmark instead of \leftmark. However, this may occasionally leave the last section title of the previous page in the title (actually this would be the section title of the first text of the page, which then still belongs to the last section on the previous page). This would happen if there was a subsection on that page before the first section.


Q: XMLHttpRequest works but no response/status back on callback I have an XMLHttpRequest where i am sending an image across to be saved on my Amazon s3 bucket. It works correctly and the file goes to my bucket but i am getting no response back saying it is in process or has successfully uploaded. My code is below:
Javascript code in html page:
var ajax = new XMLHttpRequest();

ajax.open("POST",'http://www.xxxx.php',false);
ajax.setRequestHeader('Content-Type', 'application/upload');
ajax.send(theImage);

ajax.onreadystatechange=function(){
    if (ajax.readyState==4 && ajax.status==200) {
        console.log('success');
    }
    else {
        console.log('ongoing...');
    }
}

PHP code in xxxx.php:
<?php
if (isset($GLOBALS["HTTP_RAW_POST_DATA"])){
    $imageData = $GLOBALS['HTTP_RAW_POST_DATA'];
    $filteredData = substr($imageData, strpos($imageData, ",")+1);
    $imgFileString = base64_decode($filteredData);
    $s3Filename = time().'.png';

    if($s3->putObjectString($imgFileString, $bucket , $s3Filename, S3::ACL_PUBLIC_READ) ){
        echo "SUCCESS";
    }
    else{
        echo "ERROR";
    }
}
else {
    echo "EMPTY";
}
?>

How can i get a callback to say when the upload has successfully been uploaded or if an error has occurred?

A: ajax.open("POST",'http://www.xxxx.php',false);
                                       ^^^^^^

You are making a synchronous request, so the request is being made and the response received before you assign your event handler. Don't do that. Remove false (or change it to true).


Q: How to load last on changed Google sheet data and send an email as PDF using script I have written a script function to get google sheet data and send the email as an attached PDF. I have used here pivot tables in the google sheet.

The problem is here. after the filtered pivot table and then if I send an email.it sent only without filter data. That means is default values only export as pdf.
How to send an email pdf with current filtered data?
function sendEmail(){
  try {
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var getTabsheetName=ss.getSheetByName('report');

      var url = 'https://docs.google.com/a/mydomain.org/spreadsheets/d/'
      + ss.getId()  //Your File ID
      + '/export?exportFormat=pdf&format=pdf'
      + '&size=LETTER'
      + '&portrait=true'
      + '&fitw=true'
      + '&top_margin=0.50'
      + '&bottom_margin=0.50'
      + '&left_margin=0.50'
      + '&right_margin=0.50'
      + '&sheetnames=false&printtitle=false&pagenumbers=true'
      + '&pagenum=false'
      + '&gridlines=false'
      + '&fzr=FALSE'
      + '&gid='
      + getTabsheetName.getSheetId();       //the sheet's Id

    var emailsheet=ss.getSheetByName('Email');
    var emailContentsheet=ss.getSheetByName('EmailContent');
    var subject = emailContentsheet.getRange(2,1).getValue();
    var n=emailsheet.getLastRow();

    var params = {
      method      : "get",
      headers     : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
      muteHttpExceptions: true
    };
    var blob = UrlFetchApp.fetch(url, params).getBlob().setName('Report.pdf');
    for (var i = 2; i < n+1 ; i++ ) {
      // SpreadsheetApp.flush();
      var emailAddress = emailsheet.getRange(i,2).getValue();
      var name=emailsheet.getRange(i,1).getValue();
      var message = emailContentsheet.getRange(2,2).getValue();
      var returnData = [name,message];
      var templ = HtmlService.createTemplateFromFile('index');
      templ.data = returnData;
      var htmlboday = templ.evaluate().getContent();
      MailApp.sendEmail({
        to: emailAddress,
        subject: subject,
        htmlBody: htmlboday,
        attachments:[blob]
      });
  }
  } catch (f) {
    Logger.log(f.toString());
  }
}


Q: Parameterization in adf? If we define array type parameters outside all activity then want to apply it in dataset in copy activity in foreach where string type parameters is there then how can we access these parameters ?

A: I'm assuming, you are asking for source dataset. For Sink dataset as well, it will follow same steps but you will have to do the same things in "Sink" tab.
Here, I'm doing it for "Source".

*

*Take array as parameter (outside of all activities that means it is a pipeline parameter).

*Choose "Add dynamic content"

*Choose pipeline array parameter "test_param", for which "ForEach" activity will run and click finish.

*Add New source dataset "test_Parquet" using "+" symbol.

*Go to Source dataset "test_Parquet" -> Parameters and add new parameter,<here I've added "param" with datatype String>

*After adding that, return to "Copy activity" and you will see "param (your parameter)" under "DataSet Properties":

*Click on "add dynamic content" and add "pipeline array parameter element" to the dataset parameter value.

*Click on "ForEach iterator -> current item" and click Finish.

This process will add the pipeline array parameter elements to Copy Activity source dataset.


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: Making Windows XP use a global input language instead of per-application I work with 2, sometimes 3 different languages on my XP boxes.
Windows XP chooses input language on a per-application basis. That is, when I switch to a different application, Windows sometimes changes the input language because it remembers that I used that language last time I used that app.
I don't like that. I want Windows to maintain one global input language, and change it only when I hit Alt-Shift.
Is it possible to hack Windows to behave like that? Maybe with AutoHotKey?

A: The only way I could see this working, is by only having one keyboard layout installed at a time.  For example, when you want to only use Romanian, you would delete all other keyboard layouts...
AutoHotKey can be used for creating shortcuts to quickly delete and install keyboard layouts.
Post comments with any additional questions or concerns regarding my answer.

A: Here's the AHK script I've been using for this for maybe a year now:
language := 0

;;; Forced Hebrew: ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;                                                                            ;
#z::
    language := 0
    Return

+#z::
    language := 1
    Return

#if language=1 and not GetKeyState("Capslock", "T")
    `:: SendInput {;}
    q:: SendInput /
    w:: SendInput '
    e:: SendInput ק
    r:: SendInput ר
    t:: SendInput א
    y:: SendInput ט
    u:: SendInput ו
    i:: SendInput ן
    o:: SendInput ם
    p:: SendInput פ
    a:: SendInput ש
    s:: SendInput ד
    d:: SendInput ג
    f:: SendInput כ
    g:: SendInput ע
    h:: SendInput י
    j:: SendInput ח
    k:: SendInput ל
    l:: SendInput ך
    `;:: SendInput ף
    ':: SendInput `,
    z:: SendInput ז
    x:: SendInput ס
    c:: SendInput ב
    v:: SendInput ה
    b:: SendInput נ
    n:: SendInput מ
    m:: SendInput צ
    ,:: SendInput ת
    .:: SendInput ץ
    /:: SendInput .

    (:: SendInput )
    ):: SendInput (
    [:: SendInput ]
    ]:: SendInput [
    >:: SendInput <
    <:: SendInput >

#if
;                                                                            ;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;


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: Why using where in indexed field is slow? we have a big table. the table structure is  :
CREATE TABLE `visit_logs` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `user_id` int(10) NOT NULL,
  `ref_id` int(10) NOT NULL DEFAULT '0',
  `link_id` int(12) NOT NULL,
  `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `day_of_week` tinyint(1) NOT NULL,
  `jalali_month` tinyint(2) NOT NULL ,
  `value` int(9) NOT NULL ,
  `ref_share` float(4,2) NOT NULL DEFAULT '0.00',
  `balance` int(9) NOT NULL ,
  `ads_id` int(12) NOT NULL,
  `ip` varchar(15) NOT NULL,
  `hash` varchar(32) NOT NULL,
  `referer` text,
  `shw` text,
  PRIMARY KEY (`id`),
  KEY `user_id` (`user_id`),
  KEY `jalali_month` (`jalali_month`),
  KEY `value` (`value`),
  KEY `ads_id` (`ads_id`),
  KEY `ip` (`ip`),
  KEY `hash` (`hash`),
  KEY `link_id` (`link_id`),
  KEY `day_of_week` (`day_of_week`),
  KEY `ref_share` (`ref_share`),
  KEY `ref_id` (`ref_id`),
  KEY `date` (`date`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8;

these are some sample queries :
mysql> SELECT count(*),SUM( value ) AS `revenue` FROM `visit_logs` where id>13197856;
+----------+-----------+
| count(*) | revenue   |
+----------+-----------+
| 10443393 | 200940970 |
+----------+-----------+
1 row in set (6.02 sec)

mysql> SELECT count(*),SUM( value ) AS `revenue` FROM `visit_logs` where `date`  > NOW() - INTERVAL 90 day;
+----------+-----------+
| count(*) | revenue   |
+----------+-----------+
| 10443354 | 200940430 |
+----------+-----------+
1 row in set (9.24 sec)

mysql> SELECT count(*),SUM( value ) AS `revenue` FROM `visit_logs` ;
+----------+-----------+
| count(*) | revenue   |
+----------+-----------+
| 23641291 | 596178719 |
+----------+-----------+
1 row in set (3.32 sec)

as you can see , selecting all rows is faster than selecting some row filtered by id , also filter by id is faster than filter by timestamp . id and timestamp fields are indexed !
Mysql version is 5.1 .
my.conf :
thread_concurrency = 8
query_cache_size = 1G
thread_cache_size = 8
myisam_sort_buffer_size = 1G
read_rnd_buffer_size = 256M
read_buffer_size = 512M
sort_buffer_size = 512M
table_open_cache = 512
max_allowed_packet = 20M
key_buffer_size = 1G
#log = /var/log/mysqlq.log
wait_timeout=120
connect_timeout=50
#max_execution_time=60000
tmp_table_size=2G
max_heap_table_size=2G

Explain :
explain SELECT count(*),SUM( value ) AS `revenue` FROM `visit_logs` where id>13197856;
+----+-------------+------------+------+---------------+------+---------+------+----------+-------------+
| id | select_type | table      | type | possible_keys | key  | key_len | ref  | rows     | Extra       |
+----+-------------+------------+------+---------------+------+---------+------+----------+-------------+
|  1 | SIMPLE      | visit_logs | ALL  | PRIMARY       | NULL | NULL    | NULL | 12978097 | Using where |
+----+-------------+------------+------+---------------+------+---------+------+----------+-------------+
1 row in set (0.00 sec)
mysql> explain SELECT count(*),SUM( value ) AS `revenue` FROM `visit_logs` force index (PRIMARY) where id>13197856;
+----+-------------+------------+-------+---------------+---------+---------+------+----------+-------------+
| id | select_type | table      | type  | possible_keys | key     | key_len | ref  | rows     | Extra       |
+----+-------------+------------+-------+---------------+---------+---------+------+----------+-------------+
|  1 | SIMPLE      | visit_logs | range | PRIMARY       | PRIMARY | 4       | NULL | 10604250 | Using where |
+----+-------------+------------+-------+---------------+---------+---------+------+----------+-------------+
1 row in set (0.00 sec)

mysql>  SELECT count(*),SUM( value ) AS `revenue` FROM `visit_logs` force index (PRIMARY) where id>13197856;
+----------+-----------+
| count(*) | revenue   |
+----------+-----------+
| 10534567 | 202721650 |
+----------+-----------+
1 row in set (10.73 sec)

mysql>  SELECT count(*),SUM( value ) AS `revenue` FROM `visit_logs` force index (PRIMARY) where id>13197856;
+----------+-----------+
| count(*) | revenue   |
+----------+-----------+
| 10534578 | 202721830 |
+----------+-----------+
1 row in set (10.75 sec)

mysql>  SELECT count(*),SUM( value ) AS `revenue` FROM `visit_logs`  where id>13197856;
+----------+-----------+
| count(*) | revenue   |
+----------+-----------+
| 10534588 | 202722030 |
+----------+-----------+
1 row in set (3.50 sec)

mysql>  SELECT count(*),SUM( value ) AS `revenue` FROM `visit_logs`  where id>13197856;
+----------+-----------+
| count(*) | revenue   |
+----------+-----------+
| 10534592 | 202722070 |
+----------+-----------+
1 row in set (3.53 sec)

mysql>  SELECT count(*),SUM( value ) AS `revenue` FROM `visit_logs` ;
+----------+-----------+
| count(*) | revenue   |
+----------+-----------+
| 12978727 | 262590120 |
+----------+-----------+
1 row in set (1.66 sec)

mysql>  SELECT count(*),SUM( value ) AS `revenue` FROM `visit_logs` ;
+----------+-----------+
| count(*) | revenue   |
+----------+-----------+
| 12978730 | 262590180 |
+----------+-----------+
1 row in set (1.65 sec)

A: Using an index requires bouncing back and forth between the index and the data.
In MyISAM, each index is a BTree sitting in the .MYI file.  At the leaf node of the index is a pointer into the .MYD file.  (Or, for FIXED, it will be a record number.)  Your SELECTs are happy to scan linearly through the index (a BTree is efficient at that), but then for each row, it has to use the pointer to 'seek' into the .MYD file to pick up any fields that were not in the index.
Since you are fetching about half the table -- a lot of work.
Without using an index, MyISAM will scan the .MYD file (in whatever order it is in).  This is more efficient than the back-and-forth of using an index.
Normally (without FORCE INDEX) the optimizer will decide to do a table scan if the estimated fraction of rows to do via an index lookup is more than somewhere around 20%.  That is, usually the optimizer does the "right thing" by ignoring the index.
If this does not explain all the differences, then I suspect there were caching differences -- the data blocks (.MYD) cached in the OS and/or the index blocks (.MYI) cached in the key_buffer.
Note a difference between MyISAM and InnoDB:  For MyISAM, the PRIMARY KEY is stored like any other index.  For InnoDB, it is clustered with the data; so WHERE id > ... would be a range scan over the data, thereby more efficient, and you would not have seen 10sec times.  (There are other significant differences, too.)


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: Не работает DNS в ubuntu 12.04 Проблема только с одним компом в сети. Ping по ip адресу идёт, по имени нет. ДНС в настройках карты 192.168.1.1, пробовал устанавливать публичные яндекса, результат тот же.
ping ya.ru
ping: unknown host ya.ru

ifconfig
eth0      Link encap:Ethernet  HWaddr 00:15:f2:16:bb:e4
          inet addr:192.168.1.210  Bcast:192.168.1.255  Mask:255.255.255.0
          inet6 addr: fe80::215:f2ff:fe16:bbe4/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:23456 errors:0 dropped:60 overruns:0 frame:0
          TX packets:6018 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:2072033 (2.0 MB)  TX bytes:544421 (544.4 KB)

A: sudo nano /etc/resolv.conf.head
nameserver 8.8.8.8
nameserver 8.8.4.4

Так после перезагрузки настройки не сбрасываются


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: Help me translate Windows 10 SMBv2 credentials into to Ubuntu 18.10 equivalent I have an Windows 10 v1809 PC (which I'll just call Windows10PC) that has an SMBv2 folder (SMBv2Folder) shared to my home LAN (i.e. NOT a domain). From a Windows 10 v1809 client perspective, the folder location looks like //Windows10PC/SMBv2Folder, and the credentials are Windows10PC\MyMicrosoftAccountUsername + MyMicrosoftAccountPassword. Note that I'm using a Microsoft Account and not a local Windows one. These credentials work perfectly from all my Windows 10 clients.
However, I'm having great difficulty connecting to the same folder from an Ubuntu 18.10 client; I get either "Permission denied" or "Stale file handle" error messages. Can anyone tell me what the Ubuntu equivalent of the above Windows credentials are for the following SMB fields: Path, Domain (bear in mind that the PC in question is on a home LAN, NOT a domain), and Username?
Also, AFAIK I only need to have cifs-utils installed to mount an SMBv2 share. Is this the case, or should I install something additional?


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: Verifying Stokes theorem (i.e. prove both integrals are equal) I have that $\hat{F}=[-y,x,0]$ and I have a surface defined by $S: rz=1$ where $1\leq z \leq 2$.
I interpret this surface as a truncated cone with curved edges.
So I am trying to show that, indeed $\oint_{C} \mathbf{F} \cdot d \mathbf{r}=\iint_{S}(\nabla \times \mathbf{F}) \cdot \mathbf{n} d \sigma$.
I have found that $\oint_{C} \mathbf{F} \cdot d \mathbf{r} = 3 \pi$, by parameterising the two boundary curves (the circles at top and bottom of S).
However, when calculating the surface integral I end up with $\frac{3}{ 2}\pi$.
Can anyone do this surface integral? Thank you!

A: First, note that in cylindrical coordinates $\vec F(\vec r)$ is given by $\displaystyle \vec F(\vec r)=\hat \phi r$ and $\nabla \times \vec F(\vec r)=\hat z 2$.
Let the surface $S$ be the set defined by $S=\{(r,\phi,z)|rz=1, z\in [1,2], \phi\in[0,2\pi] \}$.
On $S$ at $z=1$, $r=1$.  On $S$ at $z=2$, $r=1/2$.  Hence, the line integral in the boundary of $S$ is
$$\begin{align}
\oint_{C_{z=1}}\vec F(\vec r)\cdot \,d\vec \ell+\oint_{C_{z=2}}\vec F(\vec r)\cdot \,d\vec \ell&=\int_0^{2\pi} \left(\hat \phi 1\right)\cdot \left(\hat \phi 1\right)\,d\phi+\int_0^{2\pi} \left(\hat \phi \frac12\right)\cdot \left(-\hat \phi \frac12\right)\,d\phi\\\\
&=2\pi -2\pi \left(\frac14\right)\\\\
&=3\pi/2\tag1
\end{align}$$
where the minus sign on $\hat \phi$ in the second integral on the right-hand side of $(1)$ is a consequence of the right-handed orientation of $S$.
Next, we calculate the surface integral of Stokes's Theorem using two methodologies.

METHODOLOGY $(1)$:  DIRECT COMPUTATION
We can parameterize the surface with $r$ and $\phi$ with
$$\vec r=\hat r(\phi) r +\hat z \frac1r $$
The surface differential vector is given
$$\begin{align}
\hat n d S&=\left(\frac{\partial \vec r}{\partial r}\times\frac{\partial \vec r}{\partial \phi}\right)\,dr\,d\phi\\\\
&=\left(\hat r\frac1r+\hat z r\right)\,dr\,d\phi
\end{align}$$
Hence, we find that
$$\begin{align}
\int_S \color{blue}{\nabla \times \vec F(\vec r)}\cdot \,\color{red}{\hat n \,dS}&=\int_0^{2\pi }\int_{1/2}^1 \color{blue}{\left(\hat z 2\right)}\cdot \color{red}{\left(\hat r\frac1r+\hat z r\right)\,dr\,d\phi}\\\\
&=3\pi/2
\end{align}$$
as was to be shown!

METHODOLOGY $(2)$:  USE OF THE DIVEREGENCE THEOREM
Let's close the surface $S$ with the surfaces $S_u=\{(r,\phi,z)|z=2, r\in[0,1/2], \phi\in[0,2\pi]\}$ and $S_l=\{(r,\phi,z)|z=1, r\in[0,1], \phi\in[0,2\pi]\}$.
Using $\nabla\cdot \nabla \times \vec F(\vec r)=0$ along with the Divergence Theorem, we have
$$\oint_{S+S_u+S_l}\nabla \times \vec F(\vec r)\cdot \hat n\,dS=0$$
Therefore we see that
$$\begin{align}
\oint_{S}\nabla \times \vec F(\vec r)\cdot \hat n\,dS&=-\oint_{S_u+S_l}\nabla \times \vec F(\vec r)\cdot \hat n\,dS\\\\
&=-\int_0^{2\pi}\int_0^{1/2} (\hat z 2)\cdot (\hat z)\,r\,dr\,d\phi-\int_0^{2\pi}\int_0^{1} (\hat z 2)\cdot (-\hat z)\,r\,dr\,d\phi\\\\
&=3\pi/2
\end{align}$$
as expected!


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: The Chain rule - prove identity let $z(x,y)=\frac{\ln x}{y^{2}}f\left(\frac{e^{-y}}{x}\right)$  for some differentiable  $f(t)$
prove:
$$(xy\ln x)\cdot\frac{\partial z}{\partial x}-(y \ln x)\cdot\frac{\partial z}{\partial y}=(2\ln x+y)\cdot z$$
my try:
my idea was to use the Chain rule
let $u=\frac{lnx}{y^{2}},v=\frac{e^{-y}}{x}$ the composition is:
$$z=uf\left(v\right)\longleftarrow(u,v)=(\frac{\ln x}{y^{2}},\frac{e^{-y}}{x})\longleftarrow(x,y)$$
and by the Chain rule:
$$
\begin{pmatrix}\frac{\partial z}{\partial x} & \frac{\partial z}{\partial y}\end{pmatrix}=\begin{pmatrix}\frac{\partial z}{\partial u} & \frac{\partial z}{\partial v}\end{pmatrix}\begin{pmatrix}\frac{\partial u}{\partial x} & \frac{\partial u}{\partial y}\\
\frac{\partial v}{\partial x} & \frac{\partial v}{\partial y}
\end{pmatrix}$$
but I don't know how to continue because $\frac{\partial z}{\partial v}$ depends on the function $f$

A: Since $z(x,y)=\frac{\ln x}{y^2}f\left(\frac{e^{-y}}x\right)$, you have$$\frac{\partial z}{\partial x}=\frac1{xy^2}f\left(\frac{e^{-y}}x\right)-\frac{e^{-y}\ln x}{x^2y^2}f'\left(\frac{e^{-y}}x\right)$$and$$\frac{\partial z}{\partial y}=-\frac{2\ln x}{y^3}f\left(\frac{e^{-y}}x\right)-\frac{e^{-y}\ln x}{xy^2}f'\left(\frac{e^{-y}}x\right).$$Therefore,$$xy\ln(x)\frac{\partial z}{\partial x}=\frac{\ln x}yf\left(\frac{e^{-y}}x\right)-\frac{e^{-y}\ln^2x}{xy}f'\left(\frac{e^{-y}}x\right)$$and$$y\ln(x)\frac{\partial z}{\partial y}=-\frac{2\ln^2x}{y^2}f\left(\frac{e^{-y}}x\right)-\frac{e^{-y}\ln^2x}{xy}f'\left(\frac{e^{-y}}x\right).$$So\begin{align}xy\ln(x)\frac{\partial z}{\partial x}-y\ln(x)\frac{\partial z}{\partial y}&=\left(\frac{\ln x}y+\frac{2\ln^2x}{y^2}\right)f\left(\frac{e^{-y}}x\right)\\&=\frac{y\ln(x)+2\ln^2(x)}{y^2}f\left(\frac{e^{-y}}x\right)\\&=(y+2\ln x)z(x,y).\end{align}

A: The final result will depend on $f$ (and $f'$). For instance,
$$
\frac{\partial z}{\partial x} = \frac{1}{y^2}\left[\frac 1x f\left(\frac{e^{-y}}{x}\right) + \ln x \cdot \left(-\frac{e^{-y}}{x^2}\right)\cdot f'\left(\frac{e^{-y}}{x}\right) \right].
$$

In a simpler case, assuming enough regularity and $g: \mathbb{R}^2 \to \mathbb{R}$, $f: \mathbb{R} \to \mathbb{R}$
$$
\frac{\partial}{\partial x} f(g(x,y)) = \frac{\partial g}{\partial x} f'(g(x,y))
$$
$$
\frac{\partial}{\partial y} f(g(x,y)) = \frac{\partial g}{\partial y} f'(g(x,y))
$$


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: Kerbal space program number binding Basically i want to be able to press 2 (or any number or key) and have my all solar panels deploy instead of having to activate them all one by one with many annoying mouse click.
How do I do this?

A: You can do this with Action Groups.
This youtube tutorial provides a good example of how to do exactly what you want:

In short, once you have the solar panels added to your ship:

*

*Click on the "Action Groups" icon at the top of the screen. It's the blue button that looks like two gears.

*Select "Custom1" or whichever number you would like the action to bind to.

*Click on the solar panels you would like to extend/retract when the key is pressed.

*Then select "Toggle Panels" (or "Extend Panels"/"Retract Panels", if you only want this action to work in one direction.)
Now when your ship is launched, you can use whichever number key you bound this action group to to toggle your solar panels.


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: No Animations in Unity Dock I've noticed that animations in the Unity dock are no longer showing.  I've installed the Paper Theme and Cairo dock (which I later removed).  I don't know what reports to run to help identify the problem.  If this questions isn't specific enough please let me know what additional information is needed.

A: This seems to be the result of the Paper theme.  Removing the theme restores the animations to the Unity dock.


Q: If you create the Hell Fire ring (the new one) with a level 1 monk, does i still roll level 70 stats? The Hell Fire ring does not have a level requirement. It also has a chance to roll Main stat.  Will there be any difference between making it with a level 1 monk, as opposed to a level 70 monk. Will the stats be the same? Meaning will they roll at their level 70 equivelant, as a higher stat?


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 is `MakeExpression` processed by Mathematica? According to the documentation on MakeExpression,

MakeExpression[boxes, form] is the low-level function used in Wolfram System sessions to construct expressions from boxes.

what exactly does "low-level" mean?  Do I understand that Mathematica has a parser before feeding the parsed expression to the Kernel for evaluation? Or is MakeExpression handled by the Kernel itself, with a different meaning for "low-level"?

I am asking this because I have discovered two different ways to have custom notation in my package:
I am using the angle bracket characters 〈 and 〉 to denote inner products.  Either I can assign a DownValue to the meaningless function AngleBracket to point to my package function myInnerProduct, or I can use a construct like MakeExpression[boxes_, form_] = MakeExpression[..."myInnerProduct"..., form].  It would be useful to know how MakeExpression is processed by Mathematica before committing to a particular way of implementing the custom notation.

A: First you need to be aware of what boxes are and the fact that MakeExpression works only on boxes.
"Boxes" are Mathematica expressions that represent stuff that appears in a notebook.  They are bound to notebooks and the Front End.  When you type something in a notebook, it will be stored as boxes.  Select a cell and hit Command-Shift-E to see them.  MakeExpression is used during the process of converting boxes to expressions, e.g. going from RowBox[{"1", "+", "1"}] to Plus[1,1].  This conversion process is hackable.  Users can modify MakeExpression.  This is how the Notation package works.
This is different from when you send a plain string to the kernel.  If you run the kernel in command line mode, then the input you type is just string.  It doesn't get converted to boxes.  Instead it gets directly converted to expressions by a hardwired parser.  "1+1" goes directly to Plus[1,1].   This process is not customizable.
The implication is that custom notations, such as those created by the Notation package, only work if you are using the Front End and notebooks.
However, the parsing rules to go from "〈x〉" to AngleBracket[x] are already known to Mathematica, and already work in command line mode.  You don't need to add a custom notation to work with angle brackets – the notation is already there.  You can just create a definition for AngleBracket and it will work whereever.
MakeExpression and MakeBoxes are considered low-level because they are the lowest level user-accessible pieces in the conversion chain between expressions and boxes.  These functions are assignable.  You can add new definitions to them to teach Mathematica how to do certain parts of the conversion.  These definitions will also often involve calling MakeExpression/MakeBoxes again recursively to process sub-pieces.
In contrast, ToExpression/ToBoxes are high level functions which do the complete conversion in one step, and are not modifiable. They call call MakeExpression/MakeBoxes. Use ToExpression/ToBoxes if your goal is to perform the conversion and not to modify the conversion process.
All of this stuff is not well documented and I do not fully understand the details.  You can read about it here: http://reference.wolfram.com/language/tutorial/TextualInputAndOutputOverview.html