text:
Q: Java FX SplitPane I have two Canvas instances in my SplitPane. When I drag the divider bar, one Canvas grows. When I drag the divider back, the Canvas doesn't really shrink. It holds the same maximum dimension as it was ever given by the resize. So I only see a part of that Canvas, however much space the SplitPane can show. Similar behavior occurs for the other Canvas. I need them to shrink back to fit into their respective sections when the divider is dragged, not just have them clipped.
The Canvases are wrapped in a one-element GridPane subclass before being added to the SplitPane. This wrapper class resizes the Canvas whenever the wrapper resizes.
The problem is that the SplitPane is giving the wrong sizes: whatever the maximum size ever was for that Canvas. Why would the SplitPane think this is the right thing to do?

A: package experimental;

import javafx.application.Application;
import javafx.geometry.Orientation;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.control.SplitPane;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;

public class SplitPaneProblem extends Application {

    static public void main(String[] args) {launch(args);}

    public SplitPaneProblem() { }

    @Override
    public void start(Stage primaryStage) throws Exception {
        SplitPane splitPane = new SplitPane();
        splitPane.setOrientation(Orientation.VERTICAL);
        splitPane.getItems().add(new TestPane("0",new Canvas()));
        splitPane.getItems().add(new TestPane("1",new Canvas()));
        primaryStage.setScene(new Scene(splitPane));
        primaryStage.setHeight(400);
        primaryStage.setWidth(400);
        primaryStage.show();
    }

    public class TestPane extends AnchorPane {

        String name;
        Canvas canvas;

        public TestPane(String name,Canvas canvas) {
            super();
            this.canvas = canvas;
            getChildren().add(canvas);
//1         canvas.setManaged(false);
            this.name = name;
        }

        @Override
        public void resize(double width,double height) {
            System.out.println(name+" input  "+width+' '+height);
            super.resize(width, height);
            System.out.println(name+" panel  "+getWidth()+' '+getHeight());
//0         canvas.setWidth (width);
//0         canvas.setHeight(height);
            System.out.println(name+" canvas "+canvas.getWidth()+' '+canvas.getHeight());
        }
    }
}

Canvas doesn't resize by itself. Run the code as shown, and drag the divider up and down. Read the console output. The size of the Canvas instances never changes from (0,0).
Uncomment the lines beginning with //0 and run it again. Now the Canvas instances are forcibly resized to the size of their containing panes. Drag the divider up and down. Note that the Canvas instances grow vertically, but they never shrink, even though the code tells them to. Imagine we were drawing an X across the corners of the Canvases. These X drawings would grow with the divider. But when you drag the divider the other direction, the image is clipped, but it never shrinks.
Uncomment the line beginning with //1 and run it again. Now it works.
I don't know about you, but I think this is bizarre.

A: Based on this post from Jasper Potts, you can create a resizable canvas, and use it in your split pane.
class ResizableCanvas extends Pane {

    private final int id;
    private final Canvas canvas = new Canvas();

    public ResizableCanvas(int id) {
        this.id=id;
        getChildren().add(canvas);
    }

    @Override
    protected void layoutChildren() {
        final int top = (int)snappedTopInset();
        final int right = (int)snappedRightInset();
        final int bottom = (int)snappedBottomInset();
        final int left = (int)snappedLeftInset();
        final int w = (int)getWidth() - left - right;
        final int h = (int)getHeight() - top - bottom;
        canvas.setLayoutX(left);
        canvas.setLayoutY(top);
        if (w != canvas.getWidth() || h != canvas.getHeight()) {
            canvas.setWidth(w);
            canvas.setHeight(h);
            GraphicsContext gc = canvas.getGraphicsContext2D();
            gc.clearRect(0, 0, w, h);
            if(id==1){
                gc.setFill(Color.BLUE);
                gc.fillOval(5, 5, w-10, h-10);
            } else {
                gc.setFill(Color.RED);
                gc.fillRect(10, 10, w-20, h-20);
            }
        }
    }
}

@Override
public void start(Stage stage) throws Exception {
    ResizableCanvas canvas1 = new ResizableCanvas(1);
    ResizableCanvas canvas2 = new ResizableCanvas(2);

    SplitPane split = new SplitPane();
    split.getItems().addAll(canvas1,canvas2);

    stage.setScene(new Scene(split, 600, 400));
    stage.show();
}

Note that everytime the scene is resized or the split content divider is moved, both canvases will be redrawn, but always with the exact size of their respective panes. As he also suggests, you may consider snapshot your canvas contents, and use an image to improve performance.


text:
Q: Emulate Mac trackpad with MS Precision trackpad I'm currently working on a hackintosh machine with a precision trackpad, which is currently being handled by VoodooPS2 which is the staple for hackintosh keyboard/trackpad support. The precision trackpad is Microsoft's attempt to rival the Mac trackpad and as such provides all the same multitouch information that the Mac trackpad does. As a research project and for some utility, I'd like to create a relay that uses calls from a precision trackpad to emulate an actual Mac trackpad for proper gesture support and better tracking.
Some resources:
FingerMgmt

*

*Touches on the information held in trackpad multitouch support in macOS.

*Information taken from the trackpad includes the x,y coordinates of finger touches as well as the minor / major axes of touch points. Touch points are actually treated as ellipsoids instead of circles; luckily this information doesn't seem to be used that much by the operating system.

*The bottom of the page mentions that the Mac trackpad most likely supplies a 2d bitmap of pressure data to the OS; precision trackpads don't seem to provide this so trackpad data will have to be supplied at the multitouch level.

Precision trackpad

*

*Information sent about a finger contact includes x,y (of course) along with a "confidence" value for palm rejection and the width and height of a contact.

*The height and width of a finger contact should be able to be used to estimate the major / minor ellipsoid for Mac multitouch.
The theory seems to check out; the challenge will be creating a virtual trackpad device and relaying / translating input from the actual hardware to it.
Is this a possibility? What would be a good way to start to play with the raw data from the precision trackpad on macOS?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to override color value in colors.xml? I overwrite some system color which is responsible for the color of the status bar when entering Action Mode in my colors.xml file in this manner:
<color name="abc_input_method_navigation_guard" tools:override="true">@color/colorPrimaryDark</color>

But when I create a new theme, and expose a new color of colorPrimaryDark:
<style name="AppTheme.NewTheme">
    <item name="colorPrimaryDark">#000000</item>
</style>

It does not change in colors.xml file and in and "abc_input_method_navigation_guard" overwrites with old color.
How can I override color value in colors.xml in my theme or maybe programmatically?
I tried this but it didnt work for me:
<style name="AppTheme.NewTheme">
    <item name="colorPrimaryDark" tools:override="true">#000000</item>
</style>

A: Colors is where you should create color and give it a name :
colors.xml
<color name="abc_input_method_navigation_guard">#000000</color>

styles.xml
   <style name="AppTheme.NewTheme">
<item name="colorPrimaryDark">@color/abc_input_method_navigation_guard</item>
   </style>


text:
Q: ggplot2: colour legend with many different data sources I have two or more data sources. Each has different colour groups. I do
pPrice = ggplot() +
    geom_step(data = data1, aes(x=Time, y=v, colour=TYPE)) +
    geom_point(data = data2, aes(x=Time, y=x, colour=g), shape = 18, size = 5)
pPrice

And I get:

I want to seperate the line and the dots into two legends. The first has a line in it with the corresponding colors and the second has the diamonds with the corresponding colors. My full graph contains even more layers with different data sets, an extra set with geom_points and 'x's instead of diamonds and colour groups. I would like to sperate those as well.


text: Q: Does Azure Active Directory authenticate Virtual and Physical server access? Just like Active Directory installed in Windows Servers, does Azure Active Directory does the same thing? Note: Please feel free to edit my question if its not relevant.


text:
Q: Radio button keeps re-rendering when clicked I'm fetching data from an API, and I map over it in order to generate 5 groups of radio buttons. Everything works fine, except for the fact that when I click on any of the input radio buttons, it seems to re-render the entire component or something, as you can see below (this is only one of the groups, but it happens and affects all of them):

Here's the code:
import { useState } from "react";
import { nanoid } from "nanoid";

export default function Question({ data }) {
    const [userSelections, setUserSelections] = useState({
        question0: "",
        question1: "",
        question2: "",
        question3: "",
        question4: "",
    })

    function handleSelection(event) {
        const {name, value} = event.target

        setUserSelections(prevSelection => {
            return {
                ...prevSelection,
                [name]: value
            }
        })
    }

    const renderQuestionBlocks = data.map(({question, correct_answer, incorrect_answers, uniqueQuestionId}, questionIndex) => {
        const allAnswers = [...incorrect_answers, correct_answer].sort((a, b) => 0.5 - Math.random())
        data.uniqueQuestionId = nanoid()

        return (
            <form className={`question--container question${questionIndex}`} key={data.uniqueQuestionId}>

{question.replace(/"/g, '"').replace(/'/g, "'")}

                {allAnswers.map((answer, answerIndex) => {
                    data[questionIndex].uniqueAnswerId = nanoid()

                    return (
                    <div
                        key={data[questionIndex].uniqueAnswerId}
                        className={`choice--container question${questionIndex}`}
                    >
                        <input
                            type="radio"
                            name={`question${questionIndex}`}
                            id={`question${questionIndex}option${answerIndex}`}
                            value={answer}
                            checked={userSelections[`question${questionIndex}`] === answer}
                            onChange={handleSelection}
                        />
                        <label htmlFor={`question${questionIndex}option${answerIndex}`}>{answer.replace(/"/g, '"').replace(/'/g, "'")}

                    )
                })}
            </form>
        )
    })

    return (

            {renderQuestionBlocks}
            <button>Check answers</button>

    )
}

A:
it seems to re-render the entire component or something

Updating state re-renders a component.  This is expected and correct (and fundamentally necessary) behavior in React.  But... What does your component do when it renders?
It randomly sorts the values:
const allAnswers = [...incorrect_answers, correct_answer].sort((a, b) => 0.5 - Math.random())

It sounds like either that sort shouldn't be random, or should be randomized outside the scope of this component, or that randomization should itself be persisted in state so you can re-use it on each render.
For example, if you just need a random number for the component then you can generate one and keep it in state:
const [randonNumber] = useState(Math.random());

This will randomly generate a number, but won't re-generate one on every render.  Then you can consistently use the same randomly generated number:
const allAnswers = [...incorrect_answers, correct_answer].sort((a, b) => 0.5 - randonNumber)


