text:
Q: How to search unread mail in Outlook with VBScript? I am able to open Outlook, focus it to the inbox folder, and count unread mails with .Unread.
I would like to be able to search unread email for a particular email address in the body of the emails.
I am using Windows 7 with Outlook 2007.

A: You need to use the Restrict or Find/FindNext methods of the Items class. Take a look at the following articles for the sample code and more information about them:

*

*How To: Use Find and FindNext methods to retrieve Outlook mail items from a folder (C#, VB.NET)

*How To: Use Restrict method to retrieve Outlook mail items from a folder
For example, to find all unread emails in the folder you can use the following search criteria:
  [UnRead] = true

Also you may find the AdvancedSearch method of the Application class helpful. The key benefits of using the AdvancedSearch method in Outlook are:

*

*The search is performed in another thread. You don't need to run another thread manually since the AdvancedSearch method runs it automatically in the background.

*Possibility to search for any item types: mail, appointment, calendar, notes etc. in any location, i.e. beyond the scope of a certain folder. The Restrict and Find/FindNext methods can be applied to a particular Items collection (see the Items property of the Folder class in Outlook).

*Full support for DASL queries (custom properties can be used for searching too). You can read more about this in the Filtering article in MSDN. To improve the search performance, Instant Search keywords can be used if Instant Search is enabled for the store (see the IsInstantSearchEnabled property of the Store class).

*Finally, you can stop the search process at any moment using the Stop method of the Search class.

The Outlook object model provides three main ways for working with item bodies:

*

*Body - a string representing the clear-text body of the Outlook item.

*HTMLBody - a string representing the HTML body of the specified item.

*Word editor - the Microsoft Word Document Object Model of the message being displayed. The WordEditor property of the Inspector class returns an instance of the Document class from the Word object model which you can use to set up the message body.

You can read more about all these ways in the Chapter 17: Working with Item Bodies. It us up to you which way is to choose to customize the message body.


text:
Q: How to disable subscription notification on startup of Meteor.js? Start notification:
** You've set up some data subscriptions with Meteor.publish()

How to disable?

A: I'm going to assume you're getting this whole error message:
** You've set up some data subscriptions with Meteor.publish(), but
** you still have autopublish turned on. Because autopublish is still
** on, your Meteor.publish() calls won't have much effect. All data
** will still be sent to all clients.
**
** Turn off autopublish by removing the autopublish package:
**
**   $ meteor remove autopublish
**
** .. and make sure you have Meteor.publish() and Meteor.subscribe() calls
** for each collection that you want clients to see.

To make the notification go away, just do what it asks you to do and run:
meteor remove autopublish

What is autopublish?
Autopublish is a package used for rapid prototyping. It sends all collections from MongoDB to the client for easy use. From the docs:

Publish all server collections to the client. This package is useful for prototyping an app without worrying about which clients have access to certain data, but should be removed as soon as the app needs to restrict which data is seen by the client.

Before putting your app on the internet you will want to turn this off and use publications and subscriptions to secure, filter and mange your data flow

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can you shorten repetitive if/else statements? How can you simplify this code? It gets very lengthy and is extremely repetitive, with so many null checks.
    id data;

    data = [dictionary objectForKey:@"FirstName"];
    if ([data isEqual:[NSNull null]]) {
        self.firstName = @"";
    }
    else{
        self.firstName = (NSString *)data;
    }

    data = [dictionary objectForKey:@"MiddleName"];
    if ([data isEqual:[NSNull null]]) {
        self.middleName = @"";
    }
    else{
        self.middleName = (NSString *)data;
    }

    data = [dictionary objectForKey:@"LastName"];
    if ([data isEqual:[NSNull null]]) {
        self.lastName = @"";
    }
    else{
        self.lastName = (NSString *)data;
    }

    ...

Ideally I would want to put all the variables in an array of sorts, and just loop through and apply the null check and assignment to all of them. But you can't exactly store variables in an array. What is the best way to shorten this code?

A: You could wrap each of those calls into one method.
- (NSString *)stringFromDictionary:(NSDictionary *) forKey:(NSString *)key
{
    id data = [dictionary objectForKey:key];
    if ([data isKindOfClass:[NSString class]]) {
        return = (NSString *)data;
    } else {
        return @"";
    }
}

Then call the method three times.
self.firstName = [self stringFromDictionary:dictionary forKey:@"FirstName"];
self.middleName = [self stringFromDictionary:dictionary forKey:@"MiddleName"];
self.lastName = [self stringFromDictionary:dictionary forKey:@"LastName"];

A: You could use the ternary operator to shorten your code
self.firstName = [data isEqual:[NSNull null]] ? @"" : (NSString *)data;


text:
Q: Why is Amazon SES mail simulator bounces not working? (Am I missing headers or something?) I'm trying to use the amazon SES simulator as documented here: http://docs.aws.amazon.com/ses/latest/DeveloperGuide/mailbox-simulator.html
The body of the message looks like this:
MIME-Version: 1.0
Content-Type: multipart/alternative; charset="utf-8";
 boundary="===============123456789=="
Content-Transfer-Encoding: base64
Subject: hello test message!
Reply-To: my_address@my_provider.com
To: complaint@simulator.amazonses.com
Return-Path: my_address@my_provider.com
Bounces-to: my_address@my_provider.com
Errors-to: my_address@my_provider.com
From: my_address@my_provider.com

--===============123456789==
MIME-Version: 1.0
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: base64

Ym9keSB3aXRoIG5vbmNlOiAw

--===============123456789==
MIME-Version: 1.0
Content-Type: text/html; charset="utf-8"
Content-Transfer-Encoding: base64

Ym9keSB3aXRoIG5vbmNlOiAw

--===============123456789==--

I'm sending this as the body, and using the boto3 interface ses_client.send_raw_message.
I'm generating this message body with something like this
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import re

msg = MIMEMultipart('alternative')
msg.set_charset('utf8')

text_message='Ym9keSB3aXRoIG5vbmNlOiAw'

p = re.compile('<.*?>')
text_message = 'body with nonce: {}'.format(str(nonce))
text = MIMEText(p.sub('', text_message), 'plain', 'utf8')
html = MIMEText(text_message, 'html', 'utf8')
msg.attach(text)
msg.attach(html)

source = 'my_email@my_provider.com'
msg['Subject'] = 'hello test message!'

msg['Reply-To'] = source
msg['To'] = to_mail
msg['Return-Path'] = source
msg['Bounces-to'] = source
msg['Errors-to'] = source

So I can send emails through SES and it works just fine.
I can also send emails to complaint@simulator.amazonses.com, and that works.
I haven't set up any SNS messaging, but I expected, through all the header fields that I set, to get a bounce back at the desired address. However, nothing happens if i use bounce@simulator.amazonses.com.
This is a list of header fields that amazon acknowledges:
http://docs.aws.amazon.com/ses/latest/DeveloperGuide/header-fields.html
I have also enabled email feedback forwarding, as described here:
http://docs.aws.amazon.com/ses/latest/DeveloperGuide/notifications-via-email.html
Also, for sending the emails I use this logic:
amazon_client = boto3.client('ses', 'region', **credentials)
amazon_client.send_raw_email(
            Source=from_mail,
            Destinations=to_mails,
            RawMessage={'Data': body}
        )

According to the page documenting how to receive notifications, I should be getting mails back at the Source address specified - which I do set, and I do have the email feedback forwarding enabled for....
Any ideas what I might be missing?

A: The headers you are putting in suggest that the real problem is false expectations. Errors-To: will be ignored pretty much by everything you can find, and Return-Path: will be replaced with the envelope sender by the receiving MTA. To control bounces, you need to control the envelope sender (traditionally, with sendmail -f) and what you put in the headers is completely irrelevant.

A: Solved.
The bounce address was different from the 'From' address. Therefore, the bounces ended up in the SPAM of that other address.
Interestingly, that address had a filter to forward everything to the address I had used as for 'From' address, when sending the email.
So my confusion was caused because I expected to get mail forwarded from that other address, but the bounces never got forwarded.


text:
Q: mysql procedure insertion use variable I have a question when making a insertion in mysql Procedure.
I used a local variable IDnew to get the (max(id) +1) from original table.
Then I want to insert it back with some specific information.
However, I failed as the new ID is not what I want after insertion.
What is being missed here?
DELIMITER $$
create procedure proc_InsertStar(IN sname varchar(100), IN syear INT(11))

BEGIN
    declare IDnew varchar(255);
    select IDnew;                #line A
    select concat("nm",lpad(cast(max(replace(id,"nm","")+1)as char),7,'0')) into IDnew from stars;
    select IDnew;                #line B
    insert into moviedb.stars(id,name,birthYear) values(IDnew,sname, syear);

END
$$

DELIMITER ;

call proc_InsertStar("jaden smith", 1998);
select * from stars where name="jaden smith";  #line C

The outcome is shown below:
line A:
   [enter image description here][1]

line B:
[enter image description here][2]

line C:
[enter image description here][3]

However, the max Id should be 'nm9423081' which is 'nm9423080' add one on the lowest bit.
  [1]: https://i.stack.imgur.com/mg7HF.png
  [2]: https://i.stack.imgur.com/BaHiZ.png
  [3]: https://i.stack.imgur.com/qzotC.png


text:
Q: Tapas manga about a guy going into a simulation where he would take care of children This manga from Tapas was about a guy going into a simulation where he would take care and help whatever child he got grow up healthy and well. I thought it was super cute, but then I forgot the name of it. I only remember the little boy's name being Mir and that there was a butler who was like the guidebook for the main protagonist, being the guy playing the simulator (forgot his name). I really wanna pick up where I left off on it, but can't seem to remember the name at all. Please, if someone thinks they know it, I'd like to know.

A: This is Childminder by Peacock Kim but it was removed from Tapas so I don't know where you could read it:

One day Hyun gets chosen to test out a parenting game called Childminder. He thought the game would be easy because all he had to do was be a good father to a very cute child named Mir. However Hyun eventually finds out Childminder is not a normal game nor is Mir a normal child. — Korean Webtoons Wiki

Found thanks to a post on the Tapas forum.


text:
Q: Firemonkey application developed through RAD Studio 10.0 is crashing on iOS 7.1? I have an application to which I have released on http://www.diawi.com/index.php for the testers, but it isn't launching on IOS 7.1 devices. I have set the minimum deployment target as IOS 7.1, but my base sdk is IOS 9. It is launching fine on iOS 8 and iOS 9. what could be the reason? Is there no support for iOS versions less than 8.0 on Delphi 10 Seattle?

A: Per Embarcadero's documentation:
Adding a Mac OS X or iOS SDK

Notes:

*

*RAD Studio does not support versions of the iOS SDK lower than 8.0.

*iOS applications built with a given SDK version may only run on that version or later versions of iOS. For example, an application built with version 9 of the iOS SDK might crash on a device running iOS 8.

Based on that, the following documentation seems to have a contradiction:
FireMonkey Platform Prerequisites

The following iOS devices are supported:

*

*iPod Touch, iPhone, or iPad

*iOS 7

*iOS 8

*iOS 9

  For iOS application development, you need to have installed on the Mac:

*

*iOS 8 SDK or iOS 9 SDK

*Xcode 6 or Xcode 7, see Installing Xcode

This suggests they support iOS 7 devices, but do not support the iOS 7 SDK.
However, there are Delphi forum discussions that claim you can use xCode 6.4 and the iOS 8.4 SDK to target iOS 7 and 8 in Delphi Seattle.  And there is this Embarcadero blog post that supports that claim, and points to a Hotfix for Seattle that allows Delphi to use the iOS 9 SDK to target iOS 7 and 8.
Do you have that hotfix installed?


text:
Q: Калькулятор на 3 числа Java Как сюда добавить 3 число?
public static void main(String[] args) throws IOException {
    System.out.print("Введите пример: ");
    char x = (char) System.in.read();
    char ope = (char) System.in.read();
    char y = (char) System.in.read();
    int xVal = x - 48;
    int yVal = y - 48;
    System.out.print("= ");
    System.out.print(xVal + yVal);

// сейчас выводится пример 5+5=10
// нужно чтобы считывался 2ой оператор и число и выводил результат. Пример 10-2*2=16
Вот что получилось
public static void main(String[] args) throws IOException {
    System.out.print("Введите пример: ");
    char x = (char) System.in.read();
    char ope = (char) System.in.read();
    char y = (char) System.in.read();
    char ope1 = (char) System.in.read();
    char z = (char) System.in.read();
    int xVal = x - 48;
    int yVal = y - 48;
    int zVal = z - 48;
    System.out.print("= ");

Я понимаю что тут все злые и проще нагрубить или отправить дальше самой с этим разбираться. Не тратьте ваше время тогда если вы не знаете или не хотите помочь, я потому и задала тут вопрос потому что спросить мне больше не у кого и не знаю как это продолжить. Про поиск в интернете не надо мне говорить, я не на столько ленивая чтобы им в первую очередь не пользоваться.

A: Вам нужно преобразовать пришедшую строку из консоли в число.
Пример :
Integer.parsInt("4");

Или
Integer.valueOf("4");

A: Этот код считает примеры с операциями + и -. Например 132-45+12-23. Если хотите можете расширить его на */, но стоит учесть то уже не будет работать, так как нужен будет приоритет операций, но думаю у вас всё получится, если немножко посидеть и подумать! :)
public class Calc {

    public static void main(String[] args) throws IOException {
        {
            Scanner in = new Scanner(System.in);
            System.out.print("Введите пример: ");
            String example = in.nextLine();
            System.out.print(calculate(example));
        }
    }

    public static Integer calculate(String example){
        example = example.replace(" ", "");

        if(!example.matches("^(\\d{1,}[-+]){1,}\\d{1,}$")){
            throw new RuntimeException("НЕДОПУСТИМЫЙ ФОРМАТ");
        }

        Integer[] ints = Arrays.stream(example.split("[-+]")).map(Integer::parseInt).toArray(Integer[]::new);

        int result = ints[0];
        int counter = 1;
        for (char ch : example.replaceAll("[0-9]","").toCharArray()) {
            if (ch == '-') result -= ints[counter];
            if (ch == '+') result += ints[counter];
            counter++;
        }

        return result;
    }
}


text:
Q: io.netty.handler.codec.DecoderException: javax.net.ssl.SSLHandshakeException: Received fatal alert: bad_certificate Small question regarding an issue faced when mTLS is enabled.
On a Java + Spring Webflux project for both client and server, the client is configured to send requests as such:
public SslContext getSslContext() {
        try {
            final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            try (InputStream file = Files.newInputStream(Paths.get(URI.create(keyStorePath)))) {
                final KeyStore keyStore = KeyStore.getInstance(keyStoreType);
                keyStore.load(file, keyStorePassPhrase.toCharArray());
                keyManagerFactory.init(keyStore, keyPassPhrase.toCharArray());
            }

            final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            try (InputStream trustStoreFile = Files.newInputStream(Paths.get(URI.create(trustStorePath)))) {
                final KeyStore trustStore = KeyStore.getInstance(trustStoreType);
                trustStore.load(trustStoreFile, trustStorePassPhrase.toCharArray());
                trustManagerFactory.init(trustStore);
            }

            return SslContextBuilder.forClient().keyManager(keyManagerFactory).trustManager(trustManagerFactory).build();
        } catch (CertificateException | NoSuchAlgorithmException | IOException | KeyStoreException | UnrecoverableKeyException e) {
            return null;
        }
    }

//the webflux web client
WebClient.create().mutate().defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).clientConnector(new ReactorClientHttpConnector(HttpClient.create().wiretap(true).secure(sslContextSpec -> sslContextSpec.sslContext(getSslContext())))).build();

Upon the HTTP call, I am seeing this on client side log:
[or-http-epoll-3] r.netty.http.client.HttpClientConnect    : [id: 0x02d7d229, L:/123:44092 ! R:the-service.com/456:19010] The connection observed an error

io.netty.handler.codec.DecoderException: javax.net.ssl.SSLHandshakeException: Received fatal alert: bad_certificate
    at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:478) ~[netty-codec-4.1.58.Final.jar!/:4.1.58.Final]
    at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:276) ~[netty-codec-4.1.58.Final.jar!/:4.1.58.Final]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) ~[netty-transport-4.1.58.Final.jar!/:4.1.58.Final]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) ~[netty-transport-4.1.58.Final.jar!/:4.1.58.Final]
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357) ~[netty-transport-4.1.58.Final.jar!/:4.1.58.Final]
    at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1410) ~[netty-transport-4.1.58.Final.jar!/:4.1.58.Final]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) ~[netty-transport-4.1.58.Final.jar!/:4.1.58.Final]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) ~[netty-transport-4.1.58.Final.jar!/:4.1.58.Final]
    at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:919) ~[netty-transport-4.1.58.Final.jar!/:4.1.58.Final]
    at io.netty.channel.epoll.AbstractEpollStreamChannel$EpollStreamUnsafe.epollInReady(AbstractEpollStreamChannel.java:795) ~[netty-transport-native-epoll-4.1.58.Final-linux-x86_64.jar!/:4.1.58.Final]
    at io.netty.channel.epoll.EpollEventLoop.processReady(EpollEventLoop.java:480) ~[netty-transport-native-epoll-4.1.58.Final-linux-x86_64.jar!/:4.1.58.Final]
    at io.netty.channel.epoll.EpollEventLoop.run(EpollEventLoop.java:378) ~[netty-transport-native-epoll-4.1.58.Final-linux-x86_64.jar!/:4.1.58.Final]
    at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:989) ~[netty-common-4.1.58.Final.jar!/:4.1.58.Final]
    at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74) ~[netty-common-4.1.58.Final.jar!/:4.1.58.Final]
    at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) ~[netty-common-4.1.58.Final.jar!/:4.1.58.Final]
    at java.base/java.lang.Thread.run(Thread.java:834) ~[na:na]
