text:
Q: SSL certificate Error with App Transport Security I have created Hybrid Mobile app with the support of cordova.
In this project I trying to access https server, which has SSL certificate for security.
On emulate the app I am getting following two errors on Xcode7.2.
CFNetwork SSLHandshake failed (-9824)
NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9824)

I tried following keys in info.plist not working.

How to access https from hybrid mobile app using cordova?
I run nscurl --ats-diagnostics --verbose https://XXX.XXXX.XXX anf got following result,
Starting ATS Diagnostics

Configuring ATS Info.plist keys and displaying the result of HTTPS loads to https://xxxxxx.xxxxxx.xxx.
A test will "PASS" if URLSession:task:didCompleteWithError: returns a nil error.
================================================================================

Default ATS Secure Connection
---
ATS Default Connection
ATS Dictionary:
{
}
2017-03-20 19:27:19.190 nscurl[16582:163070] CFNetwork SSLHandshake failed (-9824)
2017-03-20 19:27:19.191 nscurl[16582:163070] NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9824)
Result : FAIL
Error : Error Domain=NSURLErrorDomain Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made." UserInfo={_kCFStreamErrorCodeKey=-9824, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, NSUnderlyingError=0x7fbdf341b6f0 {Error Domain=kCFErrorDomainCFNetwork Code=-1200 "(null)" UserInfo={_kCFStreamPropertySSLClientCertificateState=0, _kCFNetworkCFStreamSSLErrorOriginalValue=-9824, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9824}}, NSLocalizedDescription=An SSL error has occurred and a secure connection to the server cannot be made., NSErrorFailingURLKey=https://xxxxxx.xxxxxx.xxx/, NSErrorFailingURLStringKey=https://xxxxxx.xxxxxx.xxx/, _kCFStreamErrorDomainKey=3}
---

================================================================================

Allowing Arbitrary Loads

---
Allow All Loads
ATS Dictionary:
{
    NSAllowsArbitraryLoads = true;
}
Result : PASS
---

================================================================================

Configuring TLS exceptions for xxxxxx.xxxxxx.xxx

---
TLSv1.2
ATS Dictionary:
{
    NSExceptionDomains =     {
        "xxxxxx.xxxxxx.xxx" =         {
            NSExceptionMinimumTLSVersion = "TLSv1.2";
        };
    };
}
2017-03-20 19:27:19.612 nscurl[16582:163070] CFNetwork SSLHandshake failed (-9824)
2017-03-20 19:27:19.612 nscurl[16582:163070] NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9824)
Result : FAIL
Error : Error Domain=NSURLErrorDomain Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made." UserInfo={_kCFStreamErrorCodeKey=-9824, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, NSUnderlyingError=0x7fbdf360c3c0 {Error Domain=kCFErrorDomainCFNetwork Code=-1200 "(null)" UserInfo={_kCFStreamPropertySSLClientCertificateState=0, _kCFNetworkCFStreamSSLErrorOriginalValue=-9824, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9824}}, NSLocalizedDescription=An SSL error has occurred and a secure connection to the server cannot be made., NSErrorFailingURLKey=https://xxxxxx.xxxxxx.xxx/, NSErrorFailingURLStringKey=https://xxxxxx.xxxxxx.xxx/, _kCFStreamErrorDomainKey=3}
---

---
TLSv1.1
ATS Dictionary:
{
    NSExceptionDomains =     {
        "xxxxxx.xxxxxx.xxx" =         {
            NSExceptionMinimumTLSVersion = "TLSv1.1";
        };
    };
}
2017-03-20 19:27:19.669 nscurl[16582:163070] CFNetwork SSLHandshake failed (-9824)
2017-03-20 19:27:19.669 nscurl[16582:163070] NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9824)
Result : FAIL
Error : Error Domain=NSURLErrorDomain Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made." UserInfo={_kCFStreamErrorCodeKey=-9824, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, NSUnderlyingError=0x7fbdf3727cf0 {Error Domain=kCFErrorDomainCFNetwork Code=-1200 "(null)" UserInfo={_kCFStreamPropertySSLClientCertificateState=0, _kCFNetworkCFStreamSSLErrorOriginalValue=-9824, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9824}}, NSLocalizedDescription=An SSL error has occurred and a secure connection to the server cannot be made., NSErrorFailingURLKey=https://xxxxxx.xxxxxx.xxx/, NSErrorFailingURLStringKey=https://xxxxxx.xxxxxx.xxx/, _kCFStreamErrorDomainKey=3}
---

---
TLSv1.0
ATS Dictionary:
{
    NSExceptionDomains =     {
        "xxxxxx.xxxxxx.xxx" =         {
            NSExceptionMinimumTLSVersion = "TLSv1.0";
        };
    };
}
2017-03-20 19:27:19.725 nscurl[16582:163070] CFNetwork SSLHandshake failed (-9824)
2017-03-20 19:27:19.726 nscurl[16582:163070] NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9824)
Result : FAIL
Error : Error Domain=NSURLErrorDomain Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made." UserInfo={_kCFStreamErrorCodeKey=-9824, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, NSUnderlyingError=0x7fbdf371abe0 {Error Domain=kCFErrorDomainCFNetwork Code=-1200 "(null)" UserInfo={_kCFStreamPropertySSLClientCertificateState=0, _kCFNetworkCFStreamSSLErrorOriginalValue=-9824, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9824}}, NSLocalizedDescription=An SSL error has occurred and a secure connection to the server cannot be made., NSErrorFailingURLKey=https://xxxxxx.xxxxxx.xxx/, NSErrorFailingURLStringKey=https://xxxxxx.xxxxxx.xxx/, _kCFStreamErrorDomainKey=3}
---

================================================================================

Configuring PFS exceptions for xxxxxx.xxxxxx.xxx

---
Disabling Perfect Forward Secrecy
ATS Dictionary:
{
    NSExceptionDomains =     {
        "xxxxxx.xxxxxx.xxx" =         {
            NSExceptionRequiresForwardSecrecy = false;
        };
    };
}
2017-03-20 19:27:19.784 nscurl[16582:163070] CFNetwork SSLHandshake failed (-9801)
2017-03-20 19:27:19.785 nscurl[16582:163070] NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9801)
Result : FAIL
Error : Error Domain=NSURLErrorDomain Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made." UserInfo={_kCFStreamErrorCodeKey=-9801, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, NSUnderlyingError=0x7fbdf354f3d0 {Error Domain=kCFErrorDomainCFNetwork Code=-1200 "(null)" UserInfo={_kCFStreamPropertySSLClientCertificateState=0, _kCFNetworkCFStreamSSLErrorOriginalValue=-9801, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9801}}, NSLocalizedDescription=An SSL error has occurred and a secure connection to the server cannot be made., NSErrorFailingURLKey=https://xxxxxx.xxxxxx.xxx/, NSErrorFailingURLStringKey=https://xxxxxx.xxxxxx.xxx/, _kCFStreamErrorDomainKey=3}
---

================================================================================

Configuring PFS exceptions and allowing insecure HTTP for xxxxxx.xxxxxx.xxx

---
Disabling Perfect Forward Secrecy and Allowing Insecure HTTP
ATS Dictionary:
{
    NSExceptionDomains =     {
        "xxxxxx.xxxxxx.xxx" =         {
            NSExceptionAllowsInsecureHTTPLoads = true;
            NSExceptionRequiresForwardSecrecy = false;
        };
    };
}
2017-03-20 19:27:19.843 nscurl[16582:163070] CFNetwork SSLHandshake failed (-9801)
2017-03-20 19:27:19.908 nscurl[16582:163070] CFNetwork SSLHandshake failed (-9801)
2017-03-20 19:27:19.962 nscurl[16582:163070] CFNetwork SSLHandshake failed (-9801)
2017-03-20 19:27:19.962 nscurl[16582:163070] NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9801)
Result : FAIL
Error : Error Domain=NSURLErrorDomain Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made." UserInfo={_kCFStreamErrorCodeKey=-9801, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, NSUnderlyingError=0x7fbdf3488c30 {Error Domain=kCFErrorDomainCFNetwork Code=-1200 "(null)" UserInfo={_kCFStreamPropertySSLClientCertificateState=0, _kCFNetworkCFStreamSSLErrorOriginalValue=-9801, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9801}}, NSLocalizedDescription=An SSL error has occurred and a secure connection to the server cannot be made., NSErrorFailingURLKey=https://xxxxxx.xxxxxx.xxx/, NSErrorFailingURLStringKey=https://xxxxxx.xxxxxx.xxx/, _kCFStreamErrorDomainKey=3}
---

================================================================================

Configuring TLS exceptions with PFS disabled for xxxxxx.xxxxxx.xxx

---
TLSv1.2 with PFS disabled
ATS Dictionary:
{
    NSExceptionDomains =     {
        "xxxxxx.xxxxxx.xxx" =         {
            NSExceptionMinimumTLSVersion = "TLSv1.2";
            NSExceptionRequiresForwardSecrecy = false;
        };
    };
}
2017-03-20 19:27:20.020 nscurl[16582:163070] CFNetwork SSLHandshake failed (-9801)
2017-03-20 19:27:20.021 nscurl[16582:163070] NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9801)
Result : FAIL
Error : Error Domain=NSURLErrorDomain Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made." UserInfo={_kCFStreamErrorCodeKey=-9801, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, NSUnderlyingError=0x7fbdf3534c00 {Error Domain=kCFErrorDomainCFNetwork Code=-1200 "(null)" UserInfo={_kCFStreamPropertySSLClientCertificateState=0, _kCFNetworkCFStreamSSLErrorOriginalValue=-9801, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9801}}, NSLocalizedDescription=An SSL error has occurred and a secure connection to the server cannot be made., NSErrorFailingURLKey=https://xxxxxx.xxxxxx.xxx/, NSErrorFailingURLStringKey=https://xxxxxx.xxxxxx.xxx/, _kCFStreamErrorDomainKey=3}
---

---
TLSv1.1 with PFS disabled
ATS Dictionary:
{
    NSExceptionDomains =     {
        "xxxxxx.xxxxxx.xxx" =         {
            NSExceptionMinimumTLSVersion = "TLSv1.1";
            NSExceptionRequiresForwardSecrecy = false;
        };
    };
}
Result : PASS
---

---
TLSv1.0 with PFS disabled
ATS Dictionary:
{
    NSExceptionDomains =     {
        "xxxxxx.xxxxxx.xxx" =         {
            NSExceptionMinimumTLSVersion = "TLSv1.0";
            NSExceptionRequiresForwardSecrecy = false;
        };
    };
}
Result : PASS
---

================================================================================

Configuring TLS exceptions with PFS disabled and insecure HTTP allowed for xxxxxx.xxxxxx.xxx