text:
Q: Check empty editbox objects in ListView I have listview with N number of rows and the same number EditText object. User should enter values in each EditText, if hi misses one of entries application have to put focus on that field.
This is how I check entries:
    for(int i=0;i<listOfInouts.size();i++){

     View view=lv.getChildAt(i);
     EditText editText=(EditText) view.findViewById(R.id.txtMyEntry);

     if (editText.getText().toString().isEmpty()
     {
       // Toast - here goes toast message
       editText.setFocusable(true);
     }
     else
     {
       // do something else
     }

}

But this code doesn't work well. Is this correct way to check values insied EditText?

A: if (TextUtils.isEmpty(editText.getText())
     {
       // Toast - here goes toast message
       editText.setFocusable(true);
     }
     else
     {
       // do something else
     }

try this code
and the view which is used in a list view get recycled , so u cant get the exact view at each  position (Only Visible view get correct values )


text:
Q: Sequelize join and relationships I have a database running, but I've not been able to execute a join between two tables. I already did a join between two other tables but this one doesn't work.
On my db.js file I establish the following relationship between tables:
db.diet.hasMany(db.meal, {as : 'Diet', foreignKey : 'dietId'});

And on my server.js file, I'm trying to build this query:
db.meal.findAll({
    include : [db.diet],
    where : {
        dietId : idDiet
    }
}).then(function (meals) {
    res.json(meals)
});

This gives me the following error:
ReferenceError: idDiet is not defined

I also tried querying the diet table like this:
db.diet.findAll({
    include :[db.meal],
    where : {
        idDiet : dietId
    }
}).then(function (meals) {
    res.json(meals);
});

But it also gives me an error:
ReferenceError: dietId is not defined

Any ideas on how I can improve this?
Thank you so much, any help is appreciated. If more information is needed please let me know.

A: This:
db.diet.hasMany(db.meal, {as : 'Diet', foreignKey : 'dietId'});

Should be this:
db.diet.hasMany(db.meal, {as : 'Meals'});

You're saying that diet has many meal models known as Meals so you'll be able to include the Meals with the diet.
db.diet.findAll({
  include: [db.meal] // include the meal in the query ("join")
}).then((diet) => {
  // diet.Meals is a array of "meal" models that
  // belongs to the queried "diet"
});

I've answered as similiar question like this over here: https://stackoverflow.com/a/39822966/3254198


text:
Q: Moodle installation dataroot directory problem I am trying to install moodle and I need to put moodledata on server A and install moodle on other server B
I did a directory named dataroot on server A and installed virtual host to be accessed through http://A.A.A.A/moodledata and I accesses it through google chrome and gave permissions to apache to read/write on it
I stared installing moodle on Server B but when I asked to put the dataroot directory, I put it http://A.A.A.A/moodledata but I received an error message Data directory (http://A.A.A.A/moodledata ) cannot be created by the installer
I changed the dataroot directory by deleting http so that it is now A.A.A.A/moodledata and it is accepted but when I finished I received an error  $CFG->dataroot is not configured properly, directory does not exist or is not accessible! Exiting.
and when I trying to install moodle again, I receive the same error without allowing me to complete the installation
What do you suggest?
I am trying to install Moodle 3.5.3 on centos7
Thanks and best regards

A: The dataroot directory on your server should be somewhere that is not accessible from the internet and you should specify the path, not the URL of the directory.
e.g. if the code for your site was on your server at:
/var/www/moodle
And your dataroot directory was
/var/moodledata
Then you should write:
$CFG->dataroot = '/var/moodledata';

A: Moodle expects the dataroot to be a local directory, preferably outside of the web root.
You could create an NFS share on Server A and mount it on Server B, that way dataroot will appear to Moodle like it is a local folder.


text:
Q: ClassNotFoundException when executing a .jar, but not when executing with classpath
I have this code in Java that I'm to compile and execute. The code itself is working and the compilation goes ok. When I execute the code giving the classpath, with a command like "java -cp classes:lib/* main.class parameters" it works well.

But the problem is when I try to generate a jarfile and execute it with a command like "java -jar file.jar parameters". When I execute this, code starts running but crashes on the following error:

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/http/ssl/TrustStrategy

at java.lang.ClassLoader.defineClass1(Native Method)

at java.lang.ClassLoader.defineClass(ClassLoader.java:634)

at [...]
Caused by: java.lang.ClassNotFoundException: org.apache.http.ssl.TrustStrategy

at [...]
... 17 more

I thought it could be missing some class on MANIFEST, though for what I could find on the internet, the package providing this class is httpcore, which is included there. I tried to modify in many ways the manifest with no success, so I don't believe the problem is on this file.

I don't know if it helps, but the code is being compiled with ant and I have some 3rd-party libs stored on a lib folder, which is on the classpath of MANIFEST.
I'm compiling on a computer with:
openjdk version "1.8.0_131"
OpenJDK Runtime Environment (build 1.8.0_131-b12)
OpenJDK 64-Bit Server VM (build 25.131-b12, mixed mode)

And running it on a computer with:
java version "1.6.0_24"
OpenJDK Runtime Environment (IcedTea6 1.11.3) (6b24-1.11.3-1ubuntu0.12.04.1)
OpenJDK 64-Bit Server VM (build 20.0-b12, mixed mode)

Does anyone know why may this be happening?


text:
Q: Question regarding proof of: For any x and any base b, $x = log_{b}(b^{x}$) I am reading 'A beginners guide to discrete mathematics'. And i stumbled on this proof they have:
Theorem. For any x and any base b, $x = log_{b}(b^{x})$
Proof. By definition, $u = b\text{ }log_{b}(u)$. Putting $ u = b^{x}$ we have $bx = b(log_{b}(b^{x}))$. So comparing the exponents, $x = log_{b}(b^{x})$
How the book writes it:
Why does $u = b\text{ }log_{b}(u)$ make any sense? e.g. $16 = 2*log_{2}(16)$,
so what they are saying is that $16 = 8$ ? or is there something i am misunderstanding by the way they write "By definition" ?

A: This appear to be a typo.  Try $u = b^{\log_b u}$, which is true (and differs mostly in white space).  The same typographical error comes when setting $u =b^x$, but "$bx$" appears on the left-hand side of the substituted equation.


text:
Q: Is there a way to override id for disabled options in a select before submitting the form in Rails I am trying to disable the options inside the dropdown for archived records and want to know is there a way to override the id/ send value to the form before submitting. I have 2 dropdown which uses the same id and while editing the form for already disabled records(in the 2nd dropdown), id is getting passed from the 1st dropdown since the disabled record will not be sent.How to override this id while submitting the form?

    <%= form.label :discrepancy_id, 'Discrepancy Category' %>
    <%= form.select :discrepancy_id, Discrepancy.get_first_category_details, {include_blank: "Select the Discrepancy category....." , :selected => (@fault.id.nil?) ? nil : Fault.selectedCategory(@fault.discrepancy_id)},:class => 'failure-category', :required => true%>

    <%= form.label :discrepancy_id, 'Discrepancy Name' %>
    <%= form.select :discrepancy_id, grouped_options_for_select(Discrepancy.get_grouped_names_based_on_category, {:selected => @fault.discrepancy_id, :disabled => Discrepancy.get_archived_entries}), {include_blank: "Select the Discrepancy Name....."}, :class => 'failure-mode', :required => true %>


text:
Q: How to modify JFrame using JRootPane? I want to remove title bar from JFrame and then using JRootPane I want to create custom title bar component in Synth L&F. I have searched and found that I can customize frame's look by using the root pane.
How to modify JFrame using JRootPane?


text:
Q: Extending interface signature without editing code in multiple places I have an interface and existing code which implements this interface:
public interface IBusinessService<T> where T : class
{
    Task Add(T category);

    Task Delete(T category);

    Task Update(T category);

    Task<IEnumerable<T>> GetAll();

    Task<T> GetById(int id);
}

Now some id has type of Guid. So I cannot use this method to send Guid id:
var id = Guid.NewGuid()
var result = GetById(id);

So we need that id parameter can be type of Guid. It would be ideal if it is possible:
public interface IBusinessService<T> where T : class
{
    /* ... the other code is omitted for the brevity */
    Task<T> GetById(Guid or int id );
}

What I thought to implement is to create a new method with parameter type of Guid:
public interface IBusinessService<T> where T : class
{
    Task Add(T category);

    Task Delete(T category);

    Task Update(T category);

    Task<IEnumerable<T>> GetAll();

    Task<T> GetById(int id);

    Task<T> GetById(Guid id);
}

But if I will do this, then I need to edit so many code. So it looks like it is  not a good solution.
Is there a way to add another type of id to the interface method GetById without breaking changes?

A: This seems to be a design problem (interface/API design) in the first place. It should be clear from the beginning whether IDs are represented by a Guid or a raw int value. But not both. Usually you try to use a protocol to control the client-server communication or at least by defining a server API. This protocol would define what values the API expects and the client must take care to input them in the correct format.
Consider to stay with the int ID an use a custom conversion from Guid to int where required. Alternatively introduce a table (Dictionary) where you store pairs of Guid and int values. So for each Guid that enters your application you internally generate a integer which will replace the Guid. But there must be some constraints or algorithm to guarantee the uniqueness of the IDs especially when using int values. But I assume when you are using int for unique IDs you already have an algorithm to generate those IDs.
Adding members to an interface is always a breaking change.
Since you are not using C# 8 you can't make use of the new Default Interface Method feature.
So, if you can accept breaking changes then you could refactor the interface to take one more generic parameter for the id parameter.
You could also change the type of the id parameter from int to object. But this would also introduce the costs of boxing/unboxing (in order to convert value types like int to object). I personally think using either object or string would be the best. I don't know your web interface but string could be the preferred ID type.
So the best solution, in case you can't accept those breaking changes, would be to implement a new interface e.g., IGuidIdBusinessService<T>:
public interface IGuidIdBusinessService<T> : IBusinessService<T> where T : class
{
  Task<T> GetByGuid(Guid id);
}

Implementing the interfaces:
public class MyClass : IGuidIdBusinessService<object>
{
  #region Implementation of IBusinessService<object>

  ...

  // Either throw NotSupportedException or implement conversion
  public async Task<object> GetById(int id)
  {
    Guid guid = ConvertIntToGuid(id);
    return GetByGuid(guid);
  }

  #endregion

  #region Implementation of IGuidIdBusinessService<object>

  public async Task<object> GetByGuid(Guid id) => throw new NotImplementedException();

  #endregion
}

A: I really don't see the problem as big as you describe -- "But if I will do this, then I need to edit so many code"
How many implementations do you have. 20? Key here, implementation vs usages. Usages can be many or very many.
Looks like your goal is to keep usage intact as
var id = Guid.NewGuid();
var result = someInst.GetById(id);
// or
var id = 5;
var result = someInst.GetById(id);

No problem, you need minimal changes. This happens all the time
public interface IBusinessService<T> where T : class
{
    Task<T> GetById(object id);    // NOTE - change to 'object'
}

Now, you just need to change only few of your implementations that you have to distinct Guid from int
public Task<T> GetById(object id)
{
    if (id is int i)
        return ProcessIdAsInt<T>(i);
    else if (id is Guid g)
        return ProcessIdAsGuid<T>(g);
    else
        throw new InvalidOperationException("Supplied data type not supported");
}

So, the changes are minimal. Usages will remain intact. Nothing unusual.


text:
Q: Update/redraw canvas on clicking a button I'm using cirque.js plugin to show circle percentage values drawn with a canvas.
Here's a JSFIDDLE I made that should contain all the info with plugin code.
Initially, the circle gets drawn correctly, with the correct value.
Issue: When I try to update the value via a function on clicking a button, nothing happens, not working, I think the canvas needs to be drawn again with the new value?
Q: How can I update the circle percentage value asynchronously?
$('.cirque').cirque ({ //this works
    radius: 40,
    value: 65,
    total: 100,
    trackColor: '#ccc',
    arcColor: '#5cb85c',
    label: 'percent',
    lineWidth: 12
});

$('#update').click(function (e) {
    updateCircle(50); //this does not work
});

function updateCircle(val){
    $('.cirque').cirque ({
        radius: 40,
        value: val,
        total: 100,
        trackColor: '#ccc',
        arcColor: '#5cb85c',
        label: 'percent',
        lineWidth: 12
    });
}

A: I've not find any function to update value in this plugin. But you can update value with a trick. Replace the div having class cirque with a same div and initialize it with new value like following. Hope this will help you.
function updateCircle(val){
    var cirque=$('

');
    $('.cirque').replaceWith(cirque);

    cirque.cirque ({
         radius: 40,
         value: val,
         total: 100,
         trackColor: '#ccc',
         arcColor: '#5cb85c',
         label: 'percent',
         lineWidth: 12
    });
}

Updated Fiddle: https://jsfiddle.net/8d9sw1yg/2/


text:
Q: Splitting txt file to new lines I have a big txt file goes like this:
"Hello how are you878SAZIm Fine Thank you878SAZHave a Nice Day"
I want to split this file to new line every time i see "878SAZ" and save it as txt.. ive tried couple of things but im unable to do this, what to do?
$txt_file = file_get_contents('C:/files/file.txt');
$rows = explode("878SAZ", $txt_file);

array_shift($rows);
foreach($rows as $row)
{
}
file_put_contents("C:/files/file.txt, $rows)";

A: You can try replacing the string '878SAZ' with "\n" which means newline
$input = file_get_contents(YOUR_FILE_PATH);
$text = str_replace('878SAZ', "\n", $input);
file_put_contents(WRITE_FILE_PATH, $text);


text:
Q: Using Count distinct case in sql and group by multiple columns I have a query that works great (listed below). The issue I am having is we have run into a patient that has had event on two different days and because I am grouping by the PATNUM, it is only showing it as one.
How can I get it to count 1 for each time if the PATNUM and SCHDT are different
Example:
      PATNUM    SCHDT
      12345      30817
      12345      30817
      54321      30817
      54321      30717

PATNUM 12345 should only count once while PATNUM 54321 should count twice.
My count statement is this:
SELECT ph.*, pi.*,
COUNT(DISTINCT CASE WHEN `SERVTYPE` IN ('INPT','INPFOP','INFOBS','IP') AND Complete ='7' THEN pi.PATNUM ELSE NULL END) AS count1,
COUNT(DISTINCT CASE WHEN `SERVTYPE` IN ('INPT','INPFOP','INFOBS','IP') AND Complete ='8' THEN pi.PATNUM ELSE NULL END) AS count2
FROM patientinfo as pi
INNER JOIN physicians as ph ON pi.SURGEON=ph.PName
WHERE PID NOT IN ('1355','988','767','1289','484','2784')
GROUP BY SURGEON
ORDER BY Dept,SURGEON ASC

A: Which columns do you want to see?
You can adjust your GROUP BY:
SELECT
ph.pname,
ph.specialty,
SUM(CASE WHEN complete = 7 THEN 1 ELSE 0 END) count1,
SUM(CASE WHEN complete = 8 THEN 1 ELSE 0 END) count2
FROM
(
  SELECT
  DISTINCT
  surgeon,
  patnum,
  schdt,
  complete,
  servtype
  FROM patientinfo
  WHERE complete IN (7,8)
  AND servtype IN ('INPT','INPFOP','INFOBS','IP')
  AND pid NOT IN ('1355','988','767','1289','484','2784')
) pisub
INNER JOIN physicians ph ON pisub.surgeon = ph.pname
GROUP BY ph.pname, ph.specialty
ORDER BY ph.pname, ph.specialty;

Also, I would make a few suggestions:

*

*If you're going to give your tables an alias, then use the alias when referring to any column in your query. I've made a guess here about some of your columns as to which table they come from (e.g. dept), so feel free to change it if it is not correct

*You don't need to select all records from both tables if you don't need them

*The query won't run if you don't GROUP BY all columns you're selecting. I've written about this for Oracle and SQL in general, but actually in MySQL I think it does run but show incorrect results.


text:
Q: Variable assignment and expansion at the same time Why does
for i in {1..5}; do x="${i}" echo "$x"; done

not output
1
2
3
4
5

?
What is the right way to do this?
(Tested for i in {1..5}; do x=$(i) echo "$x"; done

-bash: i: command not found

and others)

A: You asked for answers to two questions:

*

*You asked for an explanation of why your current code does not produce the expected output.

*You asked for the correct way to write your code so that it does produce the expected output.
Looking at your code, I can see two likely explanations for why you wrote your code the way you did:

*

*There might be some slight confusion about the syntax of a for-loop.

*There might be some slight confusion about the order of evaluation in what's called a simple command.
for-loop syntax
In the first case, I would say that you're missing a semicolon after your variable assignment. If you want to write your for-loop on a single line then you need to put a semi-colon after each command in the loop body. Try this instead:
for i in {1..5}; do x="${i}"; echo "$x"; done

Another alternative would be to write the for-loop using the multi-line syntax with newlines in place of the semicolons:
for i in {1..5}
do
x="${i}"
echo "${x}"
done

You can also mix-and-match semicolons and newlines, e.g.:
for i in {1..5}; do
x="${i}"; echo "${x}"
done

evaluation of simple commands
In the second case, I would say that you probably had assumed that the variable assignment in the prologue of the command (i.e. the x="$i" assignment) occurs before the variable expansion in the body of the command (i.e. the expansion of ${x} in echo "${x}"). But this is actually not the case. To verify this we can refer to the page on simple command expansion in the Bash Manual or to the subsection on simple commands in the Posix Specification. Both of these references include the following passage:

A "simple command" is a sequence of optional variable assignments and redirections, in any sequence, optionally followed by words and redirections, terminated by a control operator.
When a given simple command is required to be executed (that is, when any conditional construct such as an AND-OR list or a case statement has not bypassed the simple command), the following expansions, assignments, and redirections shall all be performed from the beginning of the command text to the end:

*

*The words that are recognized as variable assignments or redirections according to Shell Grammar Rules are saved for processing in steps 3 and 4.

*The words that are not variable assignments or redirections shall be expanded. If any fields remain following their expansion, the first field shall be considered the command name and remaining fields are the arguments for the command.

*Redirections shall be performed as described in Redirection.

*Each variable assignment shall be expanded for tilde expansion, parameter expansion, command substitution, arithmetic expansion, and quote removal prior to assigning the value.

Notice that step 2 is where the variable expansion in the command occurs, but step 1 tells us that the variable assignments are saved until steps 3 and 4. It follows that the expression echo "${x}" is expanded to echo "" before the assignment x="${i}" takes place. This explains why you were getting empty output.
For further discussion on this topic see the following posts:

*

*Why is setting a variable before a command legal in bash?

*bash script's temporary value on command

A: Answering your question as asked

Why does for i in {1..5}; do x="${i}" echo "$x"; done not output 1, 2, 3, 4, 5?

The reason is to do with the order of which operations are evaluated during execution. Look at this command
x="${i}" echo "$x"

What this does is

*

*Substitute variables with their values

*Assign a temporary value to variable x

*Execute the command

So you get

*

*x=1 echo "" (or x=2 echo "", etc.)

*For the duration of this command, x is set to the value 1

*The command is executed: echo ""
It's probable you meant this command to be two instructions: assign a value to x, output its value. But in shell syntax what you wrote was perfectly legal code so the shell executed it without objection.

A: In zsh, using a third ${var::=value} form of the ${var=value}, ${var:=value} Bourne operators where the assignment is unconditional (as opposed to only if var is unset/empty).
for i in {1..5}; do echo ${x::=$i}; done

Or:
for i ({1..5}) echo ${x::=$i}

In bash:
set -o posix # so the value of x remains after eval returns
for i in {1..5}; do x=$i eval 'echo "$x"'; done

That is, you need $x to have been set at the time the code that contains its expansion is evaluated.
For decimal integer values like here, you can also do:
for i in {1..5}; do echo "$((x = i))"; done

Or you can always use the ${var:=value} Bourne operator after having set x to the empty string.
for i in {1..5}; do x=; echo "${x:=$i}"; done


text:
Q: Usage of 'write for' Does the sentence sound good to you, given the context that I have been spending some time preparing for the test:

I am becoming increasingly happier with the way I write for the IELTS
  exam.

Thanks!

A: "The way I write for the IELTS exam" sounds fine. Because you are practicing for the IELTS exam, your writing is done for the purpose of being used on that exam, so that wording is fine. You are happy with your writing with regards to its usage on the exam.
That said, in your sentence I would either change "happier" to "happy" or remove the word "increasingly." "Happier" implies that your happiness is increasing, so you don't need to use both terms. Either say "I am becoming increasingly happy" or "I am becoming happier."


text:
Q: Retraction of disk minus a point For any $p\in D^2$ consider $D^2\setminus\{ p\}$.
I am trying to show this retracts to the circle $S^1$ so that I can show $D^2\setminus\{ p\}$ does not have the fixed point property, since $S^1$ does and it is conserved by a retraction.
I can see that if $p$ is in the interior of the disk then the map $x\mapsto \frac{x} {\| x \|} $ is a retraction, but I cannot see how this would work with $p \in \partial D^2$.
Is there an explicit retraction? And if not is there another way to approach this question?

A: Let $p$ be in the interior of $D^2$. For any $x\in D^2\setminus \{p\}$ consider the ray from $p$ to $x$. This is given by $p + t(x-p)$ for $t\in[0,\infty)$ and there exists a unique $t_0\in(0,\infty)$ such that $\|p+t_0(x-p)\| = 1$. We define a map $f\colon D^2\setminus\{p\}\to S^1$, $x\mapsto p+t_0(x-p)$. This is well defined, continuous (one  can work out an explicit formula) and if $\|x\|=1$, then $f(x)=x$. So $f$ is a retraction.
Note that if $p\in\partial D^2$, the map $f$ gives a retraction of  $D^2\setminus\{p\}$ to $S^1\setminus\{p\}$ which is contractible.


text:
Q: How to plot the cross section of event horizon of hairy kerr black hole? I was growing through the paper "Parameter estimation of hairy Kerr black holes from its shadow and
constraints from M87*" whose link is https://arxiv.org/abs/2103.11417. In the paper it plots the cross sections of event horizon in fig.3 using eq.3.
Can anyone please explain how it is done?


text:
Q: How to resize image for list view i am loading image and title for list view from webservices text is f9 but image is too big.how to resize it and i want to set text in right side and image in left side in each row of list view .i am using this method  Bitmap resized = Bitmap.createScaledBitmap(bitmap, 70, 70, true);     but nothing appearing on emulator This is my costant class where i am loading image
public static Bitmap loadPhotoBitmap(URL url) {
Bitmap bitmap = null ;
InputStream in = null;
BufferedOutputStream out = null;
BufferedOutputStream bfs = null;

try {
FileOutputStream fos = new FileOutputStream("/sdcard/photo-tmp.jpg");
bfs = new BufferedOutputStream(fos);

in = new BufferedInputStream(url.openStream(),8192);

final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, 8192);
copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();

bfs.write(data, 0, data.length);
bfs.flush();

BitmapFactory.Options opt = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, opt);

//System.out.println(resized);
Bitmap resized = Bitmap.createScaledBitmap(bitmap, 70,70, true);
    return  resized;
} catch (IOException e) {
// android.util.Log.e("message", "Could not load photo: " + this, e);
System.out.println("Exception while loading image");
} finally {
closeStream(in);
closeStream(out);
closeStream(bfs);
}
System.out.println("returning");
return  bitmap;
}

LazyAdapter.class
public View getView(int position, View convertView, ViewGroup parent) {

System.out.println("Exception before..");
String strUrl = Constants.vctrImagePath.elementAt(counter).toString();// getting imgurl
System.out.println("Urls...." + strUrl);
URL url =null;
try {
url = new URL(strUrl);
} catch (MalformedURLException e) {
    // TODO Auto-generated catch block
e.printStackTrace();
}

Bitmap bitmap = Constants.loadPhotoBitmap(url);
//Bitmap resized = Bitmap.createScaledBitmap(bitmap, 70, 70, true);

RelativeLayout layout = new RelativeLayout(mContext);
RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT);

TextView text1 = new TextView(mContext);
text1.setText(Constants.vctrCategory.elementAt(counter).toString());
LayoutParams params1 = new       LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
params1.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
text1.setLayoutParams(params1);
text1.setTextSize(20);
text1.setGravity(Gravity.RIGHT);
layout.addView(text1);
ImageView img = new ImageView(mContext);
img.setImageBitmap(bitmap);

layout.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
layout.addView(img);
counter++;
return layout;
}

private void setContentView(ImageView image) {
// TODO Auto-generated method stub

}

A: Instead of
BitmapFactory.Options opt = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, opt);

