text:
Q: How to fake Ubuntu version number to applications I'm trying to install Intel C++ compiler on Ubuntu 13.04, but the installation script says that only Ubuntu 12.10 and below are supported, and there is no option to force installation. So is there any way I can fake a version number to the installation script so it can install? I'm just experimenting, and not afraid to break the system.

A:
So is there any way I can fake a version number to the installation script so it can install?

Do you know how it tests for the version number? /etc/lsb-release contains...
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=13.04
DISTRIB_CODENAME=raring
DISTRIB_DESCRIPTION="Ubuntu 13.04"

and is a text file so you can edit this. It might be the file that is used to test what version you are using.


text:
Q: Why is Titan throwing java.lang.IllegalArgumentException? Steps to reproduce
Setting up the environment using Docker v1.12.5:
In the host machine's shell:
$ docker run -d --name=test.cassandra cassandra:2  # cassandra v2.2.8
$ docker build -t test .  # see below for Dockerfile
$ docker run -ti --rm=true -P --link test.cassandra:cassandra test bash

Here is the Dockerfile used to build the test image:
FROM openjdk:alpine
ENV TITAN 'titan-1.0.0-hadoop1'

#
# Install system packages & Titan
#
RUN apk update && apk add bash unzip && rm -rf /var/cache/apk/* \
    && adduser -S -s /bin/ash -D srg \
    && wget -O /tmp/$TITAN.zip http://s3.thinkaurelius.com/downloads/titan/$TITAN.zip \
    && unzip /tmp/$TITAN.zip -d /opt && ln -s /opt/$TITAN /opt/titan \
    && rm /tmp/*.zip \
    && chown -R srg /opt/$TITAN/

COPY conf/srg.properties /opt/$TITAN/conf/  # see below for file contents
USER srg

And lastly, here is the contents of srg.properties:
storage.backend=cassandra
storage.hostname=cassandra

cache.db-cache = true
cache.db-cache-clean-wait = 50
cache.db-cache-time = 10000
cache.db-cache-size = 0.25

At this point there should be two containers running:  one with cassandra, and one running our test image.  You should have a bash shell running on the latter
Launching Gremlin and observing the error
In the test container's bash shell:
$ cd /opt/titan
$ ./bin/gremlin.sh

This should bring up the Gremlin shell.  From here:
g = TitanFactory.open('conf/srg.properties')

This should produce the following error:
Could not instantiate implementation: com.thinkaurelius.titan.diskstorage.cassandra.astyanax.AstyanaxStoreManager
Display stack trace? [yN] y
java.lang.IllegalArgumentException: Could not instantiate implementation: com.thinkaurelius.titan.diskstorage.cassandra.astyanax.AstyanaxStoreManager
    at com.thinkaurelius.titan.util.system.ConfigurationUtil.instantiate(ConfigurationUtil.java:55)
    at com.thinkaurelius.titan.diskstorage.Backend.getImplementationClass(Backend.java:473)
    at com.thinkaurelius.titan.diskstorage.Backend.getStorageManager(Backend.java:407)
    at com.thinkaurelius.titan.graphdb.configuration.GraphDatabaseConfiguration.<init>(GraphDatabaseConfiguration.java:1320)
    at com.thinkaurelius.titan.core.TitanFactory.open(TitanFactory.java:94)
    at com.thinkaurelius.titan.core.TitanFactory.open(TitanFactory.java:62)
    at com.thinkaurelius.titan.core.TitanFactory$open.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:110)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:122)
    at groovysh_evaluate.run(groovysh_evaluate:3)
    at org.codehaus.groovy.vmplugin.v7.IndyInterface.selectMethod(IndyInterface.java:215)
    at org.codehaus.groovy.tools.shell.Interpreter.evaluate(Interpreter.groovy:69)
    at org.codehaus.groovy.vmplugin.v7.IndyInterface.selectMethod(IndyInterface.java:215)
    at org.codehaus.groovy.tools.shell.Groovysh.execute(Groovysh.groovy:185)
    at org.codehaus.groovy.vmplugin.v7.IndyInterface.selectMethod(IndyInterface.java:215)
    at org.codehaus.groovy.tools.shell.Shell.leftShift(Shell.groovy:119)
    at org.codehaus.groovy.vmplugin.v7.IndyInterface.selectMethod(IndyInterface.java:215)
    at org.codehaus.groovy.tools.shell.ShellRunner.work(ShellRunner.groovy:94)
    at org.codehaus.groovy.tools.shell.InteractiveShellRunner.super$2$work(InteractiveShellRunner.groovy)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
    at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:324)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1207)
    at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.invokeMethodOnSuperN(ScriptBytecodeAdapter.java:130)
    at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.invokeMethodOnSuper0(ScriptBytecodeAdapter.java:150)
    at org.codehaus.groovy.tools.shell.InteractiveShellRunner.work(InteractiveShellRunner.groovy:123)
    at org.codehaus.groovy.vmplugin.v7.IndyInterface.selectMethod(IndyInterface.java:215)
    at org.codehaus.groovy.tools.shell.ShellRunner.run(ShellRunner.groovy:58)
    at org.codehaus.groovy.tools.shell.InteractiveShellRunner.super$2$run(InteractiveShellRunner.groovy)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
    at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:324)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1207)
    at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.invokeMethodOnSuperN(ScriptBytecodeAdapter.java:130)
    at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.invokeMethodOnSuper0(ScriptBytecodeAdapter.java:150)
    at org.codehaus.groovy.tools.shell.InteractiveShellRunner.run(InteractiveShellRunner.groovy:82)
    at org.codehaus.groovy.vmplugin.v7.IndyInterface.selectMethod(IndyInterface.java:215)
    at org.apache.tinkerpop.gremlin.console.Console.<init>(Console.groovy:144)
    at org.codehaus.groovy.vmplugin.v7.IndyInterface.selectMethod(IndyInterface.java:215)
    at org.apache.tinkerpop.gremlin.console.Console.main(Console.groovy:303)
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at com.thinkaurelius.titan.util.system.ConfigurationUtil.instantiate(ConfigurationUtil.java:44)
    ... 46 more
Caused by: com.thinkaurelius.titan.diskstorage.TemporaryBackendException: Temporary failure in storage backend
    at com.thinkaurelius.titan.diskstorage.cassandra.astyanax.AstyanaxStoreManager.ensureKeyspaceExists(AstyanaxStoreManager.java:572)
    at com.thinkaurelius.titan.diskstorage.cassandra.astyanax.AstyanaxStoreManager.<init>(AstyanaxStoreManager.java:291)
    ... 51 more
Caused by: com.netflix.astyanax.connectionpool.exceptions.PoolTimeoutException: PoolTimeoutException: [host=cassandra(172.17.0.2):9160, latency=10000(10000), attempts=1]Timed out waiting for connection
    at com.netflix.astyanax.connectionpool.impl.SimpleHostConnectionPool.waitForConnection(SimpleHostConnectionPool.java:231)
    at com.netflix.astyanax.connectionpool.impl.SimpleHostConnectionPool.borrowConnection(SimpleHostConnectionPool.java:198)
    at com.netflix.astyanax.connectionpool.impl.RoundRobinExecuteWithFailover.borrowConnection(RoundRobinExecuteWithFailover.java:84)
    at com.netflix.astyanax.connectionpool.impl.AbstractExecuteWithFailoverImpl.tryOperation(AbstractExecuteWithFailoverImpl.java:117)
    at com.netflix.astyanax.connectionpool.impl.AbstractHostPartitionConnectionPool.executeWithFailover(AbstractHostPartitionConnectionPool.java:352)
    at com.netflix.astyanax.thrift.ThriftClusterImpl.executeSchemaChangeOperation(ThriftClusterImpl.java:146)
    at com.netflix.astyanax.thrift.ThriftClusterImpl.internalCreateKeyspace(ThriftClusterImpl.java:321)
    at com.netflix.astyanax.thrift.ThriftClusterImpl.addKeyspace(ThriftClusterImpl.java:294)
    at com.thinkaurelius.titan.diskstorage.cassandra.astyanax.AstyanaxStoreManager.ensureKeyspaceExists(AstyanaxStoreManager.java:567)
    ... 52 more

Questions
On a high level, my question is simply "What is going on here and what can I do about it?"
I have an existing cassandra (dockerized) on top of which I would like to deploy Titan.  Ultimately, I expect to run a Titan container on each machine running Cassandra, configured to connect to the co-located cassandra container.
Suggestions and questions are, as always, appreciated.  Thanks!

A:
On a high level, my question is simply "What is going on here and what can I do about it?"

If you look at the "caused by" chain for the exception, the original one says:
Caused by:
    com.netflix.astyanax.connectionpool.exceptions.PoolTimeoutException:
    PoolTimeoutException: [host=cassandra(172.17.0.2):9160,
                           latency=10000(10000), attempts=1]
    Timed out waiting for connection

At the high level ....
What is going on is that your Gremlin instance is not able to connect to the Cassandra service.  The most likely explanation is there is a problem with network routing and/or firewalling, either across the docker boundary or between the host where you are running stuff and the Cassandra host.
What I would do in this situation is to:

*

*Check the IP and port number that are being used (per the exception) to ensure they are correct.

*Use network diagnostic tools (traceroute, tcptraceroute, ping, etc) to determine if you can make connections to Cassandra, and where the "blockage" seems to be.

What you do next depends on what you find.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Should I use inheritance or composition in my case? I'm creating a class which shares common codes with another class and am not sure which pattern I should use. The class I've already have:
public class TeamA{
    private static final Logger LOGGER = Logger.getLogger(TeamA.class);

    @Autowired
    private Utility util;

    public void proceedWithA(){
        // do something useful here
        updateProgress();
    }

    private void updateProgress(){
        LOGGER.info("Updating progress!");
        // do something to update the progress
    }
}

The class TeamB I'm creating does almost the same thing as class TeamA except that in proceedB() it does something different before calling updateProgress().
public class TeamB{
    private static final Logger LOGGER = Logger.getLogger(TeamB.class);

    @Autowired
    private Utility util;

    public void proceedWithB(){
        // do something useful here
        updateProgress();
    }

    private void updateProgress(){
        LOGGER.info("Updating progress!");
        // do something to update the progress
    }
}

So at first I'm inclined to use inheritance by creating a super class Team for them to extend from:
public class Team{
    // How should I define the Logger?

    @Autowired
    private Utility util;

    protected void updateProgress(){
        // LOGGER.info("Updating progress!");
        // do something to update the progress
    }
}

How should I use the Logger? In class TeamA/B it is defined as private static final, but apparently I can't do the same in the superclass since I want a logger for TeamA and TeamB respectively.
I also thought about composition. But it seems that I have to pass the Logger as a parameter to the updateProgress method. Is this OK or is there a better way?
public class TeamA{
    private static final Logger LOGGER = Logger.getLogger(TeamA.class);

    @Autowired
    private Team teamUtil;

    public void proceedWithA(){
        // do something useful here
        teamUtil.updateProgress(LOGGER);
    }
}

public class Team{
    @Autowired
    private Utility util;

    protected void updateProgress(Logger LOGGER){
        LOGGER.info("Updating progress!");
        // do something to update the progress
    }
}

I'm new to design patterns and this logger thing is getting me confused. Could someone give me some advice please? Thanks :)

A: public abstract class Team{
    protected abstract Logger getLogger();

    protected void updateProgress(){
        getLogger().info("Updating progress!");
        // do something to update the progress
    }
}

Your child classes can now implement getLogger to return their static final Logger.

A: " protected void updateProgress " location needs to be fixed since its functionality is changing with class.
What you can do here is create a abstract super class and make the updateProgress abstract (this is template pattern) . Let the base class give independent functionality for it. this way you would be able to use it either way by sub-class/super-class variable.
There is no law that you need to use composition every where , it depends .. in your case you should use template method pattern.


text:
Q: How to hide a column in devexpress gridview on page load? I want to hide one column from my gridview using devexpress page load event.
This is my view code:
<dx:GridViewDataTextColumn ReadOnly="True" VisibleIndex="7" Caption="Action">
    <DataItemTemplate>
        <dx:ASPxButton runat="server" ID="btnEdit" Text="Edit" OnClick="btnEdit_Click" AttId='<%# HttpUtility.UrlEncode(Eval("Id").ToString()) %>'></dx:ASPxButton>
    </DataItemTemplate>
</dx:GridViewDataTextColumn>

How to write code to hide this column on page load event?

A: if you just want it to be invisible at start you could just add the Visible attribute
<dx:GridViewDataTextColumn ReadOnly="True" VisibleIndex="7" Caption="Action" Visible="False">

if you really want to to set it in code behind
ASPxGridViewCustomers.Columns["Action"].Visible = false; // ASPxGridViewCustomers is the Id of the ASPxGridView


text:
Q: Getting the value null of the variable Here is my code in this code the value inside the try block I am getting the value of httpconn = null but in the first line I am storing the value into the variable httpconn in the first line why it so. I am getting nullpointerexception.

public static String requestToken()
    {
         String url = Const.REQUEST_TOKEN_URL;
         String header = oauth_header(url, HttpProtocolConstants.HTTP_METHOD_GET);
         String requestTokenUrl = concatURL(url, header);
         HttpConnection httpConn = null;
         InputStream input = null;
         try
         {

            httpConn = (HttpConnection) Connector.open(requestTokenUrl); // kris connection
             httpConn.setRequestMethod(HttpProtocolConstants.HTTP_METHOD_GET);
             httpConn.setRequestProperty("WWW-Authenticate","OAuth realm=http://twitter.com/");
             httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

             input = httpConn.openDataInputStream();
             int resp = httpConn.getResponseCode();
             if (resp == HttpConnection.HTTP_OK)
             {

                 StringBuffer buffer = new StringBuffer();
                 int ch;
                 while ( (ch = input.read()) != -1)
                 {
                     buffer.append( (char) ch);
                 }
                 String content = buffer.toString();
                 Const.token = content.substring(content.indexOf((Const.OAUTH_TOKEN+"="))+(Const.OAUTH_TOKEN+"=").length(), content.indexOf('&'));
                 Const.tokenSecret = content.substring(content.indexOf((Const.OAUTH_TOKEN_SECRET+"="))+(Const.OAUTH_TOKEN_SECRET+"=").length(), content.length());

                 message = httpConn.getResponseMessage();

             }
             return message;//(getTwitterMessage(httpConn.getResponseCode()));
            }
            catch (IOException e)
            {
                return "exception";
            }
            catch (Exception nc)
            {
                return "noConnection";
            } finally {
             try {
                 httpConn.close();
                 input.close();
             } catch (IOException e) {
                 e.printStackTrace();
             }

A: In the finally block, do
if (httpConn != null)
    httpConn.close();

if (input != null)
    input.close();

If e.g. in the code you posted Connector.open() throws an exception, httpConn will not be initialized to anything other than null. You will catch that exception and want to return information related to it but before returning, you try to access a null pointer (in the finally block) which raises the NullPointerException.

A: Null pointer exception is thrown when:

Thrown when an application attempts to use null in a case where an object
    is required. These include:

*

*Calling the instance method of a null object.

*Accessing or modifying the field of a
null object.

*Taking the length of null as if it
were an array.

*Accessing or modifying the slots of
null as if it were an array.

*Throwing null as if it were a
Throwable value.

So this indicates that your httpConn = (HttpConnection) Connector.open(requestTokenUrl); // kris connection is not working. Check in that


text:
Q: Iteration of Child Lightning Component I am building a lightning component for an app home page and want to render a list of records. I have created a parent component that iterates over a list of children components. The parent component loads on page load but the list child component won't render within the parent component. I've checked my apex controller to make sure the query is returning results - it is. As a check, I've done the iteration in the parent component and am able to render results.
Here's my code. What could I be missing?
Parent Component:
<aura:component implements="flexipage:availableForAllPageTypes" controller="WirelessEventListController">
    <aura:attribute name="wirEvList" type="Wireless_Events__c[]"/>
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>

                    Upcoming Hospitality Events

Date

Event Name

Spots

Location

Link

                    <aura:iteration var="x" items="{!v.wirEvList}">
                       <c:WirelessEventDetailList wirEv="{!x}"/>
                    </aura:iteration>

</aura:component>

Parent Controller.js
({
    doInit : function(component, event, helper) {
        var action = component.get("c.getAllwirelessEvents");
        action.setCallback(this, function(response){
            var name = response.getState();
            if (name === "SUCCESS") {
                component.set("v.wirEvList", response.getReturnValue());
                console.log(component.get("v.wirEvList"))
            }
        });
        $A.enqueueAction(action);
    },
   /*-- handleClick: function (component, event, helper) {
        var idLink = component.get("r.id")
        var urlLink = event.currentTarget.id;
        var navEvt = $A.get("e.force:navigateToSObject");
        navEvt.setParams({
            "recordId": idLink,
            "slideDevName": "detail"
        });
        navEvt.fire();
    } --*/
})

