text:
Q: Why can't it show up on Search in reactJS? My question is: I want to ask if I search for "Computer Science" and the "Programming Language" subLayer section appears but if you search for sections in the subLayer such as "HTML" and "CSS" it doesn't appear or can't, why is that? And what needs to be fixed from my coding in reactJS?
This is my json file:
layers :[
    {
      key: "1",
      title: "Computer Science",
      expanded: false,
      subLayer: [
        {
          key: "a",
          title: "Programming Language",
          expanded: false,
          subLayer: [
            {
              key: "a.1",
              title: "HTML",
              expanded: false,
              subLayer: [],
            },
            {
              key: "a.2",
              title: "CSS",
              expanded: false,
              subLayer: [],
            },
          ],
        },
      ],
    },
  ]

Code:
import data from './Data'

const checked = (e) => { }

function List(props) {
  const filteredData = data.layers.filter((el) => {
    if (props.input === '') {
      return el
    }
    return el.title.toLowerCase().includes(props.input) || el.subLayer.findIndex(x => x.title.toLowerCase().includes(props.input)) >= 0
  })

  return (
    <Accordion allowMultipleExpanded allowZeroExpanded className="text-sm">
      {filteredData.map((list) => (
        <AccordionItem key={list.key}>
          <AccordionItemHeading>
            <AccordionItemButton>
              <input
                type="checkbox"
                className="mx-2 text-sm"
                value="false"
                onClick={(e) => e.stopPropagation()}
                onChange={checked}
              />
              {list.title}
              <WorkspacesIcon className="WorkspacesIcons" />
            </AccordionItemButton>
          </AccordionItemHeading>
          <AccordionItemPanel>
            {list.subLayer.length !== 0 ? (
              <>
                {list.subLayer.map((listDetails) => (
                  <Accordion allowMultipleExpanded allowZeroExpanded>
                    <AccordionItem>
                      <AccordionItemHeading>
                        <AccordionItemButton>
                          <input
                            type="checkbox"
                            className="mx-2"
                            value="false"
                            onClick={(e) => e.stopPropagation()}
                            onChange={checked}
                          />
                          {listDetails.title}
                        </AccordionItemButton>
                      </AccordionItemHeading>
                      <AccordionItemPanel />
                      <AccordionItemPanel>
                        {listDetails.subLayer.length !== 0 ? (
                          <>
                            {listDetails.subLayer.map((listDetails1) => (
                              <AccordionItem>
                                <AccordionItemHeading>
                                  <AccordionItemButton>
                                    <input
                                      type="checkbox"
                                      className="mx-2"
                                      value="false"
                                      onClick={(e) => e.stopPropagation()}
                                      onChange={checked}
                                    />
                                    {listDetails1.title}
                                  </AccordionItemButton>
                                </AccordionItemHeading>
                                <AccordionItemPanel />
                              </AccordionItem>
                            ))}
                          </>
                        ) : (
                          ''
                        )}
                      </AccordionItemPanel>
                    </AccordionItem>
                  </Accordion>
                ))}
              </>
            ) : (
              ''
            )}
          </AccordionItemPanel>
        </AccordionItem>
      ))}
    </Accordion>
  )
}

Images:

if i write my code reactJS part filteredData, is there any error in this part:
const filteredData = data.layers.filter((el) => {
    if (props.input === '') {
      return el
    }
    return el.title.toLowerCase().includes(props.input) || el.subLayer.findIndex(x => x.title.toLowerCase().includes(props.input)) >= 0
  })

A: Looking at your code, you are just filtering based on the first layer title (eg: Computer Science) and the first sublayer title (eg: Programming language) only. You need to add another condition to look for the second sublayer.
Based on your code your return line would be:
return el.title.toLowerCase().includes(props.input) || el.subLayer.findIndex(x => x.title.toLowerCase().includes(props.input)) >= 0 || el.subLayer[0].subLayer.findIndex(x => x.title.toLowerCase().includes(props.input)) >= 0

To make more dynamic for when you have multiple arrays you can do this:
  return (
      el.title.toLowerCase().includes(props.input.toLowerCase()) ||
      el.subLayer.findIndex((x) => x.title.toLowerCase().includes(props.input.toLowerCase())) >= 0 ||
      el.subLayer
        .map(
          (x) =>
            x.subLayer.findIndex((x) => x.title.toLowerCase().includes(props.input.toLowerCase())) >= 0,
        )
        .includes(true)
    )


text:
Q: Negative division in little man computer I always get stuck in a loop when I try to make a division with a negative number in LMC. For exemple 10/2 will give me 5 and -10/-2 will also work and give 5. The problem is when there is a single negative number in the division for exemple 10/-2 and -10/2... 10-2-2-2-2-2=0 ; -10--2--2--2--2--2--2=0 but -10-2-2-2-2-2 does not equal 0. I thought of doing the absolute value but brings me nowhere... really in a pinch right now. If some bright mind could show me the way to enlightement and end my suffering please.

A: I'm not sure how you're doing it (since you've posted no code) but the usual way to do division is via repeated subtraction of just the magnitudes (no signs), followed by an adjustment for the signs.
For example, with 10 / -2, just use repeated subtraction of two from ten (to get five), then adjust the sign based on original signs. If divisor and dividend have different signs, the result is negative. Otherwise the result is non-negative.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Comparison of Classes using the `===` (subsumption operator) The fact that TypeOfClass === TypeOfClass is false strikes me as counter-intuitive. In the following code, even if field.class is the same class, it evaluates to false:
case field.class
when Fixnum, Float
  field + other_field
when Date, DateTime, Time
  field
else
  puts 'WAT?'
end

I did this:
Fixnum === Fixnum # => false
Class === Class   # => true

I found another thread:
Integer === 3 # => true
Fixnum === 3  # => true
3.class       # => Fixnum

I fail to find a reason for this language design. What were the language designers thinking when they baked in this behavior?
I think this is relevant to the answer provided in another thread. It is not unnatural to assume that Numeric === Integer since an Integer is a more specific type of Numeric. But, it isn't:
Numeric === Integer #=> false

I think case statements or === requires caution. If this operator is what we think it is , then, a Numeric should be a Numeric, an Integer should be a Numeric, etc.
Does anyone have an explanation of why this feature doesn't extend to classes? It seems like it would be easy enough to return true if the compared class is a member of the class' ancestors.
Based on an answer submitted below, the code was originally classifying Time (as extended by ActiveSupport:CoreExtensions::Integer::Time and ActiveSupport:CoreExtensions::Float::Time):
Timeframe = Struct.new(:from, :to) do
  def end_date
    case self.to
    when Fixnum, Float
      self.from + self.to
    when Date, DateTime, Time
      self.to
    else
      raise('InvalidType')
    end
  end
end

and in the console, I get:
tf = Timeframe.new(Time.now, 5.months)
# => #<struct Timeframe from=Tue Dec 10 11:34:34 -0500 2013, to=5 months>
tf.end_date
# => RuntimeError: InvalidType
#  from timeframe.rb:89:in `end_date'

A: I do not really see the problem here. For classes, the case equality operator asks whether the left hand argument is an instance of the class (or any subclass). So Fixnum === Fixnum really asks: "Is the Fixnum class itself a subclass of Fixnum?" No it is not.
Is the class Class itself a class? Class === Class, yes it is.
The point of the operator is that you should not need to go look for the class. What is wrong with using the case statement without the .class method in the beginning?
case field
when Fixnum, Float
  field + other_field
when Date, DateTime, Time
  field
else
  puts 'WAT?'
end

If you have a more complex example you can write your own lambdas to make the case statement easier:
field_is_number =  -> x {[Fixnum, Float].include? x.class}
field_is_time   =  -> x {[Date, DateTime, Time].include? x.class}

case field.class
  when field_is_number
    field + other_field
  when field_is_time
    field
  else
    puts 'WAT?'
end

A: If one of the operands is a class, it is checking whether the second one is this class instance. If they are both classes it will return false unless at least one of them is Class.
Note that Class is both a class and an instance of itself - it's probably biggest ruby weird TBH, but it makes perfect sense.
The reason I would vote for keeping this logic is that we can write those nice case statements without adding .class to objects.
Summary:
ClassName === object    <=>    object.kind_of? ClassName

However, if you really want to override this use:
class Class
  def ===(object)
    return object == self if object.is_a? Class
    super
  end
end

A: That's Module#=== and its intended behavior:

mod === obj → true or false
Case Equality—Returns true if anObject is an instance of mod or one of
mod's descendants. Of limited use for modules, but can be used in case
statements to classify objects by class.

It simply returns obj.kind_of? mod:
Fixnum === Fixnum      #=> false
Fixnum.kind_of? Fixnum #=> false

Class === Class        #=> true
Class.kind_of? Class   #=> true

String === "foo"       #=> true
"foo".kind_of? String  #=> true

3 is both, an Integer and a Fixnum because of its class hierarchy:
3.kind_of? Integer     #=> true
3.kind_of? Fixnum      #=> true
3.class.ancestors      #=> [Fixnum, Integer, Numeric, Comparable, Object, Kernel, BasicObject]

Numeric is not an Integer, it's a Class:
Numeric.kind_of? Integer  #=> false
Numeric.kind_of? Class    #=> true

But 3, (2/3) and 1.23 are all Numeric:
3.kind_of? Numeric               #=> true
Rational(2, 3).kind_of? Numeric  #=> true
1.23.kind_of? Numeric            #=> true

Bottom line: for case statements, just use case obj instead of case obj.class.
Update
You are getting this error because 5.months doesn't return an Integer, but a ActiveSupport::Duration:
Integer === 5.months                 #=> false
ActiveSupport::Duration === 5.months #=> true

Calling your method with 5.months.to_i or adding ActiveSupport::Duration to your classes should fix it.


text:
Q: How to overlay a  object and a raster Image I am trying to overlay some objects from up to down by this layer order:

*

*Info window

*PNG Image

*Google Maps

I did overlay the 2nd and 3rd layer. However, I couldn't display Info Window upon it.
I debugged the modified code. It happened when I add the autocomplete variable, the overlay PNG image couldn't be displayed.
(The autocomplete variable was marked as a comment by me in the current code snippet below)
Do you have any idea, please? Thanks before
My 2nd layer image to be overlay is:

My code is:

// This example creates a custom overlay called USGSOverlay, containing
// a U.S. Geological Survey (USGS) image of the relevant area on the map.

// Set the custom overlay object's prototype to a new instance
// of OverlayView. In effect, this will subclass the overlay class therefore
// it's simpler to load the API synchronously, using
// google.maps.event.addDomListener().
// Note that we set the prototype to an instance, rather than the
// parent class itself, because we do not wish to modify the parent class.

var overlay;
USGSOverlay.prototype = new google.maps.OverlayView();

// Initialize the map and the custom overlay.

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 11,
    center: {
      lat: -7.782886,
      lng: 110.367037
    },
    mapTypeId: 'satellite'
  });

  var bounds = new google.maps.LatLngBounds(
    new google.maps.LatLng(-7.9161700000000002, 110.1243099999999941),
    new google.maps.LatLng(-7.3161699999999996, 110.7243100000000027));

  // The photograph is courtesy of the U.S. Geological Survey.
  var srcImage = 'https://i.stack.imgur.com/vR3Rz.png';

  var input = document.getElementById('pac-input');
  map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
  // Variable untuk Location Seach Bar

  var infowindow = new google.maps.InfoWindow();
  var infowindowContent = document.getElementById('infowindow-content');
  infowindow.setContent(infowindowContent);
  // Variable untuk kotak keterangan lokasi

  var marker = new google.maps.Marker({
    map: map
  });

  marker.addListener('click', function() {
    infowindow.open(map, marker);
  });

  /*
  var autocomplete = new google.maps.places.Autocomplete(input);
  autocomplete.bindTo('bounds', map);

  autocomplete.addListener('place_changed', function() {
   infowindow.close();
   var place = autocomplete.getPlace();

   if (!place.geometry) {
    return;
   }

   if (place.geometry.viewport) {
    map.fitBounds(place.geometry.viewport);
   } else {
    map.setCenter(place.geometry.location);
    map.setZoom(17);
   }

   // Set the position of the marker using the place ID and location.
   marker.setPlace({
    placeId: place.place_id,
    location: place.geometry.location
   });

   marker.setVisible(true);

   infowindowContent.children['place-name'].textContent = place.name;
   //infowindowContent.children['place-id'].textContent = place.place_id;//Script penampil Place ID tidak perlu dijalankan
   infowindowContent.children['place-address'].textContent = place.formatted_address;
   infowindow.open(map, marker);
  });
  */

  // The custom USGSOverlay object contains the USGS image,
  // the bounds of the image, and a reference to the map.
  overlay = new USGSOverlay(bounds, srcImage, map);

}

