Q: Is JQuery namespace a good practice? Can anyone explain to me please that if using a namespace is a good coding practice. And why is it needed? If it was a good approach why JQuery didn't include it by default. There is a separate plugin to allow this functionality.
I saw this post that mentions few ways to do it. Someone mentioned about memory leak in the post that is worrisome.
Lastly, what is the best way to organize JQuery libraries?
thanks,

A: Re: best ways to organize jQuery libraries, you should start by reading the Plugins Authoring article on jquery.com:
http://docs.jquery.com/Plugins/Authoring

A: Notes:

*

*Namespacing is a good practice because you have less chance of having conflicting names with other scripts. This way, only your name-space has to be unique, but multiple name-spaces can have the same functions in them.

*jQuery DOES use namespacing, and you do not need the plug-in. The jQuery object itself is a name-space. . . Any function inside jQuery is 'name-spaced' in the jQuery object.  This is true for any JavaScript object.

In response to Amir's comment:
YUI achieves namespacing by adding a variable to the YUI object where the added variable is also an object.  Their namespace function just builds it for you.
var lib = {
    util:{},
    widget:{},
    tool:{}
};

//creates a function named reset in the lib.util namespace
lib.util.reset = function() {};

//creates a function named reset in the lib.widget namespace
lib.widget.reset = function() {};

In jQuery, you add it to the jQuery.fn (or $.fn if you use $ for jQuery() namespace.

A: require.js is a better practice because it doesn't require you to add objects onto the window object unnecessarily. It also doesn't mean you have to worry about the loading order of previous javascript files.


Q: Any ccTalk libraries available? I want to integrate a coin acceptor into one of our applications. This specific coin acceptor uses the ccTalk protocol (specs here).
I've been looking for a ccTalk library which I can use from C#, but until this point I've only found this open source project which seems not quite ready, and abandoned.
Any of you guys know of any ccTalk libraries out there? I can't believe this hasn't been done before. It doesn't necessarily has to be free.

A: Have you looked at cctalk-net? It's a rewrite of libcctalk and has been worked on up to August 2011 this year. It does not support everything in ccTalk but might just support enough for your needs.

A: I managed to come up with a solution based on the aforementioned cctalk-net project.
I hosted my project on github: https://github.com/Hitman666/nbCcTalkCoinAcceptor so I hope it will help someone. I made a full fledged documentation for an easy start (which can't be said for cctalk-net project).


Q: Converter Coluna em Linhas Oracle Bom dia!
Preciso que o resultado desse SQL:
SELECT
    CD_ITEM_PAI,
    CD_ITEM_FILHO
FROM ESTRUTURA
WHERE CD_ITEM_PAI = 707534

Que no momento é esse:

Seja assim:

Podem me ajudar?
Utilizando o PIVOT não obtive o resultado, pois as funções COUNT, SUM, etc.. não servem no meu caso.


Q: filter2D OpenCV function c++ I have noticed differences between the OpenCV implementation of filter2D in C++ and a direct implementation of the corresponding kernel. I have read the following question:
Opencv - how does the filter2D() method actually work?
The author of that question had tried to get a working implementation of the filter2D function. He claims that using a normalized version of filters yields correct results. I have tested his hypothesis and found that normalization gives the correct answer only when all the coefficients are positive. Thus an averaging filter can be successfully implemented using the filter2D function.[We must still normalize the kernel].
However this is not the case for filters with negative coefficients such as the Sobel,Laplacian and any edge detection filter. The author of that question has encountered the same problems as me.
https://stackoverflow.com/users/2669614/bovaz
The user mentioned above replied to the linked question. He claimed that filter2D might modify its implementation if the sum of the coefficients of  the kernel equals zero. Is that the case? Why does the implementation of filter2D in C+ give different results from a direct implementation? I have checked that filter2D in Python and a direct implementation of the corresponding kernel in C++ yield the same results.

A: It is mainly because of scaling and overflow issues.
The documentation for filter2D does not mention(atleast i did not find) whether the overflowed values are clipped or scaled appropriately to the min-max range.
This is more important in the case of directional filters, where the co-efficients are positive and negative and after the algebraic
The function 'myfilter2D' presented on the link above does not scale to the min-max range which should be the case.
If you could post the sample code then it would be easier to help.
My suggestion would be to convert the matrices to float(with scaling) and perform algebraic operations because this tends to preserve the resulting values and values are not lost due to overflow or saturation.
im2double()->"perform algebraic operations"->im2uchar() for displaying
void im2uchar( Mat & src, Mat  & dest){
  double minVal, maxVal;
  minMaxLoc(src, &minVal, &maxVal); //find minimum and maximum intensities
  src.convertTo(dest, CV_8U, 255.0/(maxVal - minVal), -minVal * 255.0/(maxVal - minVal));
  }

void im2float( Mat  & src, Mat  & dest){
  double minVal, maxVal;
  minMaxLoc(src, &minVal, &maxVal); //find minimum and maximum intensities
  src.convertTo(dest, CV_32F, 1.0/(maxVal - minVal), -minVal * 1.0/(maxVal - minVal));
  }


Q: API $http delete returns 405 when calling from factory in angular This is what I have in my factory. This was working fine when I was running it in regular ajax syntax from the controller.
function endAgentSession(sessionData, tokenData) {

            var sessionId = sessionData.data.sessionId,
                access_token = tokenData.access_token,
                baseURI = tokenData.resource_server_base_uri,
                endAgentSessionPayload = {
                    'sessionId': sessionId,
                    'forceLogOff': true,
                    'endContacts': true,
                    'ignorePersonalQueue': false
                    };

            console.log(sessionId, "sessID");

            return $http({
                'url': baseURI + 'services/v6.0/agent-sessions/' + sessionId,
                'type': 'DELETE',
                'headers': {
                    //Use access_token previously retrieved from inContact token service
                    'Authorization': 'bearer ' + access_token,
                    'content-Type': 'application/json'
                },
                'data': endAgentSessionPayload
            }).then(function(res){
               return res })};
        }

This is my controller. When I call the endAgentSession function from the controller with an ng-click, it errors out to a 405..
 $scope.endAgentSession = function(){
    agentFactory.endAgentSession($scope.sessionData, $scope.tokenData);
};

What am I doing wrong? It was working w/ ajax in the controller, then seemed to break when I moved it to the factory and used a promise.
it's actually showing it' requesting a GET request in Network..
[![enter image description here][1]][1]
full controller:
csMgmtApp.controller('launchedController', ['$scope', '$http', '$document', '$resource', 'agentFactory', '$timeout', function ($scope, $http, $document, $resource, agentFactory, $timeout) {

$scope.agentStatePayload = {};
$scope.sessionData = {};
$scope.tokenData = {};
$scope.startSessionPayload = {
    'stationPhoneNumber': '2223222222',
    'inactivityTimeout': 0,
    'inactivityForceLogout': 'false'
};

$document.ready(function () {
    $scope.tokenData = agentFactory.getToken();
    console.log($scope.tokenData);
});

agentFactory.startSession($scope.startSessionPayload, $scope.tokenData).then(function(res){
    console.log("sessionId", res);
    $scope.sessionData = res;
});

$scope.endAgentSession = function(){
    agentFactory.endAgentSession($scope.sessionData, $scope.tokenData);
};

}]);

It all seems to be working, except for the endSession, now..

A: I should have guessed that every time you said

regular ajax syntax from the controller

you meant you were using jQuery $.ajax previously.
The difference is that the property that sets the request method in Angular's $http is method, not type.
You can simplify it further using
return $http.delete(baseURI + 'services/v6.0/agent-sessions/' + sessionId, {
    headers: {
        Authorization: 'Bearer ' + access_token,
    },
    data: endAgentSessionPayload
});


Q: Declare explicit types for a dynamically created class function Say I've got this class:
class Foo {
  bar = this.createDynamicFunction((param: string) => {
    return "string" + param;
  });

  baz = this.createDynamicFunction((param: number) => {
    return 1 + param;
  });

  createDynamicFunction(fn: (param: any) => any) {
    return (param) => fn(param);
  }
}

const foo = new Foo()
foo.bar('baz') // => barbaz
foo.baz(2) // => 3

How do I declare types for the functions Foo.prototype.bar and Foo.prototype.baz? I want to explicitly say that bar and baz accept and return string and number respectively.
I realize that this is a contrived example. For some context, I'm in the final stages of rewriting one of my message queue client libraries and a lot of the class functions are dynamically created. These functions share a lot of functionality, but their inputs/outputs differ.

A: Generics are made for this:
class Foo {
  bar = this.createDynamicFunction((param: string) => {
    return "string" + param;
  });

  baz = this.createDynamicFunction((param: number) => {
    return 1 + param;
  });

  createDynamicFunction<Type>(fn: (param: Type) => Type) {
    return (param : Type) => fn(param);
  }
}

const foo = new Foo()
//console.log(foo.baz(2)) // => 3
console.log(foo.bar('baz')) // => barbaz
console.log(foo.baz(2)) // => 3

You create a generic function, for which the type can be anything. And you can define your overall function type based on that type
Playground Link


Q: Remapping fonts in unicode-math has no effect on e.g. `\mscrC` For some reason, in this setup, \mathscr{C} and \mscrC produce different results:
\documentclass[12pt,a4paper]{article}
\usepackage{unicode-math}
\unimathsetup{math-style=TeX}
\setmathfont{Cambria Math}
\setmathfont[range={\mathscr,\mathbfscr},StylisticSet=0]{xits-math.otf}
\begin{document}
\[
\mathscr{C}, \mscrC
\]
\end{document}

In the result, \mathscr{C} respects the remapping, but \mscrC does not. I was under the impression that unicode-math translates the former to the latter, but it seems as if \mathscr here contains some additional processing that "knows" about fonts. A literal  behaves like \mscrC. The only thing that seems to work is redefining \mscrC after \begin{document} to force it to go through \mathscr.

*

*What is unicode-math really doing?

*How do I work around this?

A: I'm not sure but I think that it is not a bug but a feature: It gives you the possibility to use different fonts even if the "destination position" is the same. \mathscr{C}, \mscrC and also \mathcal{C} all print the char "1D49E. The current behaviour means that e.g. \mathscr and \mathcal can come from different fonts:
\documentclass[12pt,a4paper]{article}
\usepackage{unicode-math}

\unimathsetup{math-style=TeX}
\setmathfont{Cambria Math}
\setmathfont[range={\mscrC,\mathscr,\mathbfscr},]{xits-math.otf}

\begin{document}
\mscrC
\[
\mathscr{C}, \mscrC,\mathcal{C}
\]
\end{document}

