text:
Q: What is the "associated scalar equation" of equations of motion? In an essay I am reading on celestial mechanics the equations of motion for a 2 body problem is given as:
$$\mathbf{r}''=\nabla(\frac{\mu}{r})=-\frac{\mu \mathbf{r}}{r^3}$$
Fine.  Then it says the "associated scalar equation" is:
$$r''=-\frac{\mu}{r^2}+\frac{c^2}{r^3}$$
I've never heard of such a thing.  Can someone please explain what the "associated scalar equation" of an equation of motion is.  If it is just the equation of motion in scalar form, then why does that extra term $\frac{c^2}{r^3}$ appear?
Oh, $\mu$ is the mass constant.  It's not clear from the essay what $c^2$ is.  It might be the speed of light squared, or perhaps a constant of integration.
EDIT: The essay in question can be found here.  The equations in question are found on page 5.

A: The "associated scalar equation" is just the formula for the time evolution of the scalar magnitude of the displacement, $r$, rather than all its vector components. It really only makes sense to write such an equation if the right-hand side can be expressed in terms of $r$ only, and not $\mathbf{r}$. Then you can use it to analyze the evolution of $r$ in simple scalar terms, without worrying about vector quantities.
To see where it comes from, first note the scalar $r$ can be written $r = \sqrt{\mathbf{r} \cdot \mathbf{r}}$. Then
$$ r' = \frac{1}{2} (\mathbf{r} \cdot \mathbf{r})^{-1/2} (\mathbf{r} \cdot \mathbf{r}' + \mathbf{r}' \cdot \mathbf{r}) = \frac{\mathbf{r}'\cdot\mathbf{r}}{r}. $$
Continuing with the next derivative, we find
\begin{align}
r'' & = \frac{1}{r^2} \left((\mathbf{r}'' \cdot \mathbf{r} + \mathbf{r}' \cdot \mathbf{r}') r - (\mathbf{r}' \cdot \mathbf{r}) r'\right) \\
& = \frac{1}{r^2} \left(\left(-\frac{\mu}{r^3} \mathbf{r} \cdot \mathbf{r} + \mathbf{r}' \cdot \mathbf{r}'\right) r - \frac{(\mathbf{r}'\cdot\mathbf{r})^2}{r}\right),
\end{align}
where we use the formula we found for $r'$ as well as $\mathbf{r}'' = -\mu \mathbf{r} / r^3$. Recalling $\mathbf{r} \cdot \mathbf{r} = r^2$, we can write
$$ r'' = -\frac{\mu}{r^2} + \frac{1}{r^3} \left((\mathbf{r}' \cdot \mathbf{r}') (\mathbf{r} \cdot \mathbf{r}) - (\mathbf{r}' \cdot \mathbf{r})^2\right), $$
which is the same form as the given associated scalar equation.
It remains to show that the parenthesized expression is constant. Recognizing and then manipulating some triple products yields
\begin{align}
r'' & = -\frac{\mu}{r^2} - \frac{1}{r^3} \mathbf{r} \cdot (\mathbf{r}' \times (\mathbf{r}' \times \mathbf{r})) \\
& = -\frac{\mu}{r^2} - \frac{1}{r^3} (\mathbf{r} \times \mathbf{r}') \cdot (\mathbf{r}' \times \mathbf{r}).
\end{align}
But $\mathbf{r}' \times \mathbf{r}$ is just the specific relative angular momentum $\mathbf{h}$, which is conserved in the two-body problem. Thus we recover the given formula with the constant $c^2 = \mathbf{h} \cdot \mathbf{h}$.

A: My answer is the same as Chris', but formulated in a different way (it's essentially the same as this wiki article):
In polar coordinates, the position vector is
$$
\mathbf{r} = r\,(\cos\varphi,\sin\varphi) = r\,\mathbf{\hat{r}},
$$
with $\mathbf{\hat{r}}$ the radial unit vector. The velocity is then
$$
\mathbf{v} = \dot{r}\,(\cos\varphi,\sin\varphi) + r\dot{\varphi}\,(-\sin\varphi,\cos\varphi) = \dot{r}\,\mathbf{\hat{r}} + r\dot{\varphi}\,\boldsymbol{\hat{\varphi}},
$$
with $\boldsymbol{\hat{\varphi}}$ the azimuthal unit vector. The acceleration is
$$
\mathbf{a} = (\ddot{r} - r\dot{\varphi}^2)\,\mathbf{\hat{r}} + (2\dot{r}\dot{\varphi} + r\ddot{\varphi})\,\boldsymbol{\hat{\varphi}}.
$$
But since gravity is a radial force, the azimuthal accerelation must be zero, so that
$$
2\dot{r}\dot{\varphi} + r\ddot{\varphi} = \frac{1}{r}\frac{\text{d}}{\text{d}t}(r^2\dot{\varphi}) = 0.
$$
In other words, the specific relative angular momentum $h=r^2\dot{\varphi}$ is a constant. Therefore, the (radial) acceleration becomes
$$
a_r = \ddot{r} - r\dot{\varphi}^2 = \ddot{r} - \frac{h^2}{r^3} = -\frac{\mu}{r^2},
$$
which gives the desired result.


text:
Q: Bookmark and hover functionality like Standard Related List for inline VF page I have a inLine VF page on my Standard Account Page which shows the list of related custom objects.I have a requirement where in I would like like to have a bookmark on top of the page so that when user clicks on it, it will take the user directly to that inLine VF Page.I know we can achieve this with replacing the Standard page with Custom  Page.
I came to know that there is an idea Visualforce Related List Hover Link Support  for something like this as well
As per the post Display bookmark link on detail page to inline VF page,we can not achieve this .As a workaround, we would need to play a trick with jquery.But that was 4 years ago.
As salesforce comes up with amazing new features with new releases pretty fast, I would like to know if something has changed in the past 4 years in context to this functionality.Has some been able to find some different workaround for something like this

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why is my function to find the smallest word in an array not working? I am writing a program to print out the smallest word in phrase. The output is supposed to give me the word "I" but it is instead printing out the word "am". How can I fix this? Please help, I am new to Python
#Given a string 'phrase' consisting of some words separated
# by some number of spaces, return the
# smallest word in the string.

def word_length(phrase):
    splitphrase = phrase.split(" ")

    min_word = ''
    for i, element in enumerate(splitphrase):
        if i < len(splitphrase)-1 and (len(element) <= len((splitphrase[i+1]))):
            min_word = element
    print(min_word)

word_length("hello I am Sam and am tall")

A: I'll put my code down below and then explain the changes I made:
def word_length(phrase):
    splitphrase = phrase.split(" ")

    min_word = splitphrase[0] #setting default value as first word
    for element in (splitphrase): #for each word in the list
        if len(element) < len(min_word): #if the word is shorter than our current min_word
            min_word = element #redefine min_word if the current word is shorter
    print(min_word)

word_length("hello I am Sam and am tall")

Output:
I

Similar to your code, we start by using the split() function to break our sentence up into words in a list.
To start finding the smallest word, we can define our min_word to initially be splitphrase[0] as our default value.
To determine if other words in the list are min_word, while iterating through every word in the list, if the length of the word we are iterating through in our list is less than the length of current min_word, we redefine min_word to be that current element.
I hope this helped! Let me know if you need any further help or clarification!

A: This code, just checks each word if its length if less than the previous shortest words length.
def word_length(phrase):
    splitphrase = phrase.split(" ") # Split the phrase into each individual word

    min_word = splitphrase[0] # Store the shortest word we've found yet
    for element in splitphrase: # Iterate over every word
        if len(element) < len(min_word): # Check if we haven't already set the min_word or this word is smaller than the current min_word
            min_word = element # Set min_word to the new shortest word

    print(min_word)

word_length('Hello how is it going today') # > is

A: How about like this:
def word_length(phrase):
    sw = (words := phrase.split())[0]
    for word in words[1:]:
        if len(word) < len(sw):
            sw = word
    return sw
print(word_length("hello I am Sam and am tall"))

Note:
This will fail if phrase is an empty string or None. You will also need Python 3.8+

A: *

*the maximum word length possible is the length of the sentence

*I check that each word is smaller than the maximum length

*if it is smaller I reassign the value of min_word and the min_word_length

def word_length(phrase):
    splitphrase = phrase.split(" ")

    max_word_lenght = len(phrase)
    for el in splitphrase:
        if len(el) <= max_word_lenght:
            max_word_lenght = len(el)
            min_word = el
    print(min_word)

word_length("hello I am Sam and am tall")

If you are new to python I would recommend learning a debugging tool so you can better understand the flow of your program.
If you use the command line a possibility is PDB (https://realpython.com/python-debugging-pdb/).
If you use IDE (Spyder, VS, PyTorch) they should have a debugger built-in


text:
Q: Component cant access state stored in store I am facing a problem where my Array component cant access the state "count" stored in a redux store, I have verified that the store is connected and its showing up in the react dev tools.The Array component is supposed to take the count and genearate a random array based on it.
This is my App.js
    import React from 'react'
    import './App.css';

    //redux
    import {Provider} from 'react-redux';
    import store from './store';

    //components
    import Array from './components/Array'

    const App=()=>{
      return(
      <Provider store={store}>

           <Array/>

      </Provider>
      )
    }

export default App;

This is the array component which cant access the "count" state.
import React from 'react';
import PropTypes from 'prop-types';
import {connect} from 'react-redux';

//actions
import {generate} from '../actions/genRanArray';

const Array=({count,generate})=>{

    const onClick=(e)=>{
        console.log(count);
        console.log('count displayed');
        generate(count)
    }
    return(
        <button type="button" onClick={onClick}>Click Me!</button>
    )
}

Array.propTypes={
    count:PropTypes.number,
}

const mapStateToProps = (state) =>{ return{
    count: state.count
  };
};

export default connect(mapStateToProps,{generate})(Array);

EDIT!!!
This is my "generate" action, It generates a random array .
import { GENERATE_RANDOM_ARRAY } from "./types";

//generate random no

    const generateRandomNumber=(min,max)=>{
        return Math.floor(Math.random()*(max-min)+min);

    }
    //generate random array
    export const generate=(count)=>dispatch=>{
            const temp=[];
            for(let i=0;i<count;i++){
                // temp.push(Math.floor(Math.random()*50)+200);
                temp.push(generateRandomNumber(50,200))
            }
     console.log(temp);
     dispatch({
         type:GENERATE_RANDOM_ARRAY,
         payload:temp
     })
    }

This is the reducer,
The payload is the array generated stored in the states
import { GENERATE_RANDOM_ARRAY } from "../actions/types";

const initialState={
    array:[],
    arraySteps:[],
    colorKey:[],
    colorSteps:[],
    currentSteps:0,
    count:10,
    delay:100,
    algorithm:'',
    timeouts:[],
};

//reducer
function stateReducer(state=initialState,action){
    const {type,payload}=action;
    switch(type){
        case GENERATE_RANDOM_ARRAY:
            return {
                ...state,
                array:payload,
                arraySteps:payload,
            };
        default:return state;

    }
}

Thanks for your help!!.

A: Middleware allows for side effects to be run without blocking state updates
use thunk middleware
import { Provider } from "react-redux";
import { createStore, applyMiddleware } from "redux";
import { composeWithDevTools } from "redux-devtools-extension";
import thunk from "redux-thunk";

export default function App() {
  const store = createStore(
    stateReducer,
    composeWithDevTools(applyMiddleware(thunk))
  );
  return (
    <Provider store={store}>
      <Array />
    </Provider>
  );
}


text:
Q: Headphones not working. Realtek ALC270. Asus K55VD-DS71 laptop. Ubuntu 12.04 I helping my friend to setup ubuntu who is a first time user. It's an ASUS K55VD-DS71 laptop.
Following codecs are  being reported on the system when I issue the command cat /proc/asound/card0/codec* | grep Codec

Codec: Realtek ALC270
  Codec: Intel PantherPoint HDMI`

Using the ALSA information script v0.4.60 I have obtained information about my alsa setup and device which is here
The interesting thing is that Pulse Audio sound settings reports only one device and that is Headphones (Build in Audio) BUT the sound comes only from speaker even if speakers are not listed there. There is no sound from the headphones.
I played around with alsamixer a bit and also alsa-base.conf a bit and once got the sound working from headphones but after restart the same problem as described above reappeared.
If I could get it to work once I believe there must be something really trivial which I am missing here. Does anyone have any suggestions? Thanks in advance.
P.S : My friend is using Ubuntu for the first time so I am trying to make the transition from windows as smooth as possible. A non-working hardware especially headphones can be a major roadblock.

A: Reinstalled and upgraded the system using upgrade manager. Everything worked.


text:
Q: SAS workspace server terminates unexpectantly We have a large dataset 100M rows. I have a need to aggregate the data for some summaries. We are currently doing this through Proc SQL. When I run this, the process runs for some period of time and then unexpectantly, the process terminates in the workspace server. This leaves EG hanging until it eventually errors (hours later).
What might be causing this? I monitor the box and we aren't maxing out resources.
How can I troubleshoot? There are no logs being produced by the workspace server.

A: If the process is running on another DB, via ODBC pass through or SAS/Access, the trace option may be helpful for debugging (will show you in the log exactly what is being executed)
options sastrace=',,,d' sastraceloc=saslog nostsuffix;

to remove:
options sastrace=none;

Regarding Workspace Logging - this may not be switched on.  You can do this via SMC, or manually (see this guide).
Can you give more details of the code being executed, your environment, etc etc?
Another option might be to run on a smaller number of observations (inobs=100).  If this still doesn't work, try modifying your query - removing tables one at a time..


text:
Q: C++ logger for UWP application I'm working on an UWP application in visual C++ (VS 2017) that will be uploaded to Microsoft Store. I'm looking for a configurable third-party logger that may be used for writing logs to files, automatic rolling etc. Is there an off-the-shelf logging library for visual C++ that is fully compatible with UWP and may provide such features? As far as I checked there are only loggers for UWP available in C# (e.g. Serilog, NLog in version 4.5).
If no, is there a way to integrate one of the above-mentioned C# logging frameworks with visual C++? It may be easily done the other way by using shared Windows Runtime components, but I'm not sure if it's feasible in my case.


text:
Q: Filling multiple fields in PDF form using PDFBOX and Lock editing of pdf document after filling I am new to PDF BOX, need to fill the information in PDF Form, which has sections and field names:
PDF form contains information of
NAME
and box to fill the information
Address
and box to fill the information
City
box to fill the information.
if i have the Name, Address and city information how to fill that into the pdf form using pdf box.
Have used the example from PDFbox, acroForm only fills sample fields how to get this filled with particular information at particular field.
once after filling it how to make it locked.
String formTemplate = "C:/FillFormField.pdf";
      PDDocument pdfDocument = PDDocument.load(new File(formTemplate))

        // get the document catalog
        PDAcroForm acroForm = pdfDocument.getDocumentCatalog().getAcroForm();

        // as there might not be an AcroForm entry a null check is necessary
        if (acroForm != null)
        {
            // Retrieve an individual field and set its value.
            PDTextField field = (PDTextField) acroForm.getField( "sampleField" );
            field.setValue("Text Entry");

            // If a field is nested within the form tree a fully qualified name
            // might be provided to access the field.
            field = (PDTextField) acroForm.getField( "fieldsContainer.nestedSampleField" );
            field.setValue("Text Entry");
        }

        // Save and close the filled out form.
        pdfDocument.save("C:/FillFormField.pdf");

Currently dont have errors above code is working to fill out some junk fields.
need to fill exactly the Name with box info with Name information
                         Address with box info with Address information

A: I am able to do it with PDF Debugger from PDFBOX.
Used CMD prompt to get the structure of the file
java -jar pdfbox-app-1.8.10.jar PDFDebugger yourfile.pdf
please get the above jar file from apache PDF box.
once you able to see the structure, find the fields name.

A: For my purpose of locking, i dont need to use the encryption method. so used Acroform Flatten PDF method.
// flatten() method saves the PDF read only
    acroForm.flatten();


text:
Q: XSLT format-date for an attribute <?xml version="1.0" encoding="UTF-8"?>
<catalog>
  <cd created_at="2016-12-15T15:02:55Z">
  <title created_at="2016-12-15T15:02:55Z">Empire Burlesque</title>
  <artist created_at="2016-12-15T15:02:55Z">Bob Dylan</artist>
  <cover created_at="2016-12-15T15:02:55Z"/>
  <company>Columbia</company>
  <price>10.90</price>
  <year>1985</year>
</cd>

I want to format all occurrences of created_at attribute
input format YYYY-MM-DDTHH:MM:SSZ
output format YYYY-MM-DD HH:MM:SS

I am currently using this following xslt
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>

<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()" />
    </xsl:copy>
</xsl:template>

<!-- Edit dates to conform to dbunit format-->
<xsl:template match="@created_at">
    <xsl:copy>
        <xsl:call-template name="formatdate">
            <xsl:with-param name="datestr" select="@created_at"/>
        </xsl:call-template>
    </xsl:copy>
</xsl:template>

<xsl:template name="formatdate">
    <xsl:param name="datestr" />
    <!-- input format YYYY-MM-DDTHH:MM:SSZ -->
    <!-- output format YYYY-MM-DD HH:MM:SS -->

    <xsl:variable name="datetext">
        <xsl:value-of select="substring-before($datestr,'T')" />
    </xsl:variable>

    <xsl:variable name="timetext">
        <xsl:value-of select="substring($datestr,12,18)" />
    </xsl:variable>

    <xsl:value-of select="concat($datetext, ' ', $timetext)" />
</xsl:template>
</xsl:stylesheet>

However as I debug through the transformation xslt it does not seem to enter the formatdate call-template. Is my xpath wrong? I found articles on modifying the node, but not the attribute. Any help would be much appreciated.
Thank you

A: Why not simply:
<xsl:template match="@created_at">
    <xsl:attribute name="created_at">
        <xsl:value-of select="substring(translate(., 'T', ' '), 1, 19)" />
    </xsl:attribute>
</xsl:template>

Note: you cannot use xsl:copy if you want to change an attribute's value.

A: From your post, it sounds like all you need is simple string processing.
Why your code isn't working the way you want
You're handling the @created_at attributes with this template:
<xsl:template match="@created_at">
    <xsl:copy>
        <xsl:call-template name="formatdate">
            <xsl:with-param name="datestr" select="@created_at"/>
        </xsl:call-template>
    </xsl:copy>
</xsl:template>

The kicker here is that you're using <xsl:copy>.  When used with attributes, <xsl:copy> copies the entire attribute, name and value both.  And since attributes can't contain any children, the children of your <xsl:copy> instruction are ignored -- so the XSLT processor never evaluates the <xsl:call-template name="formatdate"> instruction.
A different approach that works
Instead of using <xsl:copy>, you need to instead use <xsl:attribute> to create an attribute in a way where you can also specify the value.  In this case, you already know the name of the attribute you want to create, so you could hard-code the name value as created_at.  For a more flexible approach, you could instead give the name value as {name(.)} -- this just grabs the name of the attribute being processed, which is closer in behavior to what you probably thought <xsl:copy> would do.  :)
It is also possible to produce the desired string in a single xsl:value-of expression, without relying on so many variables.
<xsl:template match="@created_at">
    <xsl:attribute name="{name(.)}">
        <xsl:value-of select="concat(substring-before(., 'T'), ' ', substring-before(substring-after(., 'T'), 'Z'))"/>
    </xsl:attribute>
</xsl:template>

Breaking down that select statement:

*

*Use concat() to stitch together multiple bits of string.

*Use substring-before(., 'T') to grab everything before the T -- that's the date portion.

*' ' adds the single space in the middle.

*substring-before(substring-after(., 'T'), 'Z') --

*

*The inner expression substring-after(., 'T') grabs everything after the T -- that's the time portion.

*However, there's that pesky Z on the end, so we use substring-before as the outer expression to lop that off.

No need for variables, and it gets the job done.  Confirmed to work with XSLT 1.0.

A: Try this
<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>
<xsl:output method='xml' indent='yes'/>

<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()" />
    </xsl:copy>
</xsl:template>

<!-- Edit dates to conform to dbunit format-->
<xsl:template match="@created_at">
    <xsl:call-template name="formatdate">
        <xsl:with-param name="datestr" select="."/>
    </xsl:call-template>
</xsl:template>

<xsl:template name="formatdate">
    <xsl:param name="datestr" />
    <!-- input format YYYY-MM-DDTHH:MM:SSZ -->
    <!-- output format YYYY-MM-DD HH:MM:SS -->

    <xsl:variable name="datetext">
        <xsl:value-of select="substring-before($datestr,'T')" />
    </xsl:variable>

    <xsl:variable name="timetext">
        <xsl:value-of select="substring($datestr,12,8)" />
    </xsl:variable>

    <xsl:attribute name="created_at">
        <xsl:value-of select="concat($datetext, ' ', $timetext)" />
    </xsl:attribute>
</xsl:template>

</xsl:stylesheet>


text:
Q: .delay function in a .mouseleave event So im trying to add a delay to a Mouse leave event so it doesnt glitch if one is on the edge of hovering over the element
$(window).load(function(){
$("#cp_widget_7c184d64-36ed-4bb9-b617-c9034c2824c6").mouseenter(function () {
    $("#cp_widget_7c184d64-36ed-4bb9-b617-c9034c2824c6").animate({
        bottom: 75
    });
});
$("#cp_widget_7c184d64-36ed-4bb9-b617-c9034c2824c6").mouseleave(function () {
    .delay(10)//Have a delay here
    $("#cp_widget_7c184d64-36ed-4bb9-b617-c9034c2824c6").animate({
        bottom: -75
    });
});
});

Any ideas??

A: I use this plugin, does a great job on avoiding 'accidental hovers'
http://cherne.net/brian/resources/jquery.hoverIntent.html

A: On the mouseleave event, you can use setTimeout to delay the execution of a function. Capturing the id returned from the setTimeout function allows you to prevent that function from executing with clearTimeout. So if a user puts their mouse back over the area before the delay finishes, the element won't execute the mouseleave animation.
$(document).ready(function(){
    var timeoutID ;

    $("#cp_widget_7c184d64-36ed-4bb9-b617-c9034c2824c6").mouseenter(function () {
        // Don't execute the hide function if it hasn't executed
        clearTimeout( timeoutID );
        $("#cp_widget_7c184d64-36ed-4bb9-b617-c9034c2824c6").animate({
            bottom: 75
        });
    });
    $("#cp_widget_7c184d64-36ed-4bb9-b617-c9034c2824c6").mouseleave(function () {
        timeoutID  = setTimeout(function(){
            $("#cp_widget_7c184d64-36ed-4bb9-b617-c9034c2824c6").animate({
                bottom: -75
            });
        }, 1000) // Delay 1000 milliseconds
    });
});

Here is a fiddle: http://jsfiddle.net/t829p/3/
Documentation on the setTimeout and clearTimeout functions:
https://developer.mozilla.org/en-US/docs/Web/API/Window.setTimeout
https://developer.mozilla.org/en-US/docs/Web/API/window.clearTimeout


text:
Q: What is Microsoft.csharp.dll in .NET 4.0 This DLL is added by default in Visual Studio 2010 projects. What is this new assembly used for? It does not seem to contain much after looking at it using Reflector and Google does not seem to have much to say about it either.

A: It is used when/if you use the dynamic keyword in your project. The assembly contains the C# runtime binder.
The C# compiler has essentially been extracted out into a library so that it can emit, compile and run code needed to support the dynamic keyword. The first time you use dynamic in your code, this assembly (as well as System.dll, System.Core.dll and System.Dynamic.dll) will get loaded into your AppDomain.

A: Always removed it so far. No issues yet.


text:
Q: Kubernetes (delete Replica Sets) How can I remove replicasets from kubernetes?
I use kubernetes-client java libs,
the request there looks like this:
/apis/extensions/v1beta1/namespaces/{namespace}/replicasets/{name}
but I do not know the name replicasets, I know only label selector.
Configure such a request does not allow me lib:
/apis/extensions/v1beta1/namespaces/va/replicasets/labelSelector=app=some_name

A: When you create a replica-set your return type from that method is an object representing the replica-set. You should be able to get the name of the replica-set from that object and then, later on, use it in order to delete it.
Another option would be to list all replica-sets, and add a label selector to this call. This will only return the replica-sets you're looking for and then you can delete those.


text:
Q: Div height in percentage, half parent height I have two divs displayed next to each other, left div is 20% width and right is 80% width.
Now left div contains image which is resized horizontally so it's height is unknown and keeps changing.
Now when this div resizes parent height increases or decreases, so when that happens i need my right div to resize as well, how can i do that?
jsFiddle

A: You can try the CSS3 table-cell value on the display property : http://jsfiddle.net/UJYyw/5/
With

You just have to apply a table-cell display on div.one and div.two
.one, .two{
    display:table-cell;
}

Compliant browsers will adapt height of elements the way they do on td and th tags.

A: You could use jQuery to do this.
$('.container').css({'height':$('.one').height()});

See a jsFiddle here
When you change the value of .one in the css, it will update the size of .container, and thus, .two as well.

A: Here is the crossbrowser solution which uses just floats and couple of wrappers http://jsfiddle.net/RSPbD/
HTML

text in div one

text in div two

CSS:
.container{
    border:1px solid;
    width:70%;
    margin:50px;
    padding:10px;
}

.wrap1 {
    width: 25%;
    background: red;
    position: relative;
    left: 7%;
}

.wrap2 {
    width: 200%;
    position: relative;
    left: 100%;
    margin:0 -200% 0 0;
    background: blue;
}

.one{
    float: left;
    width: 50%;
    margin-right: -100%;
    position: relative;
    left: -50%;
}

.two {
}

.clear {
    clear: both;
    font-size: 0;
    overflow: hidden;
}


text:
Q: elasticsearch bool node with constant_score I'm trying to cumulate score with elasticsearch 2.3
I want a constant score with publishEnd IS NULL and booking = true.
And after that I want different scoring depending on brand/model/fuel
Here is my search params :
$params = [
        'index' => 'app',
        'type' => 'ad',
        'body' => [
            "from" => 0,
            "size" => 12,
            'query' => [
                "constant_score" => [
                    "filter" => [
                        "and" => [
                            ["missing" => [ "field" => "publishEnd" ]],
                            ["term" => ['booked' => 0]],
                        ],
                    ],
                ],
                'bool' =>  [
                    'filter' => [
                        ["term" => ['brand' => 'renault']],
                    ],
                ],
            ],
        ],
    ];

I want to add weight on results, not filtering them.
It's ok for constant score filtering, but I got problems about adding weight for certain brands.
I got this error when I add bool node :

parse_exception: failed to parse search source. expected field name but got [START_OBJECT]

Thanks,
Phil.
Edit
Thanks to israelst, here is the correct parameters :
    $params = [
        'index' => 'app',
        'type' => 'ad',
        'body' => [
            "from" => 0,
            "size" => 12,
            'query' => [
                "bool" => [
                    'should' => [
                        "constant_score" => [
                            "filter" => [
                                "and" => [
                                    ["missing" => [ "field" => "publishEnd" ]],
                                    ["term" => ['booked' => 0]],
                                ],
                            ],
                        ],
                        'filter' => [
                            ["term" => ['brand' => 'renault']],
                        ],
                    ],
                ],
            ],
        ],
    ];

A: You get this exception because you are using "constant_score" and "bool" in the same level. Instead, you need to wrap them inside a "must" or "should" under one "bool". The outcome should be something like:
"query": {
    "bool": {
    "must": [
       {"constant_score": {
       "filter": {
           "and": {
               "filters": [
                  {"missing": {
                     "field": "publishEnd"
                  }},
                  {"term": {
                     "booked": 0
                  }}
               ]
           }
       }
    }},
    {"bool": {
        "filter": {
            "term": {
               "brand": "renault"
            }
        }
    }}
    ]
  }
}


text:
Q: Choosing different UITableViewCells depending on available text or image content I want to display different UITableViewCells depending on what content is available . How can I accomplish that ?
Example:
Lets say I have a custom UITableViewCell whose contentView has a UILabel, UITextField and a UIImageView as subviews. The UILabel is located on the top of the cell, above the UIImageView which is next to the UITextField. Depending on which contents for these views is available, I would like to only display the available parts and enlarge the other views. e.G: If there is missing the UILabel context I don't want to have a blank space at the top of the cell. If I don't have an image, the text field should start at the very left side of the cell.
There should be many newspaper/tv applications out there which had to solved exact the same problem...
Approaches:
(i) Using the same custom cell where I somehow rearrange the subviews
(ii) Calling different custom UITableViewCell's depending on what content is available
For both approaches I am having issues finding a path to solve this problem. My UITableView content size is dynamic and can have a few rows or many.
Is there any other approach I am missing out or if not which approach is best practice?

A: Your (ii) idea is the way to go to my mind. As you say, you design two customs UITableViewCell (.m, .h and .xib) you don't forget to define there CellIdentifier in interface Builder and when your delegate tableView:cellForRowAtIndexPath: is called you choose to dequeueReusableCellWithIdentifier: the appropriate UITableViewCell template.

A: Either approach works, although I would probably prefer (i).
For (i), reuse is easy. Just make sure you clear out the old data when reusing, have your UITableViewCell's layoutSubviews method lay the subviews out appropriately to match whatever data is available, and be sure to call setNeedsLayout when you change the data. The advantage here is that the rest of your code doesn't need to care about which data is available or not, and your table may not even have to care if the cell suddenly gets an image added (unless it needs to know that the cell height changed or something). The disadvantage is that the cell's implementation is more complex, and the layout cannot be completely defined in IB.
For (ii), each different custom UITableViewCell type must have its own reuseIdentifier, and then use dequeueReusableCellWithIdentifier: with the identifier appropriate to the available data. The advantage here is that the individual cell types are simpler (and can probably be done entirely in IB), while the disadvantage is that you have to have several of them for each possible combination of available data. Also, you would need to have the UITableView reload the cell (e.g. using reloadRowsAtIndexPaths:withRowAnimation:) if the type needs to change.


text:
Q: Default arguments in Python not consistent I'm getting unexpected behavior in Python 2.7 when using default arguments. Instead of using the value passed in by the caller, one argument is getting overridden by the default. Consider the following functions:
def vm_list(domain, username, server, verbose, cluster, datacenter, name,
            regex, template_only, detailed_list, vm_status):

    print 'inside vm_list vm_stauts is', vm_status
    vcenter_request = "get_registered_vms"
    vmlist = vcenter_connect(server, user, password, vcenter_request, vm_status)

def vcenter_connect(server, user, password, request,
                    source_vm=None, target_vm=None,
                    res_pool=None, num=1, vm_status=None):

    print 'inside vcenter_connect vm_stauts is', vm_status

vm_list gets called first with vm_status passed in as a string, such as "poweredOff". Inside this function vm_status is equal to "poweredOff" as expected, but when I pass the value to vcenter_connect it's getting overridden by the default argument None. I am using other default arguments in vcenter_connect but they are working as expected, that is, they're only using the default values when nothing is passed in.
Running the relevent parts to test the string value gives me this:
inside vm_list vm_stauts is poweredOff
inside vcenter_connect vm_stauts is None

What am I doing wrong?

A: You pass vm_status as the 5th positional parameter to vcenter_connect, but the 5th positional parameter to that function is source_vm, so vm_status gets its default of None.
Instead, you must tell it which keyword parameter you are sending after the first 4 positional ones:
vmlist = vcenter_connect(server, user, password, vcenter_request, vm_status=vm_status)


text:
Q: How can I create a Xamarin.Forms cards carousel? How can I get this carousel of cards in Xamarin Forms?
I did it in ASP.Net-MVC C# and I'm using a JS plugin and HTML and CSS.
Now I need to do it using Xamarin Forms C# and XAML?

These are my namespaces:
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

A: Install CarouselView.FormsPlugin into your NuGEt solution.
Add  CarouselViewRenderer.Init(); in your MainActivity.s and AppDelegate.cs before  LoadApplication(new App());
In your xaml where you want to use carousalview,
            <controls:CarouselViewControl   IndicatorsTintColor="LightBlue"  x:Name="TilesSlider" IsVisible="False"  ArrowsTintColor="White"   CurrentPageIndicatorTintColor="White"  ItemsSource="{Binding }" ShowIndicators="True" AnimateTransition="True" ShowArrows="True"  Orientation="Horizontal"  InterPageSpacing="10"   VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" >
                <controls:CarouselViewControl.ItemTemplate>
                    <DataTemplate>

                        <Frame HorizontalOptions="FillAndExpand" HasShadow="False" CornerRadius="7" BackgroundColor="White" BorderColor="Snow" Margin="10,2,10,7">

                         <-----You can add your control her---->

                        </Frame>
                    </DataTemplate>
                </controls:CarouselViewControl.ItemTemplate>
            </controls:CarouselViewControl>

Inside the frame add your controls accordingly.

A: You can also use CardsView by nuget installing.
<ContentPage
x:Class="demo2.collection.Page14"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:cards="clr-namespace:PanCardView;assembly=PanCardView"
xmlns:controls="clr-namespace:PanCardView.Controls;assembly=PanCardView"
xmlns:ffimage="clr-namespace:FFImageLoading.Forms;assembly=FFImageLoading.Forms"
xmlns:proc="clr-namespace:PanCardView.Processors;assembly=PanCardView"
BackgroundColor="Black">
<ContentPage.Content>
    <StackLayout>
        <cards:CarouselView ItemsSource="{Binding Items}" SlideShowDuration="3500">
            <x:Arguments>

                <!--<proc:BaseCarouselFrontViewProcessor
                    OpacityFactor="0"
                    RotationFactor="0.1"
                    ScaleFactor="0.5" />

                <proc:BaseCarouselBackViewProcessor
                    OpacityFactor="0"
                    RotationFactor="0.1"
                    ScaleFactor="0.5" />-->

            </x:Arguments>
            <cards:CarouselView.ItemTemplate>
                <DataTemplate>
                    <ContentView>

                        <Frame
                            Padding="0"
                            CornerRadius="10"
                            HasShadow="false"
                            HeightRequest="300"
                            HorizontalOptions="Center"
                            IsClippedToBounds="true"
                            VerticalOptions="Center"
                            WidthRequest="300">

                            <ffimage:CachedImage Source="{Binding imagesource}" />

                        </Frame>
                    </ContentView>
                </DataTemplate>
            </cards:CarouselView.ItemTemplate>

            <controls:IndicatorsControl ToFadeDuration="1500" />

            <!--<controls:LeftArrowControl ToFadeDuration="2500" />

            <controls:RightArrowControl ToFadeDuration="2500" />-->
        </cards:CarouselView>
    </StackLayout>
</ContentPage.Content>

public partial class Page14 : ContentPage
{
    public ObservableCollection<model> Items { get; set; }
    public Page14 ()
    {
        InitializeComponent ();
        Items = new ObservableCollection<model>()
        {
            new model(){imagesource="a11.jpg"},
            new model(){imagesource="a12.jpg"},
            new model(){imagesource="a13.jpg"},
            new model(){imagesource="a14.jpg"},
            new model(){imagesource="a15.jpg"},
            new model(){imagesource="a9.jpg"}
        };
        this.BindingContext = this;
    }
}

public class model
{
    public string imagesource { get; set; }

}

Add the following code in Android Mainactivity and IOS AppDelegate, after Forms.Init()
CardsViewRenderer.Preserve() for iOS AppDelegate in FinishedLaunching
CardsViewRenderer.Preserve() for Android MainActivity in OnCreate

More ways about using CardsView, you can take a look:
https://github.com/AndreiMisiukevich/CardView


text:
Q: Transforming .csv Discovery Report into pipe delimited Marketing Cloud We would like to export a Marketing Cloud Discovery report. Marketing Cloud only gives you four options for download or SFTP:  .csv, pdf., .xlsx, .xsl . Is there a workaround for transforming a columned report into a pipe-delimited .txt file?
Our aim is trying to export the report, then import that report into a data extension. The only issue is that when we import the .csv, we have to select ',' as a delimiter. This causes an exception, as we have some data that has ',' in the values themselves. This causes an InvalidFieldCount error upon import.

A: When you export a Discover report as a csv file, Discover uses double-quote as the text qualifier. In order to successfully import a file like this to a Data Extension, ensure you check the "Respect double quotes as a text delimiter" box when defining the Import Definition.

In this way, you'll see data that incorporates commas successfully import into your DE:


text:
Q: how to change the decimal places based on conditions? based on certain condition i had to create an expression which shows either 2 or 3 decimal points. please see the code i have used
=Format(IIf(Fields!checkamt.Value>0,Fields!checkamt.Value * Fields!ExchangeRate.Value,""),"#,##0.F"+CStr(Fields!DecimalPlaces.Value))

output is 10000F2 or 10000F3 , which should be 10000.56 or 10000.561
based on the decimal places
which is not working . can someone help ?

A: From my understanding of the question we can follow the following steps;
1. Get the decimal Place column in your table (if not present)
2. Use
left(cast(round(cost,decimal_number) as char(32) ),decimal_number) as R


text:
Q: ArgumentError for very simple "initialize" method in Ruby on Rails with no arguments I have the simplest possible Ruby on Rails class:
class ProductProperty < ApplicationRecord
  def initialize
    puts 'hello world'
  end
end

But when I simply try to instantiate it, I get an ArgumentError:
[1] pry(main)> ProductProperty.new
ArgumentError: wrong number of arguments (given 1, expected 0)

I'm unclear why it thinks I am passing an argument in ("given 1"). Do I need to do something else to be able to write an initialize method that doesn't take arguments?

A: You can add *args.
class ProductProperty < ApplicationRecord
  def initialize(*args)
    puts 'hello world'
  end
end

But I am wondering why you override initialize?
You can use active record callbacks for that.

A: If you want to do something before, during or after you create/initalize an object you can use callbacks
For example:
class ProductProperty < ApplicationRecord
  after_create :do_something_special

  def do_something_special
    puts "I'm doing something"
  end
end
ProductProperty.create #=> "I'm doing something"

there are more callbacks available, so you can call specific methods during the lifecycle of an object.
you might also want to check out active record migrations if you want to persist and change data in your database


text: Q: Android Swipe View with Tabs How can I add a tab underline that follows the swipe like in the google play store. For now the tab line only moves when I finish the swipe. Also how can i add a background between fragments while swiping.


text:
Q: Adding a `;` at the end of while loop #include<stdio.h>

int main()
{
    int i=5;
    while(i--)
    {
        printf("%d\n",i);
    };
    printf("Out of loop\n");
    return 0;
}

This code works fine! Does ; at the end of a loop not mean anything?
So even if we add it, we don't have any problems? Just curious! I think adding ; at the end of a loop doesn't make any sense.

A: The ; here is considered as an empty statement or null statement.
Sample
int i = 0;;

For more information, you can check this question.
Word of Caution: Don't consider this as a thumb rule. There are cases where the representation may appear same, but they are not null statement but part of a syntax. Example: do..while loop

A: A superfluous ; is an empty statement and is redundant in this particular instance.
One instance where you're required to use an empty statement is in a switch to a final branch that does nothing:
switch (expression)
{
    case 1:
       /*Some statements here or empty*/
    case 2:
    ;  /*A statement is required between here and the closing brace
         An empty statement will suffice.*/
}

You ought to avoid using superfluous empty statements; they can emit bugs (particularly if you enclose your code in if statements during a refactoring effort), and older compilers will complain. Using excess semicolons in macros is particularly pernicious.

A: It "works", but it's an empty statement so it changes the structure of your program.
Consider this:
if (foo())
  while (bar())
  {
    foo_some_more()
  }
else
{
  do_something_about_it();
}

The above works since the while is a single statement, and thus the else is still able to "find" the if properly. If you add a semi-colon after the while-loop's closing brace, you break that structure and it will no longer compile.
So, although empty statements can look harmless, they are not so they really should be avoided. Plus: they add pointless confusion to the code, of course.

A: These are Perfectly Valid, They are called Empty statements,They do nothing.
int main()
{
  ;
  ;
  ;
  ;
  {
  }
  return 0;
}

A: As stated by various users above, the relevant semi-colon is an empty statement and has no effect.
This however is a slightly different story:
#include <stdio.h>

int main()
{
    int i=5;
    while(i--); //<--- Put the semi-colon here and see what you get.
    {
        printf("%d\n",i);
    }
    printf("Out of loop\n");
    return 0;
}

A: #include<stdio.h>

int main()
{

    int i=5;
    while(i--)
    {
        printf("%d\n",i);
    }/*blank statement*/;
    printf("Out of loop\n");
    return 0;
}

it's just a blank statement.
above The braces itself tells end of the block so then it would treat the ; as blank stament


text:
Q: Automatically select state and city according to zip code in Magento's onepage checkout I want to select automatically the state and city according to a zipcode in the billing information process bar of one page checkout.

A: Use GeoCoding APIs.
For example if you want result for zip 10017
http://maps.googleapis.com/maps/api/geocode/json?address=10017+US&sensor=true

Here we are passing ZIP code + Country. Reason is, some of the zip code returns more than one result. For example - 208006.
Thanks.


text:
Q: Is it possible to change the URL without re-loading the page in Meteor? I remember in Angular, I was able to dynamically change the URL without re-loading the page simply by changing $location
Is this possible to do something similar in Meteor?
I've tried using Router.go but that does reload the page, clearing all the fields.

A: You can use pure JavaScript (in modern browsers) to change the URL without reloading the page. See https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history As an example, evaluate history.pushState({}, "A new page", "myNewPage.html") in the console in your browser, and notice the change in the adressbar.
I guess Iron Router uses this under the hood when you change page.


text:
Q: Launch an specific app on android phone via WearOS app I am working on a WearOS application. This app is connected to an android device via bluetooth. I have created an app in that android device too. I want to launch that android app from my watch app by a button. I don't know how can I make my WearOS app to launch an specific app that I created in the android device.
I have learned to launch implicit intent using androidx.wear.remote.interactions.RemoteActivityHelper but it seems to work only with implicit intents.


text:
Q: Google group only visible inside organization I am owner of a Google group. I'm trying to use it to forward emails from AWS to group members so they can respond properly. However, messages sent to the group email address from outside the group cannot be sent. Every test email I send returns a response stating:
We're writing to let you know that the group you tried to contact (quantum) may not exist, or you may not have permission to post messages to the group. A few more details on why you weren't able to post:

*

*You might have spelled or formatted the group name incorrectly.

*The owner of the group may have removed this group.

*You may need to join the group before receiving permission to post.

*This group may not be open to posting.

I have confirmed that the email address matches the group email, and the owner (me) has not removed the group. That leaves the last two options. So, I went into the group settings and saw this:

The issue appears to be that the group is only visible to organization members and only organization members can post. But I don't have an option to allow posts from outside the organization. Does anyone know how to fix this?


text:
Q: Mandatory Active Directory attributes from LDAP Cannot create AD entry from LDAP because I'm missing mandatory attributes.

2019/02/08 15:50:29 LDAP Result Code 65 "Object Class Violation":
  00002077: UpdErr: DSID-03051277, problem 6002 (OBJ_CLASS_VIOLATION),
  data 0

This error is given when you are missing or trying to add an incorrect attribute value.
I'm using the gopkg.in/ldap.v3 library in golang. I can delete entries so the connection is fine but I cannot add them. This is the list of attributes I'm adding:
ar.Attribute("cn", []string{"test"})
ar.Attribute("instanceType", []string{"4"})
// ar.Attribute("nTSecurityDescriptor", []string{"user@example.org"})
ar.Attribute("objectCategory", []string{"CN=Person,CN=Schema,CN=Configuration,DC=sfh,DC=microlab-eindhoven,DC=nl"})
ar.Attribute("objectClass", []string{"organizationalPerson"})
ar.Attribute("objectClass", []string{"person"})
ar.Attribute("objectClass", []string{"top"})
ar.Attribute("objectClass", []string{"user"})
// ar.Attribute("objectGUID", []string{"user@example.org"})
// ar.Attribute("objectSid", []string{"user@example.org"})
ar.Attribute("sAMAccountName", []string{"test"})
ar.Attribute("givenName", []string{"test"})
ar.Attribute("displayName", []string{"test"})
ar.Attribute("userPassword", []string{"test"})
ar.Attribute("userPrincipalName", []string{"test"})
ar.Attribute("sAMAccountName", []string{"test"})

A: It has to be like this:
ar.Attribute("objectClass", []string{"organizationalPerson","person","top","user"})


text:
Q: How to check if a module is installed or a model is existed in odoo I want to inherit a form from another custom module without depends but It need to be check if that module is installed or model is existed before inherit it. I researched many docs but not found any solution regards so pls help me how can I do this

A: Check whether the module has been installed, and is in an installed state by querying against ir.module.module:
bokeh = self.env['ir.module.module'].search([('name', '=', 'module_name')])

if not bokeh or bokeh.state != 'installed':
    raise UserError(_('...'))

A: You can know if a module is installed checking the state field in the ir_module_module table.
I hope this help you!

A: To check module installed in odoo or not follow below step :
Login with Administrator access user > Click on Apps Menu from the Top Bar > You can search module with name or Apply Filter Installed


text:
Q: OpenCV: how to detect if video has fast moving object in it? What would be the best way to detect a fast moving object using OpenCV?
Say, I have 5 random video files:
1) Video of a crowd, people walking, static camera.
2) Video of a cat playing with a ball, shaky iPhone camera.
3) Video of a person being interviewed. Static camera.
4) Animation (3D) of a fast moving car, background is blurred etc. etc.
5) A blurred out video shot with iPhone camera (just camera waved around, nothing is visible).
So I would like to isolate video5 and detect that there is a lot of movement in video4 and video2.
What would be the best approach to do that? I think of using OpenCV2, but if there is a better solution for that, I'd be happy to learn about that.
Any input greatly appreciated. Pseudo-code or just recommendations of specific algorithms.
Thank you

A: Optical Flow This will be one of many ways of detecting motion.

A: I don't know if you are still on it but I found it interesting to answer.
Approach 1-
As suggested by user349026, one of the most intuitive way is to work with Optical flow, it will give you dominating motion but optical flow always comes with noises. You will have to use some filter before using the optical flow.
Approach- 2
This one difficult but gives good results.
This is from CVPR-2013 paper link- http://www.irisa.fr/texmex/people/jain/w-Flow/motion_cvpr13.pdf
I think the just introduction of this paper will solve your problem.


text:
Q: optimizer got an empty parameter list while using adam I was creating conv nets for cifar100 and code is give below but I have encounted the error mentioned in the title while initializing optimizer.
Code for model
class CNN(nn.Module):
  def __init__(self,k):
    super(CNN,self).__init__()
    #Convolutional layer
    conv1=nn.Conv2d(3,32,kernel_size=3,padding='same')
    conv2=nn.Conv2d(32,64,kernel_size=3,padding='same')
    conv3=nn.Conv2d(64,128,kernel_size=3,padding='same')
    conv4=nn.Conv2d(128,128,kernel_size=3,padding='same')
    conv5=nn.Conv2d(128,256,kernel_size=3,padding='same')
    conv6=nn.Conv2d(256,256,kernel_size=3,padding='same')
    #feddfordward layer
    f1=nn.Linear(4*4*256,4096)
    f2=nn.Linear(4096,k)
  def forward(self,x):
    x=f.relu(self.conv1(x))
    x=f.relu(self.conv2(x))
    x=f.max_pool2d(x,kernel_size=2,stride=2)
    x=f.relu(self.conv3(x))
    x=f.relu(self.conv4(x))
    x=f.max_pool2d(x,kernel_size=2,stride=2)
    x=f.relu(self.conv5(x))
    x=f.relu(self.conv6(x))
    x=f.max_pool2d(x,kernel_size=2,stride=2)
    x=x.view(-1,4*4*256)
    x=f.relu(self.f1(x))
    x=self.f2(x)
    return x

Model initialization
model=CNN(k)

device=th.device("cuda:0" if th.cuda.is_available() else "cpu")
print(device)
model.to(device)

lossFunction=th.nn.CrossEntropyLoss()
optimizer=th.optim.Adam(model.parameters())
epoch=100

I tried changing maxpool2d function but it didnot help. I am new to pytorch and any help will be appreciated

A: Your submodules must be registered as attributes of your parent nn.Module:
class CNN(nn.Module):
    def __init__(self,k):
        super(CNN,self).__init__()
        # convolutional layer
        self.conv1 = nn.Conv2d(3, 32, kernel_size=3, padding='same')
        self.conv2 = nn.Conv2d(32, 64, kernel_size=3, padding='same')
        self.conv3 = nn.Conv2d(64, 128, kernel_size=3, padding='same')
        self.conv4 = nn.Conv2d(128, 128, kernel_size=3, padding='same')
        self.conv5 = nn.Conv2d(128, 256, kernel_size=3, padding='same')
        self.conv6 = nn.Conv2d(256, 256, kernel_size=3, padding='same')

        # feedfordward layer
        self.f1 = nn.Linear(4*4*256, 4096)
        self.f2 = nn.Linear(4096, k)


text:
Q: RoR - Routing Error after creating an event I've a webapplication that can create new events and ruby binds them to a day. So I have an belongs_to has_many relationship
To create a new Event I made an own template:
newform.html.erb
<% provide(:title, "Event Optionen") %>

<%= form_for(@event) do |f| %>
  <%= render 'shared/error_messages', object: f.object %>

    <%= f.label :title, "Titel" %>

    <%= f.text_field :title %>

    <%= f.label :description, "Beschreibung" %>

    <%= f.text_area :description %>

    <%= f.label :day_id, "Tag"%>

    <%= f.collection_select :day, @dates, :to_s, :to_s, include_blank: false %>

    <%= f.label :start %>

    <%= f.time_select :start, :minute_step => 15 %>

    <%= f.label :end, "Ende" %>

    <%= f.time_select :end, :minute_step => 15 %>

    <%= f.hidden_field :day_id, :value => :day%>
    <%= f.submit "Event erstellen", class: "btn btn-large btn-primary" %>

<% end %>

events_controller.rb
class EventsController < ApplicationController
  include SessionsHelper
  before_action :set_event, only: [:show, :edit, :update, :destroy]
  before_filter :admin_authenticate

  def index
    @events = Event.all
  end

  def show
  end

  def new
    @event = Event.new
    lager  = Lager.find(params[:id])
    @dates = []
    for i in lager.start..lager.end
      @dates << i
    end

  end

  def edit
    @day = Day.find(params[:id]).date
  end

  def create
    event_params = params[:event]
    date         = Date.new event_params["start(1i)"].to_i, event_params["start(2i)"].to_i, event_params["start(3i)"].to_i
    start_time   = Time.new event_params["start(1i)"].to_i, event_params["start(2i)"].to_i, event_params["start(3i)"].to_i, event_params["start(4i)"].to_i, event_params["start(5i)"].to_i
    end_time     = Time.new event_params["end(1i)"].to_i, event_params["end(2i)"].to_i, event_params["end(3i)"].to_i, event_params["end(4i)"].to_i, event_params["end(5i)"].to_i
    title        = event_params[:title]
    description  = event_params[:description]
    day          = event_params[:day]
    day_id       = Day.find_by(date: "#{day}")

    @event = Event.new(start: start_time, end: end_time, title: title, description: description, day_id: day_id)

    respond_to do |format|
      if @event.save
        format.html { redirect_to root_path, notice: 'Event wurde erfolgreich erstellt.' }
        format.json { head :no_content }
      else
        format.html { render action: 'new' }
        format.json { render json: @event.errors, status: :unprocessable_entity }
      end
    end

  end

  def update
    respond_to do |format|
      if @event.update(event_params)
        format.html { redirect_to @event, notice: 'Event was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: 'edit' }
        format.json { render json: @event.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @event.destroy
    respond_to do |format|
      format.html { redirect_to events_url }
      format.json { head :no_content }
    end
  end

  private
    def set_event
      @event = Event.find(params[:id])
    end
end

so after creating this event it should redirect to the root_path otherwise rendering back the new.html.erb.
I get every time this error :/ And i don't know how to handle with it.

A: I think you get an error because you have not setup @dates in method create. I think you post the form with invalid params, @event can't be saved and you render new which use @dates.

A: Problem is you are trying for map method for nil object so try to find the object.I think for new Event @dates value will be nil ,so comment the line
<%= f.collection_select :day, @dates, :to_s, :to_s, include_blank: false %>
and reload page.


text:
Q: White Screen of Death error The home page of my website is loading well, but once loaded, it gets refreshed and a white screen is displayed. I tried many solutions, including restoring the database, deactivating plugins, etc, but no success.

A: According to the error you are defining WP_CACHE as true somewhere (maybe in wp-config.php?).  This way Wordpress is looking for a file that doesn't exist in default installation.
Disable it and the error will be gone.
You can also create an empty file advanced-cache.php in wp-content/ directory if you are unable to find WP_CACHE

A: thanks friends for all your support.
i tried many things excluding one .js file in my theme.
one .js file created by payment gateway integration team was creating the whole problem. i have just replaced it and site is working fine.


text:
Q: Exception: missing } in XML expression I am getting this error Exception: missing } in XML expression and also when i open my html file in FIREFOX  and use Firebug 1.9.2, this error appear:
WL is not defined [Break On This Error]
WL.Event.subscribe("auth.login", onLogin);`

Here is my code:

<title>Greeting the User Test page</title>

Connect to display a welcome greeting.

I dont know where is mistake, i just copy this sample code from skydrive api tutorial.
Of course, that I id and url strings replace with strings of my personal app.
Thanks for answers.

A: Your first

or possibly

if that site is configured properly. Without that, your URL was interpreted as being relative to the URL of your page.

A: You need to include the Javascript file from the Microsoft server:


text:
Q: Blur UINavigationBar like the photo app How can I achieve a blur on a UINavigationBar similar to the one found in the Apple photos app?
When I use this code I cannot even see my bar:
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new]
                                              forBarMetrics:UIBarMetricsDefault];
self.navigationController.navigationBar.shadowImage = [UIImage new];
self.navigationController.navigationBar.translucent = YES;
self.navigationController.view.backgroundColor = [UIColor whiteColor];

And in AppDelegate.m
[[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];

A: The behaviour you are looking for is called translucency, and is the default behaviour of aUINavigationBar. Is this behaviour not occuring by default in your application? What have you tried so far? Some more information could help.
Here's a link to the documentation for this property specifically.
EDIT: I've found a similar question on SO with an answer that may help you if you're using a custom background image for the bar. Find it here.

A: The easiest way to make a translucent navigation bar is to do nothing, since that is the default.
You are basically preventing that from happening. Let's look at your code:
A bar's tint color is not its color. It is the color of its buttons and images. If you make the tint color white and background color white, you are creating white buttons on a white background. That is going to be hard to see!
The color of the bar, on the other hand, is the barTintColor. Set that, and set the translucent to YES. Experiment with various barTintColor values and see what happens.
Do not set the background color, as this complicates things.
And above all do NOT set the background image, especially not to an empty image, since this overrides everything else and punches a hole in the navigation bar, making it completely transparent.


text:
Q: Does the Hochschild cohomology of an $A_{\infty}$-algebra have an algebra structure? For an algebra $A$ we can define its Hochschild cohomology (see this Wikipedia page) $HH^{\cdot}(A,A)$. It is well-known that the cup product makes $HH^{\cdot}(A,A)$ a (graded-commutative) algebra.
Now let $A$ be an $A_{\infty}$-algebra (see Mescher - A primer on $A_\infty$-algebras and their Hochschild homology Section 1 for definition) and we can still define its Hochschild cohomology (see the same preprint Section 3 for definition).

My question is: is $HH^{\cdot}(A,A)$ still an algebra for an $A_{\infty}$-algebra $A$? Or it is an $A_{\infty}$-algebra?


text:
Q: C language: remove the last element of a vector I'm trying to remove the last element of a vector. Returns 0 if the vector is empty, or 1 if not. x takes the value of the last element before it is thrown out.
int vector_pop(struct vector *v, int *x)
{
    if (v->size == 0)
    {
        return 0;
    }
    x = v->data[v->size];
    free(v->data[v->size]);
    return 1;
}

A: Since your vector contains ints, you do not free its elements individually. A simple option is to drop free altogether, and make sure that you reduce size before taking the element off the vector:
if (v->size == 0)
{
    return 0;
}
v->size--;
*x = v->data[v->size]; // Note the asterisk
return 1;

It is important to keep track of both the allocated size and the effective size when implementing your own dynamic vector. v->size tells you how many elements are set in your vector now, while v->allocated_size should tell you how many elements you could push into the vector without having to reallocate memory in v->data.


text:
Q: Comparing Different Properties of a Class in a std::vector of a Class I really didn't know what's the proper title for this would be, please bear with me.
So, imagine I have a class like:
class data {
    double a;
    double b;
    double c;

    bool is_blue;
};

and then I use it to construct a vector, std::vector<data> vdata. What I'm interested in is to be able to compare values of the vector based on the given property of the class. For instance, I'd like to find the element with smallest a, or find all elements with b > 2.0, or is_blue == true.
I have a few ideas on how to achieve this, but they don't cover all the cases that I want to. For instance, I can probably loop over elements of the vdata, select a's and construct a std::vector<double> and then use std::min_element to get the min. Or, use std::find to find what I want.
Or, maybe I can use std::transform and a lambda and generate a vector indicating if my test passed or not, and then select from that, like:
std::vector<bool> s;
std::transform(s.begin(), s.end(), std::back_inserter(ordinals),
                   [](auto &d) -> bool { return d.b > 2.0 });

I also thought maybe I can use std::sort and basically sort my vdata based on what I'm interested in. I'm not even sure if this method make sense.
So, I know how to approach this in different ways, and they work but I feel I'm missing something, and it should be a better way that covers all the cases. I'm mostly interested in some comparisons and min/max elements. I also have a complete control over the data class, so, I can freely add to it, encapsulate it into another class, etc.
P.S. Please let me know if I can choose a better title for this question.

A: For the things you mention, you can use functions in the standard library. You'll need std::min_element (as you mentioned) and std::partition (or std::stable_partition).
#include <algorithm> // min_element, partition

std::ostream& operator<<(std::ostream& os, const data& d) {
    return os << '{' << d.a << ',' << d.b << ',' << d.c << ',' << d.is_blue << '}';
}
//...

    std::cout << "element with smallest a\n";
    auto min_it = std::min_element(vdata.begin(), vdata.end(),
                                   [](const data& l, const data& r) { return l.a < r.a; });
    std::cout << *min_it << '\n';

    std::cout << "range with all b > 2.0\n";
    auto pivot = std::partition(vdata.begin(), vdata.end(),
                                [](const data& d) { return d.b > 2.; });
    for(auto it = vdata.begin(); it != pivot; ++it) {
        std::cout << *it << '\n';
    }

    std::cout << "range with all blue\n";
    pivot = std::partition(vdata.begin(), vdata.end(),
                           [](const data& d) { return d.is_blue; });
    for(auto it = vdata.begin(); it != pivot; ++it) {
        std::cout << *it << '\n';
    }

I have a few ideas on how to achieve this, but they don't cover all the cases that I want to.

There are different algorithms for different scenarios. You'll hardly find one that covers all the cases (except in some trivial cases where you may get one for free so to speak).


text:
Q: How do you get the selected directory path from file system access api window.showDirectoryPicker() When I choose a folder I do get a dirHandle but cannot figure out what property or method will give me the full path
const dirHandle = await window.showDirectoryPicker()

So something like let path = dirHandle.fullpath
Any ideas?

A: For security reasons the full path will not be revealed to web applications. You can only learn the relative paths by walking through a directory. In the example below, if the user opens shared/, you can learn about the existence of ./public and ./public/file.txt inside of it, but not that shared/ lies in secret/ and further up.
/root/secret/shared/public/file.txt


text:
Q: Variable o metodo no definida en Ruby ¿Como lo solucion con metaprogramacion? Buenas que tal, estoy trantado de definir un comportamiento a la Clase Persona:

Lo que necesito hacer es que al colocarle el "transaccional" dentro del cuerpo de la clase dinamicamente me incluya un mixin a la clase o ejecute algun metodo. Entiendo que se puede hacer con metaprogramación pero no se como.Espero que puedan darme una ayuda. Gracias de antemano.

A: No sé exactamente qué comportamiento buscas o por qué quieras utilizar metaprogramación, pero considerando que tengas un módulo Transaccional:
module Transaccional
  # métodos
end

Podrías lograrlo agregando el método transaccional a la clase Class, el cual se encargue de hacer el include; por ejemplo:
class Class
  def transaccional
    self.class_eval("include Transaccional")
  end
end

Ahora al utilizar transaccional dentro del cuerpo de la clase será lo mismo que utilizar include Transaccional.

Si únicamente quieres agregar el método dinámicamente y sin metaprogramación entonces lo único que tendrías que hacer es esto:
Persona.include(Transaccional)

En este caso no necesitarás poner nada en el cuerpo de la clase Persona:
class Persona
  include Lockeable

  attr_accesor :nombre, :edad
  # ...
end


text:
Q: Azure Web App update We have created the Web applications and we have a plan to publish the application as Web App in Azure Marketplace. Publishing the Web App to Marketplace can be done using ARM templates(POC) for one-click deployment for our customers.
When we release the newer version of the application, how can we provide the seamless upgrade to our customers through the Azure Marketplace like Google Play Store (Install button for 1st time and Update button for older version use users?
I came through this article explained the deployment in Azure. But, i didn't find any article for Upgrade Azure App
https://learn.microsoft.com/en-us/azure/app-service-web/web-sites-deploy

A: We can use git pull command to get the updates from other git repository. In Azure kudu, the command could be like this,
D:\home\site\wwwroot>git remote add gitsource https://username@passwordyourgitserver.com/xx.git
D:\home\site\wwwroot>git pull gitsource master

When we release the newer version of the application, how can we provide the seamless upgrade to our customers

After released the new version of your application, you could force your client to execute upper command to get the updates. If you use C# as your programming language, you could use following steps to execute powershell command.

*

*Install System.Management.Automation dll using NuGet.

*Run powershell scripts using following method.

private static string RunScript(string scripts)
{
    // create Powershell runspace
    Runspace runspace = RunspaceFactory.CreateRunspace();
    // open it
    runspace.Open();
    // create a pipeline and feed it the script text
    Pipeline pipeline = runspace.CreatePipeline();

    pipeline.Commands.AddScript(scripts);
    pipeline.Commands.Add("Out-String");
    //execute the script
    Collection<PSObject> results = pipeline.Invoke();
    //close the runspace
    runspace.Close();
    // convert the script result into a single string
    StringBuilder stringBuilder = new StringBuilder();
    foreach (PSObject obj in results)
    {
        stringBuilder.AppendLine(obj.ToString());
    }
    return stringBuilder.ToString();
}

A: In the ARM template you use to provision the site for the customer, you can enable continuous deployment to that site from a GitHub repo. So anytime that repo is updated, the website (any or all of them) provisioned by your template will be update with the new drop.
See this sample template: https://github.com/Azure/azure-quickstart-templates/tree/master/201-web-app-github-deploy
And then for automated deployments set this to "false":
https://github.com/Azure/azure-quickstart-templates/blob/master/201-web-app-github-deploy/azuredeploy.json#L101


text:
Q: Spring security SAML authentication failure with Microsoft ADFS We are trying to use Spring Security to connect to a Microsoft ADFS server.
We set up the Spring SAML sample application, as described in Spring security documentation, but we get the following errors on the ADFS server.
Exception details:
    Microsoft.IdentityServer.Protocols.Saml.SamlProtocolSignatureVerificationException: MSIS7075: SAML authentication request for the WebSSO profile must not specify any SubjectConfirmations.
       at Microsoft.IdentityServer.Web.Protocols.Saml.SamlProtocolManager.ValidateSignatureRequirements(SamlMessage samlMessage)
       at Microsoft.IdentityServer.Web.Protocols.Saml.SamlProtocolManager.Issue(HttpSamlRequestMessage httpSamlRequestMessage, SecurityTokenElement onBehalfOf, String sessionState, String relayState, String& newSamlSession, String& samlpAuthenticationProvider, Boolean isUrlTranslationNeeded, WrappedHttpListenerContext context, Boolean isKmsiRequested)
       at Microsoft.IdentityServer.Web.Protocols.Saml.SamlProtocolHandler.RequestBearerToken(WrappedHttpListenerContext context, HttpSamlRequestMessage httpSamlRequest, SecurityTokenElement onBehalfOf, String relyingPartyIdentifier, Boolean isKmsiRequested, Boolean isApplicationProxyTokenRequired, String& samlpSessionState, String& samlpAuthenticationProvider)
       at Microsoft.IdentityServer.Web.Protocols.Saml.SamlProtocolHandler.BuildSignInResponseCoreWithSerializedToken(HttpSamlRequestMessage httpSamlRequest, WrappedHttpListenerContext context, String relyingPartyIdentifier, SecurityTokenElement signOnTokenElement, Boolean isKmsiRequested, Boolean isApplicationProxyTokenRequired)
       at Microsoft.IdentityServer.Web.Protocols.Saml.SamlProtocolHandler.BuildSignInResponseCoreWithSecurityToken(SamlSignInContext context, SecurityToken securityToken, SecurityToken deviceSecurityToken)
       at Microsoft.IdentityServer.Web.Protocols.Saml.SamlProtocolHandler.Process(ProtocolContext context)
       at Microsoft.IdentityServer.Web.PassiveProtocolListener.ProcessProtocolRequest(ProtocolContext protocolContext, PassiveProtocolHandler protocolHandler)
       at Microsoft.IdentityServer.Web.PassiveProtocolListener.OnGetContext(WrappedHttpListenerContext context)

And then:
The verification of the SAML message signature failed.
Message issuer: http://adfs.xxxx.yyyy.com/adfs/services/trust
Exception details:
MSIS7075: SAML authentication request for the WebSSO profile must not specify any SubjectConfirmations.

This request failed.

User Action
Verify that the message issuer configuration in the AD FS configuration database is up to date.
Configure the signing certificate for the specified issuer.
Verify that the issuer's certificate is up to date.
Verify the issuer and server message signing requirements.

We already applied the above suggestions.
There is no error message in the Spring security logs.

A: The SAML specs (4.1.4.1  Usage) say:

Note that the service provider MAY include a  element in the
  request that names the actual identity about which it wishes to
  receive an assertion. This element MUST NOT contain any
   elements. If the identity provider does not
  recognize the principal as that identity, then it MUST respond with a
   message containing an error status and no assertions.

Looks like the module may be violating that spec. Check and see if there is an option to avoid sending SubjectConfirmation elements to the IDP.


text:
Q: How do I pass cookies from HEAD to POST-Request I need to pass csrf cookies _gorila_csrf and csrf_token from my HEAD-Request to my POST-Request. What is the best practice for that?
For now I get the Cookie Value with res.Cookies() for the two cookies, built the Cookie-Header Value and pass to the next function. Is there any method to pass the real cookie to the next request?
var c = resp.Cookies()[0].Name+"="+resp.Cookies()[0].Value+";"+resp.Cookies()[1].Name+"="+resp.Cookies()[1].Value
var t = resp.Cookies()[1].Value

Is it possible to address the cookie by name in case more cookies are added in the future and the order changes?
Edit - Example (not working because the api url does not response with the right cookies):
package main

import (
    "fmt"
    "net/http"
    "time"
)

const url = "https://google.com"

func main() {
    client := &http.Client{
        Timeout: time.Second * 5,
    }
    r, _ := http.NewRequest("HEAD", url, nil)
    resp, _ := client.Do(r)

    var c = resp.Cookies()[0].Name + "=" + resp.Cookies()[0].Value + ";" + resp.Cookies()[1].Name + "=" + resp.Cookies()[1].Value
    var t = resp.Cookies()[1].Value

    fmt.Println(c)
    fmt.Println(t)
    }


text:
Q: Difference between differential and derivative I'm really not clear with the subtlety between derivative and differential. Let $f:\mathbb R^2\to \mathbb R$, then the derivative is $\nabla f(x,y)=(\partial _x(x,y) f,\partial _y f(x,y))$ where as the differential is $df=\partial f_xdx+\partial _y dy$. What these notation mean ? Also, I always thought that differential and derivative where almost the same, but with thise definitions, I'm completely confuse.

A: I'm going to try to answer this:
If you consider a function $f:\mathbb{R}^n \to \mathbb{R}$, then the vector of its partial derivatives, $\nabla f(x_1,.....,x_n)=(\frac{\partial f}{\partial x_1},....,\frac{\partial f}{\partial x_n})$ is called the gradient and it is a vector in $\mathbb{R}^n$. It is a generalisation of the derivative in a one-dimensional setting.
The total derivative (what you called differential), in the case where the codomain is one-dimensional, is simply a scalar and is the result of multiplying the gradient $\nabla f(x_1,.....,x_n)=(\frac{\partial f}{\partial x_1},....,\frac{\partial f}{\partial x_n})$ with a vector $\vec{v} \in \mathbb{R}^n $ (vetor multiplication). It represents the linear approximation of the variation of f when the the coordinates vary by $\vec{v}$.
Example
$f(x,y) = x^2+ y^2$, then $\nabla f(x,y) = (2x,2y)$. If you consider the point (1,1), then $\nabla f(1,1) = (2,2)$ . If you have a variation of the coordinates by the vector $\vec{v}= (3,3)$, so you go from $(1,1)$ to $(4,4)$, then your linear approximation of the variation of the function is $ (2,2)*(3,3) = <(2,2),(3,3)> = 12$. This means that the differential (linear approximation of the variation) is of 12.
So if you compute $f(1,1) + \nabla f(1,1)*(3,3) = 14$, you obtain a linear approximation of $f(4,4) = 32$. Now this is a bad approximation because we only took the first-order derivative in consideration (look at Taylor Series for more detail on it).  If instead we had $f(x,y) = 2x + 2y$, you would see that the linear approximation would give you the exact value.


text:
Q: Calculate price from width and height The question is divided into 2 parts.
1. How to structure the data in the json array
2. How to calculate the price from the json array
I need to store the price data inline in HTML as JSON, as AJAX requests to the server are too slow/heavy.
The data are stored as serialized strings in a database. This is added to the database from CSV file uploads. The CSV files looks like below.
      50    100    150    200    250
20    70     90    110    130    150
30    90    110    130    150    170
40    110   130    150    170    190
50    130   150    170    190    210
60    150   170    190    210    230

If you enter 100 in width and 40 in height, the price should be 130.
If you enter 170 in width and 52 in height the price should be 210.
If column or row is not found, it should round up to next column or row.

*

*What is the best way to store this as JSON inline, if you need to calculate the price based on width and heigth?

*How would you calculate the price, based on user input width and height?
I am not looking for specific code, just suggestions on the JSON structure and how to calculate from this.

A: You could take two arrays for widths and heights and a 2D array for the prices.
For getting a right price get the indices first and then the price.
Maybe you need to add some guard for the values to prevent getting wrong indices.

const
    getPrice = (width, height) => {
       const
           w = widths.findIndex(w => width <= w),
           h = heights.findIndex(h => height <= h);
       return prices[w][h];
    },
    widths = [50, 100, 150, 200, 250],
    heights = [20, 30, 40, 50, 60],
    prices = [[70, 90, 110, 130, 150], [90, 110, 130, 150, 170], [110, 130, 150, 170, 190], [130, 150, 170, 190, 210], [150, 170, 190, 210, 230]];

console.log(getPrice(100, 30));
console.log(getPrice(90, 25));

A: When there is a regular pattern for the width and height steps you could also do the following:

const h0=20,dh=10,w0=50,dw=50, prices=
 [[  70,   90,  110,  130,  150],
  [  90,  110,  130,  150,  170],
  [ 110,  130,  150,  170,  190],
  [ 130,  150,  170,  190,  210],
  [ 150,  170,  190,  210,  230]];

// w,h
[[100,30],[90,25]].forEach(([w,h])=>
 console.log(prices[Math.ceil((h-h0)/dh)][Math.ceil((w-w0)/dw)]));


text:
Q: Reverse a string with a single loop I want to reverse a string by only using a single loop. How can I do it? I tried one simple way but doesn't get the output I wish.
#include<iostream>
using namespace std;

int main()
{
    int i;
    char a[10];

    cout << " Enter String :";
    cin >> a;

    for(a[i] = '\0'; i > 0; i--)
    {
        cout << "Reverse string is" << a[i];
    }

    return 0;
}

A: Note that you do not initialize your iterator variable i and that you could declare the index within the for-statement as you do not need this variable outside the scope of the for-loop. Furthermore, you can also use a std::string instead of a char array, this also allows for strings longer than the ten characters as you had specified.
EDIT: I assume that you can use C++17 or newer. From C++17 they finally added the non-member version std::size (which I prefer over the member related versions since I read the book effective modern c++ from Scott Meyers). If, for some reason, you cannot use this function, then you can just replace it by the string member function length, i.e., a.length().
If you only want to print the reverse of the string you could use something like the following
int main()
{
    string a;

    cout << "Enter String: ";
    cin >> a;

    for (int idx = size(a) - 1; idx >= 0; --idx)
      cout << a[idx];
    cout << endl;
}

You may also use the built-in reverse function (see description here). This function actually reverses the string itself.
int main()
{
    std::string a;

    std::cout << "Enter String: ";
    std::cin >> a;

    std::reverse(std::begin(a), std::end(a));

    std::cout << a << endl;
}

Another option is to manually reverse the string (which doesn't make sense since std::reverse is part of the standard library, but as a learning exercise it might be helpful). Note that we only iterate to half the size of the string as otherwise each element is swapped twice, resulting in the original string.
int main()
{
  string a;

  cout << "Enter String: ";
  cin >> a;

  for (size_t idx = 0, n = size(a); idx < n / 2; ++idx)
    swap(a[idx], a[n - idx - 1]);
  cout << a << endl;
}


text:
Q: please explain what happens when you access a jQuery object directly? For example:
$('.something')[0]

I've been working with javascript for about a year now and I see this sometimes in various projects' codebase... What does it mean and what does it do?

A: $(".class") selector selects all elements with the specific class. Internally, it uses getElementsByClassName() to traverse the DOM and retrieve the elements. That method  returns "an array-like object of all child elements which have all of the given class names". Hence, $('.something')[0] is simply retrieving the first element off that array. It will hold the very first HTML DOM element with that class (since you might have many elements having that class, right?). Type of $('.something')[0] will be object.


text:
Q: What is time complexity for the following code? It seems the complexity of the following code should be O(n^2) but it's O(n), how?
void fun(int n, int arr[])
{
    int i = 0, j = 0;
    for(; i < n; ++i)
        while(j < n && arr[i] < arr[j])
            j++;
}

A: In the first look, the time complexity seems to be O(n^2) due to two loops. But, please note that the variable j is not initialized for each value of variable i.
Hence, the inner j++ will be executed at most n times.
The i loop also runs n times.
So, the whole thing runs for O(n) times.
Please observe the difference between the function given in question and the below function:
void fun(int n, int arr[])
               {
int i = 0, j = 0;
for(; i < n; ++i)
{
    j = 0;
    while(j < n && arr[i] < arr[j])
        j++;
}

}`
Still not convinced ?
Let's assume the array passed has its element in decreasing order. We will just dry run through the code :
               Iteration 1 : i = 0, j = 0. arr[0] < arr[0] is false. So, the
                             inner while loop breaks.
               Iteration 2: i =1, j = 0. arr[1] < arr[0] is true. j becomes
               Iteration 3 : i = 1, j = 1. Condition false. We break. Note
                            that j will remain 1 and is not reset back to 0.
               Iteration 4 : i = 2, j = 1. arr[2] < arr[1]. True. j = 2.
               Iteration 5 : i = 2, j = 2. Condition false. Break.
               Iteration 6 : i = 3, j = 2. arr[3] < arr[2]. True. j = 3.
               Iteration 7 : i = 3, j = 3. Condition false. Break.

As you can see, the inner while loop only runs once in this case.
So, total iterations is 2 * N.

A: j is not reset to 0 with every iteration of the outer loop. As such, it runs to n-1 just once, same as i does. So you have two parallel/intermingled iterations from 0 to (at most) n-1.

In every step, the program increases i by one. The program terminates when i reaches n. The "outer loop" is run n times.
There is also an "inner loop" about j. But all it does is increase j until it reaches i (at most, sometimes it does less). j is never decreased. So that part is also run at most n times in total (not n times for each iteration of the "outer loop").

A: The answer is O(n)
The outer loop runs 'n' times and the inner loop only runs to 'n' a single time in all the iterations combined as the value of j is never reset to 0.
Therefore the answer is O(n+n)=O(n).

A: Lets consider the worst case when the while loop is executed maximum no. of times.
Initially: i=0 , j=0  => while loop does not gets executed since arr[0] = arr[0] i.e. j=0.
Second iteration : i=1 , j=0 => while loop gets executed for the worst case i.e. j=1.
Third iteration : i=2 , j=1 => while loop again gets executed for the worst case i.e. j=2.
...
nth iteration : i=n-1 , j=n-2 => while loop again gets executed for the worst case i.e. j=n-1.
So, by doing this exercise we can observe that every time j = i-1
except i=0 and j=0 OR we can say that the while loop is just running in parallel to the for loop and thus the no. of executions of the while loop is equal to the no. of executions of the for loop.
Hence Order = O(n);

A: The answer is O(n) because the test condition inside the 'while' loop fails!
while(j < n && arr[i] < arr[j])

In the beginning, i=0 and j=0, which means arr[i] = arr[j], but the while loop test condition says arr[i]<arr[j], and its completely wrong to assume arr[0]<arr[0]
The code only runs the for loop n times.
The final answer is O(n) not O(n^2)
For some clarity, you can go through these two examples
Example 1 :
#include <stdio.h>

int main()
{
    int i = 0, j = 0;
    int n = 5;
    int arr[] = {6,7,8,9,10,11};
    for(; i < n; ++i)
    {
        printf("\nThis is for loop, its running 5 times\n");

        while(j < n && arr[i] < arr[j]){
            j++;
            printf("\nThis is while loop!\n");
        }
    };
    return 0;
}

The Output is :
This is for loop, its running 5 times

This is for loop, its running 5 times

This is for loop, its running 5 times

This is for loop, its running 5 times

This is for loop, its running 5 times

In the above output, we can't find the print statement present in 'while' loop
Example 2 :
#include <stdio.h>

    int main()
    {
        int i = 0, j = 0;
        int n = 5;
        int arr[] = {6,7,8,9,10,11};
        for(; i < n; ++i)
        {
            printf("\nThis is for loop, its running 5 times\n");

            while(j < n && arr[i] <= arr[j]){
                j++;
                printf("\nThis is while loop!\n");
            }
        };
        return 0;
    }

Here, a small change is made
arr[i] <= arr[j]
'=' is used
Output:
This is for loop, its running 5 times

This is while loop!

This is while loop!

This is while loop!

This is while loop!

This is while loop!

This is for loop, its running 5 times

This is for loop, its running 5 times

This is for loop, its running 5 times

This is for loop, its running 5 times

Here, the print statement in while loop is executed, because arr[i]=arr[j],
arr[0] = arr[0]
For the 'Example 2' shown above the time complexity is O(n^2)

A: Note that the variable j is not initialized for each value of variable i.
Hence, the inner j++ will be executed at most n times.
The i loop also runs n times.
So, the whole thing runs for O(n) times.


text:
Q: Constant work function although changing Fermi energy I'm working with the following book "Interfacial Electrochemistry" (2nd Edition) written by Wolfgang Schmickler and Elizabeth Santos and I'm trying to understand the process described in section "Absolute electrode potential". You can find the chapter here.
There the work function is defined as follows:

For electrons in a metal the work function Phi is defined as the
  minimum work required to take an electron from inside the metal to a
  place just outside. [...]  The work function is the negative
  of the Fermi level, provided the reference point for the latter is chosen just
  outside the metal surface.

"Just outside" means (mentioned in an earlier chapter):

A postion very close to the surface, but so far away that the image
  interaction with the phase can be ignored.

The process I'm refering to is described on page 31:

[...] let us first consider two metals, I and II, of different chemical
  composition and different work functions ΦI and ΦII. When the two
  metals are brought into contact, their Fermi levels must become equal.
  Hence electrons flow from the metal with the lower work function to
  that with the higher one, so that a small dipole layer is established
  at the contact, which gives rise to a difference in the outer
  potentials of the two phases (see Fig. 4.1).

I don't understand the last half sentence. Why do the outer potentials change and not the work functions? E.g. I'm decreasing the Fermi Level of metal 1, hence (according to the definition) I'm increasing the work function.
These work functions and outer potentials are relative to the adjoining surfaces. The electrons flow to the metal with the lower Fermi energy and build a dipole at the interface. This could have impact on the work function.
Because of the same reason I could understand why the outer potentials change after joining the metals. I just don't get why the work function stays the same.
Thanks for your help!

A: Workfunction should be consistent under conditions where material is made up of same composition within same surface because it is a property of materials. It was confusing to me when I was in my first year. That being said workfunction varies from materials and it also depends on the surface. As I sum it up, you can think of workfunction as a function of material,surface. On the other hand, fermi level of which definition is a chemical potential of electron. That means, fermi level can only be the value varied. You can either check text book or google defintion of Fermi level and Workfunction.
Hope this helps
Seoul National University, M.S candidates, school of mechanical engineering.


text:
Q: Handling selection of buttons + adding selected items to new array I am working with a set of arrays which are printed to the screen as buttons via an API call.
I am looking to add my bases/frostings buttons (select one) and then add the key of each one selected to a new OrdersArray. I also need to be able to select multiple toppings (multi-select) and add those to a nested array within the OrdersArray.
I would like to also change the colors of each selected button when they are selected.
My Buttons function generates the buttons.
function Buttons({ list }) {
  const style = {
    display: 'inline-block',
    textAlign: 'center',
    border: '1px solid black',
    padding: '10px',
    margin: '10px',
    width: '35%'
  }

  return (

        {list && list.map(item =>
            <button key={item.key}
            style={style}
            >
                {/*
{item.key}
 */}

{item.name}

${item.price}.00

                {/*
{item.ingredients}
 */}
            </button>
        )}

  );
};

My app component renders the buttons.
Class App extends Component {
        constructor() {
          super();

          this.state = {
              'basesObject': {},
              'frostingsObject': {},
              'toppingsObject': {},
              selectedButton: null
          }
      }

      componentDidMount() {
        this.getBases();
        this.getFrostings();
        this.getToppings();
      }

      /* GET DATA FROM SERVER */
      getBases() {
        fetch('http://localhost:4000/cupcakes/bases')
        .then(results => results.json())
        .then(results => this.setState({'basesObject': results}))
      }

      getFrostings() {
        fetch('http://localhost:4000/cupcakes/frostings')
        .then(results => results.json())
        .then(results => this.setState({'frostingsObject': results}))
      }

      getToppings() {
        fetch('http://localhost:4000/cupcakes/toppings')
        .then(results => results.json())
        .then(results => this.setState({'toppingsObject': results}))
      }

render() {
    let {basesObject, frostingsObject, toppingsObject} = this.state;

    let {bases} = basesObject;
    let {frostings} = frostingsObject;
    let {toppings} = toppingsObject;

    return (

Choose a base

        <Buttons on
         list={bases}
        />

Choose a frosting

        <Buttons
         list={frostings}
        />

Choose toppings

        <Buttons
         list={toppings}
        />

    );
  }
}

I'm new to React, any help would be appreciated! :)

A: You'll need to pass a function to the buttons that will modify a state value in the parent component when the button is clicked.
In parent:
const addToOrder = item => {
orderArray.push(item);
const newOrder = orderArray.reduce((acc, order) => {
  return acc + " " + order.name;
}, "");
setOrder(newOrder);
};
...
<Button addToOrder={addToOrder} />

In Button.js
<button onClick={() => addToOrder(item)} >

Check out the whole thing in this Sandbox
For keeping track of which ones have been clicked you'll need to keep track of button state either in the button component itself or in the parent container if you want to keep the buttons stateless.  Then set the button attribute disabled to true or false based on that state.
<button disabled={isButtonDisabled} />

Sorry I didn't have time to flesh the full thing out, but this should get you in the right direction.


text:
Q: How to add quantity to a rails form (create n records when submitting)? I have a library-like booking system. I want to make a form for adding books in stock, allowing the user to choose a book and choose a library (both are collection_select). Book has a many-to-many relationship with Library, through the stock_items table.
What I can't figure out is how can bring in the quantity, so that the user can add a number of instances of the same book to a chosen university. How should I approach implementing this quantity-type feature. It should create a chosen amount of records in the join table.
Here's my form (currently creates only 1 instance at a time):
<%= form_for(@item) do |f| %>

    <%= f.label :choose_book %>
    <%= f.collection_select(:book_id, Book.all, :id, :name, prompt: true) %>

    <%= f.label :choose_library %>
    <%= f.collection_select(:library_id, Library.all, :id, :name, prompt: true) %>

    <%= f.submit "Add item in stock", class: "btn btn-info" %>
<% end %>

StockItem model
class StockItem < ActiveRecord::Base

    belongs_to :library
    belongs_to :book

    has_many :bookings, foreign_key: :stock_id, dependent: :destroy

    validates :availability, presence: true
    validates :library_id, presence: true
end

Library model
class Library < ActiveRecord::Base

    has_many :stock_items
    has_many :books, through: :stock_items

end

Book model
class Book < ActiveRecord::Base

    validates :year_of_publication, presence: true, length: { maximum: 4 }
    validates :description, presence: true, length: { minimum: 10 }
    validates :name, presence: true

    has_many :stock_items,      dependent: :destroy
    has_many :libraries,        through: :stock_items
    has_many :contributions,    dependent: :destroy
    has_many :authors,      through: :contributions
    has_many :bookings,         through: :stock_items

    has_many :book_images, dependent: :destroy
    accepts_nested_attributes_for :book_images
    accepts_nested_attributes_for :authors
    accepts_nested_attributes_for :libraries
    accepts_nested_attributes_for :stock_items
    accepts_nested_attributes_for :contributions

    validates :name, presence: true
end

A bit of the StockItemsController
def create
    @item = StockItem.new(item_params)

    if @item.save
        flash[:success] = "Item added to stock"
        redirect_to stock_items_path
    else
        flash[:danger] = "Item has not been added to stock!"
        render 'new'
    end
  end

  def new
    @item = StockItem.new
  end

  private

    def item_params
        params.require(:stock_item).permit(:library_id, :book_id, :availability)
    end

A: I think your answer is systemic, rather than syntaxic, meaning you have to consider your system rather than the specific action syntax
--
M-to-M
You specifically need to look at the many-to-many association you've deployed here
Your population of the StockItem table is basically a way to create a collection for each library, and so you should look at the many collection based methods which ActiveRecord provides (specifically << and .delete)
Bottom line is that instead of creating new records for your StockItem model, I would just add to the collection of both library - giving you the files you need to make it work
--
Collection
As you're using has_many :through, you can add multiple instances of the same record to your collection (as opposed to has_and_belongs_to_many, which only permits single instances of records, as there is no primary_key)
This means you'll be able to just add books individually to the collection, and then use the sum method of SQL to calculate the quantity:
#app/controllers/stock_items_controller.rb
class StockItemsController < ApplicationController
   def create
       @library = Library.find params[:stock_item][:library_id]
       @book = Book.find params[:stock_item][:book_id]

       @library << @book
   end
end

--
Quantity
This is opposed to the idea that you can add a qty attribute to your StockItem model, and then use the increment! method:
#app/controllers/stock_items_controller.rb
Class StockItemsController < ApplicationController
   def create
      @item = StockItem.find_by(library_id: params[:stock_item][:library_id],book_id: params[:stock_item][:book_id])
      @item ? @item.increment!(:qty) : StockItem.create(stockitem_params)
   end
end