Replace that with
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inPreferredConfig = Bitmap.Config.ARGB_8888;
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, opts);

A:
problem was not in my this bitmapfactory class.i hav resolved my isssue.
  i just change code in my lazy adapter class.

Bitmap bitmap = Constants.DownloadImage(strUrl);
    Bitmap resized=null;
    if(bitmap!=null){
    resized = Bitmap.createScaledBitmap(bitmap, 100, 100, true);
}else{
    System.out.println(strUrl+ "no image here");
}

before i was resizing image in  my list view.while it will resize in adpter class of list view.


text:
Q: Рандомное врашение квадрата на JQuery Привет, мне нужно сделать на HTML странице кнопку и прямоугольник . При нажатии на кнопку прямоугольник должен будет вращаться, каждый щелчок будет вращать прямоугольник случайным углом. Анимация вращения должна длится 300ms. Подскажите, пожалуйста с чего начать, что да как. Сделать все это надо при помши JQuery.

A:

$(function() {
  $('#but').on('click', function() {
    var deg = Math.random() * (180 - 30) + 30;
    $('#div').animate({
      borderSpacing: deg
    }, {
      step: function(now, fx) {
        $(this).css('-webkit-transform', 'rotate(' + now + 'deg)');
        $(this).css('-moz-transform', 'rotate(' + now + 'deg)');
        $(this).css('transform', 'rotate(' + now + 'deg)');
      },
      duration: 'slow'
    }, 'linear');
  });
});
#div {
  background-color: tomato;
  width: 100px;
  height: 100px;
  margin: 50px;
}