Caused by: javax.net.ssl.SSLHandshakeException: Received fatal alert: bad_certificate
    at java.base/sun.security.ssl.Alert.createSSLException(Alert.java:131) ~[na:na]
    at java.base/sun.security.ssl.Alert.createSSLException(Alert.java:117) ~[na:na]
    at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:336) ~[na:na]
    at java.base/sun.security.ssl.Alert$AlertConsumer.consume(Alert.java:293) ~[na:na]
    at java.base/sun.security.ssl.TransportContext.dispatch(TransportContext.java:185) ~[na:na]
    at java.base/sun.security.ssl.SSLTransport.decode(SSLTransport.java:171) ~[na:na]
    at java.base/sun.security.ssl.SSLEngineImpl.decode(SSLEngineImpl.java:681) ~[na:na]
    at java.base/sun.security.ssl.SSLEngineImpl.readRecord(SSLEngineImpl.java:636) ~[na:na]
    at java.base/sun.security.ssl.SSLEngineImpl.unwrap(SSLEngineImpl.java:454) ~[na:na]
    at java.base/sun.security.ssl.SSLEngineImpl.unwrap(SSLEngineImpl.java:433) ~[na:na]
    at java.base/javax.net.ssl.SSLEngine.unwrap(SSLEngine.java:637) ~[na:na]
    at io.netty.handler.ssl.SslHandler$SslEngineType$3.unwrap(SslHandler.java:282) ~[netty-handler-4.1.58.Final.jar!/:4.1.58.Final]
    at io.netty.handler.ssl.SslHandler.unwrap(SslHandler.java:1387) ~[netty-handler-4.1.58.Final.jar!/:4.1.58.Final]
    at io.netty.handler.ssl.SslHandler.decodeJdkCompatible(SslHandler.java:1282) ~[netty-handler-4.1.58.Final.jar!/:4.1.58.Final]
    at io.netty.handler.ssl.SslHandler.decode(SslHandler.java:1329) ~[netty-handler-4.1.58.Final.jar!/:4.1.58.Final]
    at io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:508) ~[netty-codec-4.1.58.Final.jar!/:4.1.58.Final]
    at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:447) ~[netty-codec-4.1.58.Final.jar!/:4.1.58.Final]
    ... 15 common frames omitted

And on server log, I am seeing the following.
s.ApplicationProtocolNegotiationHandler : [id: 0x10b61280, L:/1xx.xxx:19010 - R:/1xxx:45678] Failed to select the application-level protocol:

javax.net.ssl.SSLHandshakeException: Empty client certificate chain
    at java.base/sun.security.ssl.Alert.createSSLException(Alert.java:131) ~[na:na]
    at java.base/sun.security.ssl.Alert.createSSLException(Alert.java:117) ~[na:na]
    at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:336) ~[na:na]
    at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:292) ~[na:na]
    at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:283) ~[na:na]
    at java.base/sun.security.ssl.CertificateMessage$T13CertificateConsumer.onConsumeCertificate(CertificateMessage.java:1193) ~[na:na]
    at java.base/sun.security.ssl.CertificateMessage$T13CertificateConsumer.consume(CertificateMessage.java:1180) ~[na:na]
    at java.base/sun.security.ssl.SSLHandshake.consume(SSLHandshake.java:392) ~[na:na]
    at java.base/sun.security.ssl.HandshakeContext.dispatch(HandshakeContext.java:443) ~[na:na]
    at java.base/sun.security.ssl.SSLEngineImpl$DelegatedTask$DelegatedAction.run(SSLEngineImpl.java:1074) ~[na:na]
    at java.base/sun.security.ssl.SSLEngineImpl$DelegatedTask$DelegatedAction.run(SSLEngineImpl.java:1061) ~[na:na]
    at java.base/java.security.AccessController.doPrivileged(Native Method) ~[na:na]
    at java.base/sun.security.ssl.SSLEngineImpl$DelegatedTask.run(SSLEngineImpl.java:1008) ~[na:na]
    at io.netty.handler.ssl.SslHandler.runAllDelegatedTasks(SslHandler.java:1557) ~[netty-handler-4.1.58.Final.jar!/:4.1.58.Final]
    at io.netty.handler.ssl.SslHandler.runDelegatedTasks(SslHandler.java:1571) ~[netty-handler-4.1.58.Final.jar!/:4.1.58.Final]
    at io.netty.handler.ssl.SslHandler.unwrap(SslHandler.java:1455) ~[netty-handler-4.1.58.Final.jar!/:4.1.58.Final]
    at io.netty.handler.ssl.SslHandler.decodeJdkCompatible(SslHandler.java:1282) ~[netty-handler-4.1.58.Final.jar!/:4.1.58.Final]
    at io.netty.handler.ssl.SslHandler.decode(SslHandler.java:1329) ~[netty-handler-4.1.58.Final.jar!/:4.1.58.Final]
    at io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:508) ~[netty-codec-4.1.58.Final.jar!/:4.1.58.Final]
    at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:447) ~[netty-codec-4.1.58.Final.jar!/:4.1.58.Final]
    at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:276) ~[netty-codec-4.1.58.Final.jar!/:4.1.58.Final]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) ~[netty-transport-4.1.58.Final.jar!/:4.1.58.Final]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) ~[netty-transport-4.1.58.Final.jar!/:4.1.58.Final]
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357) ~[netty-transport-4.1.58.Final.jar!/:4.1.58.Final]
    at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1410) ~[netty-transport-4.1.58.Final.jar!/:4.1.58.Final]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) ~[netty-transport-4.1.58.Final.jar!/:4.1.58.Final]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) ~[netty-transport-4.1.58.Final.jar!/:4.1.58.Final]
    at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:919) ~[netty-transport-4.1.58.Final.jar!/:4.1.58.Final]
    at io.netty.channel.epoll.AbstractEpollStreamChannel$EpollStreamUnsafe.epollInReady(AbstractEpollStreamChannel.java:795) ~[netty-transport-native-epoll-4.1.58.Final-linux-x86_64.jar!/:4.1.58.Final]
    at io.netty.channel.epoll.EpollEventLoop.processReady(EpollEventLoop.java:480) ~[netty-transport-native-epoll-4.1.58.Final-linux-x86_64.jar!/:4.1.58.Final]
    at io.netty.channel.epoll.EpollEventLoop.run(EpollEventLoop.java:378) ~[netty-transport-native-epoll-4.1.58.Final-linux-x86_64.jar!/:4.1.58.Final]
    at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:989) ~[netty-common-4.1.58.Final.jar!/:4.1.58.Final]
    at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74) ~[netty-common-4.1.58.Final.jar!/:4.1.58.Final]
    at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) ~[netty-common-4.1.58.Final.jar!/:4.1.58.Final]
    at java.base/java.lang.Thread.run(Thread.java:834) ~[na:na]