---
TLSv1.2 with PFS disabled and insecure HTTP allowed
ATS Dictionary:
{
    NSExceptionDomains =     {
        "xxxxxx.xxxxxx.xxx" =         {
            NSExceptionAllowsInsecureHTTPLoads = true;
            NSExceptionMinimumTLSVersion = "TLSv1.2";
            NSExceptionRequiresForwardSecrecy = false;
        };
    };
}
2017-03-20 19:27:20.358 nscurl[16582:163070] CFNetwork SSLHandshake failed (-9801)
2017-03-20 19:27:20.416 nscurl[16582:163070] CFNetwork SSLHandshake failed (-9801)
2017-03-20 19:27:20.471 nscurl[16582:163070] CFNetwork SSLHandshake failed (-9801)
2017-03-20 19:27:20.471 nscurl[16582:163070] NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9801)
Result : FAIL
Error : Error Domain=NSURLErrorDomain Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made." UserInfo={_kCFStreamErrorCodeKey=-9801, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, NSUnderlyingError=0x7fbdf3530fd0 {Error Domain=kCFErrorDomainCFNetwork Code=-1200 "(null)" UserInfo={_kCFStreamPropertySSLClientCertificateState=0, _kCFNetworkCFStreamSSLErrorOriginalValue=-9801, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9801}}, NSLocalizedDescription=An SSL error has occurred and a secure connection to the server cannot be made., NSErrorFailingURLKey=https://xxxxxx.xxxxxx.xxx/, NSErrorFailingURLStringKey=https://xxxxxx.xxxxxx.xxx/, _kCFStreamErrorDomainKey=3}
---

---
TLSv1.1 with PFS disabled and insecure HTTP allowed
ATS Dictionary:
{
    NSExceptionDomains =     {
        "xxxxxx.xxxxxx.xxx" =         {
            NSExceptionAllowsInsecureHTTPLoads = true;
            NSExceptionMinimumTLSVersion = "TLSv1.1";
            NSExceptionRequiresForwardSecrecy = false;
        };
    };
}
Result : PASS
---

---
TLSv1.0 with PFS disabled and insecure HTTP allowed
ATS Dictionary:
{
    NSExceptionDomains =     {
        "xxxxxx.xxxxxx.xxx" =         {
            NSExceptionAllowsInsecureHTTPLoads = true;
            NSExceptionMinimumTLSVersion = "TLSv1.0";
            NSExceptionRequiresForwardSecrecy = false;
        };
    };
}
Result : PASS
---

================================================================================

A: added following key also in info.plist the issue get resolved.
<key>NSTemporaryExceptionRequiresForwardSecrecy</key>
<false/>


text:
Q: server sent events using servlets I am using a servlet as my server to send updates to my jsp client(Using HTML5 SSE). This is my jsp code
<script type="text/javascript">

    if(typeof(EventSource)!=="undefined")
      {
      var source=new EventSource("server");
      source.onmessage=function(event)
        {
        document.getElementById("news1").innerHTML+=event.data + "<br />";
        };
      }
    else
      {
      document.getElementById("news1").innerHTML="Sorry, your browser does not support server-sent events...";
      }
      </script>

This is my servlet doGet method.
response.setContentType("text/event-stream");

        PrintWriter out = response.getWriter();

        int messagesSent = 0;

            out.print("data: {" + messagesSent++ + "}\n\n");
            out.flush();
            out.close();

This is working fine and server is sending updates approximately in every 3 seconds by default. I want to change this to every 10 minutes. Is it possible? If yes,How?

A: In your response you need to send retry: with the timeout in milliseconds
Therefore you doGet should look like this....
response.setContentType("text/event-stream");

PrintWriter out = response.getWriter();

int messagesSent = 0;

out.print("retry: 600000\n"); //set the timeout to 10 mins in milliseconds
out.print("data: {" + messagesSent++ + "}\n\n");
out.flush();
out.close();

See HTML5Rocks.com for more info an the EventSource object.

A: The above solution does not work with Chrome because of the ContentType.
Chrome expects this:
response.setContentType("text/event-stream;charset=UTF-8");

Find a sample googling "milestonenext HTML5 Server-Sent Events Sample with Java Servlet as Event Server"

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ways to generate database errors for exception handling I am writing java code to do database operations using JPA. i.e. getTransaction, getResultList, setFirstResult, setMaxResults, begin, commit, flush, clear, ...
My question is, even though I can wrap my codes in try catch blocks, I still need ways to generate exception to test if my code works.
How would you generate database errors to test your exception handling? Some SQL commands to run on the DB outside java at the same time when the program runs? My target DB is SQL server 2008 R2.
Examples on common errors like locking and "StaleObjectStateException:Row was updated or deleted by another..." would be appreciated.
Thank you!

A: For the StaleObjectStateSession you can write a JUnit test case like
e1 = session1.load(key);
e2 = session2.load(key);
e2.modifyAnything();
e2.update();
e2.commit();
e1.modifyAnything();
e1.update();

Then you get your exception. By the way, the StaleObjectStateSession is a Hibernate exception, NOT a database exception.
For testing a real database exception you can violate a database constraint, for example write a JUnit case where you insert a row with a primary key which already exists or which has a null value in a column which is declared as NOT NULL on the database.
If you want to test only once and you want to avoid the effort for writing a JUnit test case, then you can do it with the eclipse debugging and SQL manipulations:
You set a breakpoint between the load and the commit of the record in your code. When the breakpoint is reached then in SQL you manually remove this record with DELETE FROM table WHERE primary_key =... and commit this modification before you continue execution. (Alternatively you can UPDATE the row, but then do not forget to update the version column too.) Then in Eclipse you continue the execution of the program.
Another idea is to temporarily make a nullable column to not null with ALTER TABLE table MODIFY(column ... NOT NULL). After your test you have to undo this modification. Sure, such a test only should be done on a dedicated test database and not on the productive system.

A: I'd mock the interface-based DAO to create whatever exceptions I wanted.
You are writing interface-based DAOs, aren't you?
I'm not sure that it's practical to try and unit test for each and every exceptional situation that might come up.


text:
Q: Hosting a server behind NAT
So basically my PC is behind NAT.
I have total 3 IP addresses,
1. MY ISP Public Address. (27.106.96.113)
This address has been showed up when I google for "My IP".
2. MY Private Address that My ISP has given me. (172.16.91.141)
This address has been showed up in my router as my Public Address.
3. My actual Private Address. (192.168.0.100)
This IP Address is set for my PC by My Router(192.168.0.1) via DHCP.
I can access my PC locally with this(192.168.0.100) address.
I can access my PC inside My ISP network (People with same ISP as I have) with this(172.16.91.141) address.
However I cannot access my PC globally with this(27.106.96.113) address.
I know this is happening because my ISP having NAT Configuration so my Global IP is useless.
Now I am unable to host Apache(for php) neither Java Servlet Page nor my Counter-Strike 1.6 Game server Globally because of my ISP's NAT.
I tried to find solution for this but failed.
I have my free php host (let's say my.hosting.com) which is Globally accessible .
so I thought if I used Socket Programming in my PHP web host and make connection from my PC to PHP web host (Which is Globally accessible) then I have a tunnel through PHP web host and my PC.
And then I will redirect all internet traffic from my PHP web host to my PC.
so if i redirect all my internet traffic from (my.hosting.com:80) to (192.168.0.100:8080) then I can connect to my server by connecting to my PHP web host.
Now I am new to PHP and never tried socket programming.
This is just my thought and this may sound as foolish if I mistaking the concept of PHP Socket Programming.
Therefore I extremely need help from you guys in order to successfully connect my PC Globally.
Thank you so much for reading this and please help me to solve my problem.
Thank You.

A: So judging by what your trying to achieve, your best bet is to just ask your ISP to create a NAT on a spare TCP port (If they will let you) to NAT that specific traffic to your gateway 172.16.91.141, then you will need create a NAT rule on your router to NAT that traffic (say it was '8080' from your ISP router) and convert you could then convert it back to '80'.
WAN->ISP Router(27.106.96.113 - 8080 to 8080)->Your Router(172.16.91.141 8080 to 80)->Your Web Server(http://192.168.0.100:80)
Your IP address looks to be static as they've only got a block of 254 addresses so you shouldn't have to worry about it changing every so many days:
https://wq.apnic.net/whois-search/static/search.html?query=27.106.96.113

A: In before flame: This is actually no direct answer to the problem described above, but it could solve OPs problem.
Have you ever heard about dynamic DNS https://en.wikipedia.org/wiki/Dynamic_DNS. There are many dyndns providers (also for free) and a lot of internet routers natively support it by providing their public IP to the provider.
Instead of an IP you will get a domain name, like u0815.ddnsprovider.foo which you can use to access your PC through the routers port forwarding machanism.


text:
Q: mail does not reciveing with node mailer smtp In my node.js application I am using nodemailer with MY SMTP configuration.
While working with local machine there is no problem. The mail does receiving while sending from AWS host.
var transporter = nodemailer.createTransport({
host: 'smtp.***.com',
port: 25,
auth: {
    user: '******',
    pass: '******
},
tls: {
    rejectUnauthorized: false
}

});
I did not get any error logs.
Any help?


text:
Q: How to make textarea expand when there is some value I am trying to make textarea expand when I enter some text into it, I am using focus css to make it expand but when I click out of textarea it will get back to default.
Here is my code base:
<DynamicWidthInput
  id="addLoanClause"
  value={addLoanClause}
  type="textarea"
  placeholder=""
  error={showErrors && getError("addLoanClause")}
  onChange={e =>
    handleDynamicStateChange(e, setAddLoanClause)
  }
  size={"xl"}
  rows="5"
/>

and here is my style.css:
.dynamic-textarea {
  text-align: left;
  transition: all .3s ease;
  height: 60px;
}

.dynamic-textarea:focus {
  height: 150px;
  width: 650px !important;
}

How can I achieve feature when there is some text in textarea it will automatically expand? I am using React
Updated and added component DynamicWidthInput.js:
class DynamicWidthInput extends React.Component {
  componentDidMount() {
    const { id, value } = this.props;
    resizable(document.getElementById(id), 16, value);
  }

  componentDidUpdate(prevProps) {
    const { id, value } = this.props;

    if (this.props.value !== prevProps.value) {
      resizable(document.getElementById(id), 16, value);
    }
  }

  render() {
    const { id, placeholder, type, onChange, value, error, size } = this.props;
    if (type === "textarea") {
      return (

          <textarea
            className={`input dynamic-input dynamic-textarea ${size}`}
            id={id}
            onChange={onChange}
            placeholder={placeholder}
            value={value}
            wrap="soft"
            maxLength="1000"
            {...this.props}
          />
          {error &&
{error.message}
}

      );
    }

A: You can change dynamically the rows attribute in the textarea when a change happens.
Here's a Codepen with an example: https://codepen.io/JaKto/pen/qeBpZM


text:
Q: parallelism configuration in trident topology (storm) After reading this and this I'm having difficulties understanding how to configure my trident topology.
Basically my storm application is reading from kafka, doing some data manipulations and finally writing to Cassandra.
Here is how I'm currently building my topology:
private static StormTopology buildTopology() {
// connection to kafka
ZkHosts zkHosts = new ZkHosts(broker_zk, broker_path);
TridentKafkaConfig kafkaConfig = new TridentKafkaConfig(zkHosts, topic);
kafkaConfig.scheme = new RawMultiScheme();
StateFactoryFields[] cassandraStateFactories = createStateFactories();
TransactionalTridentKafkaSpout spout = new TransactionalTridentKafkaSpout(kafkaConfig);
TridentTopology topology = new TridentTopology();
Stream kafkaSpout = topology.newStream("kafkaspout", spout).parallelismHint(1).shuffle();
Stream filterValidatStream = kafkaSpout.each(new Fields("bytes"), new SplitKafkaInput(), EventData.getEventDataFields()).parallelismHint(1);
for (StateFactoryFields stateFactoryFields : cassandraStateFactories) {
    filterValidatStream.groupBy(stateFactoryFields.groupingFields)
        .persistentAggregate(stateFactoryFields.cassandraStateFactor, new Count(), new Fields("count")).parallelismHint(2);
}
logger.info("Building topology");
return topology.build();
}

So I got a spout and a few operations (filter, grouopBy) with parallelismHint.
I don't understant hor to determine the optimal parallelismHint, moreover if I'm setting this value in my code, how does it work in conjunction with storm standard topology configurations such as
topology.max.task.parallelism
topology.workers
topology.acker.executors

Thanks in advance

A: There is an excellent gist by mrflip here that attempts to outline how to tune a storm/trident topology. This should guide you in selecting your parameters (both the ones you have suggested in your question and others you may not have thought of yet).


text:
Q: I need to copy data from json file to Postgress I need to copy data from json file to Postgresql database. I have a json file that have 9000 users with information about them, that looks like this:
"name": "Kathryn", "time_created": 1665335716, "gender": "female", "age": 38, "last_name": "Smith", "ip": "192.168.0.110", "city": "NY", "premium": null,  "birth_day": "01.01", "balance": 55.43255500944704, "user_id": 8676}

I need to copy data from this file to Postgresql. How can I do this by sql or python. Postgresql database is in local docker compose container

A: @George Rybojchuk
check complete sql :
drop table if exists sample_json;
drop table if exists target;
create table sample_json(record json not null);
create table target(name varchar(20),time_created varchar(20));
insert into sample_json(record) values('{"name": "Kathryn", "time_created": 1665335716, "gender": "female", "age": 38, "last_name": "Smith", "ip": "192.168.0.110", "city": "NY", "premium": null,  "birth_day": "01.01", "balance": 55.43255500944704, "user_id": 8676}');
select * from sample_json;
insert into target(name,time_created)
select record->'name',record->'time_created'
from sample_json;

python approach:
import json

if __name__ == '__main__':

    records = [
        '{"name": "Kathryn", "time_created": 1665335716, "gender": "female", "age": 38, "last_name": "Smith", "ip": "192.168.0.110", "city": "NY", "premium": null,  "birth_day": "01.01", "balance": 55.43255500944704, "user_id": 8676}',
        '{"name": "Kathryn1", "time_created": 1665335716, "gender": "female", "age": 38, "last_name": "Smith", "ip": "192.168.0.110", "city": "NY", "premium": null,  "birth_day": "01.01", "balance": 55.43255500944704, "user_id": 8676}',
        '{"name": "Kathryn2", "time_created": 1665335716, "gender": "male", "age": 38, "last_name": "Smith", "ip": "192.168.0.110", "city": "NY", "premium": null,  "birth_day": "01.01", "balance": 55.43255500944704, "user_id": 8676}',

    ]

    for record in records:
        json_data = json.loads(record)

        name = json_data['name']
        gender = json_data['gender']
        print(name, gender)
        # connect postgresql
        # insert into target table


text:
Q: How to store an edittext value in a string array? I am new to Android. Now I am developing a project. My project has 2 edittext, 1 button, and a custom listview. When I click the ADD button, I want to display my edittext data in a custom listview.
MainActivity.java
public class MainActivity extends AppCompatActivity {

Button btn;
EditText edt1,edt2;
ListView itemsListView;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btn=(Button) findViewById(R.id.add_id);
    edt1=(EditText) findViewById(R.id.credit_id);
    edt2=(EditText) findViewById(R.id.gpa_id);
    itemsListView  = (ListView)findViewById(R.id.list_view_items);

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            CustomListAdapter adapter = new
CustomListAdapter(MainActivity.this, generateItemsList());
            itemsListView.setAdapter(adapter);
            edt1.setText("");
            edt2.setText("");
        }
    });
}
private ArrayList<Item> generateItemsList() {

    String itemName=edt1.getText().toString();
    String itemDescription=edt2.getText().toString();
    ArrayList<Item> list= new ArrayList<>();
    Item item=new Item(itemName,itemDescription);
    item.getItemName();
    item.getItemDescription();
    list.add(item);
    return list;
}
}