<input type="button" value="Вращать" id="but">


text:
Q: How to make an animation move relative to the parent element and not the body? I want to use this css animation as a section in my home page.
body{
    margin: 0;
    padding: 0;
    overflow: hidden;
}

.flower-section{
    position: absolute;
    width: 100%;
    height: 100%;
    background: radial-gradient(#333, #000);
}

.set{
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    z-index: 1;
}

.set div{
    position: absolute;
    display: block;
}

.set div img{
    background-color: red;
    padding: 1rem;
}

.set div:nth-child(1){
    left: 5%;
    animation: animate 15s linear infinite;
    animation-delay: -7s;
}
.set div:nth-child(2){
    left: 15%;
    animation: animate 20s linear infinite;
    animation-delay: -5s;
}
.set div:nth-child(3){
    left: 25%;
    animation: animate 25s linear infinite;
}
.set div:nth-child(4){
    left: 35%;
    animation: animate 15s linear infinite;
}
.set div:nth-child(5){
    left: 50%;
    animation: animate 18s linear infinite;
    animation-delay: -10s;
}
.set div:nth-child(6){
    left: 65%;
    animation: animate 12s linear infinite;
    animation-delay: -8s;
}
.set div:nth-child(7){
    left: 75%;
    animation: animate 14s linear infinite;
}
.set div:nth-child(8){
    left: 85%;
    animation: animate 15s linear infinite;
    animation-delay: -7s;
}
.set div:nth-child(9){
    left: 95%;
    animation: animate 19s linear infinite;
}

@keyframes animate{
    0%{
        top: -10%;
        opacity: 0;
        transform: translateX(20px) rotate(0deg);
    }
    10%{
        opacity: 1;
    }
    20%{
        transform: translateX(-20px) rotate(45deg);
    }
    40%{
        transform: translateX(-20px) rotate(90deg);
    }
    60%{
        transform: translateX(20px) rotate(135deg);
    }
    80%{
        transform: translateX(-20px) rotate(180deg);
    }
    100%{
        top:110%;
        transform: translateX(-20px) rotate(225deg);
    }
}

.set2{
    transform: scale(1.5) rotateY(180deg);
    filter: blur(2px);
    z-index: 0;
}

.set3{
    transform: scale(0.8) rotateX(180deg);
    filter: blur(4px);
    z-index: 0;
}

.flower-title{
    position: absolute;
    top: 50%;
    transform: translateY(-50% );
    width: 100%;
    text-align: center;
    color: #fff;
    margin: 0;
    padding: 0;
    font-size: 5em;
    font-family: sans-serif;
    z-index: 1;
}

But when I try to implement it this happens.
The red squares seem to be moving relative to the whole body instead of the parent container. How can I fix that?
I've already tried making the parents and the children position relative, but it didn't seem to work.

A: The reason the red squares were just floating all over the place is that you had set your container element to position: relative; but then never set any of the squares to position: absolute;. By setting the squares to position absolute, everything you do on them will now be relative to their container.
What I did was set all the .set div:nth-child(n) to position: absolute;. I then went and gave main a background of white so that the red squares would have something to fall behind. I as well gave the nav a position of relative so that I could give it a higher z-index than the red squares, and so the squares start behind the nav instead of in-front.
I as well set the height of the container to a fixed height of 600px as apposed to 100% as the height in % is a relative unit, so the resulting height depends on the height of parent element's height.
Here is how I was able to achieve the outcome that you were looking for:

body{
    margin: 0;
    padding: 0;
}

main {
  background: white;
}

nav {
  position: relative;
  z-index: 99;
}

.flower-section{
    position: relative;
    height: 600px;
    background: radial-gradient(#333, #000);
    /* overflow: hidden; */
}

.set{
    position: relative;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    /* z-index: 1; */
}

.set div{
    position: relative;
    display: block;
}
.set div img{
    background-color: red;
    padding: 1rem;
}

.set div:nth-child(1){
    position: absolute;
    left: 5%;
    animation: animate 15s linear infinite;
    animation-delay: -7s;
}
.set div:nth-child(2){
    position: absolute;
    left: 15%;
    animation: animate 20s linear infinite;
    animation-delay: -5s;
}
.set div:nth-child(3){
    position: absolute;
    left: 25%;
    animation: animate 25s linear infinite;
}
.set div:nth-child(4){
    position: absolute;
    left: 35%;
    animation: animate 15s linear infinite;
}
.set div:nth-child(5){
    position: absolute;
    left: 50%;
    animation: animate 18s linear infinite;
    animation-delay: -10s;
}
.set div:nth-child(6){
    position: absolute;
    left: 65%;
    animation: animate 12s linear infinite;
    animation-delay: -8s;
}
.set div:nth-child(7){
    position: absolute;
    left: 75%;
    animation: animate 14s linear infinite;
}
.set div:nth-child(8){
    position: absolute;
    left: 85%;
    animation: animate 15s linear infinite;
    animation-delay: -7s;
}
.set div:nth-child(9){
    position: absolute;
    left: 95%;
    animation: animate 19s linear infinite;
}

@keyframes animate{
    0%{
        top: -10%;
        opacity: 0;
        transform: translateX(20px) rotate(0deg);
    }
    10%{
        opacity: 1;
    }
    20%{
        transform: translateX(-20px) rotate(45deg);
    }
    40%{
        transform: translateX(-20px) rotate(90deg);
    }
    60%{
        transform: translateX(20px) rotate(135deg);
    }
    80%{
        transform: translateX(-20px) rotate(180deg);
    }
    100%{
        top:110%;
        transform: translateX(-20px) rotate(225deg);
    }
}

.set2{
    position: absolute;
    transform: scale(1.5) rotateY(180deg);
    filter: blur(2px);
    /* z-index: 0; */
}

.set3{
    position: absolute;
    transform: scale(0.8) rotateX(180deg);
    filter: blur(4px);
    /* z-index: 0; */
}

.flower-title{
    position: absolute;
    top: 50%;
    transform: translateY(-50% );
    width: 100%;
    text-align: center;
    color: #fff;
    margin: 0;
    padding: 0;
    font-size: 5em;
    font-family: sans-serif;
    /* z-index: 1; */
}


text:
Q: Magento: Thousands of similar products, two attributes that change the price We have a poster store.
Posters come in varying sizes and have optional frames.
Both the size and frame change the price.
These are print-on-demand, so no inventory is needed.
In the Magento world:

*

*This can't be a simple product with attributes due to the pricing differences (?)

*Configurable products seem like a maintenance nightmare (every variation is a separate product)

*"Custom Options" tab similarly have to be created for each individual product, and presumably have separate db entries for every product

*I've read about custom product types, but there don't seem to be any complete examples anywhere

is there no drop-in solution for this kind of problem in Magento?

A: "Custom Options" tab is the way to go, and if you try any other solution, it will be like trying to fight against the core system and the way it is designed.
The Custom options is one product entry, with multiple entries in the Product Options data tables.
It will not be that hard to maintain.
The problem you are referring to is a feature in Magento, and not really a problem for some of us.
Options can also help you later on with Shipping calculations on different frame sizes, and so forth.
You will be happy later on, if you do not go with a custom solution, as that will cause you way more grieve than maintaining bits of data.
The Bulk update feature in the Admin area can help you update data accross multiple products quickly too.


text:
Q: Randomizing an angle?

var elem = document.getElementById('canvas');
var context = elem.getContext('2d');

context.fillStyle = '#000';
context.lineWidth = 1;

var depth = 9;

function drawLine(x1, y1, x2, y2, brightness){
  context.moveTo(x1, y1);
  context.lineTo(x2, y2);
}

function drawTree(x1, y1, angle, depth){
  if (depth !== 0){
   var thisAngle = angle*(Math.random()-0.5)
    var x2 = x1 + (Math.cos(thisAngle) * depth * 10.0);
    var y2 = y1 + (Math.sin(thisAngle) * depth * 10.0);
    drawLine(x1, y1, x2, y2, depth);
    drawTree(x2, y2, angle - 0.34906585, depth - 1);
    drawTree(x2, y2, angle + 0.34906585, depth - 1);
  }
}

context.beginPath();
drawTree(300, 500, -1.57, depth);
context.closePath();
context.stroke();
<html>
<body>
<canvas id="canvas" width="1000" height="700"></canvas>

</body>
</html>

I have a function that draws a tree-fractal in a canvas:
function drawTree(x1, y1, angle, depth){
  if (depth !== 0){
    var x2 = x1 + (Math.cos(angle) * depth * 10.0);
    var y2 = y1 + (Math.sin(angle) * depth * 10.0);
    drawLine(x1, y1, x2, y2, depth);
    drawTree(x2, y2, angle - 0.34906585, depth - 1);
    drawTree(x2, y2, angle + 0.34906585, depth - 1);
  }
}

I'm trying to randomize the fractal a bit to make it look more organic. I tried this:
function drawTree(x1, y1, angle, depth){
  if (depth !== 0){
    var thisAngle = angle*(Math.random()-0.5)
    var x2 = x1 + (Math.cos(thisAngle) * depth * 10.0);
    var y2 = y1 + (Math.sin(thisAngle) * depth * 10.0);
    drawLine(x1, y1, x2, y2, depth);
    drawTree(x2, y2, angle - 0.34906585, depth - 1);
    drawTree(x2, y2, angle + 0.34906585, depth - 1);
  }
}

For some reason this seems to be biased torwards the value 0. The tree leans torwards the right. I don't understand why.

A: You need to add a random offset (in the range ±0.5 or less) to your angle, not multiply by that factor.

var elem = document.getElementById('canvas');
var context = elem.getContext('2d');

context.fillStyle = '#000';
context.lineWidth = 1;

var depth = 9;

function drawLine(x1, y1, x2, y2, brightness){
  context.moveTo(x1, y1);
  context.lineTo(x2, y2);
}

function drawTree(x1, y1, angle, depth){
  if (depth !== 0) {
    var delta = Math.random()-0.5;
    var x2 = x1 + (Math.cos(angle + delta) * depth * 10.0);
    var y2 = y1 + (Math.sin(angle + delta) * depth * 10.0);
    drawLine(x1, y1, x2, y2, depth);
    drawTree(x2, y2, angle - 0.34906585, depth - 1);
    drawTree(x2, y2, angle + 0.34906585, depth - 1);
  }
}

context.beginPath();
drawTree(300, 500, -1.57, depth);
context.closePath();
context.stroke();
<html>
<body>
<canvas id="canvas" width="1000" height="700"></canvas>

</body>
</html>

You may also wish to experiment with changing the angle passed to the recursive calls (e.g. use the modified angle instead of the original one).


text:
Q: Display an alert/message on publish in Sitecore I need to display a warning message to the author before they publish. With the code below, I get the following exception:

Object Reference not set to the instance of an object exception.
  Sitecore.Context.ClientPage.ClientResponse is null.

How can I fix this? Or is there a different way to do this?
public class PublishPipeline :
Sitecore.Publishing.Pipelines.PublishItem.PerformAction
{
    public override void Process(PublishItemContext context)
    {
        Sitecore.Context.ClientPage.ClientResponse.Alert("This will publish to the production site!");
        base.Process(context);
    }
}

<processor type="MyProject.PublishPipeline, MyAssembly" />


text:
Q: setState is not updating inside componentWillReceiveProps I feel like I am calling setState in the proper manner, but want to make sure I didn't make a call in the wrong place. Seeing if anyone can spot the error. In the console log the state is holding the previous value, not the new cleared value. Here is the code I have:
componentWillReceiveProps(nextProps) {
    if (nextProps.value !== this.state.value && typeof nextProps.value !== 'undefined'){
        let changeVal = nextProps.value;
        let changeDisplay = nextProps.value;
        if(this.props.entryType === 'date') changeVal = Moment(nextProps.displayValue).format(this.props.format).toString();
        if(this.props.entryType === 'currency'||this.props.entryType === 'number'){
            if(isNaN(parseFloat(changeVal))){
                changeVal = 0;
                changeDisplay = 0;
            }
        }
        if(this.props.entryType === 'drop' || this.props.entryType === 'boolean'){
            if(this.props.options) {
                this.props.options.map(x => {
                    if (x.value == changeVal || x.sortOrder == changeVal){
                        changeDisplay = x.label;
                        changeVal = x.value;
                    }
                })
            }
        }
        this.setState({value: changeVal, displayValue: changeDisplay, selectValue:{value:changeVal, label:changeDisplay}}, ()=>{
            console.log("current displayValue",this.state, nextProps, this.props)
        });
    }
}

Clearly I am calling console after setState, but the value does not update.
EDIT: Thanks for the responses. I am going to attempt to rip apart the props update state method. I created a drag and drop system, where items can be dragged in and out of groups. Works great, but it has a Container >  Tree > Item > QueryValue components in that hierarchy. The problem here comes in that Container needs to know the entire tree, to be able to build it out, but the edits to the contents occur in QueryValue. So I have a method I pass through the chain which allows me to notify Container of any changes. But I may need to decouple the Container data from the QueryValue data.

A: Your code is quite complex so I would suggest trying to refactor it.
But in any case, I would suggest using "componentDidUpdate"

*

*because "componentWillReceiveProps" is deprecated and can lead to side-effects and complex state flow, which favor bugs in your code

React docs (for "componentDidUpdate"):
https://reactjs.org/docs/react-component.html#componentdidupdate

React docs (for "UNSAFE_componentWillReceiveProps"):
https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops

Note:

Using this lifecycle method often leads to bugs and inconsistencies, and for that reason it is going to be deprecated in the future.

If you need to perform a side effect (for example, data fetching or an animation) in response to a change in props, use componentDidUpdate lifecycle instead.

For other use cases, follow the recommendations in this blog post about derived state.

If you used componentWillReceiveProps for re-computing some data only when a prop changes, use a memoization helper instead.

If you used componentWillReceiveProps to "reset" some state when a prop changes, consider either making a component fully controlled or fully uncontrolled with a key instead.

In very rare cases, you might want to use the getDerivedStateFromProps lifecycle as a last resort.

A: As explained by @Tzook Bar Noy the React team strongly suggest against using componentWillReceiveProps lifecycle method. You can use componentDidUpdate but it is also considered a bad practice to use setState inside that function: it could lead to infinite loop componentWillUpdate -> setState -> componentWillUpdate -> setState -> etc if you don't manage your boundaries correctly.
I suggest, as you are not using instance methods in your code, to use the new getDerivedStateFromProps static method. This method is called with current props and state when component mounts, and when component updates. It uses the returned object to optionally update component state.
Check in react docs if it applies to your use case. Interesting article:  https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html
Your code could look like so:
    getDerivedStateFromProps(props, state) {
        if (props.value !== state.value && typeof props.value !== 'undefined') {
            let changeVal = props.value
            let changeDisplay = props.value
            if (entryType === 'date')
                changeVal = Moment(props.displayValue)
                    .format(format)
                    .toString()
            if (
                entryType === 'currency' ||
                entryType === 'number'
            ) {
                if (isNaN(parseFloat(changeVal))) {
                    changeVal = 0
                    changeDisplay = 0
                }
            }
            if (
                entryType === 'drop' ||
                entryType === 'boolean'
            ) {
                if (options) {
                    options.map(x => {
                        if (x.value == changeVal || x.sortOrder == changeVal) {
                            changeDisplay = x.label
                            changeVal = x.value
                        }
                    })
                }
            }
            return {
                value: changeVal,
                displayValue: changeDisplay,
                selectValue: { value: changeVal, label: changeDisplay }
            }
        }
        return null
    }


text:
Q: c# Automapper ProjectTo DTO with count property i have a question about automapper ProjectTo method, i have this DTO:
public class GetUsersResponse
{
    public GetUsersResponse()
    {
        Users = new List<UserLite>();
    }

    public int Count { get; set; }
    public List<UserLite> Users { get; set; }
}

public class UserLite
{
    public string Email { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
}

i have an iqueryable result from EF with this code:
var users = await _userManager.Users.Where(user => user.Name.Contains(search)
                                                       || user.Surname.Contains(search)
                                                       || user.Email.Contains(search)
                                                       || user.FiscalCode.Contains(search))
            .PageBy(user => user.Email, page, pageSize, orderByAscending)
            .ProjectTo<UserLite>(_mapper.ConfigurationProvider)
            .ToListAsync();

My question is if is possible to use ProjectTo and set both count and Users, or i should use the classic map method from automapper?
Currently my autommaper configuration is like this for projeaction:
public class UserMapperProfile : Profile
{
    public UserMapperProfile()
    {
        CreateProjection<User, UserLite>(MemberList.Destination);
    }
}

I hope I was clear. Thanks


text:
Q: MySql – Query to get contextual results
I have a nice little brain teaser and really hope someone can help me.
I have the following table:

ID ------------------- Relevance
  1 -------------------- 2,3,4,5,7
  2 -------------------- 1,3,5,7,9
  3 -------------------- 1,2,4,5,6

What I would like to do is write a query to order the results by the rows that provide the highest relevance to my input list:

1,5,6

So order by the row that offers the most matches from the list and from the relevance column. Row ID 3 has the most matches, with 1,5 and 6. Row ID 2 has only 2 matches whereas Row ID 1 only has 1 match - so in the above example, the answer would be:
ROW ID's in order of relevance

ID
  3
  2
  1

Thank you in advance

A: You could try creating a FULLTEXT index on the relevance column, and use the MATCH function.
SELECT ID FROM myTable WHERE MATCH (relevante) AGAINST ('1 5 6');

note that I'm separating the terms using a blank space. I believe using commas could be interpreted as looking for the exact string "1,5,6".


text:
Q: How can I cancel MouseWheel Windows Message in TRichEdit control to fix scrolling? In the application I'm working on, there is a TListView and a TRichEdit in a form.
When the user click an item in the TListView, it loads TRichEdit text. My problem occurs when the text is longer then the height of the TRichEdit.
If I scroll with the Mouse Wheel really quickly and I continue scrolling even when the scrolling bar is at bottom, then I click another item in the TListview (which make TRichEdit->Text change), the scrolling sometimes continues on the newly loaded text.
My hypothesis is that there is some kind of Windows Message not yet processed and when I click another item, the scroll message is read and the scrolling continue?!
I already tried to disable then enable the TRichEdit on the TRichEdit MouseLeave without success (scrolling continue when I change selected item of TListView).
I was wondering if anybody have any ideas?
[edit]
Ok so I'm trying the solution from Remy but PeekMessage() doesn't catch any WM_VSCROLL, WM_HSCROLL, WM_MOUSEWHEEL. I tried to catch it before and after the function DescriptionChanged(); but neither of them catch the scroll message.
void __fastcall TfrmJob::lvDescriptionSelectItem(TObject *Sender, TListItem *Item, bool Selected)
{

    //Function where ListView load item into RichEdit->Text
    DescriptionChanged();

    MSG msg;

    //Loop while there is messages ("If no messages are available, the return value is zero")
    while (PeekMessage(&msg, NULL /*reDocDetail->Handle*/ /*lvDescription->Handle*/, 0, 0, PM_REMOVE | PM_QS_INPUT) > 0)
    {
        //Trying to catch Scroll message
        if(msg.message == WM_VSCROLL || msg.message == WM_HSCROLL || msg.message == WM_MOUSEWHEEL)
        {
            TranslateMessage (&msg);
            DispatchMessage (&msg);
        }
    }
}


text:
Q: How to check if a promise returns an empty object The goal is to check if the user is logged in. When the page is loaded, a promise is used to check the current user. If the user is not logged in, the server returns {}. My problem is that I don't know how to check if the promise returns the empty object {}.
I defined a resource:
myapp.factory('User', function($resource) {
    return $resource('/users/:userId', {userId: '@id'}, {
    current: {method:'GET', params: {userId: 'current'}}});
});

which is used in a resolve property in ui-router. The resolve is used to provide data to my controller.
resolve: {
    user: ['User', function(User) {
        return User.current();
    }]
},
controller : function($scope, $window, user) {
    $scope.user = user;

    $scope.userLoggedIn = !isEmptyObject(user);

    function isEmptyObject(obj) {
        console.log(obj);
        var name;
        for (name in obj) {
        return false;
        }
        return true;
    }
}

The express server side is defined as:
app.get('/users/current', function(req, res) {
    console.log(req.isAuthenticated());
    console.log(req.user);
    if (req.isAuthenticated()) {
        res.send(req.user);
    } else {
        console.log("Not Authenticated");
        res.send({});
    }
});

The issue is that the isEmptyObject function always returns true.

A: Try:
    function isEmptyObject(obj) {

       if (obj.length && obj.length > 0)
           return false;

       if (obj.length === 0)
          return true;
    }

BTW, underscore.js plugin has own method:
isEmpty_.isEmpty(object)

Returns true if object contains no values (no enumerable own-properties).
 _.isEmpty([1, 2, 3]);
 => false

 _.isEmpty({});
 => true


text:
Q: Grails 3 and Spring Security @Secured I know I can configure the secured annotation by specifying something like this on my controller:
@Secured('ROLE_ADMINISTRATORS')
class HomeController {
    ... methods and things
}

Now, how would I go about injecting a property from the YML configuration file? Say my current YML file reads as follows:
security:
    roles:
        admins: ROLE_ADMINISTRATORS
        viewers: ROLE_VIEWERS
        managers: ROLE_MANAGERS

If I change my @Secured annotation to read as this
@Secured('${security.roles.admins}')

the application complains with this error:
EL1041E:(pos 1): After parsing a valid expression, there is still more data in the expression: 'lcurly({)'

I then try to use the @PreAuthorize annotation, this post shows how it can be used, as this:
@PreAuthorize('${security.roles.admins}')

But I get an error stating:
Attribute 'value' should have type 'java.lang.String'; but found type 'java.lang.Object' in @org.springframework.security.access.prepost.PreAuthorize

Is it possible to inject properties into either one of these annotations, so that I can use it with Grails 3 and Spring Security LDAP plugin?


text:
Q: How to add alternate Row color for DevExpress.UI.Xaml.Grid Gridcontrol? I am trying to add alternate row colors for odd and even rows for devexpress xaml grid in windows 8 Metro App. How can I accomplish this? I am googling a lot but in most of my samples I am getting namespace reference mismatched. I am using Devexpress v12.2.

A: Thus?:
<MultiDataTrigger>
    <MultiDataTrigger.Conditions>
        <Condition Binding="{Binding Path=EvenRow}" Value="False"/>
        <Condition Binding="{Binding Path=SelectionState}" Value="None"/>
    </MultiDataTrigger.Conditions>
    <Setter Property="Background" Value="{StaticResource evenRowBrush}" />
</MultiDataTrigger>

<MultiDataTrigger>
    <MultiDataTrigger.Conditions>
        <Condition Binding="{Binding Path=EvenRow}" Value="True"/>
        <Condition Binding="{Binding Path=SelectionState}" Value="None"/>
    </MultiDataTrigger.Conditions>
    <Setter Property="Background" Value="{StaticResource oddRowBrush}" />
</MultiDataTrigger>

A: You can modify the GridControl.ItemTemplate (row template). This approach is demonstrated in Conditional Formatting demo module (DevExpress v12.2 feature demos):
<UserControl
    ...
    xmlns:Grid="using:DevExpress.UI.Xaml.Grid">
    <UserControl.Resources>
        <local:RowHandleToBackgroundConverter x:Key="RowHandleToBackgroundConverter" EvenRowBackground="Transparent" OddRowBackground="#FFDFE7EF"/>
    </UserControl.Resources>
...
<Grid:GridControl.ItemTemplate>
    <DataTemplate>
        <Border Background="{Binding Path=RowControl.RowHandle, RelativeSource={RelativeSource Mode=TemplatedParent}, Converter={StaticResource RowHandleToBackgroundConverter}}">
            <Grid:GridCellPanel x:Name="PART_RowPanel" RowControl="{Binding Path=RowControl, RelativeSource={RelativeSource Mode=TemplatedParent}}" Margin="0,0,1,0"/>
        </Border>
    </DataTemplate>
</Grid:GridControl.ItemTemplate>

The 'RowHandleToBackgroundConverter' class is implemented as follows:
public class RowHandleToBackgroundConverter : IValueConverter {
    public Brush EvenRowBackground { get; set; }
    public Brush OddRowBackground { get; set; }
    public object Convert(object value, Type targetType, object parameter, string language) {
        if(((int)value % 2) == 0)
            return OddRowBackground;
        else
            return EvenRowBackground;
    }
    public object ConvertBack(object value, Type targetType, object parameter, string language) {
        throw new NotImplementedException();
    }
}


text:
Q: How do I get the external IP address of a client if the server and the client are on the same domain? The long and the short of this is that we use a 3rd party to retrieve addresses from the PAF database (and similar for non-UK addresses). They need the client IP address to deduce what sort of addresses (ie: British/Irish/Canadian/Amoeboid-Zingat'ularian) to default the search to.
We pass this traffic through a relay written as an MVC controller [HttpPost] action, and inject the authentication on the server, for security reasons.
For our customers that have our software hosted on Azure, this is easy, as the traffic between MVC controller action and the 3rd party's javascript will pass through an internet-facing firewall, and the IP gained using Request.ServerVariables["REMOTE_USER"] will be good enough.
BUT what if they have our software installed on premise? Then, isnt it possible that the IP this method gives me is one that only means anything to the local network?
If I could detect the difference, I could decide whether or not to send the IP: and therefore get the 3rd party to decide.

A: If the case is them installing your software on their servers would it not be easier to record what the location is at installation time or on application start.
No need then to read on each and every call.  http://bot.whatismyipaddress.com/ called once and stored in app memory would suffice.
I am also assuming that the clients of this installed software will be in the same location.  Almost certainly if they have local ip addresses.


text:
Q: Ionic ng-hide/ng-show scroll issue I'm currently building an Ionic app for someone but I'm having some issues with ng-hide and ng-scroll. The page shows a product and you can switch between seeing the nutrients or the ingredients. I use ng-hide & ng-show to achieve this. However, when I press the button to switch data, the scrollbar messes up. I attached a short video to demonstrate the issue:
https://youtu.be/W9fFMdSLW8s
Here are some code snippets that may be useful to gain insight.

Codepen
EDIT: I made a codepen that reproduces the issue:
http://codepen.io/JeremyKeusters/pen/qmBwzp
Steps to reproduce:

*

*Please make sure that the browser height and the preview window is not too big.

*Click on the green 'show nutrients' button and try to scroll down immediately. (use mouse & drag to scroll as if you were using a phone)

*You will notice that you're blocked and can't scroll down. The solution is to wait a couple of seconds until the scroll 'resets'.

*Try to click the green button on the bottom again. You'll see that there's a lot of white space in which you can scroll (the scroll area is too big). The solution is again to wait a couple of seconds until it resets.

Code
template page:

      Ingredient
      Amount per
100 ml

      {{ingredient.Ingredient.Name}}
      {{ingredient.Ingredient.Amount_g}} g

      Nutrient
      Amount per 100 ml
      % of reference quantity

      {{nutrient.Nutrient.Name}}

      {{(nutrient.Nutrient.PartOfRI * 100 | number:0)}} %

  <button ng-click="toggle=!toggle;" class="button button-block button-balanced default-button">
    Show ingredients
    Show nutrients
  </button>

controller.js:
  bottleSrv.getBottleDetails($rootScope.scannedCode).then(function (data) {
    $scope.JuiceID = data.JuiceID;
    $scope.ExpirationDate = data.ExpirationDate;
    $scope.JuiceImg = "https://someurl.com/task.php?token=" + $rootScope.userToken + "&juice_id=" + data.JuiceID + "";

    juiceSrv.getJuiceDetails($scope.JuiceID).then(function (data) {
      $scope.JuiceName = data.Name;
      $scope.JuiceDescription = data.Description;
    })

    juiceSrv.getJuiceIngredients($scope.JuiceID).then(function (data) {
      $scope.JuiceIngredients = data;
    })

    juiceSrv.getJuiceNutrients($scope.JuiceID).then(function (data) {
      $scope.JuiceNutrients = data;
    })
  });

Does someone has a solution for this problem? Thanks in advance for helping out!
-Jérémy

A: We you click button call one function in controller and resize height of document using $ionicScrollDelegate.resize();
html
<button ng-hide="toggle" ng-click="toggleButton()" class="button button-block button-balanced default-button">
Show ingredients
</button>

<button ng-show="toggle" ng-click="toggleButton()" class="button button-block button-balanced default-button">
Show nutrients
</button>

js
$scope.toggle = false;
$scope.toggleButton = function()
{
  $scope.toggle = !$scope.toggle;
  $ionicScrollDelegate.resize();
};

Note
Add dependency in controller called $ionicScrollDelegate

A: I finally found an answer for this issue. I added the overflow-scroll element to the ion-content element.
<ion-content overflow-scroll="true">

This resolved the issue. It does messes up a bit with the bottom spacing, but you can fix that with some CSS.


text:
Q: pdf text extracter class in php Is there available any class in php that extract all text from pdf file so i can store it in mysql database. My pdf has many elements like images, tables,plain text,form elements,charts etc.
So far i saw many classes for last two days, that extract texts, but no one facilitate with complete text extraction, Not extracting complete text from pdf.
I want to extract all text from given pdf file, even if the text is in table etc.
Any one know about this ?  :)
Thanks a lot. Have a nice day :)

A: If you are running this on a linux server, you could try using apdf2text calling it via exec then grabing the contents of the output file.
Note that a few pdf to text scripts are around and you'll get different mileage from all.

A: Find the below url,
Reading the clean text from PDF with PHP

A: I've tested many command line program, but none has 100% result.
So I've started my own library in PHP :
https://github.com/smalot/pdfparser
Currently it's text oriented, but image support will be planned.
If you encountered issues, thanks for sending me your PDF and if possible, the way you made it .


text:
Q: Proof of Theorem 18.8 in Rockafellar's Convex Analysis Theorem: An $n$-dimensional closed convex set $C$ in $\mathbb{R}^n$ is the intersection of the closed half-spaces tangent to it.
In the beginning of the proof, it is established that the epigraph $G$ of the support function of $C$ is the closure of the convex hull of the set $S$ of all exposed rays of $G$, i.e., $G = \operatorname{cl}(\operatorname{conv}(S))$. But then Rockafellar says that "...it follows that...$C$ is the intersection of all the half-spaces $\left\{x | \langle x, x^* \rangle \le \alpha \right\}$, such that the set of non-negative multiples of $(x^*,\alpha)$ is a non-vertical exposed ray of $G$." How do we see that? Why are the vertical exposed rays (if any) not considered?

A: If it's ok, I'll postpone the discussion of vertical exposed rays until the end. First, about the non-vertical ones. Rockafellar states
'...the linear functions $\langle x, \cdot \rangle$ majored by $\delta^*(\cdot|C)$, which correspond of course to points in $C$, are the same as the linear functions whose epigraphs contain every non-vertical exposed ray of G.'
Let $NV\subseteq S$ be the 'non-vertical' exposed rays of $G$. For each ray $r$ in $NV$ is a non-vertical ray, we may write it as $r := r(x^*, \alpha):= \{\lambda (x^*, \alpha): \lambda\geq 0\}$ for some non-zero $x^*\in \mathbb{R}^n$ and $\alpha\in \mathbb{R}$. Note that $x^*\neq 0$ which comes from the ray being non-vertical.
With this notation,
\begin{align*}
C = &\{x\in \mathbb{R}^n: \langle x, x^*\rangle\leq \alpha,~ \forall ~r(x^*, \alpha)\in NV\}\\
=&\bigcap_{r(x^*, \alpha)\in NV}\{x\in \mathbb{R}^n: \langle x, x^*\rangle\leq \alpha\}.
\end{align*}
Hence, $C$ is the intersection of half-spaces of the form $\{x\in \mathbb{R}^n: \langle x, x^*\rangle\leq \alpha\}$ where $r(x^*, \alpha)$ is a non-vertical extreme ray. In other words, $C$ is the intersection of half-spaces of the form $\{x\in \mathbb{R}^n: \langle x, x^*\rangle\leq \alpha\}$ where all non-negative scalars of $(x^*, \alpha)$ form a non-vertical extreme ray of $C$.
-------
Now for vertical exposed rays, I'll try to give an intuition (I hope this helps). A vertical exposed ray of $G$ is defined by a vertical hyperplane $H$ in $\mathbb{R}^{n+1}$ that defines a valid inequality for $G$ --- by a vertical hyperplane, I mean one of the form $H=\{(x, y)\in \mathbb{R}^n\times \mathbb{R}: \langle (x,y), (x^*, 0)\rangle = \beta\}$ for some $x^*\in \mathbb{R}^n$ and $\beta\in \mathbb{R}$ (note that $\beta$ will actually be $0$ here because of the form of a vertical ray). Note that $G$ is contained on one side of $H$. On the side of $H$ that does not contain $G$, the function support function $\delta^*(\cdot|C)$ equals infinity. This means that if $x\in \mathbb{R}^n$ is separated from $G$ by $H$, then $\delta^*(x|C) = \sup\{\langle x, x^*\rangle:~x^*\in C\} = \infty$ and so $x$ is a recession direction of $C$. So vertical exposed rays do not need to be considered as they define unbounded directions of $C$.


text:
Q: C# view SQL results in command line I have looked around stack overflow and the various solutions to this problem aren't working for me. I don't get an error but no results are returning. It just waits for me to press enter and then kills the program. I would expect four rows to return
using System;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
class Hello
{
    static void Main(string[] args)
    {

        String connectionString = "Data Source= myServer; Initial Catalog= myDatabaseName;        Integrated Security=SSPI;";

        System.Console.WriteLine(connectionString);

        //set up by connection
        SqlConnection myConnection = new SqlConnection(connectionString);

        try
        {
            myConnection.Open();
        }
        catch(Exception e)
        {
            System.Console.WriteLine(e.ToString());
        }

        //print the connection
        System.Console.WriteLine(myConnection);

        //try looking
        List<int> productID = new List<int>();
        SqlCommand cmd = new SqlCommand("select productID from product", myConnection);
        SqlDataReader reader = cmd.ExecuteReader();

        while (reader.Read())
        {
           // var myString = reader.GetString(0);
            productID.Add(Convert.ToInt32(reader["productID"].ToString()));
        }

        System.Console.ReadLine();
    }
}
}

A: What are you expecting?  You didn't even print the record to Console.  Records are returned, but they're hiding in memory :)
Example, add following before ReadLine() call:
Console.WriteLine(string.Join(Environment.NewLine, productID));