Child Component:
<aura:component>
    <aura:attribute name="wirEv" type="Wireless_Events__c"/>

{!wirEv.Start_Date__c}

{!wirEv.Name}

{!wirEv.Spots_Remaining__c}

{!wirEv.Event_Location__r.Name}

    <lightning:button variant="brand" label="Open" onclick="{!c.handleClick}"/>
</aura:component>

Child Controller:
({
    handleClick: function (component, event, helper) {
        var idLink = component.get("v.wirEv.id")
        console.log(idLink);
        var navEvt = $A.get("e.force:navigateToSObject");
        navEvt.setParams({
            "recordId": idLink,
            "slideDevName": "detail"
        });
        navEvt.fire();
    }
})

Apex Controller:
global with sharing class WirelessEventListController {
@auraEnabled
    public static List<Wireless_Events__c> getAllwirelessEvents()
    {
     List<Wireless_Events__c> wirEv=new LIST<Wireless_Events__c>();
        wirEv=[select id,name,Spots_Remaining__c,Event_Location__r.Name,Start_Date__c from Wireless_Events__c where Event_Closed__c <> True ORDER BY Start_Date__c ASC NULLS LAST];
        return wirEv;
    }
}

A: You also need to modify your child component, if you will load it will throw error as well.
To show value of field on component we need to use the value provider "v" as well. Below is the correct code for child component -
<aura:component>
<aura:attribute name="wirEv" type="Wireless_Events__c"/>

{!v.wirEv.Start_Date__c}

{!v.wirEv.Name}

{!v.wirEv.Spots_Remaining__c}

{!v.wirEv.Event_Location__r.Name}

</aura:component>


text:
Q: Eloquent inserting into table twice For the life of my I can't figure out why Eloquent is inserting into my table twice.
Here is my routing
Route::get('/tech_terminal/task/{user_id}/{id}/{equipment_type}/{component}','TaskController@complete_task');

And the controller
public function complete_task($user_id, $id, $equipment_type, $component) {
    if ($id > 0) {
        $tech_task = TechTask::where([['user_id',$user_id],['id',$id]])->first();
    } else {
        $tech_task = new TechTask;
        $tech_task->user_id = $user_id;
        $tech_task->equipment_type = $equipment_type;
        $tech_task->component = $component;

        $tech_task_array = [];
        $tasks = Task::where([['user_id',$user_id],['equipment_type',$equipment_type],['component',$component]])->get();
        foreach($tasks as $task) {
            array_push($tech_task_array, (object)[
                'task' => $task->task,
                'input_type' => $task->input_type
            ]);
        }
        $tech_task->task_data = serialize($tech_task_array);
        $tech_task->save();
    }
    return view('tech_tasks')->with('task_list',$tech_task_array)->with('id',$tech_task->id);
}

If I changed the routing, it still happens. If I change the insert to save pre-defined '1's....it still does it!
Does this have something to do with my name space? This is the only part I don;t know how to troubleshoot. I have no idea on what else to do.
use App\Task;
use App\TechTask;

Thanks in advance!

A: i thing you click submit button twice ? use javascript to handle if button was click and page still loading disabled button


text:
Q: Background image help thanks for help, ended up with this
html{
    position:relative;
    min-width:950px;
    height:100%;
    background:black url(images/GrassBG.png) repeat-y top center;
font:13px "Lucida Grande",Helvetica,Arial,sans-serif;
}

body.main{
    width:950px;
    margin:0 auto;
    position:relative;
    }

is there any way when using a div for a background image- to limit the height to only the content displayed?
im putting the background image in a div because i want it centered via position:relative but the image doesnt show up unless i put a height on the div, and thats not what i want because i dont want to be able to just scroll down to the bottom of the image where theres no content
ive tried putting the background image on the body css but if the browser is less than the width of the image, it just throws it over to the left and you can only see half of it- is there no way to make the background position:relative on the body?
sorry if that doesnt make sense ><
thanks
why can you not use Position:relative; on the body?

A: You can set your div's height to 100% and set it with no-repeat to keep it from propogating throughout the div. Make sure all of its parent elements contain a 100% height though (all the way up to body). It won't force itself, then, to be a certain height. It will just fill the page.
This is all assuming, of course, that you don't care to interact with what's underneath the div in question.


text:
Q: nginx subdomain rewrite Yet another nginx rewrite rule question
How can I do a rewrite from http://www.*.domain.com to http://*.domain.com ?
thanks in advance
-- Deb
EDIT:
I'm sorry I didn't see the textile formatting removed the * from my question. I fixed it now.
What I need to do is go from www.joe.domain.com to joe.domain.com, where joe could be any word.