/** @constructor */
function USGSOverlay(bounds, image, map) {
  // Initialize all properties.
  this.bounds_ = bounds;
  this.image_ = image;
  this.map_ = map;

  // Define a property to hold the image's div. We'll
  // actually create this div upon receipt of the onAdd()
  // method so we'll leave it null for now.
  this.div_ = null;

  // Explicitly call setMap on this overlay.
  this.setMap(map);
}

/**
 * onAdd is called when the map's panes are ready and the overlay has been
 * added to the map.
 */
USGSOverlay.prototype.onAdd = function() {
  var div = document.createElement('div');
  div.style.borderStyle = 'none';
  div.style.borderWidth = '0px';
  div.style.position = 'absolute';

  // Create the img element and attach it to the div.
  var img = document.createElement('img');
  img.src = this.image_;
  img.style.width = '100%';
  img.style.height = '100%';
  img.style.position = 'absolute';
  div.appendChild(img);

  this.div_ = div;

  // Add the element to the "overlayLayer" pane.
  var panes = this.getPanes();
  panes.overlayLayer.appendChild(div);
};

USGSOverlay.prototype.draw = function() {
  // We use the south-west and north-east
  // coordinates of the overlay to peg it to the correct position and size.
  // To do this, we need to retrieve the projection from the overlay.
  var overlayProjection = this.getProjection();

  // Retrieve the south-west and north-east coordinates of this overlay
  // in LatLngs and convert them to pixel coordinates.
  // We'll use these coordinates to resize the div.
  var sw = overlayProjection.fromLatLngToDivPixel(this.bounds_.getSouthWest());
  var ne = overlayProjection.fromLatLngToDivPixel(this.bounds_.getNorthEast());

  // Resize the image's div to fit the indicated dimensions.
  var div = this.div_;
  div.style.left = sw.x + 'px';
  div.style.top = ne.y + 'px';
  div.style.width = (ne.x - sw.x) + 'px';
  div.style.height = (sw.y - ne.y) + 'px';
};

// The onRemove() method will be called automatically from the API if
// we ever set the overlay's map property to 'null'.
USGSOverlay.prototype.onRemove = function() {
  this.div_.parentNode.removeChild(this.div_);
  this.div_ = null;
};

google.maps.event.addDomListener(window, 'load', initMap);
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */

#map {
  height: 100%;
}

/* Optional: Makes the sample page fill the window. */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

.controls {
  background-color: #fff;
  border-radius: 2px;
  border: 1px solid transparent;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
  box-sizing: border-box;
  font-family: Roboto;
  font-size: 15px;
  font-weight: 300;
  height: 29px;
  margin-left: 17px;
  margin-top: 10px;
  outline: none;
  padding: 0 11px 0 13px;
  text-overflow: ellipsis;
  width: 400px;
}

.controls:focus {
  border-color: #4d90fe;
}

.title {
  font-weight: bold;
}
<!DOCTYPE html>

  <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
  <meta charset="utf-8">

  <title>Thank you for looking around to this code</title>

  <input id="pac-input" class="controls" type="text" placeholder="Enter a location">

A: I get an error with the posted code: Uncaught InvalidValueError: initMap is not a function.  Remove the callback parameter from the API include, change:

To:

working code snippet:

// This example creates a custom overlay called USGSOverlay, containing
// a U.S. Geological Survey (USGS) image of the relevant area on the map.

// Set the custom overlay object's prototype to a new instance
// of OverlayView. In effect, this will subclass the overlay class therefore
// it's simpler to load the API synchronously, using
// google.maps.event.addDomListener().
// Note that we set the prototype to an instance, rather than the
// parent class itself, because we do not wish to modify the parent class.

var overlay;
USGSOverlay.prototype = new google.maps.OverlayView();

// Initialize the map and the custom overlay.

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 11,
    center: {
      lat: -7.782886,
      lng: 110.367037
    },
    mapTypeId: 'satellite'
  });

  var bounds = new google.maps.LatLngBounds(
    new google.maps.LatLng(-7.9161700000000002, 110.1243099999999941),
    new google.maps.LatLng(-7.3161699999999996, 110.7243100000000027));

  // The photograph is courtesy of the U.S. Geological Survey.
  var srcImage = 'https://i.stack.imgur.com/vR3Rz.png';

  var input = document.getElementById('pac-input');
  map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
  // Variable untuk Location Seach Bar

  var infowindow = new google.maps.InfoWindow();
  var infowindowContent = document.getElementById('infowindow-content');
  infowindow.setContent(infowindowContent);
  // Variable untuk kotak keterangan lokasi

  var marker = new google.maps.Marker({
    map: map
  });

  marker.addListener('click', function() {
    infowindow.open(map, marker);
  });

  var autocomplete = new google.maps.places.Autocomplete(input);
  autocomplete.bindTo('bounds', map);

  autocomplete.addListener('place_changed', function() {
    infowindow.close();
    var place = autocomplete.getPlace();

    if (!place.geometry) {
      return;
    }

    if (place.geometry.viewport) {
      map.fitBounds(place.geometry.viewport);
    } else {
      map.setCenter(place.geometry.location);
      map.setZoom(17);
    }

    // Set the position of the marker using the place ID and location.
    marker.setPlace({
      placeId: place.place_id,
      location: place.geometry.location
    });

    marker.setVisible(true);

    infowindowContent.children['place-name'].textContent = place.name;
    //infowindowContent.children['place-id'].textContent = place.place_id;//Script penampil Place ID tidak perlu dijalankan
    infowindowContent.children['place-address'].textContent = place.formatted_address;
    infowindow.open(map, marker);
  });

  // The custom USGSOverlay object contains the USGS image,
  // the bounds of the image, and a reference to the map.
  overlay = new USGSOverlay(bounds, srcImage, map);

}

/** @constructor */
function USGSOverlay(bounds, image, map) {
  // Initialize all properties.
  this.bounds_ = bounds;
  this.image_ = image;
  this.map_ = map;

  // Define a property to hold the image's div. We'll
  // actually create this div upon receipt of the onAdd()
  // method so we'll leave it null for now.
  this.div_ = null;

  // Explicitly call setMap on this overlay.
  this.setMap(map);
}

/**
 * onAdd is called when the map's panes are ready and the overlay has been
 * added to the map.
 */
USGSOverlay.prototype.onAdd = function() {
  var div = document.createElement('div');
  div.style.borderStyle = 'none';
  div.style.borderWidth = '0px';
  div.style.position = 'absolute';

  // Create the img element and attach it to the div.
  var img = document.createElement('img');
  img.src = this.image_;
  img.style.width = '100%';
  img.style.height = '100%';
  img.style.position = 'absolute';
  div.appendChild(img);

  this.div_ = div;

  // Add the element to the "overlayLayer" pane.
  var panes = this.getPanes();
  panes.overlayLayer.appendChild(div);
};

USGSOverlay.prototype.draw = function() {
  // We use the south-west and north-east
  // coordinates of the overlay to peg it to the correct position and size.
  // To do this, we need to retrieve the projection from the overlay.
  var overlayProjection = this.getProjection();

  // Retrieve the south-west and north-east coordinates of this overlay
  // in LatLngs and convert them to pixel coordinates.
  // We'll use these coordinates to resize the div.
  var sw = overlayProjection.fromLatLngToDivPixel(this.bounds_.getSouthWest());
  var ne = overlayProjection.fromLatLngToDivPixel(this.bounds_.getNorthEast());

  // Resize the image's div to fit the indicated dimensions.
  var div = this.div_;
  div.style.left = sw.x + 'px';
  div.style.top = ne.y + 'px';
  div.style.width = (ne.x - sw.x) + 'px';
  div.style.height = (sw.y - ne.y) + 'px';
};

// The onRemove() method will be called automatically from the API if
// we ever set the overlay's map property to 'null'.
USGSOverlay.prototype.onRemove = function() {
  this.div_.parentNode.removeChild(this.div_);
  this.div_ = null;
};

google.maps.event.addDomListener(window, 'load', initMap);
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */

#map {
  height: 100%;
}

/* Optional: Makes the sample page fill the window. */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

.controls {
  background-color: #fff;
  border-radius: 2px;
  border: 1px solid transparent;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
  box-sizing: border-box;
  font-family: Roboto;
  font-size: 15px;
  font-weight: 300;
  height: 29px;
  margin-left: 17px;
  margin-top: 10px;
  outline: none;
  padding: 0 11px 0 13px;
  text-overflow: ellipsis;
  width: 400px;
}

.controls:focus {
  border-color: #4d90fe;
}

.title {
  font-weight: bold;
}
<!DOCTYPE html>

  <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
  <meta charset="utf-8">

  <title>Thank you for looking around to this code</title>

  <input id="pac-input" class="controls" type="text" placeholder="Enter a location">


text:
Q: Looping through DOM elements for .ajax() calls, scope issue with request.done() I am facing a problem with the following javascript function I created. It simply loops through all 'div.ajax' elements, fetches the URL from the data-url attribute, and should use the ajax call to load a new bunch of HTML which should be inserted into the element.
The problem is, I can't seem to be able to access the 'this' variable (containing the attribute) inside the request.done function (a scope issue). I tried to attach the 'this' variable to a global variable (document.this_element), but that doesn't work since sometimes multiple ajax calls are processed at the same time (hence the content is inserted into the wrong element).
I cannot use the .load() jquery function here, as I need some additional options only available to .ajax(). Does anyone know how I can solve this problem? Thanks!
//function to reload several blocks with ajax-injected data
function reload_ajax(){
   //foreach block
   $('div.ajax').each(function(index){

      //get url
      var url = $(this).attr('data-action');

      //make the block empty, add ajax loader image with CSS class
      $(this).addClass('not-loaded').html('');

      //make request
      var request = $.ajax({url: url, type: 'GET',data: {}, dataType: 'html'});

      //if request = done
      request.done(function(response){
         //SCOPE PROBLEM, 'this' element is not known
         $(this).removeClass('not-loaded').html(response);
      });

      //if request = failed
      request.fail(function(jqXHR, textstatus){
         //SCOPE PROBLEM, 'this' element is not known
         $(this).removeClass('not-loaded').html('Error: Could not load data.');
      });
   });
}


