text:
Q: cassandra spark connector read performance I have some Spark experience but just starting out with Cassandra. I am trying to do a very simple read and getting really bad performance -- can't tell why. Here is the code I am using:
sc.cassandraTable("nt_live_october","nt")
  .where("group_id='254358'")
  .where("epoch >=1443916800 and epoch<=1444348800")
  .first

all 3 params are part of the key on the table:

PRIMARY KEY (group_id, epoch, group_name, auto_generated_uuid_field)
) WITH CLUSTERING ORDER BY (epoch ASC, group_name ASC, auto_generated_uuid_field ASC)

And the output I see from my driver is like this:

15/10/07 15:05:02 INFO CassandraConnector: Connected to Cassandra
cluster: shakassandra 15/10/07 15:07:02 ERROR Session: Error
creating pool to attila./198.xxx:9042
com.datastax.driver.core.ConnectionException:
[attila./198.xxx:9042] Unexpected error
during transport initialization
(com.datastax.driver.core.OperationTimedOutException: [attila
/198.xxx:9042] Operation timed out)
15/10/07 15:07:02 INFO SparkContext: Starting job: take at
CassandraRDD.scala:121
15/10/07 15:07:03 INFO BlockManagerInfo:
Added broadcast_5_piece0 in memory on
osd09:39903 (size: 4.8 KB, free: 265.4 MB)
15/10/07 15:08:23 INFO TaskSetManager: Finished task 0.0 in stage 6.0
(TID 8) in 80153 ms on osd09 (1/1)
15/10/07 15:08:23 INFO TaskSetManager: Finished task 0.0 in stage 6.0 (TID 8)
in 80153 ms on osd09 (1/1)
15/10/07 15:08:23
INFO DAGScheduler: ResultStage 6 (take at CassandraRDD.scala:121)
finished in 80.958 s 15/10/07 15:08:23 INFO TaskSchedulerImpl: Removed
TaskSet 6.0, whose tasks have all completed, from pool
15/10/07 15:08:23 INFO DAGScheduler: Job 5 finished: take at
CassandraRDD.scala:121, took 81.043413 s

I expect this query to be really fast yet it's taking over a minute. A few things jump out at me

*

*It takes almost two minutes to get the session error -- I pass the IPs of 3 nodes to Spark Cassandra connector -- is there a way to tell it to skip failed connections faster?

*The task gets sent to a Spark worker which is not a Cassandra node -- this seems pretty strange to me -- is there a way to get information as to why the scheduler chose to send the task to a remote node?

*Even if the task was sent to a remote node, the Input Size(Max) on that worker shows up as 334.0 B / 1 but the executor time is 1.3 min (see picture). This seems really slow -- I would expect time to be spent on deserialization, not compute...

Any tips on how to debug this, where to look for potential problems much appreciated. Using Spark 1.4.1 with connector 1.4.0-M3, cassandra ReleaseVersion: 2.1.9, all defaults on tuneable connector params

A: I think the problem lays into distribution of data between partitions. Your table has one cluster (partitioning) key - groupId, epoch is a clustering column only. Data distributes on cluster nodes only by groupId, so you have a huge partition with groupId='254358' on one node on the cluster.
When you run your query Cassandra reaches very fast partition with groupId='254358' and then filter all rows to find records with epoch between 1443916800 and 1444348800. If there are a lot of rows the query will be really slow. Actually this query is not distributed it will always run on one node.
Better practice extract date or even hour and add it as partitioning key, in your case something like
PRIMARY KEY ((group_id, date), epoch, group_name, auto_generated_uuid_field)
WITH CLUSTERING ORDER BY (epoch ASC, group_name ASC, auto_generated_uuid_field ASC)

To verify my hypothesis you can run your current query in cqlsh with turning on tracing read here how to do it. So the problem has nothing in connect with Spark.
About error and time to get it, everything is fine because you receive error after timeout happened.
Also I remember recommendations of spark-cassandra-connector to place Spark slaves joint to Cassandra nodes exactly to distribute queries by partitioning key.