CustomListAdapter.java
public class CustomListAdapter extends BaseAdapter {

private Context context;
private ArrayList<Item> items;
public CustomListAdapter(Context context, ArrayList<Item> items) {
    this.context = context;
    this.items = items;
}
@Override
public int getCount() {
    return items.size();
}
@Override
public Object getItem(int position) {
    return items.get(position);
}
@Override
public long getItemId(int position) {
    return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder viewHolder;
    if (convertView == null) {
        convertView =
LayoutInflater.from(context).inflate(R.layout.layout_list_view_row_items,
parent, false);
        viewHolder = new ViewHolder(convertView);
        convertView.setTag(viewHolder);
    } else {
        viewHolder = (ViewHolder) convertView.getTag();
    }
    Item currentItem = (Item) getItem(position);
    viewHolder.itemName.setText(currentItem.getItemName());
    viewHolder.itemDescription.setText(currentItem.getItemDescription());
    return convertView;
}
private class ViewHolder {
    TextView itemName;
    TextView itemDescription;
    public ViewHolder(View view) {
        itemName = (TextView)view.findViewById(R.id.text_view_item_name);
        itemDescription =(TextView)view.findViewById(R.id.text_view_item_description);
    }
}
}

A: Corrected your method , please check
private ArrayList<Item> generateItemsList(){
    String itemName=edt1.getText().toString();
    String itemDescription=edt2.getText().toString();
    ArrayList<Item> list=new ArrayList<String>();

    Item item=new Item();
    item.setName(itemName);
    item.setDescription(itemDescription);
    list.add(item);

    return list;
}

this method will return the current item name and item description in a list.
Declare a global arraylist to save multiple entries Like this
public class MainActivity extends AppCompatActivity {

    Button btn;
    EditText edt1, edt2;
    ListView itemsListView;
    ArrayList<Item> list = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn = (Button) findViewById(R.id.add_id);
        edt1 = (EditText) findViewById(R.id.credit_id);
        edt2 = (EditText) findViewById(R.id.gpa_id);
        itemsListView = (ListView) findViewById(R.id.list_view_items);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String itemName = edt1.getText().toString();
                String itemDescription = edt2.getText().toString();

                Item item = new Item(itemName, itemDescription);
                item.getItemName();
                item.getItemDescription();
                list.add(item);
                CustomListAdapter adapter = new
                        CustomListAdapter(MainActivity.this, list);
                itemsListView.setAdapter(adapter);
                edt1.setText("");
                edt2.setText("");
            }
        });
    }
}


text:
Q: How to filter associated HABTM data with FriendsOfCake Search for CakePHP 3 Plugin:  FriendsOfCake/Search
CakePHP: 3.1.4

I'm using the plugin to filter my index.ctp view data with a form.
This similar question:
How to Filter on Associated Data
is about a belongsTo association. My question is specifically about associated HABTM data where my associated table is linked through a joinTable and not directly. The normal setup in the Model like the following is not working in this case:
->value('painting', [
    field' => $this->Paintings->target()->aliasField('id')
)]

My tables are set up like:

*

*Tickets belongsToMany Paintings

*Paintings belongsToMany Tickets

*with joinTable tickets_paintings

Here is the main setup:
class TicketsTable extends Table
{
    public function initialize(array $config)
    {
       ...

       $this->belongsToMany('Paintings', [
        'foreignKey' => 'ticket_id',
        'targetForeignKey' => 'painting_id',
        'joinTable' => 'tickets_paintings'
       ]);
    }