If you want to change the look of \mathcal too you will have to add it to the list too (like I did for \mscrC).


Q: ipa extraction after you download an app from iTunes We are currently providing ios app via Itunes. The main function of the app is to verify `app integrity' and it is done by checking hash value (sha256) of the execution file in .ipa once we download it.
With the 32bit app we downloaded from iTunes, we can extract .ipa file to get execution file without problems. However, it does not seem to be possible with 64bit ios apps. (maybe there is a way and we couldn't find it. if this is the case please enlighten us.) Since we are planning provide our service both with 32 and 64bit, we do need to extract execution file from 64bit app.
So there are two questions we would like to ask regarding on this ipa extraction.
1. The hash value(sha256) of the app before we upload to iTunes and the value after we download it from iTunes is different. Why is that?
2. Is there any way we can extract .ipa (32/64 bit both) after we download the app from iTunes?


Q: lock/prevent close of menu reactjs I have a side menu that opens when an icon is clicked and closes when the either the page is clicked or an item on the menu is clicked. I am trying to implement a lock so when the lock icon is clicked, the menu will not close even if you click on a menu item or on the page.
I was able to setup the icon changing from a locked one to an unlocked one but I am having trouble with the functionality of stopping the close. Any help/suggestions would be awesome. Below are the 2 components that (the parent and the menu with the lock button) here is the code sandbox for a full look: https://codesandbox.io/s/pw6q46jp20

class SideBar extends Component {
  constructor(props) {
    super(props);
    this.state = {
      category: props.category,
      currentPage: {
        backgroundColor: '#383838',
        color: '#A9A9A9',
      },
      menuLocked: false,
      menuOpen: false,
      selectedIcon: null,
    };
  }
  handleIconClick = (category) => {
    this.setState({
      category,
      menuOpen: true,
      selectedIcon: category,
    });
  };
  handleMenuItemClick = (category) => {
    this.setState({
      menuOpen: false,
      selectedIcon: '',
      currentPage: category,
    });
  }
  handlePageClick = () => {
    this.setState({
      menuOpen: false,
    });
  }
  handleMenuLock = () => {
    this.setState({ menuLocked: !this.state.menuLocked });
  }
  render() {
    return (

        <TopBar {...this.props} />
        <Container>
          <SideNav>
            <ListWrapper>
              <IconList
                currentPage={this.state.currentPage}
                openMenu={this.handleIconClick}
                selectedIcon={this.state.selectedIcon}
                visible={this.state.menuOpen}
              />
            </ListWrapper>
          </SideNav>
          <PageContentWrapper>
            <Sidebar.Pushable>
              <PushMenu
                category={this.state.category}
                closeOnItemClick={this.handleMenuItemClick}
                handleMenuLock={this.handleMenuLock}
                menuLocked={this.state.menuLocked}
                params={this.props.params}
                visible={this.state.menuOpen}
              />
              <Sidebar.Pusher
                onClick={this.handlePageClick}>
                <Segment basic>
                  {this.props.children || <Home />}
                </Segment>
              </Sidebar.Pusher>
            </Sidebar.Pushable>
          </PageContentWrapper>
        </Container>

    );
  }
}

SideBar.propTypes = {
  children: PropTypes.any,
  params: PropTypes.any,
  category: PropTypes.any,
};

export default SideBar;

class PushMenu extends React.Component {
  render() {
    const category = sideNavData.lookupCategory(this.props.category);
    const menuLockButton = !this.props.menuLocked
      ? <Icon
        link={true}
        name='unlock'
        size='big'
      />
      : <Icon
        link={true}
        name='lock'
        size='big'
      />;
    return (
      <Sidebar
        className='Push-menu'
        animation='push'
        width='thin'
        visible={this.props.visible}
      >
        {this.props.category}
        <Linebreak />
        {
          Object.keys(category).map((subCategory, index) => {
            return (

                <SubcategoryHeader>{subCategory}</SubcategoryHeader>
                <List>
                  {
                    Object.keys(category[subCategory]).map((item, index) => (

                        <ListLink>
                          <Link
                            to={`/${this.props.category}/${subCategory}/${category[subCategory][item].name}`}
                            activeStyle={{ color: '#FFFFFF' }}
                            onClick={() => {
                              this.props.closeOnItemClick(this.props.category);
                            }}
                          >
                            {category[subCategory][item].name}
                          </Link>
                        </ListLink>

                    ))
                  }
                </List>
                <LockButtonWrapper onClick={this.props.handleMenuLock}>
                  {menuLockButton}
                </LockButtonWrapper>

            );
          })
        }
      </Sidebar>
    );
  }
}

PushMenu.propTypes = {
  category: PropTypes.any,
  closeOnItemClick: PropTypes.func,
  currentPage: PropTypes.func,
  handleMenuLock: PropTypes.func,
  menuLocked: PropTypes.bool,
  visible: PropTypes.bool,
};

export default PushMenu;

A: You can change your handlePageClick method to setState only when this.state.menuLocked is false.

  handlePageClick = () => {
    if (!this.state.menuLocked) {
      this.setState({
        menuOpen: false,
      });
    }
  }

A: Inside of handlePageClick() you should do a check to see if this.state.menuLocked is true. If so, don't change the value of menuOpen in state.
handlePageClick = () => {
  if (!this.state.menuLocked) {
    this.setState({
      menuOpen: false,
    });
  }
}

As a side note, in handleMenuLock() you are using the previous value of menuLocked to set the new value. Since setState is asynchronous, it's entirely possible that the value of menuLocked has changed by the time it actually saves and so you may not get the desired result. As such, you should pass it a function like this:
handleMenuLock = () => {
  this.setState((prevState) => ({ menuLocked: !prevState.menuLocked }))
}

This ensures that the value is actually toggled. Docs on using setState in this manner can be found here.


Q: Google Apps Script refresh sheet while function is running I have some script in my Google Sheets/ It can take a lot of time to finish all this script (up to 5 minutes I think). And I want to show some message that user should just wait a little. So I have some code like:
function test(){
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var cell = sheet.getRange("A1");
  sheet.clear();
  cell.setValue('WAIT!!!!');
  DATA = UrlFetchApp.fetch(url);
  // And some action that takes a lot of time ....
  cell.setValue('DONE!!!!');

But it doesn't show "WAIT" it only shows me "DONE" when everything is ok. It can only show me "WAIT" if there was any error and function crashed. It looks like I need to refresh it somehow.

A: Call the flush()method after you set the cell value to wait.
SpreadsheetApp.flush(); //Applies all pending Spreadsheet changes.


Q: How do I find the mass of a sphere using proportionality? A steel sphere 3.0 cm in diameter has a mass of 0.11 kg. What is the mass of a steel sphere 5.0 cm in diameter?
I know that $m= DV$ where D is density and V is Volume. I am assuming that both spheres have the same density since it is made of steel so I plugged in $1.5$ into $V=\dfrac{4}{3}\pi r^3$ and got $14.14cm^3$. I then plugged $14.14$ into $m= DV$ and got that the density was $0.0078$. Now I can solve for the unknown mass $m=0.0078(\dfrac{4}{3}\pi (2.5)^3)$. I got the mass is $0.51kg$. Did I do this problem correctly? If not could anyone explain what I did wrong?

A: We are scaling linear dimensions (lengths) by the factor $\frac{5}{3}$.
If we scale linear dimensions by the factor $\lambda$, then volume is scaled by the factor $\lambda^3$.
So we are scaling volume, and therefore mass, by the factor $\left(\frac{5}{3}\right)^3$.
The new mass is therefore $\left(\frac{5}{3}\right)^3(0.11)$.
Remark: Your calculation was correct. More work, though!  And suppose that the item was not a ball, but a small statue of a horse, and we were scaling linear dimensions by the factor $\frac{5}{3}$. The scaling argument above would still work, but there is no "volume of a horse" formula.

A: You said you wanted an answer using proportionality. I'll work out the proportion with algebra, only substituting at the end.
m = DV and V = 4πr3/3, so m = 4πDr3/3
Now take the ratio of two masses:
m2/m1 = (4πD2r23/3)/(4πD1r13/3)
Assuming they're the same kind of steel at the same ambient pressure and temperature, density is constant. This means D2 = D1. Now simplify the right side by dividing the top and bottom by 4πD1/3:
m2/m1 = r23/r13
Now solve for m2 by multiplying both sides by m1:
m2 = m1 * r23/r13
Finally, substitute in m1 = 0.11 kg, r1 = 3.0 cm, and r2 = 5.0 cm:
m2 = 0.11 kg * (5.0 cm)3/(3.0 cm)3 = 0.51 kg


Q: IE11 moves cursor to beginning of input when editing value I have a really odd problem on a project.  Long Story Short, I have input fields that record interest rate, so a % is appended on blur and removed on focus.  It works fine on every browser except for IE11.  For some reason, it moves the cursor to the beginning of the input, which is annoying for people tabbing through and typing in values quickly.
Here is a simplified example in:

$('#test').val('default');

$('#test').focus(function() {
    var value = $(this).val().slice(0, -1);
    $(this).val(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="test" />

Again, this only happens in IE11 (works fine in older versions of IE).  Has anyone run into this issue before?  I tried forcing focus again after the value is reassigned, but that didn't solve the issue.  Any tips are appreciated.

A: You could try to set caret position manually when appending/removing % mark, using those two functions (those are pretty generic and should work for every browser if you need setting caret positions for all browsers some other time):
function getCaretPosition(element) {
  var caretPos = 0;
  if (element.type === 'text' || element.type === 'tel') {
    if (document.selection) { // IE Support
      element.focus();
      var Sel = document.selection.createRange();
      Sel.moveStart('character', -element.value.length);
      caretPos = Sel.text.length;
    } else if (element.selectionStart || element.selectionStart === '0') {// Firefox support
      caretPos = element.selectionStart;
    }
  }

  return caretPos;
}

function setCaretPosition(element, position) {
  if (element.type === 'text' || element.type === 'tel') {
    if (element.setSelectionRange) {
      element.focus();
      element.setSelectionRange(position, position);
    } else if (element.createTextRange) {
      var range = element.createTextRange();
      range.collapse(true);
      range.moveEnd('character', position);
      range.moveStart('character', position);
      range.select();
    }
  }
}

And call them only when using IE11 :) Also, if you want, you could make those functions more specific, removing parts for FF :)

A: This issue can be solved by:

*

*getting a reference to the input element

*adding an onfocus event handler

Then setting the selection range in the onfocus handler to the end of the input value, like so:
const onFocus = (el) => {
  const { value } = el.value
  el.setSelectionRange(value.length, value.length);
}

<input type='text' onfocus='onFocus(this)'  />

If you are using ReactJS, here is that solution.


Q: Control Chart Structure - X axis I am using a computer system with Shewhart control charts. Is it appropriate to use time stamped data as the x axis in a sequential manner. Using this process will create gaps in the control chart, rather then charting at even intervals on the x axis. Our plant wants to use this to see when results are put in the system from a graphic perspective. I cannot find any reference to say that this is appropriate. All examples show even intervals. I am told plotting against time stamps is not appropriate. Please cite any references with you response, thanks


Q: How to launch Google Colab with local runtime which is an existing Docker image? I would like to connect Google Colab with a local runtime which is an existing Docker image. Specifically, FEniCS allows launching a notebook, i. e
docker run --name notebook -w /home/fenics -v $(pwd):/home/fenics/shared -d -p 127.0.0.1:8888:8888 quay.io/fenicsproject/stable 'jupyter-notebook --ip=0.0.0.0'

How can I launch it with Google Colab also with Backend port 8888?
I tried to build the image from a crash following the work here for Ubuntu 18.04. I could connect the local runtime with this image but it crashed whenever I installed FEniCS. There is something missing it seems. I really appreciate any hints.


Q: How to get the constructor name in Node.js from super class I have a "super" module in my Node.js application with a constructor and some prototype functions.
var parser = function(options, util, cache, url) {

    this.options        = options;
    this.util           = util;
    this.cache          = cache;
    this.url            = url;
}

parser.prototype.start = function() {
    console.log("I am a default start function");
    console.log(this.constructor.name);
}

module.exports = parser;

I have a handful of other modules that inherit from this module. Now, when i invoke the start function i would like to get the name of that module's constructor. For some reason this is not working for me.
var parser = require('../parser');
var util   = require('util');

var DKAN = function(options, util, cache, url) {

    parser.apply(this,arguments);

}

util.inherits(DKAN, parser);

DKAN.prototype.check = function($) {
    var DKANParser = this;
    if ($('meta[content*="Drupal"]').length !== 0 ) {
        DKANParser.start();
        return true;
    } else return false;
}

module.exports = DKAN;

When invoking the DKANParser.start() i only get the first console.log with "I am a default start function" and cannot get the name of constructor whih is supposed to be DKAN


Q: Overwriting HDFS file/directory through Spark Problem
I have a file saved in HDFS and all I want to do is to run my spark application, calculate a result javaRDD and use saveAsTextFile() in order to store the new "file" in HDFS.
However Spark's saveAsTextFile() does not work if the file already exists. It does not overwrite it.
What I tried
So I searched for a solution to this and I found that a possible way to make it work could be deleting the file through the HDFS API before trying to save the new one.
I added the Code:
FileSystem hdfs = FileSystem.get(new Configuration());
Path newFolderPath = new Path("hdfs://node1:50050/hdfs/" +filename);

if(hdfs.exists(newFolderPath)){
    System.out.println("EXISTS");
    hdfs.delete(newFolderPath, true);
}

filerdd.saveAsTextFile("/hdfs/" + filename);

When I tried to run my Spark application, the file was deleted but I get a FileNotFoundException.
Considering the fact, that this exception occurs when someone is trying to read a file from a path and the file does not exist, this makes no sense because after deleting the file, there is no code that tries to read it.
Part of my code
 JavaRDD<String> filerdd = sc.textFile("/hdfs/" + filename)    // load the file here
 ...
 ...
 // Transformations here
 filerdd = filerdd.map(....);
 ...
 ...

 // Delete old file here
 FileSystem hdfs = FileSystem.get(new Configuration());
 Path newFolderPath = new Path("hdfs://node1:50050/hdfs/" +filename);

 if(hdfs.exists(newFolderPath)){
    System.out.println("EXISTS");
    hdfs.delete(newFolderPath, true);
 }

 // Write new file here
 filerdd.saveAsTextFile("/hdfs/" + filename);

I am trying to do the simplest thing here but I have no idea why this does not work. Maybe the filerdd is somehow connected to the path??

A: The problem is you use the same path for input and output. Spark's RDD will be executed lazily. It runs when you call saveAsTextFile. At this point, you have already deleted the newFolderPath. So filerdd will complain.
Anyway, you should not use the same path for input and output.


Q: lambda function does not update the reference array I have a method which basically updates each value of the passed reference array by 5.
Initially I tried the below options but it wouldn't update the reference array.
Option 1:
void Int_Array_Update(std::vector<int>& param)
{
    auto f1 = [](int n) { return n + 5; };
    std::for_each(param.begin(), param.end(), f1);
}

Option 2:
void Int_Array_Update(std::vector<int>& param)
{
    auto f1 = [&](int n) { return n + 5; };
    std::for_each(param.begin(), param.end(), f1);
}

Option 3:
void Int_Array_Update(std::vector<int>& param)
{
    auto f1 = [&param](int n) { return n + 5; };
    std::for_each(param.begin(), param.end(), f1);
}

The workaround I have currently is as below:
void Int_Array_Update(std::vector<int>& param)
{
    for (int i = 0; i < param.size(); ++i)
        param[i] = param[i] + 5;
}

I am not able to find any answers why the lambda function is not updating the reference vector or maybe I am doing something wrong. Any help is appreciated.

A: std:.for_each does not update the elements in the range the way you expect. std::for_each applies the lambda to each element, but does not care about the return value from the lambda.
You want std::transform for that:
std::transform(param.begin(), param.end(), param.begin(), f1);
//                                         ^^^^^^^^^^^^^
//                                              |
//                it starts writing the result here

To work with std::for_each you would need to receive the argument by-reference in the lambda and make the update to the argument directly instead of returning it:
auto f1 = [](int& n) { n += 5; }; // int& and add to n directly
std::for_each(param.begin(), param.end(), f1);


Q: phpseclib - Parse mysql query to array I do a mysql select query over ssh2 with phpseclib.
I get my result back. If I add nl2br(), it's kind of readable (every row is on a seperate line). But I still can't access the columns of the rows.
How can I properly parse the output of a phpseclib ssh2 mysql query into a recursive array?
This is how I do my query:
$output = $ssh->exec('mysql -uMyUser -pMyPassword MyTable -e "SELECT * FROM users LIMIT"');

A: Doing str_replace("\t", ',', $output) would probably work.
Here's how you'd get it into an associative array (not what you asked but it could prove useful to helping you understanding how the output is formatted):
$output = $ssh->exec('mysql -uMyUser -pMyPassword MyTable -e "SELECT * FROM users LIMIT"');
$output = explode("\n", $output);
$colNames = explode("\t", $output[0]);
$colValues = explode("\t", $output[1]);

$cols = array_combine($colNames, $colValues);


Q: AWS EBS volume attachement using snapshot I am trying with AWS EBS volume. I created an EC2 Server using the AMI rancheros-v0.7.1-hvm-1. Then I attached volume and mounted to /var/lib/docker folder. Then I run few docker images on that server and I am able to access those applications also.
Later I created a snapshot of the volume. and launched another server using the same AMI and attached an EBS volume from the snapshot I created earlier and mounted to /var/lib/docker folder.
After that I ssh to the second server and did docker PS. But no docker Images are running there.
When I do df -kh command on first server the output was:
Filesystem                Size      Used Available Use% Mounted on
/dev/xvdb                29.4G      1.2G     26.7G   4% /var/lib/docker
/dev/xvdb                29.4G      1.2G     26.7G   4% /var/lib/docker/overlay
overlay                  29.4G      1.2G     26.7G   4% /var/lib/docker/overlay
.........

And followed by the docker images running.
But when I did the same command on the second server I got the output like this:
Filesystem                Size      Used Available Use% Mounted on

/dev/xvdb                29.4G     44.1M     27.8G   0% /var/lib/docker
/dev/xvdb                29.4G     44.1M     27.8G   0% /var/lib/docker/overlay

No docker images running also.
In both servers the use% are different.
Can any one tell me how can I check both are similar, and the snapshot contains all the data in the EBS volume? If the snapshot contains the similar data in the volume, then the second server should contain the docker images. But in my case its not happening.
This is the user data I gave while creating the EC2 server.
#!/bin/sh

sudo mkfs.ext4 /dev/xvdb

mkdir -p /var/lib/docker
echo "/dev/xvdb /var/lib/docker ext4 defaults 0 0" >> /etc/fstab
mount /dev/xvdb /var/lib/docker -t ext4

chown -R 1000 /var/lib/docker

Can anyone tell me a solution for this?

A: It worked now.
the server which I created from snapshot I should not create the file system. I have to remove this command
sudo mkfs.ext4 /dev/xvdb
from the user data. just create the folder and mount it. then it worked.


Q: A system of congruences Suppose $x,y$ are integers in $[T,2T]$ and $U,V$ are different primes in $[2T^{2+\epsilon},4T^{2+\epsilon}]$ then consider the congruences
$$U^2(x+y)^2=(aU^2+bUV+cV^2)\bmod (U-V)$$
$$UV(x+y)^2=(aU^2+bUV+cV^2)\bmod (U-V)$$
$$V^2(x+y)^2=(aU^2+bUV+cV^2)\bmod (U-V)$$
$$U^2(x+y)^2=(aU^2-bUV+cV^2)\bmod (U+V)$$
$$-UV(x+y)^2=(aU^2-bUV+cV^2)\bmod (U+V)$$
$$V^2(x+y)^2=(aU^2-bUV+cV^2)\bmod (U+V)$$
where $a,b,c\in[T^2,4T^2]$, $(aU^2+bUV+cV^2)\leq256T^{6+2\epsilon}$ and $a+b+c=(x+y)^2$.

Is $(aU^2+bUV+cV^2)=(Ux+Vy)^2$?

It is trivial
$$(aU^2+bUV+cV^2)=(Ux+Vy)^2+k(U-V)$$
holds at a $k=O(T^{4+\epsilon})$ from first three and
$$(aU^2-bUV+cV^2)=(Ux-Vy)^2+l(U+V)$$
holds at an $l=O(T^{4+\epsilon})$ from last three.
How to show $k,l=0$ is the question?


Q: How to add text into along the object using three.js I have added text into my object (a shirt model) using a text geometry. Here is my code:
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
ctx.font = 'italic 18px Arial';
ctx.textAlign = 'center';
ctx. textBaseline = 'middle';
ctx.fillStyle = 'red';
ctx.fillText('Your Text', 150, 50);`

