text:
Q: What happens at the user/OS level when an SSD finally wears out? I have been reading up on SSD technology current as of 2011 and don't know of any first hand reports on what happens when an SSD eventually fails due to over use. I am most interested in the SSD that apple includes as a factory option - but aftermarket information is certainly welcome.
If there are no overt signs of aging and wear, might it be possible to measure how much extra storage space remains to cover for failures and wear leveling? (assuming the SSD controller will pool memory and avoid bad/overused blocks before failure)
I am somewhat familiar with failure modes of hard drive storage but looking for similarities or differences between HDD and SSD. For example, the OS can detect (presumably using fsck and journaling) problems writing new data reliably to a HDD and warns you the drive is now mounted in read only mode. Tools like Drive Genius allow all sorts of testing specific to HDD but I'm unaware of tools that dig into SSD for whatever data may be available.
Rather than guessing or predicting how long an SSD will last, are there objective measures we can take to document how storage is aging and check in on wear leveling statistics to measure what happens when SSD are close to the end of their useful lives?

A:
"Does it just get slower and slower
  running garbage collection more and
  more often trying to find a place to
  store data as the flash storage system
  degrades?"

^^ This is what I've seen on two occasions (Aftermarkets tho, possibly the same in Apple drives).
They didn't entirely stop working because I eventually replaced them, since things become like a Windows XP after three years of use and no maintenance.
Another SSD I remember failing did it probably from day three, when it failed to mount on a few occasions. Then it failed to mount again later the same day until it eventually never mounted again. It was under warranty and I replaced it.
The SSDs I still have (non Apple) don't show signs of shrink, probably because the space you lose is not a lot compared to the size of the drive. I'm guessing that would be the case.
Although drives tend to live 2-3 years (SSDs), I'd say be prepared for a -possible- change after 1 year.

A: My aftermarket Intel SSD had a bad sector, which was reported by Disk Utility.  From my understanding, the SSD will get slower and eventually have more bad sectors, which will be noticed if you do a Disk Utility scan.
Warnings because of SMART-data reporting more disk errors than acceptable aren't build into the OS, as far as I know. Disk Utility does show SMART errors, but not in much detail. Tools like SMARTReporter will give you warnings when your SSD is degrading.

A: After 4 years of abusing all manner of Apple selected SSD, I can conclusively say that the drives I have used are more reliable than HDD and have exhibited none of the potential drawbacks or cost associated with HDD failure modes in practice.
For the first few computers I purchased, I did pay for AppleCare for several reasons.

*

*I had decent discounts on it

*I figured I would probably push the SSD harder than the average user and I was happy placing the risk and responsibility on Apple to repair my Mac should I choose to use it too much.

*I wasn't confident that third party SSD repair parts would be viable

The last two years, I have not gotten AppleCare and still am very happy with SSD. My macs run the following programs routinely and exercise the storage to the 80% full level:

*

*iTunes match and now music constantly adds offline songs and removes them as I fill up the drive

*I use local snapshots for Time Machine which also keeps all manner of file around until I reach a low storage point and backup files get purged programmatically by the OS

*Splunk - ingesting and storing system logs from multiple macs - this tool is high IO

*LAMP/MEAN stack running pretty much constantly

*Xcode - moderate use

*Virtual Machines - moderate use

I haven't yet had a failure, so my results are that the SSD are over engineered and other components will fail before the drive. Of course some people will see failures, but that those are both rare and less than the HDD failures people had to deal with in the past.
My advice would be to not place any extra thought on SSD durability for OS X/Mac hardware and just size your computer for your storage size needs and your speed requirements. If you get AppleCare and 3 years of Apple backing the drive, great. If you don't and then have to pay for a repair or pay for a third party SSD replacement, great too.


text:
Q: How do I re-run my Meteor publication to refresh the contents of a collection on the client? I'm creating a quiz app. I want to show a single random question, take the user's answer, show feedback, and move to another random question.
I'm using this to publish a single random question:
getRandomInt = function(min, max) {
  return Math.floor(Math.random() * (max - min + 1) + min);
};

randomizedQuestion = function(rand) {
  // These variables ensure the initial path (greater or less than) is also randomized
  var greater = {$gte: rand};
  var less = {$lte: rand};
  var randomBool = !!getRandomInt(0,1);
  var randomQuestion = Questions.find({randomizer: randomBool ? greater : less }, {fields: {body: true, answers: true}, limit: 1, sort: {randomizer: 1}});

  //  If the first attempt to find a random question fails, we'll go the other direction.
  if (randomQuestion.count()) {
    return randomQuestion;
  } else {
    return Questions.find({randomizer: randomBool ? less : greater}, {fields: {body: true, answers: true}, limit: 1, sort: {randomizer: 1}});
  }
};

Meteor.publish("question", function(rand) {
  if (rand) {
    return randomizedQuestion(rand);
  }
});

I have a route that subscribes to that publication:
Router.route("/", {
  name:"quiz",
  template:"question",
  subscriptions: function() {
    this.questionSub = Meteor.subscribe("question", Math.random());
  },
  data: function() {
    return {
      question: Questions.find(),
      ready: this.questionSub.ready
      };
  }
});

How can I re-run the query with a new value for Math.random() in order to get another random question after the user answers the question?

A: If you replace Math.random() with a reactive variable, that will cause your subscription to be reevaluated. For simplicity I'll use a session variable in this example.
Somewhere before the route runs (at the top of the file or in a before hook), initialize the variable:
  Session.setDefault('randomValue', Math.random());

Then change your subscription to use it:
  Meteor.subscribe('question', Session.get('randomValue'));

Finally, whenever you want to restart the subscription and update your data context, change the variable again:
  Session.set('randomValue', Math.random());

Note you may want question: Questions.findOne() instead of question: Questions.find() assuming your template needs a document instead of a cursor.

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to get message of catch-all exception If I want to write useful info to a file whenever i caught a catch-all exception, how to do it?
try
{
   //call dll from other company
}
catch(...)
{
   //how to write info to file here???????
}

A: You can't get any information out of the ... catch block. That is why code usually handles exceptions like this:
try
{
    // do stuff that may throw or fail
}
catch(const std::runtime_error& re)
{
    // speciffic handling for runtime_error
    std::cerr << "Runtime error: " << re.what() << std::endl;
}
catch(const std::exception& ex)
{
    // speciffic handling for all exceptions extending std::exception, except
    // std::runtime_error which is handled explicitly
    std::cerr << "Error occurred: " << ex.what() << std::endl;
}
catch(...)
{
    // catch any other errors (that we have no information about)
    std::cerr << "Unknown failure occurred. Possible memory corruption" << std::endl;
}

A: There's no way to know anything about the specific exception in a catch-all handler.  It's best if you can catch on a base class exception, such as std::exception, if at all possible.

A: You can't get any details. The whole point of catch(...) is to have such "I don't know what can happen, so catch whatever is thrown". You usually place catch(...) after catch'es for known exception types.

A: A caught exception is accessible by the function std::current_exception(), which is defined in <exception>.  This was introduced in C++11.
std::exception_ptr current_exception();

However, std::exception_ptr is an implementation-defined type, so you can't get to the details anyway.  typeid(current_exception()).name() tells you exception_ptr, not the contained exception.  So about the only thing you can do with it is std::rethrow_exception().  (This functions seems to be there to standardize catch-pass-and-rethrow across threads.)

A: I think he wants to make it log that an error occurred, but doesn't specifically need the exact error (he would write his own error text in that case).
The link DumbCoder posted above has at tutorial that will help you get what you're trying to achieve.


text:
Q: Select numeric string with dots and colon I have this string
string <- "Hospitalization from 25.1.2018 to 26.1.2018", "Date of hospitalization was from 28.8.2019 8:15", "Date of arrival 30.6.2018 20:30 to hospital")

And I would like to get on the numeric part of string (with dots and colons) to have this
print(dates)

    c("25.1.2018", "26.1.2018", "28.8.2019 8:15", "30.6.2018 20:30")

I have tried
dates <- gsub("([0-9]+).*$", "\\1", string)

But it gives me just first number before first dot

A: You can use
library(stringr)
unlist(str_extract_all(string, "\\d{1,2}\\.\\d{1,2}\\.\\d{4}(?:\\s+\\d{1,2}:\\d{1,2})?"))
# => [1] "25.1.2018"       "26.1.2018"       "28.8.2019 8:15"  "30.6.2018 20:30"

See the regex demo.
Details

*

*\d{1,2} - one or two digits

*\. - a dot

*\d{1,2}\.\d{4} - one or two digits, a dot and four digits

*(?:\s+\d{1,2}:\d{1,2})? - an optional occurrence of

*

*\s+ - one or more whitespaces

*\d{1,2}:\d{1,2} - one or two digits, : and one or two digits.

A: Use sapply:
sapply(str_extract_all(string, "[0-9.:]+"), paste0, collapse = " ")
[1] "25.1.2018 26.1.2018" "28.8.2019 8:15"      "30.6.2018 20:30"


text:
Q: How to make the number of ordered list disappear if there is no text I have an ordered list like this :

Then , in my js file , i use jquery to append the information to corresponding element. For example , for the 1st element :
$.getJSON(link, function (details) {
        $(/* somedata get from json*/).appendTo(".1st-assignee");
    });

The same for the other 4 elements with different json link.
However , my problem is there is some link , they return null ( no data or link may expired ) --> There is no text to append to that element. But in this case , the number order still there. Look like this for example :
1.Jane
2.Jake
3.
4.Josh
5.

Is there anyway to remove the number if there is no text . so that i can become :
1.Jane
2.Jake
3.Josh

Update : thanks for your guys advice , however , one problem is i use json to get data and it takes quite long time , therefore , it will delete all the list element before it append

A: You use each() method and check if any li element is empty:

$("#second > li").each(function(){
    if($(this).is(':empty')){
        $(this).remove()
    }
});

Jane

Jake

Josh

Jane

Jake

Josh

A: Use :empty()

Description: Select all elements that have no children (including text nodes).

$('.top-assignee li:empty').hide()

1

2

3

1

2

3

A: You can set display property of list elements li to none if the data is not available.
The ordered list will render the correct order itself.
See the example below.

// Sample Data
var data = ['Jane','Jake','','Josh',''];
// Capture all the list elements in an array
var li = $('.top-assignee li');
// Iterate the data
data.forEach((d, i) => {
  if(d) { // Check if data is non-empty
    li[i].innerHTML = d; // Update the list
  } else {
    li[i].style.display = 'none'; // Hide the element if no data.
  }
});