text:
Q: Encode 2 tables with json_encode My function looks like this
$sql = "SELECT * FROM friends WHERE id1='$id' AND accepted=1 AND notification=1;";
$result = mysqli_query($conn, $sql);
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);

header("Content-Type: application/json");
echo json_encode($data);

I want to select something from another table. How can i do that?


text:
Q: Hide paragraph but keep space I need a command that replaces its contents by white space of the same size. Unlike \phantom it should work paragraphs and/or images. It should do more or less the same as the \visible command of the beamer package when applied to a non-specified overlay number.
Looking at the source of the beamer package did not help me because I could not isolate my issue from the rest.
Any suggestions?

A: You can put paragraphs and other vertical constructs in a parbox nested inside phantom so
\noindent
\phantom{%%% remove to make visible
\begin{minipage}{\textwidth}
.....
\end{minipage}%
}%%% remove to make visible

But as with all phantoms note that this freezes the contents in a box so that all white space is frozen to its natural size, and no page breaking will occur, so the spacing is not the same if the construct was not used at all, however if you just remove the two lines marked in the block above, leaving the minipage then you can switch between visible and non-visible form without affecting the position of any other text in the document.


text:
Q: Create secret for all namespaces When I create secret with Rancher and select it should be visible in all namespaces, it creates a secret without namespace tag and with namespaceId: null.
How to create such secret without Rancher? When I use kubectl, it always binds it to the namespace from the command context.

A: kubectl currently does not support creating secrets across namespaces.
They are available to a single namespace. Rancher supports it creating secrets at the project level. it will replicate the secret to all namespaces in the project (present and future). also, functionality is not in the rancher cli yet.
there are some work around option available to replicate the secret and configmap across the namespace in Kuberenetes.
You can check this out open source projects:

*

*https://github.com/zakkg3/ClusterSecret

*https://github.com/mittwald/kubernetes-replicator


text:
Q: Determine path dynamically in Silverlight 2 I have a border with rounded corners within a canvas and want to add a clipping region to the canvas so that anything I add is clipped to the region within the border. I know that I can set the Clip property of the canvas but as the canvas and object are sized dynamically rather than having sizes assigned in the XAML, I can't figure out how to calculate the path to use. Is there some way to derive a PathGeometry from a UIElement (the border in this case)? If not what is the best way to approach this? Here is the XAML for the test page I'm working with.
<UserControl x:Class="TimelinePrototype.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid x:Name="LayoutRoot">
    <Grid.RowDefinitions>
        <RowDefinition Height="auto" />
        <RowDefinition />
    </Grid.RowDefinitions>
    <StackPanel Orientation="Horizontal" Margin="10">
        <Button x:Name="cmdDraw" FontSize="18" Click="cmdDraw_Click" Content="Draw" Margin="0,0,5,0" VerticalAlignment="Bottom" />
        <TextBlock x:Name="txtDateRange" FontSize="18" Margin="10,0,10,10" VerticalAlignment="Bottom" />
    </StackPanel>
    <Canvas x:Name="TimelineCanvas" Grid.Row="1" HorizontalAlignment="Stretch"
                SizeChanged="TimelineCanvas_SizeChanged">
        <Border x:Name="TimelineBorder"
                Background="LightGray"
                BorderBrush="Black"
                BorderThickness="2"
                CornerRadius="15"
                Margin="10"
                Grid.Row="1"
                VerticalAlignment="Top">
        </Border>
    </Canvas>
</Grid>

A: Try using the ActualHeight and ActualWidth properties
var height = TimelineCanvas.ActualHeight;
var width = TimelineCanvas.ActualWidth;

A: I ended up using this code, but would still be interested in any alternate methods.
RectangleGeometry clipRect = new RectangleGeometry();
clipRect.Rect = new Rect(TimelineBorder.Margin.Left, TimelineBorder.Margin.Top, TimelineCanvas.ActualWidth - (TimelineBorder.Margin.Left + TimelineBorder.Margin.Right), TimelineCanvas.ActualHeight - (TimelineBorder.Margin.Top + TimelineBorder.Margin.Bottom));
clipRect.RadiusX = TimelineBorder.CornerRadius.TopLeft;
clipRect.RadiusY = TimelineBorder.CornerRadius.TopLeft;
TimelineCanvas.Clip = clipRect;

A: Try blacklight
The blacklight toolpack has a rounded corner clipping tool and is free.


text:
Q: how do I delay a CSS3 transition before starting? I'm trying to display an element, wait 1second and then fade out the element using css3 transitions.
Here is what I have:
.el {
    -webkit-animation-timing-function: ease-in;
    -webkit-animation-duration: 225ms;
    -moz-animation-timing-function: ease-in;
    -moz-animation-duration: 225ms;
    animation-timing-function: ease-in;
    animation-duration: 225ms;
}
@-webkit-keyframes fadeout {
    from { opacity: 1; }
    to { opacity: 0; }
}
@-moz-keyframes fadeout {
    from { opacity: 1; }
    to { opacity: 0; }
}
@keyframes fadeout {
    from { opacity: 1; }
    to { opacity: 0; }
}
.el {
  opacity: 0;
  -webkit-animation-duration: 500ms;
  -webkit-animation-name: fadeout;
  -webkit-animation-delay: 1000ms;
  -moz-animation-duration: 500ms;
  -moz-animation-name: fadeout;
  -moz-animation-delay: 1000ms;
  animation-duration: 500ms;
  animation-name: fadeout;
  animation-delay: 1000ms;
}

I thought animation-delay would be the way to go, but doing it like this, the element appears after 1000ms instead of fading out after 1000ms.
Any idea how to delay the fadeout?
Thanks!

A: Why not add the extra delay time to your animation duration:
-webkit-animation-duration: 1500ms;

Where ~66%(1000ms) of the time is a delay:
@-webkit-keyframes fadeout
{
    0% { opacity: 1; }
    66% { opacity: 1; }
    100% { opacity: 0; }
}

Note that i used this time as an example. You can calculate the percentage of the delay yourself
jsFiddle

I hope this is what you meant.