   public function searchConfiguration()
   {
        $search = new Manager($this);

        $search->value('status', [
                'field' => $this->aliasField('active'),
            ])->like('member_name', [
               'field' => $this->Members->target()->aliasField('surname'),
               'filterEmpty' => true
            ])->value('painting', [
              'field' => $this->Paintings->target()->aliasField('id'),  // not working
            ]);

        return $search;

    }

class TicketsController extends AppController
{
    public function index()
    {
    $query = $this->Tickets
        ->find('search',
            $this->Tickets->filterParams($this->request->query))
        ->contain(['Members', 'Paintings', 'Appointments']);

    ...
    }

Everything else is working and the parameters are added to the URL when I filter etc., so I only put in the parts where sth has to be wrong.
After filtering I get an error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Paintings.id' in 'where clause'

The contain works properly when just displaying data from the Paintings table in the Tickets view.
But in the code from the SQL query I can see, that all contained tables (Members, Appoinments) are joined for the query except the Paintings table, so obviously it can not find the column...And I guess it can't really join it directly anyway since they are only connected through the joinTable.
I'm new to CakePHP and I can't really figure out what I'm doing wrong here, so hopefully someone can help me out a bit.
Do I have to use a different syntax in the plugin settings? Do I have to set up my Tables differently? Or how exactly can I tell the query to incorporate the habtm related table in the search?
Thanks!

A: The available search methods rely on the field being available in the main query (hasMany and belongsToMany associations are being being retrieved in separate queries).
While you could join it in manually in the controller, using a callback- or a finder-filter is probably the better approach, that way you can modify the query in the model layer, and you could easily utilize Query::matching() to filter by associated data.
Here's an (untested) example that should give you a hint:
use Cake\ORM\Query;
use Search\Type\Callback; // This changed in master recently
                          // now it's Search\Model\Filter\Callback

// ...

public function searchConfiguration()
{
    $search = new Manager($this);

    $search
        // ...
        ->callback('painting', [
            'callback' => function (Query $query, array $args, Callback $type) {
                return $query
                    ->distinct($this->aliasField('id'))
                    ->matching('Paintings', function (Query $query) use ($args) {
                        return $query
                            ->where([
                                $this->Paintings->target()->aliasField('id') => $args['painting']
                            ]);
                    });
            }
        ]);

    return $search;

}

See also

*

*https://github.com/FriendsOfCake/search/blob/9e12117404f824847b2d1aa093f3d52736b658b4/README.md#types

*https://github.com/FriendsOfCake/search/blob/master/README.md#filters

*Cookbook > Database Access & ORM > Retrieving Data & Results Sets > Filtering by Associated Data


text:
Q: aws elastic load balancer not distributing At work we're trying to set up our load balancer with amazon aws. We have two instances, one instance is made from an ami from the first instance.
We only have time to use the AWS GUI right now.
We also currently have one instance associated with the route 53 DNS. What was happening was once that instance started failing, the load was not rolling over to the new instance.
We then tried using the A address of the load balancer for the Route 53 DNS, but that was not distributing the load either.
Are we doing this completely wrong? Do the Route 53 an ELB need to work in conjunction?
I really appreciate any help with this.
**NOTE at low traffic our health checks work fine and our instances are "In Service"

A: *

*You need to have the route53 domain direct traffic to the ELB. If you have example.com and are trying to route that to the load balancer you need to associate the apex with the load balancer.

To do this, go to the route53 tab. Click your hosted zone and go to record sets. then create a new zone and click yes for alias You then need to associate the hosted zone with your ELB.

*

*Now to get the traffic to fail over correctly you need to be running both instances behind the load balancer (preferably in multiple availability zones) and the ELB will take care of the failover.

To do this, go to the elb section of ec2. Click your load balancer and add instances to it.


text:
Q: Switch from a not enabled button to an enabled one I'm trying to develop a simple "tris game" (user vs. computer).
In this case the app shows a grid made by 9 buttons and they get colored once clicked.
Actually I found some troubles describing "computer's behaviour", in particular I cannot find a way to handle the moment when the computer chooses a button that has been already clicked. Here is a piece of code:
switch (position.get(i)){

                case 1:
                    if (button11.isEnabled()) {

                        button11.setEnabled(false);
                        button11.setBackgroundColor(Color.RED);
                    }else{

                    }
                    break;

                case 2:
                    if (button12.isEnabled()) {

                        button12.setEnabled(false);
                        button12.setBackgroundColor(Color.RED);
                    }
                    break;

Here, the variable "position" is a list that contains the position of the buttons and then, with a switch, controls that the selected button is enabled and, in affermative cases, it provides to get the button colored and never clickable.
Now, I was trying to get some code in the "else" part in case the button is already not clickable (for example the users already clicked it previously).
I was thinking if there were a way to pass from case 1 to case 2 and so on until
I found a button which is still clickable. Any suggestions?

A: you could create an ArrayList and put your buttons inside it then perform a test inside a loop.
example :
 ArrayList<Button> buttonList= new ArrayList<Button>();
 //put your buttons inside the list in order : buttonList.add(button0);...

for(int i=0;i<position.size();i++){

if(buttonsList.get(i).isEnabled()){
                      buttonList.get(i).setEnabled(false);
                      buttonList.get(i).setBackgroundColor(Color.RED);
             }
  }


text:
Q: Mock method which is called inside another method I'm trying to use Powermock to mock calls to a database. Here is an example of what our code looks like:
public class WrapperClass {
    public static SearchUtil searchUtil = new SearchUtil();
}

public class SearchUtil {
    public Record searchForThing(String thing) {
        // Makes a call to a database and returns a record
    }
}

public class TestableClass {
    public void runMethod() {
        // When this is called, it returns null, however based on the debugger, WrapperClass.searchUtil is a mocked object
        WrapperClass.searchUtil.searchForThing("thing");
    }
}

@PrepareForTest(WrapperClass.class)
@PowerMockIgnore({"javax.management.*", "javax.xml.parsers.*", "com.sun.org.apache.xerces.internal.jaxp.*", "ch.qos.logback.*", "org.slf4j.*", "org.apache.xerces.*", "javax.xml.*", "org.xml.sax.*", "org.w3c.dom.*"})
@RunWith(PowerMockRunner.class)
public class MyTest {
    @Test
    public void runMyTest() {
        SearchUtil searchUtil = PowerMockito.mock(SearchUtil.class);
        PowerMockito.mockStatic(WrapperClass.class);
        Whitebox.setInternalState(WrapperClass.class, "searchUtil", searchUtil);
        PowerMockito.doReturn(new SearchRecord()).when(WrapperClass.searchUtil).searchForThing("thing");

        // When the below call is made, a new SearchRecord is returned and is not null
        WrapperClass.searchUtil.searchForThing("thing");

        // Calling the method that calls the searchForThing method, when searchForThing is called inside runMethod, it returns null
        new TestableClass().runMethod();
    }
 }

I know that the static variable and such is definitely not a best practice but right now let's pretend I can't change it. When the call that is mocked is called within the test, it returns a new SearchRecord as expected. When it's called within runMethod it returns null however the searchUtil object is the mocked object as per my debugger. Why does this behavior happen when the call to the stubbed method is nested?

A: Review the following, which should behave as expected.
@PowerMockIgnore({"javax.management.*", "javax.xml.parsers.*", "com.sun.org.apache.xerces.internal.jaxp.*", "ch.qos.logback.*", "org.slf4j.*", "org.apache.xerces.*", "javax.xml.*", "org.xml.sax.*", "org.w3c.dom.*"})
@RunWith(PowerMockRunner.class)
@PrepareForTest(WrapperClass.class, TestableClass.class)
public class MyTest {
    @Test
    public void runMyTest() {
        //Arrange
        Record expected = new SearchRecord();
        String arg = "thing";
        SearchUtil searchUtil = PowerMockito.mock(SearchUtil.class);
        when(searchUtil.searchForThing(arg)).thenReturn(expected);

        // mock all the static members in WrapperClass class
        PowerMockito.mockStatic(WrapperClass.class);
        // use Mockito to set up your expectation
        when(WrapperClass.searchUtil).thenReturn(searchUtil);

        TestableClass subject = new TestableClass();

        //Act
        subject.runMethod();

        //Assert
        //...
    }
 }

Note the flow of the test.
I would also suggest making sure that the argument used in the test matches the one passed by the exercised method because if they do not, then it will also return null because of the mismatched arguments/parameters.
Otherwise you will need to loosen the argument matcher
//...

when(searchUtil.searchForThing(any(String.class))).thenReturn(expected);

//...

You can also review the powermock-mockito docs here for a better understanding of how to use the framework.


text:
Q: MySQL: error when query returns no results? I have a query that looks like this:
SELECT number
            FROM table1
            INNER JOIN table2
            WHERE name = 'stack_overflow' AND table1.id = table2.id
            AND user_id = 5

This returns a number. It does the right thing, but when inside name I pass a name that does not exist in db, PHP gives me an error. This is how I am executing it:
    $stmt = $this->db->prepare($sql);
    $stmt->execute();

    $x = $stmt->fetchColumn();

I always get the correct $x value when the name exists in the table, however when it doesn't, I get the following error:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'name_that_is_not_in_table'

No idea....

A: Try to pass name in this way:
SELECT number
            FROM table1
            INNER JOIN table2
            WHERE name = ? AND table1.id = table2.id
            AND user_id = 5

$stmt = $this->db->prepare($sql);
$stmt->execute(array($name));
$x = $stmt->fetchColumn();

A: Sounds like you need to check how many rows are returned first... if none, notify the user.  If it DOES have a returned row count, then get the name column as you are expecting.
Additionally, you should clarify the alias.column in your queries as anyone new doesn't have to guess which table a given column comes from...  Such as your user_id and name columns.  (and "name" might be a reserved word and cause the choke... so you might want to wrap it in tick marks
`name`


text:
Q: Do I need to open and close a Segger JLink connection when using the dlls to access multiple cores from a single PC process using a licensed SDK Segger allow you to obtain a license for using their JLink SDK.
I am using it to create tooling to allow examination of the state of a new (not yet commercially available) SoC microprocessor that contains multiple cores (multiple ARM cortex M cores and DSPs) with SWD debug H/W.
Segger include a GDB server in their normal software download which can definitely access any single core from a single process.
I do not think Segger makes their SDK UM08002 documentation and code samples public but it demonstrates being able to access a single core (which works fine for me).
All the SDK really is is a set of headers and documentation that allow you call into the already distributed SEGGER JLink dll's (the dll's in the normal software download prompts you for auto updating) so there is no magic happening in the SDK itself; but it is licensed so I can't post any of it here.
What I do not understand is what dll calls must be made to access multiple cores sequentially from within a single process using the SDK.
Do I:

*

*Disconnect and reconnect from the SEGGER every time I wish to access a different core

*Can I switch between cores somehow without opening & closing the JLink connection

*Can I leave the cores halted when switching between cores so the device doesn't 'run off' while I'm looking elsewhere

*Will the core HW & SW debug points remain set & get triggered if I'm looking at a different core and allow me to discover this when I look back at a hopefully now halted core in question? (This may be core implementation dependant of course)

A: Short answer
No, sort of.
Long answer
The Segger JLink dll API is a single target per process API, so that means you can't start talking to another core while the process global state held by the dll is configured to talk to another core.  In order to select the target core you have to inject appropriate initialisation scripts written in Seggers 'not quite sinmple c' scripting language.  In order to change the scripts and ensure they have all run appropriately then you need to close down you connection to the target, set the new scripts and then reopen a connection to the new target core.
It is possible to adjust some details on the fly by executing some commands in a 'key=value' language but you can't do everything you might need to that way.
Recommended approach
What you can do is have multiple process sharing a JLink.
Each process initialised to a specific target core and then they share the JLink automatically on an API cal by API call basis.  For compound, multiple api call, operations you need to serialise these operations using the dll API JLinkARM_Lock() and JLinkArm_Unlock() or you can potentially get processes 'jumping in' during these compound operations and having their behaviour become undefined or unreliable.
They to communicate with multiple target cores you do some inter process communication from your master process to your spawned JLink operation processes.
Remember to include keep alives in you inter process communication so that crashes or debugging doesn't result in a plethora of orphaned or silent processes.


text:
Q: Searching a word this is my code for searching a specific word in txt file but if the word I'm searching for is on first line then it shows, it has found the word but if the word is on other line than line 1 it can't find it. 1 more thing I want to implement this within BufferedReader or FileReader.
 public void searchfile(String word)
      {
       try {

         BufferedReader bf = new BufferedReader(new FileReader("E:\\Books\\OOP\\dictionary\\Dictionary.txt"));
          int linecount = 0;
           String line;

        System.out.println("Searching for " + word + " in file...\n\n");
        while (( line = bf.readLine()) != null)
        {
                 linecount++;

                int indexfound = line.indexOf(word);

                if (line.equals(word)) {

                     System.out.println("Word you are searching for, was found in your file at position " +indexfound+" and line "+linecount);

                }
                else{
                    FileWriter fw = new FileWriter("Dictionary.txt",true);

                       BufferedWriter bw = new BufferedWriter(fw);
                       bw.write("\n");
                           bw.write(word);

                            bw.close();
                       System.out.print("Word was not found\n\n\nYour word has been added to your file");

                           }

                 bf.close();

                         }

           }
         catch (IOException e) {

                       }

           }

A: If it is one word on each line, you can just load each word onto a List<String> object and check if each element is your word. For example:
If you have a space between each word, you can load the file's contents onto a byte[], then use the new String(byte[]) constructor, split the string by the space, and search the array for your word. You can also use this method if something else if splitting the word e.g. a colon.
If there is only one line, I suggest using BufferedReader, because it can read single lines quickly, rather than using String lists or arrays.
After you have obtained your words in any of the above manners, you can then simply search for your word by getting each word in your list, array, or String and using the equals, equalsIgnoreCase, or contains methods.
I wrote a class that does what you want:
package Testers;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.FileReader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

public class FileReading {