text:
Q: SLF4J: Hibernate3 vs. RESTeasy In my project i'm using Hibernate3 (depends on slf4j-1.6) and RESTeasy (depends on slf4j-1.5). Both are not compatible and give errors at runtime.
SLF4J: The requested version 1.5.8 by your slf4j binding is not compatible with [1.6]
SLF4J: See http://www.slf4j.org/codes.html#version_mismatch for further details.
Exception in thread "main" java.lang.NoSuchMethodError: org.slf4j.helpers.MessageFormatter.format(Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/String;
        at org.slf4j.impl.SimpleLogger.formatAndLog(SimpleLogger.java:222)
        at org.slf4j.impl.SimpleLogger.info(SimpleLogger.java:258)
        at org.hibernate.annotations.common.Version.<clinit>(Version.java:37)

Any ideas to solve this conflict ?

A: I am not familiar with RESTeasy however I have encountered this problem before, I just updated all slf4j jars to the later version and found that the api I was using that depended on the older version still worked on version 1.6.
Give it a go it can't hurt to try.
Edit: I should just say, make sure you update both the slf4j api (slf4j-api-1.x.x.jar) and the plugin (e.g. slf4j-log4j12-1.x.x.jar) to the same version.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Underscore debounce for each different argument Is there a nice way to get a similar behavior for _.debounce but with the difference that every changed argument is executed once? eg:
foo = function (arg) {console.log(arg)}
lazy = _.debounce(foo,1000)

lazy("a")
lazy("a")
lazy("a")
lazy("a")
lazy("b")
a // with debounce "a" would not be printed
b // but i would like run the debounced function once for every changed arg.

A: Fo the lack of an better solution i came up with this:
args = {}
function markAllAsUnread(rooms) {
    _.each(rooms,function (roomname) {
        // Here i do my heavy work....
        console.log(roomname)
    })
    args = {}
}

markAllAsUnreadLazy = _.debounce(markAllAsUnread,2000)

function markAsUnread (arg) {
    args[arg] = arg // to unify the given args
    markAllAsUnreadLazy(args)
}

markAsUnread (1)
markAsUnread (1)
markAsUnread (123)
markAsUnread (123123)
markAsUnread (123123)
markAsUnread (123123)
markAsUnread (12334)

1
123
12334
123123


text:
Q: Setup Varnish server with Rubber gem I am trying to instal varnish on a cache server. My following stack with be...
HA Proxy Servers ----> Cache (Varnish) Servers ----> Nginx + Unicorn Servers
I have been able to correctly setup all the config files for HAProxy and Varnish to move traffic along the pipeline. However I get an error when try to bootstrap my cache servers.

** ERROR:  While executing gem ... (Gem::DependencyError)
 ** Unable to resolve dependencies: rubber requires net-ssh (~> 2.4.0); fog requires net-ssh (>= 2.1.3); capistrano requires net-ssh (>= 2.0.14); net-ssh-gateway requires net-ssh (>= 2.6.4); net-scp requires net-ssh (>= 2.6.4); net-sftp requires net-ssh (>= 2.6.4)
 ** /tmp/gem_helper:32:in `block in <main>'
 ** : Unable to install versioned gem rubber:2.1.2 (RuntimeError
 ** )
 ** from /tmp/gem_helper:30:in `each'
 ** from /tmp/gem_helper:30:in `<main>'

I can't seem to figure out why this is happening. Any help would be great. Thanks

A: I had this problem and the solution I found was somewhat unsatisfactory and temporary, but it worked.
This error occurs during the rubber:install_gems task. After it fails, log into the ec2 server via ssh. At this point if you try to run gem install rubber -v=2.1.2 manually in the remote console, it fails with the exact same error you show above. (the version number might be different for you, it depends on the rubber version you had when you did this).
So now create an empty folder with any name, and create an almost-empty Gemfile inside it.
$ mkdir dummy && cd dummy
$ nano Gemfile

Then fill the Gemfile with the following contents:
source 'http://rubygems.org'
gem 'rubber', '2.1.2'

Again, the version of rubber might be different for you.
After creating this file, run bundle install and everything will install correctly. But don't ask me why it works differently when installing rubber via bundler than installing it via a plain old gem install.
So after achieving this, logout from ec2 and re-run cap rubber:bootstrap and it should work.
The unsatisfactory part is that if you decide to create new instances on ec2, it will fail again at the same point, and you'll have to repeat this steps and re-ignite the process manually for it to complete. So if any one can come up with a better solution like modifying rubber or something, let us know.

A: Let me preface this by saying i had this same problem and solved it but i was not using varnish or unicorn.
It looks like you're missing capistrano, add that to your gemfile and it should take care of most of the dependencies. However in my case rubber complained about requiring net-ssh (~> 2.4.0) and capistrano installs the latest net-ssh gem. So to fix this edit your Gemfile.lock to use net-ssh (2.4.0) instead of the latest version, then running bundle install should fix the dependencies.


text:
Q: comparing support vector regressor with lstm model using mlxtend I wish to compare two ML models for regression tasks. I am using SVR and LSTM. When I use mlxtend's paired t-test it is throwing an error for estimator 2 which is the LSTM model. the shape of the input not matching. Is there some way to do this using mlxtend?

from mlxtend.evaluate import paired_ttest_5x2cv
from sklearn.svm import SVR
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import activations
from keras import optimizers
from keras.layers import Dropout
from keras import layers
from keras.models import Model
from keras.models import Sequential
from keras.layers import LSTM, Input, Dense

svr_rbf = SVR(kernel= 'rbf', C= 1e2, gamma= 0.1)
lstm_model=create_model()

def create_model():
    lrate=0.001
    look_back=35
    model = Sequential()
    model.add(LSTM(16, input_shape=(1, look_back)))
    model.add(Dense(1))
    model.compile(loss='mean_squared_error', optimizer='adam')
    return model

t, p = paired_ttest_5x2cv(estimator1=svr_rbf,
                          estimator2=lstm_model,
                          X=X, y=y,
                          random_seed=1)

error thrown for estimator 2
319         X_1, X_2, y_1, y_2 = train_test_split(X, y, test_size=0.5, random_state=randint)
320

--> 321         score_diff_1 = score_diff(X_1, X_2, y_1, y_2)
322         score_diff_2 = score_diff(X_2, X_1, y_2, y_1)
323         score_mean = (score_diff_1 + score_diff_2) / 2.0
~\anaconda3\lib\site-packages\mlxtend\evaluate\ttest.py in score_diff(X_1, X_2, y_1, y_2)
308
309         estimator1.fit(X_1, y_1)
--> 310         estimator2.fit(X_1, y_1)
311         est1_score = scorer(estimator1, X_2, y_2)
312         est2_score = scorer(estimator2, X_2, y_2)
~\anaconda3\lib\site-packages\keras\utils\traceback_utils.py in error_handler(*args, **kwargs)
68             # To get the full stack trace, call:
69             # tf.debugging.disable_traceback_filtering()
---> 70             raise e.with_traceback(filtered_tb) from None
71         finally:
72             del filtered_tb
~\anaconda3\lib\site-packages\keras\engine\training.py in tf__train_function(iterator)
13                 try:
14                     do_return = True
---> 15                     retval_ = ag__.converted_call(ag__.ld(step_function), (ag__.ld(self), ag__.ld(iterator)), None, fscope)
16                 except:
17                     do_return = False
ValueError: in user code:
File "C:\Users\Nikhitha\anaconda3\lib\site-packages\keras\engine\training.py", line 1249, in train_function  *
    return step_function(self, iterator)
File "C:\Users\Nikhitha\anaconda3\lib\site-packages\keras\engine\training.py", line 1233, in step_function  **
    outputs = model.distribute_strategy.run(run_step, args=(data,))
File "C:\Users\Nikhitha\anaconda3\lib\site-packages\keras\engine\training.py", line 1222, in run_step  **
    outputs = model.train_step(data)
File "C:\Users\Nikhitha\anaconda3\lib\site-packages\keras\engine\training.py", line 1023, in train_step
    y_pred = self(x, training=True)
File "C:\Users\Nikhitha\anaconda3\lib\site-packages\keras\utils\traceback_utils.py", line 70, in error_handler
    raise e.with_traceback(filtered_tb) from None
File "C:\Users\Nikhitha\anaconda3\lib\site-packages\keras\engine\input_spec.py", line 295, in assert_input_compatibility
    raise ValueError(

ValueError: Input 0 of layer "sequential_1" is incompatible with the layer: expected shape=(None, 15, 3), found shape=(None, 3)


text:
Q: Knockout JS Script works in Chrome but not in IE9 I have a web page that works great in Chrome but not in IE9. The error that comes on the console from this error is
SCRIPT5022: Unable to parse bindings.
Message: [object Error];
Bindings value: foreach: statlist.
HTML is below:

        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

 TypeCount: , Priority:

Javascript:
function MessageCountDataModel() {

    var self = this;
    var allCounts = (function() {

        var json = null;

        $.ajax({
            'async': false,
            'global': false,
            'url': "http://localhost:8080/API/getstats.json",
            'datatype': "json",
            'success': function(data) {
                self.statlist = data;
            }
        });
    })();
}

ko.applyBindings(new MessageCountDataModel());

One more piece of info is that that the json that comes out of the API looks something like this. I'm not sure if it's because the TypeCount is not a string?
[
    {
        "TypeCount": 102,
        "SentDate": "2014-08-18T00:00:00.000Z"
    }
]

A: It's not a good idea to use async: false. Maybe this is the problem because you don't initialize statlist as attribute in yout ViewModel. Better solution will be to make statlist to be an observable array, then make a async call and when it is ready to set the data.
Example:
function MessageCountDataModel() {
    var self = this;

    self.statlist = ko.observableArray();

    self.loadData = function() {
        $.ajax({
            'url': "http://localhost:8080/API/getstats.json",
            'datatype': "json",
            'success': function(data) {
                self.statlist(data);
            }
        });
    };

    self.loadData();
}

ko.applyBindings(new MessageCountDataModel());


text:
Q: JQuery - How to check specific class value is on the first child or not after click a button JQuery - How to check specific class value is on the first child in  or not after click a button
I have code like this:

...

...

...

...

...

...

On webpage, there is a button. When user click this button, a "active" value will be moved to next child. Like this:

...

...

...

...

...

...

I want to write code to check that after click this button, "active" value is placed on the first child (with "carousel-item" value) or not.
$('.button').click(function() {
If(//Check that "active" value is on the first child or not, return true if "active" value is on first child){
//Do something here
}
}

I try to mix of find(), :first-child with my code but it doesn't work.
Thanks in advance.

A: You can create a function to get the active index and another function to move it to the next child like so:

function getActiveIndex(){
  var activeIndex = 0;
  var count = 0;
  $('.carousel-item').each(function(){
    count++;
    if($(this).hasClass('active')){
      activeIndex = count;
    }
  });
  return activeIndex;
}

function moveActiveIndex(){
  var activeIndex = getActiveIndex();
  $('.carousel-item:nth-of-type('+activeIndex+')').removeClass('active');
  activeIndex++;
  $('.carousel-item:nth-of-type('+activeIndex+')').addClass('active');
}
.carousel-item {
  background-color: gray;
  border: 1px solid #ddd;
}

.carousel-item.active {
  background-color: red;
}

...

...

...

...

...

...

<button type="button" onclick="moveActiveIndex()">Move Active</button>

A: Simple in jquery:
if( $(".carousel-item").first().hasClass("active") ){
   // do something
}


text:
Q: Xdebug as a reference counting works The documentation has a few fragments illustrate how this works, but one thing is not clear, I illustrate it below:
/// Example 1
$a = 10;
xdebug_debug_zval('a');
/// Output:
/// a:(refcount=1, is_ref=0),int 10

/// Example 2
$a = 10;
$b = 10;
xdebug_debug_zval('a','b');
/// Output:
/// a:(refcount=1, is_ref=0),int 10
/// b:(refcount=1, is_ref=0),int 10

/// Example 3
$a = 10;
$b = $a;
xdebug_debug_zval('a','b');
/// Output:
/// a:(refcount=2, is_ref=0),int 10
/// b:(refcount=2, is_ref=0),int 10

/// Example 4
$a = 10;
$b = &$a;
xdebug_debug_zval('a','b');
/// Output:
/// a:(refcount=2, is_ref=1),int 10
/// b:(refcount=2, is_ref=1),int 10

/// Example 5
$a = 10;
$b = $a;
$c = $a;
xdebug_debug_zval('a','b','c');
/// Output:
/// a:(refcount=3, is_ref=0),int 10
/// b:(refcount=3, is_ref=0),int 10
/// c:(refcount=3, is_ref=0),int 10

/// Example 6
$a = 10;
$b = &$a;
$c = $a;
xdebug_debug_zval('a','b','c');
/// Output:
/// a:(refcount=2, is_ref=1),int 10
/// b:(refcount=2, is_ref=1),int 10
/// c:(refcount=1, is_ref=0),int 10

/// Example 7
$a = 10;
$b = &$a;
$c = &$a;
xdebug_debug_zval('a','b','c');
/// Output:
/// a:(refcount=3, is_ref=1),int 10
/// b:(refcount=3, is_ref=1),int 10
/// c:(refcount=3, is_ref=1),int 10

For all of the examples most illogical for me turned out to be Example 6, I really do not understand why we have to debug when we do not get all lines of the following entry
/// Output:
/// a:(refcount=3, is_ref=1),int 10
/// b:(refcount=3, is_ref=1),int 10
/// c:(refcount=3, is_ref=0),int 10

Explain what is the matter?

A: You have to think in terms of pointers from the C language, if you are familiar with it. Variables in PHP are pointers to ZVALs, so when you "copy" a variable in PHP, PHP does not actually duplicate its value, but increments the refcount and duplicates the pointer. But still if you alter the original value the other values do not change, because PHP does something called copy-on-write (unless refcount=1,
$a = 10;
$b = $a;  // $b is a soft copy of $a, refcount++
$a = 11;  // $a changes, a new zval is created

While:
$a = 10;
$b = &$a; // $b is still a copy of a, but this time a reference
$a = 11;  // $a and $b change

So what happens in your "Example 6"? Well, PHP knows that refcount > 1, but you cannot "soft-copy" $a's zval into $c, because otherwise when you change $a or $b it would also change $c's value, so $c becomes a NEW zval, with refcount=1.
$a = 10;    // new zval created (refcount=1)
$b = &$a;   // $b is a copy of $a but is_ref=1 (and refcount=2)
$c = $a;    // $c is a NEW zval, refcount=1

I'm afraid I didn't explain myself well :( I can try again if you still have doubts.


text:
Q: Domain Specific Language and Translations in Ruby Thinking about a nice architecture for creating a own domains specific language in ruby, I struggeld a bit about the translation part. Say we have a event problem:
event "We made a profit" do
   income > expenditure
end

event "We have some deficite" do
   income < expenditure
end

I like to use the event descriptions "We made a profit" and "We have some deficite" as output for the User. Problem is that the description is only in english language. It should appear in different languages. I could use the i18n gem but that looks not for a solution for me.
event "event.deficite" do
   income < expenditure
end

or similiar:
event i18n.t('event.deficite') do
   income < expenditure
end

This is not a realy nice solution because it is not that readable. The whole event description get lost through the translation and destroys in my oppinion the task of the 'Domain specific language'. What is a good solution for solving this problem?


text:
Q: How to replace matching words within a page replacing the body.innerHTML only once? The following function in JavaScript adds to each matching word a <mark> tag in the document's body.
var words = ["apple", "banana", "carrot", "pear"];

for (var i=0; i < words.length; i++) {
  var replace = new RegExp(words[i],"g");
  var page = document.body.innerHTML;
  var newPage = page.replace(replace, `<mark>${words[i]}</mark>`);
  document.body.innerHTML = newPage;
}

This way, it highlights a word within the <body> if it's an element within the array words.
The issue I have is that the document.body.innerHTML is replaced at every iteration. Do you know how I can replace the matching words in the page limiting the numbers of document.body.innerHTML = newPage to 1?
Thanks in advance for your replies!

A: Get innerHTML before loop and set innerHTML after loo. you can use replaceAll to change all matching word

var words = ["apple", "banana", "carrot", "pear"];
var page = document.body.innerHTML;

words.forEach((word)  => {
  page = page.replaceAll(word, `<mark>${word}</mark>`);
});

document.body.innerHTML = page;
<div> apple abc banana cd apple </div>

A: Read the string before the loop, modify it in the loop, and change the document body after the loop.

const words = ["apple", "banana", "carrot", "pear"];
let page = document.body.innerHTML;

for (const word of words) {
  page = page.replaceAll(word, `<mark>${word}</mark>`);
}
document.body.innerHTML = page;
"apple", "banana", "carrot", "pear"

Or you can use reduce:

const words = ["apple", "banana", "carrot", "pear"];
document.body.innerHTML = words.reduce((page, word) => page.replaceAll(word, `<mark>${word}</mark>`), document.body.innerHTML);
"apple", "banana", "carrot", "pear"


text:
Q: Having issues responding to an HTTP request with the proper array. Possible way to send results from within function with expressjs? Problem Summary: So I'm working on a program that has an SQL database on the backend and I'm using the npm SQLite3 module to talk to it. When I make my HTTP request to the server I was told in another post that I should do a res.send with the function inside it so after the function ran, it would return whatever came from the function. Easy enough right? But then I ran into an issue with an asynchronous function .all (API Doc here). Essentially what happens is that I call my database and it returns everything inside to an object inside database.all, but database.all is an asynchronous function that is void and can't return anything. I've got a callback that sends the object inside the callback, but I don't know what to do with it from there, or if I even need a callback.
So my question is: can I send an HTTP response from somewhere inside my .all function or callback, or does my function have to return the array to where it was called? Code below to show you what I mean.
Chain of events (Github repo for refrence):
I've set up an angular controller to send the following HTTP request when my page loads:
$http.get('/LoadWaitingList')
.then(function(response) {
    // alert("HTTP request set, getting data");
    console.log(response.data);
});

and when the server (server.js) receives it, I do this:
app.get('/LoadWaitingList', function (req, res) {
  res.send(DatabaseFunction.loadWaitingList());
})

which runs the loadWaitingList() function in another file named test.js:
function  loadWaitingList() {
    var callbackFunction = function(err, response){
        var returnRow = response;
        return returnRow;
    }
    updateDB.Manager(callbackFunction);
}

which calls updateDB.Manager, AKA this guy:
Manager : function(callback){
    var fs = require("fs");
    var file = "./Source/Server/Data/DaycareDB.db";
    var exists = fs.existsSync(file);
    if (!exists) {
        throw new Error("File not Found");
    }
    var sqlite3 = require("sqlite3").verbose();
    var db = new sqlite3.Database(file);
    db.all("SELECT * FROM WaitingList", function(err, row) {
        if (err){
            callback(err);
            return;
        }
        // console.log(row[0].ChildName);
        callback(null, row);
        return;
    });
},

So finally we can see, after db.all runs, the values I'm after after in row. row is passed into db.all as a parameter and returned as an array, I've tried declaring it outside the db.all and passing it in and then printing out the results, but due to db.all being asynchronous it always comes up empty because the function hasn't run yet.
When I run my callback and check the object (using vscode debugger) after the callback has been called, returnRow has the proper data in it from my database.
How do I send the data that gets put into row and eventually returnRow back as a response? Is it possible to do the initial function call when we get the HTTP request a different way and then do a res.send from the callback or something?

A: You need to look at your callbacks.
app.get('/LoadWaitingList', function (req, res) {
  DatabaseFunction.loadWaitingList(function(err,data){
    if(err) {
      // handle the error here
    }
    // send the data
    res.send(data);
  }
});

Now loadWaitingList() needs to take a standard error-first callback as a parameter. This callback is passed through to updateDB.Manager() where it will be executed.
function loadWaitingList(callback) {
  updateDB.Manager(callback);
}

A: You need to pass a callback into your loadWaitingList function and then trigger res.send from inside that callback. Something like:
app.get('/LoadWaitingList', function (req, res) {
  DatabaseFunction.loadWaitingList(function(err, response) {
    res.send(response);
  });
});

function loadWaitingList(callback) {
  updateDB.Manager(callback);
}

This way, the res.send isn't triggered until your loadWaitingList function completes. Obviously, this code is very basic. I'm not checking for errors and the loadWaitingList is simply passing the supplied callback on to the Manager method. You could probably refactor this and remove loadWaitingList altogether.
app.get('/LoadWaitingList', function (req, res) {
  updateDB.Manager(function(err, response) {
    res.send(response);
  });
});

Just remember that any code you want to run asynchronously has to be inside a callback. The res.send in your original code wasn't inside a callback, so it was running immediately. Therefore, it was completing before loadWaitingList could return a value.
Hope this helps.


text:
Q: Menu Bar quit working https://imgur.com/rq5n6E5
if you take a look at the image you'll see that my menu bar is being placed in a div instead of on the main page.. to explain the reason it looks like this is because the website that I'm creating this profile on doesn't allow certain things to be done, so I have to position some of the divs -1500px and use ease-in-out to bring it to the target spot, Hope this photo helps understand the issue.
ok so I finally got everything working fine, but now my issue is with chrome.. I don't know if chrome updated something or what ? but everything is working perfect on mozilla firefox,, but not on chrome ? is there a reason for this ?
The issue is with the right_menu / Sub_menu or something.. or even the gradient ? I'm not sure why it's working fine on mozilla and not chrome.. everything use to work fine with chrome until now
Js Fiddle

#right_menu {
  background: -webkit-linear-gradient(#FF00FF, #77047e);
  background: -o-linear-gradient(#FF00FF, #77047e);
  background: -moz-linear-gradient(#FF00FF, #77047e);
  background: linear-gradient(#FF00FF, #77047e);
  display: table;
  font-size: 15px;
  line-height: 46px;
  margin: 0;
  padding: 0;
  position: fixed;
  right: 46px;
  text-align: center;
  text-transform: uppercase;
  top: 0;
  -webkit-transform: rotate(-90deg);
  -moz-transform: rotate(-90deg);
  -ms-transform: rotate(-90deg);
  transform: rotate(-90deg);
  transform-origin: right top 0;
  width: 100vh;
  white-space: nowrap;
}

#right_menu li {
  display: table-cell;
}

#right_menu li a {
  display: block;
  padding: 0 20px;
  text-decoration: none;
}

.sub_menu
/* same as #right_menu li ul */

{
  display: none;
  left: 18%;
  margin: 0;
  padding: 0;
  position: absolute;
  top: -46px;
}

.sub_menu li a {
  background: -webkit-linear-gradient(#77047e, #FF00FF);
  background: -o-linear-gradient(#77047e, #FF00FF);
  background: -moz-linear-gradient(#77047e, #FF00FF);
  background: linear-gradient(#77047e, #FF00FF);
}

#right_menu li:hover .sub_menu {
  display: block;
}

#right_menu>li a:hover {
  background: #FF00FF;
}

Message Me

Galleries

PW Gallery

My Gallery

Interest

About Me

Home

A: These properties should do the trick:
#right_menu {

  width:100vh;
  top: 0;
  transform-origin: right bottom;
  transform: translate(-100%, -100%) rotate(-90deg);
  left: 100%;
}

Check this fiddle

A: Add below CSS code in in your CSS file. This solution will only modify Chrome behavior of right menu appearance, rest will work as before.
/* Chrome */
@media and (-webkit-min-device-pixel-ratio:0) {
  #right_menu{display:initial;}
}

/* Chrome 29+ */
@media screen and (-webkit-min-device-pixel-ratio:0)
  and (min-resolution:.001dpcm) {
    #right_menu{display:initial;}
}

/* Chrome 22-28 */
@media screen and(-webkit-min-device-pixel-ratio:0) {
   #right_menu{display:initial;}
}

Find the modified code of yours, below:-

html,
body {
  height: 100%;
}

article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
menu,
nav,
section {
  display: block;
}

b,
strong {
  font-weight: bold;
}

img {
  color: transparent;
  font-size: 0;
  vertical-align: middle;
  -ms-interpolation-mode: bicubic;
}

ol,
ul {
  list-style: none;
}

li {
  display: list-item;
}

table {
  border-collapse: collapse;
  border-spacing: 0;
}

th,
td,
caption {
  font-weight: normal;
  vertical-align: top;
  text-align: left;
}

q {
  quotes: none;
}

q:before,
q:after {
  content: '';
  content: none;
}

sub,
sup,
small {
  font-size: 75%;
}

sub,
sup {
  line-height: 0;
  position: relative;
  vertical-align: baseline;
}

sub {
  bottom: -.25em;
}

sup {
  top: -.5em;
}

svg {
  overflow: hidden;
}

body {
  font-family: Verdana, Geneva, sans-serif;
  color: #FFF;
  font-size: 12px;
  font-family: Trebuchet MS, Arial, Helvetica;
  background: url() no-repeat center 0, #000 url() left top;
  background-size: 1670px 950px;
}

#header_bar,
#profile_header,
#profile_main_photo,
#footer_bar {
  display: none;
  list-style-type: none;
}

#right_menu {
  background: -webkit-linear-gradient(#FF00FF, #77047e);
  background: -o-linear-gradient(#FF00FF, #77047e);
  background: -moz-linear-gradient(#FF00FF, #77047e);
  background: linear-gradient(#FF00FF, #77047e);
  display: table;
  font-size: 15px;
  line-height: 46px;
  margin: 0;
  padding: 0;
  position: fixed;
  right: 46px;
  text-align: center;
  text-transform: uppercase;
  top: 0;
  -webkit-transform: rotate(-90deg);
  -moz-transform: rotate(-90deg);
  -ms-transform: rotate(-90deg);
  transform: rotate(-90deg);
  transform-origin: right top 0;
  width: 100vh;
  white-space: nowrap;
}

#right_menu li {
  display: table-cell;
}

#right_menu li a {
  display: block;
  padding: 0 20px;
  text-decoration: none;
}

.sub_menu
/* same as #right_menu li ul */

{
  display: none;
  left: 18%;
  margin: 0;
  padding: 0;
  position: absolute;
  top: -46px;
}

.sub_menu li a {
  background: -webkit-linear-gradient(#77047e, #FF00FF);
  background: -o-linear-gradient(#77047e, #FF00FF);
  background: -moz-linear-gradient(#77047e, #FF00FF);
  background: linear-gradient(#77047e, #FF00FF);
}

#right_menu li:hover .sub_menu {
  display: block;
}

#right_menu>li a:hover {
  background: #FF00FF;
}

#home_page {
  width: 960px;
  height: 468px;
  position: fixed;
  top: 300px;
  left: 25%;
  padding: 40px;
  z-index: -999999;
  transition: left .4s ease-in-out;
}

#profile_about_me_friends .heading {
  text-transform: uppercase;
  font-size: 38px;
  color: #FF00FF;
  font-weight: normal;
  border-bottom: 1px dotted #666666;
  padding-bottom: 10px;
  margin-bottom: 20px;
}

#profile_about_me_friends {
  width: 400px;
  height: 600px;
  color: #000000;
  font-family: "Baskerville Old Face", serif;
  font-style: italic;
  font-size: 20px;
  background-color: rgba(0, 0, 255);
  position: absolute;
  top: 200px;
  right: -1200px;
  padding: 40px;
  transition: left 0 ease-in-out;
}

#profile_about_me_friends_content {
  color: #000000;
  font-family: "Baskerville Old Face", serif;
  font-style: italic;
  font-size: 20px;
}

#profile_about_me_friends:target {
  right: 80%;
  top: 0;
  margin-right: -520px;
}

#profile_about_me_friends .profile_section_content {
  overflow-y: scroll;
  height: 580px;
}

#profile_interests_content .heading {
  text-transform: uppercase;
  font-size: 45px;
  color: #FF00FF;
  font-weight: normal;
  border-bottom: 1px dotted #666666;
  padding-bottom: 10px;
  margin-bottom: 20px;
}

#profile_interests_content {
  width: 400px;
  height: 600px;
  color: #000000;
  font-family: "Baskerville Old Face", serif;
  font-style: italic;
  font-size: 20px;
  background-color: rgba(0, 0, 255);
  position: absolute;
  top: 200px;
  right: -1200px;
  padding: 40px;
  transition: left 0 ease-in-out;
}

#profile_interests_content:target {
  right: 80%;
  top: 0;
  margin-right: -520px;
}

#profile_interests_content .profile_section_content {
  overflow-y: scroll;
  height: 580px;
}

#profile_comments .heading {
  text-transform: uppercase;
  font-size: 38px;
  font-weight: normal;
  border-bottom: 1px dotted #666666;
  padding-bottom: 10px;
  margin-bottom: 20px;
}

#profile_comments {
  width: 400px;
  height: 600px;
  color: #FF00FF;
  font-family: "Baskerville Old Face", serif;
  font-style: italic;
  font-size: 20px;
  background-color: rgba(0, 0, 255);
  position: absolute;
  top: 200px;
  right: -1200px;
  padding: 40px;
  transition: left 0 ease-in-out;
}

#profile_comments:target {
  right: 80%;
  top: 0;
  margin-right: -520px;
}

#profile_comments .profile_section_content {
  overflow-y: scroll;
  height: 580px;
  background-color: rgba(0, 0, 0, 0.6);
}

#profile_photo_galleries .heading {
  text-transform: uppercase;
  font-size: 38px;
  color: #FF00FF;
  font-weight: normal;
  border-bottom: 1px dotted #666666;
  padding-bottom: 10px;
  margin-bottom: 20px;
}

#profile_photo_galleries {
  width: 400px;
  height: 600px;
  color: #000000;
  font-family: "Baskerville Old Face", serif;
  font-style: italic;
  font-size: 20px;
  background-color: rgba(0, 0, 255);
  position: absolute;
  top: 200px;
  right: -1200px;
  padding: 40px;
  transition: left 0 ease-in-out;
}

#profile_photo_galleries:target {
  right: 80%;
  margin-right: -520px;
  top: 0;
}

.photo_gallery {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 95.7%;
  margin-bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 99;
}

.photo_gallery .heading {
  text-transform: uppercase;
  font-size: 38px;
  font-weight: normal;
  border-bottom: 1px dotted #666666;
  padding-bottom: 10px;
  margin-bottom: 20px;
}

.photo_gallery .images a {
  display: block;
  float: left;
  border: 5px solid #000;
  margin-right: 10px;
  margin-bottom: 10px;
}

.photo_gallery_preview {
  border: 1px solid #333;
  overflow: auto;
  padding: 20px 15px;
  width: 100px;
  background-color: #000;
}

.photo_gallery_name a {
  color: #FFF;
  margin-bottom: 20px;
  display: block;
  text-transform: uppercase;
}

.photo_gallery_link {
  display: block;
  margin-bottom: 15px;
}

.photo_gallery_count {
  font-style: italic;
  color: #666;
}

#profile_password_photo_galleries .heading {
  text-transform: uppercase;
  font-size: 38px;
  color: #FF00FF;
  font-weight: normal;
  border-bottom: 1px dotted #666666;
  padding-bottom: 10px;
  margin-bottom: 20px;
}

#profile_password_photo_galleries {
  width: 400px;
  height: 600px;
  color: #000000;
  font-family: "Baskerville Old Face", serif;
  font-style: italic;
  font-size: 20px;
  background-color: rgba(0, 0, 255);
  position: absolute;
  top: 200px;
  right: -1200px;
  padding: 40px;
  transition: left 0 ease-in-out;
}

#profile_password_photo_galleries {
  right: 300%;
  margin-right: -520px;
}

.password_photo_gallery_preview {
  border: 1px solid #333;
  overflow: auto;
  padding: 20px 15px;
  width: 100px;
  background-color: #000;
}

#profile_password_photo_galleries:target {
  right: 80%;
  top: 0;
  margin-right: -520px;
}

.password_photo_gallery_name a {
  color: #FFF;
  margin-bottom: 20px;
  display: block;
  text-transform: uppercase;
}

.password_photo_gallery {
  position: absolute;
  top: 850px;
  right: 515px;
  width: 500px;
  background-color: #121212;
  padding: 40px;
  overflow: auto;
}

h3 {
  font-size: 18px;
  position: fixed;
  left: 23px;
  top: 120px;
  color: #FF00FF;
}

h4 {
  font-size: 18px;
  position: fixed;
  left: 15px;
  top: 40px;
  color: #FF00FF;
}

/* Chrome */

@media and (-webkit-min-device-pixel-ratio:0) {
  #right_menu {
    display: initial;
  }
}

/* Chrome 29+ */

@media screen and (-webkit-min-device-pixel-ratio:0) and (min-resolution:.001dpcm) {
  #right_menu {
    display: initial;
  }
}

/* Chrome 22-28 */

@media screen and(-webkit-min-device-pixel-ratio:0) {
  #right_menu {
    display: initial;
  }
}

Message Me

Galleries

PW Gallery

My Gallery

Interest

About Me

Home

A: Change display property from table to block and right property to the width of your menu.
for example:
#right_menu{
      display: block;
      right: 46px;
}

This will fix your issue.


text:
Q: CVSROOT may only specify a positive, non-zero, integer port I'm trying to compile and build our project on a Linux server machine getting the source code from a Windows repository. It seems that the repository path "c:\repository" is not reachable from Ubuntu due this error:
cvs login: CVSROOT may only specify a positive, non-zero, integer port (not `c:').
cvs login: Perhaps you entered a relative pathname?

How is it possible to checkout source from Windows repository from Ubuntu machine without using eclipse or any gui client? (Not available).


text:
Q: Java Basic: Insert data in separate Class How to insert data in separate class?
package teste01classes;

public class Teste01Classes {

    public static void main(String[] args) {
        Alunos[] aluno = new Alunos[20];
        aluno[0] = new Alunos();
        aluno[0].nome = "Abel";
        aluno[0].n1 = 10;
        aluno[0].n2 = 7;
        aluno[0].n3 = 8;

        aluno[1] = new Alunos();
        aluno[1].nome = "Ana Carolina";
        aluno[1].n1 = 8;
        aluno[1].n2 = 7;
        aluno[1].n3 = 5;
        //... n alunos
    }
}

package teste01classes;

public class Alunos {
    String nome;
    int n1, n2, n3;
}

But i need
    Alunos[] aluno = new Alunos[20];
    aluno[0] = new Alunos();
    aluno[0].nome = "Abel";
    aluno[0].n1 = 10;
    aluno[0].n2 = 7;
    aluno[0].n3 = 8;

    aluno[1] = new Alunos();
    aluno[1].nome = "Ana Carolina";
    aluno[1].n1 = 8;
    aluno[1].n2 = 7;
    aluno[1].n3 = 5;
    //... n alunos

In separated class and invoke in main.

A: Create a new class, say SchoolClass, with a createAlunos method that will create all alunos:
package teste01classes;

public class SchoolClass {

  public static Alunos[] createAlunos() {
    Alunos[] aluno = new Alunos[20];
    aluno[0] = new Alunos();
    aluno[0].nome = "Abel";
    aluno[0].n1 = 10;
    aluno[0].n2 = 7;
    aluno[0].n3 = 8;
    //... n alunos
    return aluno;
  }
}

And then, in Teste01Classes, call this method:
public class Teste01Classes {
    public static void main(String[] args) {
        Alunos[] aluno = SchoolClass.createAlunos();
    }
}


text:
Q: what is the difference between ++*var++ and ++Var++? What is difference between ++*var++ and ++var++ ?
why ++*var++ is working while ++var++ results with lvalue required error in C?

A: ++var++ is grouped as ++(var++) and that results in a compilation failure since var++ is not an lvalue. (Informally speaking this means you can't put it on the left hand side of an assignment).
++*var++ is grouped as ++(*(var++)) which means increment the pointer var by 1 using pointer arithmetic, then increase the dereferenced value of the initial value of var by 1.

A: Even though I was just advising against this in a comment, it may be useful to look at all possibilities.  For a pointer variable p, we have:

*

*++p             increment p, yield new value

*p++             increment p, yield old value

**++p           increment p, access what it newly points to

**p++           increment p, access what it used to point to

*++*p           increment what p points to, yield new value

*(*p)++        increment what p points to, yield old value

*++*++p        increment p, increment what it newly points to, yield new value

*(*++p)++     increment p, increment what it newly points to, yield old value

*++(*p++)     increment p, increment what it used to point to, yield new value

*(*p++)++     increment p, increment what it used to point to, yield old value

*++p++          meaningless

Cases 9 and 11 are the ones you were asking about.  In case 9, I've added explicit parenthesis to make it more clear what's going on.  I guess it also works if you leave them out, and say ++*p++, but this makes my head explode, so I'd prefer not to think about it any more.


text:
Q: Trouble understanding this proof from Humpreys: Linear Algebraic Groups I have trouble understanding this proof from Humpreys: Linear Algebraic Groups page 104.
Theroem
Let $G$ be a connected and diagonalizable linear algebraic group (i.e. there exists a closed embedding into a torus $D_n(\mathbb C)$). Then $G$ is  a torus.
Proof
The inclusion $G \to D_n$ induces a surjection $\mathbb C[D_n] \to \mathbb C[G]$ (restriction map) which induces a surjection $\chi(D_n) \to \chi(G)$ (restriction map) between the group characters. Since $D_n$ is a torus $\chi(D_n) = \mathbb Z^n$, and since $G$ is diagonalizable and connected $\chi(G) = \mathbb Z^r$. Thus
$$ \mathbb Z^n = \chi(D_n) \to \chi(G) = \mathbb Z^r $$ gives us a decomposition $$ \chi(D_n) = Ker(\to) \oplus\mathbb Z^r. $$ We can then pick a basis for the summands, $\chi_1, \cdots, \chi_{n-r}$ and $\chi_{n-r+1}, \cdots, \chi_n$.
Then I can't understand the conclusion.
Thanks!


text:
Q: iframe in IE triggers javascript download I am trying to make an ajax call for analytics tracking to pardot but i cant run the ajax call so instead i resorted to doing a hidden iframe. But now in IE it tries to download the js file returned in the frame. How can i avoid this issue.
HTML
<iframe id="trackingFrame" name="trackingFrame" src="" style="display:none;"></iframe>

JS
jQuery(document).ready(function($) {
            /*var filetypes = /\.(zip|exe|pdf|doc*|xls*|ppt*|mp3)$/i;*/
           if(msieversion() == false){
            var filetypes = /\.(pdf)$/i;
            var baseHref = '';
            if (jQuery('base').attr('href') != undefined)
                baseHref = jQuery('base').attr('href');
                jQuery('a').each(function() {
                    var href = jQuery(this).attr('href');
                    if (href && href.match(filetypes)) {

                        jQuery(this).click(function() {
                            var extension = (/[.]/.exec(href)) ? /[^.]+$/.exec(href) : undefined;
                            var filePath = href;

                            $('#trackingFrame').attr('src',
                                'https://pi.pardot.com/analytics?ver=3&visitor_id='+pi.tracker.visitor_id+'&pi_opt_in='+
                                '&campaign_id='+piCId+'&account_id='+piAId+'&title='+'&pi_points=10'+'&url='+filePath+'&referrer='
                            ).load(function(){
                                window.location.href = filePath;
                            });

                            return false;
                        });
                    }
                });
           }
        });


text:
Q: Small space in gnuplot Does something like tiny space exist in gnuplot? I searching for something similar to, for instance, , in LaTeX.
set xlabel "2\,400\,000"

A: Unicode provides two options roughly equivalent to LaTeX \thinspace
U+2009   THIN SPACE              UTF-8: 0xE2 0x80 0x89
U+202F   NARROW NO-BREAK SPACE   UTF-8: 0xE2 0x80 0xAF

and another that may or may not be slightly smaller than that
U+2008  PUNCTUATION SPACE       UTF-8: 0xE2 0x80 0x88

You could copy-paste the utf-8 sequence directly into gnuplot but obviously it will be hard to see whether it worked or not :-)
It is probably better to provide the unicode value as an escape sequence.
Of course this only works if you are using a font that supports the unicode code point being used; otherwise it will probably substitute a normal space. It might also be sensitive to quirks in the various graphics libraries; for example I had better luck using the wxt terminal than I did with nominally the same font using the qt terminal.
set term wxt font "Arial,15"
set label 1 at graph 0.1,0.9 "2400000"
set label 2 at graph 0.1,0.8 "2{\U+2009}400{\U+2009}000"
set label 3 at graph 0.1,0.7 "2 400 000"
set label 4 at graph 0.1,0.6 "2{\U+202F}400{\U+202F}000"

plot x

A: Well, here is an awkward workaround without using a LaTeX terminal, but using enhanced text (check help enhanced).
I assume you want a thousand separator. If you are working under Linux, the following might be of interest: gnuplot: How to enable thousand separators (digit grouping)?
Script:
### small space between numbers
reset session

set termoption font "Arial,18"

set label 1 at graph 0.1,0.9 "2400000"
set label 2 at graph 0.1,0.8 "~2{.0}~ {.0 }40~0{.0}~ {.0 }000"
set label 3 at graph 0.1,0.7 "2 400 000"

plot x
### end of script

Result: (from wxt terminal under Windows)


text:
Q: Attaining the marginal probability function Suppose X, Y are discrete random variables with joint probability mass function
$$
f(n) =
\begin{cases}
1/10,  & \text{if $1\leq y\leq x \leq 4$ } \\
0, & \text{otherwise}
\end{cases}
$$
Why is the marginal probability mass function for random variable Y, equate to the following? More specifically, if by definition marginal probability function is attained by summation of all the X's, why start from Y and not 1?
$$f_y = \sum_x f(x,y) = \sum_y^4 \frac{1}{10} $$

A: Try adding up the joint probabilities in a row for a given $y$ to get the marginal probability for $Y=y$.  You start with positive values when $x=y$ and go through to $x=4$
    x        1    2   3    4    Margin y
y

1          1/10 1/10 1/10 1/10    4/10
2           0   1/10 1/10 1/10    3/10
3           0    0   1/10 1/10    2/10
4           0    0    0   1/10    1/10

Margin x   1/10 2/10 3/10 4/10

A: Firstly, in the joint mass function, $f(n)$ should be something like $f(x,y)$, as mass function determined the probability of a combination of events $X=x$ and $Y=y$. This joint mass function assigns equal probabilities to each possible $(x,y)$ pairs in the domain, namely $(1,1), (2,1), (3,1), (4,1), (2,2), (3,2), (4,2), (3,3), (4,3), (4,4)$ (notice that these give you a "lower-diagonal" matrix, if you wrote them in a triangular form).
Generally, it may be a good exercise to include the indices, resulting in less confusion.
Say we want to find $f_Y(n)$ for some $n \in \{1,2,3,4\}$. Then for this fixed $n$, there are possible values $X$ can take, but as we don't care what value $X$ will take in the marginal mass function of $Y$, we need to add all possible cases, for example,
$$
P(Y = 1) = P(Y=1,X=1) + P(Y=1,X=2) + P(Y=1,X=3) + P(Y=1,X=4).
$$
This is why the sum is over possible values of $X$. Then
$$
f_Y(n) = \sum_{k=1}^4 f(k,n) =  \sum_{k=1}^4 P(X=k, Y=n)
$$
But since $P(X=k, Y=n)=0$ for $k<n$, you can start the sum from $n$, instead of $1$, as otherwise you are just adding zeroes. Thus,
$$
f_Y(n) = \sum_{k=n}^4 f(k,n) =  \sum_{k=n}^4 P(X=k, Y=n) =  \sum_{k=n}^4 \frac{1}{10},
$$
e.g.,
$$
f_Y(3) = \sum_{k=3}^4 f(k,n) =  P(X=3, Y=3) + P(X=4, Y=3) = \frac{1}{10} + \frac{1}{10} = \frac{2}{10}.
$$


text:
Q: Always show the file extension inside the folder using vb.net Currently, I am working on an application that will need to always show the file extensions of the files inside the folder.
Example:
I have a folder named Awards and the Contents are Images.
Contents:

As you can see, the file extension is hidden.
But when you click the options red boxed on the image. the file extension will be shown.
My question is, Is there a way to check the checkbox on the Image using vb.net? If it is possible? How??
Thank you and Regards,


text:
Q: How to deploy a Spring-Boot-Webflux application to Tomcat standalone server? A normal spring-web application can be deployed to tomcat standalone as war file as follows:
@SpringBootApplication
public class MyApplication extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(MyApplication.class);
    }

    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