A: Even though there is already a correct answer, let me enumerate what you options are.
You want an element to begin at opacity of 1, and stay like this for a second. Then, you want to fade it away to opacity of 0 during 0.5 s. And you want it to stay at opacity 0 forever.
The problem here is that the initial state and the final state are differents, so the base state of the element can not be both (of course!).
If we make the base state opacity 0, the problem is at the beginning. We can solve it as in nkmol solution. (starting the animation right away. We can also leave the animation only for the 0.5s where the opacity changes, and change the opacity usiong animation-fill-mode: backwards;
Also, you could set the base element to opacity 1. Then the problem is to make the final opacity 0; that can be done set animation-fill-mode: forwards;


text:
Q: cannot make the except conditions run as expected in this simple code I expect the result to be :
wrong range or wrong color
but no matter what it doesn't work as expected can you help out.
pen = 'yellow'
lan = 5
try :
    if pen == 'yellow' and lan <= 40 and lan >=10 :
        print ('color yellow within range')
except :
    print('wrong range or wrong color ')

EDIT #1
I get that this proplem can be solved in this situation using if , else but for a sligtly more complicated code such as this
pen = input('color: ')
lan = input( 'number: ')
lan = int(lan)
try :
    if pen == 'yellow' and lan <= 40 and lan >=10 :
        print ('color yellow within range')
    elif pen == 'green' and lan <= 60 and lan >= 30 :
        print ('color green within range')
except :
    print('wrong range or wrong color ')

how can the try and except be used in this context

A: I think you misunderstand try-except. except only executes in response ta a raise. What you want here is a simple else, i think.
pen = 'yellow'
lan = 5
if pen == 'yellow' and lan <= 40 and lan >=10 :
    print ('color yellow within range')
else :
    print('wrong range or wrong color ')

A: I think this should work:
pen = 'yellow'
lan = 5
if pen == 'yellow' and lan <= 40 and lan >=10 :
    print ('color yellow within range')
else:
    print('wrong range or wrong color ')


text:
Q: Is it possible to add in python class object's values to list? I'm making my own little game on python but I have little problem.
I'm trying to use class attribute with using only variables and i don't know if it's possible or how to do it right.
I'm kinda out of ideas and couldn't find answers from the net. This problem doesn't prevent my programming but it would be a lot easier if could make this work.
I'm making turn-based fighting game. I have two types of resistance: armor and shields. They both can block certain kind of magic. Every character has some kind of armor and shields. The function ajjaa ads their armors and shields to lists that tell what kind of magic they resistances. I could use armor_types function on both only changing the meaning of the obj variable.
Here is part of my code(It works just fine when I delete obj variable and use instead hardcoded armor/shield):

class Fighter:
    def __init__(self, nimi, fdmg, tdmg, hp, armor, shield):
        self.nimi = nimi
        self.tdmg = tdmg
        self.fdmg = fdmg
        self.hp = hp
        self.armor = armor
        self.shield = shield

namelist = ["Lilah", "Morton", "King", "Sariel", "Leaf"]
tdmg = [50, 45, 40, 35, 30]
fdmg = [5, 10, 15, 20, 25]
hp = [100, 90, 80, 70, 60]
types = []
firetype = []
icetype = []
armor = ["t", "f", "f", "t", "f"]
shield = ["f", "t", "t", "t", "f",]

def add_lists():
    types.append(firetype)
    types.append(icetype)

def armor_types(myfighter,numberx,obj):
   print (myfighter.obj)
   if myfighter.obj == 't':
      if numberx == 0 or numberx == 8:
         firetype.append(myfighter.obj)
         if numberx == 0:
            myfighter.obj = 0.97
         if numberx == 8:
            myfighter.obj = 0.97
      if numberx == 1 or numberx == 9:
         icetype.append(myfighter.obj)
         if numberx == 1:
            myfighter.obj = 0.97
         if numberx == 9:
            myfighter.obj = 0.97
   print(myfighter.obj)

def main(numberx):
    add_lists()
    for x in namelist:
        myfighter = Fighter(x, tdmg[numberx], fdmg[numberx], hp[numberx], armor[numberx], shield[numberx])
        print(myfighter.armor)
        armor_types(myfighter,numberx,'armor')
        armor_types(myfighter,numberx,'shield')
        numberx += 1

main(0)

It just shows an error, but it should be added two to mylist.
I hope i explained problem right because I don't speak english as my native language. If there is ajjaa somwhere please tell me. aijjaa meant armor_types funcion.

A: It took me some time to understand the problem because your really posted too much code. It could boil down to:
Impossible to access a parameterized attribute of object in following code:
class Fighter:
    def __init__(self, armor, shield):
        self.armor = armor
        self.shield = shield

def armor_types(myfighter, obj):
    return myfighter.obj

f = Fighter(2,3)
print(armor_types(f, 'armor'))

raising exception at return myfighter.obj:
AttributeError: 'Fighter' object has no attribute 'obj'

While it works fine with hardcoded attributes (myfighter.armor)
Explaination of the problem:
The language only allows obj.attr for hardcoded attributes. What should happen in above code if the object also contained an obj attribute?
Solution:
What you need are the builtin functions getattr and setattr. In above code, you could use:
def armor_types(myfighter, obj):
    return getattr(myfighter, obj)

and to change a parameterized attribute:
setattr(myfighter, obj, new_value)


text:
Q: Arithmetic overflow error converting numeric to data type small money I have a column called [column_us] in my table where I have given the data type as smallmoney not null.
Initially it looked good and data is feeding into this table , but after one month I'm getting an error:

Arithmetic overflow error converting numeric  to data type smallmoney.
The statement has been terminated.

Do I need to change the data type to numeric (19,4) notnull to this column? If so, can you please explain which data type I should be using small money, money, or numeric?
Also how many values does the small money allow after decimal point.

A: In general, it is recommended to choose numeric() with the precision and scale you need. Money types may produce unexpected results when used with division (much further discussion on money found on this question: Should you choose the money or decimal(x,y) datatypes in SQL Server?).
numeric:
+-----------+---------------+
| Precision | Storage bytes |
+-----------+---------------+
| 1 - 9     |             5 |
| 10-19     |             9 |
| 20-28     |            13 |
| 29-38     |            17 |
+-----------+---------------+

money and smallmoney:
+------------+-------------------------------------------------------+---------+
| Data type  |                         Range                         | Storage |
+------------+-------------------------------------------------------+---------+
| money      | -922,337,203,685,477.5808 to 922,337,203,685,477.5807 | 8 bytes |
| smallmoney | - 214,748.3648 to 214,748.3647                        | 4 bytes |
+------------+-------------------------------------------------------+---------+

Reference:

*

*Should you choose the money or decimal(x,y) datatypes in SQL Server?

*money and smallmoney - docs

*decimal and numeric - docs

A: A smallmoney is not able to store big amounts, you should use money type instead.
smallmoney and money type are mostly used for display purpose (currency symbol, ...).
numeric or decimal types are more accurate with calculation.
You should consider searching more : I've found plenty of in depth explainations.


text:
Q: Page Expired if POST method (Laravel 5.5) My routes
Route::middleware('auth.basic')->group(function(){

Route::post('/', 'DeliveryController@calc')->name('delivery');

Route::post('pickup/', 'DeliveryController@getPickup');

Route::post('pec_pickup/', 'DeliveryController@getPecPickupPoint');});

when i try send request with postman i got "Page Expired". But if i replace all routes with GET - all ok.

A: Use
 {{ csrf_field() }} just bellow your form definition.
This will send a token to Controller to ensure that the request it has been made from your site.
This is a security enforcement for POST method, which should be use for create, delete, update on your models.


text:
Q: If the app uses serveral thread, will it run smoothly than using one UI Thread? My Application is using Single Thread( UI Thread ) right now,
and it has some code like...

*

*keep checking my phone state

*google map service

*keep adding marker to current state

*and there's a "popupmenu"
and when the "Popupmenu" inflates, app frame drops.
I've never tried splitting a Single Thread to two, is this the right way to prevent the janky(laggy) frame?
Or is there something like alternatives?

A: No, more threads are probably not the answer here.
First of all the android gui is single threaded, you are only allowed to interact with it using the main thread.
Are you doing something similar to the official doc/guide here for popup menu?
https://developer.android.com/guide/topics/ui/menus#PopupEvents
Meaning code something lik this:
public void showMenu(View v) {
    PopupMenu popup = new PopupMenu(this, v);

    // This activity implements OnMenuItemClickListener
    popup.setOnMenuItemClickListener(this);
    popup.inflate(R.menu.actions);
    popup.show();
}

If you are not doing much more than this you can't optimize this much more, not easily.
If you are, perhaps you can simplify it to the basic example from the docs.
I would otherwise assume that you are consuming too much of the frames' time budget doing other things that hopefully can be optimized/paused instead so the popup menu inflating is  not going over your limits.


text:
Q: Decode base64 strings into hex strings in a file and overwrite I have a list of base64 strings in a file (file.txt) that I need to convert into hex. E.g.,
6IwwfX8Cctn85LW+vItMhw==
wIsNfYESR9Nfueo7mg3f7Q==
A+MxnRyu6kotbKPZglQ0Fg==
Jt5jNIphpmfGoFgtgM7/Sg==
sN+Q0Xcu6JHlkqdhJlM/tw==

Command:
echo -n 6IwwfX8Cctn85LW+vItMhw== | base64 -d | od -t x1 -An

This command works individually (albeit the spaces in between), but I need to convert through each string in the file, which has more than 500 lines.
Basically, I want the above base64 string format to be decoded to the below example hex string format:
30aa268d130fb78a4f8cb6f300e4c760
Is there a way that I can call each line in the file (like a for each command) and pipe with the base64 command to convert? Any help is appreciated.

A: Try:
for b64 in $(cat e.txt); do echo "$b64" | base64 -d | od -t x1 -An | tr -d ' '; done

The tr -d ' ' at the end deletes all spaces.

A: cat file.txt | while read input ; do echo -n "$input" | base64 -d | od -t x1 -An ; done

A: cat file.txt | while read b64
do echo -n "$b64" | base64 -d | od -t x1 -An | sed 's/[\t ]*//g'
done

A: You can use Awk for this and run a command on the contents of the file using the getline() syntax
awk '{ cmd = "printf '%s' "$1 "| base64 -d | od -t x1 -An" }
     { while ( ( cmd | getline result ) > 0 ) { gsub(/[[:space:]]+/,"",result); $0 = result }; close(cmd)  }1' file.txt

Use a temporary file for overwriting the file contents and move back the original file
tmpfile=$(mktemp)
awk '{ cmd = "printf '%s' "$1 "| base64 -d | od -t x1 -An" }
     { while ( ( cmd | getline result ) > 0 ) { gsub(/[[:space:]]+/,"",result); $0 = result }; close(cmd)  }1' file.txt > "$tmpfile" && mv "$tmpfile" file.txt


text:
Q: Algorithm to fill large rectangle with smaller rectangles starting from center I have various sizes of rectangles, and I am trying to fit them into a larger rectangle starting from the center. Below you will find an animation I created to visually describe what needs to take place.
I have been struggling to come up with a way to model this behavior. Does anything exist that is similar to this? I just need to be pointed in the right direction.

The following is a very rough explanation:
Initialize

*

*Start with n rectangles

*Order by density (they are really 3d cubes bird's eye view)

*Place first rectangle at center

Remaining rectangles (fit as many as I can)
try to group highest density in the center and move outward
Dimensions = { width: 400, height: 300 }
Boundries = {
  WEST = 0,
  EAST = Dimensions.width,
  NORTH = 0,
  SOUTH = Dimensions.height
}

// each rectangle has width, height, and other information
rectArr = Array of {width:60, height:40}

root = { x:EAST/2, y:SOUTH/2 }

foreach rect in rectArr {
  // I will always traverse from the root and try to go left and right. If I cannot, I move up and try the same thing. I then move down. The problem is if there are 5 or more rows. I will be starting from the root and going up, then down, then up-up, then down. It's like I have two parallel trees.

  // Try to branch left or right
  if rect.width <= (Boundries.EAST - ('rightmost rectangle'.x + 'rightmost rectangle'.width/2)) branch-right
  if rect.width <= (('leftmost rectangle'.x + 'leftmost rectangle'.width/2) - Boundries.WEST) branch-left
  // Try to branch up or down
  if rect.height <= ((root.x + root.height/2) - Boundries.NORTH) branch-up
  if rect.height <= (Boundries.SOUTH - (root.x + root.height/2)) branch-down
}

A: EDIT: Started writing this too early. This solution only pertains to filling the larger rectangle with as many small rectangles as is possible assuming the locations of the smaller rectangles is static.
Sounds like a dynamic programming solution will work best here; if you haven't studied algorithms, I'd advise looking into the definition of greedy algorithms, the definition of dynamic programming algorithms, examples of each kind, and where you'd use one rather than the other.
This problem is very similar to the weighted scheduling problem, but in 2 dimensions. In weighted scheduling, we're given an interval and a set of sub intervals and asked to determine the set of sub intervals whose summed weights are the largest and whose ranges don't overlap:
|--------------------------|
|{--a--}-------------------|
|----{------b-------}------|
|--------{----c----}-------|
|--------------------{-d-}-|

If we expanded this to two dimensions, the larger interval would be the x/y lengths of the bounding rectangle, the sub intervals would be the x/y lengths of the smaller rectangles, and the sub interval's weights are the areas of the smaller rectangles.
In the greedy algorithm, we would attempt to fill the bounding rectangle with as many of the biggest sub rectangles as was possible, then attempt to fit in as many of the the second biggest, then third biggest and so on until none of your rectangles fit. The problem with it is that you may end up filling in less of the bounding rectangle when using 1 of the biggest sub rectangles than when using 4 of the second biggest (think of the case where we have a a bounding square with sides size 6, the biggest sub-squares have sides size 5, and the second biggest sub-squares have sides with size 3). It looks like your initial solution may run into this same problem.
The dynamic programming solution breaks the larger problem down into overlapping subproblems, then builds up a solution based on the sub problem's outcomes. In the case of the rectangles, you want to ask the same question for every rectangle in your set: is the outcome better when I include it or when I don't include it in my solution. Based on the answer to this question, you'd add the rectangle to your solution set and remove all other rectangles it overlaps with or you'd remove only that rectangle and continue. I'd propose the following psudeo code:
compute_opt ( set of rectangles ){
  if(set.size == 0)
    return 0
  return max (area of selected rectangle i +
              compute_opt( rectangles that don't overlap with i) ,
              compute_opt( rectangles without rectangle i included) )
}

I'm a bit rusty on memoization, so I won't go into it here. But see this princeton lecture on dynamic programming for more info on weighted scheduling. You should be able to figure out the specifics of the rectangle problem given the specifics of the interval problem.


text:
Q: trackpad doesn't work after suspend Ubuntu 14.04 and a Fujitsu Lifebook U-series.I can't get trackpad to work after suspend bluetooth mouse does.Sorry to say that trackpad didn't work form the beginning but my son googled something and edited something and got it to work. Trackpad works fine if I reboot or start the computer from scratch, two finger scrolling and so forth. Need some help to search what goes wrong.

A: I have this problem as well, what I found works for me is switching to text console and back.
Ctrl+Alt+F1 switches you to text console 1.
Ctrl+Alt+F7 switches you back to your desktop. If not, try Ctrl+Alt+F8.


text:
Q: SQL Several Count First sorry if my english is bad, it's not my native language.
I have two tables (A and B) with the following columns:
A:
PRENUMERO (ID), DATA, ARMAZEM, TIPO
and
B:
Autoreg (ID), PRENUMERO, PRODUTO
I want a result like:
*CountA, CountB, CountC, DATE *
CountA is when PRODUTO is equal to 1.
CountB is when PRODUTO is > than 1.
CountC is when PRODUTO has both 1 and > 1 in the same PRENUMERO.
I joined the tables like this:

SELECT DISTINCT
b.[Autoreg],
a.[PRENUMERO],
b.[PRENUMERO],
b.[PRODUTO]
FROM
b.[VendasPOS_Linhas]
JOIN a
ON b.[PRENUMERO]=a.[PRENUMERO]
WHERE
a.[DATA] > '2015-06-01 00:00:00.000' AND
a.[Armazem] = '111'

And this is the result:

So if I do [PRENUMERO] = '1' (for CountA) the result should be for example 1000 and if I do [PRENUMERO] > '1' (for CountB) the result should be for example 1100 and the CountC should be the rest (667). But I do not know how to do it.
As you can see in the line 11 and 12, they have the same PRENUMERO, but the PRODUTO is 1 and the other is 10900... so this is for CountC. If the PRENUMERO is the same (several exactly PRENUMERO) but the PRODUTO is 1 (CountA (like line 8 and 9)) or >1 (CountB) this count only as 1 (DICTINCT here?)
(IF PRODUTO = 1 THEN CountA; IF PRODUTO >1 THEN CountB)
EDIT:
So I did this:

SELECT
    (SELECT
    COUNT(DISTINCT [B].[PRENUMERO])
FROM
    [B]
JOIN    [A]
ON    [B].[PRENUMERO] = [A].[PRENUMERO]
WHERE
    [A].[DATA] > '2015-06-01 00:00:00.000' AND
    [A].[Armazem] = '454' AND
    [B].[PRODUTO] > '1') AS X,
    (SELECT
    COUNT(DISTINCT [B].[PRENUMERO])
FROM
   [B]
JOIN    [A]
ON    [B].[PRENUMERO] = [A].[PRENUMERO]
WHERE
    [A].[DATA] > '2015-06-01 00:00:00.000' AND
    [A].[Armazem] = '454' AND
    [B].[PRODUTO] = '1') AS Y,
    (SELECT COUNT([A].[PRENUMERO]) from A where DATA> '2015-06-01 00:00:00.000' and Armazem = '454') AS Total

And this is the result:

But I think this is wrong because it's counting the CountC as well.
For example:
If the same PRENUMERO as 1 and >1 it belongs to CountC. What can I do to not count does? (How do I check if PRENUMERO doesn't have 1 and >1 (diferent rows))

A: MySQL is pretty handy for this, since it's very forgiving of type conversions:
SELECT SUM(PRODUTO = 1) AS countA,
    SUM(PRODUTO > 1) AS countB,
    SUM((PRODUTO = 1) AND (PRENUMERO > 1)) AS countC
...

MySQL will take the boolean true/false of the = and > tests, convert them to integer 0 and 1, and them sum up those integers, giving you your counts.

A: Well If I understand you are trying to do the next.

*

*COUNT A -> Only products=1

*COUNT B -> Only products>1

*COUNT A -> products=1 AND Prenumero>1
SELECT SUM(if(producto)=1,1,0) AS COUNT_A
  ,SUM(if(producto)>1,1,0) AS COUNT_B
  ,SUM((if(producto)=1 AND PRENUMERO>1),1,0) AS COUNT_C
  ,a.DATA
FROM b
JOIN a USING(PRENUMERO)
    WHERE a.DATA > '2015-06-01 00:00:00.000'
      AND a.Armazem = '111' AND b.producto>0
GROUP BY a.DATA;
You are sharing information between count A and count C, for discating this you could use the alias from each tabla to validate by example
a.prenumero>1 AND b.prenumero =1

but if this is your inner join field always will have the same value for both tables
Regards.

A: Solution
> SELECT    COUNT(DISTINCT CASE WHEN MinProduto = 1 AND MaxProduto = 1
> THEN PRENUMERO END) AS QtdCombustivel
>          ,COUNT(DISTINCT CASE WHEN MinProduto <> 1 AND MaxProduto <> 1 THEN PRENUMERO END) AS QtdLoja
>          ,COUNT(DISTINCT CASE WHEN MinProduto = 1 and MaxProduto <> 1 THEN PRENUMERO END) AS QtdMisto
>          ,COUNT(DISTINCT PRENUMERO) AS Total FROM (
>     SELECT  [VendasPOS_Linhas].[PRENUMERO]
>             ,MIN([VendasPOS_Linhas].[PRODUTO])            AS MinProduto
>             ,MAX([VendasPOS_Linhas].[PRODUTO])            AS MaxProduto
>     FROM    [VendasPOS_Linhas]
>     INNER JOIN [VendasPOS_Cabecalhos]
>        ON    [VendasPOS_Linhas].[PRENUMERO] = [VendasPOS_Cabecalhos].[PRENUMERO]
>     WHERE    UPPER([VendasPOS_Cabecalhos].[FACT_VD]) IN ('T','F','C')
>       AND    [VendasPOS_Cabecalhos].[DATA] > '2015-06-11 00:00:00.000'
>       AND    [VendasPOS_Cabecalhos].[Armazem] = '404'
>     GROUP BY [VendasPOS_Linhas].[PRENUMERO] , [VendasPOS_Cabecalhos].[DATA] )Res


text:
Q: Android scribe-java doesnt provide token for magento Such a situation , i use scribe-java (https://github.com/fernandezpablo85/scribe-java) to authenticate through Oauth ,and always get such an error:
     org.scribe.exceptions.OAuthConnectionException: There was a problem while creating a connection to the remote service.
on this line of code

        Token requestToken = service.getRequestToken();

Please Help who can or solved such an issue.
  Here my main activity :
    public class MainActivity extends Activity {
            final String MAGENTO_API_KEY = "key";
            final String MAGENTO_API_SECRET = "secret";
            final String MAGENTO_REST_API_URL = "https://www.myweb.com/api/rest";

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

        doAsyncTask doIt = new doAsyncTask();
            doIt.doInBackground();
    }
    public void testOauth(){
        OAuthService service = new ServiceBuilder()
                .provider(MagentoThreeLeggedOAuth.class)
                .apiKey(MAGENTO_API_KEY)
                .apiSecret(MAGENTO_API_SECRET)
                .callback("SUCCESS")
                .debug()
                .build();
        Scanner in = new Scanner(System.in);
        System.out.println("Magento'srkflow");
        System.out.println();
        // Obtain the Request Token
        System.out.println("FetchingRequest Token...");
        Token requestToken = service.getRequestToken();
        System.out.println("GotRequest Token!");
        System.out.println();

        // Obtain the Authorization URL
        System.out.println("FetchingAuthorization URL...");
        String authorizationUrl = service.getAuthorizationUrl(requestToken);
        System.out.println("GotAuthorization URL!");
        System.out.println("Nownd authorize Main here:");
        System.out.println(authorizationUrl);
        System.out.println("Ande the authorization code here");
        System.out.print(">>");
        Verifier verifier = new Verifier(in.nextLine());
        System.out.println();

        // Trade the Request Token and Verfier for the Access Token
        System.out.println("TradingRequest Token for an Access Token...");
        Token accessToken = service.getAccessToken(requestToken, verifier);
        System.out.println("GotAccess Token!");
        System.out.println("(if curious it looks like this: "
                + accessToken + " )");
        System.out.println();

// Now let's go and ask for a protected resource!
            OAuthRequest request = new OAuthRequest(Verb.GET, MAGENTO_REST_API_URL+ "/products?limit=2");
            service.signRequest(accessToken, request);
            Response response = request.send();
            System.out.println();
            System.out.println(response.getCode());
            System.out.println(response.getBody());
            System.out.println();
     /*   OAuthRequest request = new OAuthRequest(Verb.POST, MAGENTO_REST_API_URL+"/customers");
        request.addHeader("Content_Type", "text/xml");//this is a nasty bug in the current Magento implementation...we have to sent over
        final String user = "<!--?xml version=\"1.0\"?-->" +
                "<magento_api>" +
                "<firstname>Gerardo</firstname>" +
                "<lastname>Martinez</lastname>" +
                "<password>123123q</password>" +
                "<email>jerry@example.com</email"+
        "<website_id>1</website_id>" +
                "<group_id>1</group_id>" +
                "</magento_api>";
        request.addPayload(user);
        service.signRequest(accessToken, request);
        Response response = request.send();
        System.out.println();
        System.out.println(response.getCode());
        System.out.println(response.getBody());*/

    }
    public class doAsyncTask extends AsyncTask<String,Void,Boolean>
        @Override
        protected Boolean doInBackground(String... params) {

            testOauth();

            return null;
        }
    }

    public static final class MagentoThreeLeggedOAuth extends DefaultApi10a {
        private static final String BASE_URL = "https://www.myweb.com/";

        @Override
        public String getRequestTokenEndpoint() {
            return BASE_URL + "oauth/initiate";
        }

        @Override
        public String getAccessTokenEndpoint() {
            return BASE_URL + "oauth/token";
        }

        @Override
        public String getAuthorizationUrl(Token requestToken) {
            return BASE_URL + "admin/oauth_authorize?oauth_token="
                    + requestToken.getToken(); //this implementation is for admin roles only...
        }

        }

    }

Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.example.myapplication" >

    <uses-permission android:name="android.permission.INTERNET" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>

</manifest>

A: In MagentoThreeLeggedOAuth.class, change the BASE_URL to your base url.
Instead of using AsyncTask, you can write that code in onCreate() method, and include following lines to your onCreate() method :
StrictMode.ThreadPolicy policy = new
StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

A: I think may be error at  OAuthService service, you sure that's contain value of MAGENTO API KEY & MAGENTO API_SECRET exactly.
and when registering the application, you also need to define the CALLBACK_URL, to  be redirected after successfully authorizes.
Ex:
service = new ServiceBuilder()
            .provider(MagentoThreeLeggedOAuth.class)
            .apiKey(Contants.ConsumerKey)
            .apiSecret(Contants.ConsumerSecret)
            .callback(Contants.URL_CALLBACK)
            .build();

refer standard Scribe in java at here : example scribe-java-android
Good luck ^^


text:
Q: CoordinatorLayout custom behavior at right of Toolbar with AppBarLayout Based on this tutorial, https://github.com/saulmm/CoordinatorBehaviorExample,I am trying to create an application which have a circle image that scrolls up to the Right of Toolbar and when scrolling down goes to the middle of the expanded AppBarLayout.
How to make it move to right of Toolbar with above mentiond behaviour and animation.

A: AppBarTranslateScaleBehavior will help you achieve such a behavior.


text:
Q: Don't want to use columns in the COUNT which are NULL I have asked a question with the same query earlier but this time the question is different so I am posting another question. Below is the sql stored procedure query.
SELECT ROW_NUMBER() OVER (ORDER BY [PostedDate] Desc)AS RowNumber,[Products].[Id], [Name], [Description], [PostedDate],
       ISNULL(AVG([Rating].[RatingValue]), 0) AverageRating, COUNT([Rating].[RatingValue]) RatingCount
       INTO #DealResults1
       FROM [Products]
       LEFT OUTER  JOIN [Rating] ON [Product].[Id] = [Rating].[ProductId]
       WHERE [City] = CASE WHEN @CityId IS NULL THEN [City] ELSE @CityId END
       AND [Description] IS NOT NULL
       Group by [Products].[Id], [Name], [Description], [PostedDate]
       ORDER BY [PostedDate] Desc

This is the query for 1 day. I have changed the table structure and now it is like this,
Id      Rating_Monday      Rating_Tuesday        Rating_Wednesday .......
 1            3.0                NULL                    NULL
 2            3.5                NULL                    NULL
 3            NULL               2.0                     NULL
 4            NULL               3.0                     NULL
 5            NULL               1.5                     NULL
 6            NULL               NULL                    1.0
 7            NULL               NULL                     2.5
 8            NULL               NULL                     4.5

On Monday, value for all other days will be Null. Now for Monday the rating selected is Rating_Monday. Everything works fine. In the above query there are two important parts which are,
ISNULL(AVG([Rating].[Rating_Monday]), 0) AverageRating
COUNT([Rating].[Rating_Monday]) RatingCount

Average is selected absolutely fine but RatingCount is wrong because it is selected according to row count and does not check for the Null value.

A: COUNT(expression) evaluates expression for each row in a group and returns the number of nonnull values.
You may look into using the OVER clause : COUNT(EmployeeID) OVER (PARTITION BY DepartmentID) AS EmployeesPerDept
See COUNT (Transact SLQ) for more information.

A: Try this for the count:
sum(case when [Rating].[Rating_monday] is null then 0 else 1 end)

A: Using a case can solve this.
SELECT ROW_NUMBER() OVER (ORDER BY [PostedDate] Desc)AS RowNumber,[Products].[Id], [Name],  [Description], [PostedDate],
   ISNULL(AVG([Rating].[RatingValue]), 0) AverageRating,
   SUM(case  when (Rating.RatingValue) is null then 0 else 1 END) RatingCount
   INTO #DealResults1
   FROM [Products]
   LEFT OUTER  JOIN [Rating] ON [Product].[Id] = [Rating].[ProductId]
   WHERE [City] = CASE WHEN @CityId IS NULL THEN [City] ELSE @CityId END
   AND [Description] IS NOT NULL
   Group by [Products].[Id], [Name], [Description], [PostedDate]
   ORDER BY [PostedDate] Desc

A: To count use condition aggragate logic.
Case statement will convert your NULL values to 0 on that put a SUM aggregate which will help you to count the rows only those are NOT NULL
SELECT Row_number()OVER (ORDER BY [PostedDate] DESC)        AS RowNumber,
       [Products].[Id],
       [Name],
       [Description],
       [PostedDate],
       Isnull(Avg([Rating].[RatingValue]), 0) AverageRating,
       Sum(CASE WHEN [Rating].[Rating_monday] IS NULL THEN 0 ELSE 1 END) RatingCount
INTO   #DealResults1
FROM   [Products]
       LEFT OUTER JOIN [Rating]
                    ON [Product].[Id] = [Rating].[ProductId]
WHERE  [City] = CASE WHEN @CityId IS NULL THEN [City] ELSE @CityId END
       AND [Description] IS NOT NULL
GROUP  BY [Products].[Id],
          [Name],
          [Description],
          [PostedDate]
ORDER  BY [PostedDate] DESC


text:
Q: Making a copy of a object pandas column as a category type giving warning I'm making a copy of a pandas object column into a separate ordered column but I'm getting a warning and haven't figured out for the life of me how to do it the correct way.
I can't post the entire data frame up but here is the syntax I'm using:
marriage_cat_type = CategoricalDtype(categories= ['M_22', 'M_23', 'M_24', 'M_25', 'M_26', 'M_27', 'M_28', 'M_29', 'M_30'
                                                  , 'M_31', 'M_32', 'M_33', 'M_34', 'M_35', 'M_36', 'M_37', 'M_38', 'M_39'
                                                  , 'M_40', 'M_41', 'M_42', 'M_43', 'M_44', 'M_45', 'M_46', 'M_47', 'M_48'
                                                  , 'M_49', 'M_50', 'M_51', 'M_52', 'M_53', 'M_54', 'M_55', 'M_56', 'M_57'
                                                  , 'M_58', 'M_59', 'M_60', 'M_61', 'M_62', 'M_63', 'M_64', 'M_65', 'M_66'
                                                  , 'M_67', 'M_68', 'M_69', 'M_70', 'M_71', 'M_72', 'M_73', 'M_74', 'M_75'
                                                  , 'M_76', 'M_77', 'M_78', 'M_79', 'M_80', 'M_81', 'M_82', 'M_999', 'S_18'
                                                  , 'S_19', 'S_20', 'S_21', 'S_22', 'S_23', 'S_24', 'S_25', 'S_26', 'S_27'
                                                  , 'S_28', 'S_29', 'S_30', 'S_31', 'S_32', 'S_33', 'S_34', 'S_35', 'S_36'
                                                  , 'S_37', 'S_38', 'S_39', 'S_40', 'S_41', 'S_42', 'S_43', 'S_44', 'S_45'
                                                  , 'S_46', 'S_47', 'S_48', 'S_49', 'S_50', 'S_51', 'S_52', 'S_53', 'S_54'
                                                  , 'S_55', 'S_56', 'S_57', 'S_58', 'S_59', 'S_60', 'S_61', 'S_62', 'S_63'
                                                  , 'S_64', 'S_65', 'S_66', 'S_67', 'S_68', 'S_69', 'S_70', 'S_71', 'S_72'
                                                  , 'S_73', 'S_74', 'S_75', 'S_77', 'S_79', 'S_999'], ordered = True)

coll_train['marriage_statusXage_codes'] = coll_train['marital_statusXage2'].astype(marriage_cat_type)

I'm getting this warning.

C:\ProgramData\Anaconda3\lib\site-packages\ipykernel_launcher.py:2:
  SettingWithCopyWarning:  A value is trying to be set on a copy of a
  slice from a DataFrame. Try using .loc[row_indexer,col_indexer] =
  value instead
See the caveats in the documentation:
  http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy

And I've tried this resulting in failure:

coll_train['marriage_statusXage_codes'] = coll_train.loc[:,
  'marital_statusXage2'].astype(marriage_cat_type)

Can anyone point me in the right direction?

A: This is a chained assignment issue.  That may be manipulated by pd.set_option('chained_assignment',None|'warn'|'raise').
The warnings are turned on, and Pandas does not like coll_train.
There are a couple options:  Make sure coll_train is the source dataframe you intend to modify (which you are doing by placing a new column named marriage_statusXage_codes in it).  If it is, and Pandas is wrong, set pd.set_option('chained_assignment',None). Can Pandas be wrong about that? I don't know.
Here is an illustration of setting a value on a slice.
import pandas as pd
from pandas.compat import StringIO

print(pd.__version__)

csvdata = StringIO("""date,LASTA,LASTB,LASTC
1999-03-15,2.5597,8.20145,16.900
1999-03-31,2.7724,7.73057,16.955
1999-04-01,2.8321,7.63714,17.500
1999-04-06,2.8537,7.63703,17.750""")

df = pd.read_csv(csvdata, sep=",", index_col="date", parse_dates=True, infer_datetime_format=True)

pd.set_option('chained_assignment','warn')

a_slice = df['1999-03-31':'1999-04-01']
print(id(df), id(a_slice))
# generates the warning
a_slice['LASTA'] = 10
# original does not have the data set on a slice!
print(df[df['LASTA'] == 10]['LASTA'].any())

# create a new object to which values can be set, no warning.
a_slice = a_slice.copy()
a_slice['LASTA'] = 10
print(a_slice[a_slice['LASTA'] == 10]['LASTA'].any())

Results
0.20.3
(4549520208, 4594637776)
slicecopy.py:20: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  a_slice['LASTA'] = 10
False
True


text:
Q: How to scroll whole visible page down to an anchor with a smooth effect (Scriptaculous or jQuery)? I want to create an navigation with anchors. By clicking on a navigation link, the whole visible page should scroll down to the clicked anchor.
The most important is the following structure of the page.
--------------- (Begin visible browser area)
NAV1 nav2 nav3

content
--------------- (Begin/end visible browser area)
nav1 NAV2 nav3

content
--------------- (Begin/end visible browser area)
nav1 nav2 NAV3

content
--------------- (end visible browser area)

Finally all content is in a single document and the height of the current page (selected by the nav-item) has to be calculated (with a JS Library). I prefer PrototypeJS/Scriptaculous and jQuery.
The scroll effect should be a smooth slide/ effect.
Chris

A: If you want a jQuery solution, use ScrollTo, and if all you need is anchor-based animations implement the associated LocalScroll plugin.
If you want the content panes to take up the entire visible browser area, you can set that dynamically at page load (and on browser resize) with jQuery as well.  There's a great explanation of the "height" method here.

A: See: Effect.ScrollTo
link

A: I think maybe you could use this scroller: http://ruwix.com/simple-javascript-page-scroll-slider-jquery-scrollto-function-label-end
It's the shortest I found so far and it's really simple. Unfortunately it scrolls a fix amount of pixels, not to a label but you could use its idea.


text:
Q: QTextEdit.find() doesn't work in Python Simple code demonstrating the problem:
#!/usr/bin/env python

import sys
from PyQt4.QtCore import QObject, SIGNAL
from PyQt4.QtGui import QApplication, QTextEdit

app = QApplication(sys.argv)

def findText():
    print(textEdit.find('A'))

textEdit = QTextEdit()
textEdit.show()
QObject.connect(textEdit, SIGNAL('textChanged()'), findText)
sys.exit(app.exec_())

After typing 'A' into the window, find('A') still returns False.
Where is the problem?

A: The problem is the position of the cursor in the window.
By default - unless you specify some flags to be passed to the find() function, the search only happens forward (= from the position of the cursor onwards).
In order to make your test work, you should do something like this:

*

*Run the program.

*Go to the window and type BA

*Move your cursor to the beginning of the line

*Type C
This way you will have in the window the string CBA, with the cursor between C and B and the string onto which the find() method will work returning True will be BA.
Alternatively you can test this other version of your code that has the backward flag set.
#!/usr/bin/env python
# -*- coding: utf-8  -*-

import sys
from PyQt4.QtCore import QObject, SIGNAL
from PyQt4.QtGui import QApplication, QTextEdit, QTextDocument

app = QApplication(sys.argv)

def findText():
    flag = QTextDocument.FindBackward
    print(textEdit.toPlainText(), textEdit.find('A', flag))

textEdit = QTextEdit()
textEdit.show()
QObject.connect(textEdit, SIGNAL('textChanged()'), findText)
sys.exit(app.exec_())


text:
Q: Prove that $\frac{1}{2}+\frac{2}{2^2}+\frac{3}{2^3} +...+ \frac{n}{2^n} = 2 - \frac{n+2}{2^n} $ I need help with this exercise from the book What is mathematics? An Elementary Approach to Ideas and Methods. Basically I need to proove:
$$\frac{1}{2}+\frac{2}{2^2}+\frac{3}{2^3} +...+ \frac{n}{2^n} = 2 - \frac{n+2}{2^n} $$
$i)$ Particular cases
$ Q(1) = \frac{1}{2} ✓ $ ---------- $ P(1) = 2 - \frac{1+2}{2^1}  = \frac{1}{2} ✓ $
$+ = 1 ✓ (=Q(1)+Q(2))$
$ Q(2) = \frac{2}{4}(=\frac{1}{2})$----$P(2) = 2 - \frac{2+2}{2^2} = 1 $ ✓
$ii)$ Hypothesis
$$F(k)=\frac{1}{2}+\frac{2}{2^2}+\frac{3}{2^3} +...+ \frac{k}{2^k} = 2 - \frac{k+2}{2^k} $$
$iii)$ Proof
$P1 | F(k+1) = ( 2 -\frac{k+2}{2^k} ) + ( \frac{k+1}{2^{k+1}}) = 2 - \frac{k+3}{2^{k+1}}  $
$P2 | \frac{2^{k+1}-k-2}{2^k} + \frac{k+1}{2^{k+1}} = \frac{2^{k+2}-k-3}{2^{k+1}} $
$P3 | \frac{2^{2k+2}-2^{k+1}K-2^{k+2}+2^kk+2k}{2^{2k+1}} = \frac{2^{k+2}-k-3}{2^{k+1}} $
$P4 | \frac{2(2^{k+1}-2^kk-2^{k+1}-2^{k-1}k+k)}{2^{k+1}} = \frac{2^{k+2}-k-3}{2^{k+1}} $
I get stuck here; if you could help me, that would be really kind.
Thanks in advance.