    /**
     * Uses a BufferedReader object
     * Reads a line of a file
     * @param file the file to read
     * @return line the line that is read
     * @throws IOException if the file cannot be found, cannot be read or the input stream cannot be closed
     */
    public String readLine(File file) throws IOException{
        String line = "";
        BufferedReader reader = new BufferedReader(new FileReader(file));
        line = reader.readLine();
        reader.close();
        return line;
    }
    /**
     * Uses static methods in the Files class of NIO
     * Reads everything in a file, and puts it in a String
     * @param file the file to read
     * @return a String representing the contents of the file
     * @throws IOException "if an I/O error occurs reading from the stream" (Files.readAllBytes javadoc)
     */
    public String readFileContents(File file) throws IOException {
        String filecontents = "";
        filecontents = new String(Files.readAllBytes(Paths.get(file.toURI())));
        return filecontents;
    }

    /**
     * Uses static methods in the Files class of NIO
     * Gets each individual line in a file, puts it in a list (List<String>)
     * A line is usually defined by {@code System.getProperty("line.separator");}
     * @param file the file to read each line from
     * @return {@code List<String>} representing each line
     * @throws IOException "if an I/O error occurs reading from the file or a malformed or unmappable byte sequence is read" (readAllLines javadoc)
     */
    public List<String> obtainWordsByLine(File file) throws IOException{
        List<String> lines = null;
        lines = Files.readAllLines(Paths.get(file.toURI()));
        return lines;
    }
    /**
     * Obtains each word in a file by reading the contents from a file and splitting it by a character
     * @param file the file to read. {@link #readFileContents(File)}
     * @param split the character to split by
     * @return an array of each word
     * @throws IOException thrown from method {@link #readFileContents(File)}
     */
    public String[] obtainWordsBySplit(File file, char split) throws IOException{
        return obtainWordsBySplit(file, String.valueOf(split));
    }

    /**
     * Obtains each word in a file by reading the contents from a file and splitting it by a string
     * @param file the file to read. {@link #readFileContents(File)}
     * @param split the string to split by
     * @return an array of each word
     * @throws IOException thrown from method {@link #readFileContents(File)}
     */
    public String[] obtainWordsBySplit(File file, String split) throws IOException{
        String contents = readFileContents(file);
        return contents.split(split);
    }

    /**
     * Checks if a string exists in a String[]
     * @param word the word to look for. Assumes that each string in the String[] could EQUAL the word, rather than if it CONTAINS the word. Use {@link #doesWordExist(String, String, boolean)} to see if it CONTAINS it.
     * To obtain a string from a String[], use {@link #toParsableString(String[])}
     * @param contents the array to search for each string in.
     * @param ignoreCase whether to ignore case or not
     * @return If the word is exactly the same (including case) returns true. If the word is a different case and {@code ignoreCase} is true, returns true. Otherwise, if it gets to the end and cannot find the word, returns false.
     */
    public boolean doesWordExist(String word, String[] contents, boolean ignoreCase){
        for(int i = 0; i < contents.length; i++){
            String w = contents[i];
            if(w.equals(word)) return true;//Word exists
            else if (w.equalsIgnoreCase(word)){ //Word exists in different case
                if(ignoreCase) return true;
                else continue;
            }
            else continue; //That word isn't it!
        }
        return false; //Word does not exist
    }

    /**
     * Checks if a string exists in another string. Check is using the CONTAINS method.
     * You can always use this method for a {@code String[]} or {@code List<String>}
     * @param word the word to look for
     * @param contents the contents to look for the word in
     * @param ignoreCase whether to ignore case or not
     * @return If the word is exactly the same (including case) returns true. If the word is a different case and {@code ignoreCase} is true, returns true. Otherwise returns false.
     */
    public boolean doesWordExist(String word, String contents, boolean ignoreCase){
        if(ignoreCase){
            return containsIgnoreCase(word, contents);
        }else{
            return word.contains(contents);
        }
    }

    /**
     * Checks if a string exists in a list of strings.
     * This method is for simplicity. It turns {@code words} into a {@code String[]} and calls {@link #doesWordExist(String, String[], boolean)}.
     * @param word the string to look for
     * @param words the list of strings to look at
     * @param ignoreCase whether to ignore case or not
     * @return If the word is exactly the same (including case) returns true. If the word is a different case and {@code ignoreCase} is true, returns true. Otherwise, if it gets to the end and cannot find the word, returns false.
     */
    public boolean doesWordExist(String word, List<String> words, boolean ignoreCase){
        String[] w = new String[words.size()];
        String contents = "";
        for(int i = 0; i < words.size(); i++){
            contents = contents + words.get(i) + " ";
        }
        w = contents.split(" ");
        return doesWordExist(word, w, ignoreCase);
    }

    /**
     * Turns a String array into a string that can be parsed for the contains method, or other similar methods.
     * This doesn't just have to be used for files, it can be used for anything
     * @param array The array to turn into a string
     * @return the String representing the array
     */
    public String toParsableString(String[] array){
        String parseString = "";
        for(int i = 0; i < array.length; i++){
            parseString = parseString + array[i] + " ";
        }
        return parseString;
    }

