Sticky Component inside scrollview

Question: I'm trying to build a a sticky component like this app
http://www.screencapture.ru/file/E88F08Fc
Deals, Products, Events tabs/segmentControl are actually start from bottom and as you scroll when you hit bottom of the header it stops and start stick while the content keep scrolled
this is my code
        <View style={styles.container}>
            <ScrollView
                style={styles.container}
                scrollEventThrottle={16}
                onScroll={
                    Animated.event(
                        [{nativeEvent:{contentOffset: {y: this.state.scrollY}}}]
                    )
                }
            >
                {this._renderScrollViewContent()}
            </ScrollView>
            <View style={styles.stickyStuff}></View>
            <Animated.View
                style={[styles.header, {height: headerHeight}]}
            >
                <Animated.Image
                    source={require('../../assets/images/pvj.jpg')}
                    style={[styles.backgroundImage, {opacity: imageOpacity}]}
                />
                <Animated.View style={[styles.bar, {transform: [{translateY: titleTranslateY}, {translateX: titleTranslateX}]}]}>
                    <Text style={styles.title}>PARIS VAN JAVA</Text>
                </Animated.View>

            </Animated.View>
        </View>

Comment: @ChrisGeirman sorry to make you confuse, cause i still havent got any reputation so i cant embed images need to screen cap every movement to demonstrate the UX so here step by step the ux i need to expect 1. http://www.screencapture.ru/file/1609269e 2. http://www.screencapture.ru/file/fEA8377B 3.http://www.screencapture.ru/file/651a7f98 4.http://www.screencapture.ru/file/8871a435 as you see the tab (Deals, Products, Events) start from middle of the screen as you scroll up it will start to stick at header
Comment: I don't understand what you're trying to do
Comment: Strange that SO would restrict new users from adding screenshots. I don't remember that. I understand now. Will think on it, but have you looked at [LayoutAnimation](https://facebook.github.io/react-native/docs/layoutanimation.html)?
Answer: It is very simple with ScrollView component. There is already something called "stickyHeaderIndices" which takes the index of child to make sticky.In following code, content inside renderComponent2 stays sticky when you scroll.
<ScrollView
      stickyHeaderIndices={[1]}
      showsVerticalScrollIndicator={false}
 >
  {this.renderComponent1()}
  {this.renderComponent2()}
  {this.renderComponent3()}
 </ScrollView>

Refer: https://facebook.github.io/react-native/docs/scrollview.html#stickyheaderindices
Comment: doesn't let the content below the sticky index scroll. once the sticky header is stuck in position, the only way you can scroll is down...
Comment: This was exactly what I was looking for.
Comment: Refer should be https://reactnative.dev/docs/scrollview#stickyheaderindices
Answer: Thank you for answering my first question. I found it how to do it now. So basically what I do is I cheat on F8App code where they fallback from F8Scrolling native module if it is not available to this:
if (!NativeModules.F8Scrolling) {
  var distance = EMPTY_CELL_HEIGHT - this.state.stickyHeaderHeight;
  var translateY = 0; this.state.anim.interpolate({
    inputRange: [0, distance],
    outputRange: [distance, 0],
    extrapolateRight: 'clamp',
  });
  transform = [{translateY}];
}

which gives the idea of animating my sticky view so here is i ended up
const stickySegmentControlX = this.state.scrollY.interpolate({
    inputRange: [0, STICKY_SCROLL_DISTANCE],
    outputRange: [INIT_STICKY_HEADER, HEADER_MIN_HEIGHT],
    extrapolate: 'clamp'
})

...

    return(
    ....
     <Animated.View ref="stickyHeader" style={[styles.stickyStuff, {top: stickySegmentControlX}]}>
       <Text>Go Stick</Text>
     </Animated.View>
    ....
   );

so basically what I've done is animating the top position of an {position: 'absolute'}'s view while as the value of output range is between bottom position to the height of my header (so it'll stop right below my header) and the input range is between 0 and the difference of the top position and the header height. Eventually, the animation will feel natural as you scroll the scrollview.
There you go a sticky header custom view. Here is the result:

If you feel my answer is confusing, its better you heading to janic duplessis Medium post:
React Native ScrollView animated header
Comment: I go through your medium blog, i did not see sticky header there. I need sticky header (one of multiple header in list), can you tell way?
Comment: @bondan-herumurti can you please eloborate whats the distance variable in inputRange
Comment: Would you mind providing the source code for this please?
Answer: This is very easy you just need to know the index component that you want it to sticky during scrolling inside a scrollview component. Here is an example:
 <ScrollView
      style={styles.screen}
      stickyHeaderIndices={[0]}
 >
     <View><Text>Hello1</Text></View>
     <View><Text>Hello2</Text></View>
     <View><Text>Hello3</Text></View>
 </ScrollView>

So when scrolling Hello1 text will sticky to the top of the ScrollView
Good Luck
Answer: In some cases, you'll actually want to just position your element outside of the ScrollView and use position: absolute to achieve a sticky effect. This is often more straightforward, if the element is consistently supposed to stick at the top or bottom, and doesn't involve any styling issues, which stickyHeaderIndices can sometimes cause.

<MyComponent style={{position: absolute;}}/> // will be sticky to top
<ScrollView>
    // scrolling components
</ScrollView>
<OtherComponent /> // functionally sticky to bottom; looks like content is scrolling behind it, even though the scrollview just stops before it.

Answer: For people trying to have a sticky spacer over the status bar, you can use an intermediate element as a placeholder.
      const insets = useSafeAreaInsets();

      return (<ScrollView stickyHeaderIndices={[1]}>
        <HeroImage />

        <View style={{ paddingTop: insets.top, backgroundColor: 'white' }} />

        <View style={{ backgroundColor: 'white' }}>
          .... Your components
        </View>
      </ScrollView>)

The second view is what pads the top.
Answer: This can prove useful
import android.os.Build
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.ScrollView
import androidx.annotation.RequiresApi
import kotlinx.coroutines.handleCoroutineException

@RequiresApi(Build.VERSION_CODES.M)
class StickyViewHistory(val stickyViewInflateListener: StickyViewInflateListener, val scrollView: ScrollView) {

    interface StickyViewInflateListener {
        fun inflate(view : View)
        fun getHeaderViews() : List<View>
        fun removeSticky()
        fun getStickyHolderView() : View
        fun getStickyLayout() : View
    }

    var currentVisibleHeader : ViewOverLapState? = null
    private var isStickyVisible = false

    init {
        scrollView.setOnScrollChangeListener { view: View, i: Int, newScrollY: Int, i2: Int, oldScrollY: Int ->
             val overlapStates = getOverlappStates()
             val numberOfHeadersAboveScroll = overlapStates.filter { it == ViewOverLapState.IS_ABOVE }.count()
             //If all of the headers are either visible or below the screen, we remove the sticky
             if(numberOfHeadersAboveScroll == 0){
                 if(isStickyVisible == true){
                   removeSticky()
                 }
             }
             else {
                 if(newScrollY < oldScrollY){
                     displayHeaderWhenScrollingDown(overlapStates)
                 }
                 else {
                     displayHeaderWhileScrollingUp(overlapStates)
                 }

             }

        }
    }

    /**
     * Assumes there is atleast one header view which has scrolled above screen
     */
    fun displayHeaderWhileScrollingUp(overlapStates : List<ViewOverLapState>){
        val mostRecentAboveHeader = getMostRecentAboveHeader(overlapStates)
        val highestVisibleHeader = getHighestVisibleHeader(overlapStates)

        //If there is a header on screen which is just about to overlap the current sticky layout we remove the Sticky altogether
        highestVisibleHeader?.let {
            if(isOverlappingCurrentStickyLayout(it.view)){
                removeSticky()
                return
            }
        }

        // If the most recent header that has scrolled above screen is the current sticky,
        // we dont do anything since its already being displayed as sticky
        if(currentVisibleHeader != null && currentVisibleHeader!!.view == mostRecentAboveHeader.view){
            //Do nothing
        }
        else {
            //We sticky the most recent header which has scrolled above screen
            setSticky(mostRecentAboveHeader)
        }

        isStickyVisible = true
    }

    fun displayHeaderWhenScrollingDown(overlapStates : List<ViewOverLapState>){
        currentVisibleHeader?.let { cvh ->
            val highestVisibleHeader = getHighestVisibleHeader(overlapStates)
            highestVisibleHeader?.let { hvh ->
                if(isOverlappingCurrentStickyLayout(hvh.view)){
                    removeSticky()
                    return
                }
            }
        }

        if(currentVisibleHeader == null){
            val mostRecentAboveHeader = getMostRecentAboveHeader(overlapStates)
            setSticky(mostRecentAboveHeader)
        }
    }

    /**
     * Checks if a view is overlapping with any part of the current sticky layout
     */
    fun isOverlappingCurrentStickyLayout(childView: View) : Boolean{
        val locationOfSticky = IntArray(2)
        stickyViewInflateListener.getStickyLayout().getLocationOnScreen(locationOfSticky)
        val childLocation = IntArray(2)
        childView.getLocationOnScreen(childLocation)
        val locationOfScrollView = IntArray(2)
        scrollView.getLocationOnScreen(locationOfScrollView)
        if(childLocation[1] <= locationOfSticky[1]+stickyViewInflateListener.getStickyLayout().height &&
                childLocation[1] >= locationOfScrollView[1]){
            return true
        }

        return false
    }

    /**
     * Get the headerview which most recently scrolled above screen
     */
    fun getMostRecentAboveHeader(overlapStates : List<ViewOverLapState>) : ViewOverLapState {
        val aboveViews = overlapStates.filter { it == ViewOverLapState.IS_ABOVE }
        var lowestAboveView : ViewOverLapState? = null
        var highestYCooridnatesoFar = Int.MIN_VALUE
        aboveViews.forEach {
            val locationOnScreen = IntArray(2)
            it.view.getLocationOnScreen(locationOnScreen)
            if(locationOnScreen[1] > highestYCooridnatesoFar){
                lowestAboveView = it
                highestYCooridnatesoFar = locationOnScreen[1]
            }
        }
        return lowestAboveView!!
    }

    /**
     * Highest here does not mean the highest [y] value but its position on the screen, so lower y means higher
     */
    fun getHighestVisibleHeader(overlapStates: List<ViewOverLapState>) : ViewOverLapState? {
        val insideViews = overlapStates.filter { it == ViewOverLapState.IS_INSIDE }
        var highestInsideView : ViewOverLapState? = null
        var lowestYCordinatesoFar = Int.MAX_VALUE
        insideViews.forEach {
            val locationOnScreen = IntArray(2)
            it.view.getLocationOnScreen(locationOnScreen)
            if(locationOnScreen[1] < lowestYCordinatesoFar){
                highestInsideView = it
                lowestYCordinatesoFar = locationOnScreen[1]
            }
        }
        return highestInsideView
    }

    fun getOverlappStates() : List<ViewOverLapState>{
        return stickyViewInflateListener.getHeaderViews()
            .map {
                getOverlapState(scrollView,it)
            }
    }

    /**
     * For all of the view headers, get their overlap state with the scroll view
     */
    fun getOverlapState(parentView : View, childView : View) : ViewOverLapState{
        val scrollViewLocation = IntArray(2)
        parentView.getLocationOnScreen(scrollViewLocation)

        val childLocation = IntArray(2)
        childView.getLocationOnScreen(childLocation)

        if(childLocation[1] < scrollViewLocation[1]){
            return ViewOverLapState.IS_ABOVE.apply { view = childView }
        }
        else if(childLocation[1] > (scrollViewLocation[1]+parentView.height)){
            return ViewOverLapState.IS_BELOW.apply { view =childView }
        }
        else {
            return ViewOverLapState.IS_INSIDE.apply { view = childView }
        }
    }

    fun setSticky(viewOverLapState: ViewOverLapState){
        stickyViewInflateListener.inflate(viewOverLapState.view)
        currentVisibleHeader = viewOverLapState
        isStickyVisible = true
    }

    fun removeSticky(){
        currentVisibleHeader = null
        stickyViewInflateListener.removeSticky()
        isStickyVisible = false
    }

    enum class ViewOverLapState(val text : String) {
        IS_INSIDE("inside"),IS_ABOVE("above"),IS_BELOW("below");
        lateinit var view : View
    }
}

Sticky Component inside scrollview


What is the difference between XML data and XML metadata?

Question: I'm rebuilding some XML feeds, so I am researching when to use elements and when to use attributes with XML.
Several sites have said "Data goes in elements, metadata in attributes."
So, what is the difference between the two?
Let's take an example from W3Schools:
<note date="12/11/2002">
  <to>Tove</to>
  <from>Jani</from>
  <heading>Reminder</heading>
  Don't forget me this weekend!
</note>

Should the date stay as an attribute of the note element? Or does it make more sense to go into its own element?
<date>12/11/2002</date>

Or, does it make sense for it to be separated into multiple elements?
<date>
  <day>12</day>
  <month>11</month>
  <year>2002</year>
</date>

Comment: This question is the best argument for JSON that I've ever heard.
Comment: Why is this? How would you structure the example using JSON? So far I have the following, and I'm not sure where I would put attributes, such as a note id: "notes": [{
  "to": "Tove",
  "from": "Jani",
  "heading": "Reminder",
  "body": "Don't forget me this weekend!"
}]
Comment: what's wrong with "notes": [{"id":27, "to":"Tove", ...}] ?
Comment: @Ned Nothing is wrong with that. But, it's worth noting that you lose distinction of attributes from elements, and you lose the ability to distinguish between attributes and elements when translating back to XML. For my purposes, I am forced to use XML, as we already have people relying on feeds, so JSON is a non-option.
Answer: Following the "Data goes in elements, metadata in attributes.", I would have made the Date a child element. You don't need to break it down into day, month, and year, because I think there's actually a way to specify in an XSD that an element must be a Date type. I think an example of "metadata" here would be a noteID field or maybe a noteType. Example:
<note id="NID0001234" type="reminder">
  <date>2002-11-12</date>
  <to>Tove</to>
  <from>Jani</from>
  <heading>Reminder</heading>
  Don't forget me this weekend!