A first intuition was to look inside the server trust store, and for sure, I am trusting the root of the certificate chain used in the client keystore.

*

*Why is it a "bad" certificate?

*Why the client certificate chain is empty? I Build the client keystore with a full chain.

I will be glad if I can understand the root cause of this issue and how to fix it.
Thank you


text:
Q: Showing only a particular div in AngularJS So i have 2 ng-repeats like so:

   {{driver}}

    {{car}} {{driver}}

I would like that when I click on a certain  label that the most inner div (div 3) only show for a specific combination of car and driver. Right now, when i click label it actually affects all the divs. For instance, if i click on driver 1 then it would show all the divs3 that have driver 1. basically it impacts all the drivers 1 for each car. I do not want to use href. I have tried to give a specific id to div 3 and in my controller to activate that specific div; but to no avail. Any input?
details:
Basically, the layout will be x number of divs, x represents the number of cars. So let say i have 7 cars. I will have 7 divs one on top of another. Each div will have 4 labels (if we have  4 drivers). So 7divs containing 4 labels.
So each of those 7 divs contains the 4 labels.
Now, when i click on one driver label of let say div 1 (1 of 6); I want to show that particular inner div3 (div1.div3) without showing the other 6 divs of driver 1. So i want to be able to say for this car, driver 1 has it or does not have it. But right now, it will show me the status of driver 1 for all the cars (7 divs). It shows all the inner divs3.

<div0>
   'driver0'  'driver1' 'driver2' 'driver3'

      <div3>

</div0>
<div1>
   'driver0'  'driver1' 'driver2' 'driver3'

    <div3>
</div1>
<div2>
   'driver0'  'driver1' 'driver2' 'driver3'

    <div3>
</div2>
<div3>
   'driver0'  'driver1' 'driver2' 'driver3'

    <div3>
</div3>
<div4>
   'driver0'  'driver1' 'driver2' 'driver3'

     <div3>
</div4>
<div5>
   'driver0'  'driver1' 'driver2' 'driver3'

    <div3>
</div5>
<div6>
   'driver0'  'driver1' 'driver2' 'driver3'

   <div3>
</div6>

`div0`
`driver0 driver1 driver3 ....`
` -->shared space for content for drivers <---`
`div1`
`driver0 driver1 driver3 ....`
` -->shared space for content for drivers <---`

A:

angular.module('app', []).controller('ctrl', function($scope) {
  $scope.cars = ['car0', 'car1', 'car2', 'car3', 'car4', 'car5', 'car6'];
  $scope.drivers = ['driver0', 'driver1', 'driver2', 'driver3'];
})
.driver {
  cursor: pointer;
  margin-left: 15px;
}
.content {
  margin-left: 30px;
}

    {{car}}

      {{driver}}

        Some content for {{car}}-{{temp.selected}}


text:
Q: Automatically remove unused code with Resharper I clicked "Find Code Issues", then Resharper showed me list of unused classes and methods. But I can't find how to automatically remove all them. List of unused classes and methods contains thousands of lines, so сlicking on each line and delete method manually is not real. How to do it automatically?
I tried to use "Code Cleanup", but it doesn't remove unused classes and methods
The version of Resharper: JetBrains ReSharper 8.2.1 Full Edition Build 8.2.1000.4556 on 2014-05-19T09:12:38

A: Unfortunately Resharper does not provide this feature as it can be unsafe.
To partially automate the deletion you can try installing AutoHotkey. This program will allow you to automate the entry of hotkeys and therefore 'automate' repetitive Resharper tasks like deleting unused code detected by Code Issues.
The following script automatically goes to the next code issue and attempts to 'Safely Delete'. If this takes too long it cancels it with {Escape} as this is generally means Resharper has found a conflict or usage.
#d::
    Loop {
        Send !{Del}
        Sleep, 500
        Send {Enter}
        Sleep, 1000
        Send {Escape}
        Sleep, 500
        Send {F8}
        Sleep, 500
    }
Return

To use this script click on the first item under the Type Or Member is Never Used category then hit the Win-D hot key. The script will then cycle through all the issues deleting the methods which do not have conflicts. To break the loop select outside of Visual Studio & Reload the script.
If you remove the Loop & {Escape} then you can use this as a single shortcut to delete & move to the next issue.


text:
Q: UPDATE by matching ROW_NUMBER with another table? This can be done fine in SQL Server (whereas we can use FROM clause in UPDATE statement). But I'm fairly new to Oracle SQL. The scenario is simple like this. I have 2 tables (having the same number of rows). Now I need to update one column of this table to one column of another table by matching row_number of each table.
I've referenced the Oracle UPDATE and this looks like the most promising approach:
update
(select * from
 (select A1,
         row_number() over (order by A1) as rn from A) d
 join
 (select B1,
         row_number() over (order by B1) as rn from B) v on d.rn = v.rn)
set A1 = B1;

but it threw error saying this:

cannot modify a column which maps to a non key-preserved table

There are some examples involving UPDATE like this but it's not exactly like in my scenario because the matching condition does not involve any existing column of the base table (the table we need to update)

A: A table should ideally have a Primary key or a Unique key in order to identify the rows. And if two tables are considered to be related, either there should be a foreign key linking  each other or a common set of columns which uniquely identify the records. If not, it violates the basic RDBMS principles. row_number() is a function which generates numbers and not a physical key that exists in the table. You should consider changing your design to make use of efficient data extraction methods and simpler queries.
As a workaround, you may use a MERGE statement usingROWID. However, do note that there could be chances where this might not work as expected if the number of rows mismatch or some other scenario I can't think of.
MERGE INTO a
using (SELECT a.a1,
              b.b1,
              a.rid
       FROM   (SELECT a.*,
                      row_number()
                        OVER (
                          ORDER BY a1 ) AS rn,
                      a.rowid           AS rid
               FROM   a) a
              JOIN (SELECT b.*,
                           row_number()
                             OVER (
                               ORDER BY b1 ) AS rn
                    FROM   b) b
                ON ( a.rn = b.rn )) s
ON ( a.rowid = s.rid )
WHEN matched THEN
  UPDATE SET a.a1 = s.b1;

Demo
The reason this is not a straightforward update is because the rows in a table do not have a default ordering. Hence it is essential to have a key like primary key to give us a desired order.

A: You can achieve your desired result by sequence of statements, but there is no direct one statement solution to this:
SOLUTION 1: Alter Table
--alter table to add a column for sequencing
alter table A
add(rownumber number);
alter table B
add(rownumber number);

--add sequencing
update A
set rownumber = rownum;
update B
set rownumber = rownum;

--update Data
update A
set A1 = (select B1 from B where A.rownumber = B.rownumber)

--undo DDL changes
alter table A
drop column rownumber;
alter table B
drop column rownumber;

SOLUTION 2: Use Third Table
CREATE global TEMPORARY TABLE ab
  (
     a1 VARCHAR(10),
     b1 VARCHAR(10)
  )
ON COMMIT DELETE ROWS;

INSERT INTO ab
(SELECT a1,
        b1
 FROM   (SELECT a1,
                Row_number()
                  over (
                    ORDER BY a1) AS rna
         FROM   a) xa
        join (SELECT b1,
                     Row_number()
                       over (
                         ORDER BY b1) AS rnb
              FROM   b) xb
          ON xa.rna = xb.rnb);

UPDATE a
SET    a1 = (SELECT b1
             FROM   ab
             WHERE  ab.a1 = a.a1);

DROP TABLE ab;

Using Oracle Merge would had been a possible solution, if your row_number column was different than column to update, as merge doesn't support updating the  same column used for ON clause.


text:
Q: org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type I am frequently getting the below error while running the application in eclipse. does anyone come across this problem or know how to fix it?
org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [com.employee.service.customfield.impl.EmployeeMapper] is defined: expected single bean but found 0:
The same application works fine in command promot via mvn (maven)
Please let me know how to resolve this.
Thanks.

A: What this error means is that your configuration is different between Eclipse and your command line (probably caused by a difference in the classpath).  If you're running this from Eclipse using a run configuration, you probably need to make some tweaks to the classpath settings either in the run config, or on the project's build path.
As an example, if you've got a spring-mybatis.xml application context file under src/main/resources that defines your EmployeeMapper bean, but Eclipse isn't configured to pick this up as part of the build path, this would cause an error like this (maven will pick up this directory by default)

A: This error occures after I altered the JRE version in Debug Configuration. To handle this get to the classpath tab in the debug configuration. Edit the configuration in user entries. Check the Only include exported entries checkbox.


text:
Q: Where can I find the Xenial source, and instructions on building it into an ISO? (custom install CD for Ubuntu 16.04) I followed LiveCDCustomization and managed to build a distro:
However it only boots with VirtualBox, and this guide is hopelessly out of date. Searching around the net, I found this handy tutorial on
Legacy Bios, UEFI and SecureBoot ready Ubuntu Live image customization

Now I managed to get something sort of working. There are still problems and the guide is not complete.
However the question still remains- where can I find this info?
Where is the source repository for Ubuntu with the build guide?

A: You can find it here
https://launchpad.net/ubuntu/xenial/+package/ubuntu-minimal
Hope it helps, thanks


text:
Q: If $|f'(c)|We have a derivative function $f$ with for every $c$ element of $\mathbb{R}: |f'(c)|<M$. I tried to prove that
prove that $\displaystyle \left|\int_{0}^{1}f(x)\mathrm{d}x-\frac{1}n \sum_{k=0}^{n-1}f\left(\frac{x}n\right)\right|\leq\frac{M}{n}$.
I really have no idea how to start. I'm trying to use integral , derivative, sums ... so my paper is full of definitions but i can't use one. Can someone give me a hint how to start with this question so that i can move on.
I'm really sorry i can't give a proper prove that i have already found but i'm stuck at the beginnin already.