Question: how can I deploy such an application after migrating to spring-webflux to tomcat?
Docs say:
https://docs.spring.io/spring-framework/docs/current/reference/html/web-reactive.html#webflux-httphandler

To deploy as a WAR to any Servlet 3.1+ container, you can extend and
include AbstractReactiveWebInitializer in the WAR. That class wraps an
HttpHandler with ServletHttpHandlerAdapter and registers that as a
Servlet.

So but there is no example how to.
I tried as follows, which gives an exception:
@SpringBootApplication
public class MyApplication extends AbstractReactiveWebInitializer {

    @Override
    protected Class<?>[] getConfigClasses() {
        return new Class[] {MyApplication.class};
    }

    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

Result:
MyApplication.java:13:8
java: cannot access javax.servlet.ServletException
  class file for javax.servlet.ServletException not found

A: This use case is not supported by the Spring Boot team, as explained in the reference documentation. Even if some features might work, you'll find many limitations and bugs to this approach - and it seems you've started to experience just this.


text:
Q: Delphi: Why does this generate a memory leak? Why is TDemo.TBuilder is not automatically freed and producing a memory leak ?
TDemo.TBuilder should be freed automatically, as this is a TInterfacedObject object based on IInterface
type
  TDemo = class
    public type
      TBuilder = class(TInterfacedObject)
        public
          function Generate: TDemo;
      end;
    public
      class procedure Using;
  end;

implementation

function TDemo.TBuilder.Generate: TDemo;
begin
  Result := TDemo.Create;
  // on finish this method, TDemo.TBuilder should be freed !
end;

class procedure TDemo.Using;
begin
  with TDemo.TBuilder.Create.Generate do try
    // use TDemo