A: Whats the significance of the extra period before domain.com? Is the goal to remove the www from the URL? If so, this should do the trick:
if ($host ~* www\.(.*)) {
  set $host_without_www $1;
  rewrite ^(.*)$ http://$host_without_www$1 permanent; # $1 contains '/foo', not 'www.mydomain.com/foo'
}

Don't forget to: sudo /etc/init.d/nginx restart to load it up
Source: NGINX Wiki

A: You can use regular expression server names (see http://nginx.org/en/docs/http/server_names.html#regex_names):
server {
  listen 80;
  listen 443;
  server_name ~^www\.(\w+)\.domain\.com$
  location / {
    rewrite ^ $scheme://$1.domain.com$request_uri permanent;
  }
}

A: That's quite a bit of a hack.
The fastest way performance wise would be
server {
  server_name www.domain.com;
  rewrite ^ http://domain.com$request_uri permanent;
}

You save a regex match as well as two captures plus you get the advantage of nginx using hash tables to look up the matching server block.
Also, you do not need to restart nginx - a reload is all that's required, and whoever would want to have more down time than required?

A: Martin F's solution is all well and good, until you've got hundreds of domains.  I would, however, suggest going the other way - serve the app at www.joe.domain.com, and redirect from joe.domain.com.  Pretty sure that's in an RFC.


text:
Q: Adjusting XORShift generator to return a number within a maximum I need to generate random integers within a maximum. Since performance is critical, I decided to use a XORShift generator instead of Java's Random class.
long seed = System.nanoTime();
seed ^= (seed << 21);
seed ^= (seed >>> 35);
seed ^= (seed << 4);

This implementation (source) gives me a long integer, but what I really want is an integer between 0 and a maximum.
public int random(int max){ /*...*/}

What it is the most efficient way to implement this method?

A: I had some fun with your code and came up with this:
public class XORShiftRandom {

private long last;
private long inc;

public XORShiftRandom() {
    this(System.currentTimeMillis());
}

public XORShiftRandom(long seed) {
    this.last = seed | 1;
    inc = seed;
}

public int nextInt(int max) {
    last ^= (last << 21);
    last ^= (last >>> 35);
    last ^= (last << 4);
    inc += 123456789123456789L;
    int out = (int) ((last+inc) % max);
    return (out < 0) ? -out : out;
}

}

I did a simple test and it is about Four times as fast as the java.util.Random
If you are intrested in how it works you can read this paper:
Disclamer:

The code above is designed to be used for research only, and not as a
  replacement to the stock Random or SecureRandom.

A: Seeding
There are many problems here. In case, you're using nanoTime more than once, you'd definitely doing it wrong as nanoTime is slow (hundreds of nanoseconds). Moreover, doing this probably leads to bad quality.
So let's assume, you seed your generator just once.
Uniformity
If care about uniformity, then there are at least two problems:
Xorshift
It never generates zero (unless you unlucky with seeding and then zero is all you ever get).
This is easily solvable by something as simple as
private long nextLong() {
    x ^= x << 21;
    x ^= x >>> 35;
    x ^= x << 4;
    y += 123456789123456789L;
    return x + y;
}

The used constant is pretty arbitrary, except for it must be odd. For best results, it should be big (so that all bits change often), it should have many bit transitions (occurrences of 10 and 01 in the binary representation) and it shouldn't be too regular (0x55...55 is bad).
However, with x!=0 and any odd constant, uniformity is guaranteed and the period of the generator is 2**64 * (2*64-1).
I'd suggest seeding like
seed = System.nanoTime();
x = seed | 1;
y = seed;

nextInt(int limit)
The accepted answer provides non-uniformly distributed values for the reason I mentioned in a comment. Doing it right is a bit complicated, you can copy the code from Random#nextInt or you can try something like this (untested):
public int nextInt(int limit) {
    checkArgument(limit > 0);
    int mask = -1 >>> Integer.numberOfLeadingZeros(limit);
    while (true) {
        int result = (int) nextLong() & mask;
        if (result < limit) return result;
    }
}

Above, the mask looks in binary like 0...01...1, where the highest one corresponds with the highest one of limit. Using it, a uniformly distributed number in the range 0..mask gets produced (unifomrnity is easy as mask+1 is a power of two). The conditional refuses numbers not below limit. As limit > mask/2, this happens with a probability below 50%, and therefore the expected number of iterations is below 2.
Recommendation
Fooling around with this is fun, but testing it is hard and I'd recommend using ThreadLocalRandom instead, unless you need reproducibility.


text: Q: How do I have session available in PHP application which makes HTTP requests to java servlets using cURL (Session is started in servlet)? I have a web service made using Java Servlet and I can access that using curl in PHP which returns data in JSON. Now the problem is I start session in java servlet and I want to have that session in PHP after the request is made. How can I do it?


text:
Q: Can't center navbar and have to click the word itself This is my css code (for the index page):
span{
display:block;
font-size:100px;
font-weight: lighter;
font-family: "Times New Roman", Times, serif;
}

.index {
    background-image: url("images/indexbackground.png");
    background-repeat: no-repeat;
    background-attachment: fixed;
  background-size: 1600px 800px;
}

/*NAVBAR (begin)*/
a {
  text-decoration: none;
}

nav {
    font-family: Arial;
    background-color: Black;
}

ul {
  background: black;
    list-style: none;
    margin: 0;
    padding-left: 0;
}

li {
    color: #white;
  background: black;
    display: block;
    float: left;
    padding: 27px;
    position: relative;
    text-decoration: none;
  transition-duration: 0.5s;
}

li a {
  color: #fff;
}

li:hover {
    background: #DEB887;
    cursor: pointer;
}

ul li ul {
    background: black;
    visibility: hidden;
  opacity: 0;
  min-width: 17rem;
    position: absolute;
  transition: all 0.5s ease;
  margin-top: 27px;
    left: 0;
  display: none;
}

ul li:hover > ul,
ul li ul:hover {
  visibility: visible;
  opacity: 1;
  display: block;
}

ul li ul li {
    clear: both;
  width: 100%;
}
/*NAVBAR (end)*/

This is the code for HTML (index page):
<!DOCTYPE html>
<link rel="stylesheet" href="piano.css" />

<title>The piano - Home</title>

The Piano

Home

The piano itself

Mechanics

Construction

Types of pianos

Grand

Upright

Electric

History of the piano

Piano songs

I already tried a lot of things but nothing seems to work...
Right now my index page looks like this:
(Index page but I had to cut it because the full picture was over 2 mb)
(I'm sorry, It's really bad but it's my first time making a website with html and css).
I need to center the navigation bar and to be able to click the box instead of the word.
Thank you for reading (and maybe answering)!

A: First of all, I recommend to use classes instead of the direct element selector,
If you want to center the nav, you only need to set the property align-text: center in the parent divof the main nav. and if you want to click all the box instead only the text, the element that needs the padding and margin is the a not the li.
Check the snippet:

span{
display:block;
font-size:100px;
font-weight: lighter;
font-family: "Times New Roman", Times, serif;
}

.index {
    background-image: url("images/indexbackground.png");
    background-repeat: no-repeat;
    background-attachment: fixed;
  background-size: 1600px 800px;
}

.navwrapperindex {
  text-align: center;
}
.navwrapperindex > nav{
  display: inline-block;
}

a {
  text-decoration: none;
}

nav {
    font-family: Arial;
}

ul {
  background: black;
    list-style: none;
    margin: 0;
    padding-left: 0;
}

li {
    color: #white;
  background: black;
    float: left;
    position: relative;
    text-decoration: none;
  transition-duration: 0.5s;
}

li a {
  color: #fff;
  padding: 27px;
  display: block;
}

li:hover {
    background: #DEB887;
    cursor: pointer;
}

ul li ul {
    background: black;
    visibility: hidden;
  opacity: 0;
  min-width: 17rem;
    position: absolute;
  transition: all 0.5s ease;
    left: 0;
  display: none;
}

ul li:hover > ul,
ul li ul:hover {
  visibility: visible;
  opacity: 1;
  display: block;
}

ul li ul li {
    clear: both;
  width: 100%;
}
The Piano

Home

The piano itself

Mechanics

Construction

Types of pianos

Grand

Upright

Electric

History of the piano

Piano songs


text:
Q: Android - getting actionbar size gives inconsistent result Why does getting the effective screensize (screen-actionbar-statusbar) like below give different results different times? first time my fragment is started and calls getEffectiveScreenSize it gets it wrong (actionbar size is 0) but 2nd time and the rest it is correct.
So getting the actionbar size like below is not reliable, why? What is the corrrect and safe way?
public static Point getScreenSize( Activity theActivity )
{
    Display theDisplay = theActivity.getWindowManager().getDefaultDisplay();
    Point sizePoint = new Point();
    theDisplay.getSize( sizePoint );

    return sizePoint;
}

public static int getStatusBarHeight( Activity theActivity )
{
    int result = 0;
    int resourceId = theActivity.getResources().getIdentifier( "status_bar_height", "dimen", "android" );

    if (resourceId > 0)
    {
        result = theActivity.getResources().getDimensionPixelSize( resourceId );
    }

    return result;
}

public static int getActionBarHeight( Activity theActivity )
{
    return theActivity.getActionBar().getHeight();
}

public static Point getEffectiveScreenSize( Activity theActivity )
{
    Point screenSize = getScreenSize( theActivity );
    screenSize.y = screenSize.y - getStatusBarHeight( theActivity ) - getActionBarHeight( theActivity );

    return screenSize;
}

This change did not help:
public static int getActionBarHeight( Activity theActivity )
{
    //return theActivity.getActionBar().getHeight();
    int result = 0;
    int resourceId = theActivity.getResources().getIdentifier( "actionbar_bar_height", "dimen", "android" );

    if (resourceId > 0)
    {
        result = theActivity.getResources().getDimensionPixelSize( resourceId );
    }

    return result;
}

A: I'm not sure why all your methods are static, but more to the point for some reason you haven't included relevant code - where is getEffectiveScreenSize used?
The best answer I can give you has to be based on assumptions - you must be calling getEffectiveScreenSize at different points in the lifecycle - before, and after the layout has been measured and/or before the action bar is fully initialized (maybe look at the callbacks related to action bar).
If you want to have your layout account for the action bar there is a dimension you can use for that
?android:attr/actionBarSize

If you are trying to make or maybe stop the content and action bar overlapping then you probably have to change the value of action bar overlay in your styles
<item name="android:windowActionBarOverlay">bool</item>

A: Make sure that you are giving the action bar enough time to load before checking its size. I'm sure there is a best practices means of doing this, but for now just trying waiting a bit until it has loaded (you could try a loop that blocks until it is not size zero)

A: The ActionBar's height probably is 0 when you measure it the first time. Wait until layout of the main view is finished, then you can measure the ActionBar and react.
final ViewTreeObserver vto = mainView.getViewTreeObserver();
vto.addOnGlobalLayoutListener(
    new OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            // Get the ActionBar height here
            vto.removeGlobalOnLayoutListener(this);
        }
    };
);