</note>

UPDATE: As many others have pointed out, it can be rather subjective. I try to separate the two by how they will be used. Data will usually be presented to the user, metadata will control the presentation and may be used internally for other purposes. But there are always exceptions...
Comment: Honestly, I could make the case that "type" should have its own element, and I could *also* make the case that date/to/from/heading should all be attributes.  What constitutes "metadata" is very subjective and open to lots of interpretation.
Comment: "Data will usually be presented to the user, metadata will control the presentation and may be used internally for other purposes" -- I've arrived at the same conclusion after further research. Data (elements) is potentially displayed to the user; metadata (attributes) is necessary for information about the data and is not displayed to the user. Attribute examples: type="text"; version="1.0"; xmlns="..."; scheme="http://..."; rel="alternative".
Answer: The distinction between data and metadata is almost entirely subjective.  One man's data is another's metadata.  The "metadata in attributes" rule grew out of the markup world, where a rule of thumb was, if you remove all of the markup, and just leave the text, it should be a reasonable document.  This meant attributes should be discardable, and elements essential.  If you display XML in an uncomprehending browser, it will be treated this way.
But your XML (and most XML these days) likely won't be displayed to the user in an uncomprehending browser, so you can use better rules for how to design your XML.
For example, you can have multiple elements with the same name, but not multiple attributes.  And whitespace is ignored in attributes, but not in elements.
Comment: Good point about attributes being discardable. This would make dates non-discardable and therefore elements. It seems like attributes should not be displayed to the user and are more meta for and internal to elements.
Answer: There are differing views on the principles to use when deciding whether to use an attribute or an element for a piece of data.  For example, see this old article from IBM, which lays out a bunch of proposed principles, and then decorates the whole article with a giant caveat that says "there are lots of exceptions and these principles are not intended to be prescriptive" (essentially).
I think the main thing is to be internally consistent.  Be consistent within your own world, however large that is.  Your "world" could be a single schema - in which you should be consistent in your approach.  Every element within that schema should be philosophically consistent.  Or your world could be a set of related schema, or it could be all XML documents emitted by a particular company, or even all XML schema used by an industry or technology group.
Now, regarding the sample you offered:
<note date="12/11/2002">
  <to>Tove</to>
  <from>Jani</from>
  <heading>Reminder</heading>
  Don't forget me this weekend! Remember what happenned last time you forgot!!!
</note>

...this seems internally inconsistent because only one piece of data is factored out, and there doesn't seem to be a good reason to do so.
Better if all the items were attributes or all were elements.  One exception: the longish body element should probably always be an element.  This feels right to me:
<note date="12/11/2002" to="Tove" from="Jani" heading="Reminder">
  Don't forget me this weekend! Remember what happenned last time you forgot!!!
</note>

Putting the body into an attribute hurts readability, and that recommends putting the body into an element.
Keep in mind that whitespace can be collapsed in attribute values (source: that IBM article I cited); the hard rule that arises from that, is that if whitespace is meaningful, then you should use an element.
Now, if the heading in that fragment of xml is something like an email subject, I'd probably factor that out into an element as well, since subjects can be lengthy.
As for your question regarding the month/day/year of the date, yes, factor those things out if you need easy access to these individual data in tools that process the XML. It's easier to search for all notes from before 2009 with an xpath statement that does not have to do string parsing and then string-to-number conversion, if you see what I mean.  On the other hand if your use of the XML does not require you to do selects or searches on those individual data (month, day, year), then keep them consolidated into a human-readable form as in your original.

tl;dr:  There are few firm rules. As long as your use of elements and attributes is consistent, it will be easy for other developers and tools to understand and use.


Setting custom service class names for different WSDL versions with wsdl2java

Question: I'm developing a SOAP client based on Apache CXF. The Java classes for accessing the webservices are generated using the Maven plugin of wsdl2java. There are two WSDLs which define a service (InfoService) in two different versions:

info_service_v1.wsdl
info_service_v2.wsdl

Internally, both WSDLs use the identical naming, i.e. the generated webservice class is in each case named InfoService.
Is it possible to specify another name depending on the used WSDL?
Example:

info_service_v1.wsdl --> InfoServiceV1
info_service_v2.wsdl --> InfoServiceV2
Answer: In wsdl2java, you can set the option -sn service-name in order to change the service name for both versions.
Another option is to generate each version of code in a different package with option -p package-name
Comment: The option `-sn` only selects a specific service if there are multiple services in the WSDL. It does not support renaming the service interface. Guess I'll have to use specific packages.


Can't print out function result in Python

Question: I'm new to Python and after going through an example using a function to raise a number to a specific exponent, I tried to have it as the user for the numbers instead of just inputting them into the code.
Below is what I have:
def raise_to_power(base_num, pow_num):
    int(base_num)
    int(pow_num)
    result = 1
    for index in range(pow_num):
        result = result * base_num2

    return result