A: I might recommend Console.WriteLine(reader["productID"].ToString()) inside of the while loop.  If you don't write to the console, don't expect there to be anything.


text:
Q: Trouble with Rails assets in production I've ran
rake assets:precompile
RAILS_ENV=production rake assets:precompile
git add -A
git commit -m "message"
git push heroku master

This is the live site - http://www.collegeinsideview.com/.
It seems that none of the assets are available. I can't figure out why.

*

*Both of the precompile commands seem to have worked.

*In development, my public/assets/ folder is filled with the assets (with the fingerprints at the end; ex. adelphi_social_atmosphere_7-c13258f14849b2f66e162688b9c9228f.png).

*There weren't any errors with pushing to heroku.

production.rb
Collegeanswers::Application.configure do
  # Settings specified here will take precedence over those in config/application.rb

  # Add the fonts path
  config.assets.paths << Rails.root.join('app', 'assets', 'fonts')

  # Code is not reloaded between requests
  config.cache_classes = true

  # Full error reports are disabled and caching is turned on
  config.consider_all_requests_local       = false
  config.action_controller.perform_caching = true

  # Disable Rails's static asset server (Apache or nginx will already do this)
  config.serve_static_assets = true

  config.assets.js_compressor  = :uglifier
  config.assets.css_compressor = :sass

  # Don't fallback to assets pipeline if a precompiled asset is missed
  config.assets.compile = true

  # Generate digests for assets URLs
  config.assets.digest = true

  # Defaults to nil and saved in location specified by config.assets.prefix
  # config.assets.manifest = YOUR_PATH

  # Specifies the header that your server uses for sending files
  # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
  # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx

  # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
  # config.force_ssl = true

  # See everything in the log (default is :info)
  # config.log_level = :debug

  # Prepend all log lines with the following tags
  # config.log_tags = [ :subdomain, :uuid ]

  # Use a different logger for distributed setups
  # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)

  # Use a different cache store in production
  # config.cache_store = :mem_cache_store

  # Enable serving of images, stylesheets, and JavaScripts from an asset server
  # config.action_controller.asset_host = "http://assets.example.com"

   # Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
  config.assets.precompile += %w( about_college.css college_pages.css colleges.css essay_list.css
  essays.css home.css layout.css static_pages.css tldr.css college_pages.js essays.js home.js static_pages.js favicon.ico .svg .eot .woff .ttf)

  # Disable delivery errors, bad email addresses will be ignored
  # config.action_mailer.raise_delivery_errors = false

  # Enable threaded mode
  # config.threadsafe!

  # Enable locale fallbacks for I18n (makes lookups for any locale fall back to
  # the I18n.default_locale when a translation can not be found)
  config.i18n.fallbacks = true

  # Send deprecation notices to registered listeners
  config.active_support.deprecation = :notify

  # config.action_controller.asset_host = "https://#{ENV['FOG_DIRECTORY']}.s3.amazonaws.com"

  config.eager_load = true