text:
Q: Increasing mean deviation with increasing sample size on Excel's NORMINV() I have a strange behaviour in my attempt to code Excel's NORMINV() in C. As norminv() I took this function from a mathematician, it's probably correct since I also tried different ones with same result. Here's the code:
double calculate_probability(double x0, double x1)
{
    return x0 + (x1 - x0) * rand() / ((double)RAND_MAX);
}

int main() {

long double probability = 0.0;
long double mean = 0.0;
long double stddev = 0.001;
long double change_percentage = 0.0;
long double current_price = 100.0;
srand(time(0));
int runs = 0;
long double prob_sum = 0.0;
long double price_sum = 0.0;

while (runs < 100000)
{
    probability = calculate_probability(0.00001, 0.99999);
    change_percentage = mean + stddev * norminv(probability); //norminv(p, mu, sigma) = mu + sigma * norminv(p)
    current_price = current_price * (1.0 + change_percentage);
    runs++;
    prob_sum += probability;
    price_sum += current_price;
}
printf("\n\n%f %f\n", price_sum / runs, prob_sum / runs);
return 0;
}

Now I want to simulate Excel's NORMINV(rand(), 0, 0.001) where rand() is a value > 0 and < 1, 0 is the mean and 0.001 would be the standard deviation.
With 1000 values it looks okay:
100.729780 0.501135
With 10000 values it spreads too much:
107.781909 0.502301
And with 100000 values it sometimes spreads even more:
87.876500 0.498738
Now I don't know why that happens. My assumption is that the random number generator has to be normally distributed, too. In my case probability is calculated fine since the mean is pretty much 0.5 all the time. Thus I don't know why the mean deviation is increasing. Can somebody help me?

A: You're doing something along the lines of a random walk, except your moves are with a multiplicative scaling factor rather than additive steps.
Consider two successive moves, the first of which gives 20% inflation, the second with 20% deflation.  Starting with a baseline of 100, after the first step you're at 120.  If you now take 80% of 120, you get 96 rather than the original 100.  In other words, seemingly symmetric scaling factors are not actually symmetric.  While your scaling factors are random, they are still being created symmetrically around 1, so I'm not surprised to see deviations accumulate.


text:
Q: What type of differential equation is it and how can it be solved? The equation is:
$$\frac{dA(t)}{dt}=aA(t)\cdot k^{2}(t)+b\cdot k(t)$$
If not the last part, I would use the separation of variables, but how to solve it in this form?

A: Reform your given equation to the known ODE form :
$$\frac{dA(t)}{dt}=aA(t)\cdot k^{2}(t)+b\cdot k(t) \Leftrightarrow \frac{dA(t)}{dt}-aA(t)k^2(t)=bk(t)$$
Let $$μ(t)= e^{\int-atk^2(t)dt}=e^{-a\int tk^2(t)dt}$$
and multiply both sides of the reformed ODE by that $μ(t)$.
Substitute :
$$-atk^2(t)e^{-a\int tk^2(t)dt} = \frac{d}{dt}\big(e^{-a\int tk^2(t)dt}\big)$$
It will then be :
$$\frac{\frac{dA(t)}{dt}}{e^{a\int tk^2(t)dt}} + \frac{d}{dt}\big(e^{-a\int tk^2(t)dt}\big)A(t)= \frac{bk(t)}{e^{a\int tk^2(t)dt}}$$
Integrate both sides with respect to $t$ :
$$\int \frac{d}{dt}\bigg(\frac{A(t)}{e^{a\int tk^2(t)dt}}\bigg)dt =\int \frac{bk(t)}{e^{a\int tk^2(t)dt}}dt$$
It will then be :
$$\frac{A(t)}{e^{a\int tk^2(t)dt}}=b\int e^{-a\int tk^2(t)dt}k(t)dt + c$$
Dividing both sides with the initial $μ(t)$ will yield the solution :
$$A(t) = e^{a\int tk^2(t)dt}\bigg(b\int e^{-a\int tk^2(t)dt}k(t)dt + c\bigg)$$

A: This is first order linear. You solve by multiplying by the integrating factor $$\exp\left(\int ak^2(t)\,dt\right).$$

A: It is a linear equation. Indeed, the first step is to solve the equation without the last part. Next is you are assuming that C=C(x) and put it into full equation. Some reduction will appear. An example of the theory in Polish (as I guess from your name) you have here:
http://smurf.mimuw.edu.pl/node/271


text:
Q: How to add non-maven jars to classpath? I have to add some non-maven jars into a Spring boot project (MVC). Those jars are not built by maven or gradle or ..., and the don't have a pom.xml or build.gradle or ...
The jars are provided by a company, and they have no plan to host those jars on any maven repositories even their own (actually they don't have a private maven repo).
My project structure is like
my-app/
  |-lib
  |  |-some.jar
  |  |-other.jar
  |
  |-src/
     |-main/
     |   |-java/
     |   |-resources/
     |
     |-test/
         |-java/

I added a folder lib/ to the project root, and put those non-maven jars in it. The problem is how can I configure pom.xml to include those jars in classpath? Or can I put those jars in some other folder to avoid twisting maven configuration?

A: You can do this :
For example i want to add ojdbc-7.jar on my repository, i go to my repository
\USERFolder\Laptop_Login.m2\repository\ojdbc\ojdbc\7
and i create manually the path ojdbc\ojdbc\7\ and in the path 7 i put my File Jar.
dependency
groupId ojdbc groupId
artifactId ojdbc artifactId
version 7 version
dependency
between the tag's value of artifactId and the tag's value of version add a mince like this (ojdbc-7).
i think it's the better way to do.


text:
Q: How to convert date in string to Long in java? I have date and time in string format in one of my models.
"startTime": "2022-10-19T14:31:22+00:00"
How can I convert it to long format in Java?
I tried using
'Long.valueOf(startTime)' and 'Long.parseLong(startTime)' are two functions.
but in both I am getting an exception.
"at the java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)"

A: You can parse your datetime format using builtin methods - also to convert it to a long value (assuming the number of seconds since the epoch).
Instant.parse("2022-10-19T14:31:22+00:00").getEpochSecond()

See https://docs.oracle.com/en/java/javase/19/docs/api/java.base/java/time/Instant.html
See code run at Ideone.com.


text:
Q: vector addition using graphical and component method Suppose there are four vectors A = 8.00 cm, South; B = 15.0 cm, 30.0° E◦N; C = 12.0 cm, 25° S◦W; and D = 10.0 cm, 53° W◦N. Using the materials, employ the graphical method (tail-to-tip) to determine the resultant vector A+B+C+D. Compare your results when using component method
i tried graphing it but i think my graph is wrong, my angle and resultant vector is way off compared to my answer when using component method


text:
Q: How to modify the prepended protocol and host in Tomcat's RewriteValve I am using the RewriteValve in Tomcat 8 to redirect client requests like so:
RewriteRule /login$ /~autoLogin [R,L]
This is fine but the problem I'm running into is that when a redirect is used [R], the redirect target URL is created by prepending the server with http:// rather than what the client originally requested (the docs say that this will be the case [1]).
For example, when the client requests
https://myserver.com/login I expect it to redirect to
https://myserver.com/~autologin.
However, it actually redirects to http://myserver.com/~autologin
How can I configure/change how the prepending works?
At the moment I am working around this by hardcoding the target URL to
https://myserver.com/~autologin
but this is undesirable as I keep this configuration in version control and use it on multiple servers for developing, test, staging and production.

A: It turns out this is not a problem with the RewriteValve, but a side effect of the server infrastructure I am using.
The Tomcat server is running on an EC2 instance behind an Elastic Load Balancer on AWS. The ELB hosts the certificate that allows HTTPS requests. However, because the EC2 instance can't use the certificate directly, the request that comes in as HTTPS on the ELB gets forwarded to the Tomcat instance as an HTTP request; the ELB will transparently negotiate the certificate exchange and encryption of the communications.
Thus, to the RewriteValve, the incoming request is on HTTP and thus, it prepends with HTTP.


text:
Q: How to observe changes in system preference "Sidebar icon size" in AppKit? In the Main section of the System Preferences of macOS, the user can change the "Sidebar icon size". This setting changes the icon size (and since macOS 11 also the font size) used in Sidebars, when the size mode of the NSOutlineView in question is set to default.
I want to add an UserNotification observer in my app to track changes to the said setting, so I can perform some additional finetuning after each size change, but could not find any applicable NSNotification.Name or other constant.
Any workable solution or suggestion is welcome.

A: I knew I had a solution for this, but I was searching in the wrong projects. This is what I found. Observing UserDefaults is not a fantastic option, but at least it works:
fileprivate let tableViewDefaultSizeModeKey = "NSTableViewDefaultSizeMode"

override func viewDidLoad() {
    super.viewDidLoad()
    UserDefaults.standard.addObserver(self, forKeyPath: tableViewDefaultSizeModeKey, options: .new, context: nil)
}

deinit {
    UserDefaults.standard.removeObserver(self, forKeyPath: tableViewDefaultSizeModeKey)
}

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if keyPath == tableViewDefaultSizeModeKey {
        // Do whatever is needed
    }
}