My output looks like this:

The text does not fit into the shirt model. If I rotate the shirt model means text showing irrelevant view. I want to fit the text into the shirt model like this:

How can I fit my dynamic text into the shirt model using three.js.

A: if you are searching for " How to fit a 3D text in a 3D object" I will explain how to do this, lets begin with the theory,
Imagine having a flag with the form of the flag given sin(2*pi) if your camera is watching from y axis (three js axes) then you gonna add a text that exactly fits the function sin(2*pi), right?

so,
as you can see the idea of this is trying to get some tangets of sin(x) function, the secret of this is to cut the text in the number of tangents that will fit your text...
for the text, "Montiel Software" it will be now ["Mon","tiel","Soft","Ware"]
Flag:
function flag(u,v,vector)
{
var x = 10*u;
var y = 10*v;
var z = Math.sin(2*Math.PI*u) ;
vector.set(x,y,z);}

Create the Geometry:
var geometry_sin = new THREE.ParametricGeometry(flag, 100, 100);
var material_sin = new THREE.MeshPhongMaterial({map:groundTexture,side:THREE.DoubleSide, color:0x000000} );
var flag = new THREE.Mesh( geometry_sin, material_sin );

Now add the text to flag (choose your tangents here) then the flag to scene:
var loader = new THREE.FontLoader();
loader.load('js/examples/fonts/helvetiker_regular.typeface.json',function(font){
var geometry = new THREE.TextGeometry( 'Mon', {
        font: font,
        size: 1,
        height: 0.5,
        curveSegments: 12,
        bevelEnabled: false,
        bevelThickness: 0.1,
        bevelSize: 0.1,
        bevelSegments: 0.1
    } );
    var txt_mat = new THREE.MeshPhongMaterial({color:0xffffff});
    var txt_mesh = new THREE.Mesh(geometry, txt_mat);
    txt_mesh.position.z = 0.2;
    txt_mesh.position.y = 5;
    txt_mesh.rotation.y = -Math.PI/8;
    flag.add(txt_mesh);
    var geometry = new THREE.TextGeometry( 'tiel', {
        font: font,
        size: 1,
        height: 0.5,
        curveSegments: 12,
        bevelEnabled: false,
        bevelThickness: 0.1,
        bevelSize: 0.1,
        bevelSegments: 0.1
    } );
    var txt_mat = new THREE.MeshPhongMaterial({color:0xffffff});
    var txt_mesh = new THREE.Mesh(geometry, txt_mat);
    txt_mesh.position.z = 1.2;
    txt_mesh.position.x = 2.5;
    txt_mesh.position.y = 5;
    txt_mesh.rotation.y = Math.PI/12;
    flag.add(txt_mesh);
    var geometry = new THREE.TextGeometry( '$oft', {
        font: font,
        size: 1,
        height: 0.5,
        curveSegments: 12,
        bevelEnabled: false,
        bevelThickness: 0.1,
        bevelSize: 0.1,
        bevelSegments: 0.1
    } );
    var txt_mat = new THREE.MeshPhongMaterial({color:0xffffff});
    var txt_mesh = new THREE.Mesh(geometry, txt_mat);
    txt_mesh.position.z = 0.28;
    txt_mesh.position.x = 4.5;
    txt_mesh.position.y = 5;
    txt_mesh.rotation.y = Math.PI/7;
    flag.add(txt_mesh);
    var geometry = new THREE.TextGeometry( 'Ware', {
        font: font,
        size: 1,
        height: 0.5,
        curveSegments: 12,
        bevelEnabled: false,
        bevelThickness: 0.1,
        bevelSize: 0.1,
        bevelSegments: 0.1
    } );
    var txt_mat = new THREE.MeshPhongMaterial({color:0xffffff});
    var txt_mesh = new THREE.Mesh(geometry, txt_mat);
    txt_mesh.position.z = -1;
    txt_mesh.position.x = 7;
    txt_mesh.position.y = 5;
    txt_mesh.rotation.y = -Math.PI/8;
    flag.add(txt_mesh);

} );
scene.add(flag);