A: thanks for your advices , i realize i can do it using jquery getJSON success and error handle . Ill post here for someone who needs
 $.getJSON(link).then(function (details) {
        $("some text")
            .appendTo(".5th-assignee");
        console.log("Fifth success");
        $('.5th-assignee').show();
    },function(){
        console.log("Fifth fail");
        $('.5th-assignee').hide();
    });


text:
Q: Defining type of optional generic closure parameter I want to create an interface, that can be invoked with a generic and a non generic parameter used in the Result type.
The API would look like the following:
struct NonGenericParameter {}

func taskPreparation<T: Decodable>(onTypedComplete: ((Result<T, Error>) -> Void)?,
                                   onTyplessComplete: ((Result<NonGenericParameter, Error>) -> Void)?) {
    // Do the neccessery preparation...

    if let onComplete = onTypedComplete {
        task(onComplete: onComplete)
    }

    if let onComplete = onTyplessComplete {
        task(onComplete: onComplete)
    }
}

func task<T: Decodable>(onComplete: @escaping (Result<T, Error>) -> Void) {
    // do task...
}

func task(onComplete: @escaping (Result<NonGenericParameter, Error>) -> Void) {
    // do task...
}

However, when i try to invoke the taskPreparation API, specifying onTyplessComplete as nil
taskPreparation(onTypedComplete: nil,
                onTyplessComplete: { result in // Do something ... })

I receive the error

Generic parameter 'T' could not be inferred.

I understand, i have to specify the type of the generic parameter. I have tried to create a dummy decodable parameter, and pass it to the closure.
struct DummyDecodable: Decodable {}
taskPreparation(onTypedComplete: { (result: Result<DummyDecodable, Error>) in },
                onTyplessComplete: { result in // Do something ... })

But obviously, in this case the onTypedComplete closure is not nil.
Does someone have an idea how could I specify a nil closure and satisfy the type inference too?

A: You would still need the DummyDecodable for this, which is kind of ugly, but at least you are passing a nil value:
Simply pass ((Result<DummyDecodable, Error>) -> Void)?.none. nil is in fact just a syntactic sugar for Optional<WhateverType>.none.
struct DummyDecodable: Decodable {}
taskPreparation(onTypedComplete: ((Result<DummyDecodable, Error>) -> Void)?.none,
                onTyplessComplete: { result in /* Do something ...*/ })


text:
Q: Copy files to usb problem I'm using Ubuntu 14.04 and when i copy files to a USB stick ( format Fat32) the files do get copied onto the USB ok and can be accessed while its plugged into my Ubuntu laptop.
but its when I try to use the USB Stick on other computers, windows or Mac the            files ( which are compatible on all OS systems )  cannot be view, used or the USB stick appears to be empty. except when I plug it back into my Ubuntu laptop the files are there and works. i have also tried other USB Sticks and ext hard drives i still have the same problem. Any help would be great, i really don't want to go back to using Windows.

A: I had a same problem, or clearly Ubuntu still has this problem that copy dialog is finished and is closeed until without completing copy process. If you see blink LED on your USB flash, it is blinking already, it means still copy not finished but unfortunately copy dialog closed before. I think it's a big bug on Ubuntu.
My solution is : wait for blink LED until it turn off that means copy is finished.
Alternatively run sync in terminal and wait until it's completed. After that, use "Eject" or "Unmount" and remove the USB Flash.


text:
Q: receive specific amount of data from gen_tcp socket I have the following code using a gen_tcp socket, which should receive using {active, true} some binary commands that are always of size 5 (e.g. Command =  <<"hello">>)
{ok, ListenSocket} = gen_tcp:listen(5555,  [{active, true}, {mode, binary},
                                            {packet, 0}]),
{ok, Socket} = gen_tcp:accept(ListenSocket),
loop().

receive() ->
    {tcp, _Socket, Message:4/binary} ->
         io:format("Success~n", []),
         loop();
    {tcp, _Socket, Other} ->
         io:format("Received: ~p~n", [Other]),
         loop()
end.

But if I try to connect as a client like this:
1> {ok, S} = gen_tcp:connect("localhost", 5555, []).
   {ok,#Port<0.582>}
2> gen_tcp:send(S, <<"hello">>).
ok

I have in the receiving part:
Received: {tcp,#Port<0.585>,<<"hello">>}

so I suppose my error is in the pattern matching...but where?

A: Your receive clause doesn't look right, it should be:
{tcp, _Socket, <<Message:5/binary>>} ->
  ....

A: As far as I understood you need gen_tcp:recv function. From documentation:
recv(Socket, Length) -> {ok, Packet} | {error, Reason}

In your code it will be something like:
...
{ok, Socket} = gen_tcp:accept(ListenSocket),
loop(Socket).

loop(Socket) ->
    case gen_tcp:recv(Socket, 5) of
        {ok, Data} ->
            io:format("Success~n", []),
            loop(Socket);
        {error, closed} ->
            ok
end.


text:
Q: Firefox can't access internet in Ubuntu 10.04 I installed Ubuntu 10.04. Firefox will not access the internet. It works fine in 10.04.
This happens every time Firefox opens. Do I have to update the kernel, is there another way?

A: No you don't have to update the Linux kernel.
You have to identify the cause of the problem, typically this involves looking for error messages and describing the exact symptoms.
There are diagnostic tools you can use in a command-prompt window. For example.
  sudo ifconfig
  netstat -nr
  host www.google.com
  ping www.google.com
  traceroute www.google.com
  wget www.google.com

You may need to install traceroute using
  sudo apt-get install traceroute

Here's relevant extractts of what those commands produce on a working system
$ sudo ifconfig
eth0      Link encap:Ethernet  HWaddr 00:ff:19:60:1a:00
          inet addr:10.0.2.15  Bcast:10.0.2.255  Mask:255.255.255.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1

$ netstat -nr
Kernel IP routing table
Destination     Gateway         Genmask         Flags   MSS Window  irtt Iface
10.0.2.0        0.0.0.0         255.255.255.0   U         0 0          0 eth0
0.0.0.0         10.0.2.2        0.0.0.0         UG        0 0          0 eth0

$ host www.google.com
www.google.com is an alias for www.l.google.com.
www.l.google.com has address 173.194.66.99
www.l.google.com has address 173.194.66.105
www.l.google.com has address 173.194.66.104
www.l.google.com has address 173.194.66.106
www.l.google.com has address 173.194.66.103
www.l.google.com has address 173.194.66.147

$ ping -c 5 www.google.com
PING www.l.google.com (173.194.66.147) 56(84) bytes of data.

--- www.l.google.com ping statistics ---
5 packets transmitted, 0 received, 100% packet loss, time 4000ms

Oops - OK Google block ping, that's OK
$ wget www.google.com
--2012-05-18 15:59:51--  http://www.google.com/
Resolving www.google.com... 173.194.66.105, 173.194.66.104, 173.194.66.106, ...
Connecting to www.google.com|173.194.66.105|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: unspecified [text/html]
Saving to: `index.html'

    [ <=>                                   ] 12,013      --.-K/s   in 0.02s

2012-05-18 15:59:52 (587 KB/s) - `index.html' saved [12013]


text:
Q: How to keep h2 tag centered while using bounceInDown class? Basically I have an h2 tag that is centered but whenever I add the bounceInDown class from animate.css it makes the text in h2 not centered. I need the text in the h2 tag to stay centered while still having the bounceInDown class in use.
example of what it should look like:

body {
  font-family: "Source Sans Pro", sans-serif;
  color: #ccc;
  z-index: -100;
  background-color: black;
  overflow: hidden;
  text-align: center;
}

h2 {
  display: inline-flex;
  color: aquamarine;
  font-family: Raleway;
  opacity: .86;
  font-size: 3em;
  flex-direction: column;
  align-items: center;
  margin: 0;
  position: absolute;
  margin-top: 7%;
}

h2>span {
  margin-left: auto;
  font-size: .4em;
  margin-top: -.4em;
}

@-webkit-keyframes bounceIn {
  from, 20%, 40%, 60%, 80%, to {
    -webkit-animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
    animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
  }

  0% {
    opacity: 0;
    -webkit-transform: scale3d(.3, .3, .3);
    transform: scale3d(.3, .3, .3);
  }

  20% {
    -webkit-transform: scale3d(1.1, 1.1, 1.1);
    transform: scale3d(1.1, 1.1, 1.1);
  }

  40% {
    -webkit-transform: scale3d(.9, .9, .9);
    transform: scale3d(.9, .9, .9);
  }

  60% {
    opacity: 1;
    -webkit-transform: scale3d(1.03, 1.03, 1.03);
    transform: scale3d(1.03, 1.03, 1.03);
  }

  80% {
    -webkit-transform: scale3d(.97, .97, .97);
    transform: scale3d(.97, .97, .97);
  }

  to {
    opacity: 1;
    -webkit-transform: scale3d(1, 1, 1);
    transform: scale3d(1, 1, 1);
  }
}

@keyframes bounceIn {
  from, 20%, 40%, 60%, 80%, to {
    -webkit-animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
    animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
  }

  0% {
    opacity: 0;
    -webkit-transform: scale3d(.3, .3, .3);
    transform: scale3d(.3, .3, .3);
  }

  20% {
    -webkit-transform: scale3d(1.1, 1.1, 1.1);
    transform: scale3d(1.1, 1.1, 1.1);
  }

  40% {
    -webkit-transform: scale3d(.9, .9, .9);
    transform: scale3d(.9, .9, .9);
  }

  60% {
    opacity: 1;
    -webkit-transform: scale3d(1.03, 1.03, 1.03);
    transform: scale3d(1.03, 1.03, 1.03);
  }

  80% {
    -webkit-transform: scale3d(.97, .97, .97);
    transform: scale3d(.97, .97, .97);
  }

  to {
    opacity: 1;
    -webkit-transform: scale3d(1, 1, 1);
    transform: scale3d(1, 1, 1);
  }
}

.bounceIn {
  -webkit-animation-name: bounceIn;
  animation-name: bounceIn;
}

@-webkit-keyframes bounceInDown {
  from, 60%, 75%, 90%, to {
    -webkit-animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
    animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
  }

  0% {
    opacity: 0;
    -webkit-transform: translate3d(0, -3000px, 0);
    transform: translate3d(0, -3000px, 0);
  }

  60% {
    opacity: 1;
    -webkit-transform: translate3d(0, 25px, 0);
    transform: translate3d(0, 25px, 0);
  }

  75% {
    -webkit-transform: translate3d(0, -10px, 0);
    transform: translate3d(0, -10px, 0);
  }

  90% {
    -webkit-transform: translate3d(0, 5px, 0);
    transform: translate3d(0, 5px, 0);
  }

  to {
    -webkit-transform: none;
    transform: none;
  }
}

@keyframes bounceInDown {
  from, 60%, 75%, 90%, to {
    -webkit-animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
    animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
  }

  0% {
    opacity: 0;
    -webkit-transform: translate3d(0, -3000px, 0);
    transform: translate3d(0, -3000px, 0);
  }

  60% {
    opacity: 1;
    -webkit-transform: translate3d(0, 25px, 0);
    transform: translate3d(0, 25px, 0);
  }

  75% {
    -webkit-transform: translate3d(0, -10px, 0);
    transform: translate3d(0, -10px, 0);
  }

  90% {
    -webkit-transform: translate3d(0, 5px, 0);
    transform: translate3d(0, 5px, 0);
  }

  to {
    -webkit-transform: none;
    transform: none;
  }
}

.bounceInDown {
  -webkit-animation-name: bounceInDown;
  animation-name: bounceInDown;
}

  Al-Saba.net

A: Add left: 50%; transform: translateX(-50%);

body {
  font-family: "Source Sans Pro", sans-serif;
  color: #ccc;
  z-index: -100;
  background-color: black;
  overflow: hidden;
  text-align: center;
}

h2 {
  display: inline-flex;
  color: aquamarine;
  font-family: Raleway;
  opacity: .86;
  font-size: 3em;
  flex-direction: column;
  align-items: center;
  margin: 0;
  position: absolute;
  margin-top: 7%;
  left: 50%;
  transform: translateX(-50%);
}

h2>span {
  margin-left: auto;
  font-size: .4em;
  margin-top: -.4em;
}

@-webkit-keyframes bounceIn {
  from, 20%, 40%, 60%, 80%, to {
    -webkit-animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
    animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
  }

  0% {
    opacity: 0;
    -webkit-transform: scale3d(.3, .3, .3);
    transform: scale3d(.3, .3, .3);
  }

  20% {
    -webkit-transform: scale3d(1.1, 1.1, 1.1);
    transform: scale3d(1.1, 1.1, 1.1);
  }

  40% {
    -webkit-transform: scale3d(.9, .9, .9);
    transform: scale3d(.9, .9, .9);
  }

  60% {
    opacity: 1;
    -webkit-transform: scale3d(1.03, 1.03, 1.03);
    transform: scale3d(1.03, 1.03, 1.03);
  }

  80% {
    -webkit-transform: scale3d(.97, .97, .97);
    transform: scale3d(.97, .97, .97);
  }

  to {
    opacity: 1;
    -webkit-transform: scale3d(1, 1, 1);
    transform: scale3d(1, 1, 1);
  }
}

@keyframes bounceIn {
  from, 20%, 40%, 60%, 80%, to {
    -webkit-animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
    animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
  }

  0% {
    opacity: 0;
    -webkit-transform: scale3d(.3, .3, .3);
    transform: scale3d(.3, .3, .3);
  }

  20% {
    -webkit-transform: scale3d(1.1, 1.1, 1.1);
    transform: scale3d(1.1, 1.1, 1.1);
  }

  40% {
    -webkit-transform: scale3d(.9, .9, .9);
    transform: scale3d(.9, .9, .9);
  }

  60% {
    opacity: 1;
    -webkit-transform: scale3d(1.03, 1.03, 1.03);
    transform: scale3d(1.03, 1.03, 1.03);
  }

  80% {
    -webkit-transform: scale3d(.97, .97, .97);
    transform: scale3d(.97, .97, .97);
  }

  to {
    opacity: 1;
    -webkit-transform: scale3d(1, 1, 1);
    transform: scale3d(1, 1, 1);
  }
}

.bounceIn {
  -webkit-animation-name: bounceIn;
  animation-name: bounceIn;
}

@-webkit-keyframes bounceInDown {
  from, 60%, 75%, 90%, to {
    -webkit-animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
    animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
  }

  0% {
    opacity: 0;
    -webkit-transform: translate3d(0, -3000px, 0);
    transform: translate3d(0, -3000px, 0);
  }

  60% {
    opacity: 1;
    -webkit-transform: translate3d(0, 25px, 0);
    transform: translate3d(0, 25px, 0);
  }

  75% {
    -webkit-transform: translate3d(0, -10px, 0);
    transform: translate3d(0, -10px, 0);
  }

  90% {
    -webkit-transform: translate3d(0, 5px, 0);
    transform: translate3d(0, 5px, 0);
  }

  to {
    -webkit-transform: none;
    transform: none;
  }
}

@keyframes bounceInDown {
  from, 60%, 75%, 90%, to {
    -webkit-animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
    animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
  }

  0% {
    opacity: 0;
    -webkit-transform: translate3d(0, -3000px, 0);
    transform: translate3d(0, -3000px, 0);
  }

  60% {
    opacity: 1;
    -webkit-transform: translate3d(0, 25px, 0);
    transform: translate3d(0, 25px, 0);
  }

  75% {
    -webkit-transform: translate3d(0, -10px, 0);
    transform: translate3d(0, -10px, 0);
  }

  90% {
    -webkit-transform: translate3d(0, 5px, 0);
    transform: translate3d(0, 5px, 0);
  }

  to {
    -webkit-transform: none;
    transform: none;
  }
}

.bounceInDown {
  -webkit-animation-name: bounceInDown;
  animation-name: bounceInDown;
}

  Al-Saba.net


text:
Q: how to use two dimensional array concept for retrieving the data from the selected rectangle in javascript I want to retrieve the data from the selected rectangle.I am having number of rectangles.If i am selecting the particular rectangle that data of the particular rectangle will be shown.I have stored the data of the rectangles in one array collection.But i dont know how to retrieve the data.Because if i am removing the one rectangle among 3 rectangles array collection indices changed.
For example,I am having two rectangles.data of the rectangles stored in one array collection.
Like this.
this.model.rectCollection[this.rectIndex]=this.model.selectedData;

here rectIndex changed for every rectangle.
My problem is, i am removing first rectangle using this code.
if(this.rectRemovedIndex>-1){
this.model.rectCollection.splice(this.rectRemovedIndex,1);
}

now rectcollection indices changed.data of the second rectangle stored in rectCollection[0].
I want to drag the second rectangle means,that corresponding rectIndex is 1.
so that selected data push into rectCollection[1].Index added for second one.but the rectCollection[0] only modified for the second one also.
if (this.dragdrop || this.rectPan) {
                this.model.rectCollection[this.rectIndex] = 0;
               this.model.rectCollection[this.rectIndex] = this.model.selectedData;
        }

here,the rectIndex should be 1.so data changed.
how to do.


text:
Q: Insert Meta tag into web page A while ago I designed a app that would insert a meta tag into my pages so I could test them with internet explorer in different document modes. My solution, though functional, was klugy. Assuming IIS7 and explorer as server/client, what are some light weight solutions for quickly adding a meta tag programmaticly for a short time.

A: You can do that very easily using URL Rewrite and leverage the Outbound Rewrite capabilities. Once it is installed just add a web.config to the application folder like the following and it will automatically insert a META tag to every HTML page that is served by the application. You can obviously add more conditions and make that only rewrite for pages you want (see preConditions) as well as capture data from headers or other places and add it in the response.
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <outboundRules rewriteBeforeCache="true">
                <rule name="WriteMETA" preCondition="MatchHTML">
                    <match pattern="<head>" occurrences="1" />
                    <action type="Rewrite" value="<head>

                        <meta name='author' content='Carlos Aguilar Mares' />
                        " />
                </rule>
                <preConditions>
                    <preCondition name="MatchHTML" patternSyntax="Wildcard">
                        <add input="{RESPONSE_CONTENT_TYPE}" pattern="text/html" />
                    </preCondition>
                </preConditions>
            </outboundRules>
        </rewrite>
    </system.webServer>
</configuration>


text:
Q: MYSQL search if a string contains special characters? I need to search table field contains special characters. I found a solution given here something like:
SELECT *
FROM `tableName`
WHERE `columnName` LIKE "%#%"
OR `columnName` LIKE "%$%"
OR (etc.)

But this solution is too broad. I need to mention all the special characters. But I want something which search something like:
SELECT *
FROM `tableName`
WHERE `columnName` LIKE '%[^a-zA-Z0-9]%'

That is search column which contains not only a-z, A-Z and 0-9 but some other characters also. Is it possible with MYSQL

A: Use regexp
SELECT *
FROM `tableName`
WHERE `columnName` REGEXP '[^a-zA-Z0-9]'

This would select all the rows where the particular column contain atleast one non-alphanumeric character.
or
REGEXP '[^[:alnum:]]'


text:
Q: drupal 7 Query database and display results after form submit in custom module function mymodule_search_form($form, &$form_state) {

  $form..... define the form here

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Search',
  );

  return $form;
}

function mymodule_search_form_submit($form, &$form_state) {

  //process the form and get result
  $output = this is the result with a table of data.
  //I want to display the result table here.

 //Now I can only use drupal message to display on top.
 drupal_set_message($output);

  return;
}

So basically I want to have a form to search something from database.
Once click the submit to search, and get the result.
I want to display the result just under the form in the same form page.
Do not go to another page, just in the original form page.
The form can be clean/reset into original status, which is fine.
http://drupal.org/node/542646
This discussion is what I want, but there looks no solid result/solution there.

A: You can stash the output table in the $form_state, set the form to rebuild, and display it if it exists in the original form function, e.g.
function mymodule_search_form($form, &$form_state) {

  $form..... define the form here

  if (!empty($form_state['results_table'])) {
    $form['results_table'] = array('#markup' => $form_state['results_table']);
  }

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Search',
  );

  return $form;
}

function mymodule_search_form_submit($form, &$form_state) {
  $form_state['results_table'] = function_to_get_table();
  $form_state['rebuild'] = TRUE;
}


text:
Q: Modifying empty matrix given matrix of positions and vector of values Given the following setup:
> vals = matrix(nrow = 3,ncol = 4)
     [,1] [,2] [,3] [,4]
[1,]   NA   NA   NA   NA
[2,]   NA   NA   NA   NA
[3,]   NA   NA   NA   NA

> position =  matrix(c(4,2,1, 6,3,2, NA,NA,3, NA,NA,4), nrow = 3, ncol = 4)
     [,1] [,2] [,3] [,4]
[1,]    1    4   NA   NA
[2,]    2    3   NA   NA
[3,]    1    2    3    4

> temp = c(10, 5, 8, 6, 9, 2, 4, 3)

I'm trying to populate vals with the values held in temp. However, the values must be placed in the spots given by position. Specifically, each row in position represents a row in vals, and the values represent the column in which the value must be placed.
For example, position[2,2] = 3. Since that's position's second row, the respective value must go into vals[2,3]. The final result would be:
     [,1] [,2] [,3] [,4]
[1,]   10   NA   NA    5
[2,]   NA    8    6   NA
[3,]    9    2    4    3

This would be straightforward with for-loops, but can it be done without them?

A: We can use a row/column indexing by cbinding the row index (created with row, c -> convert the numeric index matrix to vector), with the column index by transposing the 'position', coerce it to vector (c), remove the NA elements (na.omit), extract the elements in 'vals' based on the indexes and assign (<-) to 'temp'
vals[na.omit(cbind(c(t(row(position))), c(t(position))))] <- temp
vals
#     [,1] [,2] [,3] [,4]
#[1,]   10   NA   NA    5
#[2,]   NA    8    6   NA
#[3,]    9    2    4    3

data
position <- structure(c(1, 2, 1, 4, 3, 2, NA, NA, 3, NA, NA, 4), .Dim = 3:4)


text:
Q: How To Change Login & Register View in Laravel I'm new to Laravel, so here I want to make a view for login and register, and then I change the default view login and register into my own view, I changed it in the route and then it work, and then I try to run this code: php artisan ui:auth and then my login view before, it changes to the default view of Laravel. How to change it again into my login and view design ? Thank you.
This is my route web.php:
<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('pages/home');
});

Route::get('/register','Auth\AuthController@register');
Route::post('/register','Auth\AuthController@postRegister')->name('register');

Route::get('/login','AuthController@login');
Route::post('/login','AuthController@postLogin')->name('login');

and this is my AuthController
<?php

namespace App\Http\Controllers\Auth;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\User;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Facades\Socialite;

class AuthController extends Controller
{

    public function register()
    {
        return view('login_register/register');
    }

    public function postRegister(Request $request )
    {
        User::create([
            'name'=> $request->nama,
            'email'=> $request->email,
            'password'=> bcrypt($request->password)

        ]);
           return redirect('/login');
    }

    public function login()
    {
        return view('login_register/login');
    }

    public function postLogin(Request $request)
    {
        if(!\Auth::attempt(['email' => $request->email, 'password' => $request->password ])){
            return redirect()->back();
        }

         return redirect('/galangdana/list');
    }

public function redirectToProvider($provider)
    {
        return Socialite::driver($provider)->redirect();
    }

    /**
     * Obtain the user information from provider.  Check if the user already exists in our
     * database by looking up their provider_id in the database.
     * If the user exists, log them in. Otherwise, create a new user then log them in. After that
     * redirect them to the authenticated users homepage.
     *
     * @return Response
     */
    public function handleProviderCallback($provider)
    {
        $user = Socialite::driver($provider)->user();
        $authUser = $this->findOrCreateUser($user, $provider);
        Auth::login($authUser, true);
        return redirect('/');
    }

    /**
     * If a user has registered before using social auth, return the user
     * else, create a new user object.
     * @param  $user Socialite user object
     * @param $provider Social auth provider
     * @return  User
     */
    public function findOrCreateUser($user, $provider)
    {
        $authUser = User::where('provider_id', $user->id)->first();
        if ($authUser) {
            return $authUser;
        }
        else{
            $data = User::create([
                'name'     => $user->name,
                'email'    => !empty($user->email)? $user->email : '' ,
                'provider' => $provider,
                'provider_id' => $user->id
            ]);
            return $data;
        }
    }

}

?>

A: You can override the showLoginForm() method, in you LoginController.php:
public function showLoginForm()
{
    return view('my.view');
}

It overrides the function showLoginForm defined in the trait Illuminate\Foundation\Auth\AuthenticatesUsers.
For registration, you showRegistrationForm method, defined in Illuminate\Foundation\Auth\RegistersUsers trait:
public function showRegistrationForm()
{
    return view('my.register.view');
}

Hope it helps.

A: solved, that becasue i put Auth::routes() so that make multiple login, thank you for the answer


text:
Q: When do we not put a comma before "because"? In what situation do you put a comma before "because"?
And, when do you not put a comma before "because"?
I've always assumed that you put a comma, because the clause introduced by "because" will always be independent, because it cannot stand on its own, because it wouldn't make sense on its own.
Is this the case? Could you think of an example where it doesn't take a comma?

A: The use of a comma before because is best seen with negative statements.

I didn't run because I was afraid. (I ran because I was late.)

Without a comma, this means that you did run, and that you ran for some reason other than fear—as explained in the sentence in parentheses that follows it.

I didn't run, because I was afraid. (I was too scared to run.)

With a comma, this means that you didn't run—and it was fear that prevented you from running.

With positive statements, the comma doesn't change the meaning.

I ran because I was afraid.
  I ran, because I was afraid.

Both of those sentences mean the same thing. However, the comma doesn't do anything syntactically. In terms of a concise statement, the lack of a comma is better.
However, some people may add one for stylistic effect. Although, if writing for stylistic effect (where liberties can be taken with grammar), it would probably be considered more appropriate to use a dash or even break it into a second sentence.

I ran—because I was afraid.
  I ran. Because I was afraid.

Alternatively, a comma can be used if it's a conjunction that immediately follows it rather than because itself:

I ran, but not because I was afraid.
  I ran, but only because I was late.

A: The most common error with commas is to use one for a pause.
For a comprehensive list of rules see
https://www.businessinsider.com/a-guide-to-proper-comma-use-2013-9


text:
Q: Reading JSON in Javascript I am trying to parse some json that my server replies me.
I am getting this answer from the server:
{
"ROWCOUNT": 1,
"COLUMNS": [
    "REGISTRATION_DT",
    "USERNAME",
    "PASSWORD",
    "FNAME",
    "LNAME",
    "EMAIL",
    "MOBILE",
    "FACEBOOK_ID"
],
"DATA": {
    "REGISTRATION_DT": [
        "March, 17 2012 16:18:00"
    ],
    "USERNAME": [
        "user"
    ],
    "PASSWORD": [
        pass
    ],
    "FNAME": [
        "name"
    ],
    "LNAME": [
        "lname"
    ],
    "EMAIL": [
        "somemail"
    ],
    "MOBILE": [
        mobile
    ],
    "FACEBOOK_ID": [
        "fbid"
    ]
}

}
I am trying to extract the data with this way:
var xml2 = this.responseData;
var xml3 = JSON.parse(xml2);
Ti.API.log(xml3.DATA[0].FNAME);

What I am doing wrong here?

A: You're reading your JSON wrong. DATA is an object of arrays and not vica versa.
Ti.API.log( xml3.DATA.FNAME[0] );

A: Ti.API.log(xml3.DATA.FNAME[0]);

A: Two fields come without quotes:
"PASSWORD": [
    pass
]

And
"MOBILE": [
    mobile
],

A: xml3.DATA is an object, not an array.
You need to write
xml3.DATA.FNAME[0]


text:
Q: How can I disable Java EE interceptor on application start up, for example by condition from database logger=info? I use Java EE and WebLogic server. I declare interceptor with annotated style: @Interceptor. I need to add some functionality which would disable certain interceptor. I use annotation to mark methods when Interceptor needs to invoke.

@Inherited
@InterceptorBinding
@Retention(RUNTIME)
@Target({METHOD, TYPE})
public @interface Traced {
}

 @Traced
    @Interceptor
    @Priority(Interceptor.Priority.APPLICATION)
    public class MethodInvocationInterceptor implements Serializable {

        private static final Logger LOG = Logger.getLogger(MethodInvocationInterceptor.class);

        @AroundInvoke
        public Object intercept(final InvocationContext ctx) throws Exception {
          LOG.trace(ctx.getMethod().getName() + " method started");
        return ctx.proceed();
      }

A: There are three reasonable approaches I can think of.
First is same as what @Nikos suggested, keep interceptor enabled at all times and just add conditional logic based on configuration.
Second approach requires CDI extension where you monitor AfterTypeDiscovery event. This allows you to get hold of lists of alternatives, interceptors and decorators. Those lists are mutable and once you change them, container has to take the changes values into consideration. Removing the interceptor should result in interceptor being disabled.
This approach, again with CDI extension, requires you to monitor for the AnnotatedType of interceptor using ProcessAnnotatedType event and disable it using veto() method. Alternatively, if vetoing doesn't cut it, you can alter the AnnotatedType and remove/replace the interceptor binding (although that approach sounds a bit "hacky" as you end with an interceptor without bindings).


text:
Q: Watir click on drop down I'm a newbie to web app automation testing. I'm using watir-webdriver to automate our functional testing with an application.
I would my javascript drop down menu to test with Watir like to know as I do. I just can not get past and every attempt results in an error.
About one tip I would be very grateful

            <form action="/index.php" method="post" class="">
                    <input type="hidden" name="tx_bodpricecalculation_pi1[controller]" value="priceCalc">

                            <input type="hidden" name="tx_bodpricecalculation_pi1[action]" value="calculate">
                            <input type="hidden" name="type" value="54321">

                    <input type="hidden" name="tx_bodpricecalculation_pi1[isEditor]" value="0">

                    <input type="hidden" name="tx_bodpricecalculation_pi1[binding]" id="binding" value="">

                                <select name="tx_bodpricecalculation_pi1[product]" data-required="" id="selFNF" class="chzn-done" style="display: none;">
                                    <option value="" selected="selected" disabled="">ProduktNEU</option>
                                    <option value="FunNEU">FunNEU</option>
                                    <option value="ClassicNEU">ClassicNEU</option>
                                    <option value="ComfortNEU">ComfortNEU</option>
                                </select>
Comfort

<input type="text" autocomplete="off" readonly="">

Produkt

Fun

Classic

Comfort

                                Bitte Ergänzen Sie die Angaben

First Test-Code
    browser.select_list(:class => 'chzn-done').select('Fun')

First Test-Output
    Test Suite
    New Test Case (FAILED - 1)
    Failures:
    1) Test Suite New Test Case
    Failure/Error: browser.select_list(:class => 'chzn-done').select('FunNEU')
    Selenium::WebDriver::Error::ElementNotVisibleError:
    Element is not currently visible and so may not be interacted with
    # [remote server] file:///var/folders/8m/3byyttvd4cxbqx22s60hvb4c0000gn/T/webdriver-                 profile20140212-5829-7ai1pp/extensions/fxdriver@googlecode.com/components/command_processor

Second Test-Code
    browser.select_list(:name => 'tx_bodpricecalculation_pi1[product]').select('Fun')

Second Test-OutputTest Suite
    Test Suite
    New Test Case (FAILED - 1)
    Failures:
    1) Test Suite New Test Case
    Failure/Error: browser.select_list(:name =>         'tx_bodpricecalculation_pi1[product]').select('FunNEU')
    Selenium::WebDriver::Error::ElementNotVisibleError:
    Element is not currently visible and so may not be interacted with
    # [remote server] file:///var/folders/8m/3byyttvd4cxbqx22s60hvb4c0000gn/T/webdriver-        profile20140212-5829-        ry619a/extensions/fxdriver@googlecode.com/components/command_processor.js:8179:in         `fxdriver.preconditions.visible'
    # [remote server] file:///var/folders/8m/3byyttvd4cxbqx22s60hvb4c0000gn/T/webdriver-        profile20140212-5829-ry619a/extensions/fxdriver@googlecode.com/components/command_processor.js:10814:in `DelayedCommand.prototype.checkPreconditions_'

I get the following test simply not go.
=> Click on PRODUKTNEU
=> Select FUNNEU
At the end is to take place, a calculation for the product FUNNEU. Just the part and PRODUKTNEU and FUNNEU makes problems.
About your help I would be very grateful

A: The select list that was given in the sample html has a display style of none. As a result, it is not considered visible.
You actually want to interact with the content that comes after the select list. The "dropdown" is actually a link and the "options" are actual li elements.
The following works against the actual page:
require 'watir-webdriver'

b = Watir::Browser.new
b.goto 'http://www.bod.de/autoren/buch-veroeffentlichen/preiskalkulation.html'

# This is the div containing the "dropdown" you want to work with.
input_field = b.div(:class => 'product')

# Click the link to expand the dropdown
input_field.link(:class => 'chzn-single').click

# Click the related li element
input_field.li(:text => 'Fun').click


text:
Q: Outlook's Local Failures has 750k messages. How can I delete them? I am running Outlook 2016 with an Office365 account. Its Local Failures folder has 750k messages, apparently totalling ~16GB. How can I delete them?
I can't actually view the messages: Outlook says the folder has no contents, despite the blue "2" next to it in the folder list. No idea why it says 2, because the details say the server version has 23, and the local one has over 750k.
I tried the obvious things, such as clicking 'Clear Offline Items' from the folder's details: this makes Outlook crash.
So I looked up some more, and installed mfcmapi and tried to empty the folder. I tried the following while Outlook was not running.

*

*When in the screen "Delete Items and Subfolders" and checking no options, or just the option called 'Delete associated (hidden) items', then mfcmapi crashes.

*If I select 'Hard Deletion', it throws an error.

*If I select "Delete manually", it's (Not Responding) for minutes, and I decide to end the program after a while because to be honest I don't really want to manually delete almost a million messages.

*If I try instead to Delete the whole folder, it throws that same error.

I have considered just removing and reinstalling the whole account, but the whole reason I'm trying to empty the Local Failures folder is because my Inbox refuses to sync with the server.
So anyone have another idea? Gratitude will be your reward!
If anyone asks, this is the error mfcmapi throws:
Error:
Code: MAPI_E_UNKNOWN_FLAGS == 0x80040106
Function lpParentFolder->DeleteFolder( lpItemEID->cb, reinterpret_cast<LPENTRYID>(lpItemEID->lpb), lpProgress ? reinterpret_cast<ULONG_PTR>(m_hWnd) : NULL, lpProgress, ulFlags)
File Dialogs\HierarchyTable\MsgStoreDlg.cpp
Line 891

A: I ended up removing and readding the account, effectively throwing away all local content (such as those Local Failures).
I was avoiding this solution because my local Inbox wasn't synced with the online one. So I moved the 'visible' mails in my local inbox to a new subfolder, because for some reason that one does manage to sync, and then removed and readded the account. Upon restarting (and making sure 'cached mode' is turned off), I just had to refile some mails of the past few months, and I'm up and running again now.


text:
Q: Best practices for modifying foundation CSS framework In implementing foundation.css framework, shall I update the actual foundation.css for my custom needs (font colors, backgrounds, etc) or shall I use a secondary css for my customization so that when foundation.css needs updating I can replace it without losing my customization.
Let me know your thoughts on this strategy. This would be the code the second option above:
<link rel="stylesheet" href="css/foundation.css" media="screen, projection" />
<link rel="stylesheet" href="css/my-custom.css" media="screen, projection" />

Thank you

A: Well I think this is more an opinion request than a real question.
Still, I'd say the answer is, as always in these cases, it depends.
You can certainly override the original stylings with a second css, and I think that's what they suggested on their docs (haven't been using Foundation during the last, I think, 6 months, sorry). It will just work ok, and your future upgrades will be easier to integrate, in case the framework will get some. This is certainly a perfect future-proof approach.
Performance-wise I'd suggest to directly customise that very css. My reasons are:

*

*Less KB: Your css will be lighter = faster to load.

*Less DOM painting: the browser won't have to style elements the Foundation way and then style them again your way.

*Less HTTP requests: the browser will only download one css, saving one extra HTTP request (fater load time)

So, it's really up to you, as you're the only one who knows if the website will need a framework update.
I never had the need of an update when I used Foundation, and I think it's been tested quite a lot that vital updates will hardly be needed.


text:
Q: Flutter Image can't be assigned to parameter type ImageProvider CircleAvatar(
  radius: 30,
  backgroundImage: Image.asset("images/bg.png"),
),

Error:

The argument type 'Image' can't be assigned to the parameter type 'ImageProvider?'. (argument_type_not_assignable at [love_messenger] lib\main.dart:85)

What should ı do??

A: Use
 backgroundImage:AssetImage("images/bg.png") ,

CircleAvatar(
  radius: 30,
  backgroundImage: AssetImage("images/bg.png"),
),

A: You need to use ImageProvider like this:
    CircleAvatar(
                 radius: 30,
                 backgroundImage: AssetImage('images/bg.png')

Or use child property:
    CircleAvatar(
                 radius: 30,
                 child: Image.asset("images/bg.png")

Have a nice time!


text:
Q: Easiest way to embed a piece of Python code in C# (Simpler than IronPython) Basically I want to make a C#.NET application but also create full Python modules that can be called from C#. I was going with IronPython but I found out that I can't add libraries like BeautifulSoup to IronPython.
I guess what I'm looking to do is embed pure python into C# rather than using IronPython which is a limited implementation of Python

A: I recommend against this type of cross-language development. It is possible, but it winds up being hackish, hard to deploy, etc.
Replace your Python libraries with C# libraries, and replace your Python code with C# code. For example, replace BeautifulSoup with Html Agility Pack.


text:
Q: Dual boot Ubuntu 16.04/WIndows 10 with hardware RAID Long story short:
Want dual boot
Using live USB
Installer won't recognize Windows OS as present
Won't list system disk as possible install location
System disk and all partitions shown in GParted
hibernate /off
swap /off
hardware RAID 1 6TB LD (x2 3TB)
400GB unallocated HDD space on system disk
AMD Phenom II X4 3.4GHz
16GB RAM
64-bit Windows 10 OS
ASUS M5A97 R2.0 Motherboard with RAID
Please assist. I've seen a few options but I'm afraid of messing up my RAID configuration in Windows. Not to mention the OS itself.


text:
Q: Multi-threading issue with selenium I currently need to do an automated work, and I want to speed up using threadings
However, the issue is that when I start 2 threads or more, the program will automatically closes until it reached 1 thread.
Any solution to this?.
from time import sleep
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait as wait
from selenium.common.exceptions import TimeoutException
import random
import threading

def ChromeMetamask():
    options = ChromeOptions()
    options.add_extension("metaMaskextension.crx")
    ChromeMetamask.web = webdriver.Chrome(chrome_options=options)
    return ChromeMetamask.web

def StreamTeam():
    ...
    ChromeMetamask.web.quit()

def run(x):
    print("Running thread" ,x)
    sleep(x)
    while True:
        try:
            ChromeMetamask()
            print("Creating wallet of thread" ,x)
            CreateWallet()
            print("Working on thread" ,x)
            StreamTeam()
            print("Thread " + str(x) + " has completed")
        except Exception as e:
            print("Thread " + str(x) + " encounters an error, restarting")
            continue

if __name__ == "__main__":
    thread = int(input("Enter number of threads: "))
    threads = []
    for x in range(1,thread+1):
        threads += [threading.Thread(target = run, args ={x}, )]
    for t in threads:
        t.start()
    for t in threads:
        t.join()


text:
Q: How to map non related JPA entity hi i am using hibernate 5.4.32. i have two JPA entities which does not have any association between them . Is there any way i can get the results in my entity.
Entity 1
@Entity
@Table(name = "XYZ_EC")
public class LoanOrder{
    @Id
    UUID id;

    public List<DDLTable> ddlTables; // select TABLE_NAME, DESCRIPTION, FILTER_TYPE from DDLTable where TABLE_NAME = 'ABC', this is the query i want to be executed .
    //LoanOrder Entity does not have any column to map to DDL entity.

Entity 2
@Table(name = "DDL_TABLE")
@Entity
public class DDLTable implements Serializable {

    @Id
    @Column(name = "TABLE_NAME")
    private String tableName;

    @Id
    @Column(name = "DESCRIPTION")
    private String description;

    @Id
    @Column(name = "FILTER_TYPE")
    private String filterType;
}

A: You could try to use @JoinFormula
@OneToMany
@JoinFormula("TABLE_NAME = 'ABC'")
public List<DDLTable> ddlTables;

Please find more information in the documentation:
https://docs.jboss.org/hibernate/orm/5.5/userguide/html_single/Hibernate_User_Guide.html#associations-JoinFormula

A: Though it is not very correct and clean what you are trying to achieve (it would be better to use a third class, a DTO to hold all the data you want from both Entities), you can try the following:
At LoanOrder Entity, mark the ddlTables list as transient in order JPA to ignore it and not try to map this field to a database column.
@Transient
public List<DDLTable> ddlTables;

Then supposedly you have somewhere a @Service class which deals with database queries etc
@Service
public class LoanOrderService {

    @Autowired
    EntityManager em;

    public LoanOrder loadSomething() {
        List<DDLTable> ddlTables = em.createQuery("SELECT ddl FROM DDLTable ddl WHERE ddl.tableName = 'ABC'", DDLTable.class).getResultList();

        //load a `LoanOrder` object from database similarly and set its ddlTables list to the one loaded above.
        LoanOrder loanOrder = ....; // load from database or create new depends on what you want to do
        loanOrder.setDdlTables(ddlTables);
        return loanOrder;
    }
}


text:
Q: Spark elasticsearch connector: how to select _id field? I'm using the spark elasticsearch connector and I want to extract from ES some fields plus the _id.
myquery = """{"query":..., """
val df = spark.read.format("org.elasticsearch.spark.sql")
                 .option("query", myquery)
                 .option("pushdown", "true")
                 .load("myindex/mytype")
                 .limit(10)
                 .select("myfield","_id")

Unfortunately, the _id field is not recognized:
AnalysisException: u'cannot resolve \'`_id`\' given input columns:
[query, size, @version, @timestamp,
 sourceinfo, signaletic, document, metadata, fields, aggs]

With this mapping I can select for example document.{fieldA}, sourceinfo.{fieldB}, etc. but not _id. It's like if it's at a level to high in the mapping.
Any idea how to get this particular field?

A: You can access _id or the metadata by setting the es.read.metadata to True
For example in your code:
myquery = """{"query":..., """
val df = spark.read.format("org.elasticsearch.spark.sql")
                 .option("query", myquery)
                 .option("pushdown", "true")
                 .option("es.read.metadata",True) # Set it to True
                 .load("myindex/mytype")
                 .limit(10)
                 .select("myfield","_id")

When you do
df.printSchema()

it will print something like ( in my case )
 |-- user_id: string (nullable = true)
 |-- user_rt: string (nullable = true)
 |-- user_rt_id: string (nullable = true)
 |-- username: string (nullable = true)
 |-- video: long (nullable = true)
 |-- _metadata: map (nullable = true) # this map column will be added
 |    |-- key: string
 |    |-- value: string (valueContainsNull = true)

You can further extract the properties like
_index, _type, _id, _score, sort from _metadata column
To access the _id column from _metadata (map type) i have used this, you can use what you think best
df.createOrReplaceTempView('temp_table_name')
spark.sql("""
     SELECT
     _metadata._id as reference_id
     FROM temp_table_name
    """)

Hope this solves your problem

A: Some of the special characters like _,₹ not support in spark SQL.please try to replace the special characters with another character like "Id".


text:
Q: Why does the for loop cause jvm escape failure When a for loop is added, the escape fails. JVM memory GC frequently。
On the surface, the CTX field should escape successfully.
However, when CTX is before and after the for loop, it has different results.
I'm not sure about the detailed implementation of the JVM, but there is no place to explain the reasons for the escape failure.
Both jvm8 and 14 have tried, and the result is the same.
Can someone tell me why?
class Ctx {
    private String name;

     public Ctx(String name) {
         this.name = name;
     }

     public String getName() {
         return name;
     }

     public void doNothing() {

     }
 }

public class Test {
    public static void main(String[] args) {
        for (long i = 0; i < Long.MAX_VALUE; ++i) {
            Ctx ctx = new Ctx("name");
            // escape success
            ctx.doNothing();
            for (int c = 0; c < 4; c++) {

            }
            // escape fail
            // ctx.doNothing();
        }
    }
}


text:
Q: users connecting to remote desktop to use software Im an IT assistant at a CNC milling company and we use a program called made2manage. Its an ERP (enterprise resource management) software. Each license is something like 5k and instead of giving each employee there own copy of the software he has everyone that uses the program connect to a server that has a copy of m2m on it. Its slow when there are a bunch of people connected to it. But I guess they dont want to buy more licenses.
Is there a better way to do something like this? How bad of a practice is this?

A: Run performance monitors like perfmon or taskmanager when there is low use and run it again when there is high use (maybe early morning and again in the afternoon).  Compare the results during the different times and it should tell you whether or not your server hardware is an issue.
Like zored said, it's a pretty common practice but if your hardware is below specs then things will run slow. Some ERP software require a strong server especially if the database is run on the same server as the application.

A: Running stuff of a Terminal server is somewhat common.  We have several special cause applications licensed for a limited number of concurrent users that we run on a Terminal server combined with a limit to the number of users.
Since, it is performing badly, it sounds like your Terminal server may be below specs, you may need to do some investigation and bump up the hardware allocated to that system.  Or, at least change user limit on the server so that only a reasonable number of people can connect and still have the application perform at acceptable levels.
Assuming the usage is within the license terms, I don't think there is anything wrong with the practice.

A: It may actually be illegal, depending on what the license reads. If it says "CPU" or "machine" then you're clear. If it says "seat" then you are in violation of the license, regardless of how many machines it's installed on.

A: The server with TS and the M2M client software - it's not also the SQL Server for M2M, is it? Because if it is, then that's your problem.

A: I'm an IT Manager administering Made2Manage with 55 concurrent licenses with a SQL 2000 backend. The above server setup is not untypical of most m2m installs. things affecting m2m performance:

*

*improperly configured server.sql or server below specs

*not setting users up to disconnect sessions when not using the software

*users accessing the SQL tables in m2m directly using Excel (easily possible) and they could be joining tables/creating pivot tables, etc. and they no little about sql.

m2m can run virtualized - just a thouht there

A: Also depends on what version of M2M you are operating with.  V6.0.x is running with quite a bit of Visual Foxpro (VFP) code for the forms and reports.  It interfaces with VFP tables that have been upsized to MS-SQL server but much of the behind the curtains in V6 is still VFP. - An issue as Microsoft stopped supporting VFP in 2009.
M2M V7 is still using VFP but not as much.  Their next major release is due out at the end of 2014 and support is saying there are no more VFP hooks in it.  That's great for performance, bad for continuity.  This means any code, custom form, and many of the reports will have to be recreated - (not to mention the data migration).  A side note, the licensing issue in V6 is concurrent.  They have structured it to allow terminal services on the floor, on multiple shifts.  In addition, shop Floor Manager has no license limit.
I have looked looked into upgrading to the latest and greatest, and am not convinced that I want to stay with M2M.  Odoo (OpenERP) has made some solid growth in their application, and as long as we are going to have to clean up the mess that is V6.0.x I'm leaning that way.
If you are looking to just keep the monster running - look at a utility called SQL Check.  It can show real time performance and show you some processor/disk/memory hogs.


text:
Q: The requested resource (/ProjectName/) is not available in Struts 2 I have created a web dynamic project Struts2Starter and for Target runtime, web container is Apache Tomcat 7.
When I run this project, it gives an error:
The requested resource(/Struts2Starter/) is not available

Here's the path:

Webb folder elements/files/contents deployed and in Deployed Resources folder:

Code snippets:
struts.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
<package name="default" extends="default">
<action name="getTutorial" class="TutorialAction">
<result name="success">/success.jsp</result>
<result name="failure">/error.jsp</result>

</action>
</package>

</struts>

web.xml:
 <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
      <display-name>Struts2Starter</display-name>

      <filter>
      <filter-name>struts2</filter-name>
      <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
      </filter>

      <filter-mapping>
      <filter-name>struts2</filter-name>
      <url-pattern>/*</url-pattern>
      </filter-mapping>

    </web-app>

error.jsp:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Error Page!
</body>
</html>

success.jsp:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Success Page!
</body>
</html>

However, when I am running other web projects they run fine. I had given welcome file in web.xml. I removed it later because I did not need it.
I tried running:
http://localhost:8083/Struts2Starter/
http://localhost:8083/Struts2Starter/TutorialAction
http://localhost:8083/Struts2Starter/TutorialAction.action

Same error for all as compiler does not find project available.
Project is built. Port is 8083 and not 8080, as 8080 is already used for some service. However, as i mentioned earlier, other web projects are running fine with Apache 7, using 8083. In Deployment Assembly for project,  i had mapped my user Library "Struts2" (shown in project explorer image above) to Deploy Path "WEB-INF/lib".
I am not able to figure out why project is not running, any suggestions?
I have referred other threads with similar issue, but most of them are for servlets and i am not doing any servlet mapping and instead using filter.
Error Snapshot:

A: Try following in your struts configuration
<?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
        "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
    <package name="default" extends="default" namespace="/">

        <action name=""> <!-- or you can include index.jsp file in web.xml -->
            <result>/index.jsp</result>
        </action>

        <action name="getTutorial" class="TutorialAction">
            <result name="success">/success.jsp</result>
            <result name="failure">/error.jsp</result>
        </action>

    </package>
</struts>

If you don't provide namespace The default namespace is "" an empty string. Here is documentation

A: You have used
http://localhost:8083/Struts2Starter/
http://localhost:8083/Struts2Starter/TutorialAction
http://localhost:8083/Struts2Starter/TutorialAction.action

but neither of them map to the action. struts.xml should be modified and changed for the correct DTD.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
 <package name="default" extends="struts-default">
  <action name="getTutorial" class="TutorialAction">
    <result name="success">/success.jsp</result>
    <result name="failure">/error.jsp</result>
  </action>
</package>

Try this urls
http://localhost:8083/Struts2Starter/getTutorial
http://localhost:8083/Struts2Starter/getTutorial.action

Also download all necessary jars to the lib folder of your application. For example commons-lang3-3.3.2.jar.


text:
Q: Not sure if this is appropriate to do -- calling a Spring endpoint from another endpoint Is there a way for me to do this and is it appropriate? I need the data that comes back from an endpoint in a different controller. Would I create a HTTP request on right in the java code?
Please advise if this is an appropriate question for here...

A: You might want to consider separating the retrieval of the data and the presentation of the data from your current endpoint in two different classes. After you've done that you can easily have two Spring controllers share the same source of data. One of them is your current Spring controller, the other one is the new one.
Performing an HTTP request from one Spring controller to another one in the same application would introduce a lot of overhead and complexity. I would try to avoid that.

A: The correct thing to do is to call the service that is generating the data for the controller in the controller that needs the data.
I hope that you've structured your project as an MVC. If not, you should be addressing that before you do anything else.


text:
Q: React native flow, typescript and Visual Studio Code Could someone explain me this:
When I create new React native project with react-native init it also generates .flowconfig
does it also add dependency on flow at the same time?
When using Visual Studio code it provides some intellisense capabilities but I didn't install TypeScript or anything. Do I have to additionally install TypeScript if I want to use TypeScript instead of Flow?
I'm just confused, because in directory of my project I have .flowconfig and when using VS Code it uses TypeScript anyway.
And what if I just want to use Flow and disable TypeScript completely? There isn't much information about it.

A: Flow is not being installed with base RN scaffolding. This .flowconfig file is only to help you get efficient type-checking process for Flow, in case if you're willing to use Flow. Otherwise, you can delete it. Note that to use Flow you still have to install some packages and maybe editor plugins, also its better to turn off vscode analysis.
TypeScript has to be configured too, even if vscode uses it undercover. One thing (1) is to get intellisense & other helping stuff inside editor and other thing (2) is to use TS to transpile your code.
In first case you can grab some type definitions and feel almost happy with raw JavaScript - vscode still helps with some tips and suggestions. For this I used vscode-react-native plugin, which downloaded RN's type definitions.
In second case - tbh, I don't know much about how popular TS is among RN devs, but you can grab some setup from create-xp-app or similar projects.


text:
Q: java.lang.UnsatisfiedLinkError: Cannot load library: not a valid ELF executable The error
java.lang.UnsatisfiedLinkError: Cannot load library: load_library(linker.cpp:761): not a valid ELF executable: /data/app-lib/com.yepstudio.android.nightclub-2/libgnustl_shared.so

The project was in eclipse.Now i have to use Android studio.
I keep the .jar and .so file in the $projectDir/libs.
And I add the code
sourceSets {
        main {
            jniLibs.srcDirs = ['libs']
        }
    }

But the error is still there


text:
Q: Does redirecting standard output in a child process do so for the parent process as well? I am studying for an OS exam on Tuesday. In order to prepare, I am attempting to simulate the command line pipe via a C program.
The program is pretty simple. I make a pipe and then fork a child process.
The child process redirects standard output to the write-end of the pipe, closes the file descriptors for the pipe, and then executes a command (ls, in this case).
The parent process waits for the child process to exit, redirects standard input to the read-end of the pipe, closes the file descriptors for the pipe, and then executes a command (grep 'school', in this case).
When I execute the command via the command line using ls | grep 'school' there is a line that says "school" printed to standard output, which makes sense given that there is a directory in the directory that I am running the program in named that.
When I run the program that I made, I do not receive any error messages, but it does not produce any output.
The only thing I can think of that would prevent this from working is that redirecting standard output in the child process is somehow affecting the output of the parent process's command, but I'm almost positive that that shouldn't be the case.
Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>

int main() {
    int fds[2];
    int pipe_val, close_val, write_val, dup_val, status;
    pid_t pid;
    char *error;

    pipe_val = pipe(fds);
    if (pipe_val) {
        fprintf(stderr, "Failed to prepare pipe.\n");
        return -1;
    }
    pid = fork();
    if (pid == -1) {
        fprintf(stderr, "Failed to fork a child process.\n");
        return -1;
    } else if (pid == 0) {
        dup_val = dup2(fds[1], STDOUT_FILENO);
        if (dup_val) {
            error = strerror(errno);
            fprintf(stderr, "Failed to redirect standard output in child process because %s\n", error);
            exit(1);
        }
        close_val = close(fds[0]);
        if (close_val) {
            fprintf(stderr, "Failed to close read-end of pipe in child process.\n");
            exit(1);
        }
        close_val = close(fds[1]);
        if (close_val) {
            fprintf(stderr, "Failed to close write-end of pipe in child process.\n");
            exit(1);
        }
        execl("/bin/ls", "ls", NULL);
        fprintf(stderr, "Failed to execute command in child process.\n");
        exit(1);
    } else {
        wait(&status);
        dup_val = dup2(fds[0], STDIN_FILENO);
        if (dup_val) {
           error = strerror(errno);
           fprintf(stderr, "Failed to redirect standard input in parent process because %s.\n", error);
            return -1;
        }
        close_val = close(fds[0]);
        if (close_val) {
            fprintf(stderr, "Failed to close read-end of the pipe in the parent process.\n");
            return -1;
        }
        close_val = close(fds[1]);
        if (close_val) {
            fprintf(stderr, "Failed to close write-end of the pipe in the parent process.\n");
            return -1;
        }
        execl("/bin/grep", "grep", "school", NULL);
        fprintf(stderr, "Failed to execute the command in the parent process.\n");
        return -1;
    }
}

A: Your first problem is that you haven't included all the necessary headers for the functions you're using. strerror requires <string.h> and wait requires <sys/wait.h>.
If you're compiling with gcc, always use gcc -Wall and read the warnings. In this case it would have complained about the implicit declaration of strerror.
Because strerror wasn't declared, the compiler assumes that it returns an int, which is wrong. If you are running the program on 64-bit Linux x86, int is not even the same size as the pointer returned by strerror. This becomes a fatal problem when you then pass the result of strerror to fprintf with a %s format, because the pointer has been misinterpreted as an int and then converted back to a pointer, ending up with a bogus value. fprintf segfaults and you never see your error message.
Include the right headers and you'll see an error message which will lead you to the next problem you need to fix.


text:
Q: Is a REST messaging layer for micro services fast enough? I know very little of micro services so this is part of my learning phase for sure. Say I have multiple nodejs micro services (Auth Service, User Service, Vehicles Service etc). What is the best way to share data between then?
Are HTTP calls good enough? Because it is very easy to just call many HTTP calls from a "Pointsman" service or something. All these nodejs services will be running on the same machine so they should have quite fast speeds. HTTP calls are also async, so you can control how service wait for each other rather easily. Basic calling tests seem super fast, but it is hard to know how bigger pieces of data will work.
The reason why I ask is because people talk about messaging layers. Where messages will lie in a place for services to watch. So services will place and pick up messages assign for them.
I just feel like HTTP calls are good enough, why not use them?

A: The question is not about fast enough but rather scaleable and available microservices.
HTTP protocol is sync
There is very wide misconception that HTTP is async. Http is synchronous protocol but your client could deal it async. E.g. when you call any service using http your http client would schedule is on the backend thread (async). However The http call will be waiting until either it's timeout or response is back , during all this time the http call chain is awaiting synchronously. Now if you have hundreds of requests at a time you can image how many http calls are scheduled synchronously and you may run of sockets.
AMQP
In Microservices architecture we prefer AMQP (Advance message queue protocol) . Which means the service drops the message in queue and forgets about it. This is true async transport protocol since your service is done once it drops the message in the queue and interested services will pick those.
This type of protocol is preferred since you can scale without worry even when other services are down as they will eventually get message/event/data.
That's why HTTP is not preferred way to share the messages/data.

A: To answer your question we need to understand that there are diff. kinds of communication that needs to happen between microservices and based on that there are diff. approaches.
Lets discussion about type of communication by taking a domain example of Facebook :

*

*FOR MESSAGING You like on some post. In this case lots of things needs to happen like first of all count of like on post need to increase , then some recommendation service will try to see what kinds of post you like based on that change your recommendations , some app service will send some notifications to apps about the post update and so on. In these cases where based on some event like UserLikedAPost many a things needs to happen in diff. microservice we should write such event in a Message Queue like Kafka or Rabbit MQ and then other services can subscribe and do the respective work.

In this case as we do not want all the other operations to complete before sending the final response for user HTTP request as it will make the post like request time to increase.

*FOR HTTP OR gRPC Get my account details: in this case while showing your data one will show your interests , your job which all are part of diff. microservice like Interest and Job. For this when one requests come that request needs to call each service either using Rest or gRPC (it is highly optimized that REST with JSON) to return the results.

Now i have given you examples that both Messaging and HTTP (or gRPC) are needed.
Also there are much more scenarios where you may prefer one over the another. You might like to read: microservices pattern to understand more about these things


text:
Q: Azure Mobile Services Auth - We can't connect to the service I'm getting "We can't connect to the service you need right now. Check your network connection or try this later." every now and then on my Windows 10 application when executing
user = await MyCloud.AzureClient.LoginAsync(provider, true);

Does anyone know the root cause of this error?
The app is connected to internet, checking internet connectivity of the app with
ConnectionProfile internetConnectionProfile =
                               NetworkInformation.GetInternetConnectionProfile();

A: The problem is with calling
LoginAsync(this IMobileServiceClient client, string provider, bool useSingleSignOn)

Single Sign On does not work well. Everything is working fine by just calling
LoginAsync(this IMobileServiceClient client, string provider)


text:
Q: I'm unable to to put my nickname I m not able to choose a nickname for me in the game so which type of nickname I should try?

A: Do you mean that the nickname is already taken? Your nickname has to be unique.


text:
Q: backbone - how to get the model when listening to "add" event on the collection first question here at SO :)
I'm workin on a backbone project and the main example I rely on is TODOMVC by Addy Osmani, but there's something I cant figure out:
on the Todo app inside AppView
this.listenTo(app.Todos, 'add', this.addOne);

calls
addOne: function (todo) {
            var view = new app.TodoView({ model: todo });
            $('#todo-list').append(view.render().el);
        }

when I try to do the same I get the collection as the todo param inside addOne.
so, how can I get the actual model that was added?


text:
Q: Eigenvalues of large symmetric matrices When I try to compute the eigenvalues of the adjacency matrix of a very large graph I get, what can be charitably described as, garbage. In particular, since the graph is four-regular, the eigenvalues should be in $[-4, 4]$ but they are visibly not. I used Matlab (via MATLink), and got the same problems, so this is clearly an issue that transcends mathematica. The question is: what is the best way to deal with it? I am sure MATLAB and Mathematica use the venerable EISPAK code, so there may be something newer/better

A: Eigenvalue methods for dense matrices usually proceed by first transforming the matrix into Hessenberg form, here this would result in a tridiagonal matrix. After that some variant of the shifted QR algorithm, like bulge-chasing, is applied to iteratively reduce the non-diagonal elements, splitting the matrix at positions where these become small enough.
But what I would like to draw the attention to is that first step and its structure destroying consequences. It is, for instance, not guaranteed that the tri-diagonal matrix is still symmetrical. This applies also to all further steps if they are not explicitly tailored for symmetric matrices.
But what is much more relevant here is that this step ignores all connectivity or non-connectivity of the graph and potentially connects all nodes, albeit with very small weights, when the transformation is reversed.
Each of the m connected component of the graph gives one eigenvalue 4 with an eigenvector that is 1 at the nodes of the components and 0 else. These eigenspaces have all dimension 1. Any small perturbation of the matrix first removes that separation and joins them in an eigenspace of dimension m and then perturbs this as a multiple eigenvalue. This then can result in an approximately regular m pointed star in the complex plane of radius 4*(1e-15)^(1/m) around the original value 4. Even for medium sized m this gives a substantial deviation from the true eigenvalue.

So in summary, use a sparse method as these usually will first re-order the matrix to be as diagonal as possible, which should give a block-diagonal structure according to the components. Then the eigenvalue method will automatically work on all blocks separately, avoiding the above described mixing. And if possible, use a method for symmetric matrices or set a corresponding option/flag if it exists.


text:
Q: Angular displaying a different placeholder in an input dependant on a mat select I'm trying to display different placeholder text in a mat-input dependant on what I select in my mat-select, and I cant seem to find a way to bind it to my selected option.
<mat-form-field appearance="outline" class="search-field" style="width:40vw">
          <input matInput type="text" class="input" placeholder="Enter a Plant No" formControlName="searchQuery">
          <mat-select name="ampm" class="ampm" style="width:10vw;" [value]="selected">
            <mat-option value="PLANT_NO">PLANT_NO</mat-option>
            <mat-option value="EQUIP_NO" disabled>EQUIP_NO</mat-option>
            <mat-option value="LOCN_DESC" disabled>LOCN_DESC</mat-option>
            <mat-option value="EQUIP_GRP_ID" disabled>EQUIP_GRP_ID</mat-option>
            <mat-option value="EQUIP_CLS" disabled>EQUIP_CLS</mat-option>
            <mat-option value="MAINT_ZONE_NAM" disabled>MAINT_ZONE_NAM</mat-option>
            <mat-option value="PRNT_PLNT_NO" disabled>PRNT_PLNT_NO</mat-option>
            <mat-option value="SUBSTATION" disabled>SUBSTATION</mat-option>
            <mat-option value="IP_PLNT_NO" disabled>IP_PLNT_NO</mat-option>
          </mat-select>
          <button mat-icon-button title="Search">
            <mat-icon>search</mat-icon>
          </button>
</mat-form-field>

A: you can use [placeholder] property binding, and mat select change event you can update as per your requirement.
ts
inputPlaceholderUpdate = "Enter a Plant No";

selectChange(event){
   const value = event.value;
   this.inputPlaceholderUpdate = value == 'PLANT_NO' ? 'Enter a Plant No' : value == 'EQUIP_NO' ? 'Enter a Equip No' : 'Enter a Locn Desc';
}

html
<input matInput type="text" class="input" [placeholder]="inputPlaceholderUpdate" formControlName="searchQuery">
<mat-select name="ampm" class="ampm" style="width:10vw;" [value]="selected" (selectionChange)= "selectChange($event)">
......
......
</select>


text:
Q: hover effect with quicksand plugin I'm using Quicksand plugin on a website and I want to have all the items to have a hover effect. I managed to do it but the hover effect would disappear after the filtering occurs. I then followed this advice:
jQuery quicksand plugin with .click method
and added the following to my code:
$("img.on").live({
mouseover:
function() {
$(this).stop().animate({"opacity": "0"}, "slow");},
mouseout:
function() {
$(this).stop().animate({"opacity": "1"}, "slow");}});
$("img.over").live({
mouseover:
function() {
$(this).stop().animate({"opacity": "1"}, "slow");},
mouseout:
function() {
$(this).stop().animate({"opacity": "0"}, "slow");}});

It seems to work fine on ff but ie8 won't work. The hover image appears above the original one and doesn't move from there. If I change mouseover to mouseenter and mousout to mouseleave it will at least fade out after hovering and leaving and then perform as expected.
I have the opacity of the hover img to cero via css.
I might have made a newbie mistake, I'm completely new to js and jquery.

A: Using .live() I solved this so the clonned elements get affected by the hover


text:
Q: Linux/Unix Socket Self-connection When a client try to connect to a server, if client and server are both localhost, self-connection may happen(source port and destination port happened to be the same.). But my problem is, client is not listening to that port, how can self-connection be possible?

A: I found your question after encountering the same phenomenon. The best explanation I found is at Everything About Nothing: TCP Client Self Connect.
You can ask for the port assigned to you via getsockname() and compare it to the remote port to detect these self connections:
sockaddr_in addr_client;
socklet_t len = sizeof(saddr_in);

if(getsockname(sock_client, (struct sockaddr *)&addr_client, &len))
    { /* error */ }
if(len != sizeof(saddr_in)))
    { /* error */ }

if(addr_client.sin_port == addr_server.sin_port &&
  addr_client.sin_addr.s_addr == addr_server.addr.sin_addr.s_addr)
    { /* self-connection detected! */ }

A: The server and client in localhost don't use the same port.
As a connected Tcp connection,
To server,source port is A and destination port is B.
To client,source port is B and destination port is A.
A is set by bind() in server, and is known to all clinets; B is usually assigned by clinets' kernel, and is known to server when the server's accept() returns.
In details:
In tcp,the server's port is set by bind()  which lets us specify a port number, an IP address, both, or neither, but it is rare for a TCP server to let the kernel choose an ephemeral port Afterwards, server listen() the port and IP address.
and client uses connect() whose socket address structure must contain the IP address and port number of the server.  the kernel will choose both an ephemeral port and the source IP address if necessary. Anyway, it can't be the port your server using.
That's to say, the ports of a server and a clinet in the same computer is not the same.
For example, when simple C/S programs running in a localhost, typing netstat -t in terminal,and you will get:
Proto Recv-Q Send-Q Local Address           Foreign Address             State
tcp        0      0 localhost:41742         localhost:9877          ESTABLISHED
tcp        0      0 localhost:9877          localhost:41742         ESTABLISHED

the prots is obviously different.
If you force the client to use the same port of your the one server is using on local by bind(), the bind() will return -1 as a error.

A: We can simple reproduce this phenomenon with the following python program
import socket
for i in range(65536):
  try:
    s = socket.create_connection(('127.0.0.1', 50000))
    print 'connected to {0}'.format(s.getpeername())
  except Exception as e:
    pass

when we try to connect some socket in the same host. if we don't bind your client to a specific port, operating system will provide ephemeral port for you. if it's happened to be the one you want to connect to. it causes self connection. Make sure the port you are trying to connect is in /proc/sys/net/ipv4/ip_local_port_range


text:
Q: is it possible pinging through nat from outside the nat inside? is it possible to send an echo-request to a host set behind nat
after. all the echo-request doesn't hold a port for the destination host so if there are several hosts using the same external ip address how will the nat be able to forward the echo-request to a specific host

A: Most modern NAT/packet filtering implementations are stateful. That means they have a wider concept of the word connection than the older stateless variants. That allows them to handle more complex protocols that use additional connections (e.g. FTP), as well as connection-less protocols like ICMP.
In the case of ICMP packets, echo requests contain an ID field that is preserved in the reply. While its 16 bits are somewhat restrictive, it allows in conjuction with the source IP address from the IP header to have a reasonably high confidence on which echo request each reply corresponds to.
EDIT:
As for targeting specific hosts behind a NAT implementation, that is not generally possible. You might be able to:

*

*Redirect all ICMP traffic to one internal host to monitor that one host only.

*Use the "pad" data bytes of the echo request packet to provide some kind of host identifier. For example, the -p option of ping on some Linux systems allows setting that field. This is by no means standard, though.
In general, NAT is supposed to hide the hosts behind it from the world, with the exception of any forwarded IP connections.


text:
Q: C boolean logic I have been trying some programs in the C Language and come across to this...
#include<stdio.h>
int main()
{
    int j = 3, k;
    k= !5 && j;
    printf("%d", k);
    return 0;
}

Can anyone figure out what is the problem in this if I compile the program I will result to 0.
and when I tried the same code in C#
public void logic()
{
    j = 5;
    k = !4 && j;
    Console.WriteLine("hence the value would be " + k);
}

this will generate the error

( Error    1   Operator '!' cannot be applied to operand of type 'int' C:\Documents and Settings\SANDEEP\My Documents\Visual Studio 2005\Projects\ConsoleApplication18\ConsoleApplication18\Program.cs 21  17  ConsoleApplication18 )

I want to know why the output of my C code is not working, and how can I use the ! operator in C#.
Please help.

A: 5 when interpreted as a boolean value is true, so!5 gives the boolean result false, which causes && to give false as well. False interpreted as an int is 0.

A: In C, any non-zero value such as 5 is considered to be "true", therefore !5 evaluates to 0, or "false". Thus, 0 && 3 is false as well. Logical operators in C.
In C#, the type system is a little stronger in this respect. The ! operator only works on values of type bool, which is completely independent of the integer types. See ! Operator in C#.

A: The readable C code:
Compile it, run it, and how the expressions are evaluated.
#include <stdio.h>
int main() {
        int j = 3, k;
        k = !5 && j;

        printf("!5 = %d \n", !5);
        printf("j = %d \n", j);
        printf("!5 && j = %d \n", !5 && j);
        printf("k = %d \n",k);

        return 0;
}

You probably cannot apply "!" to ints in C# in this manner. I believe you can achieve that by using "~" on an int.
You can aply "!" to a Boolean (I don't know how it's called in C#).

A: The equivalent code to this C code
#include<stdio.h>
int main()
{
    int j=3,k;
    k=!5&&j;
    printf("%d",k);
    return 0;
}

in C# would be
class Program {
static int Main()
{
    int j=3, k;
    k = !(5 != 0) && (j != 0) ? 1 : 0;
    Console.WriteLine("{0}", k);
    return 0;
}
}

Notice that C# does not allow Boolean logic operators to be used on ints. If you want to convert ints to bools, you'll have to write code to do that, as I have here.
Both programs correctly output zero because 5 is not equal to 0, therefore !5 (C) or !(5!=0) (C#) is false. In C, the false converts to zero. In C#, the alternative of the conditional operator gives zero.
Does that answer your question?

A:
and how can i use the ! operator in c#.

That's the logical-not operator. You put it to the right of a bool and it produces the opposite. In C# there is no implicit conversion from integer to bool.
By the way, your "same code" in C# has different number values in it!

A: You are trying to do a logical NOT.  You have to do a bitwise NOT on an int in C# (the ~ operator, not !).  See here:
http://msdn.microsoft.com/en-us/library/d2bd4x66(VS.71).aspx

A: In C# (and Java) you could do something like
k = (4 == 0) && (j != 0);

to get the same behaviour as your C program. Comparing an integer to 0 gives the same "logics" than C.

A: If you want to do bit arithmetic rather than simple boolean arithmetic, your C code is using the wrong operators. Here's a sample link with the correct operators.
In your current C code, k=!5&&j, 5 is considered true, so !5 is 0 (false). You then AND it with j, but any false ANDed with any boolean is false, so you get 0.
You probably want something like (tilda5)&j


text:
Q: HTML select from list I'm a HTML noob, but what is the easiest way to create something like

Where I have the possibility to make a slection from a bigger list

A: If you are a beginner in HTML then you might want to start and the beginning.
I don't know what your goal is so i can't adjust my answer to it. The element you are looking for is called SELECT
http://www.tizag.com/htmlT/htmlselect.php
And if you really like to make it like the availible selection menu you sould take a look into jQuery as well. Though from the fact that you are a beginner in HTML that would be kind of hard.

A: Take a look at <select multiple> and event handlers.
You'll need two of those, and some buttons/links to move the selection from one to another.
You'll need to attach event handlers for those buttons to move the selected <options> from one <select> to the other by means of javascript.