  finally
    Free;
  end;
end;

A: You have memory leak because TBuilder.Create returns object reference and since it is used as intermediate reference in with call it was never assigned to interface reference and its reference counting mechanism was never properly initialized.
To solve this, you need to declare IBuilder interface and use class function returning that interface for constructing such intermediate object.
  TDemo = class
  public type
    IBuilder = interface
      function Generate: TDemo;
    end;

    TBuilder = class(TInterfacedObject, IBuilder)
    public
      function Generate: TDemo;
      class function New: IBuilder;
    end;
  public
    class procedure Using;
  end;

class function TDemo.TBuilder.New: IBuilder;
begin
  Result := TBuilder.Create;
end;

  with TDemo.TBuilder.New.Generate do
  ...


text:
Q: Many, complex ModelError add I'm little bit new in .core mvc programming.
I have many date validations.
e.g.:
private void Validations()
{
    if (startDate >= endDate)
    {
       ModelState.AddModelError("", "ErrorMessage");
       return;
    }

    if (startDate < DateTime.Today)
    {
       ModelState.AddModelError("", "ErrorMessage");
       return;
    }

    if (startDate < dateInTheFuture)
    {
       ModelState.AddModelError("", "ErrorMessage");
       return;
    }

    var substracted = startDate.Subtract(endDate);

    if (substracted.Days < MinDays)
    {
       ModelState.AddModelError("", "ErrorMessage");
       return;
    }

    // and so on
}

Is there any way to make it cleaner or better than this?

A: You can:

*

*Use validation attributes to write manual validations less

*Create your own validation attribute for complex field validation logic

*Implement IValidatableObject on your model and move validation code inside model class


text:
Q: Blocking part of a website I am trying to block Google Reader:
reader.google.com
www.google.com/reader
The hard part is blocking the reader directory
I blocked reader.google.com by changing my /etc/hosts file (this is for a Mac)
Is there any way to block www.google.com/reader without buying software?
Note this is for Safari so Greasemonkey won't work, and Leopard's Parental Controls throttle the CPU when they are turned on.
Also I've tried OpenDNS, which is awesome, but doesn't work for this...
Any thoughts?
Update: This is for a laptop that travels a lot. So a router or a home proxy server won't work. Firefox would work, but I don't think I can uninstall Safari from a mac.

A: Set up a proxy server and block it via that.
-Adam

A: You could do this with a proxy (for example Proxomitron).

A: You can use Privoxy to filter about anything.

A: Another option is to use a free service like www.opendns.com as your dns servers, they allow you to block specific domains or turn on filtering etc.

A: What about at the router level?  My router as an URL blocker built in.

A: Maybe you can find some sort of http proxy you could install to filter this content and use that when browsing. On Firefox you could easily define a rule for Adblock Plus.

A: I did exactly what you're looking for using Safari AdBlock. Just define a few rules in Safari->Preferences->AdBlock and you should be good to go!


text:
Q: jQuery/Javascript Detect when user wants to scroll further -the "bounce" effect at the end of the page I am developing a website with 8 different sections. For the mobile version, I want that once the user has reached the bottom of a section if he tries to scroll further down, right after (or instead of) the content bounce that usually happens, the next section will come up.
I already know how to detect when the user reaches the bottom using jquery
function check_bottom(e)
{
    var elem = $(e.currentTarget);
    if (elem[0].scrollHeight - elem.scrollTop() == elem.outerHeight())
    {}
}

but how do I know if he tries to scroll past that point?
Thank you so much!


text:
Q: Need guidance in using Spark for publishing data to Kafka I'm trying to write a spark java code for publishing messages to kafka topic. Its working as expected. However, the amount of time it takes to load data is on similar scale to Naive approach.
Can you help me understand if I m missing out something?
Spark producer way:
public void loadInputDataToKafka(JavaRDD<Customer> inputData)
  {

    inputData.foreachPartition(customerIterator -> {
      Properties properties = getKafkaConfiguration();
      Producer<String, String> producer = new KafkaProducer<String, String>(properties);

      while(customerIterator.hasNext()) {
        producer.send(new ProducerRecord<String, String>("testTopic",
            null, customerIterator.next().toString())).get();
      }
      producer.close();
    });
  }

Naive Approach:
public void loadInputDataToKafka(JavaRDD<Customer> inputData)
      {

        Properties properties = getKafkaConfiguration();
        Producer<String, String> producer = new KafkaProducer<String, String>(properties);

        List<Customer> customerList = inputData.collect();
        for(Customer customer:customerList) {
          try {
            producer.send(new ProducerRecord<String, String>("testTopic",
                null, customer.toString())).get();
          } catch (Exception e) {
            producer.close();
            throw Throwables.propagate(e);
          }
        }

Time taken to load 80K records using approach 1 and 2 are on similar scale (150 seconds). Am I not using spark partitions in the right way? If no, what is the advantage that I get out of spark vs going for a regular iteration?


text:
Q: How to take the input as an image instead of taking input from the camera in python I want to take the input as an image instead of taking input from the camera. in this code i am taking the input from the camera. But i want to take the input from an image which is in a folder. How to do that. Here is my code
I am going to input images for pre trained model and get the output. This is a OCR project. I have trained the model. In this code the input image is getting from the camera. But i want to give the image from a file, not from the camera. How to do that....
import numpy as np
import cv2
import pickle
from tensorflow.python.keras.models import load_model

###parameterrs###

width = 640
height = 480
threshold = 0.65
#threshold means minimum probability to classify

#this is the code for creatinng the image objrct
imageObj=cv2.imread("SinhalaDataSet/1/img0_0.png")

#this is the code for creatinng the camera objrct

capture = cv2.VideoCapture(0)
capture.set(3,width)
capture.set(4,height)

#here im loading the saved pretrained model
model = load_model('model.h5')

#thid is the code for processing
def preProcessing(img):
    img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    img = cv2.equalizeHist(img)
    img = img/255
    return img

while True:
    success, imgOriginal = capture.read()
    img = np.asarray(imgOriginal)
    img=cv2.resize(img,(32,32))
    img = preProcessing(img)
    cv2.imshow("Processsed Image",img)
    img = img.reshape(1, 32, 32, 1)
    #prediction
    classIndex = int(model.predict_classes(img))

    labelDictionary = {0: '0',    1: 'අ',   2: 'ඉ',  3: 'ඊ',   4: 'උ',  5: 'එ',  6: 'ඒ',    7: 'ඔ',    8: 'ක', 9: 'ක්', 10: 'කා',
                       11: 'කැ',  12: 'කෑ', 13: 'කි', 14: 'කී', 15: 'කු', 16: 'කූ', 17: 'කෙ', 18: 'කේ',  19: 'කො',
                       20: 'කෝ', 21: 'ඛ', 22: 'ග',  23: 'ගි', 24: 'ගී', 25: 'ගු',  26: 'ගූ',  27: 'ඝ',   28: 'ඟ', 29: 'ච',
                       30: 'ඡ',   31: 'ජ', 32: 'ජ්',  33: 'ජි', 34: 'ජී', 35: 'ඣ', 36: 'ඤ',  37: 'ඥ',  38: 'ට', 39: 'ඨ',
                       40: 'ඩ',   41: 'ඪ', 42: 'ණ', 43: 'ඬ', 44: 'ත', 45: 'ත්', 46: 'ථ',   47: 'ථි',   48: 'ථී', 49: 'ද', 50: 'දු',
                       51: 'දූ',   52: 'ධ', 53: 'න',  54: 'ඳ', 55: 'ප', 56: 'පු', 57: 'පූ',   58: 'ඵ',   59: 'බ', 60: 'භ',
                       61: 'ම',   62: 'ම්', 63: 'මි',  64: 'මී', 65: 'ඹ', 66: 'ය', 67: 'ර',   68: 'ල',   69: 'ව', 70: 'ව්', 71: 'වි',
                       72: 'වී',   73: 'වු', 74: 'වූ',  75: 'ශ', 76: 'ෂ', 77: 'ස', 78: 'හ',   79: 'ළ',   80: 'ළු', 81: 'ෆ',
                       82: 'ා'}

    predictions = model.predict(img)
    predictedLetter = labelDictionary.get(classIndex)
    probabilityValue = np.amax(predictions)
    print(predictedLetter, probabilityValue)

    if probabilityValue > threshold:

        cv2.putText(imgOriginal, str(predictedLetter) + "   " + str(probabilityValue),
                    (50, 50), cv2.FONT_HERSHEY_COMPLEX_SMALL,
                    1, (0, 0, 255), 1)

    cv2.imshow("Testing Window", imgOriginal)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

A: You can read an image from a file using the cv2.imread() method:
import cv2

img = cv2.imread("image.png")

cv2.imshow("Image", img)
cv2.waitKey(0)

Similarly, you can allow the user to input the names of images:
import cv2
import os

imgs = []

while True:
    file = input("Input filename >>> ")
    if file == "QUIT":
        break
    if os.path.exists(file):
        img = cv2.imread(file)
        imgs.append(img)
    else:
        print("File not found.")

If you have a series of images you want to display, in the form of an animation, you can use the built-in glob module to list all the needed images. For example, if you have 10 images in desktop that begins with image, followed by a number and the image's extension, here is how you would go about looping through and displaying each image:
import glob
import cv2

for img in glob.glob("C:\\Users\\Username\\Desktop\\image*.png"):
    cv2.imshow("Animation", img)
    if cv2.waitKey(1) & 0xFF == ord("q"):
        break


text:
Q: Cancel ajax request from chrome developer tools I want to cancel the ajax request from chrome developer tools after it has initiated. For example I want to test my fallback message is showing correctly. I can set No throttling to Offline so that all calls will fail, but I just want to test one API to fail, for debugging purposes.

I know I can use abort() methods, (ie I can do it through JavaScript). I dont want to touch the code for just this need.
There's a replay XHR option in right click of the API, It'll be great there is something like abort XHR in same way. But there isn't.

A: From Chrome 59 you can block specific requests from Network tab of developer tools itself.
https://developers.google.com/web/updates/2017/04/devtools-release-notes#block-requests
Right-click on the request in the Network panel and select Block Request URL. A new Request blocking tab pops up in the Drawer, which lets you manage blocked requests.
So, In my case, I will run the code block that specific API and then re-run. :)
As per the comment, this is not exactly canceling the already started request, but checking how the app behaves if only one request is failed by blocking only one request. Thanks @Ross Ivantsiv for this.

A: There is a simple trick I use. Pressing F5 while in the tab immediately followed by ESC.
XHR requests still active by chrome are canceled before the new answer is loaded.

A: *

*If you don't know the exact URL, You can debug all XHR by adding an XHR breakpoint within the Sources tab

*Or if you know the name or part of XHR URL which you need to debug you can add it XHR by clicking the ( + ) icon.


text:
Q: Java Regex doesn't work with special chars I got a problem with my parser. I want to read an image-link on a webiste and this normally works fine. But today I got a link that contains special chars and the usual regex did not work.
This is how my code looks like.
Pattern t = Pattern.compile(regex.trim());

Matcher x = t.matcher(content[i].toString());
if(x.find())
{
    values[i] = x.group(1);
}

And this is the part of html, that causes trouble

And this is the regex I am using to get the part in the src-attribute:

I believe that it has something to do with all the special character inside the link. But I'm not sure how to escape all of them. I Already tried
Pattern.quote(content[i].toString())

But the outcome was the same: nothing found.

A: The . character usually only matches everything except new line characters. Therefore, your pattern won't match if there are newlines in the img-tag.
Use Pattern.compile(..., Pattern.DOTALL) or prepend your pattern with (?s).

In dotall mode, the expression . matches any character, including a
  line terminator. By default this expression does not match line
  terminators.

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/regex/Pattern.html#DOTALL

A: You should actually use  with (?s) modifier.

A: You regex should be like:
String regex = "";

A: This probably caused by the newline within the tag. The . character won't match it.
Did you consider not using regex to parse HTML? Using regex for HTML parsing is notoriously fragile construct. Please consider using a parsing library such as JSoup for this.


text:
Q: componentsByString for NSMutableSet in Swift 3.0 I have label and NSMutable Set.
I want to assign my set value to label.text.
  @IBOutlet var location: UILabel!
 var mutSet:NSMutableSet = NSMutableSet()