A: You don't need any induction for this. This Series is simple AGP. Procedure for solving these series is assume
$$s=\frac{1}{2}+\frac{2}{2^2}+\frac{3}{2^3}.....\frac{n-1}{2^{n-1}}+\frac{n}{2^n}$$ Now multiply whole series by $\frac{1}{2}$ and write the whole series as one term shifted $$\frac{s}{2}= \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \frac{1}{2^2}+\frac{2}{2^3}+\frac{3}{2^4}......\frac{n-1}{2^{n}}+\frac{n}{2^{n+1}}$$ Second series should be subtracted from first in such a way that terms which has same powers of $2$ comes togethar. Now subtract series $$\frac{s}{2}=\frac{1}{2}+\frac{1}{2^2}+\frac{1}{2^3}......\frac{1}{2^{n}}-\frac{n}{2^{n+1}}$$ First n terms are of GP and can be written as $(1-\frac{1}{2^n})$, so $\frac{s}{2}=1-\frac{n+2}{2^{n+1}}$ . Now multiply with $2$ so as to get the correct expression for s $$s=2-\frac{n+2}{2^{n}}$$ Hence proved without induction.

A: In $P2$ you have made a misktake. It will be, $$\dfrac{2^{k+1}-k\color{red}{-}2}{2^k}+\dfrac{k+1}{2^{k+1}}=\dfrac{2^{k+2}-k\color{red}{-}3}{2^{k+1}}$$
Now if you simplify LHS then,
 $$\dfrac{2^{k+2}-2k-4+k+1}{2^{k+1}}=\dfrac{2^{k+2}-k-3}{2^{k+1}}=2-\dfrac{k+3}{2^{k+1}}$$and you are done.