A: Your hypothesis on $f'$ implies that $f$ is Lipschitz
$$|f(x)-f(y)|< M|x-y|\,.$$
You can rewrite the integral splitting the domain in $n$ subinterval of length $1/n$, i.e.
$$\int_0^1 f(x)dx = \sum_{k=0}^{n-1}\int_{\frac{k}{n}}^{\frac{k+1}{n}}f(x)dx\,.$$
So you get
$$\left|\int_{0}^{1}f(x)dx-1/n \sum_{k=0}^{n-1}f(k/n)\right|\leq \sum_{k=0}^{n-1}\left|\int_{\frac{k}{n}}^{\frac{k+1}{n}}f(x)dx-\frac{1}{n}f(k/n)\right|\leq\sum_{k=0}^{n-1}\int_{\frac{k}{n}}^{\frac{k+1}{n}}\left|f(x)-f(k/n)\right|dx\,.$$
Using the Lipschitz property you have
$$\left|f(x)-f(k/n)\right|< M|x-k/n|$$
and since $x\in[k/n,(k+1)/n]$ it follows that
$$\left|f(x)-f(k/n)\right|< M/n\,.$$
So you conclude
$$\left|\int_{0}^{1}f(x)dx-1/n \sum_{k=0}^{n-1}f(k/n)\right|< \sum_{k=0}^{n-1}\int_{\frac{k}{n}}^{\frac{k+1}{n}}\frac{M}{n}dx=\sum_{k=0}^{n-1}\frac{M}{n^2}=\frac{M}{n}\,.$$


text:
Q: Series of Ajax request doesn't wait for finish I have series of ajax calls, I want that when the calls get completed the page reloads , I am doing this
function verifyFrnds() {
    var boxes = $(".matchFrnds:checked").length;
    //alert(boxes);
    var call = 1;
    $(".matchFrnds").each(function (index) {
        if ($(this).is(':checked')) {
            call++;
            var sendData = $(this).val();
            $.post('AJAX PAGE', {
                sendData: sendData
            }, function (data) {
                //window.location.reload();
            });
            //alert(call);
            //alert(call + ' ' + boxes + ' ' + (call >= boxes));
            if (call >= boxes) {
                // window.location.reload();
                alert("I am executed");
            }
        }
    });
}

so If I do alert, then all the ajax calls are exexuted and I am shown an alert message, but If I do window.localtion.reload() then after few ajax calls the page get reloaded, which should be reloaded after ALL calls. My main purpose is to reload the page when all calls are done.Any idea what I am doing wrong.
There is already a question on SO but it didn't help me much.

A: Try using $.when:
function verifyFrnds() {
    var deferreds = []; //using an array to save promise interfaces
    $(".matchFrnds").each(function (index) {
        if ($(this).is(':checked')) {
            var sendData = this.value;
            //we push each request in array (returned promise interface)
            deferreds.push($.post('AJAX PAGE', {
                sendData: sendData
            }));
        }
    });
    //as $.when only accept deferred(promise) as arguments, we need to apply $.when to each promise of array
    $.when.apply(null, deferreds).done(function () {
        alert("I am executed once all requests done (success)");
        window.location.reload();
    });
}

A: You could chain your ajax call using $.then if you need to do it sequentially. Like this:
function verifyFrnds() {
    var d = jQuery.Deferred();
    var p=d.promise();

    $(".matchFrnds:checked").each(function (index) {//instead of .matchFrnds
        if ($(this).is(':checked')) {

            var sendData = $(this).val();
            p.then($.post('AJAX PAGE', {
                sendData: sendData
              }, function (data) {
                //window.location.reload();
              })
            );
        }
    });

    p.then(function(){
         alert("I am executed");
    });
    d.resolve();
}