        self.location.text = **mutSet.allObjects.componetsJoinedByString("\n")**

mutSet.allObjects.componetsJoinedByString("\n") throws compile time error
similarly I have tried joined , it also throws compile time error.
Please provide me alternative way in Swift

A: First of all to answer your question: You have to write
(mutSet.allObjects as! [String]).joined(separator: "\n")

NS(Mutable)Set lacks any type information. You have to cast the type to actual [String]

It's highly recommended to use native Set and generally you are discouraged from using NSMutable... types if there is a native counterpart.
var mutSet = Set<String>(["a", "b", "c"])

You can append (actually insert) an item - a set is unordered
mutSet.insert("d")

or an array of items
mutSet.formUnion(["c", "d", "f"])

Joining is much shorter than in Foundation NSMutableSet
mutSet.joined(separator: "\n")

or sorted joined
mutSet.sorted().joined(separator: "\n")


text:
Q: animation with medal & ribbon at level finished i am new to cocos2d and iphone. i have implemented one simple animation using particle system. it works fine. now i want some more animation like , when my star animation(using particles) completes , i want one medal with ribbon falling down from top to bottom in my screen, i want it's movement just same like we release medal from our hand & hold the ribbon. .can we achieve this kind of action or rather say animation using cocos2d ... any kind of help or idea would be appreciated a lot . .
i have implemented something like this :

A: I think rope physics would work, but it seems a little too much to add physics just for that.
I would say that the best strategy would be to make an CCSprite animated with CCAnimation.
There is a tutorial for that in this site: http://getsetgames.com/2010/04/18/how-to-animate-sprites-in-cocos2d/
[edit]
Cocos2d introduction to Rope Simulations: cocos2d-iphone.org/verlet-rope


text:
Q: SwiftUI: Arrange middle layer in ZStack dependent on top layer I would like to implement a UI, which has

*

*a background image, which is fullscreen and scales with the device size

*a gradient above the background image and below the main UI, which is aligned bottom and it's size is dependent of the positioning of one element in the main UI

*the main UI with multiple VStacks of interface elements. There is a top area and a bottom area which are both fix aligned and sized, and a variable spacer in between

This mockup shows the intended arrangement with a 3 layer ZStack (from left to right):
This is what I got in SwiftUI:
struct TestView: View {