text:
Q: Python: displaying an image as a background process? I am using scikit-image, and the following shows what I'm doing, in an ipython console:
import skimage.io as io
import skimage.viewer.viewers.core as sv
im = io.imread('image.jpg')
sv.ImageViewer(im).show()

This works well, except that the viewer runs as a foreground process, which means that I can't access the ipython shell until I've closed the viewing window.  I like this viewer; for a grayscale image at least, the cursor shows the gray level and the indices of the current pixel.  But I would like to be able to both display the image, and to continue work in the console.  How can I best do this?

A: Worked it out!  Just need to do it in two stages (as per the documentation); first
from skimage.viewer import ImageViewer

and then
fs = ImageViewer(f)
fs.show()

This works fine (except for a blank figure window which is created with the ImageViewer command).

A: Try launching IPython with:
ipython --gui=qt4


text:
Q: The structure of a matrix I am a complete noob at C (<1 week) and I'm trying to get a grasp how to work on it, although I'm familiar with programming in other languages. As a first goal, I wanted to write a function to do Gauss reduction on a matrix. I have no problem with the algorithm, but it turned out I do not know how to represent a matrix. For simplicity, let me assume that we work with float entries.
The first naif way would be to use an array of arrays like
float naifMatrix[3][3] = {
    {2, 1, 3},
    {0, -1, 4},
    {1, 3, 0}
};