Note that for jQuery prior to 1.8, you have to use .pipe instead of .then. Also check your code, I think there is a mistake, it should be $(".matchFrnds:checked").each( instead of  $(".matchFrnds").each(

A: Just like A. Wolff said, use jQuery.when and jQuery.then.
Another alternative is: call a method on ajax finish ( jqXHR method always ) . Check if call >= boxes ( or whatever condition you like ) in that method. For me, this is a bit easy to understand as compared to another solution.
function verifyFrnds() {
    var boxes = $(".matchFrnds:checked").length;
    //alert(boxes);
    var call = 1;
    $(".matchFrnds").each(function (index) {
        if ($(this).is(':checked')) {
            //call++; Move it to .always Thanks for pointing out Khanh
            var sendData = $(this).val();
            $.post('AJAX PAGE', {
                sendData: sendData
            }, function (data) {
                //window.location.reload();
            }).always ( function() {
                // This method will be called on ajax completion. be it a failure or success.
                // see .done ( for success only )  ; .fail ( for failure only )
                call++;
                if (call >= boxes) {
                  // window.location.reload();
                   alert("I am executed");
                }
            }   ;

        }
    });
}

For more on jqXHR object. Read: http://api.jquery.com/jQuery.ajax/#jqXHR

A: You should increment call not after the if, but in the success of your ajax calls.
I advice you to put the reload call in a function you call with setInterval and not in the success ajax returns.


text: Q: How can you animate new added path data? I am using SVG <path/> to plot x and y values. I am receiving new values and want to add them to the path with a smooth animation. How can I achieve this, or is it even possible to do such kind of things with SVG? Like this example below:


text:
Q: Mapping scope to profileFields I'm using Passport and Passport-Facebook Strategy.
There are two options we can pass:
"scope": ["email", "user_about_me", "..."]

and
profileFields: ["id", "emails", "..."]

Is there a map somewhere online where i can find out which profileFields i can access for each scope added?
Example:
"scope": ["user_about_me"]

I have tried
profileFields: ["about_me", "user_about_me"]

none of the profileFields work
So here are the possible scopes i can ask permission for:
https://developers.facebook.com/docs/facebook-login/permissions/v2.5


text:
Q: List of Services for SQL Server 2012 Express I recently installed VS2013 Preview onto a clean OS and I'm trying to figure out if SQL Server Express 2012 got installed.  Unfortunately, when I look in Control Panel->Administrative Tools->Services, the only thing I see mentioning SQL is the "SQL Server VSS Writer"
Can someone tell me what entries I should see in Control Panel->Administrative Tools->Services after a successful installation of SQL Server Express?
Ideally, both SQL Server Express and SQL Server Management Studio would have been installed on my PC when I installed VS2013 Preview but that doesn't seem to be the case for me.
NOTEs:

*

*I see a bunch of SQL Server Entries in Control Panel->Programs and Features but when I try to connect to [ComputerName]\SQLExpress via the SQL Editor of VS2013 Preview, I get a can't connect error.

*If I remember correctly, a default installation of VS2010 Pro will also install a copy of SQL Sever Express, so I would expect a VS2013 installation to do the same

A: I just installed SQL Server 2012 Express (SSE) on the mentioned machine and now I see the following SQL related entries under Control Panel->Administrative Tools->Services:

*

*SQL Server (SQLEXPRESS) - Running

*SQL Server Agent (SQLEXPRESS) - Disabled

*SQL Server Browser - Disabled

*SQL Server VSS Writer - Running (Was on PC Before Installing SSE 2012)
Now I can connect to [ComputerName]\SQLExpress via the SQL Editor of VS2013 Preview; whereas before, I could not.
Please feel free to correct me if I have missed a critical service for a minimal install of SSE 2012 onto Windows 8.1 Preview.  In addition, I'm not entirely sure that the SQL Server VSS Writer Service is necessary, but I don't have time to verify that right now.


text:
Q: Responsive code is not working in mobile with fullpage.js I am using fullpage.js on my page and it's working. I am getting on issues on a mobile device. I mean I added some responsive code for mobile devices but it's not working.

$(document).ready(function() {

  //initialising fullpage.js in the jQuery way
  $('#fullpage').fullpage({
    sectionsColor: ['#ff5f45', '#0798ec', '#fc6c7c', '#fec401'],
    navigation: true,
    slidesNavigation: true,
  });
});
@media all and (max-width: 768px) {
  .a-herosliderContent h2 {
    font-size: 80px;
  }
  .a-herosliderContent p {
    font-size: 40px;
  }
}
<link rel="stylesheet" type="text/css" href="https://alvarotrigo.com/fullPage/fullpage.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,

About Us

Lorem ipsum dolor sit amet,

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,

View Products

Lorem ipsum dolor sit amet,

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,

View Services

A: I remove this lines

<link rel="stylesheet" type="text/css" href="https://alvarotrigo.com/fullPage/fullpage.css" />

and I added these lines to your code:

<link rel="stylesheet" type="text/css"
    href="https://cdnjs.cloudflare.com/ajax/libs/fullPage.js/3.0.9/fullpage.min.css" />

I hope I've been helpful
Example:

<!DOCTYPE html>

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

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">

    <link rel="stylesheet" type="text/css"
        href="https://cdnjs.cloudflare.com/ajax/libs/fullPage.js/3.0.9/fullpage.min.css" />

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut
                        labore et dolore magna aliqua. Ut enim ad minim veniam,

About Us

Lorem ipsum dolor sit amet,

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut
                        labore et dolore magna aliqua. Ut enim ad minim veniam,

View Products

Lorem ipsum dolor sit amet,

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut
                        labore et dolore magna aliqua. Ut enim ad minim veniam,

View Services


text:
Q: How to simulate random point following multivariate t distribution? If X is a multivariate t random variable with mean=[1,2,3,4,5] and a covariance matrix C, how to simulate points in matlab? I try mvtrnd in matlab, but clearly the sample mean does not give mean close to [1,2,3,4,5]. Also, when I test three simple examples, say X1 with mean 0 and C1=[1,0.3;0.3,1], X2 with mean 0 and C2=[0.5,0.15;0.15,0.5] and X3 with mean 0 and C3=[0.4,0.12;0.12,0.4] and use mvtrnd(C1,3,1000000), mvtrnd(C2,3,1000000) amd mvtrnd(C2,3,1000000) respectively, I find the sample points in each case give nearly the correlation matrix [1,0.3;0.3,1] but the sample covariance computed all give near [3,1;1,3]. Why and how to fix it?

A: The Mean
The t distribution has a zero mean unless you shift it. In the documentation for mvtrnd:

the distribution of t is that of a vector having a multivariate normal
  distribution with mean 0, variance 1, and covariance matrix C, divided
  by an independent chi-square random value having df degrees of
  freedom.

Indeed, mean(X) will approach [0 0] for X = mvtrnd(C,df,n); as n gets larger.
The Correlation
Matching the correlation is straightforward as it addresses a part of the relationship between the two dimensions of X.
% MATLAB 2018b
df = 5;                        % degrees of freedom
C = [0.44 0.25; 0.25 0.44];    % covariance matrix
numSamples = 1000;

R = corrcov(C);                % Convert covariance to correlation matrix
X = mvtrnd(R,df,numSamples);   % X ~ multivariate t distribution

You can compare how well you matched the correlation matrix R using corrcoef or corr().
corrcoef(X)               % Alternatively, use corr(X)

The Covariance
Matching the covariance is another matter. Admittedly, calling cov(X) will reveal that this is lacking. Recall that the diagonal of the covariance is the variance for the two components of X. My intuition is that we fixed the degrees of freedom df, so there is no way to match the desired variance (& covariance).

A useful function is corrcov which  converts a covariance matrix into a correlation matrix.
Notice that this is unnecessary as the documentation for mvtrnd indicates

C must be a square, symmetric and positive definite matrix. If its
  diagonal elements are not all 1 (that is, if C is a covariance matrix
  rather than a correlation matrix), mvtrnd rescales C to transform it
  to a correlation matrix before generating the random numbers.


text:
Q: Is there an idiomatic way to convert a Class to an Object when the class relies on an implicit? I'm new to Scala.
I have a series of test classes that perform UI tests, and a series of classes that contain reusable helper methods.
Example Test Class:
class MyCoolTestClass extends FreeSpec {

    //Note:  This driver needs to be configurable by the test in some way.
    implicit val driver:WebDriver = new ChromeDriver()

    val myCoolPage = new MyCoolPage

    //Tests below rely on myCoolPage methods
}

Example Helper Class:
class MyCoolPage(implicit driver:WebDriver) {
    def clickElement1(){
     //relies on driver
    }
    def assertElement2Enabled(){
     //relies on driver
    }
}

Now, none of the helper classes actually have mutable state.  This makes me want to convert them from classes to objects.
However, the only way I can figure out how to do this is to add an implicit WebDriver argument to every method.  That works, but it's ugly.  Are there any more concise ways to achieve what I want here?  Alternatively, is there a more idiomatic way to organize this Test Class / Helper Method relationship entirely?

A: You can change your help classes into objects and still provide an implicit value to member methods.
object MyCoolPage {

  private val driver :WebDriver = implicitly[WebDriver]

  def clickElement1() = ???          //relies on driver
  def assertElement2Enabled() = ???  //relies on driver
}

But then the implicit declaration has to move out of the test class. Two possibilities come to mind: the WebDriver object...
object WebDriver {
  implicit val wd :WebDriver = new ChromeDriver()
  ...

...or in a dedicated object.
object MyCoolPage {
  import MyTestImplicits._
  private val driver :WebDriver = implicitly[WebDriver]
  ...

All in all, I'm not convinced it's going to be worth the effort.

A: Consider turning MyCoolPage into a trait with an abstract implicit driver field like so
trait MyCoolPage {
  implicit val driver: WebDriver

  def clickElement1() = {
    //relies on driver
  }

  def assertElement2Enabled(){
    //relies on driver
  }
}

Then have MyCoolTestClass extend MyCoolPage and override driver field with custom-configured driver as follows
class MyCoolTestClass extends FreeSpec with MyCoolPage {
  override implicit val driver: WebDriver = new ChromeDriver()

  //Tests below rely on myCoolPage methods
}

Now MyCoolTestClass has access to every method from MyCoolPage, and those methods do not need an implicit driver parameter.

A: I'd argue, there is no idiomatic way to convert the classes to objects, as you are asking. And here is my point of view on why:
You declared an attribute driver in MyCoolClass, you are using in the methods. Therefore your class actually has state. The WebDriver is state injected into MyCoolPage. Depending on the implementation of the injected WebDriver, the way method calls are handled may vary.
To overcome this, you'd need to give the WebDriver as implicit argument to each of your methods, as you found out by yourself. However, this would allow to externally replace the driver during runtime. This would violate the Open-Closed-Principle, which I'd argue is even less idiomatic than using your class construct.
If you encounter this problem again in the future, you might try to write the code without the use of implicit. If it still seems like an appropriate way to change class to object, you are probably good to go.

A:
Now, none of the helper classes actually have mutable state. This makes me want to convert them from classes to objects.

But they do have state. Yes, it's immutable, but so is the state of most case classes, Options, Lists... None of them should be converted into objects. I don't think there is a solution which is really better than the one you started with.
However, here is an option: nesting the helper objects in a superclass:
abstract class AbstractTestClass extends FreeSpec {
  // may optionally be implicit or non-abstract
  val driver: WebDriver

  object MyCoolPage {
    def clickElement1(){
      //relies on driver
    }
    def assertElement2Enabled(){
      //relies on driver
    }
  }

  object MyCoolPage2 ...
}

class MyCoolTestClass extends AbstractTestClass {
  override val driver: WebDriver = new ChromeDriver()

  // can use MyCoolPage methods
}

Note that objects are loaded lazily, so if MyCoolTestClass doesn't use MyCoolPage2 it won't pay for it. The trade-off is that all helper classes have to be defined in a single file.


text:
Q: Validate multiple form with one javascript I have a page that has 6 forms that all have a value with the same name 'audit_id_upload'.  Currently I have one of them being validated (I'm just looking for empty values) with...
function validateForm()
{
var x=document.forms["audit_upload"]["audit_id_upload"].value;
if (x==null || x=="")
  {
  alert("Please Select an Audit");
  return false;
  }
}
</script>

Can I adapt this to validate the other forms as well without having to repeat it 5 more times?
Thanks

A: Since you have a input element with audit_id_upload in every form, you could pass the name of your form to this function and use it to validate the item.
function validateForm(fName)
{
   var x=document.forms[fName]["audit_id_upload"].value;
   if (x==null || x=="")
   {
      alert("Please Select an Audit");
      return false;
   }
   return true;
}

and call it on the for onSubmit event.
<form name='f1' onsubmit="return validateForm('f1')">

</form>

<form name='f2' onsubmit="return validateForm('f2')">

</form>

<form name='f3' onsubmit="return validateForm('f3')">

</form>

A: Try this:
<html>
    <script type="text/javascript">
    function test(theform)
    {
        if (theform.thefield.value == "foo") return true;
        else return false;
    }
    </script>
    <body>
        <form action="" onsubmit="return test(this);">
        <input type="text" value="" name="thefield" />
        <input type="submit" />
        </form>
        <form action="" onsubmit="return test(this);">
        <input type="text" value="" name="thefield" />
        <input type="submit" />
        </form>
        <form action="" onsubmit="return test(this);">
        <input type="text" value="" name="thefield" />
        <input type="submit" />
        </form>
    </body>
</html>


text:
Q: How to solve this react native error execute project react native? [enter image description here][1]
this my error
[1]: https://i.stack.imgur.com/eDILQ.png

A: You must update your react native version or update this package because the version of this package is not adequate with react native version.


text:
Q:  tag inside  tag not working After using <input type="hidden" name="contactId" value="<c:out value="${contactForm.contactId}"/>">
My App is not working giving 404 error.
Can any one tell me the reason behind this?
and please tell me the solution this.
Thanks,
Amresh


text:
Q: Weinberg QFT Eqns 2.4.8 & 2.4.10 In Weinbergs QFT book vol 1, pg. 60, equations (2.4.8) and (2.4.10) are respectively
$$U(\Lambda,a)J^{\rho\sigma}U^{-1}(\Lambda,a)={\Lambda_\mu}^\rho {\Lambda_\nu}^\sigma(J^{\mu\nu}-a^\mu P^\nu+a^\nu P^\mu)$$and
$$J^{\rho\sigma}+i[\frac{1}{2}w_{\mu\nu}J^{\mu\nu}-\epsilon_\mu P^\mu,J^{\rho\sigma}]=J^{\rho\sigma}{+w_\mu}^\rho J^{\mu\sigma}+ {w_\nu}^\sigma J^{\rho\nu} - \epsilon^\rho P^\sigma + \epsilon^\sigma P^\rho.$$
I added a term of $J^{\rho\sigma}$on both sides of eqn (2.4.10).
The second equation is derived from the first at by taking infinitesimal Lorentz transformations ${\Lambda^\mu }_\nu={\delta^\mu}_\nu + {w^\mu}_\nu$ and $a^\mu=\epsilon^\mu$.
I tried to prove this myself by taking the infinitesimal inverse Lorentz tranformation as $${({\Lambda^{-1}})^\mu}_\nu={\Lambda_\nu}^\mu={\delta^\mu}_\nu-{w^\mu}_\nu.$$
Substituting the above expression and $a^\mu=\epsilon^\mu$ into the RHS of eqn (2.4.8), I get
$${\Lambda_\mu}^\rho {\Lambda_\nu}^\sigma(J^{\mu\nu}-a^\mu P^\nu+a^\nu P^\mu)=J^{\rho\sigma}-{w^\rho}_\mu J^{\mu\sigma}-{w^\sigma}_\nu J^{\rho\nu}- \epsilon^\rho P^\sigma + \epsilon^\sigma P^\rho.$$
Hence I will get the correct expression for the RHS of eqn (2.4.10) if
$${w^\rho}_\mu=-{w_\mu}^\rho$$
$${w^\sigma}_\nu=-{w_\nu}^\sigma$$
How can I show that the above two expressions are true?


text:
Q: ffmpeg stream video file from ubuntu to youtube I'm trying to create a stream to youtube. I could see how preview button changes into enable state. However it never actually changes from offline.
And it gives me several error. What am I doing wrong?
     ffmpeg -i video.flv -f flv rtmp://a.rtmp.youtube.com/live2/XXXXXX

  ffmpeg version 2.8.11-0ubuntu0.16.04.1 Copyright (c) 2000-2017 the FFmpeg developers

      built with gcc 5.4.0 (Ubuntu 5.4.0-6ubuntu1~16.04.4) 20160609
      configuration: --prefix=/usr --extra-version=0ubuntu0.16.04.1 --build-suffix=-ffmpeg --toolchain=hardened --libdir=/usr/lib/x86_64-linux-gnu --incdir=/usr/include/x86_64-linux-gnu --cc=cc --cxx=g++ --enable-gpl --enable-shared --disable-stripping --disable-decoder=libopenjpeg --disable-decoder=libschroedinger --enable-avresample --enable-avisynth --enable-gnutls --enable-ladspa --enable-libass --enable-libbluray --enable-libbs2b --enable-libcaca --enable-libcdio --enable-libflite --enable-libfontconfig --enable-libfreetype --enable-libfribidi --enable-libgme --enable-libgsm --enable-libmodplug --enable-libmp3lame --enable-libopenjpeg --enable-libopus --enable-libpulse --enable-librtmp --enable-libschroedinger --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libspeex --enable-libssh --enable-libtheora --enable-libtwolame --enable-libvorbis --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx265 --enable-libxvid --enable-libzvbi --enable-openal --enable-opengl --enable-x11grab --enable-libdc1394 --enable-libiec61883 --enable-libzmq --enable-frei0r --enable-libx264 --enable-libopencv
      libavutil      54. 31.100 / 54. 31.100
      libavcodec     56. 60.100 / 56. 60.100
      libavformat    56. 40.101 / 56. 40.101
      libavdevice    56.  4.100 / 56.  4.100
      libavfilter     5. 40.101 /  5. 40.101
      libavresample   2.  1.  0 /  2.  1.  0
      libswscale      3.  1.101 /  3.  1.101
      libswresample   1.  2.101 /  1.  2.101
      libpostproc    53.  3.100 / 53.  3.100
    Input #0, flv, from 'video.flv':
      Metadata:
        major_brand     : qt
        minor_version   : 0
        compatible_brands: qt
        com.apple.quicktime.creationdate: 2017-07-20T21:44:12+0700
        com.apple.quicktime.make: Apple
        com.apple.quicktime.model: iPhone 6s Plus
        com.apple.quicktime.software: 10.3.2
        encoder         : Lavf57.83.100
      Duration: 00:01:15.24, start: 0.000000, bitrate: 4454 kb/s
        Stream #0:0: Video: flv1, yuv420p, 1920x1080, 200 kb/s, 29.97 fps, 29.97 tbr, 1k tbn, 1k tbc
        Stream #0:1: Audio: adpcm_swf, 44100 Hz, mono, s16, 176 kb/s
    Output #0, flv, to 'rtmp://a.rtmp.youtube.com/XXXXXX':
      Metadata:
        major_brand     : qt
        minor_version   : 0
        compatible_brands: qt
        com.apple.quicktime.creationdate: 2017-07-20T21:44:12+0700
        com.apple.quicktime.make: Apple
        com.apple.quicktime.model: iPhone 6s Plus
        com.apple.quicktime.software: 10.3.2
        encoder         : Lavf56.40.101
        Stream #0:0: Video: flv1 (flv) ([2][0][0][0] / 0x0002), yuv420p, 1920x1080, q=2-31, 200 kb/s, 29.97 fps, 1k tbn, 29.97 tbc
        Metadata:
          encoder         : Lavc56.60.100 flv
        Stream #0:1: Audio: mp3 (libmp3lame) ([2][0][0][0] / 0x0002), 44100 Hz, mono, s16p
        Metadata:
          encoder         : Lavc56.60.100 libmp3lame
    Stream mapping:
      Stream #0:0 -> #0:0 (flv1 (flv) -> flv1 (flv))
      Stream #0:1 -> #0:1 (adpcm_swf (native) -> mp3 (libmp3lame))
    Press [q] to stop, [?] for help
    [flv @ 0x162bac0] Failed to update header with correct duration.ate=4125.4kbits/s
    [flv @ 0x162bac0] Failed to update header with correct filesize.
    frame= 2255 fps=114 q=31.0 Lsize=   37863kB time=00:01:15.24 bitrate=4122.0kbits/s
    video:37194kB audio:588kB subtitle:0kB other streams:0kB global

headers:0kB mixing overhead: 0.213941%

A: When streaming a video file you should use the -re option. Otherwise ffmpeg will attempt to encode it as fast as it can.
You can try to stream copy, assuming your file formats and parameters are suitable to do so:
ffmpeg -re -i video.flv -c copy -f flv rtmp://a.rtmp.youtube.com/live2/XXXXXX

Or re-encode:
ffmpeg -re -i video.flv -c:v libx264 -b:v 4000k -maxrate 4000k -bufsize 6000k -pix_fmt yuv420p -g 60 -c:a aac -f flv rtmp://a.rtmp.youtube.com/live2/XXXXXX


text:
Q: Java jar throttled when run by launchd? We have a well functioning launchd plist starting our jar file, but there's a performance issue.  We expect to send a UDP stream every 25ms.  If we run the jar manually on the command line, our output is ~25ms as expected.  However, when run via our launchd configuration, the interval is ~100ms and then jumps to ~190ns after a few minutes.
Things that have been tried...
• Setting the ProcessType
• Using the Nice key in our plist
• Allocating memory via java options
• Increasing heap size via java options
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Debug</key>
    <true/>
    <key>GroupName</key>
    <string>staff</string>
    <key>InitGroups</key>
    <true/>
    <key>KeepAlive</key>
    <true/>
    <key>Label</key>
    <string>org.project</string>
    <key>ProcessType</key>
    <string>Interactive</string>
    <key>ProgramArguments</key>
    <array>
        <string>/usr/bin/java</string>
        <string>-jar</string>
        <string>/var/project/project.jar</string>
        <string>-server</string>
        <string>--interval</string>
        <string>25</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>StandardErrorPath</key>
    <string>/var/project/logs/project.stderr</string>
    <key>StandardOutPath</key>
    <string>/var/project/logs/project.stdout</string>
    <key>UserName</key>
    <string>projectuser</string>
    <key>WorkingDirectory</key>
    <string>/var/project</string>
</dict>
</plist>


text:
Q: Why can variable declarations always overwrite function declarations? No matter whether I define the function after the variable
var a = 1;
function a() {};
typeof a // number

Or if I define the function before the variable
function a() {};
var a = 1;
typeof a // number

the final typeof result is always number
I found some explanation about execution context in http://davidshariff.com/blog/what-is-the-execution-context-in-javascript/
Before executing the function code, create the execution context.
......
Scan the context for variable declarations:
If the variable name already exists in the variable object, do nothing and continue scanning.

but this does not seem to work.
So how can I explain it?

A: It's to do with JavaScript's variable hoisting. Try this instead:
var a = 1;
var a = function() {};
typeof a // function

A: You're implicitly declaring the variable multiple times by using the function statement 'function a() {};', which as noted by others hoists the variable and behaves unexpectedly due to the order that the browser registers the declarations.
Behind the scenes, this statement instantiates a function object and assigns the result to the variable passed as the function name (reference) but this is done before the explicit var declarations are performed, and so that overrides the implicit declaration.  If you just do the following, it will work more intuitively:
var a = 1;
a = function(){};
console.log(typeof a);  // function

This is a better option than the multiple var declaration in the other answer from a logical standpoint because (even though you can), it's not a good practice to declare the variable multiple times anyway.
To specifically answer the 'why' for this question: it's so that you can use these kinds of statements to define functions and use them in your explicit declarations, as in
var a = someFunction();
function someFunction(){ return 'someVal'; }

If the function statements weren't parsed and hoisted first, this wouldn't be possible.

A: As already mentioned, it has to do with the way JavaScript hoisting works. The main issue to notice is that JavaScript will hoist the complete function definition (along with the function body) up to the top, but keeps the variable initialization where it is (only the declaration is hoisted).
So if you write this:
var a = 1;
function a () {
}

it will be translated to:
var a;
function a() {
}
a = 1;

and if you write this:
function a () {
}
var a = 1;

it will be translated to:
function a () {
}
var a;
a = 1;

So no matter what you do, a = 1; will remain at the very bottom.
Please note that the above "translations" should be seen theoretically. JavaScript probably has a way to omit the var a; statement if there is already a function declaration with the same name. And there also might be a defined order (functions get hoisted before variables or the other way around). But all of this doesn't affect the outcome of the variable initialization being the only part that is NOT hoisted at all.


text:
Q: Create string in C where first character is string length This question is related to Concatenate string literal with char literal, but is slightly more complex.
I would like to create a string literal, where the first character of the string is the length of the string, and the second character is a constant. This is how it is being done currently:
const char myString[] =
{
    0x08,
    SOME_8_BIT_CONSTANT,
    'H',
    'e',
    'l',
    'l',
    'o',
    0x00
};

Ideally, I would like to replace it with something like:
const char myString[] = BUILD_STRING(0xAA, "Hello");

I tried implementing it like this:
#define STR2(S) #S
#define STR(S) STR2(S)
#define BUILD_STRING(C, S)  {(sizeof(S)+2), C, S}

const char myString[] = BUILD_STRING(0xAA, "Hello");

but it expands to:
const char myString[] = {(sizeof("Hello")+2), 0xAA, "Hello"};

and the compiler doesn't seem to like mixing numbers and strings.
Is there any way to do this?

A: You could in-place define a structure to hold the prefix and the rest, conveniently initialize it, and then treat the whole struct as a char array (not a strict-aliasing violation because standard C lets you treat any object as a char array).
Technically, you're not guaranteed that the compiler won't insert padding between the prefix and the rest, but in practice you can count on it.
#define BUILD_STRING(C, S)  \
      ((char const*)&(struct{ char const p[2]; char const s[sizeof(S)]; })\
                            { {(sizeof(S)+2), C}, S})

const char *myString = BUILD_STRING(0xAA, "Hello");

#include <stdio.h>
int main()
{
    printf("%d, %#hhX, '%s'\n", myString[0], myString[1], myString+2);
    //PRINTS: 8, 0XAA, 'Hello'
}

Edit:
If you're paranoid about the possibility of padding, here's one way to statically assert none is inserted:
#define BUILD_STRING__(S)  \
      char const p[2]; char const s[sizeof(S)]
#define BUILD_STRING(C, S)  \
      ((char const*)&(struct{BUILD_STRING__(S); \
            _Static_assert(sizeof(S)+2== \
                    sizeof(struct{BUILD_STRING__(S);_Static_assert(1,"");}),""); \
        }){ {sizeof(S)+2, C}, S})

Alternatively, using the first version with the (nonstandard)
__attribute((__packed__)) should do the same.


text:
Q: Reverting to a previous revision using TortoiseSVN What is the easiest way to revert my working copy to a previous revision using Windows TortoiseSVN?
I did not find any "findable" command to do that quickly.

A: Right click on the folder which is under SVN control, go to TortoiseSVN → Show log. Write down the revision you want to revert to and then go to TortoiseSVN → Update to revision....

A: There are several ways to do that. But do not just update to the earlier revision as suggested here.
The easiest way to revert the changes from a single revision, or from a range of revisions, is to use the revision log dialog. This is also the method to use of you want to discard recent changes and make an earlier revision the new HEAD.

*

*Select the file or folder in which you need to revert the changes. If you want to revert all changes, this should be the top level folder.

*Select TortoiseSVN → Show Log to display a list of revisions. You may need to use Show All or Next 100 to show the revision(s) you are interested in.

*Select the revision you wish to revert. If you want to undo a range of revisions, select the first one and hold Shift while selecting the last one. Note that for multiple revisions, the range must be unbroken with no gaps. Right click on the selected revision(s), then select Context Menu → Revert changes from this revision.

*Or if you want to make an earlier revision the new HEAD revision, right click on the selected revision, then select Context Menu → Revert to this revision. This will discard all changes after the selected revision.

You have reverted the changes within your working copy. Check the results, then commit the changes.
All solutions are explained in the "How Do I..." part of the TortoiseSVN docs.

A: I have used the same instructions Stefan used, taken from Tortoise website.
But it's important to click COMMIT right after. I was getting crazy until I realized that.
If you need to make an older revision your head revision do the following:

*

*Select the file or folder in which you need to revert the changes. If you want to revert all changes, this should be the top level folder.

*Select TortoiseSVN → Show Log to display a list of revisions. You may need to use Show All or Next 100 to show the revision(s) you are interested in.

*Right click on the selected revision, then select Context Menu → Revert to this revision. This will discard all changes after the selected revision.

*Make a commit.

A: The Revert command in the context menu ignores your edits and returns the working copy to its previous state.
You may also select the desired revision other than the "Head" when you "CheckOut" from the repository.

A: Here's another method that's unorthodox, but works*.
I recently found myself in a situation where I'd checked in breaking code, knowing that I couldn't update our production code to it until all the integration work had taken place (in retrospect this was a bad decision, but we didn't expect to get stalled out, but other projects took precedence).  That was several months ago, and the integration has been stalled for that entire time.  Along comes a requirement to change the base code and get it into production last week without the breaking change.
Here's what we did:
After verifying that the new requirement doesn't break anything when using the revision before my check in, I made a copy of the working directory containing the new code.  Then I deleted everything in the working directory and checked out the revision I wanted to it.  Then I deleted all the files I'd just checked out, and copied in the files from the working copy.  Then I committed that change, effectively wiping out the breaking change from the repository and getting the production code in place as the head revision.  We still have the breaking change available, but it's no longer in the head revision so we can move forward to production.
*I don't recommend this method, but if you find yourself in a similar situation, it's a way out that's not too painful.

A: In the TortoiseSVN context menu, select 'Update to Revision', enter the desired revision number, and voilà :)


text:
Q: Python iterating over elements of a column in a list of lists Hi all new to python more used to matrix like software
I have a problem with iterating through a list of lists.
I've imported a csv file as a list of lists
['2004', '1', '7', '20', '50', '0', '8.92', '7.63', '9.84', '0.34', '2'],
 ['2004', '1', '7', '21', '0', '0', '9.4', '8.69', '10.04', '0.27', '2'],
 ['2004', '1', '7', '21', '10', '0', '9.14', '8.02', '9.75', '0.29', '2'],
 ['2004', '1', '7', '21', '20', '0', '9.12', '8.11', '9.75', '0.14', '2'],
 ['2004', '1', '7', '21', '30', '0', '9.09', '8.59', '9.75', '0.17', '2'],
 ['2004', '1', '7', '21', '40', '0', '8.85', '8.11', '9.56', '0.16', '2'],
 ['2004', '1', '7', '21', '50', '0', '8.86', '8.11', '9.46', '0.24', '2'],
 ['2004', '1', '7', '22', '0', '0', '8.72', '7.92', '9.36', '0.23', '2'],
 ['2004', '1', '7', '22', '10', '0', '9.01', '7.73', '10.23', '0.35', '2'],
 ['2004', '1', '7', '22', '20', '0', '9.45', '8.4', '10.42', '0.37', '2'],
 ['2004', '1', '7', '22', '30', '0', '9.14', '8.4', '10.13', '0.34', '2'],
 ['2004', '1', '7', '22', '40', '0', '9.04', '8.5', '9.94', '0.25', '2'],
 ...]

each row is a list of elements
I need to extract (filter) the rows of data from the file using 4th column (col 3 starting count at 0) as a criteria i.e. if  any element in 4th column is greater than 3 and less than 5 write that row to a new list and if any 4th column element is greater than 17 and less than 19 write this row to same new list also.
import csv

data = open('imput.csv', 'r')
datareader = csv.reader(data)
dataIn = []
for row in datareader:
dataIn.append(row) # reading in the data as a list of lists

dataFlt = []; #initialise new lists
data_vals = [];

for i in range(0,len(dataIn)):
if dataIn[i][3] >= 3.0 and dataIn[i][3] <= 5.0:
dataFlt.append(i)
elif dataIn[i][3] >= 17.0 and dataIn[i][3] <=19.0:
dataFlt.append(i)

This code runs without an error but returns an empty dataFlt list
Any suggestions greatly appreciated

A: You need to convert your column from a string to a float first:
column = float(dataIn[i][3])
if 3.0 <= column <= 5.0 or 17.0 <= column <= 19.0:
    dataFlt.append(dataIn[i])

I used comparison chaining to simplify your test, and I added the row, not the index, to dataFlt.
Your code could be simplified to filter while reading:
with open('imput.csv', 'r') as data:
    datareader = csv.reader(data)
    dataFlt = [row for row in datareader
               if 3.0 <= float(row[3]) <= 5.0 or 17.0 <= float(row[3]) <= 19.0]

This produces the dataFlt list in one step, and doesn't build a dataIn list at all. If you do need a dataIn list for other purposes, just call list() on the CSV reader:
with open('imput.csv', 'r') as data:
    datareader = csv.reader(data)
    dataIn = list(datareader)

dataFlt = [row for row in dataIn
           if 3.0 <= float(row[3]) <= 5.0 or 17.0 <= float(row[3]) <= 19.0]

A: You are comparing strings to floats, you need to cast to float:
for row in datareader: # just iterate over the datareader
    if  3.0 <= float(row[3]) <=  5.0:
        dataFlt.append(row)
    elif 17.0 <=  float(row[3]) <= 19.0:
        dataFlt.append(row)

Or:
if  3.0 <= float(row[3]) <=  5.0 or  17.0 <=  float(row[3]) <= 19.0:
      dataFlt.append(row)

You can also use filter to only keep the lines you want:
filter(lambda x: 3.0 <= float(x[3]) <= 5.0 or 17.0 <= float(x[3]) <= 19.0  , datareader)


text:
Q: How to merge .txt files in subfolders and name them after in the same way as the main folder using R? I have performed an experiment under different conditions. Each of those condition has its own Folder. In each of those folders, there is a subfolder for each replicate that containts a text file called DistList.txt. This then looks like this, where the folders "C1.1", "C1.2" and so on contain the mentioned .txt files:

Those .txt files then look like this, but their length may vary from only one or two to several hundreds:

Now, I would like to merge those .txt files and create a .csv file out of it in a way that it looks like this:
C1.1  C1.2  C1.3  ...
155   223   996
169   559   999
259   623   1033
2003        2220
4421

Until now, I was able to write a script that takes together all the files and plots the single data in different columns, just as I want it. However, I would like the title of each column to be the name of the main folder I extracted the .txt file of (e.g. C1.1, C1.2, C1.3, C2.1, ...).
So far, I have this script:
fileList <- list.files(path = ".", recursive = TRUE, pattern = "DistList.txt", full.names = TRUE)

listData <- lapply(fileList, read.table)

names(listData) <- gsub("DistList.txt","",basename(fileList))

library(tidyverse)
library(reshape2)

bind_rows(listData, .id = "FileName") %>%
  group_by(FileName) %>%
  mutate(rowNum = row_number()) %>%
  dcast(rowNum~FileName, value.var = "V1") %>%
  select(-rowNum) %>%
  write.csv(file="Result.csv")

This then yields a .csv file like this, where there are just numbers as column headers and not the name I would like to have. This is an extract of the file created, where I have marked the row that should contain the titles as mentioned above (C1.1, C1.2, C1.2, ...):

Is there any possibility to name the columns as I have mentioned above?

A: Perhaps I misunderstood, but why not do this
# Generate some sample data consisting of a list
# of single-column data.frame's
set.seed(2017);
listData <- list(
    C1 = data.frame(V1 = runif(10)),
    C2 = data.frame(V1 = runif(10)),
    C3 = data.frame(V1 = runif(10)))

setNames(bind_cols(listData), names(listData))
#           C1          C2         C3
#1  0.92424261 0.674331481 0.63411352
#2  0.53717641 0.002020766 0.37986744
#3  0.46919565 0.025093514 0.94207403
#4  0.28862618 0.432077786 0.75499369
#5  0.77008816 0.499391912 0.22761184
#6  0.77276871 0.388681932 0.91466603
#7  0.03932234 0.395375316 0.62044504
#8  0.43490560 0.715707325 0.31910458
#9  0.47216639 0.940999879 0.07628881
#10 0.27383312 0.827229161 0.26083932

Explanation: We simply bind the single column of all data.frames in listData and set column names with setNames.
I don't understand why you're doing a bind_rows first, and then later recast from long to wide. The same can be achieved with a single bind_cols.

A: In this case, the line :
names(listData) <- gsub("DistList.txt","",basename(fileList))

has to be replaced by
names(listData) <- basename(dirname(fileList))

so that the the names of the subfolders are used as the headers of the single columns.


text:
Q: What's the use of `!#` in bash? I'm not talking about the UNIX shebang meant to give the path of an interpreter. In fact, the shebang has made it quite hard to google this question successfully...
I'm talking about bash expansion:

*

*!! retrieves the immediately preceding command (akin to the up arrow, but more usable)

*!$ retrieves the last word of the last command

*!# appears to retrieve the current line

But what're actually useful uses of !#?

*

*echo !# expands to echo echo

*echo echo !# expands to echo echo echo echo

*ls !# expands to ls ls.

All of which seem overwhelmingly pointless. All I know about the !# command is what I've learned from using it – I'm not certain that I know its true functionality.

A: As mentioned comments on the question and other answer(s), you can easily find the section of man bash:
!#     The entire command line typed so far.

What isn't made explicit by the man pages or other documentation and perhaps leading you your befuddlement to a useful use for !# is that bash event designators are meant to be used in combination with the word designators and modifiers (found just below event designators on the man page). The use cases also make more sense when chaining commands together with pipes, ; or &/&&
For example:
I could use the substitution modifier to run a script foo.sh against two inputs bar and baz:
$ ./foo.sh bar; !#:s/bar/baz/

expands to form:
./foo.sh bar; ./foo.sh baz;

Or an example from the Docs (R.I.P. Docs) reproduced below shows how to use the word selector :N to select the first argument to the command as typed so far and neatly cd into the just created directory:
$ mkdir backup_download_directory && cd !#:1
mkdir backup_download_directory && cd backup_download_directory

These examples are pretty trivial, but I hope they show how !# could really save somebody some serious redundant typing while crafting powerful one-liners.

A: !# is The entire command line typed so far. From man bash:
Event Designators
   An event designator is a reference to a command line entry in the history list.

   !      Start a history substitution, except when followed by a blank, newline, carriage return,  =  or  (
          (when the extglob shell option is enabled using the shopt builtin).
   !n     Refer to command line n.
   !-n    Refer to the current command line minus n.
   !!     Refer to the previous command.  This is a synonym for `!-1'.
   !string
          Refer to the most recent command starting with string.
   !?string[?]
          Refer  to  the  most recent command containing string.  The trailing ? may be omitted if string is
          followed immediately by a newline.
   ^string1^string2^
          Quick substitution.  Repeat the last command,  replacing  string1  with  string2.   Equivalent  to
          ``!!:s/string1/string2/'' (see Modifiers below).
   !#     The entire command line typed so far.

One example of usage:
$ mkdir foo && cd !#:1

Makes the directory foo and changes to it.


text:
Q: Filled contour polygons from Terrain50 polyline contours I am trying to create filled polygons from the Ordnance Surveys Terrain 50 contour polylines.
I have tried the simple Feature to Polygon tool in ArcGIS 10.4, but this does not bring across the height attributes.
Is there a simple way to quickly create filled polygons? I would like to ideally do it across a large section of the UK.

A: After you have converted the lines to polygons with Feature to Polygon, you can use Spatial Join to join the attributes of the lines to the matching polygons. Set the polygons as Target Features, the lines as Join Features and make sure you use "BOUNDARY_TOUCHES" as match option:


text:
Q: Java string input comparison Figured it out. Thanks guys. I know its not a perfect answer but, I'm new to java.
package Dr._Coles_Practice_Problems;
import java.util.Scanner;
public class GpaCalc {
public static void main(String[] args) {

   // Needed variables

    double credits = 0.0;

    double totalcredits = 0.0;

    double grade = 0.0;

    double qualitypoints = 0;

    int classes;

    String lettergrade;

    Scanner input = new Scanner(System.in);

    System.out.println("Enter the amount of classes for this semester");

    classes = input.nextInt();

    while (classes > 0) {

    System.out.println("Enter the amount of credits for this class");

    credits = input.nextDouble();

    System.out.println("Enter the grade achieved for this class");

    lettergrade = input.next();

        if (lettergrade.equalsIgnoreCase("a")) {

            grade += 4.00;

        }

        if (lettergrade.equalsIgnoreCase("a-")) {

            grade += 3.67;

        }

        if (lettergrade.equalsIgnoreCase("b+")) {

            grade += 3.33;

        }

        if (lettergrade.equalsIgnoreCase("b")) {

            grade += 3.00;

        }

        if (lettergrade.equalsIgnoreCase("b-")) {

            grade += 2.67;

        }

        if (lettergrade.equalsIgnoreCase("c+")) {

            grade += 2.33;

        }

        if (lettergrade.equalsIgnoreCase("c")) {

            grade += 2.00;

        }

        if (lettergrade.equalsIgnoreCase("c-")) {

            grade += 1.67;

        }

        if (lettergrade.equalsIgnoreCase("d+")) {

            grade += 1.33;

        }

        if (lettergrade.equalsIgnoreCase("d")) {

            grade += 1.00;

        }

        if (lettergrade.equalsIgnoreCase("f")) {

            grade += 0.00;

        }

        classes--;

        totalcredits += credits;

    }

     qualitypoints = grade * credits;

    // GPA is calculated via total credits / total quality points
   //of which are calculated by multiplying the credit(s) * the quality point value

    System.out.println("Your total credit(s)are: " + totalcredits);

    System.out.println("Your total quality points are: " + qualitypoints);

    System.out.println("Your GPA is: " + (qualitypoints / totalcredits));
}

}
/*
Bloomsburg University's grading scale
A = 4.00 Superior Attainment
A- = 3.67
B+ = 3.33
B = 3.00 Above Average Attainment
B- = 2.67
C+ = 2.33
C = 2.00 Average Attainment
C- = 1.67
D+=1.33
D = 1.00 Minimum Attainment
F = 0.00 Failure
*/

A:  if (grade.toLowerCase() == "a") {

Since "a" and grade.toLowerCase() are objects (of type String), comparing them wih == compares the objects' references, not the content of the String.
Use equals() method.
if (grade.toLowerCase().equals("a")) {

More over use equalsIgnoreCase  method to ignore the case.
if (grade.equalsIgnoreCase("a")) {

A: In addition to Suresh Atta's answer, I would suggest that you use the method shown below to compare String  :
"a".equals(grade){
  // something
}

The reason being, it protects you against NullPointerExceptions.

A: Object comparison in Java using == goes by object reference, not by content. Use equals() or equalsIgnoreCase() to compare strings, depending on your needs.

A: You're dividing by zero.
Ignoring a portion of your code, you're basically doing this:
while (credits / 3 > 0) {
  credits = credits - 3;
}
grades / credits;

When your while loop finishes, credits will be <=0.

A: As several others have pointed out already, you must use equals() instead of == to compare Strings.
To make your code more compact and readable, you could also use a switch statement:
switch (grade.toLowerCase()) {

    case "a":
        grades += 4.00;
        break;

    case "a-":
        grades += 3.67;
        break;

    /* etc. */

}


text:
Q: Derived functors definition I´m searching for a reference that defines $n^{th}$derived functors in an analogous way to the definition given in Mitchell´s "Theory of Categories" for the $0^{th}$ derived functor of $T$ covariant functor, i.e, $R^0 T$ is the reflection of $T$ in the category of functors that preserves cokernels.
Thanks in advance.

A: The modern way about thinking about derived functors stems from work of Quillen and Verdier in the 1960s and has a very pleasing formulation, albeit at the cost of introducing some fairly sophisticated machinery. I will try to explain this briefly.
Let $\mathcal{A}$ be an abelian category and let $\mathbf{Ch}^{\ge 0}(\mathcal{A})$ to be the category of cochain complexes (concentrated in degrees $\ge 0$). We define a quasi-isomorphism in $\mathbf{Ch}^{\ge 0}(\mathcal{A})$ to be a morphism that induces isomorphisms in cohomology. The derived category $\mathbf{D}^{\ge 0}(\mathcal{A})$ is the localisation of $\mathbf{Ch}^{\ge 0}(\mathcal{A})$ with respect to the quasi-isomorphisms, i.e. the category obtained by freely inverting all quasi-isomorphisms in $\mathbf{Ch}^{\ge 0}(\mathcal{A})$. Under good conditions, the category $\mathbf{D}^{\ge 0}(\mathcal{A})$ has a reasonably explicit description. For instance, if $\mathcal{A}$ is small, then its morphisms are zigzags of morphisms in $\mathbf{Ch}^{\ge 0}(\mathcal{A})$ modulo a certain equivalence relation; or if $\mathcal{A}$ has enough injectives, then there is a Quillen model structure on $\mathbf{Ch}^{\ge 0}(\mathcal{A})$ in which the weak equivalences are precisely the quasi-isomorphisms, and $\mathbf{D}^{\ge 0}(\mathcal{A})$ turns out to be equivalent to the category of degreewise injective cochain complexes with morphisms modulo homotopy.
Now, let $\mathcal{B}$ be an abelian category and let $T : \mathcal{A} \to \mathcal{B}$ be an additive functor. There is an obvious induced functor $T : \mathbf{Ch}^{\ge 0}(\mathcal{A}) \to \mathbf{Ch}^{\ge 0}(\mathcal{B})$, but it need not preserve quasi-isomorphisms. The Quillen–Verdier conception of derived functors, in retrospect, can be identified with certain Kan extensions and should be understood as the "best approximation" of arbitrary functors by functors that preserve quasi-isomorphisms. More precisely, let $\gamma_\mathcal{A} : \mathbf{Ch}^{\ge 0}(\mathcal{A}) \to \mathbf{D}^{\ge 0}(\mathcal{A})$ and $\gamma_\mathcal{B} : \mathbf{Ch}^{\ge 0}(\mathcal{B}) \to \mathbf{D}^{\ge 0}(\mathcal{B})$ be the localising functors. A total right derived functor for $T : \mathbf{Ch}^{\ge 0}(\mathcal{A}) \to \mathbf{Ch}^{\ge 0}(\mathcal{B})$ is then a left Kan extension of $\gamma_\mathcal{B} T$ along $\gamma_\mathcal{A}$, i.e. a functor $\mathbf{R} T : \mathbf{D}^{\ge 0}(\mathcal{A}) \to \mathbf{D}^{\ge 0}(\mathcal{B})$ equipped with a natural transformation $\eta : \gamma_\mathcal{B} T \Rightarrow (\mathbf{R} T) \gamma_\mathcal{A}$ such that, for any other functor $F : \mathbf{D}^{\ge 0}(\mathcal{A}) \to \mathbf{D}^{\ge 0}(\mathcal{B})$ and natural transformation $\alpha : \gamma_\mathcal{B} T \Rightarrow F \gamma_\mathcal{A}$, there is a unique natural transformation $\tilde{\alpha} : \mathbf{R} T \Rightarrow F$ such that $\tilde{\alpha} \gamma_\mathcal{A} \bullet \eta = \alpha$.
This must seem rather abstract and far-removed from old-style derived functors. To see the connection, we must find a way to compute total right derived functors. For this, it is useful to apply the technology of Dwyer, Hirschhorn, Kan, and Smith. We define a  right deformation for $T$ to be a functor $R : \mathbf{Ch}^{\ge 0}(\mathcal{A}) \to \mathbf{Ch}^{\ge 0}(\mathcal{A})$ equipped with a natural quasi-isomorphism $i : \mathrm{id}_{\mathbf{Ch}^{\ge 0}(\mathcal{A})} \Rightarrow R$ such that, for $\mathcal{A}'$ the full subcategory of $\mathbf{Ch}^{\ge 0}(\mathcal{A})$ spanned by the image of $R$, the restriction $T : \mathcal{A}' \to \mathbf{Ch}^{\ge 0}(\mathcal{B})$ preserves quasi-isomorphisms. For instance, if $\mathcal{A}$ is a sufficiently nice abelian category, $R$ could be a functor that sends a cochain complex to a quasi-isomorphic cochain complex of injective objects. (Note that $T : \mathbf{Ch}^{\ge 0}(\mathcal{A}) \to \mathbf{Ch}^{\ge 0}(\mathcal{B})$ always preserves cochain homotopy equivalences, and any quasi-isomorphism of complexes of injectives is a cochain homotopy equivalence.) Regardless, suppose $(R, i)$ is a right deformation for $T$. It is clear that $T R : \mathbf{Ch}^{\ge 0}(\mathcal{A}) \to \mathbf{Ch}^{\ge 0}(\mathcal{B})$ preserves quasi-isomorphisms, so the universal property of $\mathbf{D}^{\ge 0}(\mathcal{A})$ implies there is a unique functor $\mathbf{R} T : \mathbf{D}^{\ge 0}(\mathcal{A}) \to \mathbf{D}^{\ge 0}(\mathcal{B})$ such that $(\mathbf{R} T) \gamma_\mathcal{A} = \gamma_\mathcal{B} T R$. Let $\eta : \gamma_\mathcal{B} T \Rightarrow (\mathbf{R} T) \gamma_\mathcal{A}$ be the natural transformation $\gamma_\mathcal{B} T i$.
Theorem. With notation as above, $(\mathbf{R} T, \eta)$ is an absolute left Kan extension of $\gamma_\mathcal{B} T$ along $\gamma_\mathcal{A}$. In particular, it is a total right derived functor for $T$.
The proof is not hard: it is just a matter of manipulating natural transformations. Hopefully, it is now clear that (when $\mathcal{A}$ is nice enough) the old-style $(R^n T) A$ is just the $n$-th cohomology of the cochain complex $(\mathbf{R} T) A$, where we are regarding objects in $\mathcal{A}$ as cochain complexes concentrated in degree $0$. (This makes sense because cohomology is invariant under quasi-isomorphism by definition!)

A: One can do this using satellites (see nlab) inductively. The classic reference (for module categories, but the same holds in general) is Homological algebra by Cartan-Eilenberg.


text:
Q: MySQL Database Design Questions I am currently working on a web service that stores and displays money currency data.
I have two MySQL tables, CurrencyTable and CurrencyValueTable.
The CurrencyTable holds the names of the currencies as well as their description and so forth, like so:
CREATE TABLE CurrencyTable ( name VARCHAR(20), description TEXT, .... );
The CurrencyValueTable holds the values of the currencies during the day - a new value is inserted every 2 minutes when the market is open. The table looks like this:
CREATE TABLE CurrencyValueTable ( currency_name VARCHAR(20), value FLOAT, 'datetime' DATETIME, ....);
I have two questions regarding this design:
1) I have more than 200 currencies. Is it better to have a separate CurrencyValueTable for each currency or hold them all in one table?
2) I need to be able to show the current (latest) value of the currency. Is it better to just insert such a field to the CurrencyTable and update it every two minutes or is it better to use a statement like:
    SELECT value FROM CurrencyValueTable ORDER BY 'datetime' DESC LIMIT 1
The second option seems slower.. I am leaning towards the first one (which is also easier to implement).
Any input would be greatly appreciated!!
p.s. - please ignore SQL syntax / other errors, I typed it off the top of my head..
Thanks!

A: To your questions:

*

*I would use one table.  Especially if you need to report on or compare data from multiple currencies, it will be incredibly improved by sticking to one table.

*If you don't have a need to track the history of each currency's value, then go ahead and just update a single value -- but in that case, why even have a separate table?  You can just add "latest value" as a field in the currency table and update it there.  If you do need to track history, then you will need the two tables and the SQL you posted will work.
As an aside, instead of FLOAT I would use DECIMAL(10,2).  After MySQL 5.0, this will actually have improved results when it comes to currency handling with rounding.

A: *

*It is better to have one table holding all currencies

*If there is need for historical prices, then the table needs to hold them.  A reasonable compromise in many situations is to split the price table into a full list of historical prices and another table which only has the current prices.

*Using data type float can be troublesome.  Please be sure you know what you are doing.  If not, use a database currency data type.

A: *

*As your webservice is transactional it is better if you'd have to access less tables at the same time. Since you will be reading and writing a lot, I would suggest having a single table.

*Its better to insert a field to the CurrencyTable and update it rather than hitting two tables for a single request.


text:
Q: Analyze CSV data in R I have CSV data as follows:
 code, label, value
 ABC,  len,   10
 ABC,  count, 20
 ABC,  data,  102
 ABC,  data,  212
 ABC,  data,  443
 ...
 XYZ,  len,   11
 XYZ,  count, 25
 XYZ,  data,  782
 ...

The number of data entries is different for each code. (This doesn't matter for my question; I'm just point it out.)
I need to analyze the data entries for each code. This would include calculating the median, plotting graphs, etc. This means I should separate out the data for each code and make it numeric?
Is there a better way of doing this than this kind of thing:
 x = read.csv('dataFile.csv, header=T)
 ...
 median(as.numeric(subset(x, x$code=='ABC' & x$label=='data')$value))
 boxplot(median(as.numeric(subset(x, x$code=='ABC' & x$label=='data')$value)))

A: split and list2env allows you to separate your data.frame x for each code generating one data.frame for each level in code:
list2env(split(x, x$code), envir=.GlobalEnv)

or just
my.list <- split(x, x$code)

if you prefer to work with lists.

A: I'm not sure I totally understand the final objective of your question, do you just want some pointers of what you could do it? because there are a lot of possible solutions.
When you ask: I need to analyze the data entries for each code. This would include calculating the median, plotting graphs, etc. This means I should separate out the data for each code and make it numeric?
The answer would be no, you don't strictly have to. You could use R functions which does this task for you, for example:
x = read.csv('dataFile.csv', header=T)

#is it numeric?
class(x$value)
# if it is already numeric you shouldn't have to convert it,
# if it strictly numeric I don't know any reason why it
# should be read as strings but it happens.

aggregate(x,by=list(x$code),FUN="median")

boxplot(value~code,data=x)
# and you can do ?boxplot to look into its options.