that's the only way I can imagine to do this in three JS, if you are just searching to make a 3D objet, I suggest you to install 3D builder and try options there then load the object to THREE js.

A: Simply drawing the text to your 2D canvas will most likely never give you a satisfactory result. You have three possibilities to tackle this issue.

*

*Using textures loaded with a THREE.TextureLoader.

*

*several examples here: http://threejs.org/examples

*tutorial: http://www.johannes-raida.de/tutorials/three.js/tutorial06/tutorial06.htm

*Using THREE.TextGeometry:

*

*an example: https://threejs.org/docs/index.html?q=textgeo#api/en/geometries/TextGeometry

*Using a CSS3D solution.

*

*a nice blog post on this topic: http://learningthreejs.com/blog/2013/04/30/closing-the-gap-between-html-and-webgl/

Check also the UI example on the THREE.TextGeometry documentation page:


Q: In which order should I start watching Star Trek? I don't know anything about Star Trek except for the fact that it's about spaceships.
In this question the person only wanted to watch the TV series. I want to watch every movie and TV series there is about Star Trek but I don't know where to start. I found this page on Wikipedia which is about a time line. Do I need to watch it in this order? Are the movies and TV series related?

A: This is really a matter of taste.
If you're interested in understanding the history of Star Trek, the way Star Trek interacted with American culture and the times it was made in -- watch it all in original broadcast order.  This can be looked up on the Internet.
Broadcast order is rather complicated.

*

*The Original Series has a production order which is different from the broadcast order.  It makes more internal sense, but gives less of a representation of how the "culture of the 60s" received the episodes.

*The original pilot for The Original Series, "The Cage", wasn't broadcast until the 1980s.  It's actually quite good.  You might want to watch it first.

*DS9 aired simultaneously with TNG and Voyager.

*Star Trek V, Star Trek VI, and the TNG movies aired simultaneously with various series.

*The widely available versions of Star Trek: The Motion Picture and Star Trek VI are NOT the original versions shown in theaters.  If you're looking for the true "how the culture received it at the time" version, you would have to dig up the original versions of both of them, and in the case of Star Trek VI, there are no such copies anywhere on the Internet and the only video release was altered.  In the case of The Motion Picture, most people think the director's cut is better, but it's not 100% period-authentic... the original version was released on videotape and can be found on the Internet if you research it.

*There is a widely-available version of The Original Series with doctored-up modern special effects.  Just avoid these and find the as-broadcast copies.  The special effects are the least of the problems with The Original Series; the sexism, bigotry, imperialism, and casual genocide in The Original Series are actually easier to watch when the show's visuals are reminding you how dated it is.

If you're not as much of a historian and don't mind some "revisionism" in your Star Trek, you may want to try a simplified order:

*

*The Cage

*The Original Series (production order)