The problem is that you cannot pass such an object as an argument without knowing the dimensions a priori (of course I want to be able to use matrices of arbitrary size, which is not known at compilation time). One does not see this problem when working with vectors and representing them as arrays. If I do
float vector[3] = {1, 2, 3};
norm(vector);

it will work, provided I declare norm like
norm(float * vector);

When vector is passed, it is converted to &vector[0], and not much information is lost (basically one has to keep track of the length). But I cannot just call
gaussReduction(naifMatrix);

and declare gaussReduction with
gaussReduction(float ** naifMatrix);

because naifMatrix is converted (and rightly so) to a pointer to an array of floats, not in a pointer to a pointer. Since I do not know how big this array will be, I do not see a way to declare gaussReduction.
Of course I could cheat by passing a pointer to a void, but before dereferencing it, I would need to cast it to the right type (float[3] *), which, again, I do not know a priori. Moreover it seems to me that by abusing of void * one defeats one of the purposes of using C over other languages, which is a strict type checking.
The best solution I have found so far is to use a struct. A matrix is basically given by the list of its entries and the two dimensions. So I can do
struct matrix {
    float * begin;
    int rows, columns;
};

and use it as
struct matrix matrix = {&naifMatrix[0], 3, 3};

The problem is that this is still annoying. First it is akward to get a struct matrix from a double array, and second one has to give the dimensions explicitly. I would be happy with wrapping this with a sort of "constructor" function, like
struct matrix matrix = Matrix(naifMatrix);

but I cannot do this for two reasons. First, I have the same problem as above in passing naifMatrix as argument to a function. Second, even if I could pass it,  I would get a pointer, and thus I would not be able to get information on the dimensions (in this case, that both are 3).
Is there a more sensible way to pass around and manipulate the datum of a matrix?

A: C99 added variable-length arrays to the language:
_Bool gaussReduction(size_t rows, size_t cols, float matrix[rows][cols]);

If you have the definition
float naifMatrix[3][3] = {
    {2, 1, 3},
    {0, -1, 4},
    {1, 3, 0}
};

you can get at the dimensions via
size_t rows = sizeof naifMatrix / sizeof *naifMatrix;
size_t cols = sizeof *naifMatrix / sizeof **naifMatrix;

You can use macros to minimize repetition. Using
#define rowsof(MATRIX) (sizeof (MATRIX) / sizeof *(MATRIX))
#define colsof(MATRIX) (sizeof *(MATRIX) / sizeof **(MATRIX))
#define matrixarg(MATRIX) rowsof(MATRIX), colsof(MATRIX), (MATRIX)

you'd end up with
gaussReduction(matrixarg(naifMatrix));

or, using a compound literal instead of a variable, with
gaussReduction(matrixarg(((float [3][3]){
    {2, 1, 3},
    {0, -1, 4},
    {1, 3, 0}
})));

