text:
Q: How to modify following jQuery function to detect iframe height? I use facebook commenting plugin on my website. It is hidden in a div.

This is facebook comments javascrip part

There is a jquery function that shows hidden .comentBox div, it lunches once the following link is clicked
Comments

and here is a jQuery function
function toggleSlideBox(x) {
    if ($('#' + x).is(":hidden")) {
        $(".comentBox").slideUp(200);
        $('#' + x).slideDown(200)
    } else {
        $('#' + x).slideUp(200)
    }
}

The problem is as follows. Once a hidden div get's expanded there is a lot of space under facebook comments that is not suppose to be there, I guess this is caused, because jquery function doesn't know the height of facebook iframe. Could you please suggest any
solutions / modifications that can fix this problem?
You can see the problem yourself here: http://inelmo.com/inelmo (click on several comments links under the posts to oppen hidden divs.)
NOTE: I tested it in several browsers, FireFox works normaly, the problems are present in chrome, safari and IE, not sure about opera.

A: This might be a bit hacky, but it should work. (Unable to test).
The problem seems to be that your iframe is deciding its height is around 400px more than it needs to be for some reason. This might be a facebook issue.
What you could do is manually set the height of the iframe to "auto" at pageload.
$(document).ready(function() {
   $(".fb-comments iframe").css("height", "auto");
});

I'm unable to test this, but have proof of concept editing DOM in chrome.
---Edited Code Below---
$(".fb-comments iframe").css("height", function() {
    $(this).contents().find("body").height();
});