end

home.html
<% content_for(:title, 'College Inside View') %>

In-Depth Reviews of Colleges

                    <%= image_tag "columbia1.jpg", size: "297x187", class: 'picture' %>
                    <%= image_tag "columbia2.jpg", size: "297x187", class: 'picture' %>
                    <%= image_tag "columbia3.jpg", size: "297x187", class: 'picture' %>
                    <%= link_to "• • Read more about Columbia • •".html_safe, "/columbia/academics/professors/1", class: 'school_link' %>

How does the workload impact your social life?

                    <%= image_tag "columbia_social_atmosphere_7.png", class: 'answers' %>
                    <%= link_to '--read more--', '/columbia/social-life/social-atmosphere/7', class: 'read_more' %>

                    <%= image_tag "princeton1.jpg", size: "297x187", class: 'picture' %>
                    <%= image_tag "princeton2.jpg", size: "297x187", class: 'picture' %>
                    <%= image_tag "princeton3.jpg", size: "297x187", class: 'picture' %>
                    <%= link_to "• • Read more about Princeton • •".html_safe, "/princeton/academics/professors/1", class: 'school_link' %>

How would you make your classes better?

                    <%= image_tag "princeton_classes_6.png", class: 'answers' %>
                    <%= link_to '--read more--', '/princeton/academics/classes/6', class: 'read_more' %>

                    <%= image_tag "brown1.jpg", size: "297x187", class: 'picture' %>
                    <%= image_tag "brown2.jpg", size: "297x187", class: 'picture' %>
                    <%= image_tag "brown3.jpg", size: "297x187", class: 'picture' %>
                    <%= link_to "• • Read more about Brown • •".html_safe, "/brown/academics/professors/1", class: 'school_link' %>