    var body: some View {
        ZStack() {
            // BG Image
            Image("BgImg")
                .resizable()
                .scaledToFill()
                .frame(width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.width)

            // Gradient
            VStack {
                Spacer()
                Rectangle()
                    .fill(
                        LinearGradient(gradient: Gradient(stops: [
                            Gradient.Stop(color: Color(.black).opacity(0.0), location: 0),
                            Gradient.Stop(color: Color(.black), location: 0.5),
                        ]), startPoint: .top, endPoint: .bottom)
                    )
                    // HOW TO GET THE RIGHT SIZE HERE?
                    .frame(height:500)
            }

            // Main UI
            VStack {
                // VStack 1
                VStack {
                    Text("ABC")
                    Text("DEF")
                }.frame(height:260)

                // Fixed spacer
                Spacer().frame(height:26)

                // VStack 2
                VStack {
                    Text("123").foregroundColor(.white)
                    Text("456").foregroundColor(.white)
                }.frame(height:162)

                // Variable spacer
                Spacer()

                // VStack 2
                VStack {
                    Text("!!!").foregroundColor(.white)
                    Text("???").foregroundColor(.white)
                }.frame(height:304)
            }
            // Fixed spacer top
            .padding(.top, 26)
            // Fixed spacer bottom
            .padding(.bottom, 32)

        }
        .edgesIgnoringSafeArea(.all)
    }
}

struct TestView_Previews: PreviewProvider {
    static var previews: some View {
        TestView()
            .previewDevice("iPhone 13 Pro")
            .preferredColorScheme(.light)
    }
}

My questions are:

*

*How can I size the gradient the right way?

*Why does the gradient now align to the bottom, and why does the background image not scale to fullscreen, see bottom of the preview screenshot

A: For the Image not taking the fullscreen, you need to let that Image ignore the safe area, not just the ZStack;
You need to read the height up till the end of the stack using a GeometryReader then assign it to a value used to size the gradient.


text:
Q: Rails 3 string contains HTML code need to loop through the code in string I am working on the rails 3 application where i need to pass the html code in to the string variable and pass it to the web services as parameter.
I have the following code with the loop inside but since it is declare in to the string it is not working  with the <%%> and #{} tag
      @emaildata = "
FLOOR VIEW ACTION REQUEST

          Submitted On:
          #{Date.today}

           Originator:
          #{session[:user_name]}

                    ACTION CODE
                    PART
NUMBER
                    LOCATION
                    BIN QTY
                    PACK QTY
                    UM
                    SCAN CODE
                    REASON / COMMENTS

                <% (1..PartNoListInEmail.length).each_index do |i|%>

                    #{@ActionCodeListInEmail[i]}
                    #{@PartNoListInEmail[i]}
                    #{@SendToListInEmail[i]}
                    #{@OrderQtyListInEmail[i]}
                    #{@PackQtyListInEmail[i]}
                    #{@UMListInEmail[i]}
                    #{@ScancodeListInEmail[i]}
                    #{@reasonForActionIn[i]}