Using a variable-length array has the same performance characteristics as the equivalent C90 code - the only thing you'll gain is nicer syntax:
// C99:
_Bool gaussReduction(size_t rows, size_t cols, float matrix[rows][cols])
{
    // size_t i = ..., j = ...
    float x = matrix[i][j];

/* C90: */
int gaussReduction(size_t rows, size_t cols, float *matrix)
{
    /* size_t i = ..., j = ... */
    float x = matrix[i * cols + j];

A: If you define thus:
float naifMatrix[][] = {
    {2, 1, 3},
    {0, -1, 4},
    {1, 3, 0}
};

You should have a pointer to an array of pointers. Then you can use
gaussReduction(float ** naifMatrix);

My C is rusty, though.


text:
Q: Unexpected text size staircase effect while looping database I just created the v.2 of my database requesting system. However, for some reason I have this "Staircase effect", it prints out the data but then it prints it over and over and over and over again increasing the size of the font. What is this?! My code:
$query=$db->prepare("SELECT post_id, title, body, category FROM posts INNER JOIN categories ON categories.category_id");
    $query->execute();
    $query->bind_result($post_id, $title, $body, $category);
while($query->fetch()):?>

<?php echo $title?>

<?php echo $body?>

    <p2>Category:</p2><?php echo $category?>
    <?php endwhile ?>

You can see the effect @ http://wrya.x10host.com/highflyer/index.php
Can anyone help me fix this and explain to me what I did wrong?

A: Does it help to move the
 one line up, inside your while-loop? Like so:
$query=$db->prepare("SELECT post_id, title, body, category FROM posts INNER JOIN categories ON categories.category_id");
$query->execute();
$query->bind_result($post_id, $title, $body, $category);
while($query->fetch()):?>

<?php echo $title?>

<?php echo $body?>

        <p2>Category:</p2><?php echo $category?>

<?php endwhile ?>

A: What exactly is a p2 tag?
Pretty sure that's not a valid HTML tag in any DOCTYPE. The easiest way to see the problem is to view the source in Firefox, it will highlight in red any unclosed tags and I'd hazard a guess that's the problem.
You also have lots of opening article tags inside your loop, but the closing tag is outside.


text:
Q: Delete localStorage, databaseStorage for a tab in Chrome/Chromium I want to delete all storage data from an tab when it's going to close. I found an extension which deletes cookies. But as I am a total newbie in extension writing I would like a hint where to look in the docs localStorage purge.
When a tab is removed the background.js gets the callback onRemoved with tabId. I can get the Tab object for the id.. However I have yet to find how one should remove items from localStorage or databaseStorage.
The w3c docs mention localStorage.clear(). How do I trigger this in the right context (in the tab and not in the background process)?
UPDATE: to clarify the central goal, I am looking for a way to restrict or reconstruct calls of methods chrome.browsingData.removeLocalStorage/removeIndexedDB/removeWebSQL only onto the closed tab/domain
Thank you,
pingi

A: You can make use of the beforeunload event in JavaScript.
window.onbeforeunload = function()
{
localStorage.removeItem(key);
return '';
};

NOTE: The onbeforeunload method should return a string.


text:
Q: Qt TCP/IP communication only works locally, but gets lost in a network I've created two simple TCP/IP communication programs (server & client). It basically just sends and receives the same message over and over again.
However when I execute client and server on the same workstation everything runs fine. It is only then, when I execute the same programs via a lokal network that the server doesn't receive any incomming connection requests.
The firewall is disabled on both stations. Has anyone an idea what I'm missing out?
Here is the code

client.cpp
#include "client.h"
#include <QHostAddress>
#include <iostream>
#include <conio.h>

Client::Client(QObject* parent): QObject(parent)
{
connect(&client, SIGNAL(connected()), this, SLOT(startTransfer()));
connect(&client, SIGNAL(readyRead()), this, SLOT(receive()));
QHostAddress addr = QHostAddress("127.0.0.1");
client.connectToHost(addr, 5200);
}

Client::~Client()
{
client.close();
}

void Client::startTransfer()
{
client.write("Hello, world", 13);
send("start client communication");
}

void Client::send(const char *buffer)
{
    std::cout<<"OUT: "<<buffer<<std::endl;
    client.write(buffer,strlen(buffer));

}

void Client::receive()
{
    char temp[1024] = {0};
    int len = client.read(temp,client.bytesAvailable());
    std::cout<<"IN: "<< temp<<std::endl;
    send("client to server");
}

server.cpp
#include "theserver.h"
#include <iostream>
#include <conio.h>
using namespace std;

Server::Server(QObject* parent): QObject(parent)
{
connect(&server, SIGNAL(newConnection()), this, SLOT(acceptConnection()));
server.listen(QHostAddress::Any, 5200);
}

Server::~Server()
{
server.close();
}

void Server::acceptConnection()
{
    client = server.nextPendingConnection();
    if(client)
    {
        connect(client, SIGNAL(readyRead()), this, SLOT(receive()));
    }
}

void Server::startRead()
{
char buffer[1024] = {0};
client->read(buffer, client->bytesAvailable());
cout << "IN: "<<buffer << endl;

}

void Server::receive()
{
    char buffer[1024] = {0};

    client->read(buffer, client->bytesAvailable());
    cout << "IN: "<<buffer << endl;
}

void Server::sendData(const char* buffer)
{
    cout <<"OUT: "<<buffer<<endl;
    if(client)
        client->write(buffer);
}

I'm first initiating the server program following by the client

A: You need to use the remote machine's IP address to connect. Now you are always connecting to 127.0.0.1, which is the machine where the application is being run. That is why the connection is never made to a remote machine.


text:
Q: Using a text classifier model vectorized done using Tfidf with unigrams and bigrams I have the following data frame or a text classification problem:
 X = df['text'].apply(clean_text)

clean_text does some of the basic cleaning required for this particular case like removal of special characters, converting numeric values in the text to buckets etc. As a next step - I create a pipeline as shown below:
 text_clsf = Pipeline([('tfidf',TfidfVectorizer(use_idf=True,max_df=max_df,min_df=min_df,stop_words=stop_words,ngram_range=(1,2))),
                      ('clsf',LinearSVC(C=C))])

 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20)
 text_clsf.fit(X_train,y_train)

This model was tested using test data, and saved using pickle library
 pickle.dumps(text_clsf,open(file_path,'wb'))

Upon using this model on real world data, I use pickle again to load the model, and then for my real world text I apply cleaning using the same clean method as shown below.
 text_value = 'this is my real world sample text to predict'
 text_cleaned = clean_text(text_value)
 text_clsf = pickle.loads(open(filepath,'rb'))

I have a concern regardin the next step: Can I code, as shown below, directly to do the prediction? I haven't created bigrams here though the tfidf vectorizer was given ngram_range(1,2), text_cleaned contains just the cleaned text.
     text_clsf.predict([text_cleaned])
Or is it that the model text_clsf by itself takes care of creating bigrams.


text:
Q: How to create custom dashed line I want to create a component where it has a dashed line that looks like this, basically I want to add a border-radius to each dash, that make it curves like in the picture.

Here what I try so far:

.line {
  height: 12px;
  background: repeating-linear-gradient(to right,#52cc7a 0,#52cc7a 6px,transparent 6px,transparent 18px)
}

A: You can approximate it with a radial gradient:

.line {
  height: 12px;
  background:
   radial-gradient(4px 8px, #52cc7a 80%,transparent 87%) 0 0/20px 100%;

}

A: We can draw several background images. Using circles for the top and bottom 'roundy' bits and a rectangle in the middle we can achieve something like in this snippet - the circles have been given different colors just to show what is going on, and the size has been magnified so we can check more easily on alignment.
I'm on a very old screen and the edges look a bit jagged but I'm hoping on a better display like retina it will seem smoother.

.line {
  height:100px;
  width: 100vw;
  background-image: radial-gradient(cyan 0, cyan 12px, transparent 12px, transparent 100%),radial-gradient(magenta 0, magenta 12px, transparent 12px, transparent 100%),linear-gradient(to right,#52cc7a 0,#52cc7a 24px,transparent 24px,transparent 100%);
  background-size: 60px 60px, 60px 60px, 60px 60px;
  background-position: -18px -15px, -18px 39px, 0 12px;
  background-repeat: no-repeat no-repeat, no-repeat no-repeat, no-repeat no-repeat;
  }

Of course, there needs to be fiddling around with sizes to get the exact spacing you want, and some thinking about what should happen on small screens versus large ones, how does it all fit in with the font size and so on.
Anyway, here's a snippet with the colors the same and repeated background images.

.line {
          height:100px;
          width: 100vw;
          background-image: radial-gradient(#52cc7a 0, #52cc7a 12px, transparent 12px, transparent 100%),radial-gradient(#52cc7a 0, #52cc7a 12px, transparent 12px, transparent 100%),linear-gradient(to right,#52cc7a 0,#52cc7a 24px,transparent 24px,transparent 100%);
          background-size: 60px 60px, 60px 60px, 60px 60px;
          background-position: -18px -15px, -18px 39px, 0 12px;
          background-repeat: repeat no-repeat, repeat no-repeat, repeat no-repeat;
          }


text:
Q: Batchnorm using Tensorflow is causing Overfitting I am working on MINST style ASL( Americn Sign Language) recognition problem.
I am epereincing issues with Batchnorm using Tensorflow 2.0
When I use batchnorm I am seeing massive overfitting on validation dataset. See below
model = Sequential()
model.add(Flatten(input_shape =(784,)))
model.add(BatchNormalization())
model.add(Dense(40,activation = "elu", kernel_initializer = "he_normal"))
model.add(BatchNormalization())
model.add(Dense(30,activation = "elu", kernel_initializer = "he_normal"))
model.add(BatchNormalization())
model.add(Dense(30,activation = "elu", kernel_initializer = "he_normal"))
model.add(BatchNormalization())
model.add(Dense(100,activation = "elu", kernel_initializer = "he_normal",  kernel_regularizer = keras.regularizers.l2(0.001)))
model.add(Dense(30,activation = "elu", kernel_initializer = "he_normal"))
model.add(BatchNormalization())
model.add(Dense(25,activation = "softmax"))

Overfitting
But when I remove batchnorm I get perfect result.
model = Sequential()
model.add(Flatten(input_shape =(784,)))
#model.add(BatchNormalization())
model.add(Dense(40,activation = "elu", kernel_initializer = "he_normal"))
#model.add(BatchNormalization())
model.add(Dense(30,activation = "elu", kernel_initializer = "he_normal"))
#model.add(BatchNormalization())
model.add(Dense(30,activation = "elu", kernel_initializer = "he_normal"))
#model.add(BatchNormalization())
model.add(Dense(100,activation = "elu", kernel_initializer = "he_normal",  kernel_regularizer = keras.regularizers.l2(0.001)))
model.add(Dense(30,activation = "elu", kernel_initializer = "he_normal"))
#model.add(BatchNormalization())
model.add(Dense(25,activation = "softmax"))

Not overfitting
I am not able to understand why batchnorm is causing overfitting here as it supposed to remove the overfitting.
Will apperciate some help understanding this
Zion


text:
Q: Notificaciones para un portal web Estoy empezando a crear un apartado sencillo para las notificaciones de un portal web, estas notificaciones serán cuando se agregue un comentario o se genere un nuevo tramite, pero me he topado con un problema el cual es el siguiente.
Tengo mi base de datos en la cual utilizo una tabla llamada notificaciones para hacer las consultas que se muestran en el código.

            $sqlNotif = "SELECT * FROM notificaciones WHERE contador = '1' GROUP BY id DESC";
            $resultNotif = mysqli_query($conexion, $sqlNotif);
            while ($verNotif = mysqli_fetch_row($resultNotif)) {
                $datos = $verNotif[0] . "||" .
                    $verNotif[1] . "||" .
                    $verNotif[2] . "||" .
                    $verNotif[3] . "||" .
                    $verNotif[4] . "||" .
                    $verNotif[5] . "||" .
                    $verNotif[6];

            ?>

                            <?php
                            if ($verNotif[5] == "TRAMITE") {

                                echo $verNotif[2] . " generó un nuevo" . " $verNotif[5]" . " el día" . " $verNotif[4]" . " y le fue asignado el folio" . " $verNotif[1]";

                            } elseif ($verNotif[5] == "COMENTARIO") {
                                $sqlComent = "SELECT COUNT(*) FROM notificaciones WHERE contador = '1' AND (folio = '$verNotif[1]' AND tipo = 'COMENTARIO') GROUP BY folio";
                                $resultComent = mysqli_query($conexion, $sqlComent);
                                while ($verComent = mysqli_fetch_row($resultComent)) {
                                    $coment = $verComent[0];
                                }
                                echo $verNotif[2] . " agrego" . " $coment" . " Comentario(s)" . " al folio" . " $verNotif[1]";

                            }
                            ?>

El problema radica cuando imprimo dichos resultados en el portal web, como se muestra en la imagen, es correcto que agregue 4 comentarios en un folio pero necesito agruparlos, es decir, que no se muestren de esta manera:

Si no que solo se muestre una sola vez, ejemplo así:


text:
Q: Taylor series of a square matrix Let $A$ be a constant square matrix, $\Delta t$ is a scalar. I would imagine a taylor series of its exponential like this:
$$e ^{A\,\Delta t} = I + \sum_{n=1}^\infty \frac{(A\,\Delta t)^n}{n!} $$
Now if I want to approximate as a first order term only:
$e ^{A\,\Delta t} = I + A\,\Delta t$, I have to say that $\frac{(A\,\Delta t)^2}{2!}$ should be small. But $A$ is not a number but a matrix. What matrix norm should I use to say that $\frac{(A\,\Delta t)^2}{2!}$ is small?


text:
Q: Decomposition of direct image of a smooth morphism, Deligne's theorem, motives Let $f : X \to Y$ be projective and smooth morphism of complex algebraic varieties. Here we care about the algebraic topology of $X$ and $Y$, so use classical topology for simplicity.
I can take the constant sheaf $\mathbb{Q}_X$ and (derived) push it forward to get $f_* \mathbb{Q}_X \in D^b_c(Y,\mathbb{Q})$. There is a celebrated theorem of Deligne that $f_* \mathbb{Q}_X$ is semi-simple, i.e. isomorphic to a direct sum of its cohomology sheaves. The argument uses hard Lefschetz along the fibres. (It is also true that each summand is a semi-simple local system, as a polarizable VHS, however I want to ignore that extra piece of information below.)
Suppose I replace $\mathbb{Q}$ with $k := \mathbb{F}_p$.
Question: Is it true that $f_* k_X \in D^b_c(Y,k)$ is always semi-simple? That is, does it always split as a direct sum of its (not-necessarily semi-simple) cohomology sheaves.
I had always assumed the answer was no, but woke up this morning feeling unusually optimistic. (I have tried several times to produce a counter-example.) I understand that this is deep water, and I am happy with a heuristic answer either way (potentially using motives).

A: We can give many counterexamples to semisimplicity in positive characteristic using the observation that if the canonical morphism $k_Y\rightarrow f_*k_X$ in $D^b_c(Y,k)$ is split, then the induced morphism in $k$ cohomology must be injective: $$f^*:H^*(Y,k)\rightarrow H^*(X,k).$$
So we just need to cook up nontrivial elements in this kernel. For instance, take any nontrivial abelian cover $f:X\rightarrow Y$ of degree $p$. This is classified by an element $\alpha$ of $H^1(Y,\mathbb{Z}/p\mathbb{Z})$, and since this cover is the pullback of the universal degree $p$ cover along a morphism $Y\rightarrow B(\mathbb{Z}/p\mathbb{Z})$, we see that $\alpha$ vanishes in $H^1(X,\mathbb{Z}/p\mathbb{Z})$, since $E(\mathbb{Z}/p\mathbb{Z})$ is contractible.
For a more geometric example, let $E$ be an elliptic curve over $Y$, and $A$ an $E$ torsor over $Y$. Then this is classified up to homotopy by a map to $B(S^1\times S^1)\cong K(\mathbb{Z},2)\times K(\mathbb{Z},2)$. Since the total space $E(S^1\times S^1)$ is contractible, the associated classes $(\alpha,\beta)$ in $H^2(Y,\mathbb{Z})$ will lie in the kernel of $H^2(Y,\mathbb{Z})\rightarrow H^2(A,\mathbb{Z})$. Then one can reduce this mod $p$ and get counterexamples over a field if the orders of these elements aren't divisible by $p$.
Finally, one can use nonliftable projective bundles to give counterexamples, in line with Anonymous' suggestion. If $f:X\rightarrow Y$ is a (complex) dimension $n-1$ projective bundle, then its obstruction to being the projectivisation of a complex vector bundle is a class $\beta_f\in H^2(X,\mathbb{C}^*)\cong H^3(X,\mathbb{Z})$. Then one can check in the universal case of $u:U\rightarrow BPGL_n(\mathbb{C})$, we have $u^*(\beta_u)=0$, so this class $\beta_f$ is always in the kernel of the map:
$$H^3(Y,\mathbb{Z})\rightarrow H^3(X,\mathbb{Z}).$$
These examples have been written up in full detail in an upcoming paper, which should be coming to the arXiv soon.