Are people intellectual? Do they have thoughtful conversations with each other?

                    <%= image_tag "brown_social_atmosphere_5.png", class: 'answers' %>
                    <%= link_to '--read more--', '/brown/social-life/social-atmosphere/5', class: 'read_more' %>

                    <%= image_tag "university-of-pennsylvania1.jpg", size: "297x187", class: 'picture' %>
                    <%= image_tag "university-of-pennsylvania2.jpg", size: "297x187", class: 'picture' %>
                    <%= image_tag "university-of-pennsylvania3.jpg", size: "297x187", class: 'picture' %>
                    <%= link_to "• • Read more about Penn • •".html_safe, "/university-of-pennsylvania/academics/professors/1", class: 'school_link' %>

Are your classes too hard, or too easy? Why?

                    <%= image_tag "penn_dificulty_4.png", class: 'answers' %>
                    <%= link_to '--read more--', '/university-of-pennsylvania/academics/difficulty/4', class: 'read_more' %>

                    <%= image_tag "yale1.jpg", size: "297x187", class: 'picture' %>
                    <%= image_tag "yale2.jpg", size: "297x187", class: 'picture' %>
                    <%= image_tag "yale3.jpg", size: "297x187", class: 'picture' %>
                    <%= link_to "• • Read more about Yale • •".html_safe, "/yale/academics/professors/1", class: 'school_link' %>

Is it easy to make friends? How did you make friends?

                    <%= image_tag "yale_social_atmosphere_1.png", class: 'answers' %>
                    <%= link_to '--read more--', '/yale/social-life/social-atmosphere/1', class: 'read_more' %>

                    <%= image_tag "cornell1.jpg", size: "297x187", class: 'picture' %>
                    <%= image_tag "cornell2.jpg", size: "297x187", class: 'picture' %>
                    <%= image_tag "cornell3.jpg", size: "297x187", class: 'picture' %>
                    <%= link_to "• • Read more about Cornell • •".html_safe, "/cornell/academics/professors/1", class: 'school_link' %>