               <%end%>

"

Please help me .

A: Save your html as partial as a html.erb
@emaildata = "<%= escape_javascript(render :partial=>'some_partial_name', :locals => {:PartNoListInEmail => @PartNoListInEmail}).html_safe %>"

A: For combining strings with HTML, you want to use a template system like Erb or Haml. If you don't intend to immediately render the template back to a browser, you can still use Erb to do this by calling Erb directly, having it parse the HTML string and variables and return the result as a string.
Once you go down this road, be extra careful of user provided content and escape anything untrustworthy. When you render erb templates normally in rails, rails does a fair amount of work for you to avoid these sorts of problems, but once you do something like what your example showed, or if you use Erb directly to parse it, you no longer benefit from Rails' safety checks, and therefore will need to put in your own checks.


text:
Q: Can a \hbox be made to attain all of its surrounding space? If I have two boxes like so:
\hbox to 2cm{\vrule\hfil\hbox{\vrule keke\vrule}\hfil\vrule}
\bye

, then is it possible somehow for the inner \hbox to take all of that 2cm? (the \hfils and \vrules are there only to illustrate the sizes)

A: This doesn't answer your question, but perhaps you want something like this?
\documentclass{article}
\makeatletter
\newcommand\labeleddownbracefill[1]{%
        $\m@th
        \setbox\z@\hbox{$\braceld$}%
        \braceld
        \leaders\vrule\@height\ht\z@\@depth\z@\hfill
        \braceru
        \raise1ex\hbox to\z@{\hss$\scriptstyle#1$\hss}%
        \bracelu
        \leaders\vrule\@height\ht\z@\@depth\z@\hfill
        \bracerd
        $%
}
\makeatother
\begin{document}
\begin{tabular}{cc}
foo&\labeleddownbracefill{\lambda}\\
bar&Here is some text to be braced\\
\end{tabular}
\end{document}

A: My idea was hairier than I thought, and falls a bit too far from a solution to count as an answer, but since I spent some time on it ...  the basic idea, given code as follows (all code in Plain Tex):
\setbox0=\hbox to 3in
    {\hfill a\hfill} % Box 0 is an hbox containing a skip, an hbox-like item, and a skip
\showbox0

is that (i) \showbox will tell you the information you need to reengineer the hbox by telling you how it "sets" glue:
\hbox(4.30554+0.0)x216.81, glue set 105.905fill
.\glue 0.0 plus 1.0fill
.\tenrm a
.\glue 0.0 plus 1.0fill

namely that 1.0fill is 105.905 of Tex's internal measure; and (ii), you can use this glue setting factor to go back and substitute the vrule for the last skip:
\skip0=105.95 % the glue setting factor
\setbox1=\hbox to 3in
   {\unhcopy0 % Make contents so far of this box be contents of box 0
    \unskip %remove last skip
    \hbox to \skip0{\vrule}} %put in hbox of same width as removed skip

The the two box registers will contain three items of the same width, but the last skip from box 0 will be replaced by a rule in box 1.  You can make this step easier by defining a macro with a "hole" where the skip/hbox are to go.
We don't want to have to calculate the width based on looking up the results by hand: we want to get the "setting" width for the glue dimension automatically.  This is where it gets hard.  I think there is no way in Tex or Etex to internally extract the stretch/shrink factor of skips, although there is the possibility to spit out the information using \showbox and perform the calculation externally.  Luatex does allow you to look inside the stretch/shrink factor, but it doesn't seem to directly allow you to inspect the setting factor.
So I can think of two problematic ways to get the value wanted here:

*

*By parsing the output of \showbox externally;

*In Luatex, by recursing over the structure of a box and computing the glue setting based on the information gathered (i.e., reconstructing what the Tex algorithm does already).


text:
Q: Avoid mutating a prop directly in VueJS 2 First of all, I am just starting playing with VueJS, so this cannot be a VueJS version thing as suggested here
It might be a duplicate of :

*

*How to solve [Vue warn]: Avoid mutating a prop directly since the value will be overwritten on vue.js 2? - the difference is that I am only trying to set the values with v-bind, once.

*Avoid mutating a prop directly since the value will be overwritten - This also looks somehow similar, but the solution didn't worked for me.

*What's the correct to modify VUE component via javascript? - this solution looks pretty much what I have in my case

*vuejs update parent data from child component
My problem starts with my Html looking like this:

      <birthday-controls
       :birthDay="birthDay"
       :birthMonth="birthMonth"
       :birthYear="birthYear">
      </birthday-controls>

and JS:
Vue.component('birthday-controls', {

    template: `

    <input type="text" name="year"  placeholder="yyyy" v-model="birthYear" size="4" maxlength="4"/>
    <input type="text" name="month" placeholder="mm" v-show="validYear" v-model="birthMonth" size="3" maxlength="2"/>
    <input type="text" v-show="validYear && validMonth" name="day" placeholder="dd" v-model="birthDay" size="2" maxlength="2"/>

`,

    props: ['birthDay', 'birthMonth', 'birthYear'],

    computed: {
        validYear: function() {
            return (this.birthYear > new Date().getFullYear()-100 && this.birthYear < new Date().getFullYear()-14)
        },
        validMonth: function() {
            return (this.birthMonth > 0 && this.birthMonth <= 12)
        },
        validDay: function() {
            return (this.birthDay > 0 && this.birthDay <=31) //I have to add more checking here for february, leap years and ....
        }
    }

});

new Vue({
    el: '#app',

    data: function() {
        return {
            birthDay: "",
            birthMonth: "",
            birthYear: ""
        }
    },

});

I have prepared codepen here: http://codepen.io/AngelinCalu/pen/OpXBay
However, the second answer from here: vuejs update parent data from child component makes me realise that I'm missing something
In that example it sets an this.$emit('increment') inside one of the methods, and triggers that on specific event.
In this other example: Update a child's data component to the father component in vue.js using .vue webpack(vue2) , the answer suggest adding a watch to emit the change.
  watch: {
    val() {
      this.$emit('title-updated', this.val);
    }
  }

Now I'm even more confused! What is the right (or best) way to deal with this problem?
Note:
If I remove from the initial html :
   :birthDay="birthDay"
   :birthMonth="birthMonth"
   :birthYear="birthYear"

It still works as expected, but I'm still getting that Vue warn, however, if I'm following the method from here: https://stackoverflow.com/a/41901150/2012740, it stops working, but I'm getting no error.
My Updated code: https://jsfiddle.net/angelin8r/647m7vdf/
To conclude: I need the functionality from the beginning but without the [Vue warn]
This is what I got in my initial example:

[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "birthYear"

A: The warning is the result of setting v-model to the value of your properties. The reason is because if you change birthYear, birthMonth, or birthDay outside the component, then whatever the value is currently inside the component will be immediately overwritten.
Instead, capture a copy.
Vue.component('birthday-controls', {

    template: `

    <input type="text" name="year"  placeholder="yyyy" v-model="internalBirthYear" size="4" maxlength="4"/>
    <input type="text" name="month" placeholder="mm" v-show="validYear" v-model="internalBirthMonth" size="3" maxlength="2"/>
    <input type="text" v-show="validYear && validMonth" name="day" placeholder="dd" v-model="internalBirthDay" size="2" maxlength="2"/>

`,

    props: ['birthDay', 'birthMonth', 'birthYear'],

    data(){
      return {
        internalBirthDay: this.birthDay,
        internalBirthMonth: this.birthMonth,
        internalBirthYear: this.birthYear
      }
    },

    computed: {
        validYear: function() {
            return (this.internalBirthYear > new Date().getFullYear()-100 && this.internalBirthYear < new Date().getFullYear()-14)
        },
        validMonth: function() {
            return (this.internalBirthMonth > 0 && this.internalBirthMonth <= 12)
        },
        validDay: function() {
            return (this.internalBirthDay > 0 && this.internalBirthDay <=31) //I have to add more checking here for february, leap years and ....
        }
    }

});

You did this almost exactly in your fiddle, but you did not correct your computed values.
computed: {
    validYear: function() {
        return (this.birthYear > new Date().getFullYear()-100 && this.birthYear < new Date().getFullYear()-14)
    },
    validMonth: function() {
        return (this.birthMonth > 0 && this.birthMonth <= 12)
    },
    validDay: function() {
        return (this.birthDay > 0 && this.birthDay <=31) //I have to add more checking here for february, leap years and stuff
    }
},

should be
computed: {
    validYear: function() {
        return (this.var_birthYear > new Date().getFullYear()-100 && this.var_birthYear < new Date().getFullYear()-14)
    },
    validMonth: function() {
        return (this.var_birthMonth > 0 && this.var_birthMonth <= 12)
    },
    validDay: function() {
        return (this.var_birthDay > 0 && this.var_birthDay <=31) //I have to add more checking here for february, leap years and stuff
    }
},


text:
Q: jQuery Validate - Checkbox Group ONLY ONE can be checked I'm seeing a LOT of "at least one needs to be checked", but I'm not seeing any solutions on how to limit a checkbox group to only ONE can be checked.
EDIT: 3/2/17 # 9:20am
Why not a radio button?
Here's why:  This particular group of checkboxes lives inside a larger group of checkboxes that only require you to have at least one checked. I need to retain THAT rule, but also apply the rule, in this specific group, that only ONE of these can be selected - yet still maintain the overall group rule that at least one must be selected. Here's some markup:
HTML:

     <input type="checkbox" id="A" name="atLeastOne" value="A"> A
     <input type="checkbox" id="B" name="atLeastOne" value="B"> B
     <input type="checkbox" id="C" name="atLeastOne" value="C"> C
     <input type="checkbox" id="D" name="atLeastOne" value="D"> D

               <input type="checkbox" id="E" name="onlyOne" value="E"> E
               <input type="checkbox" id="F" name="onlyOne" value="F"> F
               <input type="checkbox" id="G" name="onlyOne" value="G"> G

     <input type="checkbox" id="H" name="atLeastOne" value="H"> H

Hopefully this makes more sense than my original question.

A: If you want that only one option can be selected that rather use a radio button instead.
<input name="field" type="radio" />

A: https://www.w3schools.com/html/html_forms.asp
<input type="radio">

Should fulfill your needs better than trying to validate checkboxes.


text:
Q: Replacing second part of string with Javascript and replace() I need to replace any occurrence of a sequence of integers followed by a dash and then another sequence of integers, with only the first sequence of integers. For example:
THIS IS A STRING   2387263-1111  STRING CONTINUES

Will become:
THIS IS A STRING   2387263  STRING CONTINUES

Can I use that with Javascript and replace()?

A: NEW ANSWER -
Yes, in your case according to me, first you need to match that whole string "2387263-1111" using a regex and then remove that part followed by '-' and then replace the result in the original string.
Check the answer from codaddict. Mine would've almost been same but his answer seems more appropriate.
OLD ANSWER: -
Why replace? Just use split and get the first value.
var str = "2387263-1111";
var output = str.split("-")[0];

A: You can do:
str = str.replace(/(\d+)-\d+/,'$1');

See it
Which replaces a group of digits followed by a hyphen followed by a group of digits with the first group of digits.
If you want to replace multiple occurrences of such pattern just use the g modifier as:
str = str.replace(/(\d+)-\d+/g,'$1');

A: User RegExp function of javascript
str = str.replace(new RegExp("-[0-9]+"), " ");

A: Not really a new answer, just an addition to codaddict. Don't know JScript's regex
all that well, but I asume it uses extended regular expressions (if not, forget this).
If you need validation on boundry conditions you could do something like this:
str = str.replace( /((^|\s)\d+)-\d+(?=\s|$)/g, '$1' );
That would prevent matching this type of thing:
A STRING 2387263-1111STRING CONTINUES
A STRING2387263-1111 STRING CONTINUES
A STRING2387263-1111STRING CONTINUES


text:
Q: mocking globals in react tests not working I have got a test for a setup that uses a GlobalStore which uses the context api that wraps a second object which also utilizes the globals.
I've tried mocking the following syntax inside my test and my program crashes when I add in the child component
global.MyGlobal = {object: "whatever"}
Does anyone have any sugestions?


text:
Q: ggmap not handling polygons that fall outside boundary I have a data frame that has the boundaries for several polygons (in this case, US Census Tracts).
I'm trying to plot those with ggmap, but I'm getting an error when I try to zoom in. Since some points in those polygons fall outside the ggmap boundary, they are removed (instead of considered, but not in the plot area), which leads to wrong shapes.
For example, here's the top of the data frame:
> head(tract_df)
       long      lat order  hole piece id group
1 -110.8798 32.24926     1 FALSE     1  0   0.1
2 -110.8798 32.24973     2 FALSE     1  0   0.1
3 -110.8798 32.24988     3 FALSE     1  0   0.1
4 -110.8798 32.25004     4 FALSE     1  0   0.1
5 -110.8798 32.25051     5 FALSE     1  0   0.1
6 -110.8798 32.25058     6 FALSE     1  0   0.1

When I simply plot with ggplot, I can plot those nicely, using the coord_map() function:
ggplot() +
  geom_polygon(data = tract_df,
               aes(x = long, y = lat, group = group),
               color = "black",
               size = 0.10, alpha = 0.7) +
  coord_map(xlim = c(-112.68, -111.44),
            ylim = c(33.18, 33.83))

However, if I use ggmap, it breaks those borders:
ggmap(phoenix_map) +
  geom_polygon(data = tract_df,
               aes(x = long, y = lat, group = group),
               color = "black",
               size = 0.10, alpha = 0.7)

If I add coord_map to the ggmap plot, I get a warning, but it works. Is there a correct way of doing this that won't get me the warning?


text:
Q: Using wix, how to install Dot net framework 4.5 for Windows 7/8 and dot net 4.0 from Xp and vista I want to install Dot net framework 4.5 as a prerequisite for my application wherever it is possible.As minimum  OS requirement for dot net framework 4.5 is Windows Vista SP2.I would like to install dot net framework 4.5 on OS on or above Windows Vista SP2 and Dot net framework 4.0 below Windows Vista Sp2 (i.e. Windows Xp machine). I am using below code.
<PropertyRef Id="NETFRAMEWORK40FULL" />
<PropertyRef Id="NETFRAMEWORK45" />
<Condition Message="This application requires .NET Framework 4.0 Full or .NETFramework 4.5. Please install the .NET Framework then run this installer again.">
  <![CDATA[Installed OR NETFRAMEWORK40FULL OR NETFRAMEWORK45]]>
</Condition>

<Chain>
  <PackageGroupRef Id="NetFx40Web" />
  <PackageGroupRef Id="NetFx45Web" />
  <PackageGroupRef Id="SqlServer2008R2" />
</Chain>

But it is giving error as
The Windows Installer XML variable 'WixMbaPrereqPackageId' is declared in morethan one location.
The Windows Installer XML variable 'WixMbaPrereqLicenseUrl' is declared in more than one location.

I think We can not install both DotnetFramework4 and DotnetFramework 4.5 using WixNetFxExtension library. What choices to do i have now to implement it?? Should i have to manually write a PackageGroup to install Dot net Framework 4.5 checking the OS version is compatible to install it.

A: Wix has documentation for installing the .Net framework with your applications using Burn.
http://wixtoolset.org/documentation/manual/v3/howtos/redistributables_and_install_checks/install_dotnet.html


text:
Q: Hyperopt Exploration/Exploitation strategy What kind of settings Hyperopt provides to adjust balance between exploration with exploitation ? There's something like "bandit" and "bandit_algo" in the code but no explanation.
Could someone provide any code sample.
Thanks a lot for any help!

A: I just found hyperopt partial() a magical wrapper function for the optimizer algo. It allows to balance between different strategies and then E/E:
Partial returns the result of a randomly-chosen suggest function. For example to search by sometimes using random search, sometimes anneal, and sometimes tpe, type:
fmin(...,
algo=partial(mix.suggest,
p_suggest=[
(.1, rand.suggest),
(.2, anneal.suggest),
(.7, tpe.suggest),]),
)

Parameter "p_suggest": list of (probability, suggest) pairs. Make a suggestion from one of the suggest functions, in proportion to its corresponding probability. sum(probabilities) must be [close to] 1.0.
If you want an even sharper control of algo progression: you can use the fact that hyperopt optimizer algos are stateless and return the trial object which can be provided as an input to a new fmin to continue the process. Then you can call fmin with max_evals at 1 and handle the process in a loop, therefore you could modify "trials" and "suggest algo" between each iteration.

A: For the best bet, read the papers by Bergstra et. al. 1 2 and 3. I am not 100% clear on what the bandit_algo is, except that one of the papers mentions it as an alternative method to Gaussian Process and Tree of Parzen Estimators - maybe you can use it in the same way as those two?
My guess is that if it not documented, it may not be finished yet. You can try raising an issue on Github - the devs are fairly responsive from what I have seen.
EDIT: Looking at this paper, these bandit algorithms may be the base class that the others inherit from.


text:
Q: How can you persist user data for command line tools? I'm a front-end dev just venturing into the Node.js, particularly in using it to create small command line tools.
My question: how do you persist data with command line tools? For example, if I want to keep track of the size of certain files over time, I'd need to keep a running record of changes (additions and deletions) to those files, and relevant date/time information.
On the web, you store that sort of data in a database on a server, and then query the database when you need it again. But how do you do it when you're creating a Node module that's meant to be used as a command line tool?
Some generic direction is all I'm after. I don't even know what to Google at this point.

A: It really depends on what you're doing, but a simple approach is to just save the data that you want to persist to a file and, since we're talking node, store it in JSON format.
Let's say you have some data like:
var data = [ { file: 'foo.bar', size: 1234, date: '2014-07-31 00:00:00.000'}, ...]

(it actually doesn't matter what it is, as long as it can be JSON.stringifiy()d)
You can just save it with:
fs.writeFile(filename, JSON.stringify(data), {encoding: 'utf8'}, function(err) { ... });

And load it again with:
fs.readFile(filename, {encoding: 'utf8'}, function(err, contents) {
    data = JSON.parse(contents);
});

You'll probably want to give the user the ability to specify the name of the file you're going to persist the data to via an argument like:
node myscript.js <data_file>

You can get that passed in parameter with process.argv:
var filename = process.argv[2]; // Be sure to check process.argv.length and have a default

Using something like minimist can be really helpful if you want to get more complex like:
node myscript.js --output <data_file>

A: You also can store files in temporary directory, for example /tmp directory on linux and give user the option to change the directory.
To get path to temporary directory you can use os module in nodejs:
const os = require('os');

const tmp = os.tmpdir();


text:
Q: Unhide hidden column with the same button as Hide Command I have this code on a command button. and once the columns are hidden, I want to unhide it by clicking the same button
Private Sub CommandButton16_Click()
    For i = 22 To 145

    If Worksheets("Material Masterlist").Cells(3, i).Value = "Quantity" Then
    Worksheets("Material Masterlist").Columns(i).Hidden = True
    CommandButton16.Caption = "Unhide Quantity"
        CommandButton15.Font.Size = 7
    End If
    Next
End Sub

A: Replace:
Worksheets("Material Masterlist").Columns(i).Hidden = True

With:
Worksheets("Material Masterlist").Columns(i).Hidden = (Not Worksheets("Material Masterlist").Columns(i).Hidden)

A: It seems that the requirement is to hide or unhide the columns with value Quantity base on the caption of the CommandButton16, not based on whether the column is already hidden or not.
This is my understanding of the requirements:

*

*If CommandButton16 caption = "Hide Quantity" (or <> "Hide Quantity", change as required)
1.1. Hide column of any cell in Range [V3:EO3] that is equal to "Quantity"
If there was at least one cell in Range [V3:EO3] equal to "Quantity" then:
1.2. Change CommandButton16 caption to "Unhide Quantity"
1.3. Change CommandButton15 font size to 7

*If CommandButton16 caption = "Unhide Quantity"
2.1. Unhide all columns in Range [V3:EO3](i)
2.2. Change CommandButton16 caption to "Hide Quantity" (change as required)
2.3. Change CommandButton15 font size to 12 (change as required)
(i) Assumes that only the columns of cells equal to "Quantity" in Range [V3:EO3] are hidden.
*Otherwise: * 2.1. Unhide column of any cell in Range [V3:EO3] that is equal to "Quantity"
Try this code:
Private Sub CommandButton16_Click()
Const kValue As String = "Quantity"     'Use Constants to provide flexibility
Const kHide As String = "Hide "
Const kUnhide As String = "Unhide "
Dim Rng As Range, Cll As Range
Dim blHide As Boolean

    Set Rng = Worksheets("Material Masterlist").Cells(3, 22).Resize(1, 124) '1 +145 -22     'Set range of cells to be checked

    With CommandButton16

        If .Caption = kHide & kValue Then

            For Each Cll In Rng.Cells
                With Cll
                    If .Value = kValue Then
                        .Columns.Hidden = True
                        blHide = True
                    End If
                End With
            Next

            If blHide Then
                .Caption = kUnhide & kValue
                CommandButton15.Font.Size = 7
            End If

        ElseIf .Caption = kUnhide & kValue Then

            Rem Use this line if only the columns of cells equal to "Quantity" in Range [V3:EO3] are hidden.
                Rng.Columns.Hidden = False

            Rem Otherwise use these lines
                For Each Cll In Rng.Cells
                    If Cll.Value = kValue Then Cll.Columns.Hidden = False
                Next

            .Caption = "Hide Quantity"
            CommandButton15.Font.Size = 12   'Change as required

        End If
    End With

    End Sub

Resource used:
Worksheet.Range,
With statement


text:
Q: WKWebKit on iOS crashes without debug information WebKit is crashing on iOS 11 without any debugging information - below is the best I can do.
Thread 1: EXC_BAD_ACCESS (code=1, address=0x10)

Is it possible to find out why this is crashing?
Thanks
WebKit`>::lookup<WTF::HashMapTranslatorAdapter<WTF::HashMap<WTF::String, WTF::Ref<WebKit::WebURLSchemeHandler>, WTF::StringHash, WTF::HashTraits<WTF::String>, WTF::HashTraits<WTF::Ref<WebKit::WebURLSchemeHandler> > >::KeyValuePairTraits, WTF::IdentityHashTranslator<WTF::HashMap<WTF::String, WTF::Ref<WebKit::WebURLSchemeHandler>, WTF::StringHash, WTF::HashTraits<WTF::String>, WTF::HashTraits<WTF::Ref<WebKit::WebURLSchemeHandler> > >::KeyValuePairTraits, WTF::StringHash> >, WTF::String>:
    0x19270161c <+0>:   stp    x26, x25, [sp, #-0x50]!
    0x192701620 <+4>:   stp    x24, x23, [sp, #0x10]
    0x192701624 <+8>:   stp    x22, x21, [sp, #0x20]
    0x192701628 <+12>:  stp    x20, x19, [sp, #0x30]
    0x19270162c <+16>:  stp    x29, x30, [sp, #0x40]
    0x192701630 <+20>:  add    x29, sp, #0x40            ; =0x40
    0x192701634 <+24>:  mov    x19, x1
    0x192701638 <+28>:  ldr    w21, [x0, #0xc]
    0x19270163c <+32>:  ldr    x22, [x0]
    0x192701640 <+36>:  ldr    x0, [x19]
->  0x192701644 <+40>:  ldr    w8, [x0, #0x10]

A: Make sure the url you are using has the http url scheme using the following code:
if !urlString.hasPrefix("http://") && !urlString.hasPrefix("https://")
    {
        urlString = "http://" + urlString
    }

You may also need to ensure you have NSAllowsArbitraryLoads enabled, open your plist as source code and copy and past this in.
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>


text:
Q: Recall Twise UiSwitch action code When i execute the code '[switchOutlet setOn:NO animated:NO]' in UiSwitch Action method, it will recall that method again.
I want to block the user to click the switch button, it will accessed only by the admin.

A: If you want the user can not interact with the UISwitch you can deactivate it with the command
 [switchOutlet setUserInteractionEnabled:NO];


text:
Q: Convert date to unix time stamp in c++ As some websites that convert those unix time stamps say, the stamp of
2013/05/07 05:01:00 (yyyy/mm/dd, hh:mm:ss) is 1367902860.

The way I do it in C++, the stamp differs from the date.
Here is the code:
time_t rawtime;
struct tm * timeinfo;

int year=2013, month=5, day=7, hour = 5, min = 1, sec = 0;

/* get current timeinfo: */
time ( &rawtime ); //or: rawtime = time(0);
/* convert to struct: */
timeinfo = localtime ( &rawtime );

/* now modify the timeinfo to the given date: */
timeinfo->tm_year   = year - 1900;
timeinfo->tm_mon    = month - 1;    //months since January - [0,11]
timeinfo->tm_mday   = day;          //day of the month - [1,31]
timeinfo->tm_hour   = hour;         //hours since midnight - [0,23]
timeinfo->tm_min    = min;          //minutes after the hour - [0,59]
timeinfo->tm_sec    = sec;          //seconds after the minute - [0,59]

/* call mktime: create unix time stamp from timeinfo struct */
date = mktime ( timeinfo );

printf ("Until the given date, since 1970/01/01 %i seconds have passed.\n", date);

The resulting time stamp is
1367899260, but not 1367902860.

What is the problem here? Even if I change to hour-1 or hour+1, it does not match. EDIT: Well yes if i add 1 to hour, it works. previously also added 1 to minutes.

A: You must use timegm() instead of mktime(), and that's all. Because mktime is for localtime and timegm for UTC/GMT time.
Converting Between Local Times and GMT/UTC in C/C++

A: Do you have daylight saving time when you are from? The tm::tm_isdst parameter is a flag for daylight saving time. This will get filled by the localtime call based on where you are and the time of year and you do not reset it. So even if both you and the web page are using the same time, if you have the daylight saving flag set and the web page doesn't then you will end up different by 1 hour.
Note you don't really need the localtime call. You can just fill in all the parts manually because tm::tm_wday and tm::tm_yday are ignored by mktime. Check out http://www.cplusplus.com/reference/ctime/tm/ and http://www.cplusplus.com/reference/ctime/mktime/

A: mktime() converts local calendar time to a time since epoch as a time_t object, so your result will be different from the website's if you are in a different time-zone.  The website takes 2013/05/07 05:01:00 as a UTC time.  The same code on my machine has a result of 1367874060, which is 8 hour away from the website's value.  I'm in UTC+8:00 time-zone, so mktime() on my machine takes the input 2013/05/07 05:01:00 as a UTC+8:00 time, thus causing the difference.
PS: localtime() returns a pointer to a static internal struct tm object. The structure may be shared between gmtime(), localtime(), and ctime(), and may be overwritten on each invocation.  So it's a better practice to have your own local copy of a struct tm object.

A: Don't use a pointer to localtime.  Save the actual value
struct tm timeinfo;
...
timeinfo = *localtime(&rawtime);
...
date = mktime(&timeinfo);

You don't know what else may be using the pointer that localtime is returning.  mktime might possibly be using it.

A: It looks like the website is assuming the time is in the UTC timezone, and your computer is set to some other timezone.
You can call gmtime rather than localtime to use UTC for that; but I've just noticed that you're not actually using localtime to do anything except get a pointer to a tm. You'd be better off declaring a local tm; the one used by localtime could be reused whenever you call another time library function.
Unfortunately, there's no standard variation of mktime using UTC. If you want UTC, your options are:

*

*Set the timezone using setenv("TZ", "", 1);. Note that this affects the whole program, so can be awkward if you also need to deal with local time.

*Use a library like Boost.DateTime, which is slightly better at handling dates and timezones than the C library.