A: Thanks for the code.
Please note that the changed value accessible in observeValue(forKeyPath... is the reliable way to access the new value. If one tries to access the effectiveRowSizeStyle in the table/outline view in this callback, the value has not yet been set in the view..and is still equal to the old value.
I also tried to call reloadData() from the observeValue(forKeyPath... callback to force a redraw of some cells that had some custom icon sizes, and found that event in the drawing code, the new updated rowSize was inaccessible. I ended up adding a custom ivar to my OutlineView to store the 'next' rowSize in order to properly size my icons in the redraw of the cells.


text:
Q: Component is not rendering I'm working through the React 16 course on Udemy. We are using Codepen to create our first React apps in the course. Although the instructor is able to render the component in the video, I follow his code and it doesn't render. Here's the HTML, CSS, and JS code:
HTML:

Your name

  <p1>Manu</p1>

CSS:
.person {
  margin:10px;
  box-shadow:2px 2px #ccc;
  border: 1px solid #eee;
  padding: 20px;
  width: 200px;
  display: inline-block;
}

JavaScript:
function Person(){
  return(

Your name

      <p1>Tristan</p1>

  );
}

ReactDOM.render(<Person/>, document.querySelector('#p1'));

A: You have a misprint: Persan vs Person.
Also instead of class you should use className because JSX is just a javascript and keyword class is reserved.
Also instead of p1 element I believe you should use either p or some custom component which will have a name started with a capital letter.

function Person() {
  return (

Your name

Tristan

  );
}

ReactDOM.render(<Person/>, document.querySelector('#p1'));
.person{
  margin:10px;
  box-shadow:2px 2px #ccc;
  border: 1px solid #eee;
  padding: 20px;
  width: 200px;
  display: inline-block;
}

A: The issue is due to the typo Persan in the component declaration.
It should be
function Person(){
 return(

Your name

   <p1>Tristan</p1>

 );
}

ReactDOM.render(<Person/>, document.querySelector('#p1'));


text:
Q: Silverlight performance design tips What's your top 3 Silverlight performance design tips?
Thanks

A: *

*Only transfer the data you need -
use lazy loading where possible (via RIA Services
etc)

*Only load the bare minimum at start-up. Use a module-based downloading pattern (MEF, PRISM or other). Silverlight developers seem to have forgotten the 8 second attention span of Internet users still applies to them.

*Don't do excessive fullscreen animations and expect a high frame-rate on all machines :)

A: *

*Use Virtualized UI (Virtualized stack pannels, ect..)

*Cache data client side in Isolated Storage

*Take advantage of MEF to reduce the amount downloaded when your app changes

*Use animated GIFs instead of Silverlight animation for loading animations


text:
Q: Why are so many terms nautical in origin? I have joked that whenever I don't know the etymology of a word, I reply "of indeterminate nautical origin" (that's right - it's party 24/7 at my crib).
What is it about the nautical tradition in the 18th century that seems to have spawned a wildly out-sized portion of our vocabulary? It's not as if there weren't other highly specialized professions with their own jargon.

A: Just speculating widely here.
Sailing was big in the 18C, you think the dot-com boom was big? That's nothing to the spice trade, Dutch east India company, Canada (and some other non-descript place just to the south).
Since it boomed fairly quickly and under some sort of central control there was a standardization of terms. Carpentry or blacksmithing might need a lot of technical terms, but every village probably had it's own word for each tool while the navy training meant that sailing terms were standardized, at least in English.
There are a LOT of technical terms on a sailing boat, they look simple but they are insanely complex to operate and since the command protocol consists of shouting at people the terms have to be precise, definite and standard.
It was also the time of a great boost in literature and since sailing and maritime trade was the exciting big thing of the day it was a natural setting for your literary hero. There are probably lots of technical terms required to build a medieval cathedral, but there wasn't a big market for 13C romantic fiction about the workers.
ps. And of course sailors had contact with other countries, so a lot of foreign (especially Indian and Chinese) words would have been first encountered by sailors and then incorporated into their language and jargon.

A: England, the home of "English," is located on a small island. (Three other English speaking countries, the USA, Canada, and Australia, can be considered to be located on LARGE islands.)
To get from the island (Britain), to the rest of the world, it is necessary to travel by sea. This was particularly true in the 18th and 19th centuries (when much of our modern vocabulary was developed) before the age of air travel in the twentieth century.
Most of what the country was about was getting goods and people to and from the country BY SEA. If President Coolidge said, "The business of America is business," he might have said, "The business of England is shipping." Hence, "naval" and "nautical" issues were pre-eminent in the life of Britain (and to a slightly lesser extent in the other English-speaking countries), and that's why a lot of English vocabulary/expressions is connected to the sea.
Under the circumstances, sailing wasn't a "highly specialized profession." Instead, it was part of the "mainstream" (pun intended).


text:
Q: Where can I get a list of all iOS elements? What is a good resource for a list of iOS GUI elements?
The official documentation, such as the UIPickerView docs do not include images, and while sometimes the official overview documentation has images, they are not easily found.
The closest thing I have found is iOS photoshop templates (including the awesome Teehan Lax one ), but they don't reference the class name, or have any common third party controls.
Edit: A web based site would be great, so I can share with others who do not have Xcode, or browse on an iPad.

A: You can take an in-depth look at UIElements inside this page of documentation LINK

A: The Apple Developer portal has a document listing all the UI elements for iOS and also goes into what their various uses are. Here's an excerpt for how they describe a UITextView:

Text View
  A text view accepts and displays multiple lines of text. To learn more about defining a text view in your code, see UITextView Class Reference.

Appearance and Behavior
  A text view is a rounded rectangle of any height. A text view supports scrolling when the content is too large to fit inside its bounds.If the text view supports user editing, a keyboard appears when the user taps inside the text view. The keyboard's input method and layout are determined by the user's language settings. When users tap the button labeled ".?123," the keyboard changes to display numbers, punctuation marks, and a few common symbols.
Guidelines
  You have control over the font, color, and alignment of the text in a text view, but only as they apply to the entirety of the text. In other words, you can't change any of these properties for only part of the text. The default font is the system font and the default color is black, because these tend to be the most readable. The default for the alignment property is left (you can change it to center or right).If you must enable variable fonts, colors, or alignments within a view that displays text, you can use a web view instead of a text view, and style the text using HTML. You can also specify different keyboard styles, depending on the type of content you expect users to enter. For a description of the styles you can use, see "Text Field."

If you simply want to see a list of UI Elements and not the descriptions, go to the sidebar on the left and click on the disclosure arrow next to "iOS UI Elements Usage Guidelines", and it'll have a list of general categories like "Bars", "Content Views", "Controls", etc. From there you can click the disclosure arrow next to the category headings to see individual UI elements. The image below illustrates what I mean:

A: If you are looking for a list of GUI elements of the standard framework, you can check Interface Builder for them, and even change the configuration to show the possible ways to create them. Storyboard also gives you some flexibility to add content to it.


text:
Q: "must match numbers of columns" error in dynlm in R I have the folllowing codes:
y<-my.data$GDP
tt<-my.data$period
dataset<-data.frame(y,tt)
gnp.lm <- dynlm(formula = y ~ L(d(y), 1:10) + 1 + L(y) + tt, data = dataset)

Both my.data$period and my.data$GDP are one-dimensional arrays with the same lengths.
However, I got the following error message:
error in fix.by(by.x x) 'by' must match numbers of columns.

Could someone help me with this problem?

A: Without giving a reproducible example, the following reason could be the answer:
obs <- 1000
y <- rnorm(1000)
tt <- 1:obs

dataset <- data.frame(y, tt)
dyn_lm <- dynlm(y~L(y,1:5)+ tt)

Here, the error occurs due to the problem of the unknown class of y. But if you specifiy the class of y and tt to be of ts, it perfectly works.
y.ts <- ts(y)
tt.ts<-ts(tt)

dyn_lm_ts <- dynlm(y.ts~L(y.ts,1:5)+ tt.ts)


text:
Q: Geometry proof problem (high school) I have an upcoming chapter test and this was one of the practice problems. Can someone guide me?
Given: Isosceles $\triangle ABC$ with $AB$ congruent to $AC$;  $AD$ is not a median of $\triangle ABC$.
Prove: $AD$ does not bisect $\angle A$.
My idea is to use proof by contradiction but I'm not sure if my thinking is right.

A: What you can do, and this might be what you meant, is to prove the contrapositive, which is kind of like a proof by contradiction, but is more direct. We take as given the isosceles triangle with $AB \cong AC$, with $D$ on $BC$, prove that
Assume $AD$ bisects $\angle A,$ then prove that AD is a median of $\triangle ABC$.
If you can do this, you will have proven
(I) IF $AD$ bisects $\angle A,$, THEN $AD$ is a median of $\triangle ABC$.
Proving (I) is equivalent to proving, with the initial "givens", that
(II) if $AD$ is NOT a median of $\triangle ABC$, then AD does not bisect $\angle A$.
Do you think you can do this? (Think SAS).

A: I would prove it using the contrapositive.
You want to prove this: If AD is not a median of $\triangle ABC$
(which is the same as D does not bisect BC),
then AD does not bisect $\angle A$.
The contrapositive, which is logically equivalent is this:
If AD  bisects $\angle A$
then AD is a median of $\triangle ABC$
(which is the same as D bisects BC).
This should be easy to prove
(SAS).

A: If you want to proof by contradiction, then you can do this.
Assume that $AD$ is not median and bisects $\angle BAC$, as it's shown on the picture below

then, according to SAS ($AB = AC$ by statement of the problem, $\angle BAD = \angle DAC$ by assumption and $AD$ is common edge) $\triangle BAD \cong \triangle ADC$ which means $BD = DC$ as well, which in turn means that $D$ is median. Contradiction.


text:
Q: Chrome Devtools become grayed out while debugging for specific JS file while debugging 3rd party code in Chrome DevTools one file became gray and I couldn't debug it, see values or do any operation on the content.
it occurs in a specific file only.

why is it happening?

A: After digging I found the issue is:
this._slot.innerHTML += '...

apparently, the debugger doesn't like those things and disabled the whole file from debugging.
BTW, the code working with that type of "+=" but it so not the right way it fricking out the debugger.


text:
Q: What is an appropriate mapping for a field that is a title of a news article in Elasticsearch? I have a document for storing news articles' contents and metadata. How should I map field title which is a short text value of a news article title? I want to be able to search for the exact match (keyword type), but at the same time I want to apply some analyzer to it (text type).

A: Keep the title field as text and use a custom analyzer
I dont know what your requirements are for analyzer but you can use index template for your index and define the custom analyzer like below:
PUT my_index
{
  "settings": {
    "analysis": {
      "analyzer": {
        "my_custom_analyzer": {
          "type": "custom",
          "tokenizer": "standard",
          "char_filter": [
            "html_strip"
          ],
          "filter": [
            "lowercase",
            "asciifolding"
          ]
        }
      }
    }
  },
  "mappings": {
    "doc_type": {
      "properties": {
        "title": {
          "type": "text",
          "analyzer": "my_custom_analyzer"
        }
      }
    }
  }
}

A: Use fields in your index mapping to store it as both text and keyword.
{
    "my-index": {
        "mappings": {
            "_doc": {
                "properties": {
                    "title": {
                        "type": "text",
                        "fields": {
                            "keyword": {
                                "type": "keyword"
                            }
                        }
                    }
                }
            }
        }
    }
}

To use the analysed field, refer to "title". To use the keyword field, refer to "title.keyword".
Further reading: https://www.elastic.co/guide/en/elasticsearch/reference/current/multi-fields.html

A: Have you tried to duplicate the field?, then you will have 2 fields one with keyword type and another with text type


text: Q: How to set a default directory for ask_open_folder() in Ruby Shoes? I am writing a small app in Ruby using Shoes GUI. In this app user need to select several directories as import destinations. Is there any way to give a default path for ask_open_folder() (based for example on the last user selection), so the user do not have to start from main every time the function is called? This can be really annoying after selecting the fifth directory....


text:
Q: How to eliminate the animation of the annotation on swift I'm using MapKit and I have some annotations on map. They are markerAnnotationViews. The thing is that I want that, when the user touches an annotation, to present  a view controller (without going through a callout accessory view).
For now, I've done so with the didSelectView with: MKAnnotationView. But my problem is that when I press the annotation, it expands and shows the following view controller.
Is there a way for the annotation to not expand when the user presses it?
Thanks.
Edit:
This is how I present the modal view controller when I press on an annotation:
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {

    if let annotation = view.annotation as? FirstAnnotation {
        let rootVC = DetailPinVC()
        rootVC.title = "Detail Pin"
        rootVC.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .close, target: self, action: #selector(dismissDetailVC))
        let navVC = UINavigationController(rootViewController: rootVC)
        present(navVC, animated: true)
    } else if let annotation = view.annotation as? SecondAnnotation {
        let rootVC = DetailPinVC()
        rootVC.title = "Detail Pin"
        rootVC.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .close, target: self, action: #selector(dismissDetailVC))
        let navVC = UINavigationController(rootViewController: rootVC)

And this is my problem. When I dismiss the modal view, the annotation stays expanded on the map. The first photo is before i press on the annotation and the second is after. I want the "bobble" to stay as the first photo:

A: The annotation is now selected so it appears different.
To continue using didSelect to monitor for tap events on the annotation, call mapView.deselectAnnotation immediately within didSelect. This will unselect the annotation and return it to the normal unselected size.
Alternatively, you could add a UITapGestureRecognizer to custom annotationViews. This will free up your didSelect method so you can readily harness its full use should your app's feature set require it.

A: You should be able to
override func setSelected(_ selected: Bool, animated: Bool) {
    //super.setSelected(false, animated: false)
}

in your MKMarkerAnnotationView subclass to prevent a selection.


text:
Q: Trying to visualyze Heap Fragmentation Im trying to measure heap fragmentation, I will use this formula :
Fragmentation = 1 - (LargestFreeBlockAvailable / TotalFreeMemory)
The tricky part is to find the largest free blocks.
I have found this code which allow me to show all blocks in the heap :
https://learn.microsoft.com/en-us/windows/win32/toolhelp/traversing-the-heap-list
I'm trying to create fragmentation allocating and deallocating larger and larger blocks :
std::allocator<char> alloc;
char * tmp = alloc.allocate(100);
    alloc.deallocate(tmp,100);
    tmp = alloc.allocate(200);
    alloc.deallocate(tmp,200);
    tmp = alloc.allocate(300);
    alloc.deallocate(tmp, 300);
    tmp = alloc.allocate(400);
    alloc.deallocate(tmp, 400);
    tmp = alloc.allocate(1000);
    alloc.deallocate(tmp, 1000);
    tmp = alloc.allocate(2000);
    alloc.deallocate(tmp, 2000);
    tmp = alloc.allocate(3000);
    alloc.deallocate(tmp, 3000);
    tmp = alloc.allocate(5000);
    alloc.deallocate(tmp, 5000);
    alloc.allocate(15000);

But I see no fragmentation when I run run the program, There is only one free block which correspond to the available memory left :
Results
It's like if the block I freed previously where merged to this big last block... There arent any "hole" in the heap which would indicate fragmentation.
Is anyone aware of the mechanism that occurs which avoid the fragmentation?
Maybe im doing it wrong to create the fragmentation ?
Thank you in advance.
Sorry for bad english.


text:
Q: Hypothesis testing for RMSE I want to compare two distributions of values. While the mean value is approximatively the same in both distributions, the RMSE in both with respect to 1 is quite different.
With RMSE I mean $\sqrt{(((1−)^2)}$, with VCF the Volume Conservation Factor

However, the RMSE does not have any estimate of uncertainty. I was wondering if there was any statistical method with which I can obtain a p-value testing the hypothesis that the RMSE are equal.
One thing I thought of doing was to segment the distribution into subsections, and create a distribution of RMSEs. Which is not very clean and can be optimized to obtain desired values.


text:
Q: Excel fonts: Embedding or fallback options? I'm working with making a form in Excel instead of Illustrator or InDesign, as I typically do. One of the benefits about working with Adobe (and the subsequent PDFs) is that I control the fonts 100%. This is not the case when I am required to work with an Excel file that'll be passed around.
So, is there a way to embed fonts? I'd like to embed Calibri. If not, is there a way to specify a fallback font, such as Tahoma? My thinking is along the lines of a CSS font stack; not sure if there's anything like that in Excel.

A: Doesn't look like Excel supports embedding fonts. Word does, so there's a workaround if you're willing to embed your Excel spreadsheet inside a Word doc.
References:

*

*http://www.microsofttraining.net/article-687-how-embed-fonts-in-excel.html

*http://excel.tips.net/T001969_Embedding_Fonts_in_Excel.html
If you're using Calibri, you shouldn't have to worry too much. It's the default font in Office since 2007. I even have it in Mac Office.
Hope this helps.
-- jm


text:
Q: How do I display label text in table view cell when pressing a button? I have this UIlabel that displays text and I want to be able to press the addButton and then display the text in the tableViewCell. How would I be able to do that?
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return amountLabelArray.count
}

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

    cell.textLabel?.text = amountLabelArray[indexPath.row]

    return cell
}

@IBOutlet weak var amountLabel: UILabel!
@IBOutlet weak var tableView: UITableView!

var amountLabelArray = [String]()

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.delegate = self
    tableView.dataSource = self

}

@IBAction func oneButton(_ sender: Any) {

let number = 1
amountLabel.text = amountLabel.text! + String(number)
}

//this will add the amount to the table view cell
@IBAction func addButton(_ sender: Any) {

        amountLabelArray.append(amountLabel.text!)
        print("This is the array \(amountLabelArray)")
        amountLabel.text = ""

   }
 }

A: Have you tried to call reloadData() on your tableView on button tap?
@IBAction func addButton(_ sender: Any) {
    amountLabelArray.append(amountLabel.text!)
    print("This is the array \(amountLabelArray)")
    amountLabel.text = ""
    tableView.reloadData()
}


text:
Q: mvn install error eclipse After doing maven clean install then running mvn install in eclipse getting this error, not sure what it is referring:
[ERROR] /Users/user1/Desktop/proj1/src/main/java/com/proj/proj1/dao/testDAO.java:[18,21] try-with-resources is not supported in -source 1.5
[ERROR] (use -source 7 or higher to enable try-with-resources)

A: try-with-resources is a Java 7 specificity.
So, as you are using Maven, you have to configure the Maven compiler plugin in your pom.xml to use at least Java 7.
If you use for example JDK 8, you could add this properties in the build element of the pom.xml :
<build>
    ...
    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
    ..
<build>

source and target must not necessarily have the same value but in the very most of cases, it is better.

A: Add a properties tag in your POM.xml to ensure that you will be working using Java 8 (try-with-resources requirement). Check if you have the Java 1.8 sdk installed, and your IDE is properly configured.
<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>


text:
Q: Generate 3 circles dataset with three classes in python I actually wanted to generate 3 circles one inside the another with three different classes (class0, class1, class2) in python(that is first the bigger circle then inside it the second biggest circle and inside that the third circle). I am only able to generate 2 circles with two classes from the code below. Could anyone please help me with that?

import numpy as np
import pylab as pl
import sklearn.metrics as sm
from sklearn.datasets import make_circles
X, y = make_circles(n_samples=200)
print(X)
print(y)
plt.scatter(X[:,0],X[:,1], marker='o', facecolors='none', edgecolor='r')

A: Probably there is a more polite way to proceed, but here I show a practical way to do it.
Basically you can generate another two circles with the function make_circles but playing with another hyperparameter, the factor.
What I do, is generating the same main circle, and then a new circle that is multiplied by the factor value (0.6 in my case).
Here is the code:
X, y = make_circles(n_samples=200)
z, w = make_circles(n_samples=200, factor=0.6)

plt.scatter(X[:,0],X[:,1],  facecolors='none', edgecolor='r')
plt.scatter(z[:,0],z[:,1],  facecolors='none', edgecolor='r')

If you want to change the radius of the new circle, play with the factor.
The only problem of this code is that the big circle is duplicated (plotted twice), but, since they are overlapped, there is no visual problem.

A: According to the documentations of make_circles and make_blobs:

make_circles
sklearn.datasets.make_circles(n_samples=100, *, shuffle=True, noise=None, random_state=None, factor=0.8)
Make a large circle containing a smaller circle in 2d. A simple toy dataset to visualize clustering and classification algorithms.
make_blobs
sklearn.datasets.make_blobs(n_samples=100, n_features=2, *, centers=None, cluster_std=1.0, center_box=- 10.0, 10.0, shuffle=True, random_state=None, return_centers=False)
Generate isotropic Gaussian blobs for clustering.

You can not make 3 circles using make_circles, but for generating 3 classes, you can use make_blobs.
For having 3 classes circle data, you can use a combination of these two functions as the following example:
import sklearn.datasets as ds
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs

data, labels = ds.make_circles(n_samples=100,
                               shuffle=True,
                               noise=0.0,
                               random_state=42)

center = [[3, 4]]
data2, labels2 = make_blobs(n_samples=100,
                            cluster_std = 0.2,
                            centers=center,
                            random_state=1)

for i in range(len(center)-1, -1, -1):
    labels2[labels2==0+i] = i+2

print(labels2)
labels = np.concatenate([labels, labels2])
data = data * [1.2, 1.8] + [3, 4]

data = np.concatenate([data, data2], axis=0)

and then the below codes to see the result:
fig, ax = plt.subplots()

colours = ["orange", "blue", "magenta"]
label_name = ["Class1", "Class2", "Class3"]
for label in range(0, len(center)+2):
    ax.scatter(data[labels==label, 0], data[labels==label, 1],
               c=colours[label], s=40, label=label_name[label])

ax.set(xlabel='X',
       ylabel='Y',
       title='dataset')

ax.legend(loc='upper right')

The results will be as:

Another ways is to use two make_circle functions to generate 4 circles but using 3 of them.
import sklearn.datasets as ds
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs

data, labels = ds.make_circles(n_samples=100,
                               shuffle=True,
                               noise=0.01,
                               random_state=42)

data2, labels2 = ds.make_circles(n_samples=100,
                               shuffle=True,
                               noise=0.0,
                               random_state=42)

data2 = data2 * [1.2, 1.8]

then plot results using:
fig, ax = plt.subplots()
colours = ["orange", "blue"]
label_name = ["Class1", "Class2"]
ax.scatter(data[labels==0, 0], data[labels==0, 1], color='red'
               ,s=40)
ax.scatter(data[labels==1, 0], data[labels==1, 1], color='green'
               ,s=40)
ax.scatter(data2[labels2==0, 0], data2[labels2==0, 1], color='blue',
               s=40)

ax.set(xlabel='X',
       ylabel='Y',
       title='dataset')

ax.legend(loc='upper right')

Then the results are represented as below:

if you want to change the size of circle(3rd circle, here the outer one), you can multiply by different coefficients.
data2 = data2 * [a1, a2]

where a1 and a2 can be any values but perfectly between 0 and 2. if the values are below 1, the circles will put inner other circles and vice versa.


text:
Q: Create two way table and change to data frame format I have data as below. I can convert it into format that I want. Second last line gives me the required format. But when I convert into a dataframe I loose the format. How could I keep the format while converting to a dataframe?
start_city=c("a","b","a")
end_city=c("b","a","a")
travel=data.frame(start_city,end_city)
table(start_city,end_city)
abc=data.frame(table(start_city,end_city))

A: We need to convert it to matrix first
tbl <- table(start_city, end_city)
res <- as.data.frame.matrix(tbl)
str(res)
#'data.frame':   2 obs. of  2 variables:
#$ a: int  1 1
#$ b: int  1 0

Here, we will loose the names of dimnames of 'tbl' output


text:
Q: Order Pandas dataframe groups by minimum index number, then re-order all other columns within groups based on a 3rd column I have a dataframe like this:
import numpy as np
import pandas as pd

columns=['Order', 'Group_code', 'Grade', 'Contextual_info']

data = np.array([np.arange(6)]*4).T
mydf = pd.DataFrame(data, columns=columns)

mydf.Order = [1,2,3,4,5,6]
mydf.Group_code = ['group99','group2','group2','group2','group12','group12']
mydf.Grade = [80,0,60,80,85,70]
mydf.Contextual_info = [5,4,3,2,1,0]

mydf

   Order Group_code  Grade Contextual_info
0      1    group99     80               5
1      2     group2      0               4
2      3     group2     60               3
3      4     group2     80               2
4      5    group12     85               1
5      6    group12     70               0

Which is ordered by Order. I want to preserve the ordering of Group_code by Order, thus the column values in Group_code should not change.
However, within each Group_code group, I want to order the rows descending by Grade. Finally, I will replace Order with a new vector of integers 1... n, such that it is still 1, 2, 3, 4, 5, 6 in this example.
Desired result:

   Order Group_code  Grade  Contextual_info
      1    group99     80                 5
      2     group2     80                 2
      3     group2     60                 3
      4     group2      0                 4
      5    group12     85                 1
      6    group12     70                 0

A: Use
In [677]: mydf.Grade = (mydf.groupby('Group_code')['Grade']
                            .transform(pd.Series.sort_values, ascending=False))

In [678]: mydf
Out[678]:

  Order Group_code  Grade
0      1    group99     80
1      2     group2     80
2      3     group2     60
3      4     group2      0
4      5    group12     85
5      6    group12     70


text:
Q: When does hibernate release list of entities? Suppose an Criteria was created which select a non-empty list of values. Then criteria.list().get(0) is called and return from some function. It is clear that this element exists in further call chain, but what about other list elements? When does they are released? When hibernate session ends or when?

A: Assuming you are using Session and not StatelessSession, the L1 cache will be cleared under several conditions:

*

*When the session is closed.

*When session.clear() is called on an active session instance.

You may also clear instances of a managed entity individually on an open session which manages the given entity by passing the entity instance to session.evict(Object object).


text:
Q: Execute dynamic rules on every row in spark I have one Dataframe with the actual data that needs evaluation (df) and one with the set of rules that should be evaluated (criterias).
Example for df:

ID
features

XX
{'A':1,'B':2, 'C':'green'}

YY
{'A':2,'B':1, 'C':'blue'}

Example for criterias:

ID
criteria

1
(cast(filter(features, x -> x.key = 'A')[0].value AS double) < (cast(filter(features, x -> x.key = 'B')[0].value AS double)

2
(cast(filter(features, x -> x.key = 'C')[0].value AS string) = 'green' AND (cast(filter(features, x -> x.key = 'A')[0].value AS double) > 1

First rule says that A needs to be smaller than B and second rule says that if C = green than A has to be bigger than 1.
As a result I want to have a struct in a new column that shows which criteria was met and which was missed:

ID
features
result

XX
{'A':1,'B':2, 'C':'green'}
{1:TRUE,2:FALES}

YY
{'A':2,'B':1, 'C':'blue'}
{1:FALSE,2:NULL}

My current approach is to loop over the criterias table and execute a sparksql adding to the result array. It is working, but when there are hundreds of criterias and million of df rows it is very slow. Is there a way to do this better? Is there a framework that could be used?
I am using spark pools in azure synapse. Spark 3.1.


text:
Q: GAE - ImportError: No module named django.core.wsgi First of all, let me say that I did my homework and search for this error for several hours. I get this error when I try to access my Django 1.11 'Hello world' app deployed on GAE.
I'm perfectly able to run the app locally, inside a Docker with Python 2.7.
My current setup is as follows:
Install
virtualenv env
pip install -r requirements-vendor.txt -t lib/
pip install -r requirements.txt

requirements-vendor.txt
Django==1.11

app.yaml
runtime: python27
api_version: 1
threadsafe: yes

handlers:
- url: /static
  static_dir: static/
- url: .*
  script: hi.wsgi.application

libraries:
- name: MySQLdb
  version: 1.2.5

skip_files:
- ^(.*/)?#.*#$
- ^(.*/)?.*~$
- ^(.*/)?.*\.py[co]$
- ^(.*/)?.*/RCS/.*$
- ^(.*/)?\..*$
- ^env/.*$

appengine_config.py
from google.appengine.ext import vendor

#vendor.add('lib')  <--- tried that too
vendor.add(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'lib'))

The error is caused because the lib folder (which contains the Django framework and other libraries) isn't getting added to Python's PATH, but why? Why is GAE ignoring my appengine_config.py?


text:
Q: Ratio of areas of two triangles Based on the figure below, what is the ratio of the area of triangle $CGI$ to the area of triangle $ABC$, in terms of $\theta$?

A: All the right triangles in the picture are similar, so (noting $|BG|=|BD|$)
$$\begin{align}
\frac{|\triangle CIG|}{|\triangle ABC|} &= \left(\frac{|CG|}{|AC|}\right)^2 = \left(\frac{|BC|-|BG|}{|AC|}\right)^2 = \left(\frac{|BC|-|BD|}{|AC|}\right)^2 \\
&= \left(\frac{|BC|\left(1-\sin\theta\right)}{|AC|}\right)^2 = \left(\frac{|BC|}{|AC|}\right)^2\left(1-\sin\theta\right)^2 \\
&= \tan^2\theta \left(1-\sin\theta\right)^2
\end{align}$$

A: Fixing $AC$ at length $1$, $\dfrac{\text{Area}(CGI)}{\text{Area}(ABC)}$ is seen to be $\dfrac{\left ( {\dfrac{\sin(\theta)}{\cos(\theta)}} - \sin(\theta)\tan(\theta)\right )^2 \tan(\theta)}{\sin(\theta) \left (\cos(\theta)+ \sin(\theta)\tan(\theta) \right)}$. Mathematica simplifies this ratio to $(\sin(\theta)-1)^2\tan^2(\theta)$.

A: Mathematica isn't needed for the simplification, which is quite straightforward:
$$\begin{align*}
\frac{\left({\sin\theta \over \cos\theta} - \sin\theta\tan\theta\right)^2 \tan\theta}{\sin\theta\big(\cos\theta+\sin\theta\tan\theta\big)}&=\frac{\left(\tan\theta-\sin\theta\tan\theta\right)^2\tan\theta}{\frac{\sin\theta}{\cos\theta}\left(\cos^2\theta+\sin^2\theta\right)}\\\\
&=\frac{\tan^3\theta(1-\sin\theta)^2}{\tan\theta}\\\\
&=\tan^2\theta(1-\sin\theta)^2\;.
\end{align*}$$


text:
Q: Twilio voice recording in ASP.Core I'm building a new application and one of the its function is communication between seller and customer. For this reason I want to use Twilio API.
So let's imagine we have two person: seller and customer, and they are going to communicate. My idea is that these two person shouldn't know real phone number each other, so I buy two phone numbers from Twilio, one for seller and one for customer and connect them with real phones in my app. For convenience I've created TwiML App in Twilio console and set REQUEST and STATUS CALLBACK URLs for Voice calls, these urls are pointed to Webhook in my app. My application is based on .Net Core, but I still use full .Net4.6 framework, because there are no some .dlls for .Net Core and seems Twilio helpers for C# have also been built for full .Net framework. Any way, my webhook method looks like:
    [HttpPost("call")]
    public IActionResult IncomingCall(VoiceRequest request) {
        // some logic
        VoiceResponse response = new VoiceResponse();
        response.Dial({real_seller_number}, callerId: {virtual_customer_number}, record: "record-from-ringing-dual");

        return Content(response.ToString(), "application/xml");
    }

Here, let's imagine I'm customer, I want to call seller, I call its virtual Twilio number, Twilio makes a request to this webhook and it make a call to real seller's number from virtual customer number. This is OK and works as intended.
When the call ends, Twilio makes a request to STATUS CALLBACK url, and this methos looks like:
    [HttpPost("call/callback")]
    public IActionResult IncomingCallCallback(StatusCallbackRequest request) {
        // some logic
        return Ok("Handled");
    }

In a first method you can see I want to record conversation for internal  reason, and I expected RecordingSid and RecordingUrl in second method, but I always get them null. I can see the recording in Twilio console, but cannot get them via API, that's my problem. I spent a lot of time and read a lot of docs, but didn't find clear explanation how to do it right. Can someone help me?

A: Twilio developer evangelist here.
When recording calls the recording might not be ready by the time you receive the statusCallback request. Instead you should set a recordingStatusCallback URL which will be called when the recording is complete and ready.
[HttpPost("call")]
public IActionResult IncomingCall(VoiceRequest request) {
    // some logic
    VoiceResponse response = new VoiceResponse();
    response.Dial({real_seller_number},
        callerId: {virtual_customer_number},
        record: "record-from-ringing-dual",
        recordingStatusCallback: {url_in_your_application_that_processes_recordings}
    );

    return Content(response.ToString(), "application/xml");
}


text:
Q: Updating ImageView and TextView OnClick for a Single Card in RecyclerView in Android I have an app that I want to do the following:
When the user clicks on a star imageView it updates the server (adds posts to my favoritePosts, and +1 to likesCounter), but it should also update the imageView (liked to  unliked and vice versa), and the textView with the number of likes on the cardView I clicked.
Currently, the imageView changes, and it updates server correctly, but there are some things that do not work the way they should, such as:
Some titles disappear and reappear when I click the star imageView (to add posts to favorites), and the textView is almost never updated at all, and when it is, it sometimes decreases instead of increasing and vice versa. In my database it is updated correctly, like is added/removed correctly, likes counter is updated correctly, also when I exit and reenter the activity it is updated correctly.
I have tried this, this, this, this, this, etc, but none of these solutions worked for me.
UserPostsAdapter:
public class UserPostsAdapter extends RecyclerView.Adapter<UserPostsAdapter.PostsViewHolder> {

    private List<UserPosts> postItems;
    private Context context;
    private SQLiteHandler db;
    private static final String TAG = UserPosts.class.getSimpleName();

    class PostsViewHolder extends RecyclerView.ViewHolder {
        TextView userPostsTitle, userPostsDate, userPost, textViewStars, textViewComments;
        ImageView imageViewDisplayComments, imageViewReply, imageViewCommentStar;
        String pCcontactId, postId;

        PostsViewHolder(View itemView) {
            super(itemView);

            userPostsTitle = (TextView) itemView.findViewById(R.id.userPostsTitle);
            userPostsDate = (TextView) itemView.findViewById(R.id.userPostsDate);
            userPost = (TextView) itemView.findViewById(R.id.userPost);

            textViewStars = (TextView) itemView.findViewById(R.id.textViewStars);
            textViewComments = (TextView) itemView.findViewById(R.id.textViewComments);

            imageViewCommentStar = (ImageView) itemView.findViewById(R.id.imageViewCommentStar);
            imageViewDisplayComments = (ImageView) itemView.findViewById(R.id.imageViewDisplayComments);
            imageViewReply = (ImageView) itemView.findViewById(R.id.imageViewReply);
        }
    }

    public UserPostsAdapter(List<UserPosts> postsList, Context context) {
        this.postItems = postsList;
        this.context = context;
    }

    @Override
    public UserPostsAdapter.PostsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_user_post, parent, false);

        return new UserPostsAdapter.PostsViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(final UserPostsAdapter.PostsViewHolder holder, int position) {
        final UserPosts post = postItems.get(position);

        db = new SQLiteHandler(context.getApplicationContext());
        HashMap<String, String> user = db.getUserDetails();
        final String currentUserId = user.get("uid");

        if (post.getTitle() != null && !post.getTitle().isEmpty()) {
            holder.userPostsTitle.setText(post.getTitle());
        } else {
            holder.userPostsTitle.setVisibility(View.GONE);
        }
        holder.userPostsDate.setText(post.getCreatedDateTime());
        holder.userPost.setText(post.getPostedText());
        if (Integer.parseInt(post.getLikesNumber()) > 0) {
            holder.textViewStars.setText(post.getLikesNumber());
        }
        holder.textViewComments.setText(post.getCommentsNumber());

        holder.pCcontactId = post.getUserId();
        final String postId = holder.postId = post.getId();

        if (post.getFavouritePost()) {
            holder.imageViewCommentStar.setImageResource(R.drawable.ic_icon_star_ppdcolor);
        } else {
            holder.imageViewCommentStar.setImageResource(R.drawable.ic_icon_star_outline_ppdcolor);
        }

        holder.imageViewCommentStar.setOnClickListener(new View.OnClickListener() {

            boolean isPressed = post.getFavouritePost();

            @Override
            public void onClick(View v) {
                if (isPressed) {
                    ApiInterface apiService =
                        ApiClient.getClient().create(ApiInterface.class);

                    Call<DefaultResponse> call = apiService.removePostFavourite(currentUserId, postId);
                    call.enqueue(new Callback<DefaultResponse>() {
                        @Override
                        public void onResponse(Call<DefaultResponse> call, retrofit2.Response<DefaultResponse> response) {
                            boolean success = response.body().isSuccess();

                             onFavouriteClicked(position);
                        }

                        @Override
                        public void onFailure(Call<DefaultResponse> call, Throwable t) {

                        Log.e(TAG, t.toString());
                        }
                    });
                } else {
                    ApiInterface apiService =
                        ApiClient.getClient().create(ApiInterface.class);

                    Call<DefaultResponse> call = apiService.addPostFavourite(currentUserId, postId);
                    call.enqueue(new Callback<DefaultResponse>() {
                        @Override
                        public void onResponse(Call<DefaultResponse> call, retrofit2.Response<DefaultResponse> response) {
                            boolean success = response.body().isSuccess();

                             onFavouriteClicked(position);
                        }

                        @Override
                        public void onFailure(Call<DefaultResponse> call, Throwable t) {
                            Log.e(TAG, t.toString());
                        }
                    });
                }
                isPressed = !isPressed;
            }
        });

        holder.imageViewDisplayComments.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });

        holder.imageViewReply.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                AlertDialog.Builder addCommentBuilder = new AlertDialog.Builder(context);
                LayoutInflater inflater = LayoutInflater.from(context);
                View addCommentView = inflater.inflate(R.layout.popup_add_comment_reply, null);
                final EditText addCommentReplyEditText = (EditText) addCommentView.findViewById(R.id.addCommentReplyEditText);
                FloatingActionButton imageViewCommentReply = (FloatingActionButton) addCommentView.findViewById(R.id.imageViewCommentReply);

                addCommentBuilder.setView(addCommentView);
                final AlertDialog addCommentReply = addCommentBuilder.create();
                addCommentReply.show();

                imageViewCommentReply.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        if (!addCommentReplyEditText.getText().toString().isEmpty()) {
                        addCommentReply.dismiss();
                        } else {
                            Toast.makeText(context,
                                    R.string.failure,
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        });
    }

    private void onFavouriteClicked(int position) {
        UserPosts post = postItems.get(position);
        post.setFavouritePost(!post.getFavouritePost());
        postItems.set(position, post);
        notifyItemChanged(position);
    }

    @Override
    public int getItemCount() {
        return postItems.size();
    }
}

Cardview:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="10dp"
    android:gravity="center"
    android:orientation="vertical">

    <android.support.v7.widget.CardView
        android:id="@+id/userPostsCardView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:padding="5dp"
        card_view:cardCornerRadius="4dp">

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="5dp">

            <TextView
                android:id="@+id/userPostsTitle"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="1dp"
                android:paddingEnd="5dp"
                android:paddingStart="5dp"
                android:textStyle="bold"
                tools:ignore="RtlHardcoded,SpUsage" />

            <TextView
                android:id="@+id/userPostsDate"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/userPostsTitle"
                android:layout_marginTop="1dip"
                android:paddingEnd="5dp"
                android:paddingStart="5dp"
                android:textColor="@color/aluminum"
                tools:ignore="RtlHardcoded,SpUsage" />

            <TextView
                android:id="@+id/userPost"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_below="@id/userPostsDate"
                android:padding="5dp"/>

            <View
                android:id="@+id/divider"
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:layout_below="@+id/userPost"
                android:layout_marginBottom="8dp"
                android:layout_marginTop="8dp"
                android:background="#B6B6B6" />

            <LinearLayout
                android:id="@+id/idLLUserPostsFooter"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_alignParentBottom="true"
                android:layout_alignParentStart="true"
                android:layout_below="@+id/divider"
                android:orientation="horizontal"
                android:weightSum="9">

                <ImageView
                    android:id="@+id/imageViewCommentStar"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:contentDescription="@string/star"
                    android:padding="5dp"/>

                <TextView
                    android:id="@+id/textViewStars"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="3"
                    android:padding="5dp" />

                <ImageView
                    android:id="@+id/imageViewDisplayComments"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:contentDescription="@string/comments"
                    android:padding="5dp"
                    card_view:srcCompat="@drawable/comment_multiple_outline_ppdcolor" />

                <TextView
                    android:id="@+id/textViewComments"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="3"
                    android:padding="5dp" />

                <ImageView
                    android:id="@+id/imageViewReply"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:contentDescription="@string/reply"
                    android:padding="5dp"
                    card_view:srcCompat="@drawable/reply_ppdcolor" />
            </LinearLayout>
        </RelativeLayout>
    </android.support.v7.widget.CardView>

    <TextView
        android:id="@+id/userAppId"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="@string/number_zero"
        android:visibility="gone" />

    <TextView
        android:id="@+id/userContactId"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="@string/number_zero"
        android:visibility="gone" />
</LinearLayout>


text:
Q: WebFont won't show So I would like to set a font for my webpage body, and so I created a core.css file with this code:
@font-face {
font-family: Bebas;
src: url('../fonts/bebas-webfont.ttf') format('truetype'),
     url('../fonts/bebas-webfont.eot') format('embedded-opentype'),
     url('../fonts/bebas-webfont.woff') format('woff'),
     url('../fonts/bebas-webfont.svg') format('svg');
font-weight: 700;
}

body{
background: url('../images/bg_1.png')repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
font-family: 'Bebas', serif;
}

But it doesn't seem to show up... not even when I try ... I tried this with another font and it worked, I have no idea of what is going on. The font files are in the right place.
SOLUTION:
As i was using 2 fonts i forgot to use two seperate @font-face {
once i separated them, worked like a charm

A: what you are creating here is the font for weight=700. try to add font-eweight:700; to the body:
body{
background: url('../images/bg_1.png')repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
font-family: 'Bebas', serif;
font-weight:700;
}

A: Check your browsers developer console. The answer is there.
Also, the path is relative to your css file and not your html. And font-weight is unnecessary here.

A: As i was using 2 fonts i forgot to use two seperate @font-face { once i separated them, worked like a charm


text:
Q: Is it OK to modify the default location for Python-3.6.0.exe to just the C drive? I am a 65 year old "newbie" and generally use default options when downloading.  Python.org wants to download to an obscure directory such as

C:\Users\Facdev\AppData\Local\Programs\Python\Python36-32".

Is there anything wrong with downloading instead to "C:"?

A: This should not pose a problem, as long as the directory is specified correctly in you PATH.

A: It is OK to modify the location where you will download and install Python. However, I would advise against doing so if you are unfamiliar with how system environment variables and PATH locations work in Windows.
Why does it matter?
Once you have the python executable (in your case Python-3.6.0.exe) on your system, your computer needs to know where it is in order to execute it! If you place the executable in a location like the main directory on the C: drive your computer does not care. Your computer also does not care if the executable is deep down in the AppData\ directory.
By changing the default behavior you run a risk when troubleshooting unexpected behavior that instructions will not be written for your situation. This is OK as long as you understand what you will need to change in order to apply the troubleshooting techniques listed on documentation, blog posts, and forums.
Because of those factors and this being a new process for you, I recommend sticking to the default. You can change the location later, once you understand what doing so means. Learning to program can be frustrating and trying to grasp managing the software environment only adds to the frustration. Tackle that issue later.
Good luck on your new adventure! I hope you learn to enjoy writing your own programs in python!