Mary Donlon Hall

                    <%= image_tag "cornell_housing_mary_donlon_hall.png", class: 'answers' %>
                    <%= link_to '--read more--', '/cornell/living-environment/housing/mary-donlon-hall', class: 'read_more' %>

                    <%= image_tag "harvard1.jpg", size: "297x187", class: 'picture' %>
                    <%= image_tag "harvard2.jpg", size: "297x187", class: 'picture' %>
                    <%= image_tag "harvard3.jpg", size: "297x187", class: 'picture' %>
                    <%= link_to "• • Read more about Harvard • •".html_safe, "/harvard/academics/professors/1", class: 'school_link' %>

Are there comfortable places to study?

                    <%= image_tag "harvard_campus_2.png", class: 'answers' %>
                    <%= link_to '--read more--', '/harvard/academics/classes/5', class: 'read_more' %>

                    <%= image_tag "dartmouth1.jpg", size: "297x187", class: 'picture' %>
                    <%= image_tag "dartmouth2.jpg", size: "297x187", class: 'picture' %>
                    <%= image_tag "dartmouth3.jpg", size: "297x187", class: 'picture' %>
                    <%= link_to "• • Read more about Dartmouth • •".html_safe, "/dartmouth/academics/professors/1", class: 'school_link' %>

Do professors make things easy to understand?

                    <%= image_tag "dartmouth_professors_1.png", class: 'answers' %>
                    <%= link_to '--read more--', '/dartmouth/academics/professors/1', class: 'read_more' %>

                    <%= image_tag "university-of-pittsburgh1.jpg", size: "297x187", class: 'picture' %>
                    <%= image_tag "university-of-pittsburgh2.jpg", size: "297x187", class: 'picture' %>
                    <%= image_tag "university-of-pittsburgh3.jpg", size: "297x187", class: 'picture' %>
                    <%= link_to "• • Read more about Pitt • •".html_safe, "/university-of-pittsburgh/academics/professors/1", class: 'school_link' %>

Neuroscience: What are people in the major like? How would you stereotype them?

                    <%= image_tag "pitt_neuroscience_8.png", class: 'answers' %>
                    <%= link_to '--read more--', '/university-of-pittsburgh/academics/majors/neuroscience/8', class: 'read_more' %>

                    <%= image_tag "university-of-wisconsin1.jpg", size: "297x187", class: 'picture' %>
                    <%= image_tag "university-of-wisconsin2.jpg", size: "297x187", class: 'picture' %>
                    <%= image_tag "university-of-wisconsin3.jpg", size: "297x187", class: 'picture' %>
                    <%= link_to "• • Read more about Wisconsin • •".html_safe, "/university-of-wisconsin/academics/professors/1", class: 'school_link' %>

How much will not partying limit your social life?

                    <%= image_tag "wisconsin_parties_3.png", class: 'answers' %>
                    <%= link_to '--read more--', '/university-of-wisconsin/social-life/parties/3', class: 'read_more' %>

                    <%= image_tag "colgate1.jpg", size: "297x187", class: 'picture' %>
                    <%= image_tag "colgate2.jpg", size: "297x187", class: 'picture' %>
                    <%= image_tag "colgate3.jpg", size: "297x187", class: 'picture' %>
                    <%= link_to "• • Read more about Colgate • •".html_safe, "/colgate/academics/professors/1", class: 'school_link' %>

Who wouldn't fit in?

                    <%= image_tag "colgate_social_atmosphere_2.png", class: 'answers' %>
                    <%= link_to '--read more--', '/colgate/social-life/social-atmosphere/2', class: 'read_more' %>

                    <%= image_tag "adelphi-university1.jpg", size: "297x187", class: 'picture' %>
                    <%= image_tag "adelphi-university2.jpg", size: "297x187", class: 'picture' %>
                    <%= image_tag "adelphi-university3.jpg", size: "297x187", class: 'picture' %>
                    <%= link_to "• • Read more about Adelphi • •".html_safe, "/adelphi-university/academics/professors/1", class: 'school_link' %>

How's the on-campus food (taste, price, health, convenience, hours, variety...)?

                    <%= image_tag "adelphi_food_1.png", class: 'answers' %>
                    <%= link_to '--read more--', '/adelphi-university/living-environment/food/1', class: 'read_more' %>

Columbia

Princeton

Brown

Penn

Yale

Cornell

Harvard

Dartmouth

Pitt

Wisconsin

Colgate

Adelphi

Right now I only have reviews for those 12 schools. Enter your email below to be notified when there's more!

            <%= simple_form_for :subscribe, url: 'subscribe' do |f| %>
                <%= f.input :email, placeholder: 'user@domain.com', label: false, required: true %>

                <%= f.button :submit, "1-Click Sign Up", class: "btn btn-primary", data: { :disable_with => "Submitting..." } %>
            <% end %>

<%= link_to "I Graduated High School. Now What?", "/i-graduated-high-school-now-what" %>

<%= link_to "How to Choose a College", "/how-to-choose-a-college" %>

<%= link_to "How College Inside View Got Started", "https://medium.com/what-i-learned-building/322e8668ed6f" %>

Gemfile
source 'https://rubygems.org'

ruby '2.0.0'
gem 'rails', '~>4.0.0'
gem 'bootstrap-sass', '2.3.2.0'
gem "actionmailer", "~> 4.0.3" #
gem "jquery-tablesorter", "~> 1.5.0"
gem 'jquery-rails'
gem 'meta-tags', :require => 'meta_tags'
gem "simple_form", "~> 3.0.1"
gem 'rails4_upgrade'
gem 'sass-rails', '~>4.0.0'
gem 'coffee-rails', '~>4.0.0'
gem 'uglifier', '>=1.3.0'
# gem 'asset_sync'
gem 'gibbon', '~> 1.1.2'
gem 'activerecord-tableless'
gem 'social-share-button'

# Rails 4 gems
gem 'actionpack-action_caching', '~>1.0.0'
gem 'actionpack-page_caching', '~>1.0.0'
gem 'actionpack-xml_parser', '~>1.0.0'
gem 'actionview-encoded_mail_to', '~>1.0.4'
gem "activerecord-session_store", "~> 0.1.0"
gem "activeresource", "~> 4.0.0" #
gem "actionpack", "~> 4.0.3" #
gem 'protected_attributes' #
gem "activemodel", "~> 4.0.3" #
gem 'rails-observers', '~>0.1.1'
gem 'dalli', '~> 2.6.2' #
# gem 'turbolinks'
# gem 'jquery-turbolinks'

group :production do
    gem 'pg'
    gem 'rails_12factor'
end

group :development do
    gem 'sqlite3'
    gem 'annotate', '2.5.0'
end

# Don't think I'm using these
gem 'jquery-ui-rails'
gem 'jquery-ui-themes'

some heroku logs
2014-12-28T20:26:25.937063+00:00 app[web.1]:
2014-12-28T20:26:25.937075+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/actionpack-4.0.3/lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'
2014-12-28T20:26:25.937071+00:00 app[web.1]:
2014-12-28T20:26:25.937042+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/actionpack-4.0.3/lib/action_dispatch/middleware/request_id.rb:21:in `call'
2014-12-28T20:26:25.927220+00:00 app[web.1]:   vendor/ruby-2.0.0/lib/ruby/2.0.0/webrick/httpserver.rb:138:in `service'
2014-12-28T20:26:25.937040+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/railties-4.0.3/lib/rails/rack/logger.rb:20:in `call'
2014-12-28T20:26:25.937072+00:00 app[web.1]: ActionController::RoutingError (No route matches [GET] "/assets/adelphi_food_1-30d1a701653e3ce27c72d338a617333a.png"):
2014-12-28T20:26:25.937093+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/sendfile.rb:112:in `call'
2014-12-28T20:26:25.937100+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/handler/webrick.rb:60:in `service'
2014-12-28T20:26:25.937095+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/railties-4.0.3/lib/rails/application.rb:97:in `call'
2014-12-28T20:26:25.937084+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/railties-4.0.3/lib/rails/rack/logger.rb:20:in `call'
2014-12-28T20:26:25.937085+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/actionpack-4.0.3/lib/action_dispatch/middleware/request_id.rb:21:in `call'
2014-12-28T20:26:25.937087+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/methodoverride.rb:21:in `call'
2014-12-28T20:26:25.937088+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/runtime.rb:17:in `call'
2014-12-28T20:26:25.937061+00:00 app[web.1]:   vendor/ruby-2.0.0/lib/ruby/2.0.0/webrick/httpserver.rb:94:in `run'
2014-12-28T20:26:25.937062+00:00 app[web.1]:   vendor/ruby-2.0.0/lib/ruby/2.0.0/webrick/server.rb:295:in `block in start_thread'
2014-12-28T20:26:25.937051+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/railties-4.0.3/lib/rails/engine.rb:511:in `call'
2014-12-28T20:26:25.937098+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/content_length.rb:14:in `call'
2014-12-28T20:26:25.937101+00:00 app[web.1]:   vendor/ruby-2.0.0/lib/ruby/2.0.0/webrick/httpserver.rb:138:in `service'
2014-12-28T20:26:25.937113+00:00 app[web.1]:
2014-12-28T20:26:25.937114+00:00 app[web.1]:
2014-12-28T20:26:25.937091+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/actionpack-4.0.3/lib/action_dispatch/middleware/static.rb:64:in `call'
2014-12-28T20:26:25.937078+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/railties-4.0.3/lib/rails/rack/logger.rb:20:in `block in call'
2014-12-28T20:26:25.937090+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/activesupport-4.0.3/lib/active_support/cache/strategy/local_cache.rb:83:in `call'
2014-12-28T20:26:25.937097+00:00 app[web.1]:   vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/lock.rb:17:in `call'
2014-12-28T20:26:25.937103+00:00 app[web.1]:   vendor/ruby-2.0.0/lib/ruby/2.0.0/webrick/httpserver.rb:94:in `run'
2014-12-28T20:26:25.937111+00:00 app[web.1]:   vendor/ruby-2.0.0/lib/ruby/2.0.0/webrick/server.rb:295:in `block in start_thread'

A: In order to deploy and serve Rails 4 static assets on Heroku you must include the rails12_factor Gem in the prod group of your Gemfile.
gem 'rails_12factor', group: :production

In addition you must confirm that config/application.rb serve_static_assets is set to true.
config.serve_static_assets = true

Check out Heroku documentation for more information.


text:
Q: A conceptual probability doubt. Assume that a store manufactures N guitars. Every guitar has a probability P, of being defective. If I buy a guitar, and it turns out to be defective, does it change the probability of another guitar being defective?
One way to see it is that every guitar is manufactured independently and hence the probability shouldn't change.
Another way to see it would be once everything is manufactured, there is a finite fixed number of guitars that are defective (let's call it X, which is approximately PN). So finding one defective guitar implies the probability of finding another defective guitar becomes less : ((X-1)/(N-1)) instead of (X/N).
I am tempted to assume that each guitar is in a quantum state (mutually non-entangled, obviously) such that before we check a guitar, it is in a superposition of defective and non-defective. Which supports my argument but I am not able to convince my friend (or myself) why that should be the case in a classical system.