*The Animated Series (most people would skip this; it's got decent plots but very flat animation)

*Star Trek: The Motion Picture (director's cut)

*Star Trek II, III, and IV in that order (each starts where the last one ends)

*Star Trek V (most people would skip this because it's generally considered bad; it was actually made and released after TNG was running)

*Star Trek VI (this was actually made and released after TNG was running, and is really a sort of "prequel" to TNG explaining why The Klingon Empire Is Different in TNG than it was in TOS and the first four movies)

*Star Trek: The Next Generation

*The various "Next Gen movies", from Generations to Nemesis.  These were actually overlapped with the broadcast of DS9, Voyager, and Enterprise, but it doesn't matter that much; there are a few references but they're vague and mostly irrelevant.

*Star Trek: Deep Space Nine.  The first two seasons overlapped the last two seasons of Next Gen, and there is some subtle plot overlap, but it's not essential to interlace the episodes.  The last five seasons overlapped the first five seasons of Voyager, but there is almost no overlap (there's one "easter egg" guest appearance from a Voyager character on DS9, but you can watch it without having watched Voyager).

*Star Trek: Voyager.  Most people would skip this entirely, as it suffered from a lot of really terrible episodes -- especially from heavy use of the "reset button" where huge, traumatic things happened and it's all magically back to normal by the end of the episode.  Another name for the "reset button" is "Voyager Syndrome".

*Enterprise.

*Abrams movies.  If you liked the rest of Star Trek, you'll probably hate these.  I would skip them.  They have the offensiveness of The Original Series without the intelligence, and without the excuse of being 50 years old.

Now the thing is, trying to watch all of Star Trek is a pretty big project, the style varies wildly from series to series, and I don't believe you're going to be able to run through it all in one go.  You will get bogged down in an entire season of episodes you don't like, sooner or later.  When this happens, here's my recommendation.
Every series except DS9 and season 3 of Enterprise can be watched out of order.  So can all the movies.
The Original Series: it can be groan-inducingly sexist.  Kirk's character is written wildly inconsistently from episode to episode.  The "Prime Directive" is introduced, then completely ignored as Kirk works to kill the last member of an endangered species (at least three times), overthrow the entire structure of a civilization (at least FIVE times), etc.  When you get bogged down, ask someone for a list of the good episodes ("Devil in the Dark" is one which everyone loves, as is "The Trouble with Tribbles") and the important episodes (ones which later series refer to, like "Space Seed", "The Naked Time", "Amok Time", etc.) and skip episodes such as "Spock's Brain" and "Metamorphosis" which later shows tried their best to ignore entirely.
The Animated Series: no later series refers to it; if you get bogged down, skip to the movies.
The Original Series movies: They're short, just watch them all, but if you're impatient, watch II, III, IV, and VI.  Nothing else ever refers to V, and I don't think anything refers to The Motion Picture.
TNG: you are unlikely to get bogged down -- this is the series with the most broad-based appeal -- but if you do get bogged down, first try jumping to the next season, then try skipping straight to DS9.  In the unlikely event that you don't like the episodes of TNG, you won't like the TNG movies, they're mostly like average-quality episodes, and they have no important continuity.
Later seasons of TNG set up some stuff for both DS9 and Voyager, mostly related to Cardassians, the Maquis, and Bajor (some related to the Klingons), but DS9 explains most of it again, and Voyager explains most of what it needs.  There are some DS9 references to TNG, and one to Voyager, but most of them are Easter Eggs, not essential.
DS9: if you're getting bogged down in season 1 or 2, keep going until you're partway through season 3.  If you're really stuck, skip to the last episode of season 1, and if you get stuck again, skip to the last episode of season 2.  DS9 takes a while to really get going, and I know a lot of people who were bored by seasons 1 or 2 and completely hooked by the middle of season 3.
DS9 is the most serialized of all the series, and really must be watched in order -- you get really serious payoffs for it.  The series ends with a TEN-PART story, eight episodes ending with "to be continued" followed by a two-hour finale.
Voyager: Voyager is off on the other side of the galaxy from DS9, so there are very few references between the two.  You will probably get bogged down in Voyager since so many episodes are so terrible.  No subsequent series refers to anything which happens in Voyager, and even the TNG movies have only "easter egg" levels of references.  If you get stuck, skip to Enterprise.
Enterprise: Enterprise is a prequel.  Enterprise seasons 1 and 2 are really really slow-paced and mellow.  I like them and I think they're worth pushing through.  Season 3 is a large plot arc which got pretty bad reviews.  If you get stuck in seasons 1,2, or 3, skip to season 4, and specifically skip to "Home" ("Storm Front" is resolving something from season 3).
Season 4 of Enterprise consists of several very thoughtful and intelligent multi-part stories which are rooted deeply in the 40-year history of Star Trek.   If after watching lots of other Star Trek, you get stuck in season 4 of Enterprise, you are not a Star Trek fan.  :-)  Do not try to watch it before watching lots of other Star Trek.

Now, that said, this isn't the order I originally saw any of this in.  My first Star Trek was Star Trek IV: The Voyage Home, which I saw on original release in the theaters (very much a movie of its time, which was 1986), which I love dearly, and I have been perpetually disappointed by how different every other episode of every Star Trek is from it.  But I still love DS9, and season 4 of Enterprise, and most of seasons 1 & 2 of Enterprise and most of TNG and the good episodes of TOS and TAS.

A: There are 3 possible starting-points, IMO.

*

*The beginning of the Original Series. Proceed to The Next Generation, Deep Space Nine, Voyager, then Enterprise.

*The beginning of Star TreK: The Next Generation. Proceed to Deep Space Nine, Voyager, Enterprise, then the Original Series.

*The beginning of Enterprise. Proceed to the first list, above.
The Original Series started everything, of course. You can watch everything in chronological order of release dates.
The Next Generation is essentially a fresh start. There are back-references that you will miss; but if you get hooked, you'll catch them on the second pass.
Star Trek: Enterprise, is the earliest series from the point-of-view of in-universe continuity. You may miss some details, such as the significance of certain events (like the Klingon's use of Human eugenics), but you'll pick up on these during the Original Series.
As for the movies, the Original Cast movies (1-6) can go between the Original series and the Next Generation. And the remaining Next Generation Cast movies (7-) can go anytime after The Next Generation series.

The rebooted movies, Star Trek and Star Trek: Into Darkness, can be enjoyed anytime, and at any level of familiarity with the original continuity.

A: There is no order for Star Trek as it depends much on your taste, and
available time.

*

*TOS is very dated. For an old timer like me, no other will replace
it, but it has often less appeal to a younger generation. I do
believe it was very influential intellectually on its generation,
with an unusual set of values, that were later developed in some of
the other series. It is really mostly a collection of rather
unrelated stories.

*TNG is very classical SciFi, with pretty good stories, well
structured context. You cannot be wrong with it.

*DS9 is imho the best and the most original series, with a number of
very good episodes (and a small number of pretty bad ones), a very
structured environment, a story with intertwinned themes covering
the whole series and organizing it, and many and varied well
developed characters, with original alien features. The anchoring on
the DS9 station actually offers a stronger sense of perspective.

*Voyager is more a collection of somewhat related episodes, pretty
much like TNG.  Though it has some very good parts, I think it did
not develop sufficiently its identity.

*Enterprise Takes place earlier than the others and is not always
fully consistent. It could have been quite good, and sometimes
is. It is more or less organized as a collection of substories of
many episodes. But it was too obviously commercial in some aspects,
including the ridiculous, almost embarassing, sexual role of the
Vulcan officier T'Pol. It is the only unfinished series. (though
Voyager seems to have been terminated rather abruptly)

*Then there is TAS, The Animated Series, which I have not watched yet.

*and of course the films, whenever you like.  They do not take as long
Then, you should also watch Star Wreck, which is a satyre of both Star Trek and Babylon 5, available for free on the Internet (legally).
And I discovered on a Care Bear dvd, bought for my grandson, several episodes directly inspired by Star Treck TOS.
But I am pretty sure there is more. Not to mention all the commentaries on DVD

A: I'd like to elaborate on TOS (The Original Series) and TNG (The Next Generation). In general, I'd recommend watching TOS first, but there is a caveat;
You have to be aware that TNG is how Roddenberry actually intended Star Trek to be like. Well, the part of TNG until he died, after that his vision was muddied (to varying degrees) by other people taking over. So, TOS has a lot of stuff in it that Roddenberry added to appeal to the station executives and possibly to the main-stream audience. His core ideology is in there, but you have to see past the occasional Cowboy-allusions and the depiction of gender roles (from today's point of view the latter is terrible, but for the time it was syndicated, it was actually progressive, but I digress).
So, if you watch TOS, you might not "get" it (well, chances are equally, you do), but don't despair in either case --- TNG is much better, but I'd still recommend having watched TOS first. The reason for this, is that you would have to watch TOS anyway, to watch Star Trek: Generations (Film #7). And by doing it first, you see how Humanity evolved between TOS and TNG. So, this is my suggestion;

*

*Star Trek: The Original Series

*Star Trek Films 1 through 6. Not 7!

*Star Trek: The Next Generation

*Star Trek Film 7

*Star Trek: Voyager

*Star Trek Films 8 through 10

*Star Trek: Deep Space Nine

*Star Trek: Enterprise

If you insist, you could watch DSN (Star Trek: Deep Space Nine) before Voyager (where it chronologically belongs), but I found it rather dry, and very distant from Roddenberry's Star Trek. Disclaimer: This is my personal opinion; a lot of people will tell you that VOY is awful and DSN is great.
And if you really insist, you may then watch Star Trek: Enterprise (ENT), which is the prequel to TOS, shot after VOY. It kind of goes in the opposite direction than TNG, starting from TOS. (Note that TOS, TNG and ENT take place on a ship called Enterprise, so don't confuse the series (ENT) with the ship.)
Finally, avoid watching the "new" films and expecting Star Trek. They are called Star Trek, but they decidedly have nothing to do with the classical franchise. They're action movies, and they work as such. But they're devoid of plot and meaning. So, watch them, if you really want to have watched everything, but do it only after having watched everything else above. Also, be careful with Into Darkness as it tries very hard and partially succeeds (IMO, obviously) to retroactively destroy the second film (Wrath of Khan).

A: I'm going to break the mold a bit, here.  There's a whole lot of stuff you'll want to watch, but there's also quite a few places where you could fall off.
For a modern viewer, consider what you're looking for.  If you want fantastic adventure, begin with Season 2 of Star Trek: The Next Generation.  First watch the pilot (Encounter at Farpoint) - it establishes the characters and will tell you 90% of what you need to know about them.  Season 2 is where the show 'grew the beard' (and originated that term) and started getting good.
If, instead, you are more interested in character-driven drama, begin with Star Trek: Deep Space Nine.  This show splits the Trek fans somewhat - they either love it or hate it.  It centers around a space station, not a starship, and is less episodic in nature than other shows in the Star Trek franchise.
Once you've started down the road, you will likely end up watching everything Star Trek if it catches your interest.  Rather than give you a viewing order, which others have already done, I'd like to give you a brief synopsis of each show and movie grouping.
Star Trek: The Original Series (TOS): The show that started it all.  A five year mission, exploring deep space.  The Klingons here look different from the rest of the Klingons you'll see in the newer stuff (especially the movies).  It's also very obviously from the 60s - the sets, costumes, music, etc are all dated to the modern eye.  Well worth watching, but go in understanding what it is: proto-Trek - the ideas are there, but it is limited by the technology and audiences of the time.
TOS-era Movies: General rule for movies 1-6: the odd numbers are nowhere near as good as the even.  Star Trek: The Motion Picture suffers from being written like an episode, not a movie.  II, III, and IV are a longer story arc involving easily the most tumultuous time in TOS.  II is likely the best Trek film.  V is likely the 2nd worst, but VI ends it on a high note and shows just how much some characters have grown and changed.
Star Trek: The Next Generation: This is what most viewers who've been with the show for a while think of when you say "Star Trek".  The plots are more complex than TOS, the characters more fully realized, and the ship feels like the future.  Ironically, many of the modern conveniences we have bear a striking resemblance to the things they have on the ship - datapads, communicators, even the ship control systems all influenced the generation of engineers that make our toys now.  The first season is painfully stop 'n go as actors and scripwriters figure out what works and what doesn't, but once it gets going it doesn't slow down much.
Star Trek: Deep Space Nine: This show pushes us out of our comfort zone a bit.  Especially in the early seasons, we're dealing much more with a few alien cultures in more than single episodes.  The primary focus is more on characters and how they interact (until the later seasons) and it uses TNG's later seasons as a jumping-off point.
TNG-era Movies: Starting with Generations, moving on through First Contact, Insurrection, and Nemesis, the TNG era movies are a mixed bag.  Insurrection and Nemesis are somewhat painful to watch (especially Nemesis, which is - in my opinion - extremely poorly written).  Generations is the hand-off movie, with the core players from TOS featured, but focusing on TNG's cast.  First Contact is likely the best movie from this set.
Star Trek: Voyager: You can enjoy this show.  There's a very, very large and vocal portion of the fanbase which hates it.  The first season suffers from a significant number of problems, many characters are never well fleshed out, and the only characters I really liked were The Doctor and 7 of 9.  After the mixed reviews of DS9, Voyager put the show back on a ship.  It isn't the Enterprise, and they wanted to break the ship away from the Federation.  Lost In Space-style shows were popular at the time, so Voyager hopped on the bandwagon.  Meeting new aliens and old enemies, Voyager must somehow defeat the odds and return home.  The premise was good, but the show was easily the worst Trek show.  It does improve towards the end, but not enough to save the show in general.
Enterprise: Set before TOS, before the Federation, this show focuses on humanity first exploring the stars.  Then time travel gets involved, and established canon goes out the window.  The show suffered from inconsistencies throughout it's run.  Characterization, scriptwriting, character dynamics, nothing ever stabilized.  It's a fun show to watch and it features a deeper exploration of the Federation's core races than most other shows have seen, but it failed to live up to the quality of TNG and DS9.  It does, however, handily surpass Voyager.
Star Trek and Star Trek: Into Darkness: Abrams takes the reins.  These movies are set before TOS, when the crew of the original TOS Enterprise are fresh from the Academy, long before their 5-year mission.  Within the first 15 minutes of the first film, existing canon is dragged behind the chemical shed, shot, and thrown into a shallow grave.  These movies, especially the first one, are pure popcorn flicks.  They have the window dressing of Trek, they have the elements of Trek, but the first movie was missing something important.  Into Darkness, however, realized it.  They cared for the script more, they built a more believable story around what the first movie left behind, and it played well as a tribute to the best movie in the franchise (Star Trek II: The Wrath of Khan).  The references were done well without seeming cheesy or forced, and they toned down the worst elements of the first reboot movie.
Edit, aside:
Galaxy Quest: Not technically related to Star Trek.  It's an entirely different universe, and entirely different cast, and it takes place on our earth, in our time.
Doesn't matter.  It's been said, and I agree with it, that Galaxy Quest is the best Star Trek movie.

A: I'd simply go in production order - it's how most of us did it growing up (although, I didn't see any of the animated series until well after TNG was airing. Then again, some people don't put TAS and Star Trek in the same breath).
Why? Well, the universe itself develops through the various series and movies (even the prequel series Enterprise adds more). It would be weird to watch a later episode or movie, and then watch an earlier produced episode which is set in a less developed universe, and may well contradict what you already know about the universe.
So, we have:

*

*The Original Series - all seasons

*The Animated Series (if you insist - this series isn't treated as canon)

*Movie: The Motion Picture

*Movie: Wrath of Khan

*Movie: The Search for Spock

*Movie: The Voyage Home

*The Next Generation season 1 and 2

*Movie: The Final Frontier

*The Next Generation season 3 and 4

*Movie: The Undiscovered Country

*The Next Generation season 5 and 6

*Deep Space Nine season 1

*The Next Generation season 7

*Deep Space Nine season 2

*Movie: Generations

*Deep Space Nine season 3

*Voyager season 1

*Deep Space Nine season 4

*Voyager season 2

*Movie: First Contact

*Deep Space Nine season 5

*Voyager season 3

*Deep Space Nine season 6

*Voyager season 4

*Movie: Insurrection

*Deep Space Nine season 7

*Voyager season 5, 6, 7

*Enterprise season 1

*Movie: Nemesis

*Enterprise season 2, 3, 4

*Movie: Star Trek (reboot)

*Movie: Into Darkness

A: Start by watching TNG starting from Series 3 or alternatively, the "Best of the Best" of TOS (see list below for my recommedations).
I'm also going to throw up what may be the most controversial opinion on this site, but one that I find pretty compelling.
The New Movies are better films than any other Star Trek film apart from Wrath of Kahn, which is itself very dependent on a love of TOS. There is nothing wrong with watching them first, and then delving back into the original lore.
So I'd recommend:

*

*Film: Star Trek 2009

*Film: Into Darkness

*Series: Original 60's "Best of the Best" (for example:)

*

*"Arena"

*"A Taste of Armageddon"

*"Space Seed"

*"Errand of Mercy"

*"The City on the Edge of Forever"

*"Mirror, Mirror"

*"The Trouble with Tribbles"

*"I, Mudd"

*"Journey to Babel"

*Series: The Next Generation Seasons 3
After that, if you've got a taste for the show, you can kind of chart your own course. If you liked The Original Series, you can keep watching that, and move onto the films.
If you preferred The Next Generation, there are 6 other series to watch.
And if you find the whole thing a bit naive, then I cannot recommend DS9 highly enough, which starts to investigate the darker side of Trek, for example, what happens when principles meet war.
And finally, if you're looking for something a bit more cinematic, the new films are great, very much continuing a legacy that looked for a while in danger of disappearing up its own canon.

Justification for my views on the films:
I think there's a tendency to Rose-Coloured Spectacles the older series, partly because you mentally edit for the highlights.
As someone who's watched all the early Trek after first release (in the case of TOS, long after), it can be best described as "moments of genius".
But there's also a lot of truly dated stuff, especially in TOS, and in some cases some simply awful episodes.
Almost all Season 1 and most of Season 2 of TNG, for example, is a MESS. I sat and watched all of Season 1 over a few days, and remember thinking "Under any serious scrutiny, this would have been cancelled by Code of Honor". The show manages to build on this, but there are some serious teething troubles.
The new movies stand alone, and in my opinion, successfully blend the debates and thoughtfulness of TOS and TNG with action, which is what a film needs. A lot of the major fans loved the way that the show was very much about people in rooms talking about issues, and any deviation from that is considered "dumbing down".

A: I myself am currently attempting a chronological viewing order (http://www.johnstonsarchive.net/startrek/st-episodes-1.html). TOS is, as oft mentioned, a bit dated and although there is a lot of humour and some really good eps you may want to skip right to TNG.
DS9 is indeed an oddball, it plays out mostly on a station instead of a ship but it is the only Trek in which most characters were explored deeply, even some ancillaries like Quark and Dukat have become much rounder characters than ancillaries in any other show have. It's great if you like the drama element but must be viewed in chronological order starting from about halfway season 3.
Whether or not you do watch TOS I can really recommend the fan production Phase II (once named New Voyages). It's only got a few episodes and has a good overall quality. The sets have even been used in Enterprise. Another fan-production worth watching is Of Gods and Men.
There are, thus, two possible orders:
 - Production order (mostly) (TOS - Phase II - Movies 1 through 6 - Of Gods and Men -TNG (and movies 7-10)/DS9/VOY-ENT)
 - Chronological order (With Phase II directly after TOS and Of Gods and Men after the sixth movie)
One more thing, skip the fifth movie, it'll leave you disappointed for decades to come.

A: The question and its answers are even more complex than the other answers indicate.
Star Trek: The Original Series (TOS) episodes are often considered to fictionally happen in one of three orders.

*

*Original broadcast order.  NBC selected episodes to broadcast from those delivered so far by the production company, going by which episodes seemed beter for which airdates.

*Production order.   The order in which the principal photography of scenes with the actors was completed.  The production dates of TOS episodes are listed in Wikipedia articles and Memory Alpha, etc.

*Order of stardates in episodes.  Of course not every episode had one or more stardates, so some rule to put those in order is neeeded.
And I could add:

*In order of seasons and then by order of stardates within seasons, since the stardates of episodes in different seasons overlapped slightly.

And maybe:

*order of episode number code, which may be different from number 2.

And These possible viewing orders also apply to the animated Star Trek (TAS), the TOS era movies, and the first season of Star Trek: The Next Generation (TNG).
But starting with the second season of Star trek: The Next Generation (TNG) and continuing with Star Trek: Deep Space Nine (DS9), and Star Trek: Voyager (VOY), most episodes have the same production order, broadcast order and stardate (if any stardate is in the episode) order.  Thus fans rarely have to choose between those different orders when choosing which order to view episodes of those series.  It is possible the change between the first and the second seasons of TNG is related to a change in the stardate system used by Starfleet.
there are only a few problems with choosing which order to view the episodes within a series set in the TNG era.
But DS9 started to be produced and broadcast before TNG ended, and VOY began to be produced and broadcast before DS9 ended.  So during eras when two of those shows were being made and broadcast at the same time, a fan who wants to watch that two will have to decide whether to finish one series before starting the next, or to switch between episodes of different shows by broadcast, production, or stardate, order.
Four TNG movies were also made during that time, taking place while DS9 and VOY were happening.  Someone could watch the four tNG movies after TNG and before DS9 and VOY, or mix them in with the later shows according to various possible orders.
The next series to be produced, Star Trek: Enterprise (ENT), was set about a century before TOS and stardates were not yet used.  Thus the three main orders that ENT episodes could be viewed in are:

*

*Original broadcast order.

*Production order.   The order in which the principal photography of scenes with the actors was completed.

*Earth date order, for those episodes whose Earth dates are mentioned.  Some other rule would be necessary to put the other episodes, with no Earth dates mentioned, in their proper order.
The next Star Trek productions were three movies, Star Trek  (2009), Star Trek Into Darkness (2013), and Star Trek Beyond (2016).  Those movies happen in an alternate universe caused by time travel to the time of Kirk's birth and should happen before TOS starts.
I may note that the official chronology is not canon, and thus could be, and in my opinion is, inaccurate.  On Earth there are many different calendar eras used to count the years from.  There are tens or hundreds of years mentioned as mere numbers in various productions, but as far as I known only about half a dozen are explictly Anno Domini  dates.  And I have found examples when dates would have to be given using different calendar eras to be consistent with each other.  Since the official chronology assumes that each and every date uses the Anno Domini calendar era, the official chronology must be wrong.
https://en.wikipedia.org/wiki/Calendar_era[1]
https://en.wikipedia.org/wiki/Anno_Domini[2]
Of the current Star Trek productions, the Discovery series is highly serialized, each episode following the perviously episode in fictional order, and telling a story in each season.  The first two seasons were about 10 years before TOS, and at the end of the second season the Discovery and its crew jumped many centuries into the future, the setting of the third season.
So Discovery could be watched as a whole, at either the time the first two seasons are set in, or at the far future time of the third season.  Or the first two seasons could be watched between ENT and TOS, and the third season could be watched later than all of the other shows and movies produced so far.
Picard is set about 30 years after TNG, and also has a serialized timeline.
Short Treks is an anthology series, set at many different fictional eras.  So someone could watch all the episodes at one time, despite the different eras they are set in, or try to look up the fictional eras of each episode and watch it in the proper chronological order.
I note that one episode that I saw, "Ephraim and Dot", was set over a period of decades during TOS and the TOS movies, and that events from TOS episodes are depicted in a much different order in "Ephraim and Dot" than in any usual viewing order for TOS episodes.
Another episode, "Children of Mars", should be a prequel to Picard.
In "The Girl Who Made the Stars", the frame story should be a couple of decades before the first season of Discovery, and the main story is a legend set in a prehistoric era
Lower Decks is set about 16 years after the first season of TNG and so should be after VOY and before Picard.
The future series Prodigy will have Captain Kathryn Janeway of the Voyager as as a character, but I don't know whether it will happen before, during, or after Voyager.
The future series Star Trek: Strange New Worlds  will happen on the USS Enterprise under the command of Captain Christopher Pike, about a decade before TOS, and thus about the same time as the first two seasons of Discovery.
Another way to watch star Trek shows and movies would be in the order that they were made, and broadcast or released.  This article gives a list of the various shows and movies:
https://en.wikipedia.org/wiki/List_of_Star_Trek_films_and_television_series#Feature_films[3]

A: well, I have my own ordered list of star trek series which is pretty simple...

*

*Star Trek TNG

*Star Trek DS9

*Star Trek Enterprise

*Star Trek Voyager

This is not related to anything like order of filming, stardates or anything. It's just my personal preference, based on what I've already seen (about 85% of all series).

A: *

*Original Series

*Movies: 1-6

*TNG

*Movie: 7

*Movie: 8-10

*Star Trek 2009 and into darkness

*Deep space nine

*Voyager( the only ST TV show that wasn't good)

A: For modern viewers who don't want to watch TOS, here's a shortcut...
Start with TOS - "Space Seed" Then Watch The Wrath of Khan.
After that, you're done with the original series - go straight to TNG and enjoy from there on in production order.

A: Here's a good amount of stories to get a coherent idea about what Star Trek is about, in order watch:

*

*"Where no man has gone before" (the real first episode)

*"The naked time" (it has a sequel in The Next Generation)

*"The enemy within" (it's been parodied)

*"Balance of terror" (introduces Romulans in a classic submarine style thriller)

*"Day of the Dove" (good introduction to Klingons)

*"Arena" (it's been referenced in Bill and Ted's Bogus Journey, among others)

*"Space Seed" (Star Trek II is a sequel)

*"City on the edge of forever" (award winning time travel drama)

*"Amok Time" (explains Vulcan mating habits)

*"Mirror mirror" (the alternate "evil" universe. You've seen it referenced)

*"Trouble with tribbles" (funniest episode ever)

*Star Trek II The Wrath of Khan (Star Trek the Motion Picture is unnecessary)

*Star Trek III The Search for Spock (Direct sequel to II)

*Star Trek IV (funny and accessible)

*Star Trek the Next Generation: Encounter at Farpoint (the pilot)

*"Q Who" (introduction of the Borg)

*"Best of Both Worlds" (most consequential confrontation with the Borg)

It depends which characters from TOS and TNG you want to see more of after that.
I'd recommend the movies Generations and First Contact next.
Then, watch the pilots of Deep Space Nine ("Emissary"), Voyager ("Caretaker"), and Enterprise ("Broken Bow") to see if they interest you. Or watch the JJ Abrams movies if you've grown to love the Original Series crew but wouldn't mind new actors playing them.


Q: Git deployment of October CMS site I set up Git deployment for most of my sites and it work really well. I have recently started to work with October, and for main pages which I create myself, I would like to work locally and then use Git to deploy new and updated pages to the live server.
It is my understanding that (apart from blog plugins for instance) October uses flat files for it's content. If I create files locally within my local install of October, can I safely Git push only the files I have worked on (html, css, js etc.) up to the site along with front matter and have them work on the remote deployment server? Will October just integrate them?

A: Yes, you can use git to deploy your site content and manage it via version control.
You can set your .gitignore to the following folders
.DS_Store
*.log
/vendor
/storage
/plugins/october
/modules/**/*
/config
/bootstrap
/themes/demo
artisan
index.php
.htaccess

And it will upload the text/theme files you add/commit.
After the git pull you might wish to do a cache refresh
php artisan cache:clear

or install the cache clear widget(https://octobercms.com/plugin/romanov-clearcachewidget)


Q: How to find the slope for an equation of the third degree? I need your help.
My question is, how do I find the slope for an equation of the third degree?
For example, if we want to find the slope for an equation of the second degree, we find its first derivative like this:
$$f(x)= x^2 -1 \Rightarrow
f'(x)= 2x \Rightarrow
f'(1)=2$$
Slope is equal to $2$ in our example. However, I do not know how to find the slope for an equation of the third degree. I need your help!
Clear example with images would be appreciated.
Thanks everybody.

A: The derivative gives you the slope of a tangent at a given point. So if you want to find the slope of, say $f(x)=x^3-12x-5$ at $x=3$, you would differentiate it once to get $f'(x)=3x^2-12$ and substitute in $x=3$. So the slope of the equation at $x=3$ would be $15$.
It doesn't matter what type of function you have, the first derivative will always give you the slope of the function.

A: $6$ times spelling "slop." $5$ times spelling "fined." I didn't even know browsers without autocorrect/spell-check existed.
To answer your question, you need to learn the general rule to take the derivative of a function. The rule you're looking for is the power rule, which states that, if $\varphi$ is some constant and $u$ is some variable, then:
$$\frac{d}{dx}u^\varphi=\varphi u^{\varphi -1}\frac{du}{dx}$$
In this case, since $u$ is $x$, this can be changed to be:
$$\frac{d}{dx}x^\varphi=\varphi x^{\varphi -1}$$
Hence, when you have $x^2$, its slope would be $2x^{2-1}=2x$. Therefore, for a third power, $x^3$ for instance would be $3x^{3-1}=3x^2$.


Q: How to shrink the storage size limit of IPFS? I am using IPFS and trying to understand its structure.
ISSUE: 1
The issue I am facing is that when I am trying to shrink the storage size of IPFS (for testing it is taking so long time, hence I just want to shrink File System for a while) but is unable to shrink.
I tried to configure the config file by changing the StorageMax limit
using this command

ipfs config Datastore.StorageMax 1GB

but still it does not work, it accepting (ipfs add ) the files after the 1GB also, why he is not limiting the file-storage?
anyone, please suggest me How to reduce file-system size?
ISSUE: 2
Even in case of IPFS's default storage limit (Which is 10 GB), I saw when I am adding the files on IPFS it is not stopping to store files after crosses 10GB (which was limit).
It should not be cross after the limit ends, for this what to do?
below is the config file
{
  "API": {
    "HTTPHeaders": {}
  },
  "Addresses": {
    "API": "/ip4/0.0.0.0/tcp/5001",
    "Announce": [],
    "Gateway": "/ip4/0.0.0.0/tcp/8080",
    "NoAnnounce": [],
    "Swarm": [
      "/ip4/0.0.0.0/tcp/4001",
      "/ip6/::/tcp/4001"
    ]
  },
  "Bootstrap": [
    "/dnsaddr/bootstrap.libp2p.io/ipfs/QmNnooDu7bfjPFoTZYxMWUQJyrVwtbZg5gBMjTezGAJN",
    "/dnsaddr/bootstrap.libp2p.io/ipfs/QmQCU2EcMqAqQPR2i9bChGNJchTbq5TbXJJ16u19uLTa",
    "/dnsaddr/bootstrap.libp2p.io/ipfs/QmbLHAnMoJPWSCR5Zhtx6BX9KiKNN6tpvbUcqanj75Nb",
    "/dnsaddr/bootstrap.libp2p.io/ipfs/QmcZf59bWwK5XFi76CZX8cbBhTzzA3gU1ZjYZcYW3dwt",
    "/ip4/104.131.131.82/tcp/4001/ipfs/QmaCpDMGvV2BGHeYERUEQAwe3N8SzbUtfsmvsqQLuvuJ",
    "/ip4/104.236.179.241/tcp/4001/ipfs/QmSoLPppuBtQSGwKDZT2MULpjvfd3aZ6ha4oFGL1KrGM",
    "/ip4/128.199.219.111/tcp/4001/ipfs/QmSoLSafTMBsPKadTEgaXDQVcqN88CNLHXMkTNwMKPnu",
    "/ip4/104.236.76.40/tcp/4001/ipfs/QmSoLV4Bbm51jM9C4gDYZCy3U6aXMJDAbzgu2fzaDs64",
    "/ip4/178.62.158.247/tcp/4001/ipfs/QmSoLer265NRgSp2LA3dPakiS1J6DifTC88f5uVQKNAd",
    "/ip6/2604:a880:1:20::203:d001/tcp/4001/ipfs/QmSoLPppuBtQSGwKDZT2M7Lpjvfd3aZ6ha4oFGL1KrGM",
    "/ip6/2400:6180:0:d0::151:6001/tcp/4001/ipfs/QmSoLSafTMBsPKadTEgaXctVcqN88CNLHXMkTNwMKPnu",
    "/ip6/2604:a880:800:10::4a:5001/tcp/4001/ipfs/QmSoLV4Bbm51jM9C4gDYZQ9Cy3U6aXMJDAbzgu2fzaDs64",
    "/ip6/2a03:b0c0:0:1010::23:1001/tcp/4001/ipfs/QmSoLer265NRgSp2LA3dPaeykiS1J6DifTC88f5uVQKNAd"
  ],
  "Datastore": {
    "BloomFilterSize": 0,
    "GCPeriod": "1h",
    "HashOnRead": false,
    "Spec": {
      "mounts": [
        {
          "child": {
            "path": "blocks",
            "shardFunc": "/repo/flatfs/shard/v1/next-to-last/2",
            "sync": true,
            "type": "flatfs"
          },
          "mountpoint": "/blocks",
          "prefix": "flatfs.datastore",
          "type": "measure"
        },
        {
          "child": {
            "compression": "none",
            "path": "datastore",
            "type": "levelds"
          },
          "mountpoint": "/",
          "prefix": "leveldb.datastore",
          "type": "measure"
        }
      ],
      "type": "mount"
    },
    "StorageGCWatermark": 0,
    "StorageMax": "1GB"
  },
  "Discovery": {
    "MDNS": {
      "Enabled": true,
      "Interval": 10
    }
  },
  "Experimental": {
    "FilestoreEnabled": false,
    "Libp2pStreamMounting": false,
    "P2pHttpProxy": false,
    "QUIC": false,
    "ShardingEnabled": false,
    "UrlstoreEnabled": false
  },
  "Gateway": {
    "APICommands": [],
    "HTTPHeaders": {
      "Access-Control-Allow-Headers": [
        "X-Requested-With",
        "Range"
      ],
      "Access-Control-Allow-Methods": [
        "GET"
      ],
      "Access-Control-Allow-Origin": [
        "*"
      ]
    },
    "PathPrefixes": [],
    "RootRedirect": "",
    "Writable": false
  },
  "Identity": {
    "PeerID": "QmfB8xVzjndgMWHuxszYADGrwBo1Zx6zjBQQCsqARDupsW"
  },
  "Ipns": {
    "RecordLifetime": "",
    "RepublishPeriod": "",
    "ResolveCacheSize": 128
  },
  "Mounts": {
    "FuseAllowOther": false,
    "IPFS": "/ipfs",
    "IPNS": "/ipns"
  },
  "Pubsub": {
    "DisableSigning": false,
    "Router": "",
    "StrictSignatureVerification": false
  },
  "Reprovider": {
    "Interval": "12h",
    "Strategy": "all"
  },
  "Routing": {
    "Type": "dht"
  },
  "Swarm": {
    "AddrFilters": null,
    "ConnMgr": {
      "GracePeriod": "20s",
      "HighWater": 900,
      "LowWater": 600,
      "Type": "basic"
    },
    "DisableBandwidthMetrics": false,
    "DisableNatPortMap": false,
    "DisableRelay": false,
    "EnableRelayHop": false
  }
}

A: It looks like StorageMax does not actually limit the size of the IPFS node, instead it's used to determine whether or not to run garbage collection. IPFS will write until the disk is full.


Q: Windows EFS encryption + password protection? I would like to encrypt files / folders in Windows with EFS. In addition — because EFS alone still leaves the files / folders unprotected in case an adversary managers to access my Windows profile — I would like to password-protect those files / folders. But how? On my own, private PC, where I can create any number of (administrator and of course normal) users. I thought of EFS-encrypting the according files / folders under another user of mine, then switching again back to my default user account where I'd now of course be excluded from access to those files / folders. From the other user (used for encryption), however, I imported the EFS certificate into my default user account to regain access. But to no avail: I still I couldn't open those files.
Please tell me: is there a way to achieve what I tried to do with (preferrably native) Windows tools like EFS + certificates or other solutions (excluding  Bitlocker, which is only good to encrypt whole drives >30GB)? And possibly in an easier way than I described, e.g. like transferring access to another (administrator?) user of mine which subsequently requires other users to enter a password to open if that's possible way to go? Or anything else, please? If not Windows-native, then at least available from the File Explorer context menu?

Bonus question: although I was not able to open the above-mentioned files / folders, I was very well able to delete them. I imagine that
if the other user had actually been someone else this might be a
disaster for him — is there a way to prevent unauthorized users from
deleting files? I mean I know related permissions can be set in the
Windows file properties, but afterwards it only took me (using my default
user without read access) to "take ownership" of the file again, and although I still I couldn't read it, I could very well delete it...

Info just in case it surprisingly matters: the used (EFS encryption-) test files and EFS certificate im-/export happened via a
Bitlocker-protected USB drive used under both test user accounts).


Q: Loading data into json file How can i update json file from model in sap ui5?
    var oModel  = new sap.ui.model.json.JSONModel();
    oModel.loadData("json/Product.json");

I have to update my product.json file.
Please give me your suggestion...
Thank you very much in advance.

A: You cannot update a JSON file stored on your server with UI5 or any client side library. You will need a server-side script with some file writing code to do it. You should use an OData service and perform any read/write operations to it.


Q: How to fix Signal Handler assignment For Linux C programming, I have this handler and main method:
void handler(int number, signinfo_t, void *ignore){
    printf("Signaling %d\n", si->si_pid);
}

int main(){
    struct sigaction sig;
    sig.sa_flags = SA_SIGINFO;
    sigemptyset(&sig.sa_mask);
    sig.sa_handler = handler // This line has error

If I make the handler with just 1 parameter void handler(int num)
it works fine; however, I will not be able to use si->si_pid. The warning I am getting is :
 warning: assignment to __sighandler_t from an incompatible pointer type
 -Wincompatible-pointer-types
 sig.sa_handler = handler;

Do I make it sig.sa_action instead? I want to fix the warning

A: You're assigning the handler function to the wrong member of sig. The declaration of struct sigaction is:
struct sigaction {
    void     (*sa_handler)(int);
    void     (*sa_sigaction)(int, siginfo_t *, void *);
    sigset_t   sa_mask;
    int        sa_flags;
    void     (*sa_restorer)(void);
};

sig.sa_handler is a function with only one argument, the signal number. When you use the SA_SIGINFO flag, you need to assign the 3-argument function to sig.sa_sigaction instead.
int main(){
    struct sigaction sig;
    sig.sa_flags = SA_SIGINFO;
    sigemptyset(&sig.sa_mask);
    sig.sa_sigaction = handler;


Q: loading div only visible on referrer I've got a minor problem I'm trying to resolve on my website. I have it currently so that a loading screen div appears above the page when the user visits and then fades away after a set time/the page is loaded, whichever comes latest. I want this div only to appear on first visit and would prefer to avoid cookies or anything server side. From what I understand I want to utilize session storage or referrer but have not had success with implementing that. Also, subsequent pages have a less prominent and faster loading screen that will have to go away only when each individual page has been visited once during the session. The applicable code is:
css:
.js div#preloader {
    position: fixed;
    left: 0;
    top: 0;
    z-index: 1000;
    width: 100%;
    height: 100%;
    overflow: visible;
    background-color: #202020;}

#preloader {
    z-index: 1000; }

js:
 jQuery(document).ready(function ($) {
 $(window).load(function () {
    setTimeout(function(){
        $('#preloader').fadeOut(1500, function () {
        });

    },5000);

   });
});

So it's likely obvious that I'm not well informed; I'm teaching myself as I go and needless to say I have a lot to learn about javascript. If I've done something horribly wrong here, which is entirely plausible, or a working demo is required, please let me know.
Thanks!

A: You can probably accomplish what you want using the sessionStorage object. In that object, you can track which pages have been visited in the current session.
The issue you can run into with JavaScript (and the reason I said it may not be the best approach) is that, when using a library, there is always a finite amount of time that passes while the library is loaded, parsed, and executed. This makes your "only appear on the first visit" requirement somewhat difficult to accomplish in JavaScript. If you show it by default and hide it with library code, it will show briefly each time you go to the page. If you hide it by default and show it with library code, it will be briefly hidden the first time you go to the page.
One way to handle this is to use embedded JavaScript that is executed immediately after the DOM for the preloader is defined. The downside to this is that you have to know how to write cross-browser JavaScript without assistance from a library like jQuery. In your case, the JavaScript required to simply hide the preloader is simple enough that it shouldn't have any cross-browser issues.
I created a simple page that demonstrates the technique. The source for this page is:

Preloader

This is the text of the body

I also created a fiddle for it: http://jsfiddle.net/cdvhvwmm/


Q: How to upgrade to mysql 5.6 in ubuntu 12.04 I was needed to upgrade mysql 5.5 to 5.6, to avoid some issues on importing sql files.

ERROR 1293 (HY000) at line 231: Incorrect table definition; there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT or ON UPDATE clause

How do you upgrade it?

A: Just run the following commands:
apt-get -y remove mysql-server
apt-get -y autoremove
apt-get -y install software-properties-common
add-apt-repository -y ppa:ondrej/mysql-5.6
apt-get update
apt-get -y install mysql-server


Q: Sorting string value in a case-insensitive manner in Java 8 How do I sort string values in case-insensitive order in the following?
List<Employee> listofEmployees = Arrays.asList(
    new Employee(1, "aaa", Arrays.asList(123, 345, 678)),
    new Employee(1, "bbb", Arrays.asList(91011, 121314, 1516117)),
    new Employee(2, "ccc", Arrays.asList(181920, 212223, 242526)),
    new Employee(3, "ddd", Arrays.asList(272829, 303132, 333435)),
    new Employee(4, "BBB", Arrays.asList(29, 332, 33))
);

I wrote like this:
listofEmployees.stream().sorted(Comparator.comparing(Employee::getName).reversed())
        .forEach(s -> System.out.println(s.getName()));

How do I pass a string case insensitive option here?

A: This is one of many ways:
listofEmployees.stream()
    .sorted((o1, o2) -> o1.getName().compareToIgnoreCase(o2.getName()))
    .forEach(s -> System.out.println(s.getName()));

A: As @Tree suggested in comments, one can use the java.text.Collator for a case-insensitive and locale-sensitive String comparison. The following shows how both case and accents could be ignored for US English:
Collator collator = Collator.getInstance(Locale.US);
collator.setStrength(Collator.PRIMARY);
listOfEmployees.sort(Comparator.comparing(Employee::getName, collator.reversed()));

When collator strength is set to PRIMARY, then only PRIMARY differences are considered significant during comparison. Therefore, the following Strings are considered equivalent:
if (collator.compare("abc", "ABC") == 0) {
    System.out.println("Strings are equivalent");
}

A: You can specify it as the second argument to ignore cases:
Comparator.comparing(Employee::getName, String::compareToIgnoreCase).reversed()

A: Try this
Comparator.comparing(Employee::getName, String.CASE_INSENSITIVE_ORDER)

A: It looks like there is a Comparator that orders String objects as by compareToIgnoreCase, you can read the documentation here: https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#CASE_INSENSITIVE_ORDER

A: You can lowercase or uppercase it like this:
listofEmployees.stream()
               .sorted(Comparator.comparing((Employee e) -> e.getName()
                                 .toLowerCase()) // or toUpperCase
                                 .reversed())
               .forEach(s -> System.out.println(s.getName()));


Q: installing libjpeg for pil and Google app engine on mac Mountain Lion I'm sure there's a duplicate of this somewhere out there but I looked and am about at the end of my rope.  I'm trying get PIL working on my mac OS X 10.8 so that I can use dev_appserver.py to test an imaging feature.  First I had trouble installing PIL until I got Homebrew and installed it using brew install pil.  I was under the opinion that brew installed all the necessary dependencies but when I tried to resize a jpeg in my app, it says IOError: decoder jpeg is not available.  So I looked online and most places said I needed to (1) uninstall PIL, (2) install libjpeg from source and (3) reinstall PIL.  So, I brew uninstall PIL, and then
curl -O www.ijg.org/files/jpegsrc.v7.tar.gz
tar zxvf jpegsrc.v7.tar.gz
cd jpeg-7d/
./configure
make
make install

and finally brew install pil.  I restart dev_appserver.py and reload the page on localhost, but same error.  I tested pil out from the python command-line with
>>> from PIL.Image import Image
>>> f = open("someimagefile", "rb")
>>> i = Image()
>>> i.fromstring(f.read(), decoder_name="jpeg")
Traceback blah blah blah
IOError: decoder jpeg not available

I don't have much experience installing utilities from command-line, so I probably missed something obvious.  Again, sorry if there are duplicates, but like I said, I looked and couldn't find anything that seemed to work.

A: Finally got it working!  Thanks to @zgoda and this link.  Here are the steps I ended up with for those of you who have the same problem:
First make sure PIL is not installed.  Download libjpeg from http://www.ijg.org/files/jpegsrc.v8c.tar.gz, unpacked it, ./configure, and make.  When I tried to make install it couldn't find the directory to store the man pages so installation failed.  I looked at the information on the above link and decided to
cp -r ~/Downloads/jpeg-6d/ /usr/local/jpeg
I suspect if the installation goes fine than that line isn't necessary.
Then edit the following line in PIL's setup.py:
JPEG_ROOT = None

to
JPEG_ROOT = "/usr/local/jpeg"

finally:
$ python setup.py build
$ python setup.py install

A: PIL did not found libjpeg headers during compilation. Consult your build system documentation on how to specify headers ("includes") location, eg. as environment variables.