Hopefully this will resolve the problem by setting the iframe height to the height of its contents. Again, not sure how it will turn out with the above. The auto property doesn't seem to expand the iframe to match its contents the way a normal html element would.
Keep the code in the Comment Click event.
I think this might cause another problem where when the contents of the iframe change (as they're bound to when someone adds a comment) the iframe won't expand. So we're now getting to the stage where you have to constantly monitor the contents of the iframe and apply them to the iframe itself, which seems way too complicated, but I can't think of a simpler way.
I did a quick search to see if anyone had a cleverer method of expanding an iframe to match its contents and couldn't see one. But that seems to be what your real question is now that we've looked into it.


text:
Q: Uglify-js doesn't mangle variable names Trying to prepare good build environment for my js library. According to reviews on the web UglifyJS seems to be one of the best compressing modules out there, working under NodeJS. So here is best recommended way of minifying the code:
var jsp = require("uglify-js").parser;
var pro = require("uglify-js").uglify;

var orig_code = "... JS code here";
var ast = jsp.parse(orig_code); // parse code and get the initial AST
ast = pro.ast_mangle(ast); // get a new AST with mangled names
ast = pro.ast_squeeze(ast); // get an AST with compression optimizations
var final_code = pro.gen_code(ast); // compressed code here

As seen here, pro.ast_mangle(ast) should mangle variable names, but it doesn't. All I get out of this pipe is javascript code, with no spaces. At first I thought that my code was not optimized for compression, but then I tried it with Google Closure and got quite a compression (with mangled variable names and everything).
UglifyJS experts, any hint to what I'm doing wrong?
UPDATE:
Actual code is too large to reference here, but even a snippet like this doesn't get mangled:
;(function(window, document, undefined) {

    function o(id) {
        if (typeof id !== 'string') {
            return id;
        }
        return document.getElementById(id);
    }

    // ...

    /** @namespace */
    window.mOxie = o;

}(window, document));

This is what I get (only spaces get stripped I guess):
(function(window,document,undefined){function o(id){return typeof id!="string"?id:document.getElementById(id)}window.mOxie=window.o=o})(window,document)

A: Ok, it seems that the latest version of Uglify JS requires mangle option to be explicitly passed as true, otherwise it won't mangle anything. Like this:
var jsp = require("uglify-js").parser;
var pro = require("uglify-js").uglify;

var orig_code = "... JS code here";
var options = {
    mangle: true
};

var ast = jsp.parse(orig_code); // parse code and get the initial AST
ast = pro.ast_mangle(ast, options); // get a new AST with mangled names
ast = pro.ast_squeeze(ast); // get an AST with compression optimizations
var final_code = pro.gen_code(ast); // compressed code here

A: By default uglify won't mangle toplevel names, maybe thats what you seen?
Try:
-mt or --mangle-toplevel — mangle names in the toplevel scope too (by default we don't do this).

A: If you're using Uglify2, you can use TopLevel.figure_out_scope(). http://lisperator.net/uglifyjs/scope
If you're using Uglify1, it's a little more complicated. Here's some code I put together by modifying the code from Uglify's squeeze_more.js file:
function eachGlobalFunctionCall(ast, callback) {
  var w = uglify.uglify.ast_walker(),
      walk = w.walk,
      MAP = uglify.uglify.MAP,
      scope;

  function with_scope(s, cont) {
    var save = scope, ret;
    scope = s;
    ret = cont();
    scope = save;
    return ret;
  }

  function _lambda(name, args, body) {
    return [ this[0], name, args, with_scope(body.scope, curry(MAP, body, walk)) ];
  }

  w.with_walkers({
    "function": _lambda,
    "defun": _lambda,
    "toplevel": function(body) {
      return [ this[0], with_scope(this.scope, curry(MAP, body, walk)) ];
    },
    "call": function(expr, args) {
      var fnName = expr[1];

      if (!scope.has(fnName)) {    // <--- here's the important part
        callback(fnName, args, scope);
      }
    }
  }, function() {
    return walk(uglify.uglify.ast_add_scope(ast));
  });
}

This one above only works on global function calls, but it gives you a callback which is executed as the walker finds a call to an unknown (global) method.
For example, given the following input:
function foo () {
  bar(1);
  (function () {
    function bar() { }
    bar(2);
    (function () {
      bar(3);
    }());
  }());
}

It would find the call bar(1) but not bar(2) or bar(3).

A: Variables in global scope are available to any other script, so Uglify won't change them without special switch, in case you really need them to be visible. You can either use -mt/toplevel switch/setting, or, better, yet, stop polluting global scope and clearly indicate that you don't intend for those variables to be seen outside, but framing your code into anonymous self-invoking function that will serve as private scope.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unexpected valley in Fourier Transformation using Scipy FFT I am trying to perform Scipy FFT on my dataset. Basically, I have the acceleration in the time domain(obtained numerically) and I am just trying to perform Fourier transform, to obtain the spectrum. I have a theoretical expression for Fourier transformed acceleration in a small and large frequency limit. For large frequency, the Fourier transformed acceleration should drop exponentially. However, I am getting a valley in the graph after an initial decay. Below are my code and graph
a_w = []
for k in range(len(b)): # b is paramter to be varied
 window = signal.kaiser(N, 30) # I am not sure about using Kaiser wind
 ft = fft(solaccarr[k]*window)
 ft = np.abs(ft[:N // 2])*1/N
 freq = fftfreq(N, T)[:N // 2]
 xf = np.linspace(0.0, 1.0 / (2.0 * float(T)), N // 2)
 a_w.append(ft)

I am plotting the graph on a log-log scale. My question is that whether it's possible to get rid of the kinks in graph by appropriate use of windows or any other techniques?
Here is the dataset which I used

A: These valleys may correspond to the end of the main lobe of the Kaiser window after translations.
If the input signal features a finite number of well-defined frequencies (ex: a sum of two sine waves), its Fourier transform is a Dirac comb. Multiplying the signal and the window corresponds to convolving the DFT transform of the signal by the DFT transform of the window. As convolving with a Dirac signal corresponds to a translation, the outcome of the process is a finite sum of translated DFT transforms of the window.
The  transform of the Kaiser window features a main lobe and side lobes separated by such valleys. Hence, the outcome may also features translated valleys. It can be tested by modifying 30 in window = signal.kaiser(N, 30): could you try figures like 0, 5, 6 and 8.6? It should translate the valley from left to right or right to left, as it modifies the width of the main lobe.
If you just want to get rid of the deep valleys, you can explore the exponential window eventually combined to an Hann window to form a Hann–Poisson window. This window does not feature any side lobes.
Finally, if your signal is periodic and if the length of the frame is a multiple of the period, there is no need for a window!


text:
Q: Running tsc produces errors on React components I made couple of components with props passing, and it works fine, but when I run yarn tsc i get the following errors:
src/modules/BookingsPage/BookingsPage.tsx:52:14 - error TS2322: Type '{ data: { spBookingId: string; flightBooking: string; lastName: string; amount: string; date: string; }[]; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<BookingsTable> & Readonly<{ children?: ReactNode; }>'.
  Property 'data' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<BookingsTable> & Readonly<{ children?: ReactNode; }>'.

52             <BookingsTable data={tableData}/>
                ~~~~~~~~~~~~~

src/modules/BookingsPage/BookingsTable.tsx:44:37 - error TS2339: Property 'data' does not exist on type 'Readonly<{ children?: ReactNode; }>'.

44          <TableRow data={this.props.data}/>
                                       ~~~~

src/modules/BookingsPage/TableRow.tsx:16:11 - error TS2304: Cannot find name 'T'.

16     data: T[];
             ~

Found 3 errors.

Here is my code:
class TableRow:
type IData = {
    data: T[];
  }

export default class TableRow extends PureComponent<IData> {
    public render() {
      const {
        data
      } = this.props;
      const row = data.map((data: any) =>
      <TableBodyRow>
        <TableData>{data.spBookingId}</TableData>
        <TableData>{data.flightBooking}</TableData>
        <TableData>{data.lastName}</TableData>
        <TableData>{data.amount}</TableData>
        <TableData>{data.date}</TableData>
      </TableBodyRow>
      );
      return (
        <>{row}</>
      );
    }
  }

class BookingsTable
export default class BookingsTable extends PureComponent{

  constructor(props: any) {
    super(props);
  }

  public render() {

    return (
      <TableContainer>

        <TableHeadRow>
          <TableHead>Booking id</TableHead>
          <TableHead>Flight Booking</TableHead>
          <TableHead>Last name</TableHead>
          <TableHead>Amount</TableHead>
          <TableHead>Date</TableHead>
        </TableHeadRow>

         <TableRow data={this.props.data}/>

      </TableContainer>
    );
  }
}

And BookingPage:
const tableData = [
  {
    spBookingId: 'Y37HJ',
    flightBooking: 'HJK67',
    lastName: 'DOE',
    amount: '45e',
    date: '2019-02-12',
  },
  {
    spBookingId: 'Y37HJ',
    flightBooking: 'HJK67',
    lastName: 'Johnson',
    amount: '45e',
    date: '2019-02-12',
  },
  {
    spBookingId: 'Y37HJ',
    flightBooking: 'HJK67',
    lastName: 'Madsen',
    amount: '45e',
    date: '2019-02-12',
  },
  {
    spBookingId: 'Y37HJ',
    flightBooking: 'HJK67',
    lastName: 'Doe',
    amount: '45e',
    date: '2019-02-12',
  }
];

interface IbookingsPage{}

const BookingsPage: FunctionComponent<IbookingsPage> = () => {

    return (
        <>
           <Heading>

Bookings

          </Heading>
            <BookingsTable data={tableData}/>

        </>
    );
}

export default BookingsPage;

A: you have the following
type IData = {
    data: T[]; // Error: Cannot find `T`
}

The reason why you are getting the error is because you haven't added T as a generic parameter to IData.
Fix
type IData<T> = {
    data: T[]; // OK
}


text:
Q: Search for a question inside of tags I want to search for all questions containing "tab control" that are also "tagged" c# how do I do this?

A: Search for "[c#] tab control" (no quotes).
There is also a tag for tab controls specifically, which you can filter on that page by C#.
The full search syntax is documented here.


text:
Q: MySQL server query bloom filter I'm looking for some feature or system that allows me to predict whether or not a database query will give different results.
Scenario:
client 1: SELECT * FROM table_x WHERE age >= 18    # at 12:30:00

Then another client updates the database:
client 2: INSERT INTO table_x (age) VALUES (20)   # at 12:31:00

I want something that will respond TRUE to this question, without talking to the database backend:
client 1: didChange('SELECT * FROM table WHERE age >= 18', '12:30:00')

This obviously seems to be quite complex technology. Does anybody know if this exists?
Obviously, this system would have to monitor all the update and insert queries, and keep an in-memory structure that can quickly respond TRUE or FALSE to the didChange()-function..


text:
Q: how to calculate the coordinates on a polyline perpendicular to point (in 3D)? I have two approximately parallel polylines representing railway tracks, consisting of hundreds (maybe thousands) of x, y, z coordinates. The two lines stay approximately 1.435m apart, but bend and curve as a railway would.
If I pick a point on one of the polylines, how do find the point which is perpendicular on the other parallel polyline?

I take it CAD programs use the cross product to find the distance / point and it chooses the line to snap to based on where your mouse is hovering.
I would like to achieve the same thing, but without hovering your mouse over the line.
Is there a way to simply compute the closest line segment on the parallel line? Or to see which segment of the polyline passes through a perpendicular plane at the selected point?
It isn't practical to loop through the segments as there are so many of them.
In python the input would be something like point x, y, z on rail1 and I would be looking to output point x, y, z on rail2.
Many thanks.

A: You want the point of the minimum distance to the other track.
If the other track is defined by line segments, each spanning two points with a parameter t going between 0 and 1
pos(t) => pos_1 + t * ( pos_2 - pos_1 )

You need to find the t value that produces the minimum distance to the point. Place a temporary coordinate system on the point and express the ends of each line segment pos_1 and pos_2 in relative coordinates to the point of interest.
The value of t is for the closest point is
           dot(pos_1,pos_1) - dot(pos_1,pos_2)
t = ------------------------------------------------------
    dot(pos_1,pos_1)-2*dot(pos_1,pos_2)+dot(pos_2,pos_2)

where dot(a,b)=ax*bx+ay*by+az*bz is the vector dot product.
Now if the resulting t is between 0 and 1, then the closest point is on this segment, and its coordinates are given by
pos(t) => pos_1 + t * ( pos_2 - pos_1 )


text:
Q: Replace "cmd" to start Windows Terminal instead of cmd.exe I am now using Windows Terminal as my main terminal on Windows. It's an awesome project.
However, I still have the habit of using win+R, then "cmd", then "Enter".
I'd like to replace the default behavior of "cmd" to start Windows Terminal instead this way:
""%LocalAppData%\Microsoft\WindowsApps\wt.exe" -w 0 new-tab"
I've tried the same method that Notepad++ uses to do it with the debugger entry in registry but Notepadd++ has a specific command to tell him so. When doing the same with cmd, it repeateadly open non-stop because a debugger will try to attach to "cmd". And since "debugger" is wt, it goes into an infinite loop.
I tried adding it here: Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\
Anything I haven't found that could be the answer?
Yes, I know I can use "wt" in run. :)
Thanks.


text:
Q: Set HighStocks x-axis data dynamically I'm trying, if possible, to set HighStocks x-axis data coming from PHP. I googled, looked on highcharts documentation, and looked on here for an answer, but I can't seem to find one.
I'm using CodeIgniter as a PHP Framework, and I have no problem getting the data from the model, and then the controller passes the data to the view. I used HighCharts before, and setting the x-axis for HighChart is really easy.
xAxis: {
     categories: [<?= $high_charts_category_data ?>]

}

How can I do the same thing using HighStocks?
As far as I know, the x-axis can only be a datetime value, and the $high_charts_category_data is an array of datetime with a format of "2014-10-31 11:45:41"
Thanks in advance!


text:
Q: how to make WP7 maps to fill the entire viewing page?     <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
        <Image Margin="0" Grid.RowSpan="2" Source="Images/map_bg.jpg" Stretch="Fill"/>
        <my:Map Height="649" HorizontalAlignment="Left" Name="map1" VerticalAlignment="Top" Width="451" LogoVisibility="Collapsed"  Margin="2,0,0,0" />
    </Grid>

i tried to play abit with the Height and Width variables but that only changed the position of the map rather than stretching the entire maps.
is it possible at all to make the map to 'fill' the entire  <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> property?
thanks!
edit
 <Grid x:Name="LayoutRoot" Background="Transparent" Opacity="0.7">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <!--TitlePanel contains the name of the application and page title-->
        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28"></StackPanel>

        <!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <Image Margin="0" Grid.RowSpan="2" Source="Images/map_bg.jpg" Stretch="Fill"/>
            <my:Map Name="map1" VerticalAlignment="Top" Width="451" LogoVisibility="Collapsed"  CredentialsProvider="xxx" Margin="2,0,0,0" Height="645" />
        </Grid>
    </Grid>

A: I removed all margins/size/positioning elements in my map control to let it expand itself.
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
    <my:Map CredentialsProvider="abcdefg"  Name="map1"   >
        <my:MapLayer Name="mapLayer"/>
    </my:Map>
</Grid>


text:
Q: Python-LDAP authentication on Windows 7 I would like to install Flask-LDAP to my computer (Windows 7) which has a prerequisite called python-ldap.
I tried to install according to this one:
https://pypi.org/project/python-ldap/3.1.0/
Error message on pip install:
C:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\ucrt\corecrt.h(10) : fatal error C1083: Cannot open include file: 'vcruntime.h': No such file or directory
error: command 'C:\\Users\\...\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++ for Python\\9.0\\VC\\bin\\x86_amd64\\cl.exe' failed with exit status 2

Windows SDK 7,10 installed.
Also I am not sure what is going to happen after, because OpenLDAP setup executable asks for serial. I couldnt find a version which can be installed on Windows. Visual C++ is also installed, I didnt find anything related to missing vcruntime.h. There is no file like this on my whole machine.
Could someone help me with a guide how to proceed?
Thank you in advance.

A: You have no C++ Compiler for Python, try to install it in windows:
this is Microsoft Visual C++ Compiler for Python 2.7, if your python version is 2.7, you can install python-ldap successfully after install vc compiler in windows


text:
Q: error installing waitr in ubuntu 11.10 ruby ubuntu rubygems wati automation testing tool watir in the newest version of Ubuntu.
I did a sudo apt-get install ruby to get the latest version of ruby, then I installed Rubygems and tried installing watir, but i'm getting this error.
It's using Ruby 1.8.7
I've also tried removing ruby and ruby gems and reinstalling but the error message still happens.
Can anyone tell me whats wrong?
root@kelley-VirtualBox:/home/kelley# gem -v
bash: /usr/bin/gem: No such file or directory
root@kelley-VirtualBox:/home/kelley# sudo apt-get install rubygems
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following package was automatically installed and is no longer required:
  libtcltk-ruby1.8
Use 'apt-get autoremove' to remove them.
The following NEW packages will be installed:
  rubygems
0 upgraded, 1 newly installed, 0 to remove and 2 not upgraded.
Need to get 0 B/425 kB of archives.
After this operation, 4,166 kB of additional disk space will be used.
Selecting previously deselected package rubygems.
(Reading database ... 157806 files and directories currently installed.)
Unpacking rubygems (from .../rubygems_1.7.2-1_all.deb) ...
Processing triggers for man-db ...
Setting up rubygems (1.7.2-1) ...
root@kelley-VirtualBox:/home/kelley# gem list

*** LOCAL GEMS ***

root@kelley-VirtualBox:/home/kelley# gem install watir
Building native extensions.  This could take a while...
ERROR:  Error installing watir:
    ERROR: Failed to build gem native extension.

        /usr/bin/ruby1.8 extconf.rb
checking for strncpy_s()... no
creating Makefile

make
gcc -I. -I. -I/usr/lib/ruby/1.8/i686-linux -I. -D_FILE_OFFSET_BITS=64  -fPIC -fno-strict-aliasing -g -g -O2  -fPIC   -c win32/api.c
win32/api.c:2:21: fatal error: windows.h: No such file or directory
compilation terminated.
make: *** [api.o] Error 1

Gem files will remain installed in /usr/lib/ruby/gems/1.8/gems/win32-api-1.4.8 for inspection.
Results logged to /usr/lib/ruby/gems/1.8/gems/win32-api-1.4.8/ext/gem_make.out
root@kelley-VirtualBox:/home/kelley#

A: Look at the Ubuntu documentation. There's a comprehensive, step-by-step guide that you can follow.
It seems like waitr is Windows-only. Try sudo gem install watir-webdriver


text:
Q: Bad characters printed in a queue in C I'm trying to print a queue with a char array in its struct.
I just read a text file with some web address, push into the queue and try to print. The first 4 lines are ok but then it begin to print bad characters in almost all the others. I don't know whats going on. Even if I print direcly the char array from fgets it is correctly printed and the queue is correctly printed as well, so...I'm confused...
Any idea?
Here is the relevant code:
structs:
typedef struct n_queue {
    char *web;
    struct n_queue *next;
} QUEUE_NODE, *P_QUEUE_NODE;

typedef struct k_queue {
    P_QUEUE_NODE head;
    P_QUEUE_NODE tail;
} kind_queue;

Reading the file:
void readFile(kind_queue *q) {
    char data[9][150];
    FILE *f=fopen("list.txt", "r");
    if (f == NULL) perror("Web list couldn't be found.");
    int j =0;
    int i;

    while (fgets(data[j],150, f)!=NULL) {
            //If I uncomment the line below, both char array and char array in queue
            //are printed allright
        //printf("%s", data[j]);

            //Supress the new line char
        for (i=0;i<150;i++) {
            if (data[j][i] == '\n') {
                data[j][i]='\0';
                break;
            }
        }

        push_queue(q, data[j]);
        j++;
    }

    fclose(f);
}

Push code:
void push_queue(kind_queue *q, char *web){
    P_QUEUE_NODE p;
    p = (P_QUEUE_NODE) malloc(sizeof(QUEUE_NODE));
    p->next = NULL;
    p->web = web;
    if (is_empty(q)) q->tail = q->head = p;
    else{
        q->tail->next= p;
        q->tail = p;
    }
}

Main function:
int main () {

    kind_queue queue, *pt_queue_struct;
    pt_queue_struct = &queue;
    pt_queue_struct = init_queue(pt_queue_struct);
    readFile(&queue);

    print_queue(&queue);

    return(0);
}

And finally the print function:
void print_queue(kind_queue *q) {
    P_QUEUE_NODE paux;
    int j=1;
    for (paux=q->head; paux != NULL; paux=paux->next) {
        printf("%d: %s\n", j, paux->web);
        j++;
    }
}

REAL TXT:
http://www.google.es
http://stackoverflow.com
http://www.facebook.com
http://akinator.com/cea
http://developer.android.com/map
http://tirsa.es/65/65.htm
http://www.ufo.es/
http://thisty.com/init/
http://damned-c.me/

OUTPUT:
1: http://www.google.es
2: http://stackoverflow.com
3: http://www.facebook.com
4: http://akinator.com/cea
5:
6:
7: http://www.ufo.es/
8: http:/(dU[~
9: (dU[~

A: The data read in is stored in a local variable data which goes out of scope when readFile exits. This would be ok provided the data is copied into the node structure. Currently the node data pointer just points to the local variable storage.


text:
Q: Collections sort doesnt work to me I tried to use Collections.sort and it is working until I want it to sort between double variables
price is the double variable...
@Override
public int compareTo(Product p) {
    double lastCmp = this.price.compareTo(p.getPrice());
    return (lastCmp != 0 ? lastCmp : this.price.compareTo(p.getPrice()));
}

  public void OrganizeByLowestPrice(Basket basket) {
    ArrayList<Product> products1 = basket.getBasket();
    Collections.sort(products1, new Comparator<Product>() {
        @Override
        public int compare(Product product, Product t1) {
            return product.getPrice().compareTo(t1.getPrice());
        }
    });
}

https://pastebin.com/6VxhzSRG
I added the code for Product.
problem stays the same.
It once worked for me but now as I am recovering lost codes its not.

A: So the real problem here is compilation errors.  The germane ones are these:
Product.java:51: error: double cannot be dereferenced
    double lastCmp = this.price.compareTo(p.getPrice());
                               ^
Product.java:52: error: double cannot be dereferenced
    return (lastCmp != 0 ? lastCmp : this.price.compareTo(p.getPrice()));
                                               ^
Product.java:52: error: incompatible types: possible lossy conversion from double to int
    return (lastCmp != 0 ? lastCmp : this.price.compareTo(p.getPrice()));
                         ^

These are straight forward:

*

*The first error occurs because you are trying to invoke a method (compareTo) on a double.  That is not valid Java. Primitive types don't have methods.

*The second error occurs for the same reason as the first

*The final error occurs because (lastCmp != 0 ? lastCmp : this.price.compareTo(p.getPrice())) produces a double, but the
Product::compareTo method must return an int.  So the return statement is attempting convert the double to an int.  But a conversion from double to int is lossy, and the Java language requires an explicit type cast to do that.
Solution:

*

*The lastCmp variable should not be a double.  It should be an int.

*If you want to compare two double values, use the static Double::compare method; e.g.
  int lastCmp = Double.compare(this.price, p.getPrice());

A: You can use lambda simply.
public void OrganizeByLowestPrice(Basket basket) {
    ArrayList<Product> products1 = basket.getBasket();
    Collections.sort(products1, (a,b)->{
        return Double.compare(b.getPrice(),a.getPrice());
    });
}

It sorts the list in decreasing order on the basis of price.


text:
Q: JSON deserialization in C# sub array I'm trying to desearialize the following using Newtonsoft.Json
{
    "max_id_str":"1234567",
    "results":[{
        "created_at":"Tue, 21 May 2013 03:06:23 +0000",
        "from_user":"Name Here",
        "from_user_id":33333,
        "text":"THE TEXT GOES HERE"
    }],
    "results_per_page":1,
    "since_id":0,
    "since_id_str":"0"
}

I can retrieve the max_id_str using desearialization but cannot get any of the data in "results"
Here's the code I have
public class tweet
    {
        public string max_id_str { get; set; }
        public string text{ get; set; }
        public string results_per_page{ get; set; }
        public string since_id { get; set; }
        public string since_id_str { get; set; }
    }

I then create an object of the class and attempt to desearlize it into the object
tweet t = new tweet();
t = JsonConvert.DeserializeObject<tweet>(e.Result);

Everything but "text" populates? Text's value is null when I output the value. Any ideas how to accomplish what I'm trying?

A: I'm not sure what you're expecting to get deserializing that JSON string to that type, text is not a property of the object so there's no reason to expect it to do so like that.  text is a property of the objects within the results list.  You need to map those objects as well and then access the text through the result objects.
public class tweet
{
    public string max_id_str { get; set; }
    //public string text{ get; set; }
    public List<result> results { get; set; }
    public string results_per_page{ get; set; }
    public string since_id { get; set; }
    public string since_id_str { get; set; }
}

public class result
{
    public string created_at { get; set; }
    public string from_user { get; set; }
    public int from_user_id { get; set; }
    public string text { get; set; }
}

If you were trying to use the values within results to determine the value of your text property, you could write a converter to extract the text value.  Just add a JsonProperty and JsonConverter attribute to your text property and implement the converter.
public class tweet
{
    public string max_id_str { get; set; }
    [JsonProperty("results")]
    [JsonConverter(typeof(TextPropertyResultExtractorConverter))]
    public string text { get; set; }
    public string results_per_page{ get; set; }
    public string since_id { get; set; }
    public string since_id_str { get; set; }
}

public class TextPropertyResultExtractorConverter : JsonConverter
{
    public override bool CanConvert(Type type)
    {
        throw new NotImplementedException();
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var results = (JArray)serializer.Deserialize(reader);
        var result = results.First();
        return result.Value<string>("text");
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

A: It's because text is a child element, whereas in your C# object you're having it directly in tweet. You're missing the results object as a property. There is no way for the deserializer to know where to place those values (there are no corresponding properties).


text:
Q: How can I use a script to control another application? For example, I want to write a script to control and automate a sequence of steps in an application. How can I communicate between my script and the application I want to automate?

A: You need a macro recorder.  Google "Windows Macro Recorder" or "Mac Macro recorder" or KDE macro recorder.
Specific software like MS Excel, AutoCAD, and others have built in macro recorders.
In Windows if you are willing to spend a bunch of time learning how you can use vba scripting to access Windows API.
The software may have user accessible API making your job easier.


text:
Q: Can we use tf-idf and cosine similarity for document recommendation system? The document dataset is having 9000 documents and its growing day by day, most of the documents having average 1-3 paragraphs.
The idea is to make a recommendation with the help of user's past usage of documents.
Lets say the dataset is having 10 documents (main corpus) in total and out of them 4 related to sports, 2 related to Fashion, 4 related to technology.
Now if say user x has read 2 sports and 1 technology related documents then to get the tf-idf of the user x we will combine these 3 documents and assume it as user x corpus.
Now get the tf-idf of the 10 documents (main corpus) which will get us the individual tf idf vector of all those 10 documents.
Now compare the cosine similarity of user x corpus with the main corpus (10 document)
Result should be 2 sports document and 1 technology document which user x has not yet read.
Let me know if this idea makes sense.


text:
Q: Can i import my primary key in Neo4j with CSV I'm importing CSV files to Neo4J, but Neo4J doesn't import my primary key.
I'm using this:
LOAD CSV WITH HEADERS FROM "file:///C:/c/tabela_sujeito.csv" AS row
CREATE(:Sujeito{suj_ID:row.id, idade:row.idade, altura:row.altura, peso:row.peso, genero:row.genero, mao_dominante:row.mao_dominante});

suj_ID is my primary key, and it isn't imported, unlike the other attributes.

A: As suggested by @InverseFalcon, You need to use row.suj_ID instead of row.id  in your query.
LOAD CSV WITH HEADERS FROM "file:///C:/c/tabela_sujeito.csv" AS row
CREATE(:Sujeito{suj_ID:row.suj_ID, idade:row.idade, altura:row.altura, peso:row.peso, genero:row.genero, mao_dominante:row.mao_dominante});


text:
Q: flux: view doesn't refresh after store update I study FLUX and try to write simple example on it. It is about a menu where I can select every single item (it is marked by (*)). So, here is main excerpts of the code:
AppContainer.js:
class AppContainer extends React.Component
{
    static getStores() {
        return [MenuStore];
    }
    static calculateState(prevState) {
        return {
            menu: MenuStore.getState(),
            onclick: Actions.onclick
        };
    }
    render() {
        return <MenuView onclick={this.state.onclick} menu={this.state.menu.get('list')} cur={this.state.menu.get('cur')} />;
    }
}

MenuStore.js
class MenuStore extends ReduceStore{
    constructor() {
        super(MenuDispatcher);
    }
    getInitialState() {
        // return {list: ["About", "Contacts", "Price", "Home"], cur: 0};
        return Immutable.Map({list: ["About", "Contacts", "Price", "Home"], cur: 2});
    }

    reduce(state, action) {
        switch (action.type) {
            case ActionTypes.ON_CLICK:
                console.log('MenuStone ON_CLICK');
                state.cur = action.index;
                return state;
            default:
                return state;
        }
    }
}

MenuView.js:
class MenuView extends React.Component{

    constructor(props){
        super(props);
    }
    render(){
        return <ui>{this.props.menu.map((menu, index) => {
                var active = (this.props.cur === index) ? true : false;
                return <MenuItem onclick={this.props.onclick} key={index} index={index} active={active} label={menu} />;
            })}</ui>;
    }
}

class MenuItem extends React.Component {
    constructor(props) {
        super(props);

        this.state = {label: props.label};
        this.click = this.click.bind(this);
    }

    click(index) {
        console.log('MenuItem click');
        this.props.onclick(this.props.index);
    }

    render() {
        var mark = '';
        if (this.props.active)
            mark = '(*) ';
        return
{mark}{this.state.label}
;
    }
}

Actions.js:
const Actions = {
    onclick(index) {
        console.log('Actions.onclick');
        MenuDispatcher.dispatch({
            type: ActionTypes.ON_CLICK,
            index,
        });
    }
};

When I run the code, it is work fine until I click a menu item. The code
state.cur = action.index;
executes, but nothing changes on the page.
What should I do to update the views?


text:
Q: Natural embedding of a real vector space $V$ into $V_\Bbb{C}=V\otimes\Bbb{C}$ is injective Let $V$ be a real vector space and $V_\Bbb{C}=V\otimes_\Bbb{R} \Bbb{C}$ denotes the complexification. I want to identify $V$ as a real vector subspace of $V_\Bbb{C}$. I define the natural embedding map $v\mapsto v\otimes 1$ which is $\Bbb{R}$ linear from $V$ to $V_\Bbb{C}$. But I cannot show this to be injective i.e. $v\otimes 1=0 $ implies $v=0$. Maybe I'm missing something very silly.
Can anyone help me in this regard?

A: In general injectivity and tensor products of modules is quite tricky. But with vector spaces, everything works out fine (because they are free, and therefore flat).
Actually, if $V$ and $W$ are two vector spaces over a field $K$, then $v\otimes w=0\in V\otimes_K W$ if and only if either $v$ or $w$ is zero.
You can show this by extending $v$ (resp. $w$) to a basis $(e_i)$ (resp. $(f_j)$) of $V$ (resp. $W$), if they are both non-zero. Then $v\otimes w=e_1\otimes f_1$, but you can show that $(e_i\otimes f_j)$ is a basis of $V\otimes_K W$, so in particular these tensors are definitely not zero.
Try to show that $(e_i\otimes f_j)$ is indeed a basis!


text:
Q: C# Quartz.net : do RescheduleJob and UnscheduleJob stop currently executing jobs? From what little i could find, it seems that the RescheduleJob and UnscheduleJob methods of the scheduler stop jobs if the jobs are executing at the time the methods are called.
However that is only conjecture. I need confirmation about this.
Do those methods stop the execution of jobs they are called on?


text:
Q: Check if the facebook session is valid I am trying to check if the facebook session is valid or not, it can occure because:

*

*The session has expired.

*User has logged off.

*User has deleted my facebook application.

*User no longer exists.

I have this method to check if the user is still logged in:
public boolean isLoggedIn() {
    Session session = Session.getActiveSession();
    if (session != null && session.isOpened()) {
        return true;
    } else {
        return false;
    }
}

But it returns true even if the user has removed my app from his facebook account.
When I call any facebook request I get the following response from facebook:
08-14 12:20:40.671: I/facebookActivity(2322): Result: {Response:  responseCode: 400, graphObject: null, error: {HttpStatus: 400, errorCode: 190, errorType: OAuthException, errorMessage: Error validating access token: User 343343434 has not authorized application 45345345.}, isFromCache:false}

After that every request I make to facebook I get a different response :
08-14 12:21:09.707: I/facebookActivity(2322): Result: {Response:  responseCode: 200, graphObject: null, error: {HttpStatus: -1, errorCode: -1, errorType: null, errorMessage: null}, isFromCache:false}

I can check the JSON for errors and try to create a new Facebook Session, but I want to avoid doing so before making any facebook requests or atleast call it once when the activity starts to check if the session is valid.
Is there a normal way to check whether a session is valid?

A: When you open a session from cached information (normally done automatically for you), there's no server requests made to Facebook, which is why the Session object itself has no idea whether it's still valid or not.
The only way to know that an access token has been invalidated (for any reason) is to make a graph request. You can either make a graph request every time you open a new session (to /me or even /me/permissions), or you can have your app proceed as normal, and perform the error handling steps outlined here when an error occurs (note that a session/access token can become invalid at any time - even in the middle of running your app - so you should have proper error handling regardless).


text:
Q: Strange pixelated Chromium in 18.04 After I installed Ubuntu 18.04, I started having this weird problem with Chromium browser (see screenshots). It does not appear all the time however. It happens often when I maximize Chromium from minimized (I forgot if it ever happened when I start Chromium). It goes away sometimes by just scrolling the page, changing tab, or minimizing-maximizing Chromium again.

So far, only Chromium seems to have this problem. Firefox and other software I am using seem to be fine.
So, how do I fix this? Thanks.
EDIT: I don't know if it's relevant, but I am using AMD RX-550 graphics card with built-in Ubuntu drivers (i.e. I did not install any additional driver).
EDIT AGAIN: This problem seems to have stopped after I disabled hardware acceleration in Chromium settings. But still, I wonder why it happens with hardware acceleration enabled.

A: The RX550 is on the gpu blacklist, see https://wiki.archlinux.org/index.php/Chromium#Force_GPU_acceleration
I have the same issue since 17.10 with the RX550. It's a mess.


text:
Q: Change text using onmouseover on an image? I'd like the text to change depending on which image the user is hovering over. I thought I had the right idea, but the code doesn't work.
http://jsfiddle.net/6V2TL/
HTML

some text 1

JS
function change1() {
     document.getElementById("test").innerHTML = "this is a cute cat";
}
function change2() {
     document.getElementById("test").innerHTML = "this is a cuter cat";
}

Thanks

A: Your code is inside and onLoad handler, it can't be run from the page. The first dropdown on the left changes this, please select "no wrap (head)" from the list.
Demo: http://jsfiddle.net/SO_AMK/35s4C/

function change1() {
  document.getElementById("test").innerHTML = "this is a cute cat";
}

function change2() {
  document.getElementById("test").innerHTML = "this is an angry cat";
}

  some text 1

A: If you look in the console you'll see yours throws Errors about not finding the functions when you hover.
JFiddle by default loads the code in the Javascript box after the page has loaded with a special handler, you want to change it to put the code in a non-wrapped form so when the body hovers happen the functions actually exist globally so they can be accessed: http://jsfiddle.net/6V2TL/3/
It is in the options on the left in the toolbar.

A: Your javascript methods onchange1,onchange2 is not calling on onmouseover event. You can try this link
http://jsfiddle.net/6V2TL/5/ .

A: There is something wrong with the JSfiddle site it looks.  I moved the js to the HTML window and it worked.  But your code works.
http://jsfiddle.net/6V2TL/9/


text:
Q: EOCD not found, not Zip,shows error when install apk When I am trying to install apk through command prompt it shows an error like this
daemon not running. starting it now on port 5037
daemon started successfully
EOCD not found, not Zip
file 'com.directv.dvrscheduler_v2.1.1.apk' is not a valid zip file
rm failed for /data/local/tmp/com.directv.dvrscheduler_v2.1.1.apk, No such file
or directory

help me.

A: This problem occurs when problem in downloading apk. You may transfer apk statically or storage device, and try again, Hope it will help you. I faced this problem, after transferring apk on skype, i solved my issue.


text:
Q: Opening URL inside visual basic form I would like to open webpage in VB form, however in ToolBox, there is missing WebBrowser. Could someone help me, where is the problem? I am creating project

In list of tools there is nothing with

A: Are you sure you are using the correct windows forms?
This is what I use

A: WebBrowser control is not available in .NET5 or later versions. As an alternative, you should use Webview2 control. See : How to use new WebBrowserControl in .Net 5
If your project only target windows, you can use WebBrowser control by creating a .NET Framework project.

A: Since you cannot use webview in win forms anymore. Please try this code :)
Dim webAddress As String = "http://www.example.com/" \
Process.Start(webAddress)


text:
Q: What is this random space under my div and how do I remove it? I'm making a rectangle card with a graph on it. I've moved it to the right using the transform and left property. I've tried all sorts of things but nothing seems to fix it.

* {
  margin: 0;
  padding: 0;
}

body {
  font-family: Roboto, sans-serif;
  background-color: #D7DBDD;
}

#chart {
  position: relative;
  top: 10%;
  left: 50%;
  transform: translate(0%, -73%);
  max-width: 47vw;
}

#rectangle {
  position: relative;
  left: 50%;
  transform: translate(-2%, 25%);
  width: 49vw;
  height: 63vh;
  background: #ECF0F1;
  border-radius: 10px;
  box-shadow: 20px 20px 50px 15px #BDC3C7;
  max-width: 100%;
}

All help would be appreciated and I am still learning CSS so please keep that in mind.
Screenshot:


text:
Q: WPF TextBox value doesn't change on OnPropertyChanged I have a TextBox whose Value is binded to a ViewModel property:
        <TextBox Name="txtRunAfter" Grid.Column="4" Text="{Binding Mode=TwoWay, Path=RunAfter}" Style="{StaticResource TestStepTextBox}"/>

The set and get were working fine until I tried to add some validation when the Value is set:
    private int _runAfter = 0;
    public string RunAfter
    {
        get
        {
            return _runAfter.ToString();
        }

        set
        {
            int val = int.Parse(value);

            if (_runAfter != val)
            {
                if (val < _order)
                    _runAfter = val;
                else
                {
                    _runAfter = 0;
                    OnPropertyChanged("RunAfter");
                }
            }
        }
    }

Although the OnPropertyChanged is reached (I have dubugged that), the View is not changed.
How can I make this work?
Thanks,
José Tavares

A: The problem is that you are updating the source for the Binding while the Binding is updating your property.  WPF won't actually check your property value when it raises the PropertyChanged event in response to a Binding update.  You can solve this by using the Dispatcher to delay the propagation of the event in that branch:
set
{
    int val = int.Parse(value);

    if (_runAfter != val)
    {
        if (val < _order)
        {
            _runAfter = val;
            OnPropertyChanged("RunAfter");
        }
        else
        {
            _runAfter = 0;
            Dispatcher.CurrentDispatcher.BeginInvoke(
                new Action<String>(OnPropertyChanged),
                DispatcherPriority.DataBind, "RunAfter");
        }
    }
}

Update:
The other thing I noticed is that the Binding on your TextBox is using the default UpdateSourceTrigger, which happens when the TextBox loses focus.  You won't see the text change back to 0 until after the TextBox loses focus with this mode.  If you change it to PropertyChanged, you will see this happen immediately.  Otherwise, your property won't get set until your TextBox loses focus:
<TextBox Name="txtRunAfter" Grid.Column="4" Text="{Binding RunAfter, UpdateSourceTrigger=PropertyChanged}" Style="{StaticResource TestStepTextBox}"/>

A: A few things I noticed here.
Unless you have a compelling reason to expose the RunAfter property as a string, there's no reason why it can't be an int.  That would save you the cast in the setter (as well as a lurking possible InvalidCastException if the user enters something non-integer in the field).
Secondly, the OnPropertyChanged() call should occur outside of the inner if statement, like the following:
if(_runAfter != val)
{
    if(val < _order)
        _runAfter = val;
    else
        _runAfter = 0;
    OnPropertyChanged("RunAfter");
}

Since the _runAfter local is being updated in both paths of the conditional, the OnPropertyChanged() has to be called regardless of the branch taken.  I hope that helps point you in the right direction!

A: I had the same situation. I wrote the following and it worked.
<TextBox Grid.Column="3" Grid.Row="0" HorizontalAlignment="Left" VerticalAlignment="Center" Width="100" Text="{Binding Path=FirstName}"></TextBox>
And
public string FirstName
    {
        get { return _client.FirstName; }
        set
        {
            if (value == _client.FirstName)
                return;
            else
                _client.FirstName = value;
            OnPropertyChanged("FirstName");
        }
    }


text:
Q: How do i view the local database version in safari on the iphone? I am trying to see the localDatabase version from my iPhone in safari but it is not displaying, according to the docs i am supposed to be able to do this:
var db = openDatabase('dbShortName', '', 'dbLongName', 1000);
alert(db.version);

and it should alert the current version number. It does not. It works in Chrome and safari for the desktop but not the iPhone. Does anybody have some idea why?
My next option is to store the version in a separate table, but I would prefer to use the built in system. Thanks in advance.

A: On your iPhone, if you go to Settings and scroll down to Safari, there's a Databases button which shows you the current databases on the phone. Does the database you're trying to open definitely exist?


text:
Q: Which site is showing in the WebView on an app So I have this app and I am convinced they use a WebView to show a website. But, how can I find which page (URL) they are showing inside the app?

A: You can't do that.
You might be lucky with watching logcat, if they print out some info for the sake of debugging.


text:
Q: Callback for change() method which called an ajax example of code with jQuery ALL THIS HTML PART IS LOADED via ajax too:
<button> Lets Go </button>

<select id='first'>
    <option value='1'> 1 </option>
    <option value='2'> 2 </option>
    <option value='3'> 3 </option>
</select>

<select id='second'>
</select>

$('button').click(function(){
    $('#first option[value=1]').prop('selected',true);// WORK
    $('#first').change();     //   WORK
    $('#second option[value=1]').prop('selected',true);// this DONT WORK
    $('#second').change();
});

The problem is here, it tries to select option but the data is not loaded yet via ajax so it doesn't have what to select. How can I use call back on $('#first').change(); to waiting for data load and after go next?
$('body').on('change','#first',function(){
    // on "#first" change the "#second" select automaticaly filled with code via ajax;

so will be now like
<select id='second'>
    <option value='1'> 1 </option>
    <option value='2'> 2 </option>
    <option value='3'> 3 </option>
</select>

})

$('body').on('change','#second',function(){
   //   console.log() doesn't see the selected value
});

A: If I understand your question correctly, you've assigned a change event listener to the first select element whose handler performs an AJAX request. AJAX requests being inherently Asynchronous means that code which depends on the result of the AJAX request must wait until the request completes.
So, you've got something like this: (not really, but this is a working example that makes a bit more sense)

const select = document.querySelector('select');
const wrapper = document.querySelector('#wrapper');
const button = document.querySelector('button');

const simulHTML = v => `<div class="example">Example #${v}</div>`;
const simulAJAX = v => new Promise(r => setTimeout(_ => r(simulHTML(v)), 400));

$(select).change(async e => wrapper.innerHTML = await simulAJAX(e.target.value));
$(button).click(e => {
  select.value = "1";
  $(select).change();
  console.log(wrapper.innerHTML); // ""
});

<select>
  <option disabled selected>---
  <option value="1">1
  <option value="2">2
  <option value="3">3
</select>
<button>button</button>

Once it comes time to work with the HTML inserted by the AJAX callback, we see that the result hasn't arrived yet.
Now, there are a few ways to deal with this ranging from quick and dirty (and unsafe) to the more complex (but safer). Here's a middle ground, and what I would generally choose.
First, an IIFE to keep the logic safe from the rest of the page. In this we will define a Set to hold listeners, enclose the definition of our change listener, execute the listeners once the AJAX request has completed, and finally provide a mechanism for adding and removing listeners.
const listen = (_ => {
  const listeners = new Set();

  $(select).change(async e => {
    wrapper.innerHTML = await simulAJAX(e.target.value);
    listeners.forEach(e => e());
  });

  return {
    add: (...args) => listeners.add.bind(listeners)(...args),
    delete: (...args) => listeners.delete.bind(listeners)(...args)
  }
})();

Next, to use what we just made, simply use the add and delete methods of the new listen object.
const listener = _ => {
    console.log(wrapper.innerHTML);
    listen.delete(listener); // remove after
}
listen.add(listener);

Here's a full working example:

const select = document.querySelector('select');
const wrapper = document.querySelector('#wrapper');
const button = document.querySelector('button');

const simulHTML = v => `<div class="example">Example #${v}</div>`;
const simulAJAX = v => new Promise(r => setTimeout(_ => r(simulHTML(v)), 400));

const listen = (_ => {
  const listeners = new Set();

  $(select).change(async e => {
    wrapper.innerHTML = await simulAJAX(e.target.value);
    listeners.forEach(e => e());
  });

  return {
    add: (...args) => listeners.add.bind(listeners)(...args),
    delete: (...args) => listeners.delete.bind(listeners)(...args)
  }
})();

$(button).click(e => {
  select.value = "1";
  $('select').change();

  const listener = _ => {
    console.log(wrapper.innerHTML);
    listen.delete(listener); // remove after
  }

  listen.add(listener);
});

<select>
  <option disabled selected>---
  <option value="1">1
  <option value="2">2
  <option value="3">3
</select>
<button>button</button>


text:
Q: Dynamicaly add and save in localStorage inputs via jQuery or Laravel/PHP I am using laravel, I want to dynamically add fields for product properties. The product is added via submit, so if an error occurs, all additional fields disappear. Also, when editing, I need to display them somehow. What is the best way to save them? Via localStorage or does Laravel/PHP have other methods?
P.S. Here the snippet gives an error for some reason. Possibly due to localStorage.

$(document).ready(function(){

  if(localStorage.getItem("all")){
      $('#newRow').append(localStorage.getItem("all"));
    }
  $("#addRow").click(function () {
          var html = '';
          html += '
';
          html += '
';
          html += '<input type="text" name="properties[key]" class="form-control m-input" placeholder="Key" autocomplete="off">';
          html += '<input type="text" name="properties[value]" class="form-control m-input ml-3" placeholder="Value" autocomplete="off">';
          html += '
';
          html += '<button id="removeRow" type="button" class="btn btn-danger">Delete</button>';
          html += '
';
          html += '
';

          $('#newRow').append(html);

          var allfields = [];
          allfields.push(html);

          localStorage.setItem("all", allfields);
      });

    // remove row
    $('#removeRow').on('click', function () {
        $(this).closest('#inputFormRow').remove();
    });
  });

<link href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" rel="stylesheet"/>

                  Product properties:

                                  <input type="text" name="properties[key]" class="form-control m-input" placeholder="Key" autocomplete="off">
                                  <input type="text" name="properties[value]" class="form-control m-input ml-3" placeholder="Value" autocomplete="off">

                                      <button id="removeRow" type="button" class="btn btn-danger">Delete</button>

                          <button id="addRow" type="button" class="btn btn-info">Add</button>

A: It's possible, firstly, you have to use array of array, or it just make more sense.
Your input:
<input type="text" name="properties[][key]" class="form-control m-input" placeholder="Key" autocomplete="off">
<input type="text" name="properties[][value]" class="form-control m-input ml-3" placeholder="Value" autocomplete="off">

now you will have array, which contains arrays with two keys, "key" and "value".
So after submit in your controller you can simply store your $request->properties in session before validation!
$request->session()->flash('properties', $request->properties)

or just global helper
session()->flash('properties', $request->properties)

after flash() method data will be available only next request, after that, they will be automatically deleted
then if you have error, you can do in view something like that:
@if(session->has('properties'))
@foreach (session('properties') as $prop)
<input type="text" name="properties[][key]" value="{{$prop['key']}}" class="form-control m-input" placeholder="Key" autocomplete="off">
<input type="text" name="properties[][value]" value="{{$prop['value']}}" class="form-control m-input ml-3" placeholder="Value" autocomplete="off">
@endforech
@endif


text:
Q: How to search sentence in multi page document in Swift? I have multi page document and i want to find page number for specific sentence.
I've tried to find with contains method but If the last sentence splits over two pages, it does not find the page number.
My code is:
func getPageNumber(sentence: Sentence) -> Int {
    let pages = document.pages
    for (index, page) in pages.enumerated() {
        guard let sentenceText = sentence.all else { return 0 }
        if page.text.contains(sentenceText) {
            return index
        }
    }
    return 0
}

Example Usage
Page 1
Ullamcorper a lacus vestibulum sed arcu non. Nec ullamcorper sit amet risus. Donec ac odio tempor orci dapibus ultrices. Non consectetur a erat nam at lectus urna. Cursus vitae congue mauris rhoncus aenean vel elit scelerisque. Maecenas accumsan lacus vel facilisis volutpat est velit egestas dui. Justo donec enim
Page 2
diam vulputate ut. Sed augue lacus viverra vitae. Eget duis at tellus at urna condimentum mattis. Convallis posuere morbi leo urna molestie at elementum eu. Sed tempus urna et pharetra pharetra massa massa.
If i want to find "Nec ullamcorper sit amet risus." it returns page 1. But if I want to find  Justo donec enim diam vulputate ut. it is not returning page1 and page2.
How can i achieve this efficently?
Thanks.

A: If it wasn't multi page then you could easily search all occurrences, and get back an array of matching ranges. To make it multi page you could just add page break indexes (which form ranges 0..p1..p2..end). Now, given a match range, you can see which cross which page breaks, and which are contained with a single page.


text:
Q: Simulate static ips in a private netwrok This is the context:
We are trying to monitor via SNMP a set of devices. Unfortunately, all our solutions monitor by IP, and this set of devices change ips regularly (doesn't matter why, think of it as business rules). Once ip is changed, monitoring is lost and it's a problem.
What we seek:
We want to put a layer between the monitoring tool and the devices, the layer receives the query towards a certain static IP and the layer translates it to the current ip of the device assigned to that static IP (kindn of an alias IP).
Is there any tool that does something like that?


text:
Q: AWS Appsync with Athena, do i need to create a resolver Im looking using Athena in front of S3, spanning a single bucket but multiple folders with data in zip.
I intend to use Appsync in front Athena, form looking at the some documentation and examples, i wasnt sure if a resolver is needed in front athena, In fact i didnt fully grasp why a  resolver would be needed?
Any helpful information and explanation is welcome


text:
Q: Почему нет валидации в Angular 7? Создаю форму в ангуляре, делаю валидацию примерно так
<input name="Name" #Name="ngModel" [(ngModel)]="service.formData.Name"
        class="form-control" placeholder="Mission naming" required maxlength="100">

Насколько я понимаю, после валидации в инпуте должны быть ng-invalid и ng-touched , но их нет, после компиляции код инпута такой
<input class="form-control" maxlength="100" name="Name" required="" ng-reflect-required="" ng-reflect-maxlength="100">

В чем может быть проблема?


text:
Q: simple question about assigning float to int This is probably something very simple but I'm not getting the results I'm expecting. I apologise if it's a stupid question, I just don't what to google for.
Easiest way to explain is with some code:
int var = 2.0*4.0;

NSLog(@"%d", 2.0*4.0);//1
NSLog(@"%d", var);//2

if ((2.0*4.0)!=0) {//3
    NSLog(@"true");
}

if (var!=0) {//4
    NSLog(@"true");
}

This produces the following output:
0   //1
8   //2
true    //3
true    //4

The one that I don't understand is line //1. Why are all the others converting (I'm assuming the correct word is "casting", please correct me if I'm wrong) the float into an int, but inside NSLog it's not happening. Does this have something to do with the string formatting %d parameter and it being fussy (for lack of a better word)?

A: You're telling NSLog that you're passing it an integer with the @"%d" format specifier, but you're not actually giving it an integer; you're giving it a double-precision floating-point value (8.0, as it happens).  When you lie to NSLog, its behavior is undefined, and you get unexpected results like this.
Don't lie to NSLog.  If you want to convert the result of 2.0*4.0 to an integer before printing, you need to do that explicitly:
NSLog(@"%d", (int)(2.0*4.0));

If, instead, you want to print the result of 2.0*4.0 as a double-precision floating-point number, you need to use a different format specifier:
NSLog(@"%g", 2.0*4.0);

More broadly, this is true of any function that takes a variable number of arguments and some format string to tell it how to interpret them.  It's up to you to make sure that the data you pass it matches the corresponding format specifiers; implicit conversions will not happen for you.

A: First, you never used floats in your program. They are doubles.
Second, the arguments of NSLog, printf and the likes are not automatically converted to what you specify using %d or %f. It follows the standard promotion rule for untyped arguments.  See the ISO specification, sec 6.5.2.2.6 and 6.5.2.2.7. Note the super weird rule that inside these functions,

*

*a float is automatically promoted to double,

*and any integer smaller than an int is promoted to int. (see 6.3.1.1.2)

So, strictly speaking, the specification %f is not showing a float, but a double. See the same document, Sec. 7.19.6.1.8.
Note also that in your case 1 and 3, promotions are to double.

A: In examples 2, 3 and 4, the float is either being assigned to an int (which converts it) or compared with an int (which also converts it). In 1, however, you're passing the float as an argument to a function. The printf function allows all the arguments after the initial format string to be of any type, so this is valid. But since the compiler doesn't know you mean for it to be an int (remember, you haven't done anything to let the compiler know), the float is passed along as a floating-point value. When printf sees the %d formatting specifier, it pops enough bytes for an int from the argument list and interprets those bytes as an int. Those bytes happen to look like an integer 0.

A: The format string %d expects a decimal number, meaning a base 10 integer, not a floating point. What you want there is %f if you're trying to get it to print out 8.0

A: The first parameter to NSLog is a format string, then the second (and subsequent) parameters can be any types. The compiler doesn't know what the types should be at compile time and so doesn't try to cast them to anything. At run time NSLog assumes the second (and subsequent) parameters are as specified in the format string. If there's a mismatch unexpected and generally unhappy things happen.
Summary; Make sure you pass variables of the right type in the second (and subsequent) parameter.


text:
Q: How to read from textfile(String type data) map and load data into parquet format(multiple columns with different datatype) in Spark scala dynamically we are importing data from Source RDBMS system to hadoop environment using sqoop as textfile format. And this textfile need to be loaded into hive table of parquet format.
How can we approach this scenario without using Hive support(earlier we used beeline insert and we are designing not to use hive anymore) and write directly to HDFS using parquet.
EX:-
After sqoop import, lets say we have file under HDFS target dir.
/data/loc/mydb/Mytable
data in Mytable and all are of type String.
-----------------------------------------
10|customer1|10.0|2016-09-07  08:38:00.0
20|customer2|20.0|2016-09-08  10:45:00.0
30|customer3|30.0|2016-09-10  03:26:00.0
------------------------------------------

target Hive table schema.
rec_id: int
rec_name: String
rec_value: Decimal(2,1)
rec_created: Timestamp

How can we load data from Mytable to target underlying Hive table location(parquet format) using spark and managing typecasting for all the columns dynamically.
Please Note: we cannot use HiveContext here.
Any help in the approach is much appreciated. Thanks in advance.

A: The example below read a .csv file as the same format as presented in the question.
There are some details that I would like to explain first.
In the table schema the field: rec_value: Decimal(2,1) would have to be rec_value: Decimal(3,1) for the following reason:
The DECIMAL type represents numbers with fixed precision and scale.
When you create a DECIMAL column, you specify the precision, p, and scale, s.
Precision is the total number of digits, regardless of the location of the decimal point.
Scale is the number of digits after the decimal place.
To represent the number 10.0 without a loss of precision, you would need a
DECIMAL type with precision of at least 3, and scale of at least 1.
So the Hive table would be:
CREATE TABLE tab_data (
  rec_id INT,
  rec_name STRING,
  rec_value DECIMAL(3,1),
  rec_created TIMESTAMP
) STORED AS PARQUET;

The full scala code
import org.apache.spark.sql.{SaveMode, SparkSession}
import org.apache.log4j.{Level, Logger}
import org.apache.spark.sql.types.{DataTypes, IntegerType, StringType, StructField, StructType, TimestampType}

object CsvToParquet {

  val spark = SparkSession
    .builder()
    .appName("CsvToParquet")
    .master("local[*]")
    .config("spark.sql.shuffle.partitions","200") //Change to a more reasonable default number of partitions for our data
    .config("spark.sql.parquet.writeLegacyFormat", true) // To avoid issues with data type between Spark and Hive
                                                         // The convention used by Spark to write Parquet data is configurable.
                                                         // This is determined by the property spark.sql.parquet.writeLegacyFormat
                                                         // The default value is false. If set to "true",
                                                         // Spark will use the same convention as Hive for writing the Parquet data.
    .getOrCreate()

  val sc = spark.sparkContext

  val inputPath = "hdfs://host:port/user/...../..../tab_data.csv"
  val outputPath = "hdfs://host:port/user/hive/warehouse/test.db/tab_data"

  def main(args: Array[String]): Unit = {

    Logger.getRootLogger.setLevel(Level.ERROR)

    try {

      val DecimalType = DataTypes.createDecimalType(3, 1)

      /**
        * the data schema
        */
      val schema = StructType(List(StructField("rec_id", IntegerType, true), StructField("rec_name",StringType, true),
                   StructField("rec_value",DecimalType),StructField("rec_created",TimestampType, true)))

      /**
        * Reading the data from HDFS as .csv text file
        */
      val data = spark
        .read
        .option("sep","|")
        .option("timestampFormat","yyyy-MM-dd HH:mm:ss.S")
        .option("inferSchema",false)
        .schema(schema)
        .csv(inputPath)

       data.show(truncate = false)
       data.schema.printTreeString()

      /**
        * Writing the data as Parquet file
        */
      data
        .write
        .mode(SaveMode.Append)
        .option("compression", "none") // Assuming no data compression
        .parquet(outputPath)

    } finally {
      sc.stop()
      println("SparkContext stopped")
      spark.stop()
      println("SparkSession stopped")
    }
  }
}

Input file as .csv tab separated fields
10|customer1|10.0|2016-09-07  08:38:00.0
20|customer2|24.0|2016-09-08  10:45:00.0
30|customer3|35.0|2016-09-10  03:26:00.0
40|customer1|46.0|2016-09-11  08:38:00.0
........

reading from Spark
+------+---------+---------+-------------------+
|rec_id|rec_name |rec_value|rec_created        |
+------+---------+---------+-------------------+
|10    |customer1|10.0     |2016-09-07 08:38:00|
|20    |customer2|24.0     |2016-09-08 10:45:00|
|30    |customer3|35.0     |2016-09-10 03:26:00|
|40    |customer1|46.0     |2016-09-11 08:38:00|
......

schema
root
 |-- rec_id: integer (nullable = true)
 |-- rec_name: string (nullable = true)
 |-- rec_value: decimal(3,1) (nullable = true)
 |-- rec_created: timestamp (nullable = true)

reading from Hive
SELECT *
FROM tab_data;

+------------------+--------------------+---------------------+------------------------+--+
| tab_data.rec_id  | tab_data.rec_name  | tab_data.rec_value  |  tab_data.rec_created  |
+------------------+--------------------+---------------------+------------------------+--+
| 10               | customer1          | 10                  | 2016-09-07 08:38:00.0  |
| 20               | customer2          | 24                  | 2016-09-08 10:45:00.0  |
| 30               | customer3          | 35                  | 2016-09-10 03:26:00.0  |
| 40               | customer1          | 46                  | 2016-09-11 08:38:00.0  |
.....

Hope this helps.


text:
Q: LockService ambiguity In the LockService documentation: https://developers.google.com/apps-script/service_lock it states that "getPublicLock() - Gets a lock that prevents concurrent access to a section of code by simultaneous executions for the current user"
So the query is around the comment: "section of code".  If I have multiple sections of code that use the LockService.getPublicLock(), are they essentially independent locks?
For example:
function test1() {
    var lock = LockService.getPublicLock();

    if (lock.tryLock(10000)) {
        // Do some critical stuff
        lock.releaseLock();
    }
}

function test2() {
    var lock = LockService.getPublicLock();

    if (lock.tryLock(10000)) {
        // Do some critical stuff
        lock.releaseLock();
    }
}

If I have two invocations of my script concurrently executing, with one user accessing test1() and another user accessing test2(), will they both succeed?  Or as it alludes to in this post: http://googleappsdeveloper.blogspot.co.uk/2011/10/concurrency-and-google-apps-script.html are the locks simply at the script level?  So for this scenario, only one of test1() or test2() would succeed but not both.
If it is truly as the documentation states, and both will succeed, what denotes a 'section of code' ??  Is it the line numbers that the LockService.getPublicLock() appears on or is it the surrounding function?

A: There is only one public lock and only one private lock.
If you wish to have several locks you'll need to implement some sort of named lock service yourself. An example below, using the script database functionality:
var validTime = 60*1000;  // maximum number of milliseconds for which a lock may be held
var lockType = "Named Locks";  // just a type in the database to identify these entries
function getNamedLock( name ) {
  return {
    locked: false,
    db : ScriptDb.getMyDb(),
    key: {type: lockType, name:name },
    lock: function( timeout ) {
      if ( this.locked ) return true;
      if ( timeout===undefined ) timeout = 10000;
      var endTime = Date.now()+timeout;
      while ( (this.key.time=Date.now()) < endTime ) {
        this.key = this.db.save( this.key );
        if ( this.db.query(
              {type: lockType,
               name:this.key.name,
               time:this.db.between( this.key.time-validTime, this.key.time+1 ) }
            ).getSize()==1 )
          return this.locked = true;        // no other or earlier key in the last valid time, so we have it
        db.remove( this.key );              // someone else has, or might be trying to get, this lock, so try again
        Utilities.sleep(Math.random()*200); // sleep randomly to avoid another collision
      }
      return false;
    },
    unlock: function () {
      if (this.locked) this.db.remove(this.key);
      this.locked = false;
    }
  }
}

To use this service, we'd do something like:
var l = getNamedLock( someObject );
if ( l.lock() ) {
  // critical code, can use some fields of l for convenience, such as
  // l.db - the database object
  // l.key.time - the time at which the lock was acquired
  // l.key.getId() - database ID of the lock, could be a convenient unique ID
} else {
  // recover somehow
}
l.unlock();

Notes:

*

*This assumes that the database operation db.save() is essentially indivisible - I think it must be, because otherwise there would be BIG trouble in normal use.

*Because the time is in milliseconds we have to assume that it is possible for more than one task to try the lock with the same time stamp, otherwise the function could be simplified.

*We assume that locks are never held for more than a minute (but you can change this) since the execution time limit will stop your script anyway.

*Periodically you should remove all locks from the database that are more than a minute old, to save it getting cluttered with old locks from crashed scripts.

A: this question is too old and right now "getPublicLock()" is no Longer available.
according to https://developers.google.com/apps-script/reference/lock
at this time LockServise present these three scope:
getDocumentLock(): Gets a lock that prevents any user of the current document from concurrently running a section of code.
getScriptLock(): Gets a lock that prevents any user from concurrently running a section of code.
getUserLock():Gets a lock that prevents the current user from concurrently running a section of code.


text: Q: Crop/ forest/grass classification in Erdas I am trying to calculate crop land, forest and grass land  to check the irrigation potential during the period from Landsat 8 image using supervised classification in ERDAS. I am finding difficult to differentiate the crop, grass and forest land.


text:
Q: How do I connect my IP Remote Camera to ZoneMinder? I am using Ubuntu 16.04, ZoneMinder v1.29.1 with this docker and this camera(hikvision ir panoramic fisheye). I can connect to the camera and I get the camera interface for settings etc. The problem is the live views need a windows dependent plugin, that's why I wanted to use ZoneMinder.
Now I configured everything according to this guide. Basically I had to add a monitor, set the source to remote, set the protocol to rtsp, set the method to rtp/rtsp, set the host name to < user>:< pw>@< correct-ip>, set port to the rtsp port reported by the camera webinterface and set the host path to all possible things: I tried /Streaming/Channels/[1,2,3,4]/ and /live and /Streaming/Channels/[101,102,103]-[401,402,403,404]/ but I never had a live stream. I really don't know what I am doing wrong. Does anybody know the right host path or any other issues that could prevent me from receiving a live feed? According to this site the hikvision products should work with ZoneMinder. Maybe I am just missing something small and stupid, thank you.
EDIT:
I used ONVIF Device Manager to detect my rtsp stream: It is rtsp://< ip>:554/Streaming/Channels/101?transportmode=unicast&profile=Profile_101 and I use exactly those settings in ZoneMinder but it does still give me a 404 error on the video.

A: Most Hikvision cameras don't work with the "Remote" option, but with the "Ffmpeg" option.
Source should begin with rtsp://"username":"passwd"@"IP-ADDRESS cam":554  and sometimes you have to append things like /cam/realmonitor?channel=1&subtype=0?tcp
Protocol should be RTP/Unicast


text:
Q: web.config : maxRequestLength not taking effect I have the following seetings in my web.config file.
<httpRuntime executionTimeout="90000" maxRequestLength="204800" />

But I am not able to upload anyfile which are greater than 50MB. Wht could be the reason. The web browser keeps on waiting for the upload to finish but anyfile lesser than 50MB gets uploaded without any issues. Are there any other pleases I need to check?

A: Place this in your web.config
  <system.web>
     <httpRuntime executionTimeout="360" maxRequestLength="100000" />

That enables a 360 second timeout and 100,000 Kb of upload data at a time.
If that doesn't work, run this command on your IIS server. (replace [IISWebsitename])
C:\Windows\System32\inetsrv>appcmd set config "[IISWebsitename]" -section:requestFiltering -requestLimits.maxAllowedContentLength:100000000 -commitpath:apphost

That enables 100,000,000 bytes of upload data at a time.

A: Perhaps 50MB is the maximum allowed filesize upload on the webserver? If this is the case usually an error message is returned.
Can you find out what the allowed maximum uploaded filesize on the webserver is?
P.S.: Information about the system would also be nice.
      (Windows/Linux/Mac, IIS/Apache ...)


text:
Q: Prevent copy & paste of code chunks in R/exams We currently use R/exams to create exams in our coding course. We found students could easily copy & paste the code chunk and run it without thinking. Example:

We thus wonder if there is an argument/option in R/exam or other packages that could prevent this case, e.g., converting the code chunk into images. Then, the students cannot copy & paste our code.

A: Let me play the LockPickingLawyer a little bit here. Even if you manage to provide the code as an image, we are able to OCR and run it very easily and the solution would benefit those who know how to do it.
text <- tesseract::ocr("https://i.stack.imgur.com/wSRv5.png")  ## imgur url from OP
cat(text)

## copy-paste and run
x = -2
if(x > 0){
  x<- x +1
} else if(x == 0){
  x<-x-1
} else {
  x <- x * (-1)
}
x
# [1] 2

So why not asking why the result is 2 or, "describe in words for each line what the code does" instead?

A: A partial solution
We can generate html outputs from code chunks using reprex::reprex(), and then save images of the rendered output using webshot2::webshot().
It's a very limited solution, but all the main parts are there. Right now the output is very small and I can't work out how to resize it. reprex() also evaluates the code, which means the output is included (the very thing you were hoping to avoid). But it think webshot() might still be the way to go.
Here's a reproducible Quarto file that proves the concept:
---
title: "testing-code-images"
author: "Dave Lovell"
format: html
editor: visual
---

```{r libs}
library(webshot2)
library(reprex)
```

## Code example

```{r codeExample}
#| echo: false
#| fig.width: 6
snippet <- reprex(
  x = {
    y <- -2

    if(y > 0) y <- y * 2

    y
  },
  venue = "html"  # so we can pass to webshot()
)

# Write snippet output to html file
writeLines(snippet, "test-file.html")

# Capture the html file as an image
webshot(url = "test-file.html",
        file = "test-image.png") # make it bigger

# Don't need to keep the files
file.remove("test-image.png")
file.remove("test-file.html")
```

Output:

A: General comments
There isn't a readily available option to generate the image but the building blocks are available to write a little bit of code yourself. In particular the R/exams packages provides a tex2image() function which can take a LaTeX code chunk and turn it into an image which you can subsequently embed in the question.
Worked example
Below I provide a worked example which also randomly inserts some elements into the code:
```{r, include=FALSE}
## code as character string
code <- "
x <- %s

if (x > %s) {
  x <- x + 1
} else if (x == %s) {
  x <- x - 1
} else {
  x <- x * (-1)
}

x
"

## random inputs
x <- sample(-9:9, 1)
y <- sample(-3:3, 1)
code <- sprintf(code, x, y, y)

## screenshot
img <- tex2image(c("\\begin{verbatim}", code, "\\end{verbatim}"),
  name = "code", dir = ".", resize = 220)

## solution
sol <- eval(parse(text = code))
```

Question
========
The following code results in which output?
\
![R code](code.png)

Meta-information
================
exname: Conditional execution (with screenshot)
extype: num
exsolution: `r sol`

The idea is to first set up the code (or a code template) as a character string, then insert some randomized elements, generate the image, evaluate the code output and then prepare in the usual R/exams way. You might have to play with the resize argument to control the size of the image in a suitable way.
Further recommendations
Personally, I'm not fond of such workarounds because they feel like introducing additional hurdles which are not really about learning R. Using these strategies might also incentivize students to find workarounds like using OCR (see the other answers).
Instead, I usually try to change the answer format to single-choice or multiple-choice, based on qualitative statements. For example, for the code from your original post:

*

*For any positive input, one unit is added. [true]

*If the input is not positive, one unit is substracted. [false]

*One unit is added to all non-negative inputs. [false]

And so on...


text:
Q: How to pass data from Blade file to JavaScript? I know this is how to pass data from blade file to JavaScript?
Is there any other alternative. Because I am trying to avoid script tags in blade file
 <script type="text/javascript">
      var value = {!! $chart_data !!};
 </script>

Thanks in advance!


text:
Q: Will there be a USB-C to thunderbolt 2 adaptor? I only need data transfer to be higher then USB 3.0 Right now USB C ports are just arriving in laptops and I unfortunately dedicated to go with a cheaper laptop (pc) but with thunderbolt-2.
The thing I don't like about thunderbolt 2 products is the premium price you pay for the Lacie external drives with thunderbolt2. I hope that in the future USB-C devices will come out that will be a bit cheaper as the PC world and mac are seemingly getting 1 standard thunderbolt3 and USB-C.
Long story short will the thunderbolt 2 connection be of ANY use to me in the future world of USB-C on my windows laptop in regards to my normal USB3.0 ports? If yes then what applications of USB-C will it work with?
The only application I really care about is if I could connect an external HD sold with the new USB-C to my Thunderbolt2 via an adapter.
I am thinking I will only get a benefit from thunderbolt 3 devices that are labeled as such to get an adapter to thunderbolt 2 ports for me to get a speed gain compared to USB3.0.
In short the whole idea behind these questions is to have a fast connection between disks and laptop as I am working on big files in Photoshop and TB's of photo's and film ect. Even if USB 3.0 is "fast enough" I would still like to have the Thunderbolt 2 speeds rather then the USB 3.0 speeds.
If it is compatible will the theoretical and effective speed of a USB-C to Thunderbolt2 connection surpass the USB 3.0 max speed?

A: In specific. Thunderbolt can carry USB but USB cannot carry thunderbolt.
In general, as long as your Mac has any Thunderbolt connector, it is highly likely you will be advantaged to connect over thunderbolt instead of using USB. For my money even Thunderbolt 1 is superior in many ways to the best USB 3 chipsets we have today. Now - the above statement is going to be obsolete soon since the newest Thunderbolt 3 chipsets and USB Alternate Mode Functionality mean that USB can be other protocols and TB3 looks to be an awesome step forward for simplifying the need for adapters that you would need on Thunderbolt 2 to get USB 3.0 connectivity today.

*

*What Thunderbolt to USB 3.0 cables/adapters exist for OS X and Mac hardware?

A:
Will there be a USB-C to thunderbolt 2 adaptor?

USB-C is a connector, Thunderbolt is a protocol, which makes this something of a nonsense question.  USB-C can carry a number of protocols, including Thunderbolt and USB.  Thunderbolt is a protocol used on USB-C and mini-DP connectors, if there are more external connectors than this in common use then I am not aware of it.
There are Thunderbolt mini-DP to Thunderbolt USB-C adapters available.  Apple sells one.  https://www.apple.com/shop/product/MMEL2AM/A/thunderbolt-3-usb-c-to-thunderbolt-2-adapter
This is not an adapter to the USB protocol, any drive connected by this adapter will have to be a Thunderbolt drive to work.  Having a USB-C port is not sufficient for this adapter to work, there are many drives that use USB-C but the USB protocol instead of the Thunderbolt protocol.
Thunderbolt drives with USB-C will likely be no faster or slower than Thunderbolt drives with the old mini-DP connector but they are likely to be cheaper.  USB-C drives have a bigger market and this will mean lower prices out of economy of scale.
Using a Thunderbolt drive with a mini-DP connector with a computer that supports Thunderbolt on a USB-C port only requires that Apple adapter or something like it.  Using a Thunderbolt drive with a USB-C port with a computer that supports Thunderbolt on a mini-DP port means using the same adapter, the adapter is bi-directional.  Using a Thunderbolt drive with a captive USB-C cable, a cable that is permanently attached and a USB-C male connector on the end, will not work with that adapter.  Or at least not with that adapter alone.  Adapters with female USB-C ports do not meet the USB-C spec.  They exist, can be purchased, but by not meeting the spec they can damage something.  It's best to find the right drive without the captive cable.

I only need data transfer to be higher then USB 3.0

USB 3.0 will allow 5 Gbps, USB 3.1 will allow 10 Gbps.  USB 3.0 and USB 3.1 can use the old USB-A and "wide" micro-USB-B connectors that are common on many computers and hard drives, or they can use USB-C.  Any USB drive with a USB-C port doesn't make the USB protocol any faster, but it can make them more convenient because USB-C is a nicer connector than the old micro-USB-B.
Getting faster than USB 3.0 with a computer that has a mini-DP Thunderbolt 2 port, and a drive with a USB-C port, means using a Thunderbolt drive and a Thunderbolt mini-DP to USB-C adapter.  If the drive does not support the Thunderbolt protocol then it will not work with the Thunderbolt port and adapter.  It is possible for an adapter from Thunderbolt 2 on a mini-DP connector to USB 3.1 on a USB-C connector to exist but I haven't seen one.  Using a Thunderbolt 2 to PCIe expansion chassis and a PCIe card with USB 3.1 on USB-C ports will also get faster than USB 3.0 with a USB-C drive but that's going to be expensive.
Buyer beware.  There are USB-C drives that use the USB protocol, these are limited to USB 3.0 speeds with this computer.  There are USB-C drives that use the Thunderbolt protocol, those with the USB-C port can be attached easily.  Those with the USB-C captive cable cannot be attached easily.  Check the specs before you buy.
A bit of a side note about the future of USB and Thunderbolt...
USB 3.2, which is not all that common and may not become common since USB4 came out so soon after USB 3.2, can reach 20 Gbps but only with the USB-C connector.  This is the same speed as Thunderbolt 2, half the speed USB4 and Thunderbolt 3.  USB4 is a protocol that allows the option to include support for the Thunderbolt protocol, making it backward compatible with Thunderbolt 3 and Thunderbolt 2 but not necessarily reaching the maximum speed of either.  The USB4 protocol requires backward compatibility with previous USB versions but this can mean up to USB 3.2 speed, or less than USB 2.0 speed.  To claim meeting the USB4 spec requires use of the USB-C connector, but doesn't require offering any higher speed than previous USB versions.  Buyer beware again.
Oh, and use the right cable as not all ables are created equal.
A cable tested to meet the USB spec will have the USB icon on it and often a number indicating the speed it was tested to meet in Gbps.  No number with the USB icon but with the stylized "SS" symbol usually means 5 Gbps tested speed, it might allow higher speeds, and it might not.  A cable that has been tested to meet the Thunderbolt spec will have the Thunderbolt icon on it, this is pass/fail and not different speed tests like USB, the icon means it was tested at the highest data rate.  No icon, or not a Thunderbolt or USB icon, does not mean it won't work but does mean it's not tested to meet the spec.  A mini-DP cable without the Thunderbolt icon will fit a Thunderbolt 2 port but is not likely to work with any Thunderbolt 2 device.  A USB-C cable with no USB or Thunderbolt icon will likely work at some speed, just perhaps not at the maximum speed the computer and device are capable.  Buyer beware one more time.

A: this entire question is backwards... the old connection CANNOT be adapted to by a new one. You can't get an adapter to use USB-C drives on USB or Thunderbolt. You MAY be able to use Thunderbolt 2 on USB-C. USB-C is a faster connection, so you won't be able to shove it into a smaller pipe.


text:
Q: clarification of grid lookup in eloquent javascript ch.7 - electronic life Eloquent Javascript ,Chapter 7 - Electronic Life
Trying to understand the part that describes how to use var grid:
var grid = ["top left",    "top middle",    "top right","bottom left", "bottom middle", "bottom right"];
console.log(grid[2 + (1 * 3)]);
// → bottom right

Any possible explanations will help. This is what the text offers and I need clarification on: "Or, we can use a single array, with size width × height, and decide that the element at (x,y) is found at position x + (y × width) in the array." Is there another way to re-phrase this explanation?

A: In the example, you are making a 3x2 grid.
Normally, you would do it like this:
var grid = [["top left", "top middle", "top right"],
            ["bottom left", "bottom middle", "bottom right"]];

grid[1][2]; // "bottom right"

That's pretty simple.  We made a 2D array (a matrix) are are accessing it using grid[y][x].
The example you show is trying to emulate that matrix using a 1D array.  Not quite sure why'd you want to do that.  It's not as obvious to see what you are trying to do.  I, personally, see no benefit to doing it this way.
var grid = ["top left", "top middle", "top right",
            "bottom left", "bottom middle", "bottom right"];

grid[2 + (1 * 3)]; // "bottom right"

The formula is grid[x + (y * width_of_grid)].  So, why does this work?  Your elements are in groups of 3.  So, you need to find where the group you want starts, that's what y * width_of_grid does.  Once you found where the group you want starts, then you add x to get the cell you want.
Again, no idea why this would be suggested as an option.  Most developers would pick the 1st option, that's clean and makes sense.  The 2nd one is just confusing and silly.


text:
Q: Count NAs per row in dataframe I've got dataframe that has batch ID and the results of six tests performed on each batch. The data looks like this:
batch_id  test1  test2  test3  test4  test5  test6
001       0.121     NA  0.340  0.877  0.417  0.662
002       0.229  0.108     NA  0.638     NA  0.574

(there are a few hundred rows in this dataframe, only one row per batch_id)
I'm looking for a way to count how many NAs there are for each batch_id (for each row). I feel like this should be do-able with a few lines of R code at the most, but I'm having trouble actually coding it.
Any ideas?

A: You could add a new column to your data frame containing the number of NA values per batch_id:
df$na_count <- apply(df, 1, function(x) sum(is.na(x)))

A: You can count the NAs in each row with this command:
rowSums(is.na(dat))

where dat is the name of your data frame.