base_num = input("What number would you
like to exponentially raise?: ")

pow_num = input("To what power?: ")

print(raise_to_power(base_num, pow_num))`

When I try to run it though, I get the error listed below:
Traceback (most recent call last):
File "C:/Users/PycharmProjects/Exponent
Function.py", line 17, in <module>
print(raise_to_power(base_num, pow_num))
File "C:/Users/PycharmProjects/Exponent
Function.py", line 7, in raise_to_power
for index in range(pow_num):
TypeError: 'str' object cannot be
interpreted as an integer

Could someone explain why this might be happening?
Thank you,
Comment: convert string input to integer.
Comment: hint: google the error message before you post a question, this has been asked and answered 100s of times.
Comment: Possible duplicate of [How can I read inputs as numbers?](https://stackoverflow.com/questions/20449427/how-can-i-read-inputs-as-numbers)
Comment: `pow_num = int(pow_num)`
Answer: int(base_num) doesn't change the argument. To convert the base_num to string and save into the same variable use:
base_num = int(base_num)

This code sample shows some weaknesses of the design: why should base_num be of the string type initially. Try to call the variables with more meaningful names that would avoid this confusion.
Answer: your conversion of input string to integer is not correct.
Try the below code:
def raise_to_power(base_num, pow_num):
    result = 1
    for index in range(int(pow_num)):
        result = result * int(base_num)
    return result

Answer: You did two mistake.
1- int(base_num) is not good way to type casting.
2- In method you are passing base_num but in for loop you are using base_num2.
Here is the correct code.
def raise_to_power(base_num, pow_num):
    result=1
    for index in range(int(pow_num)):
        result = result * int(base_num)
    return result
base_num = input("What number would you")
pow_num = input("To what power?: ")
print(raise_to_power(base_num, pow_num))

Answer: def raise_to_power(base_num, power_num):

    result = 1

    for index in range(power_num):
        result = result * base_num

    return result

base_num = input("enter a base number you want : ")
power_num = input("enter the power of base number : ")

print(str(raise_to_power(int(base_num), int(power_num))))

Comment: Please consider an [edit] to your answer to explain how it solves the OPs problem and how it improves upon previous answers.
Comment: i am new to this community, thank you @DavidBuck for guide me


Is there a way to add a value from a non-primitive data type using a user-input?

Question: so I was just working on my project about Binary Search Tree, I tried to get the code about BST from a youtube tutorial and decided to try it with a java Scanner for user-input. So my question is, Is there a way to add  a value from a non-primitive data type using a user-input?
Main Class
BST class
I tried adding a nextInt() method inside the insert() method from the youtube tutorial so that the user can input the numbers that they like. But the ide said that the int cannot be converted into Node(which I think is a non-primitive data type).
Comment: Please don't post images of code, errors, logs, or other text; see [ask].
Answer: If your insert method in BinarySearchTree is modified so that it can take a number as input and generate a Node from it, then your code would work. Try like this:
public class Temp {
    public static void main(String[] args) {
        BinarySearchTree tree = new BinarySearchTree();
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter 1st number you want to insert");
        tree.insert(sc.nextInt());
        System.out.println("Enter 2nd number you want to insert");
        tree.insert(sc.nextInt());
        System.out.println("Enter 3rd number you want to insert");
        tree.insert(sc.nextInt());
    }
}

class Node {
    Node left;
    int val;
    Node right;
    Node(int val) {
        this.val = val;
    }
}

class BinarySearchTree {
    Node root;
    public void insert(int key) {
        Node node = new Node(key);
        if (root == null) {
            root = node;
            return;
        }
        Node prev = null;
        Node temp = root;
        while (temp != null) {
            if (temp.val > key) {
                prev = temp;
                temp = temp.left;
            } else if (temp.val < key) {
                prev = temp;
                temp = temp.right;
            }
        }
        if (prev.val > key)
            prev.left = node;
        else
            prev.right = node;
    }
}


How to set column wrap in bootstrap 4

Question: -> how to set column in responsive view this type of structure. i want one by one column i have attachment screenshot what i want in bootstrap 4 for ipad view. i want one column than second column.

@import url('https://fonts.googleapis.com/css?family=Merriweather:300,300i,400,400i,700,700i,900,900i|Rubik:300,300i,400,400i,500,500i,700,700i,900,900i');[![enter image description here][1]][1]
body {
  font-size: 15px;
  line-height: 28px;
  font-family: 'Rubik', sans-serif;
  font-weight: 400;
}
.video-thumb .video-icon {
  width: 35px;
  height: 35px;
  background-color: rgba(0,0,0,.9);
  position: absolute;
  bottom: 0;
  left: 0;
  z-index: 1;
}
.thumbnail-main, .video-content {
  margin-bottom: 20px;
}
img {
  max-width: 100%;
}
.inner-content span {
  display: block;
  margin-bottom: 10px;
  text-transform: uppercase;
  font-size: 10px;
  font-weight: 500;
  letter-spacing: 1px;
  line-height: 12px;
 }
.inner-content a.link {
  color: #208385;
}
h5 {
  font-size: 14px;
  line-height: 22px;
  font-weight: 700;
}
section {
  padding: 100px 0;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

        10 Oct 2018

          Breast

Lorem ipsum dolor sit amet, consecte sicng elit, sedt ut labore et dolore mag aliqua laboabor.

        10 Oct 2018

          Breast

Lorem ipsum dolor sit amet, consecte sicng elit, sedt ut labore et dolore mag aliqua laboabor.

Comment: did you try nested row/col? https://getbootstrap.com/docs/4.1/layout/grid/#nesting
Answer: Bootstrap columns can only have 12 columns in one row, in your example you have 4 div's with 4, 8, 4, 8 columns.
What you need to do is the following:
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

          10 Oct 2018

            Breast

Lorem ipsum dolor sit amet, consecte sicng elit, sedt ut labore et dolore mag aliqua laboabor.

          10 Oct 2018

            Breast

Lorem ipsum dolor sit amet, consecte sicng elit, sedt ut labore et dolore mag aliqua laboabor.

I surrounded the cards within a div, that contains a row with col-md-4 and col-lg-12. This will show a card at tablet and smaller, but if larger then a tablet it will show it in a row. Don't know if this is what you mean, i hope it helps :)!

How to set column wrap in bootstrap 4


Multivariate Box Muller

Question: i am reading "machine learning - a probabilistic perspective" by Kevin Murphy - who states the following in the chapter on monte carlo inference. i understand that cov[y] = $\Sigma$, but i do not see why this implies that $y=Lx+\mu$, and why this is equal to multivariate Gaussian sampling. Any hints much appreciated.
Answer: You basically reverse the logic. He plugged $y=Lx+\mu$ into covariance formula, and showed that if you do it then you'll get the given covariance matrix $\Sigma$. This means that sampling $x$ from independent standard normals will give you the required covariance matrix.
Comment: Thanks. And $\mu$ drops out because it is a linear shift and does not affect the covariance?
Comment: @Wouter, yes, just like in a univariate case: $cov[ax+b]=a^2 cov[x]$

Multivariate Box Muller


How would I find the factor of $x$ nearest to $\sqrt{x}$?

Question: I'm looking for a way to find the factor of a natural number, call it $x$, which is closest to $\sqrt{x}$.
If this question needs to be clarified, just let me know and I'll be happy to add more.
Comment: If there were an efficient way of locating factors of $x$ near $\sqrt{x}$, then there would be an efficient way of performing Fermat factorization of $x$ for any $x$ that is not of the form $pq$ with $p$ and $q$ primes, and $p\ll q$. So I doubt that there is an efficient way of doing it.
Comment: Find $\sqrt{x}$ and then find the factors of $x$ and compare them?
Comment: Factors of $x$ always come in pairs whose product is $x$, and of each such pair, a) one is $\le\sqrt{x}$ and the other is $\ge\sqrt{x}$, and b) the lesser one is closer to $\sqrt{x}$ than the greater one. So you can restrict the search to factors $\le\sqrt{x}$.
Answer: The strength of the RSA cryptosystem hinges on the same question - more specifically, given $n=pq$ where $p,q$ are primes of the same relative magnitude, is it easy to find $p,q$? If so, you should stop putting your money in the bank.
The best known algorithm for factoring $n$ (NFS) takes time $\exp(O((\log n)^{1/3} (\log\log n)^{2/3}))$. This is much better than "trial division" (dividing by all numbers less than $\sqrt{n}$), which takes time $O(\sqrt{n}) = O(2^{(\log n)/2})$.
Comment: For those wondering (like me before I googled it), NFS stands for number field sieve.  See http://en.wikipedia.org/wiki/Number_field_sieve


NAT : understanding about interconnection

Question: English version below
J'ai 2 routeurs A et B relié en série avec les ip respectives ( 10.0.0.1/30 10.0.0.2/30) sur le routeur A j'ai activé la fonction NAT avec un pool (220.127.116.11 - 126.96.36.199/28).
Lorsque je sors je prends donc un ip du pool par exemple 126.96.36.199.
Comment ça fonctionne sachant que ma nouvelle ip (184.108.40.206) ne se trouve pas sur le meme réseau que mon interface de destination (10.0.0.2)?

English:
I have 2 routers A and B, interconnected with a serial connection, with the ip's 10.0.0.1/30 for A and 10.0.0.2/30 for B. On router A NAT was activated with the pool 188.8.131.52 - 22.214.171.124/28.
When connection to this router, I get an ip from the pool, for example 22.214.171.124.
Knowing my new ip is 126.96.36.199, which is not on the same network as my destination interface (10.0.0.2), how can this work?
Comment: If you are asking a question or making a comment, please use the 'add comment' link below the relevant answer / Si vous posez une question ou faire un commentaire, s'il vous plaît utilisez le lien «Ajouter un commentaire" ci-dessous la réponse pertinente.
Answer: As you are connected to the 2nd router with this IP, your 1st router with NAT has DHCP enabled and it sends an IP to the 2nd router in 200.0.0 network too. Anyways, you should use private IPs in the RFC1918 ranges and not 200.0.0 subnet. As your 1st router is in 10.0.0 subnet, you could use it for everything.
In french:
Comme tu es connecté au 2eme routeur avec ton IP, le 1er routeur avec le NAT envoie un IP au 2eme dans la subnet 200.0.0 aussi. Il vaudrait beaucoup mieux utiliser les adresses RPF1918 pour les IP internes. 10.0.0 des routeurs conviendrai parfaitemment.
Comment: I already use private IP for routers "10.0.0.0 / 30" but my NAT pool is public IP "188.8.131.52 / 28" so my connection is under what networks? (10.0.0.0 or 220.127.116.11) the networks without NAT is working properly but when I enable NAT pool with the mentioned I don't know which networks take the upper hand over the other?
Comment: The NAT network (18.104.22.168) has the DHCP so it will be used to give IP to machines that don't have a fixed IP in the same subnet. The network used will be the public one but this will work only if you own the public IPs and nobody else is using them.


JDBC:is it possible to execute multi-database Querys in java?

Question: I want to execute an sql-query over 2 databases using java
but have some problems finding out how to do it without writing everything by myself
maybe someone has an idea how to do it.
example:

database1
table1(names): id,Name,zip,something

database2
table2(towns): id,townname,zip

SELECT *
FROM database1.names, database2.towns
WHERE database1.names.zip = database2.towns.zip

the example works in mysql when i use phpMyAdmin and the User has rights on both databases
edit:
The question is: How do i get Java to execute such a query since i can only connect to one database(?)
or: How can I connect to 2 Databases executing an Sql Query that uses tables from both databases using java.
the way i execute sql commands in java looks like:
Connection c = DriverManager.getConnection("jdbc:mysql://localhost/database?user=root&password=");
PreparedStatement pstmt = c.prepareStatement("Select * from something");
pstmt.executeQuery();

but i cant use that to get a Sql Query that uses tables from 2 databases?
Comment: What exactly is your question? You say it "works in MySQL", so are you using a different DBMS? If yes, which one. If no, then what is the question. And what do you mean with "*without writing everything by myself*"?
Comment: I added some more infos.
Answer: Assuming that these databases are not visible from the same datasource, you have to use a mediation software to query on them, such as http://www.unityjdbc.com/doc/multiple/multiplequery.php.
It's not a trivial problem, since your "SQL" will have to deal with each datasource availability and transaction.
Some DB vendors provide some sort of dblinks (e.g. http://docs.oracle.com/cd/B19306_01/server.102/b14200/statements_5005.htm) that help you a little to deal with heterogeneous DBs.
So it would be nice if you narrow your question to what DBMSs you are interested.
Comment: I write an "Sql-Client" that can execute sql-query to any Database that u can find an jdbc driver for so even i dont know which DBMSs that will be.. but i want to start smal and take 2 databases from mysql and make it work with them
Comment: then there are two paths here. If your tool is intended to be used in different dbs than mysql, you'll have to use some mediation tool. If you're going to stick with mysql, then you can research what mysql can do in this situation (probably you'll be able to access the same mysql instance databases with the same datasource if you give mysql user permissions to do so).
Comment: since i dont want to stick with mysql i will have to use something like unityjdbc. Now i only have to find something what is free for private use... or use the trail version..
Comment: unityjdbc guys are so confident in their product that they even give us some directions :-) http://www.unityjdbc.com/doc/multiple/multiplequery.php
Comment: if you find one, you can also answer this question :-) http://stackoverflow.com/questions/15895148/open-source-alternative-to-unityjdbc-com


How can I iterate over a dataset while only extracting properties specified in an array?

Question: I'm working on a project in Angular. I found this question, but it's not quite what I need.
I make an API call and get a JSON object back that has twenty plus properties. So a user might have the following properties and then some:
user.Name
user.Nickname
user.DOB
user.FavoriteColor
user.Address
...

I also have an array that looks like this.
$scope.ThePropertiesIWantToShow = [
                { propertyID: 1, displayValue: 'Name' },
                { propertyID: 3 displayValue: 'DOB' },
                { propertyID: 5 displayValue: 'Address' },

I have a table where I'd like to show this data, but I only want certain properties displayed (the ones in the array above). If I wanted to manually show everything in ThePropertiesIWantToShow, I might do something like this:

    {{user.Name}}
    {{user.DOB}{
    {{user.Address}{

However, both the JSON data and ThePropertiesIWantToShow array are much larger. I'd like to know how to use ng-repeat to do something like the following pseudocode, so that I don't have to type out each property manually. Plus, if I needed to make changes, I could just change the array, and it would be reflected in multiple places:
for each user in users
     for each property in ThePropertiesIWantToShow
          user.property

Per the previously linked question, I know that I can do something like this to get all properties:

    {{value}}

but this gives me all the data from the API call, and I'd only like to display the properties provided in the array for each user.
Comment: You have oversimplified the data sample. This is a guessing game on our end without a better representation of what you are actually working with
Comment: Ok, I'll edit the question to make it more complete.
Comment: Done. Let me know if there's anything else I can do to improve the question.
Answer: What you probably want is something like:
$scope.fields =['Name','DOB','Address'];

Then in view you repeat the fields within each row:

    {{user[field]}}

Comment: That's almost exactly what I'm looking for! But is there a way to do that while still maintaining the format of `ThePropertiesIWantToShow`? For example, is there something like this: `{{user[property.displayValue]}}`?
Comment: Thanks! I figured it would be something simple; I was just struggling with the syntax.
Answer: If I understand well, you are trying to do this:
Declare this function in your Angular controller:
$scope.getUserProperty = function(user, property) {
    return user[property];
}

And then use it for getting user properties

      {{getUserProperty(user, p.displayValue)}}

Working demo on JSFiddle


JS: Adicionar num icone um evento para trocar o background e aparecer um conteúdo

Question: Ola.
Estou tentando criar uma aplicação, a ideia é exatamente a que se encontra neste theme http://klbtheme.com/kryptix/ com o título de How ICOX Works.
A cor do meu ícone é cinza e o background branco. Quero que ao clicar nele, ele mude para a cor branca e background roxo. O meu ícone é tipo font, então quanto a isso ok. Mas além disso, ao clicar no ícone 1, quero que o conteúdo apareça, e quando clicar no ícone 2. quero que troque pelo conteúdo do 2. Isso é fácil usando css e aplicando/removendo classes, então até ai ok, mas o problema está no javascript.
As partes do html são:

e

Financeiro

Texto para Financeiro.

Mensalidade

Textos para Mensalidade.

Criei o código abaixo, onde consigo fazer parte do que desejo que é alterar as cores.
var TodosIcones = document.querySelectorAll('.icon-visual');
for (var i = 0; i < TodosIcones.length; i++) {
  TodosIcones[i].onclick = onTabClick;
}
function onTabClick () {
  var Icon = this;
  var Icones = Icon.parentNode.querySelectorAll('.icon-visual');
  for (var i = 0; i < Icones.length; i++) {
    if (Icon == Icones[i]) {
        Icones[i].classList.add('icone-selecionado');
    } else {
        Icones[i].classList.remove('icone-selecionado');
    }
  }
}

A classe conteudo possui display none para não aparecer, então agora nenhuma aparece. Mas quero que ao ser clicado o primeiro icone, esta classe do primeiro conteúdo desapareça, fazendo com que o conteúdo esteja visível na tela, e quando clicar no segundo, adicione a classe de novo e remova a classe do segundo.
Alguém consegue me ajudar?
Answer: Olá. Você pode usar uma classe .active para indicar qual ícone e qual conteúdo estão ativos. Depois basta remover/adicionar essa classe quando houver um click.
Além disso, também pode usar a propriedade data-target para indicar qual ícone está relacionado a qual conteúdo, dessa forma, quando houver o click em um ícone, você saberá exatamente qual conteúdo deve ser mostrado. Para isso, basta atribuir o id do conteúdo ao data-target do ícone no html. Por exemplo:

E na div do conteúdo você coloca o id:

Financeiro

Texto para Financeiro.

Pelo javascript, você consegue acessar o valor do data-target usando object.dataset.target. Dessa forma, o seu código javascript ficaria assim:
var icons = document.querySelectorAll('.icon-visual');
var contents = document.querySelectorAll('.conteudo');
for (var i = 0; i < icons.length; i++) {
  icons[i].onclick = iconClick;
}

function iconClick() {
  var icon = this;
  for (var i = 0; i < icons.length; i++) {
     icons[i].classList.remove('active');
  }
  for (var i = 0; i < contents.length; i++) {
     contents[i].classList.remove('active');
  }

  var idContent = icon.dataset.target;
  var content = document.getElementById(idContent);
  content.classList.add('active');
  icon.classList.add('active');
}

Fiz um exemplo para você ver, segue o link: https://jsfiddle.net/1br4hvck/43/.
Espero ter ajudado.
Comment: Muito obrigada, isso resolveu o meu problema.
Answer: var TodosIcones = document.querySelectorAll('.icon-visual');
var content = document.querySelectorAll(".financeiro, .mensalidade");

    for (var i = 0; i < TodosIcones.length; i++) {
        TodosIcones[i].onclick = onTabClick;
    }

    function onTabClick() {
        var Icon = this;
        var Icones = Icon.parentNode.querySelectorAll('.icon-visual');
        for (var i = 0; i < Icones.length; i++) {
            if (Icon == Icones[i]) {
                Icones[i].classList.add('icone-selecionado');
                content[i].classList.remove('conteudo');
            } else {
                Icones[i].classList.remove('icone-selecionado');
                content[i].classList.add('conteudo');
            }
        }
    };

Armazenei os blocos de conteúdo dentro da variável content e depois dentro do for da function onTabClick removi a class conteudo do bloco referente ao ícone clicado, depois quando clicar em outro ícone ele adiciona a class conteudo novamente e remove do conteúdo do ícone clicado.


Dividir tabela em 4 colunas com PHP

Question: Tenho o código abaixo que imprime de 28 a 31 linhas (de acordo com o mês) e queria ao invez de imprimir 1 abaixo do outro fazer 4 colunas de 8 mais ou menos para o layout ficar melhor.
Meu código

    <?php
    $total_dias = date("t", mktime(0,0,0,date('m'),'01',date('Y')));

    for($dia = 1; $dia<= $total_dias; $dia++){

        if($dia <= 9){
            $dia = '0'.$dia;
        }

        echo '
';
        echo ''.$dia.'/'.date('m').' - '.$this->agendamento->HorariosDisponiveisPorData($profissional->id, date('Y').'-'.date('m').'-'.$dia).'	';
        echo '
';

    }
    ?>

Como poderia dividir essas 31 saidas em 4 colunas ?
Answer:  <?php
    $total_dias = date("t", mktime(0,0,0,date('m'),'01',date('Y')));
    $l = 4; // quantidade de colunas
    $c = 1; // contador auxiliar
    for($dia = 1; $dia<= $total_dias; $dia++){

        if($dia <= 9){
            $dia = '0'.$dia;
        }
        if ($c == 1) {
            echo '
';
        }
        echo ''.$dia.'/'.date('m').' - '.$this->agendamento->HorariosDisponiveisPorData($profissional->id, date('Y').'-'.date('m').'-'.$dia).'	';

        // verifica se chegou ao limite de colunas ou se está no último loop.            if ($c == 4 || ($dia + 1) > $total_dias) {
            echo '
';
            $c = 1;
        } else {
            $c++;
        }

    }
    ?>

Dividir tabela em 4 colunas com PHP


Flipping / Sliding Effect with Winforms

Question: I am trying to make an Flipping / Sliding Effect with Winforms.
To be exact: a effect where the first Form slides/ is pushed out of the screen and the second one slides in.
After a lot of research I came to the conclusion that a Flipping effect is not working in Winforms.
I tried the following things for the sliding effect:

Embedding winforms in Wpf Application - using Windowsformshost
--> Windowsformshost doesn't support animation.
Change Location of the Forms
a. with an Timer
b. with loop
c. separate threads
-->the form is flickering & does not look professional
Screen capture - i.e. screenshots of the forms
--> same Problem: flickering
AnimateWindow Function (API)
--> the API doesn't support threading
--> sliding in AND out of both forms at the same time is not possible.
--> same Problem: flickering

Additional Infos:
I use C# ,Visual Studio 2010 (Dot net Framework 4.0)
3rd party Controls - Telerik
On my Form are Custom Controls (extended Telerik controls)
I have set Doubblebuffered to True for the controls.
It would be really helpful if somebody could help/suggest to overcome this issue (winforms Flipping/Sliding Effect).
Regards, WickedSquall
Comment: Thank you for the replies.

the Requirements have changes a little:

The sliding has to be in the Form.

This is relative easy, by changing the Control.left value.

Alternative to that I try to insert a Custom WPF Control in the Winform witch moves 2 Screenshots with an Animation.

I'll update you
Answer: The best option would be
5. Switch to WPF. It runs on DirectX and you need that.
But I guess that's not an option. The most workable seems your option 3 , moving bitmaps. The flickering should be solvable with double-buffering etc.
Answer: Here our final solution:
We decided to bring this issue to a third party who has more experience with graphics.
The best solution with our knowledge moving Pictureboxs with Screenshots and an Timer.
Regards

Flipping / Sliding Effect with Winforms


Como copia o valor um DIV para outro DIV com Javascript?

Question: O meu problema é o seguinte:
Tenho uma página em html, e nessa página, tem 2 divs. no segundo div, eu tenho um javascript que armazena um valor em uma determinada variável.
O que eu quero, é exibir o valor dessa variável no primeiro div.
Vocês sabem como posso fazer isso?
Comment: Tá mal explicado mas pelo que eu entendi é como pegar o conteúdo do segundo div para primeiro div, se for, é esse código seguinte `$("#div1").html($("#div2").html())`, avisando que é Jquery
Comment: Podes colocar o código que tens para percebermos melhor o problema?
Comment: "**div, eu tenho um javascript que armazena um valor em uma determinada variável.**" - isso está muito mal explicado. `div` não pode conter javascript.
Answer: Para criar em JavaScript Puro é só seguir este exemplo:

// Elemento com o Texto
var elemento = document.getElementById('teste').innerHTML;
// Escrevendo em outro Elemento
var texto = document.getElementById('texto');
texto.innerHTML = "Texto Copiado: " + elemento;

  Exemplo

Mas se for em jQuery é só seguir o exemplo do @Adriano-Resende:

// Elemento com o Texto
var elemento = $('#teste').html();
// Escrevendo em outro Elemento
var texto = $('#texto');
texto.html('Texto Copiado: ' + elemento);

  Texto


Conversão de nome de arquivos de epoch timestamp para data

Question: Caros;
Tenho uma lista de arquivos (140 mil) com data no formato Unix epoch timestamp no nome do arquivo. Preciso converter cada arquivo para corresponder a data real dele, alterando seu nome. Exemplo: 1475279740.15044_xxx.xxx.stats, onde o epoch timestamp é 1475279740, convertendo dá 2016-09-30 (2016-09-30_xxx.xxx.stats).
Tenho a lista de arquivos com seus nomes em timestamp e outro arquivo com a lista de nomes já convertida, ambas em txt. Porém, preciso alterar/mover o arquivo que contém o timestamp para os arquivos convertidos.
Imagino ter dois for onde um abre a lista de arquivos timestamp e outro for que abre os arquivos convertidos e após seria só alterar/mover com um simples comando mv.
Para testar, criei estes dois laços for, porém apenas a segunda variável é alterada em sequência, a primeira fica estática.
Segue o código de exemplo:
 for x in $(cat timestamp.txt)
     do
         for y in $(cat timestamp-conv.txt)
       do

           echo $x convertido para $y

    done
 done

Saída esperada do código:
  1474566212 convertido para 2016-09-24
  1474566212 convertido para 2016-09-24
  1474566212 convertido para 2016-09-24
  1474566212 convertido para 2016-09-24
  1474566212 convertido para 2016-09-24
  1474566212 convertido para 2016-09-24
  1474566212 convertido para 2016-09-24
  1474566212 convertido para 2016-09-24
  1474566212 convertido para 2016-09-24
  1474566212 convertido para 2016-09-24
  1474566212 convertido para 2016-09-24
  1474566212 convertido para 2016-09-25
  1474566212 convertido para 2016-09-25

As duas listas estão idênticas, linha por linha entre as duas batem o timestamp com o outro já convertido.
Já tentei de varias formas, sem sucesso!
Podem me ajudar?
Comment: E a hora, tu não vai precisar? É possível que dois arquivos tenham a mesma data, daí o que os diferenciaria seria a hora.
Comment: Não é necessário a hora, só a data mesmo.
Comment: A lista com o nome dos arquivos está em `timestemp.txt`? Um por linha? Tu quer copiar o arquivo `1475279740.15044_xxx.xxx.stats` para o arquivo `2016-09-30_xxx.xxx.stats`, por exemplo, e imprimir um relatório no final de todos os arquivos convertidos, é isso?
Comment: Tenho um diretorio com 140 mil arquivos de logs.Cada arquivo de Log está com timestamp do dia que foi salvo. Então destes 140 mil arquivos, tenho arquivo de setembro a outrubro. Como o script que faz isso diariamente deu pau, só vimos depois de quase dois meses, teremos que filtrar cada arquivo por sua data atual em timestamp, convertendo de timestamp para a data real e salvar em um diretorio com esta data. Então, preciso saber os dias de todos arquivos para fazer esta conversao: de 1475279740.15044_xxx.xxx.stats para 2016-09-30_xxx.xxx.stats. Não sei se ficou claro, caso não desculpe !!
Answer: Acredito que este script possa fazer o trabalho:
#!/bin/bash

exec 3< timestamp.txt

while read arq <&3; do
    epoch=$(echo $arq | awk '{ print $1 }' FS="_")
    filenameend=$(echo $arq | awk '{ print $2 }' FS="_")
    date=$(date --date="@$epoch" +%Y-%m-%d)
    mv ${arq} ${date}_${filenameend} && echo ${arq} convertido para ${date}_${filenameend}
done

exec 3<&-

Comment: Você disse que não precisa diferenciar pela hora, então vais perder arquivos se tiveres mais de um no mesmo dia: o último da lista sobrescreverá o(s) anterior(es). Cuidado com isso!
Comment: Olá Thiago, na verdade, quando eu ter a certeza que estiver funcionando, eu irei adicionar no final de cada arquivo convertido uma string para diferenciar, por isso eu estava usando o echo. O que me interessa é o conteúdo de cada arquivo, e não o nome dele. Me tira uma duvida, vc setou em seu While o arquivo timestemp.txt. Onde entra o outro arquivo convertido? Ou seu codigo irá converter na hora os arquivos sem a necessidade de um arquivo secundário? Grato pelo seu interesse em ajudar.
Comment: Então, ele já move o arquivo original para o novo arquivo, com a data formatada como tu querias. Não existe a necessidade de criar mais um arquivo para controlar a conversão de nomes.
Comment: Grande Thiago, irei testar seu código. Grande abraço!
Comment: Ok! Depois dê o feedback aqui com o upvote ou alguma dúvida que tenhas para ajudar os outros que tiverem o mesmo problema.
Comment: Opa TIago, deu certo, testei e funcionou do modo esperado. Agradeço! Aproveitando, tenho algumas duvidas em relação ao seu codigo para meu aprendizado. Este serve como delimitador (FS="_") ? Para que serve este comando <&3 ? .
Comment: O `FS="_"` serve como a definição do delimitador para o comando `awk`, conforme tu supôs! Então quando direcionamos a saída do comando `echo $arq` pro `awk`, o mesmo separa em strings pelo separador definido. Logo, passando o comando `{ print $2}` na sequencia estamos nos referindo à segunda string, ou a string logo após o primeiro "_" (separador).
Comment: O comando `exec 3< timestamp.txt` vai criar um novo _file descriptor_ e vincular o arquivo timestamp.txt à ele. Isso tem a ver com teu requisito, que é de processar um grande número de linhas do arquivo `timestamp.txt`. Caso não fizesse assim, carregaríamos o arquivo todo em memória e pode haver um prejuízo de desempenho do teu script. Assim, usando um file descriptor, as linhas do arquivo podem ser lidas uma a uma e processadas da mesma forma, isso é o que acontece no comando `read arq <&3`. Existem outras soluções, essa é só uma delas. As outras soluções envolvem usar o comando `xargs`.
Comment: Alguns comandos Linux também podem não aceitar uma lista de argumentos muito grande e pode ser necessária uma solução deste tipo, usando `xargs` ou _file descriptors_. Espero ter esclarecido tuas dúvidas!
Comment: Pohhh é isso mesmo Thiago, as vezes me deparo com List too long e tenho que fazer algumas gambiarras para funcionar, porem nunca soube de uma resposta/solução para este caso. Esse (FS="_"), é a mesma coisa de usar o cut com delimitador " _ " ? . Com sua explicação, já ficou mais claro. Obrigado e grande abraço.
Comment: Sim, o FS é o delimitador  ;-)


strtok on a local variable in C

Question: I encountered an interesting problem in C, when calling an external method from main that tries to strtok a local (main) string that is passed to it by reference. If I strtok the string in main, it works as expected, but if I call the external method, it fails with segfault. Valgrind's output on accessing the first element of the strtok result:
Address 0xfffffffffeffebc0 is not stack'd, malloc'd or (recently) free'd

--- test.c ---
extern void tt(char* x);

main(argc, argv)
    int argc;
    char *argv[];
{
    char line[5000];
    // if I uncomment the following two lines and comment above it works as expected
    // char * line;
    // line = malloc(5000);
    strcpy(line, "hello world");
    printf("%d\n", sizeof(line));
    tt(line);
}

--- test2.c ---
void tt(char* l) {
    char* x = strtok(l, " \t");
    printf("%p\n", x);
    printf("%c\n", x[0]);
}

compile by
gcc -c test2.c -o test2.o
gcc test.c test2.o

IMHO it should print out something like:
./a.out
0x.....
h

But instead I get segfault on printing the "h".
Can somebody please explain this behavior?
Thanks.
Comment: Not a reason for a downvote, but you should absolutely stop using K&R style function definitions.
Comment: runs on http://codepad.org/7KUrMWdl
Comment: @MOHAMED, Can you explain why that should matter? Isn't that just a matter of linkage
Comment: There's also a second bug in the code. Your line `printf("%d\n", sizeof(line));` should read `printf("%zu\n", sizeof(line));` or `printf("%d\n", (int)sizeof(line));`. The `sizeof` operator returns a `size_t` which in 64 bit mode is defined as `unsigned long` not `unsigned int` as in 32 bit mode. So if you want to be portable you have to use the right format specifier or cast the return value.
Comment: @ticcky, why don't you step through the debugger and figure out which line it crashes and why
Comment: @user814628 looks that you put the tt function and main in the same file. but the question was the both functions are in separated files
Comment: It run also on separate files. Which compiler do you use, on which OS and with which compile flags ?
Comment: @georgesl when pointers and integers have the same size then it may work, when they aren't it might still work if the pointer is exactly representable in the range of int, but in this case the lower 32 bits of the pointer are sign extended to the full 64 bits of a pointer creating an invalid address
Comment: Just so that you know. Your program printed the right value of the sizeof because you compiled it on a little endian machine (x86, ARM), on a big endian machine it would have probably printed 0 (SPARC, POWER, MIPS).
Comment: guys, thanks for the insightful comments. this (as you correctly pointed out) filthy piece of code is a stripped-off version of someone else's code that I had to make work. I am sorry that it distracted the attention from the real problem. it is solved by adding #include  as @DanielFischer suggested.
Answer: In the file
--- test2.c ---
void tt(char* l) {
    char* x = strtok(l, " \t");
    printf("%p\n", x);
    printf("%c\n", x[0]);
}

you haven't included string.h, so the compiler assumes a return type of int for strtok. Thus the line
char *x = strtok(l, " \t");

doesn't assign the proper pointer to x (As the valgrind output shows, your pointers are 64 bits at least, but int is very probably only 32 bits). Then dereferencing the corrupted pointer causes a segmentation fault.
Comment: This is one of the reasons to compile with warnings on and pay attention to them. When I don't include `string.h` gcc gives a warning about initialization of pointer from integer without a cast and when I add `-Wall` I get a warning for implicit declaration of `strtok`. If your compiler isn't giving these diagnostics get a better one :)
Comment: wow that's incredible of you to find the solution, given the few amount of informations written by the OP !

strtok on a local variable in C


Finite Subsets of the Natural Numbers

Question: What are the 'finite' subsets of the natural numbers? Where do we draw the line between infinite and finite subsets?
Comment: A set is infinite if there is injective function from $\mathbb N$ into that set.
Comment: See [Dedekind-infinite set](https://en.wikipedia.org/wiki/Dedekind-infinite_set) : "a set $A$ is *Dedekind-infinite* (see [Richard Dedekind](https://en.wikipedia.org/wiki/Richard_Dedekind)) if some proper subset $B$ of $A$ is equinumerous to $A$. Explicitly, this means that there is a bijective function from $A$ onto some proper subset $B$ of $A$. A set is *Dedekind-finite* if it is **not** Dedekind-infinite."
Comment: A set $A$ is finite iff there exists an integer $K$ and a bijection $f: A \rightarrow \{0,\ldots,K-1\}$ (the latter set is empty for $K=0$ of course).
Answer: Generally, a set is finite if there is a natural number (possibly zero) that says how many elements there are in the set.
This assumes that you know how to count and what a natural number is. You're supposed to have learned that in primary school, and higher mathematics generally assumes that you already believe what you learned in primary school about counting and natural numbers. (This stands in stark contrast to several more advanced areas of mathematics where you're supposed to aggressively doubt your primary-school knowledge once you reach the university level).
There are various ways to attempt more technical definitions of counting and numbers, for use in contexts where having technical definitions is inescapably necessary. A selection of these have already been given as comments to the question. But appreciating these definitions still depends on you having an intuitive understanding of what it is you're trying to define in the first place.
(In the particular case of a set of natural numbers, we can sidestep this and say that the set is finite if and only if it is bounded, that is, if there exists some natural number that is larger than all elements in the set).

Finite Subsets of the Natural Numbers


Finding the $k^{th}$ root modulo m

Question: We know that method of finding $k^{th}$ root modulo $m$, i.e. if $$x^k\equiv b\pmod m,\tag {$\clubsuit$}$$ with $\gcd (b,m)=1$, and $\gcd(k,\varphi(m))=1$, then $x\equiv b^u\pmod m$ is a solution to $(\clubsuit)$, where $ku-v\varphi(m)=1$.  Because
$$\begin{array}
{}x^k &\equiv \left(b^u\right)^k\pmod m\\
&\equiv b^{uk}\pmod m\\
&\equiv b^{1+v\varphi (m)}\pmod m\\
&\equiv b\cdot b^{v\varphi(m)}\pmod m\\
&\equiv b\cdot \left(b^{\varphi (m)}\right)^v\pmod m\\
&\equiv b\pmod m
\end{array}$$
Thus $x\equiv b^u\pmod m$ is a solution to $(\clubsuit)$.
Here we use $\gcd(b,m)=1$, since we used Euler's theorem that $b^{\varphi(m)}\equiv1\pmod m$.

But I am asked to prove that if $m$ is the product of distinct primes, then $x\equiv b^u \pmod m$ is always a solution, even if $\gcd (b,m)\gt1.$

What I did, is say $m=p_1p_2$. Then $\varphi(m)=(p_1-1)(p_2-1)$
$$\begin{array}
{}b^{uk}&\equiv b\cdot b^{\varphi (m)}\pmod m\\
&\equiv b\cdot b^{(p_1-1)(p_2-1)}\pmod m
\end{array}$$
Now, we just have to compute $b^{(p_1-1)(p_2-1)}\pmod {p_i}$. Here I got stuck, because I really can't use the little theorem for every $p_i$'s, since some $p_i$ can exist in $b$.
Can someone help me?
Answer: In your case of $m=p_1p_2$. If $\gcd(b,m)>1$, then $\gcd(b,m) \in \{p_1,p_2,m\}$. Without the loss of generality, say $\gcd(b,m)=p_1$. Then
\begin{align*}
b^{ku} & \equiv b \, . b^{(p_1-1)(p_2-1)}\\
& \equiv 0 \pmod{p_1} & (\because \gcd(b,m)=\gcd(b,p_1)=p_1)\\
&  \equiv b \pmod{p_1}
\end{align*}
Likewise
\begin{align*}
b^{ku} & \equiv b \, . b^{(p_1-1)(p_2-1)}\\
& \equiv b .1 \pmod{p_2} & (\because \gcd(b,p_2)=1 \text{ so Fermat's little theorem works})\\
&  \equiv b \pmod{p_2}
\end{align*}
Thus
$$b^{ku} \equiv b \pmod{p_1p_2}$$
Comment: This works *much* more generally - see my answer.
Comment: @BillDubuque my intent was not to say this idea works only for two primes. This was just for demo purposes and to answer OP's question.
Comment: The point of my comment was to inform readers of the relationship between our answers (which may not be immediately obvious), i.e  that the above generalizes widely.
Comment: @BillDubuque That makes perfect sense.
Answer: $b^{\large ku}\!\equiv b\pmod{\!pq}\,$ is case $\,i,j,k=1\,$ of this generalization of the Fermat Euler $\color{blue}{\rm (E)}$ theorem.
${\bf Theorem}\,\ \   n^{\large k+\phi}\equiv n^{\large k}\pmod{\!p^i q^j}\ \ $ if $\,p\ne q\,$ are prime, $ \ \color{#0a0}{\phi(p^i),\phi(q^j)\mid \phi},\, $  $\, i,j \le k\ \ \ $
${\bf Proof}\,\ \ p\nmid n\,\Rightarrow\, {\rm mod\ }p^{\large i}\!:\  n^{\large  \phi}\!\equiv 1\,\Rightarrow\, n^{\large k + \phi}\equiv n^{\large k},\ $ by $\,\  n^{\large \color{#0a0}\phi} = (n^{\color{#0a0}{\large \phi(p^{\Large i})}})^{\large \color{#0a0}\ell}\overset{\color{blue}{\rm (E)}}\equiv 1^{\large \ell}\equiv 1$
$\qquad\quad\ \ \color{#c00}{p\mid n}\,\Rightarrow\, {\rm mod\ }p^{\large i}\!:\  n^{\large k}\!\equiv 0\,\equiv\, n^{\large k + \phi}\ $ by $\ n^{\large k} = n^{\large k-i} \color{#c00}n^{\large i} = n^{\large k-i} (\color{#c00}{mp})^{\large i}$ and $\,k\ge i$
So $\ p^{\large i}\mid n^{\large k+\phi}\!-n^{\large k}.\,$ By symmetry $\,q^{\large j}$ divides it too, thus so too does their lcm $ = p^{\large i} q^{\large j}\,\ $ QED
Remark $\ $ The above  proof immediately extends to an arbitrary number of primes, see this answer.  See also Carmichael's Lambda function, a generalization of Euler's phi function.

Finding the $k^{th}$ root modulo m


Frequency ratio test with correlation structures

Question: I have some data about two machines, each machine has 10-15 operation logs, and inside the log are the time-stamped status checks that takes on the value of 1 if there is a warning and 0 otherwise.
The question is to decide which machine is better? (in terms of less warnings in the log)
I am thinking of the two approaches to test the difference:

Assuming that each status check is independent (both within- and between-operations), that way the problem becomes a typical frequency count test and I can apply proc freq in SAS.
Because the records comes from different operation logs, I wonder if I should factor in the operation into the test? In other words, is there any frequency test that considers the possible correlation of status within each operation?
Answer: In that case I think that maybe you can use the logs as a covariate and fit a regression model for counts.  Maybe Poisson regression or Negative binomial regression.


Recuperar parâmetro preenchido na ActionResult

Question: Estou com um problema que já tentei de várias formas resolver e nada. Ao carregar a pagina a pagina é preenchida numa table uma lista, mas quando é submetida o modelo está nulo, mas se consultar a propriedade Request.Form.ToString() consta os valores.
https://dotnetfiddle.net/wGJbYK
namespace RequesIEnumerable
{
    public class CategoryViewModel
    {
        public int CategoryId { get; set; }
        public string CategoryName { get; set; }
    }
}

.
using System.Collections.Generic;
using System.Web.Mvc;

namespace RequesIEnumerable
{
    public class CategoryController : Controller
    {
        // GET: Category
        public ActionResult Index()
        {
            List<CategoryViewModel> categories = new List<CategoryViewModel>();
            categories.Add(new CategoryViewModel { CategoryId = 1, CategoryName = "CategoryOne" });
            categories.Add(new CategoryViewModel { CategoryId = 2, CategoryName = "CategoryTwo" });
            categories.Add(new CategoryViewModel { CategoryId = 3, CategoryName = "CategoryThree" });
            categories.Add(new CategoryViewModel { CategoryId = 4, CategoryName = "CategoryFour" });

            IEnumerable<CategoryViewModel> ieCategories = categories;

            return View(ieCategories);
        }
        [HttpPost]
        public ActionResult Index(IEnumerable<CategoryViewModel> model)
        {
            var count =  Request.Form.ToString().Split('&').Length;

            if (model == null)
                System.Console.WriteLine("model is null");

            return RedirectToAction("Index");
        }

    }
}

.
@model IEnumerable<RequesIEnumerable.CategoryViewModel>

<!DOCTYPE html>

    <meta name="viewport" content="width=device-width" />
    <title>Index</title>

    @using (Html.BeginForm())
    {

                    @Html.DisplayNameFor(model => model.CategoryId)

                    @Html.DisplayNameFor(model => model.CategoryName)

            @foreach (var item in Model)
            {

                        @Html.EditorFor(model => item.CategoryId)

                        @Html.EditorFor(model => item.CategoryName)

            }

        <input type="submit" name="submit" value="Submit" />
    }

Comment: Veja https://pt.stackoverflow.com/a/102945/5846
Comment: Obrigado, mas com uma alteração simples na view o problema foi resolvido.
Answer: Realizando uma modificação na view, consegui recuperar o modelo via parâmetro.
@model IEnumerable<CategoryViewModel>
<!DOCTYPE html>

    <meta name="viewport" content="width=device-width" />
    <title>Index</title>

    @using (Html.BeginForm())
    {

                    @Html.DisplayNameFor(model => model.CategoryId)

                    @Html.DisplayNameFor(model => model.CategoryName)

            @for (int i = 0; i < Model.Count(); i++)
            {

                        @Html.EditorFor(it => it.ToList()[i].CategoryId)

                        @Html.EditorFor(it => it.ToList()[i].CategoryName)

            }

        <input type="submit" name="submit" value="Submit" />
    }


Exclude a group that contains localhost

Question: Given the following inventory :
[group1]
myserver.domain.com   ansible_ssh_user=myUser

[group2]
localhost             ansible_connection=local

How can I only execute my playbook on the group1 host(s) ?
When I use --limit=group1, it also includes localhost
I tried --limit='!group2', it does not work either.
Any idea?
Thx in advance
EDIT:
I am using ansible 1.9.2.
Answer: I can't test it on your ansible version. I suggest you a workaround changing the target host definition in your playbook as follows:
So you'll have something like this
- name: Test limit
  hosts: "{{ hosts_nodes | default('all')}}"
  tasks:
      - file: path=/tmp/mydir state=directory

and running the playbook adding the additional environment variable hosts_nodes
ansible-playbook -i test.inventory test.yml -e hosts_nodes=group1

Comment: Thx again. This seems to be a good workaround but I would say ```default('none')``` instead of ```'all'```
Comment: It was just an example. Of course choose the most suitable default value to your purpose
Comment: Even if it was not exactly what I expected, I'd check this answer. I was hoping to have the reason why localhost is systematically included, even if I exclude its group ... I guess it is how ansible works... Thx for your time.
Answer: What ansible version are you using? It works correclty in version 184.108.40.206.
This is my test.inventory file
[group1]
myserver.domain.com   ansible_ssh_user=myUser

[group2]
localhost             ansible_connection=local

This is my test playbook test.yml
- name: Test limit
  hosts: all
  tasks:
      - file: path=/tmp/mydir state=directory

I get what expected both running
ansible-playbook -i test.inventory --limit group2 test.yml

and
ansible-playbook -i test.inventory --limit '!group1' test.yml

Comment: Thx for anwsering, but you include group2 only. What I am trying to achieve is the exact oposite : include only group1.
Comment: Are you joking? Change to "--limit group1" or --limit '!group2'". Try updating Ansible version if it doesn't work.
Comment: I am not joking ... what you answered works. but not the opposite : localhost seems to be systematically included.
Comment: And I canoot update ansible version unfortunately... I wish I could.

Exclude a group that contains localhost


how to change apk file name in android studio

Question: I am using android studio to make android application. Android studio generating .apk file with default name app-debug.apk. I have tried to change it. How I change it?
Answer: I found a very simple solution. The apk base name is the property archivesBaseName defined on the project. So the following line is enough to rename the apks:
<code>project.archivesBaseName = "AnotherName";
</code>


Is it possible to add up the accuracy rates of 2 predictors?

Question: Weather channel 1 has a 65% accuracy rate of predicting tomorrows weather
Weather channel 2 has a 59% accuracy rate of predicting tomorrows weather

Is it somehow possible to take into account their respective accuracy rates and predictions to somehow make a more accurate predictor?
What would the rates be if the both channels had the same prediction?
What would the rates be if the both channels had different predictions?

What specific topics/subjects cover this particular problem (that of combining different predictors)?

accuracy_rate will be defined in this question to avoid confusion as the
(# of correct predictions / # of total predictions) the channel has made
Answer: To do this well, you really need to understand the covariance between the two channels.  For example, in the 59% of cases where ch 2 is correct, the probability of channel 1 could be anywhere from 24% (always right when 2 is wrong) to 100% (always right when 2 is right), but I would imagine somewhere in between.
It is tempting to assume there is no correlation, in which case you can simply calculate the odds by multiplying the probabilities of the independent events and dividing by the sum of the probabilities of those which could have been.  For example, $$P(both right) = \frac{P(ch 1 right) * P(ch 2 right)}{ P(channels agree)}$$
$$=\frac{P(ch 1 right) * P(ch 2 right)}{ P(ch 1 right) P(ch 2 right) + P( ch 1 wrong) * P(ch 2 wrong)}$$
$$=\frac{0.65 \cdot 0.59}{0.65 \cdot 0.59 + 0.35 \cdot 0.41}\approx0.728$$
This stands to reason in the sense that it is better (more likely) than either alone when both are better than 50%.
However, considering they are both likely looking at the same radar maps, were instructed on the same techniques during school/training, etc, I find it very hard to believe that these would be independent.


Show/hide upload button

Question: How can I show/hide an upload button based on if a file is selected or not.
I've tried this, but the button remains hidden:

        Upload File
        <input class="form-control" type="file" ng-model="formData.file">

            <input type="submit" value="Upload" class="btn btn-default"

Comment: `ngModel` on `input[type="file"]` is not natively supported by AngularJS.
Comment: Thanks. Can you suggest any solution?
Comment: Not without knowing [which solution](https://www.google.fr/?gws_rd=ssl#safe=off&q=angularjs+file+upload) you'll use.
Comment: Okay, this is completely new to me. I would appreciate which solution to use. I am posting to a .aspx document.
Comment: Sadly, that's becoming an off-topic question. There isn't so many libraries for that, make a quick comparison and choose by yourself ;) .
Answer: As Blackhole said in comments, this code can't work, ngModel on input[type="file"] is not natively supported by AngularJS.
For debug instance, add {{formData.file.length}} in your html code,  you'll see that the value is always null.

Show/hide upload button


Preprocessor to use a different template for popup window

Question: I'd like to provide the ability to open some content in a new window without all of the headers and sidebars of the normal content window.  I tried to do this with a preprocessor, and got close, but still no cigar:
function THEME_preprocess_page(&$vars) {
  if (isset($_GET['popup']) && $_GET['popup'] == '1') {
    //error_log( var_export( $vars['theme_hook_suggestions'], true ) );
    // returns as last array item: page__node__3
    $vars['theme_hook_suggestions'][] = 'page__node__3__popup';
  }
}

I then have a template with the file name: page--node--3--popup.tpl.php which is just a straight copy of the region--content.tpl.php file, and it actually does hit that template!  The problem is that only the title shows up - and when I clear the cache I get a warning message that content is undefined in my popup template. I've also tried naming the file and setting the theme_hook_suggestions to 'region--content--popup'/'region_content_popup' with the same results.
Here is the content of region--content--popup.tpl.php
<div<?php print $attributes; ?>>
  <div<?php print $content_attributes; ?>>

    <?php if ($title): ?>
    <?php if ($title_hidden): ?>
<?php endif; ?>
    <?php print render($title_prefix); ?>

<?php print $title; ?>

    <?php print render($title_suffix); ?>
    <?php if ($title_hidden): ?>
<?php endif; ?>
    <?php endif; ?>
    <?php if ($tabs): ?>
<?php print render($tabs); ?>
<?php endif; ?>
    <?php if ($action_links): ?>
<?php print render($action_links); ?>
<?php endif; ?>
    <?php print $content; ?>
    <?php if ($feed_icons): ?>
<?php print $feed_icons; ?>
<?php endif; ?>

The H1 page title appears and nothing else.
Comment: Can you put the content of page__node__3_popup?
Comment: question updated with content of the template.
Answer: You probably want:
print render($page['content']);
You can find the variables available to you in the template by printing get_defined_vars() using print_r(), core's debug() function, or one of the extremely handy devel module debugging functions such as kpr() or dpm().
I'd install devel and do this:
kpr(get_defined_vars());
Your modal method might not play nicely with page cache so I'd definitely test to make sure it fits your usecase.
Comment: Thank you, using $page['content'] did the trick.  The mystery to me is when $content is populated and when it's not.  Thanks for the pointers for debug options.  Ignorant of the 'drupal way', I've been using good old error_log(var_export($arg,true)).


What does EXP stand for on guitar effect pedal control knob?

Question: What does the label "exp" stand for on a guitar effect pedal?
Example: there is a delay/reverb pedal with various controls - rate, repeat, tone, etc. One of the knobs is labelled "exp."
 Thanks for any response,
 Jeff
Comment: Exp typically means expression in effects, although what expression does is heavily dependent on the exact module. Can you link an example?
Comment: which pedal in particular?
Comment: expression is usually a rocker pedal like what you see on a wah or volume pedal. Perhaps the "Exp" refers to a tip-ring-sleeve midi connector.
Answer: In guitar pedal lingo - "EXP" usually means expression as in "expression pedal" which can be used to control effects such as a wha wha but are also used by guitarist to facilitate real time control of almost any variable such as volume, tone, echo repeats, delay time and many other variables.
If your pedal has a control knob labeled "EXP" then most likely it also has an expression pedal input to allow the use of an expression pedal to control some of the parameters in a live music setting while using both hands to play the guitar.
For example the EarthQuaker Devices Avalanche Run Stereo Delay and Reverb Pedal has a knob that allows you to specify which of the parameters you want to control with an expression pedal. The knob is labeled EXP on this pedal.

With this particular delay/reverb pedal the EXP control knob would be used if you plugged an expression pedal into the input on the side (also labeled EXP).  Then the knob would allow you to select the specific parameter (decay, delay time, repeats, etc).
If your pedal also has an input for a separate expression pedal, I am sure the EXP control knob is there to work in conjunction with your separate expression pedal.
Comment: perfect. and it so happens that the avalanche run is the pedal i have. this explains it. thanks for taking the time to post this. so cool that there are people willing to share their knowledge.
Comment: You are welcome.  Glad I could help.   You can mark this as an accepted answer if you want.  I think you get rep points when you mark an answer to your question as accepted.


QLabel sizehint is too small

Question: I have a QAbstractItemDelegate and in the paint method, I am trying to paint the text from a label. But the problem I am seeing is that the size hint of the QLabel is always too small for the text it contains. How can I fix this? For example:
QLabel *testlabel = new QLabel();
testlabel->setText("This is some test text that doesnt fit:");
testlabel->adjustSize();

QRect rect(testlabel->geometry());
Qt::Alignment alignFlags = testlabel->alignment();

painter->setFont(testlabel->font());
painter->drawRect(rect);
painter->drawText(rect, alignFlags, testlabel->text());

And then it looks like:

Any ideas why the bounding rectangle is too small?
Thanks
Stephen
Answer: If you are just trying to draw a bounding rectangle (or something related), you should get the  painter's font metrics and ask for a bounding rectangle for the text you want to display. There are different versions of QFontMetrics::boundingRect that will allow you to specify a containing rectangle so word wrapping will be taken into consideration.
Comment: you can use `void QCoreApplication::processEvents ( QEventLoop::ProcessEventsFlags flags = QEventLoop::AllEvents ) [static]` or `void QCoreApplication::processEvents ( QEventLoop::ProcessEventsFlags flags, int maxtime ) [static]` to process the qlabel's update event, which is needed to calculate size
Comment: Worked a treat, thank you! I still would like to know however why the rectangle from QLabel is too small for it's text?
Comment: It would likely be because the QLabel you create inside that function never gets to arrange itself until your paint function exits and returns control to the event loop at which point "update" processing can occur for the label.
Answer: why don't you use virtual QSize QLabel::sizeHint () const for getting the sizehint? it seems to be more reliable, because adjustSize();geometry() depends on the label being actually drawn onto something. but you don't draw the label (QWidget), but only it's text (QString), so adjustSize/geometry are more likely to fail than sizeHint.
see: http://doc.qt.io/qt-4.8/qwidget.html#sizeHint-prop
EDIT: oh, and using sizeHint would also simplify your code...
Comment: The width that sizeHint() gives me is the same as the width from geometry().
Comment: oh, then maybe you should look at QLabel's sources to see how it's drawn there. oh, and why can't you simply call the label's paint method? would be best imao...

QLabel sizehint is too small


Reopen question "Something went wrong while saving this configuration: Area is already set"

Question: Can the question Something went wrong while saving this configuration: Area is already set be reopened? As it is currently closed as unclear.
The question is about a bug that occurs in Magento 2.2.4 and Magento 2.2.5. The workaround in the accepted answer solves the issue by suggesting to apply an official patch.
The existence of an official patch should validate the fact that the question is actually clear and doesn't need any more details (The numbers of votes and views on the question and the answer are more proof that the question is clear in my opinion).
Disclaimer: I slightly edited the post to make it even a bit clearer.
Answer: Thanks for raising the issue about the question. I agree with you about reopen.
Please wait for a few mins, I will reopening the question.
UPDATE
Question is open now. Please edit the content of the question


Two dimensional Taylor series

Question: Can someone please explain me why:
$T_4((x,y);f,(0,0)) = xy - 0.5x^2y^2$
with: $f(x,y) = \log{(1+xy)} \cdot \cos{(2x^2)}$
Comment: https://en.wikipedia.org/wiki/Taylor_series#Taylor_series_in_several_variables
Answer: Using Rudin W. - Principles of mathematical analysis-(1976) pages 243-244, Murray H. Protter, Charles B. Jr. Morrey - Intermediate Calculus (2012) page 252 we know, that Taylor formula in case of 2 variables is
$$f(x,y)=f(a,b) + \sum\limits_{1 \leqslant s+r \leqslant p}\frac{\partial^{r+s}f(a,b)}{\partial x^r \partial y^s}\frac{(x-a)^r}{r!}\frac{(y-b)^s}{s!}+R_p=\\=f(a,b) + \sum\limits_{k=1}^{p}\frac{1}{k!}\left((x-a)\frac{\partial}{\partial x}+ (y-b)\frac{\partial}{\partial y} \right)^{\{k\}}f(a,b)+R_p$$
where $R_p$ is remainder.
In your case, assuming $\log = \log_{c}$, you need to calculate
$$\begin{array}{}f(0,0)=0, \\ \frac{\partial f(0,0)}{\partial x}=\frac{y\cos 2x^2-4x\ln (1+xy) \sin 2x^2(1+xy)}{\ln c (1+xy)} \big|_{(x,y)=(0,0)} =0, \\ \frac{\partial f(0,0)}{\partial y}=\frac{x \cos 2x^2}{\ln c (1+xy)} \big|_{(x,y)=(0,0)}=0 \\
\frac{\partial^2 f(0,0)}{\partial y^2} = -\frac{x^2 \cos 2x^2}{\ln c (1+xy)^2} \big|_{(x,y)=(0,0)}=0\\
\frac{\partial^2 f(0,0)}{\partial x \partial y} =\frac{-4yx^3\sin(2x^2)-4x^2\sin(2x^2) + \cos(2x^2)}{\ln c (1+xy)^2} \big|_{(x,y)=(0,0)}=\frac{1}{\ln c}\\
\cdots
\end{array}$$
up to member you wish.

Two dimensional Taylor series


Valor atríbuido a variável dentro do setOnClickListener não está a ser considerado

Question: Então estou fazendo um app de teste mais para estudar mesmo, sou iniciante no android não sei muita coisa, estou tentando fazer com que na aplicação quando eu clico em uma imagem que ele entra nesse método :
p1.setOnClickListener(new ImageView.OnClickListener() {

            @SuppressWarnings("ResourceType")
            public void onClick(View arg0) {
                posicao =1;
                Toast.makeText(getContext(), "Imagem 1 selecionada!", Toast.LENGTH_SHORT).show();

            }});

Estou querendo saber porque quando ele entra dentro desse método, ele não atribui valor para a variável posição, já tentei outras forma declarei outra variável ali e fiz a posição receber oque estava dentro mais nem assim funciona.
Essa são a imagens esse código acima é do primeira imagem, a ação quando clica na imagem e diz que ela foi selecionada..
A variável posição seria a variável que definiria o valor do if lá embaixo, tanto que quando eu declaro por exemplo posicao = 1 , ou seja posição recebe um fora da função ele funciona sem problemas, mais lá dentro do método p1 que é a imagem da esquerda é como se o posicao = 1 nem estivesse digitado ali.
no final da postagem tem meu código completo...

public class Fragment_main extends Fragment {

    public Fragment_main() {
    }

    private int posicao=0;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
       final View Acess = inflater.inflate(R.layout.fragment_main, container, false);

        ImageView p1 = (ImageView)Acess.findViewById(R.id.p1);
        ImageView p2 = (ImageView)Acess.findViewById(R.id.p2);

        p1.setOnClickListener(new ImageView.OnClickListener() {
            @SuppressWarnings("ResourceType")
            public void onClick(View arg0) {
                posicao =1;
                Toast.makeText(getContext(), "Imagem 1 selecionada!", Toast.LENGTH_SHORT).show();

            }});

        p2.setOnClickListener(new ImageView.OnClickListener() {
            @SuppressWarnings("ResourceType")
            public void onClick(View arg0) {
                Toast.makeText(getContext(), "Imagem 2 selecionada!", Toast.LENGTH_SHORT).show();
                posicao =2;

            }});

       // position =1;

        // pegando o valor que recebeu lá ....
                if (posicao==1) {

            Button caso1button = (Button) Acess.findViewById(R.id.bts); // botão

            //ImageView imagePreview = (ImageView)acessR.findViewById(R.id.viewimg); // idimg
            //imagePreview.setImageResource(R.drawable.colorpass); // local da img original

            caso1button.setOnClickListener(new Button.OnClickListener() {
                @SuppressWarnings("ResourceType")
                @Override
                public void onClick(View arg0) {

                    WallpaperManager myWallpaperManager
                            = WallpaperManager.getInstance(getContext());
                    try {
                        myWallpaperManager.setResource(R.drawable.gpx17); // wallpaper

                        Toast.makeText(getContext(), "Wallpaper aplicado com Sucesso!", Toast.LENGTH_SHORT).show();
                    } catch (IOException e) {

                        e.printStackTrace();
                    }
                }
            });
            posicao = 0;

        }else if (posicao==2) {

            Button caso2button = (Button) Acess.findViewById(R.id.bts); // botão

            //ImageView imagePreview = (ImageView)acessR.findViewById(R.id.viewimg); // idimg
            //imagePreview.setImageResource(R.drawable.colorpass); // local da img original

            caso2button.setOnClickListener(new Button.OnClickListener() {
                @SuppressWarnings("ResourceType")
                @Override
                public void onClick(View arg0) {

                    WallpaperManager myWallpaperManager
                            = WallpaperManager.getInstance(getContext());
                    try {
                        myWallpaperManager.setResource(R.drawable.gpx15); // wallpaper

                        Toast.makeText(getContext(), "Wallpaper aplicado com Sucesso!", Toast.LENGTH_SHORT).show();
                    } catch (IOException e) {

                        e.printStackTrace();
                    }
                }
            });
            posicao = 0;
        }

        return Acess;
    }

}

Answer: O código que está nos listener só é executado quando for clicada uma imagem.
Por isso, quando a execução chegar à linha
if (posicao==1)

o valor da variável posicao é zero.
O que deve fazer é ter o código que usa o WallpaperManager em um método à parte e aí fazer o setResource() de acordo com o valor de posicao.
Se eu entendi bem o que pretende será qualquer coisa assim:
public class Fragment_main extends Fragment {

    public Fragment_main() {
    }

    private int posicao=0;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
       final View Acess = inflater.inflate(R.layout.fragment_main, container, false);

        ImageView p1 = (ImageView)Acess.findViewById(R.id.p1);
        ImageView p2 = (ImageView)Acess.findViewById(R.id.p2);

        p1.setOnClickListener(new ImageView.OnClickListener() {
            @SuppressWarnings("ResourceType")
            public void onClick(View arg0) {
                posicao =1;
                Toast.makeText(getContext(), "Imagem 1 selecionada!", Toast.LENGTH_SHORT).show();

            }});

        p2.setOnClickListener(new ImageView.OnClickListener() {
            @SuppressWarnings("ResourceType")
            public void onClick(View arg0) {
                Toast.makeText(getContext(), "Imagem 2 selecionada!", Toast.LENGTH_SHORT).show();
                posicao =2;

            }});

        Button caso1button = (Button) Acess.findViewById(R.id.bts); // botão
        caso1button.setOnClickListener(new Button.OnClickListener() {
            @SuppressWarnings("ResourceType")
            @Override
            public void onClick(View arg0) {

                changeWallpaper();
            }
        });

        return Acess;
    }
}

private void changeWallpaper(){

    WallpaperManager myWallpaperManager = WallpaperManager.getInstance(getContext());
    if (posicao==1) {
        try {
            myWallpaperManager.setResource(R.drawable.gpx17); // wallpaper

            Toast.makeText(getContext(), "Wallpaper aplicado com Sucesso!", Toast.LENGTH_SHORT).show();
        } catch (IOException e) {

            e.printStackTrace();
        }
        posicao = 0;

    }else if (posicao==2) {
        try {
            myWallpaperManager.setResource(R.drawable.gpx15); // wallpaper

            Toast.makeText(getContext(), "Wallpaper aplicado com Sucesso!", Toast.LENGTH_SHORT).show();
        } catch (IOException e) {

            e.printStackTrace();
        }
        posicao = 0;
    }
}

Comment: Opa obrigadão, deu super certo, não imaginava que precisaria fazer só isso.


how big is the performance impact of using system('hostname') in PHP?

Question: I saw some existing code in the PHP scripts doing a
system('hostname');

how big can the performance impact on the server be if using this method?
Comment: Distinct from $_SERVER["HTTP_HOST"] ? When I do phpinfo() on my server the first table I see actually includes the system hostname in it. This is the format of the table data: [OPERATING SYSTEM HOSTNAME OS-VERSION DATE(OF OS?) EMAIL_OF_SYSADMIN:MORE OS METADATA.

It seems possible the system hostname is baked into PHP at copile-time or runtime.
Comment: by the way I found that on some servers, $_SERVER["HTTP_HOST"] doesn't always equal system('hostname'), but php_uname() and posix_uname() do.
Comment: Someone with sufficient rep should edit this question to ask about the performance impact of using system() calls in general in php, not just system('hostname') The question is slightly confusing.
Answer: Running external processes can be a real performance hit when you have thousands of clients trying to connect to your web server. That's why people ended up ditching CGI (common gateway interface, the act of web servers calling external processes to dynamically create content) and incorporating code directly into their web servers, such as mod_perl.
You won't notice it when you're testing your little web application at home but, when the hordes that make up the Internet swarm down to your site, it will collapse under the load.
You'd be far better trying to figure out a way to cache this information within PHP itself (how often does it change, really?). For your particular example, you could use the "php_uname('n')" call to retrieve the full name (e.g., "localhost.example.com" and (optionally) strip off the domain part, but I've assumed you want the question answered in a more general sense.

Update:
Since someone has requested benchmarks, here's a C program that does three loops of 1,000 iterations each. The first does nothing within the loop, the second gets an environment variable (one other possibility for having PHP get its hostname), the third runs a system() command to execute hostname:
#include <stdio.h>
#include <time.h>
#define LOOP1 1000
int main (int c, char *v[]) {
    time_t t1, t2, t3, t4;
    int i;

    t1 = time(NULL);
    for (i = 0; i < LOOP1; i++) {
    }

    t2 = time(NULL);
    for (i = 0; i < LOOP1; i++) {
        getenv ("xxhostname");
    }

    t3 = time(NULL);
    for (i = 0; i < LOOP1; i++) {
        system ("hostname >/dev/null");
    }

    t4 = time(NULL);

    printf ("Loop 1 took %d seconds\n", t2-t1);
    printf ("Loop 2 took %d seconds\n", t3-t2);
    printf ("Loop 3 took %d seconds\n", t4-t3);
    return 0;
}

The results are:
Cygwin (gcc):
    Loop 1 took 0 seconds
    Loop 2 took 0 seconds
    Loop 3 took 103 seconds
Linux on System z (gcc):
    Loop 1 took 0 seconds
    Loop 2 took 0 seconds
    Loop 3 took 5 seconds
Linux on Intel (gcc):
    Loop 1 took 0 seconds
    Loop 2 took 0 seconds
    Loop 3 took 5 seconds
Linux on Power (gcc):
    Loop 1 took 0 seconds
    Loop 2 took 0 seconds
    Loop 3 took 4 seconds
Windows on Intel (VS2008, and using "ver >nul:", not "hostname"):
    Loop 1 took 0 seconds
    Loop 2 took 0 seconds
    Loop 3 took 45 seconds

However you slice'n'dice it, that's quite a discrepancy on loop number 3. It probably won't cause any problems if you're getting one hit a week on your site but, if you hold any hope of surviving in the real world under load, you'd be best to avoid system() calls as much as possible.
Answer: Errm, you are aware of php_uname and posix_uname, right?
<?php
    echo "php_uname: " . php_uname('n') . "\n";

    $ar = posix_uname();
    echo "posix_uname: $ar[nodename]\n";
?>

should both work. In PHP 5.3, there is also a gethostname.
Comment: +1 $_SERVER["HTTP_HOST"] doesn't always equal system('hostname')... but php_uname() and posix_uname() do.
Answer: I used to have a site that was using exec, system and passthru in PHP to execute grep, sed and other tools on text files.
This made it so that each page view would result in not just one process, but two at once.  I ran into problems with the process limit on my shared hosting - more than 6 processes at once, and people got 503 errors.
This wasn't a problem until the site became popular. I had to rewrite the page to use PHP functions instead of calling external programs, and it was faster, and fixed the 503 errors. This might not be a problem if you have a less busy site, or a dedicated/virtual server.


How do I link back to a paginated and sorted list if that list is implemented using AJAX. I'm using Rails 3.2

Question: I have a list of items that are paginated using will_paginate and this works great. I finally implemented AJAX following instructions from a railscast and it works like a charm. However, now, when I navigate to an item's page, and then click the "back" link, the page and sorting are lost.
For example, in a list of Books, if I sort them via title and go to the second page, then click on a Book, that works fine. Then when I click "Back", I am taken back to the first page of the list without the sorting. I understand this is because the URL is no longer updated with the AJAX call.
How do I maintain pagination and sorting for back links with AJAX in my rails app?
This is the code I use to implement the AJAX:
results.js.erb:
$("#search_results").html("<%= escape_javascript(render :partial => "layouts/search_results_list").html_safe %>");

pagination.js:
$(function() {
  $("#search_results").on("click", ".sort a, .pagination a", function() {
    $.getScript(this.href);
    return false;
  });
});

From the Book page, I simply use:
request.referer

to go back to the list.
Answer: After lots of searching and not being able to find an appropriate solution, it turns out railscasts had the answer all along in a different post. Adding these lines to pagination.js did the trick:
history.pushState(null, "", this.href);
$(window).bind("popstate", function () {
    $.getScript(location.href);
});

This changes the URL with every AJAX request. Much simpler than other solutions I was contemplating.


Tools to Find & Fix C# coding standards

Question: I am using a tool called NDEPEND to scan my C# solution to find the coding issues. The tool  nicely list down the coding violations according to the category. My question is, will this tool give auto suggestion on the change that should be done to the listed coding issues? I cannot find anything related to this.
Answer: Looking at the list of default NDepend rules, you'll see they all come with two comment sections:  <Description> and <HowToFix>. The <HowToFix> section contains suggestions about how to fix the issues.
This feature came with NDepend v6 released in June 2015, maybe you are using a former version?
For example it looks like:
// <Name>Base class should not use derivatives</Name>

warnif count > 0
from baseClass in JustMyCode.Types
where baseClass.IsClass && baseClass.NbChildren > 0 // <-- for optimization!
let derivedClassesUsed = baseClass.DerivedTypes.UsedBy(baseClass)
where derivedClassesUsed.Count() > 0
select new { baseClass, derivedClassesUsed }

//<Description>
// In *Object-Oriented Programming*, the **open/closed principle** states:
// *software entities (components, classes, methods, etc.) should be open
// for extension, but closed for modification*.
// http://en.wikipedia.org/wiki/Open/closed_principle
//
// Hence a base class should be designed properly to make it easy to derive from,
// this is *extension*. But creating a new derived class, or modifying an
// existing one, shouldn't provoke any *modification* in the base class.
// And if a base class is using some derivative classes somehow, there
// are good chances that such *modification* will be needed.
//
// Extending the base class is not anymore a simple operation,
// this is not good design.
//</Description>

//<HowToFix>
// Understand the need for using derivatives,
// then imagine a new design, and then refactor.
//
// Typically an algorithm in the base class needs to access something
// from derived classes. You can try to encapsulate this access behind
// an abstract or a virtual method.
//
// If you see in the base class some conditions on *typeof(DerivedClass)*
// not only *urgent refactoring* is needed. Such condition can easily
// be replaced through an abstract or a virtual method.
//
// Sometime you'll see a base class that creates instance of some derived classes.
// In such situation, certainly using the *factory method pattern*
// http://en.wikipedia.org/wiki/Factory_method_pattern
// or the *abstract factory pattern*
// http://en.wikipedia.org/wiki/Abstract_factory_pattern
// will improve the design.
//</HowToFix>

Comment: Thank you Patrick. Yes I can find it in my version of NDEPEND as well. Actually I thought the NDEPEND will give suggestions/Hints just like in Resharper.

Tools to Find & Fix C# coding standards