    /**
     * Checks if a string contains another string, ignoring case
     * @param word the string to look for
     * @param contents the string to look for the other string in
     * @return If it does contain the word, returns true. Otherwise returns false. Ignoring case.
     */
    private boolean containsIgnoreCase(String word, String contents) {
        String w = word.toLowerCase();
        String c = contents.toLowerCase();
        return c.contains(w);
    }

}


text:
Q: POST request using alamofire 2.0 and Swift 2.0 I try to create a basic function that send a POST request using Alamofire.
@IBAction func createBasicAccount(sender: AnyObject)
{
    var firstNameToSend = firstName.text
    var lastNameToSend = lastName.text
    var mailAddressToSend = mailAddress.text
    var passwordToSend = password.text
    var parametersToSend = [
        "firstName": firstNameToSend,
        "lastName": lastNameToSend,
        "mailAddress": mailAddressToSend,
        "password": passwordToSend
    ]

    print("Account creation")

    Alamofire.request(.POST, postEndpoint, parameters: parametersToSend, encoding: .JSON)
}

But the Alamofire.request won't compile and compiler returns:
Cannot convert value of type '[String : String?]' to expected argument type '[String : AnyObject]?'

I tried:
Alamofire.request(.POST, postEndpoint, parameters: parametersToSend as! AnyObject as? [String : AnyObject], encoding: .JSON)

But fails:
Account creation
Could not cast value of type 'Swift.Dictionary<Swift.String, Swift.Optional<Swift.String>>' (0x11fdb1038) to 'Swift.AnyObject' (0x12035b018).

I'm using Swift 2.0, Xcode 7.0 GM Seed, iOS 8.4 & Alamofire 2.0

A: I think that's a optional type problem. Can you try to add ! to your variables such as:
var parametersToSend = [
        "firstName": firstNameToSend!,
        "lastName": lastNameToSend!,
        "mailAddress": mailAddressToSend!,
        "password": passwordToSend!
    ]

A: THIS IS LATEST VERIOSN CODE OF SWIFT 2.2 HOPE ITS HELOP YOU....
This is latest answer of SWIFT 2.2 VERSION
try this one its helps you....
PARAMETERS:-
    let params : Dictionary = ["YourKEY" : "YourVALUE"]

Post Request_Form:-
Alamofire.request(.POST,"Post Your Url HERE", parameters: params, encoding:.JSON).responseJSON
        {
          response in switch response.result
            {
                  case .Success(let JSON):
         //   print("Success with JSON: \(JSON)")
            //converting json into NSDictionary

            let response = JSON as! NSDictionary
            print(response)

            var array = NSMutableArray!()
            //converting respose form into NSMutableArray formate
            array = response.valueForKey("countryList")as? NSMutableArray

            //example if there is an id
          //  let userId = response.objectForKey("id")!

        case .Failure(let error):
            print("Request failed with error: \(error)")
            }
    }


text:
Q: Changing Bibliography Strings only for Certain References The answers to this question explain how \DefineBibliographyStrings can be used to change the "last visted" text for @online citations.
However, this solution changes the text for all references of this type. I would like to be able to change the text only for certain references.
I have some references to current webpages which I would like to keep as "last visited", however I also have some links to archive.org where I would like this to instead be displayed as "archived on".
Here is a MRE, and the output. I would like the stack exchange reference to prefix the date with "archived on", but the wikipedia reference to remain as the default "visited at".
\documentclass{article}
\usepackage{filecontents}
\begin{filecontents}{citations.bib}
@online{wikipedia,
    author       = {{Wikimedia Foundation}},
    title        = {Wikipedia},
    url          = {https://en.wikipedia.org},
    year         = {2019},
    urldate      = {2019-12-09}
}
@online{stack,
    author       = {{Stack Exchange Inc}},
    title        = {Stack Overflow},
    url          = {https://web.archive.org/web/20100813082822/http://www.stackoverflow.com/},
    year         = {2010},
    urldate      = {2010-08-13}
}
\end{filecontents}
\usepackage[style=authoryear,backend=bibtex,urldate=long]{biblatex}
\addbibresource{citations.bib}

\DefineBibliographyStrings{english}{
  urlseen = {archived on}
}

\begin{document}
Lorem ipsum dolor sit amet \autocite{wikipedia}, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua \autocite{stack}.
\printbibliography
\end{document}

A: This is a straightforward adaptation of moewe's answer to "Custom bib style for entries containing editor" (if this works for you, go upvote it too!).
First, add the following code to your preamble. This will make biblatex write "archived on" for references which include options = {archived}, and the default string otherwise.
% define a new "archivedon" string as an alternative to "urlseen"
\NewBibliographyString{archivedon}
\DefineBibliographyStrings{english}{
    archivedon = {archived on}
}

% for each reference, detect if the "archived" option is used and set the urldate string accordingly
\newtoggle{bib:archived}
\DeclareEntryOption{archived}[true]{%
  \settoggle{bib:archived}{#1}}
\DeclareFieldFormat{urldate}{%
  \mkbibparens{%
    \iftoggle{bib:archived}
      {\bibstring{archivedon}} % "archived" option is on - write "archived on"
      {\bibstring{urlseen}} % "archived" option is off - write "visited on"
    \addcolon\space#1}}

Then you have one or two options, depending on what bibliography backend (bibtex or biber) you use:
a) If you use bibtex or don't want to automate this part, you'll need to edit your .bib file and add options = {archived} to all the references where you want to use "archived on":
@online{stack,
    author  = {{Stack Exchange Inc}},
    title   = {Stack Overflow},
    url     = {https://web.archive.org/web/20100813082822/http://www.stackoverflow.com/},
    year    = {2010},
    urldate = {2010-08-13},
    options = {archived}
}

b) If you use biber, you don't need to edit the .bib file, as it can set the archived option automatically (this doesn't work with bibtex):
% automatically add the "archived" option when reference url contains "archive.org"
\DeclareSourcemap{
  \maps[datatype=bibtex]{
    \map[overwrite]{
      \step[fieldsource=url, match=\regexp{archive\.org},final]
      \step[fieldset=options, append, fieldvalue={archived=true}]
    }
  }
}

MWE for bibtex (requires editing your .bib file to add the archived option to archive.org references):
\documentclass{article}
\usepackage{filecontents}
\begin{filecontents}{citations.bib}
@online{wikipedia,
    author       = {{Wikimedia Foundation}},
    title        = {Wikipedia},
    url          = {https://en.wikipedia.org},
    year         = {2019},
    urldate      = {2019-12-09}
}
@online{stack,
    author       = {{Stack Exchange Inc}},
    title        = {Stack Overflow},
    url          = {https://web.archive.org/web/20100813082822/http://www.stackoverflow.com/},
    year         = {2010},
    urldate      = {2010-08-13},
    options      = {archived}
}

\end{filecontents}
\usepackage[style=authoryear,backend=bibtex,urldate=long]{biblatex}
\addbibresource{citations.bib}

% use "archived on" instead of "visited on" when bib entry includes "options = {archived}"
%   (inspired by https://tex.stackexchange.com/a/265929)
\NewBibliographyString{archivedon}
\DefineBibliographyStrings{english}{
    archivedon = {archived on}
}
\newtoggle{bib:archived}
\DeclareEntryOption{archived}[true]{%
  \settoggle{bib:archived}{#1}}
\DeclareFieldFormat{urldate}{%
  \mkbibparens{%
    \iftoggle{bib:archived}
      {\bibstring{archivedon}}
      {\bibstring{urlseen}}%
    \addcolon\space#1}}
%-----

\begin{document}
Lorem ipsum dolor sit amet \autocite{wikipedia}, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua \autocite{stack}.

\printbibliography
\end{document}

MWE for biber (automatic, no .bib edits needed):
\documentclass{article}
\usepackage{filecontents}
\begin{filecontents}{citations.bib}
@online{wikipedia,
    author       = {{Wikimedia Foundation}},
    title        = {Wikipedia},
    url          = {https://en.wikipedia.org},
    year         = {2019},
    urldate      = {2019-12-09}
}
@online{stack,
    author       = {{Stack Exchange Inc}},
    title        = {Stack Overflow},
    url          = {https://web.archive.org/web/20100813082822/http://www.stackoverflow.com/},
    year         = {2010},
    urldate      = {2010-08-13}
}

\end{filecontents}
\usepackage[style=authoryear,backend=biber,urldate=long]{biblatex} % changed to biber
\addbibresource{citations.bib}

% use "archived on" instead of "visited on" when bib entry includes "options = {archived}"
%   (inspired by https://tex.stackexchange.com/a/265929)
\NewBibliographyString{archivedon}
\DefineBibliographyStrings{english}{
    archivedon = {archived on}
}
\newtoggle{bib:archived}
\DeclareEntryOption{archived}[true]{%
  \settoggle{bib:archived}{#1}}
\DeclareFieldFormat{urldate}{%
  \mkbibparens{%
    \iftoggle{bib:archived}
      {\bibstring{archivedon}}
      {\bibstring{urlseen}}%
    \addcolon\space#1}}
%----------

% for biber only - add the "archived" option automatically when url contains "archive.org"
\DeclareSourcemap{
  \maps[datatype=bibtex]{
    \map[overwrite]{
      \step[fieldsource=url, match=\regexp{archive\.org},final]
      \step[fieldset=options, append, fieldvalue={archived=true}]
    }
  }
}
%-----

\begin{document}
Lorem ipsum dolor sit amet \autocite{wikipedia}, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua \autocite{stack}.

\printbibliography
\end{document}


text:
Q: Write android logcat data to a file I want to dump Android logcat in a file whenever user wants to collect logs. Through adb tools we can redirect logs to a file using adb logcat -f filename, but how can I do this programmatically?

A: Logcat can write directly to a file:
public static void saveLogcatToFile(Context context) {
    String fileName = "logcat_"+System.currentTimeMillis()+".txt";
    File outputFile = new File(context.getExternalCacheDir(),fileName);
    @SuppressWarnings("unused")
    Process process = Runtime.getRuntime().exec("logcat -f "+outputFile.getAbsolutePath());
}

more info on logcat: see http://developer.android.com/tools/debugging/debugging-log.html

A: Here is an example of reading the logs.
You could change this to write to a file instead of to a TextView.
Need permission in AndroidManifest:
<uses-permission android:name="android.permission.READ_LOGS" />

Code:
public class LogTest extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    try {
      Process process = Runtime.getRuntime().exec("logcat -d");
      BufferedReader bufferedReader = new BufferedReader(
      new InputStreamReader(process.getInputStream()));

      StringBuilder log = new StringBuilder();
      String line;
      while ((line = bufferedReader.readLine()) != null) {
        log.append(line);
      }
      TextView tv = (TextView) findViewById(R.id.textView1);
      tv.setText(log.toString());
    } catch (IOException e) {
    }
  }
}

A: Or you can try this variant
try {
    final File path = new File(
            Environment.getExternalStorageDirectory(), "DBO_logs5");
    if (!path.exists()) {
        path.mkdir();
    }
    Runtime.getRuntime().exec(
            "logcat  -d -f " + path + File.separator
                    + "dbo_logcat"
                    + ".txt");
} catch (IOException e) {
    e.printStackTrace();
}

A: public static void writeLogToFile(Context context) {
    String fileName = "logcat.txt";
    File file= new File(context.getExternalCacheDir(),fileName);
    if(!file.exists())
         file.createNewFile();
    String command = "logcat -f "+file.getAbsolutePath();
    Runtime.getRuntime().exec(command);
}

Above method will write all logs into the file. Also please add below permissions in Manifest file
<uses-permission android:name="android.permission.READ_LOGS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />


text:
Q: cannot set header when using express hbs render I am trying to insert a token into the response header of a post route just before the view-engine-hadlebars renders.
This is the post route that I want to set up the haeder in:
app.post("/signup", (req, res) => {

let email = req.body.usremail;
let password = req.body.password;

var user = new User({
    email,
    password
})
user.save().then(() => {
    return user.generateAuthToken();
}).then((token)=>{

    res.set('x-auth', token);
    res.render("project.hbs", {
        paragraph: `Welcome ${email}. What would you like to do?`,
        button1: "New poll",
        button2: "See your polls",
        button3: "See all polls",
        link1: "/newpoll",
        link2: "/yourpolls",
        link3: "/allpolls",
        pie: true,
        two: true
    })
}, (e) => {
    console.log(e.message);
})

})

This is the get route that I want to receive the header in:
loginRouter.get("/newpoll", authenticate, (req, res) => {
console.log("newpoll/get:",req.header("x-auth"));

   res.render("project.hbs", {
    paragraph: `Enter your poll question and answers then submit`,
    quessubmit: true,
    method: "post",
    action: "/newpoll",
    ques: true
})
})

the get route is saying it's undefined. Any thoughts are much appreciated.

A: That is not how headers work. When you do: res.set('x-auth', token); on /signup route, you're setting a response header, that header will be sent to the client, but won't persist to other requests.
When the user clicks on the link, and goes to /newpoll, there is no possible way to send a custom a HTTP header through the a element, so your code won't work.
What you're looking for is a cookie, that will be set on /signup and can be retrieved on any other route.
const cookieParser = require('cookie-parser');
const express = require('express');

const app = express();
app.use(cookieParser());

app.post("/signup", (req, res) => {
    /* ... */
    res.cookie('x-auth', token);
    /* .. */
});

loginRouter.get("/newpoll", authenticate, (req, res) => {
    console.log("newpoll/get:",req.cookies["x-auth"]);
});

Take a look at res.cookie documentation, to learn how to set secure options.
NOTE: I do not know what your method authenticate does, or how are you authenticating the users, but you should probably check whether x-auth cookie is set or not there.


text:
Q: Android Emulator Screen Size Issue My Android studio emulator screen is off the original positioning and I have tried resizing, reloading the emulator, and Android studio to no avail.
What is wrong with the emulator Display?

A: I have Alieanware 17 ( Dell Gaming Series ) when i updated my android studio version after week emulator screen shows small and not same size with skin fame size. i found in internet but no solutions after i searched many links   Android Emulator Screen Size not the same as device frame see this links help me but in that when i choose software option in graphic setting in emulator device configuration. my emulator going slow. it also say that use this option when computer graphic issue.
here images shows before setting apply and after setting apply

A: Experienced the same problem as Solanki after updating from 3.1.2 to 3.1.3 (and Gradle update). Configuring the AVD graphics from/to "Automatic" had no effect.
Restarting and (installing Windows 10 updates - coincidence?) solved the problem and all running normally on start up.

A: you can just go to settings -> system -> scale and layout then change the size of text apps and other items to 125% restart android studio and run again the emulator.
good luck !

A: Update android studio if it's not up to date then go to settings and then in emulator tab tick on "Launch in a tool window". It will work
See Screenshot

A: Not sure if this helps, but I had this same problem (together with the side panel menu being overly large) after updating from Android Studio 2.3.0 to 2.3.1.  After restarting my computer it went away...


text:
Q: Perl regular expression variables and matched pattern substitution Can anyone explain regular expression text substitutions when the regular expression is held in a variable?  I'm trying to process some text, Clearcase config specs actually, and substitute text as I go.  The rules for the substitution are held in an array of hashes that have the regular expression to match and the text to substitute.
The input text looks somthing like this:
element  /my_elem/releases/...  VERSION_STRING.020 -nocheckout

Most of the substitutions are simply to remove lines that contain a specific text string, this works fine.  In some cases I want to substitute the text, but re-use the VERSION_STRING text.  I've tried using $1 in the substitution expression but it doesn't work.  $1 gets the version string in the match, but the replacement of $1 doesn't work in the substitution.
In these cases the output should look something like this:
element  -directory  /my_elem/releases/... VERSION_STRING.020 -nocheckout
element  /my_elem/releases/.../*.[ch]  VERSION_STRING.020 -nocheckout

ie. One line input became two output and the version string has been re-used.
The code looks something like this.  First the regular expressions and substitutions:
my @Special_Regex = (
                  { regex => "\\s*element\\s*\/my_elem_removed\\s*\/main\/\\d+\$",                  subs => "# Line removed" },
                  { regex => "\\s*element\\s*\/my_elem_changed\/releases\/\.\.\.\\s*\(\.\*\$\)",
                    subs => "element  \-directory  \/my_elem\/releases\/\.\.\. \\1\nelement  \/my_elem\/releases\/\.\.\.\/\*\.\[ch\]  \\1" }

                );

In the second regex the variable $1 is defined in the portion (.*\$) and this is working correctly.  The subs expression does not substitute it, however.
 foreach my $line (<INFILE>)
        {
        chomp($line);
        my $test = $line;
        foreach my $hash (@Special_Regex)
        {
            my $regex = qr/$hash->{regex}/is;
            if($test =~ s/$regex/$hash->{subs}/)
                {
                print "$test\n";
                print "$line\n";
                print "$1\n";
                }
         }
}

What am I missing?  Thanks in advance.

A: The substitution string in your regex is only getting evaluated once, which transforms $hash->{subs} into its string.  You need to evaluate it again to interpolate its internal variables.  You can add the e modifier to the end of the regex which tells Perl to run the substitution through eval which can perform the second interpolation among other things.  You can apply multiple e flags to evaluate more than once (if you have a problem that needs it). As tchrist helpfully points out, in this case, you need ee since the first eval will just expand the variable, the second is needed to expand the variables in the expansion.
You can find more detail in perlop about the s operator.

A: There is no compilation for a replace expression. So about the only thing you can do is exec or eval it with the e flag:
if($test =~ s/$regex/eval qq["$hash->{subs}"]/e ) { #...

worked for me after changing \\1 to \$1 in the replacement strings.
s/$regex/$hash->{subs}/

only replaces the matched part with the literal value stored in $hash->{subs} as the complete substitution. In order to get the substitution working, you have to force Perl to evaluate the string as a string, so that means you even have to add the dquotes back in in order to get the interpolating behavior you are looking for (because they are not part of the string.)
But that's kind of clumsy, so I changed the replace expressions into subs:
my @Special_Regex
    = (
        { regex => qr{\s*element\s+/my_elem_removed\s*/main/\d+$}
        , subs  => sub { '#Line removed' }
        }
    ,   { regex => qr{\s*element\s+/my_elem_changed/releases/\.\.\.\s*(.*$)}
        , subs  => sub {
            return "element  -directory  /my_elem/releases/... $1\n"
                 . "element  /my_elem/releases/.../*.[ch]  $1"
                 ;
          }
        }

    );

I got rid of a bunch of stuff that you don't have to escape in a substitution expression. Since what you want to do is interpolate the value of $1 into the replacement string, the subroutine does simply that. And because $1 will be visible until something else is matched, it will be the right value when we run this code.
So now the replacement looks like:
s/$regex/$hash->{subs}->()/e

Of course making it pass $1 makes it a little more bulletproof, because you're not depending on the global $1:
s/$regex/$hash->{subs}->( $1 )/e

Of course, you would change the sub like so:
subs => sub {
    my $c1 = shift;
    return "element  -directory  /my_elem/releases/... $c1\n"
         . "element  /my_elem/releases/.../*.[ch]  $c1"
         ;
}

Just one last note: "\.\.\." didn't do what you think it did. You just ended up with '...' in the regex, which matches any three characters.


text:
Q: inconsistencies between the original expression and the result one in apron I'm using the OCaml interface of the Apron library.
When I want to reduce the expression [| x + y -2 >= 0; x + y > - 3=0|], the result of tab is [|-3 + 1 * x + 1 * y >= 0|], How can I get the origin expression x + y - 3 >= 0?
let _ =
  let vx = Var.of_string "x" in
  let vy = Var.of_string "y" in
  let env = Environment.make [||] [|vx;vy|] in
  let c = Texpr1.cst env (Coeff.s_of_int 2) in
  let c' = Texpr1.cst env (Coeff.s_of_int 3) in
  let vx' =  Texpr1.var env vx in
  let vy' = Texpr1.var env vy in
  let texpr = Texpr1.binop Add vx' vy' Real Near in
  let texpr1 = Texpr1.binop Sub texpr c Real Near in
  let texpr2 = Texpr1.binop Sub texpr c' Real Near in
  (* let sum' = Texpr1.(Binop(Sub,x2,Cst c,Int,Near)) in *)
  Format.printf "env = %a@." (fun x -> Environment.print x) env;
  Format.printf "expr = %a@." (fun x -> Texpr1.print x) texpr;
  let cons1 = Tcons1.make texpr1 Lincons0.SUPEQ in
  let cons2 = Tcons1.make texpr2 Lincons0.SUPEQ in

  let tab = Tcons1.array_make env 2 in
  Tcons1.array_set tab 0 cons1;
  Tcons1.array_set tab 1 cons2;
  let abs = Abstract1.of_tcons_array manpk env tab in
  let tab' = Abstract1.to_tcons_array manpk abs in
  Format.printf "tab = %a@." (fun x -> Tcons1.array_print x) tab;
  Format.printf "tab1 = %a@." (fun x -> Tcons1.array_print x) tab'

A: It seems to me that there is no inconsistency as the expressions -3 + 1 * x + 1 * y >= 0 and x + y - 3 >= 0 are semantically equivalent.
Why is the expression printed this way?
You are building a polyhedron (i'm guessing manpk refers to the polka manager) and even if it is built using tree-constraints, it is represented internally using linear-constraints. So when you convert it back to tree-constraints, you actually are converting a Lincons1.earray to a Tcons1.earray, hence the representation as a sum of monoms.
If by "get the origin expression" you mean, make Apron print it in a human friendly way, i suggest you convert your polyhedron to a linear-constraint array (using to_lincons_array) and then define your own pretty-printing utility over linear constraints.
Alternatively, you can use the Apronext library, which is a small wrapper I wrote around the Apron library which provides pp_print functions. On your specific example, using Linconsext.pp_print, you get: x+y>=3. Disclaimer, Apronext is neither efficient, nor reliable, nor maintained, so i suggest you dont use it extensively, but only for understanding purposes


text:
Q: Update variable value I have a variable (output) witch value is another variable (version).
$VERSION="10"
$OUTPUT=$VERSION
write-host $OUTPUT

If I later on the script update the version variable , the output remains the older value
$VERSION="20"
write-host $OUTPUT

UPDATE ---------
In my case, I think it's a little more tricky
$TODAY=get-date -format "yyyymmd"
$VERSION="10"
$LOGERROR=-join([Ref]$VERSION,"_",$TODAY)
write-host $LOGERROR
write-host $LOGERROR.value
$VERSION="20"
write-host $LOGERROR
write-host $LOGERROR.value

It's probably the join that is the problem here because I can get an output with the message System.Management.Automation.PSReference but I can't get the output if I use .value

A: I'm copying the answer from this site: http://powershell.com/cs/blogs/tips/archive/2009/04/27/passing-byref-vs-byval.aspx
Usually, when you assign a variable to another variable, its content is copied. Here is an example:
$a = "Hello"
$b = $a
$a = "Hello World"
$b # "Hello"

As you can see, $b is actually a copy of $a so when you change $a, $b is not changed. If you want to, you can also just pass a pointer to a variable, effectively having two variables use the very same memory to store its values. To pass a pointer, cast to [Ref] like this:
$a = "Hello"
$b = [Ref]$a
$a = "Hello World"
$b # "Hello World"

This time, changing $a will also affect $b because both are using the same storage. When you look closely at the result, though, you will notice that $b actually is not a string variable anymore. It is now a PSReference object, and this object has a value property, giving you the actual object content:
$b.Value

Likewise, to change the $a variable through $b, you should assign a new value to the value property found in $b:
$b.Value = "New Text"
$a # "New Text"


text:
Q: No available SBL style? Where can I find a link that actually works for the document class/stye/package Society of Biblical Literature (SBL)? AFAIK all related threads in this forum and elsewhere are either broken or the link to the file is dead.
** UPDATE: SEE MY ANSWER (#2) BELOW FOR A NEW STYLE **

A: *

*Go to the link: Latex styles for the Society of Biblical Literature Handbook of Style (updated class and style files)

*Click the Download Zip icon on the lower right corner as shown in the image below:

*This will ensure that you have all of the .cls files. Open the sbl-latex-master.zip file and extract all.

*Search in the folder: sbl-latex-master\Library\texmf\tex\latex\sbl. You should now see all of the class files as shown below:

*To add new style files on MacTeX, see this link: How do I add a .sty file to my MacTeX/TeXShop installation?

A: The sbl-latex repo on github is owned by Robert Fisher. It uses a .bst file to compile the bibliography. it is very sophisticated and outputs really nice documents. I don't think it is still under active development.
https://github.com/RobertFischer/sbl-latex
However, when I wrote my thesis, I found a few things about it that I couldn't change easily, so I looked around and tried to find something a little more flexible for my own purposes. I ended up writing a class that extended the article class with minimal changes and packages. I used the CMS biblatex package for the bibliography and rely on Xelatex for unicode font support.
https://github.com/jackweinbender/sblhs-latex
sbl-latex and sblhs-latex are completely unrelated.
I am not a developer, but this produced a decent looking thesis for me. Pull requests are welcomed. I'd really like to see others to contribute to this to provide a clean working class/style for SBLHS, particularly since there will likely be an SBLHS revision in the next few years.

A: THE QUESTION LED TO THIS NEW TEMPLATE:
David Purton and I (he's the genius behind it) have been actively involved in a brand new BibLaTeX standard template for SBLHS version 2. Progress is ongoing, with optimal results. Check it out at https://github.com/dcpurton/biblatex-sbl

A: I googled it by looking for the actual name of the class rcfsblpaper.cls
This seems to be the github location now

A: I am actively developing SBL-paper class from Robert Fischer and am porting biblatex-Chicago for SBLHS2. Contact me for early access


text:
Q: htaccess multiple domain, force specific domain and its paths to www and exclude a path but redirect excluded path How to force a specific domain name and all its path to www except a specific path but redirect that specific path to another domain. So what I want is to force
en.one and all its paths to www.en.one except en.one/admin. but on top of that I want the excluded en.one/admin to go to another domain http://www.en.me.
So far I have managed to exclude en.one/admin but I still have failed to redirect en.one/admin to http://www.en.me.
My code
RewriteEngine on
RewriteCond %{HTTP_HOST} ^en.one$
RewriteCond %{THE_REQUEST} !/admin //This excludes the /admin
RewriteRule (.*) http://www.en.one/$1 [R=301,L]

Note: this is a multisite and multiple domains are managed by this single .htaccess file so solution is really important to be domain specific.

A: Maybe you can try to concat few conditions
## Not www include
RewriteCond %{HTTP_HOST} !^www\.(.+) [NC]
## Not admin directory
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/admin/ [NC]
## then rewrite to www.
RewriteRule ^(.*) http://www.%{HTTP_HOST}/$1 [R=301,L]
## And then redirect your admin
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} ^/admin/(.+) [NC]
RewriteRule ^(.*) http://www.en.me/$1 [R=301,L]

A: Thanks to @Christophe for helping me find a solution. You can check out our conversation as comments within Christophe's answer. The solution was to repeat the HTTP_HOST condition again. So in the end my .htaccess looked like this.
RewriteEngine on
RewriteCond %{HTTP_host} ^en.one$
#RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/admin
RewriteRule ^(.*) http://www.en.one/$1 [R=301,L]
RewriteCond %{HTTP_host} ^en.one$
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} ^/admin
RewriteRule ^(.*) http://www.en.me/ [R=301,L]

I am sure there could be better solutions but this works for me just as I wanted.


text:
Q: How to unload swf with GreenSock SWFLoader if the swf file has external class references? I try to load a swf file to show on the stage, if the swf file has no external class, i use
swfLoader.unload();, then ide consoln "Unloaded: E:\Projects\TweenTest\bin\ui.swf", but if the ui.swf has some external class references , use unload method can't get this message, it means it's not be unloaded in nature; How can I unload it?

A: LoaderMax can't know what dependencies your subloaded swf creates or clean up its references to external objects/classes/NetStreams - you need to do that before you unload() or dispose(true).


text:
Q: Arbitrary precision arthimetic in Fortran How can I do arbitrary precision arithmetic in Fortran?
I need two things. I want to work with really big integer and real numbers, and to work with arbitrary precise real numbers.


text:
Q: C#/SQL Reusing parameter for list of values How do I generate SqlCommand for list of parameters?
How to properly reuse same parameter with new OR clause?
public class InputList
{
    public string col1 { get; set; }
    public string col2 { get; set; }
}

public void Exec(IList<InputList> list)
{
   try
   {
       using (var conn = new SqlConnection(Settings.Default.DBConnStr))
       using (var cmd = conn.CreateCommand())
       {
           conn.Open();
           cmd.CommandType = CommandType.Text;

           // want to use SqlParameter to prevent sql injection
           var clause = list
                           .Select(x => $"(col1 = {x.col1} AND col2 = {x.col2}) OR ")
                           .Aggregate((curr, next) => curr + " " + next);
           // TODO: remove trainling OR

           cmd.CommandText =
               $@"SELECT *
                  FROM T
                  WHERE {clause}";

           // TODO: execute reader
        }
   }
   catch()
}

I have to iterate list of objects to compile WHERE clause
SELECT *
FROM T
WHERE
(col1 = @col1 AND col2 = @col2) OR
(col1 = @col1 AND col2 = @col2) OR
...
(col1 = @col1 AND col2 = @col2)

A: I couldn't find solution for my initial request, but table-valued parameters (TVP) works well for my case.
Thanks to @JeroenMostert for reminding about TVP
I had to rework my query and move clauses from WHERE into INNER JOIN section
SELECT *
 FROM T
 INNER JOIN @TVP TVP
 ON  TVP.col1 = T.col1
 AND TVP.col2 = T.col2
This won't work if you aren't allowed to create TVP in database


text:
Q: Show app update message to android users when they opened the app Is there any way that I can indicate my android app users to update their app in PlayStore. I haven't written any code to "check version number and show an app update message", in my previous app. What I have known so far that in this situation some solutions could be, like:

*

*Play store will fix this issue(by sending push notification) after a new version is updated.

*I can send push notifications to the app users to inform them to update their apps.

I am new to android app development. I know that this question is not making any sense because the codes are already compiled and I am not be able to do any edit to that code. The app communicate with the server in Json data format. But I am not able to send that "app update" message to the app by using one of the array keys, from server side. If I do, the app gets crash.
So, I am guessing if there any way that I can inform to those app users to update the app (may be via playstore), when they opened that app, in a dialogue box/something, with my custom message and it is not via the push notification message.
Please suggest me the solutions other than those I have mentioned above. If it is impossible, then comment it also. I need to confirm it that what I have known so far is correct.

A: First thing that play store will not show any notification to the user when new version of your apk is available.
Also you have to upload a new apk with code for checking update in your app and then only it will work.
For showing update dialog you can use the following library
Version Checker Library
For using this add this in your app level build.gradle file
compile 'com.robohorse.gpversionchecker:gpversionchecker:1.0.8'

and in your launcher activity add this
new GPVersionChecker.Builder(this).create();


text:
Q: travis-ci multiple build stages for each matrix element I am trying to run two stages, test_it and package_it, for each element of a build matrix. If all jobs in the test_it stage pass, then I want to do all the package_it jobs.
I have a .travis.yml file that does what I want, but verbosely with repetitions. What is the best way to get the same effect?
sudo: false

language: cpp

cache:
  ccache: true

jobs:
  include:
    - stage: test_it
      os: linux
      dist: trusty
      compiler: gcc
      addons:
        apt:
          packages:
            - bash-completion
            - curl
      script: echo "test_it on $TRAVIS_OS_NAME"
    - stage: test_it
      os: osx
      compiler: clang
      script: echo "test_it on $TRAVIS_OS_NAME"
    - stage: package_it
      os: linux
      dist: trusty
      compiler: gcc
      addons:
        apt:
          packages:
            - bash-completion
            - curl
      script: echo "package_it on $TRAVIS_OS_NAME"
    - stage: package_it
      os: osx
      compiler: clang
      script: echo "package_it on $TRAVIS_OS_NAME"


text:
Q: Rotated datapoint labels in gnuplot With regards to the answer given here: https://stackoverflow.com/a/14609537/2000581
How can I apply special formatting (e.g. rotate) to the labels ?
I can use
set label {tag} rotate by 45

to get a 45 degree rotated label. But plotting labels at datapoints, as given in the previously mentioned answer, has a different command format (... w labels u ...).
Perhaps a way to change the default label formatting ?

A: Whats wrong with appending rotate by 45 to the offset 1 part?:
Consider the file test.txt:
4 1
4 5
1 1
1 5
2.5 3

and the script:
set xr [0:5]
set yr [0:6]

plot 'test.txt' using 1:2:($0+1) with labels point pt 7 offset 1 rotate by 45 notitle

which gives a nice output image:


text:
Q: Find a kernel module behind virtual network interface by info from sysfs/procfs I'd like to find kernel module which is behind virtual network interface (e.g interfaces using veth, dummy kernel modules, NOT physical NIC). It's easy with ethtool:
$ ethtool -i ltp_ns_veth2 |grep driver
driver: veth

But I don't want to depend on it. I know I can find module for physical NIC:
$ basename $(readlink -f /sys/class/net/eth0/device/driver/module)
e1000

But this doesn't work for virtual devices as there is no link to device folder.

A: You can use dmesg | grep eth if you know the interface name would contain eth.
[root@psybox ~]# dmesg | grep -i eth
[    2.009028] vmxnet3 0000:03:00.0 eth0: NIC Link is Up 10000 Mbps

The driver is displayed second, vmxnet3.


text:
Q: Correct php syntax to add an image in wp functions.php I am trying to add a function in WordPress functions.php where i want to display an image relevant to my theme folder
here is my code which is not working, it only shows the file name but without the correct path.
add_filter (somefilter_code_here);
function mycustom_func($mycustom_field ) {
$capimg =  bloginfo('template_url').'/imagename.jpg';
echo $capimg; // for  testing and it does work
$mycustom_field .= '
';
//$comment_field .= '';
$mycustom_field .= '';
$mycustom_field .= "
";
return $comment_field;
}

i need an exact php line which can retrieve image from path and display it
right now image is not displayed, it show only file name and the value of $capimage is shown separately

A: do use get_bloginfo() when working with strings;
example:
$capimg =  get_bloginfo('template_url').'/imagename.jpg';

A: To get your current template's directory, use get_template_directory_uri(), so the above code should be:
add_filter (somefilter_code_here);
function mycustom_func($mycustom_field ) {
$capimg =  get_template_directory_uri().'/imagename.jpg';
echo $capimg; // for  testing and it does work
$mycustom_field .= '
';
//$comment_field .= '';
$mycustom_field .= '';
$mycustom_field .= "
";
return $comment_field;
}

Also, use src instead of scr to output the image.


text:
Q: How to avoid "Error in data[[txt]] : subscript out of bounds" error in predict.gam? I am trying to fit a GAM model to a test dataset of two variables (x,y) and then predict the y variable using the x variable (I know this doesn't make a lot of sense but it is part of bigger development and I am testing something). Building the gam model works but when I try to do the prediction it gives an error: "Error in data[[txt]] : subscript out of bounds" and I don't understand what is the problem. If it managed to build the model with the gam function it should be able to run the predict.gam as well.
Thank you!
library(mgcv)
library(ggplot2)
library(tidyverse)

# create dataframe
x = seq(0, 20, by = 0.5)
y = dnorm(x, mean(x), sd(x))
df = cbind.data.frame(x, y)

# fit the data
gam_mod <- gam(y ~ s(x), data = df, method = "REML")

# make prediction with the model using the x-value
pred <-predict.gam(gam_mod, newdata = df[, 1])

A: When you do df[,1] you are passing an unnamed vector to predict.gam. It needs a data frame with a column called x, otherwise it doesn't understand what you're trying to do.
You could instead do
pred <- predict.gam(gam_mod, newdata = df[1])

And get the result you are looking for.
Note though, that by default, predict already uses the original data frame for newdata, and the predict method will select predict.gam automatically, so actually you need only do:
pred <- predict(gam_mod)

pred
#>          1          2          3          4          5          6          7
#> 0.01638989 0.01900049 0.02165551 0.02440705 0.02729973 0.03035588 0.03356908
#>          8          9         10         11         12         13         14
#> 0.03690525 0.04030967 0.04371685 0.04706036 0.05027996 0.05332468 0.05615203
#>         15         16         17         18         19         20         21
#> 0.05872438 0.06100479 0.06295412 0.06453086 0.06569400 0.06640812 0.06664904
#>         22         23         24         25         26         27         28
#> 0.06640812 0.06569400 0.06453086 0.06295412 0.06100479 0.05872438 0.05615203
#>         29         30         31         32         33         34         35
#> 0.05332468 0.05027996 0.04706036 0.04371685 0.04030967 0.03690525 0.03356908
#>         36         37         38         39         40         41
#> 0.03035588 0.02729973 0.02440705 0.02165551 0.01900049 0.01638989

Created on 2020-12-08 by the reprex package (v0.3.0)

A: Looks like it is simply an issue of predict.gam needing to identify predictors by name (even in a univariate regression like this), and your subsetting drops the column name and reduces to a vector. If you subset like this (no comma), the column name is kept and you're good
pred <- predict.gam(gam_mod, newdata = df[1])


text:
Q: Google Maps Javascript API gives INVALID_REQUEST I am using Google Maps JavaScript API from ionic 2 framework. This code
new google.maps.places.AutocompleteService().getPlacePredictions(
    { input: query, types: ['cities'] },
    function (predictions, status) {}
);

gives INVALID_REQUEST as a status and empty predictions.
In browser console I could see this URL query:
https://maps.googleapis.com/maps/api/place/js/AutocompletionService.GetPredictionsJson?1skha&4sen-US&9scities&15e3&key=my_api_key_is_here&callback=YYYY&token=XXXX

for query=kha.
Official documentation does not helps a lot (because there is no even error status returned).

A: After looking more closely in docs, I've found that I used incorrect type. It should be '(cities)' instead of 'cities'.


text:
Q: Is there a verb meaning to wet the floor or spread water on the area by drips or droplets? Like when you are out and got wet in the rain, you run inside and spread water around. Or when you finished showering and you rush to get your towel because you forgot keep near the shower for convenience.

A: OK, here's the obvious one:  you use drip as a noun in your question title ("by drips or droplets"), but it can also be used as a transitive verb.

Coming inside from the storm, I dripped water all over the floor.
My towel wasn't on the rack by the shower, so I dripped water on the bathroom floor as I went to get a new one from the closet.

A: Splatter is a more active version than drip or dribble, suggests the water getting on the walls as well and implies more liquid being involved. Think of a dog shaking itself after a bath. Rushing around after a shower would splatter water everywhere, though not as much as a shaggy dog would do!

A: 'to pool around'; as in water pooled around  the table leg'