Q: How do I get an iterator over the unique keys in a C++ multimap? I am using a std::multimap to map from a key to a set of matching values. I have a situation where I want to be able to list/iterate over the unique keys in the map.
How do I get an iterator of the unique keys in a C++ multimap?
Another option is using a map<K, set<V>>, but that requires more manual management.

A: If you expect the number of duplicate keys to be small, just keep incrementing the iterator until the key value changes. If you expect the number of duplicate keys to be large, just use upper_bound to get an iterator to the element with the next key value.


Q: Is it safe to expand my partition (unallocated space before the partition)? I have 13.1 GB of unallocated space before my main partition and guess what: Windows won't allow me to expand to it. I know how most of the stuff works and it's because there are files and important boot files at the beginning of the partition.
I am willing to use Easeus Partition Master 9.0.0 Server edition to resize my main partition and gain that additional 13 GB of additional space.
Last time I did that was a few years ago and I remember the operation completed succesfully but there were problems like security permissions issues and some other small issues after booting back to my Windows installation (probbly Vista).
So: How safe is it to take that additional 13 gb of space BEFORE my partition and add it to the main partition using Easeus partition master? Will it "BLOW UP" my Windows 7 installation?
Edit: What about GUIDs and saved file locations on the partition(s)/disk(s)? Will windows complain? I remember that some Windows components index files by their location on the disk/partition or am I wrong? Won't that be a problem in Windows 7?

A: Windows 2000/XP/Vista/7/8 computes partition identifier as 32-bit disk signature (found in MBR) + 64-bit partition offset (in bytes, from the start of the disk).
Partition identifier of Windows System Root Partition is stored in BCD (\Boot\BCD registry hive and \Boot\BCD.LOG registry log) and also in mount manager database (HKEY_LOCAL_MACHINE\SYSTEM\MountedDevices), physically stored in \Windows\System32\Config\SYSTEM and \Windows\System32\Config\SYSTEM.LOG.
So partition identifier of disk C: will change after your manipulations. Usually Windows is able to repair itself at boot time, but if it won't, you can fix both references using Emergency Boot CD, Mount & Boot Center: http://www.prime-expert.com/ebcd/

A: It's totally Safe, but before beginning the process check hard disk for any issue such as bad sector, integrity of file ,.....
So run this command from elevated command prompt:
chkdsk C: /f /scan

A: It should be safe to do this.  You should still do a full drive back up, then it doesn't matter what happens.


Q: Destructuring argument for key along with object in javascript How can I get the passed in object course along with the id key  using destructuring the argument as in following code snippet ?
...
return (

      {course.map(course => {
        return <Course key={course.id} course={course} />;
      })}

  );

For instance I've tried like(see below) this, but its not valid
...
return (

      {course.map(({id} = course) => {
        return <Course key={id} course={course} />;
      })}

  );

The object for reference
const course = [
    {
      name: "Half Stack application development",
      id: 1
    },
    {
      name: "Node.js",
      id: 2
    }

Are there any way to do this or is it not possible yet?

A: Destructure id and spread the rest
course.map( ({ id, ...item }) => (

 {item.foo}

))

A: You can't destruct an object into its an element and itself.
It could be better destruct item in the callback function like below.

console.log('-------Only get rest obj------');
const courses = [{ name: "Half Stack application development", id: 1 }, { name: "Node.js", id: 2 }];

courses.forEach(({id, ...item}) => console.log('rest obj:', item));

console.log('----Get full obj and destruct---------');

courses.forEach(item => {
  const { id } = item;
  console.log('id:', id);
  console.log('item:', item);
});

A: return (

      {course.map(item => {
        return <Course key={item.id} course={item} />;
      })}

  );

You are trying to use the course variable again inside map function.
Rename outer most variable from course to courses.
return (

      {courses.map(course => {
        return <Course key={course.id} course={course} />;
      })}

  );

A: Consider below example
return (

      {course.map(({ id, ...course }) => {
        return <Course key={id} course={course} />;
      })}

  );

It does gets us the id but course object does have all the keys of the original object(ie, it doesn't have the id now).


Q: First time using decorators, what am I missing? class User:
    def __init__(self):
       self.score = 0
       self.wins = 0
       self.losses = 0

    def tally(self, func):
        def wrapper_function(w):
            print("Wins: {}\nLosses: {}\nTotal Score: {}".format(self.wins, self.losses, self.score))
            return func(w)
        return wrapper_function()

    @tally
    def record_win(self, w=1):
        self.wins += w

user1 = User()
user1.record_win()

The error that I'm getting is: TypeError: tally() missing 1 required positional argument: 'func'
EDIT This post is different from the one here because in that post the decorator functions were not instance methods.. which I see now adds some peculiar requirements.

A: Your problem is that you are defining tally as an instance method, but it's really just a decorator function (it can't be called on an instance in any reasonable way). You can still define it in the class if you insist (it's just useless for instances), you just need to make it accept a single argument (the function to wrap), without self, and make the wrapper accept self (while passing along any provided arguments to the wrapped function):
class User:
    # ... other methods unchanged ...
    def tally(func):
        def wrapper_function(self, *args, **kwargs):  # Accept self + arbitrary arguments to make decorator useable on more functions
            print("Wins: {}\nLosses: {}\nTotal Score: {}".format(self.wins, self.losses, self.score))
            return func(self, *args, **kwargs)  # Pass along self to wrapped function along with arbitrary arguments
        return wrapper_function                 # Don't call the wrapper function; you have to return it so it replaces the decorated function

    @tally
    def record_win(self, w=1):
        self.wins += w

    # Optionally, once tally is no longer needed for new methods, but before dedenting out of class definition, do:
    del tally
    # so it won't stick around to appear as a possible method to call on instances
    # It's done all the work it needs to do after all

Removing the w argument in favor of *args, **kwargs means you don't need to specialize to specific function prototypes, nor duplicate the defaults of the function you're wrapping (if they don't pass the argument, the default will get used automatically).


Q: Hatcher Theorem 1.38 Example Hatcher's theorem 1.38 states that there is a correspondence between isomorphism classes of path-connected covering spaces $p: \tilde{X} \rightarrow X$ and conjugacy classes of subgroups of $\pi_1(X,x_0)$.
The proof claims that given a covering space the basepoint $\tilde{x_0}$ within $p^{-1}(x_0)$ corresponds to changing $p_*(\pi_1(\tilde{X},\tilde{x_0}))$ to a conjugate subgroup of $\pi_1(X,x_0)$.
What's an example of a case when the conjugate subgroup that it changes to is not equal to the subgroup itself? I'm looking for a specific example of an $X$ and $\tilde{X}$.

A: There is an example to your question in the Hatcher's book itself. Earlier in section 1.3 there is a table of covering spaces of the wedge sum $S^1\vee S^1$. With $X=S^1\vee S^1$ and $\tilde{X}$ the covering space of example $(3)$ and $(4)$ you have your example.


Q: Как получить переменные в php с ajax? Как получить доступ к переменной $datastring.
ХТМЛ КОД:
<form action="./js/reservations.php" method="post" class="reservationForm" id="reservationForm">

                        Choose medical department:

                         Your full name:

                        <input name="name" value="" id="name" class="inputtext required" size="40" type="text" />

                        Your email address:

                      <input name="email" value="" id="email" class="inputtext required" size="40" type="text" />

                        <input type="submit" value="MAKE APPOINTMENT" id="send" class="btn-send" />

                        <input name="date_in_input" value="" id="date_in_input" type="hidden" />

your selection not available

            </form>

Это присоединенный js код
jQuery(document).ready(function(){
tfuse_reservations_form();

                    });

function tfuse_reservations_form(){
var my_error;
jQuery("#send").bind("click", function(){

my_error = false;
jQuery("#reservationForm input, #reservationForm textarea, #reservationForm radio, #reservationForm select").each(function(i)
{
            var surrounding_element = jQuery(this);
            var value               = jQuery(this).attr("value");
            var check_for           = jQuery(this).attr("id");
            var required            = jQuery(this).hasClass("required");

            if(check_for == "email"){
                surrounding_element.removeClass("error valid");
                baseclases = surrounding_element.attr("class");
                if(!value.match(/^\w[\w|\.|\-]+@\w[\w|\.|\-]+\.[a-zA-Z]{2,4}$/)){
                    surrounding_element.attr("class",baseclases).addClass("error");
                    my_error = true;
                }else{
                    surrounding_element.attr("class",baseclases).addClass("valid");
                }
            }

            if(required && check_for != "email"){
                surrounding_element.removeClass("error valid");
                baseclases = surrounding_element.attr("class");
                if(value == ""){
                    surrounding_element.attr("class",baseclases).addClass("error");
                    my_error = true;
                }else{
                    surrounding_element.attr("class",baseclases).addClass("valid");
                }
            }

           if(jQuery("#reservationForm input, #reservationForm textarea, #reservationForm radio, #reservationForm select").length  == i+1){
                if(my_error == false){
                    jQuery("#reservationForm p.notice, #reservationForm #send").hide();
                    jQuery("#reservationForm p.sending").show();

                    var $datastring = "ajax=true";
                    jQuery("#reservationForm input, #reservationForm textarea, #reservationForm radio, #reservationForm select").each(function(i)
                    {
                        var $name = jQuery(this).attr('name');
                        $value = encodeURIComponent(jQuery(this).attr('value'));
                        $datastring = $datastring + "&" + $name + "=" + $value;
                    });

                jQuery.ajax({
                       type: "POST",

                       data: $datastring,
                          url: "./js/reservations.php",
                       success: function(response){
                           jQuery("#reservationForm p.sending, #reservationForm p.notice").hide();
                           if(response) {
                              alert('сообещние отправлено')
                           } else {
                              alert('нет')
                           }
                       }
                    });
                }
            }

        });
        return false;
});

}
В файле php
$name = $_POST['name'];
$email = $_POST['email'];
$date = $_POST['data'];

A: $datastring в данном случае будет вида:
$datastring={id: 1, name: "My name", mail: "my@mail.ru", };

в php-скрипт передаются переменные id, mail, name. Выдергивать их нужно из массива $_GET или $_POST - зависит от метода передачи
A: Вместо $datastring-a подставляете то, что вам нужно. Это не переменная, а селектором делается. Например, если у вас есть некое поле с id=test (<input id="test" value="mydata" />), то значение mydata берется вот так:
$('#test').val();

А ответный код с "succes"-а ловите.


Q: Block animations - how to cycle an array of UIImage I'm going the direction of block animations, having tried to implement multiple animations and an "on finish" event with UIImageView animations but failing.
I have a UIImage array, which I need to cycle backwards through, displaying as I go.  Here is what I have so far:
__block int i = 9;
[UIView animateWithDuration:4.0
                 animations:^{
                     self.fooView.image = fooImage[i];
                     [self.view addSubview:self.fooView];
                     i--;
                }
                 completion:NULL];

This does happily display the 9th element of fooImage[], but it doesn't iterate through the rest.
Is this a misunderstanding about what blocks can actually do in this context? I tried to also wrap a while loop, decrementing "i", but I ended up with the first element only (I sort of expected that).  How should one iterate through an array in this instance - perhaps have 9 different animation blocks?
Any tips will be gratefully received, and thanks for your time
sc.

A: Your animations completion handler is NULL, which means nothing is happened after animation is completed.
And it's strange to use animations block if you actually animate nothing. Animations won't wait 4 seconds before calling competition handler if there is nothing to animate.
__block int i = 9;
void(^process)(void(^recursive)());
process = ^(void(^recursive)()) {
    --i;
    [UIView animateWithDuration:4.0
                     animations:^{
                         NSLog(@"%d", i);
                     }
                     completion:^(BOOL finished) {
                         recursive(recursive);
                     }];
};
process(process);


Q: using TS\ES6 getters for accessing deep properties (like shortcut) Is it fine to use getters for accessign deep properties of a class property? Or there's a more delicate way to do this?
Example:

const myObject = {
  very: {
    deeply: {
      nested: {
        property: {
          with: {
            a: {
              long: {
                name: "hello world"
              }
            }
          }
        }
      }
    }
  }
};

class Sample {
  constructor(private myObj) {}

  get name(): string {
    return this.myObj.very.deeply.nested.property.with.a.long.name;
  }
}

Repo:
https://codesandbox.io/s/tses6-getters-as-a-shortcut-for-deep-object-properties-h6rgr


Q: Google Earth Engine: undefined value conversion I am using the Google Earth Engine API in Python. I am trying to reconvert undefined (i.e. null) values onto a value of choice. Inspired by a discussion here, my code is as follows:
import ee

ee.Initialize()
c = ee.ImageCollection('MODIS/006/MOD13Q1').filterDate('2003-12-19', '2004-01-19').select('NDVI')
p = ee.Geometry.Point([-8.802372,  41.722677])
data = c.getRegion(p, scale = 1000).getInfo()
print 'data=',data

def filterNull(img):
    ndviU = img.select('NDVI')
    ndviF = ee.Algorithms.If(ee.Algorithms.IsEqual(ndviU, None), -2000, ndviU)
    return img.addBands(ndviF)

cf = c.map(filterNull)
dataf = cf.getRegion(p, scale = 1000).getInfo()
print 'dataf=',dataf

It doesn't work though, the output indicates no change for the None value.
data= [[u'id', u'longitude', u'latitude', u'time', u'NDVI'],
       [u'2003_12_19', -8.798998207950714, 41.72225337093118, 1071792000000L, None],
       [u'2004_01_01', -8.798998207950714, 41.72225337093118, 1072915200000L, 7339],
       [u'2004_01_17', -8.798998207950714, 41.72225337093118, 1074297600000L, 7090]]
dataf= [[u'id', u'longitude', u'latitude', u'time', u'NDVI', u'NDVI_1'],
        [u'2003_12_19', -8.798998207950714, 41.72225337093118, 1071792000000L, None, None],
        [u'2004_01_01', -8.798998207950714, 41.72225337093118, 1072915200000L, 7339, 7339],
        [u'2004_01_17', -8.798998207950714, 41.72225337093118, 1074297600000L, 7090, 7090]]

A: Yes, ee.Image.unmask() is used to convert an image's masked values to actual values. To apply to all images in a collection, use ee.ImageCollection.map() to map a function that operates on a single image.

A: Meanwhile, I was able to solve the problem by using unmask as follows:
def filterNull(img):
    return img.addBands(img.select('NDVI').unmask(-2000))
cf = c.map(filterNull)

Is this the most appropriate mechanism?


Q: Map matrix onto other matrix, row by row I am trying to map a matrix onto another matrix, row by row. Maybe it's better to show this by a simple example:
Let
startMatrix <- t(matrix( c(2.3, 1.2, 3.6,   6.9, 5.3, 6.7), nrow = 3, ncol = 2))
mapMatrix <- t(matrix( c(1, 1.3, 2, 2.5, 3,   5, 5.6, 6, 6.2, 7), nrow = 5, ncol = 2))

Now mapMatrix functions as a sort of grid of startMatrix, that is [1, 1.3, 2, 2.5, 3] is the grid for the first row of startMatrix and [5, 5.6, 6, 6.2, 7] is the grid for the second row of startMatrix. Furthermore, the startMatrix is mapped to its nearest element smaller than himself, e.g. 2.3 goes to 2 and 6.7 to 6.2.
Thus, when mapping startMatrix onto mapMatrix the outcome should be a matrix that looks as follows:
result = [2, 1, 3 ;
          6.2, 5, 6.2]

where ; indicates the end of the row.
I am looking for an approach that is fast, as such procedure will have to be performed for over 10.000 times for matrices with over 100 rows and 1000 columns.

A: Take note that each row of mapMatrix must be ascending
startMatrix <- t(matrix( c(2.3, 1.2, 3.6,   6.9, 5.3, 6.7), nrow = 3, ncol = 2))
mapMatrix <- t(matrix( c(1, 1.3, 2, 2.5, 3,   5, 5.6, 6, 6.2, 7), nrow = 5, ncol = 2))

res <- do.call(rbind,lapply(1:nrow(startMatrix),
              function(m) mapMatrix[m,][findInterval(startMatrix[m,],mapMatrix[m,])]))

Hope this helps!
> res
     [,1] [,2] [,3]
[1,]  2.0    1  3.0
[2,]  6.2    5  6.2


Q: Get Attachment Category Name How can I call the name of an attachment category?
Something that would look like <?php get_attachment_category_name ?> or $attachment->category_name
This would simply output the name of the category, which was created using the below function:
function add_categories_to_attachments() {
    register_taxonomy_for_object_type( 'category', 'attachment' );
}
add_action( 'init' , 'add_categories_to_attachments' );

A: The answer was found here: http://www.wprecipes.com/how-to-display-category-name-without-link
For my purposes, I needed to define the category function and then call it by name-only inside the php echo:
     <?php
$category = get_the_category($attachment->ID);
    echo 'html goes here';
    echo ''.$category[0]->cat_name.';
    ?>

Additionally, to help eliminate space or punctuation in the category name, it can display the slug instead:
<?php
$category = get_the_category($attachment->ID);
    echo 'html goes here';
    echo ''.$category[0]->slug.';
    ?>


Q: PrimeFaces - JSF tree's context menu can't show Now I want to use JSF tree's mouse right menu, which is just like the link's example. When I click the mouse right, the menu can be show and disappear immediately. I don't know how to show the mouse right key menu (treecontext). Can you give some advice about that? Thanks.
http://www.primefaces.org/showcase/ui/treeContextMenu.jsf
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      xmlns:p="http://primefaces.org/ui">

    <h:form id="treeform">

    <p:tree value="#{treeBean.root}" var="node" id="tree" rendered="true"  dynamic="true" cache="false" selectionMode="single" selection="#{treeBean.selectedNode}">
        <p:ajax event="expand"    listener="#{treeBean.onNodeExpand}"/>
        <p:ajax event="collapse"  listener="#{treeBean.onNodeCollapse}" />
        <p:ajax event="select"    listener="#{tableBean.showScenario}"  update=":mainForm:scenarioDetailTable :mainForm:dynaFormGroup :mainForm:breadcrumbmenu :mainForm:accordingpanel1:treeform:tree :mainForm:accordingpanel1:treeform:treecontext" />
        <p:ajax event="unselect"  listener="#{treeBean.onNodeUnselect}" update=":mainForm:scenarioDetailTable :mainForm:dynaFormGroup :mainForm:breadcrumbmenu :mainForm:accordingpanel1:treeform:tree :mainForm:accordingpanel1:treeform:treecontext" />
        <p:treeNode id="treeNode" rendered="true" animate="true"  expandedIcon="ui-icon-folder-open" collapsedIcon="ui-icon-folder-collapsed">
            <h:outputText value="#{node.name}" id="lblNode"/>
        </p:treeNode>
    </p:tree>

    <p:contextMenu id="treecontext" for="tree" rendered="true"  >
        <p:menuitem value="Add Product"    disabled="#{tableBean.selectedProjectNodeLevel==1?false:true}" icon="ui-icon-contact" action="#{treeBean.setDialogTitle}" update=":mainForm:scenarioDetailTable  :mainForm:accordingpanel1:treeform:tree " oncomplete="PF('createproductdlg').show()"    onclick="PF('createproductdlg').show()" />
        <p:menuitem value="Add Capability" disabled="#{tableBean.selectedProjectNodeLevel==2?false:true}" icon="ui-icon-contact" action="#{treeBean.setDialogTitle}" update=":mainForm:scenarioDetailTable  :mainForm:accordingpanel1:treeform:tree " oncomplete="PF('createcapabilitydlg').show()"    onclick="PF('createcapabilitydlg').show()" />
        <p:menuitem value="Add Feature"    disabled="#{tableBean.selectedProjectNodeLevel>=3?false:true}" icon="ui-icon-contact" action="#{treeBean.setDialogTitle}" update=":mainForm:scenarioDetailTable  :mainForm:accordingpanel1:treeform:tree " oncomplete="PF('createfeaturedlg').show()"    onclick="PF('createfeaturedlg').show()" />
        <p:menuitem value="Add Scenario"   disabled="#{tableBean.selectedProjectNodeLevel>=3?false:true}" icon="ui-icon-contact" update=":mainForm:scenarioDetailTable  :mainForm:accordingpanel1:treeform:tree " oncomplete="PF('scenariodlg').show()"  onclick="PF('scenariodlg').show()" />
        <p:menuitem value="Delete" update="tree" actionListener="#{treeBean.create}" icon="ui-icon-close"/>
    </p:contextMenu>
   </h:form>
</ui:composition>

some part of main page code
<h:form id="mainForm">

<p:layout id="fulllayout" fullPage="true">
<!-- top menu start -->
<p:layoutUnit id="layoutunittop" position="north" size="50">
    <p:breadCrumb id="breadcrumbmenu" rendered="true">
     <p:menuitem value="Categories" url="#"  />
     <p:menuitem value="Project" url="#" disabled="true" />
     <p:menuitem value="Add Product"    disabled="#{tableBean.selectedProjectNodeLevel==1?false:true}" action="#{treeBean.setDialogTitle}" update=":mainForm:scenarioDetailTable  :mainForm:accordingpanel1:treeform:tree " oncomplete="PF('createproductdlg').show()"    onclick="PF('createproductdlg').show()" />
     <p:menuitem value="Add Capability" disabled="#{tableBean.selectedProjectNodeLevel==2?false:true}" action="#{treeBean.setDialogTitle}" update=":mainForm:scenarioDetailTable  :mainForm:accordingpanel1:treeform:tree " oncomplete="PF('createcapabilitydlg').show()"    onclick="PF('createcapabilitydlg').show()" />
     <p:menuitem value="Add Feature"    disabled="#{tableBean.selectedProjectNodeLevel>=3?false:true}" action="#{treeBean.setDialogTitle}" update=":mainForm:scenarioDetailTable  :mainForm:accordingpanel1:treeform:tree " oncomplete="PF('createfeaturedlg').show()"    onclick="PF('createfeaturedlg').show()" />
     <p:menuitem value="Add Scenario"   disabled="#{tableBean.selectedProjectNodeLevel>=3?false:true}" update=":mainForm:scenarioDetailTable  :mainForm:accordingpanel1:treeform:tree " oncomplete="PF('scenariodlg').show()"  onclick="PF('scenariodlg').show()" />
    </p:breadCrumb>
</p:layoutUnit>
<!-- top menu end -->

 <!-- menu begin -->
 <p:layoutUnit id="layoutunitleft" position="west" size="360"  resizable="true" collapsible="true" header="Options" minSize="260">
    <p:accordionPanel id="accordingpanel1" rendered="true" >
     <p:tab id="accordingpanel1tab" title="Project">
       <ui:include src="tree.xhtml" />
     </p:tab>
     <p:tab title="Test Set">
       <h:outputText value="Test Set" />
     </p:tab>
     <p:tab title="Report">
      <!--   <h:outputText value="Report" />  -->
      <!--   <p:calendar mode="inline" navigator="none"/> -->
     </p:tab>
     </p:accordionPanel>
  </p:layoutUnit>
  <!-- menu end -->
....


Q: Watermark onto a posted imaged So on this website an admin posts an image, before it is sent to the database via sql I want to add a watermark. This is my code for this part.
  if(!$_POST['name'] | !$_POST['cat'] | !$_POST['frame'] | !$_POST['molding'] | !$_POST['price'] | $_FILES["photo"]["tmp_name"]) {

    die('You did not fill in a required field.');

    }

$image = file_get_contents($_FILES['photo']['tmp_name']);
$_POST['name'] = addslashes($_POST['name']);
$_POST['price'] = addslashes($_POST['price']);
$_POST['molding'] = addslashes($_POST['molding']);
$_POST['frame'] = addslashes($_POST['frame']);
$_POST['cat'] = addslashes($_POST['cat']);

// Load the stamp and the photo to apply the watermark to

$stamp = imagecreatefrompng('watermark2.PNG');

$save_watermark_photo_address = 'watermark_photo2.jpg';

// Set the margins for the stamp and get the height/width of the stamp image

$marge_right = 0;
$marge_bottom = 0;
$sx = imagesx($stamp);
$sy = imagesy($stamp);

$imgx = imagesx($image);
$imgy = imagesy($image);
$centerX=round($imgx/2) - ($sx/2);
$centerY=round($imgy/2) - ($sy/2);
// Copy the stamp image onto our photo using the margin offsets and the photo
// width to calculate positioning of the stamp.

imagecopy($image, $stamp, $centerX, $centerY, 0, 0, imagesx($stamp), imagesy($stamp));

// Output and free memory
//header('Content-type: image/png');

imagejpeg($image, $save_watermark_photo_address, 80);

The save part at the end was to check it.
Anything that uses $image comes up with the error
expects parameter 1 to be resource, string given in.
I think it means the images format is wrong but I have no idea how to fix it.
For anyone's information before I added the watermark code everything works perfectly.

A: for more clarification,
you may want to  use this
old colde:
$image = file_get_contents($_FILES['photo']['tmp_name']);

new code:
$imgData= file_get_contents($_FILES['photo']['tmp_name']);
$image = imagecreatefromstring( $imgData);

this is a clarification of my comment above.


Q: How can I fill the part above the line given in Epilog with light gray? How can I fill the part above the line given in Epilog with light gray or something?
Plot[{2 Sin[x], 3 x - 2, x^2}, {x, 0, 3}, GridLines -> Automatic,
 Epilog -> {Directive[Red, Dashed, Thickness[0.008]],
   Line[{{0, 1}, {1, 1}, {10, 10}}]}]

A: Clear["Global`*"]

Show[
 ListLinePlot[{{0, 1}, {1, 1}, {10, 10}},
  PlotStyle -> Directive[Red, Dashed, Thickness[0.008]],
  Filling -> Top,
  FillingStyle -> Lighter[Gray, 0.85]],
 Plot[{2 Sin[x], 3 x - 2, x^2}, {x, 0, 3}, GridLines -> Automatic],
 PlotRange -> {{0, 3}, Automatic}]

EDIT: To obscure the lines by the Filling(adjust the Opacity to taste)
Show[
 Plot[{2 Sin[x], 3 x - 2, x^2}, {x, 0, 3}, GridLines -> Automatic],
 ListLinePlot[{{0, 1}, {1, 1}, {10, 10}},
  PlotStyle -> Directive[Red, Dashed, Thickness[0.008]], Filling -> Top,
  FillingStyle -> Opacity[0.75, LightGray]]]

A: Construct a polygon using the coordinates of the epilog line:
Plot[{2 Sin[x], 3 x - 2, x^2}, {x, 0, 3}, GridLines -> Automatic,
 Epilog -> {Directive[Red, Dashed, Thickness[0.008]],
   Line[{{0, 1}, {1, 1}, {10, 10}}],
   LightGray, Opacity[.5],
   Polygon[{{0, 1}, {1, 1}, {10, 10},
      Scaled[{0, 1}, {10, 10}],
      Scaled[{0, 1}, {0, 1}]}]}]

A: FilledCurve work for Line.
line = Line[{{0, 1}, {1, 1}, {10, 10}, {0, 10}}];
Plot[{2 Sin[x], 3 x - 2, x^2}, {x, 0, 3}, GridLines -> Automatic,
 Epilog -> {{Gray, Opacity[.5], FilledCurve[line]},
   Directive[Red, Dashed, Thickness[0.008]],
   Line[{{0, 1}, {1, 1}, {10, 10}}]}]


Q: ternary operator in javascript when variable is empty I have used the ternary operator in php $foo = get_field('foo') ?: null; but I'm looking forn an equivalent in javascript. So far I've tried the var foo = <?php echo $foo; ?> || null;. But since <?php echo $foo; ?> in this case is null/empty the console is giving me the error Uncaught SyntaxError: Unexpected token || since  the variable is var foo =  || null;.
Is there another way of using ternary operators in javascript?

A: Your problem has nothing to do with ternary operator, but with PHP output to javascript. The safest way is:
var foo = <?php echo json_encode($foo); ?> || null ;

The json_encode() function makes sure that the variable is echoed in a form that JS understands.

A: You need to return a falsy value from php. Your code was almost correct. It was only missing the quotes around it.
var foo = '<?php echo $foo; ?>' || null;
console.log('foo', foo);   // null

This is because when $foo is empty, it will be var foo = '' || null;
and since '' is falsy in Javascript, it will return null.


Q: Intel HAXM install hangs on macOS Sierra I'm trying to install HAXM 6.2.1 on a MacBook Pro running MacOS Sierra, but the installer hangs.
Attempting to install via the GUI .dmg, the dialog "This package will run a program to determine if the software can be installed" appears. I click "Continue," and then the installer hangs. The dialog does not disappear, but cannot be moved or dismissed.
Attempting to install via the command line installer simply hangs with no further information.
Attempting to install via the command line silent install, the installer hangs with the haxm-isRunning process active. Googling for "haxm-isRunning" yields 0 results.
No log file appears to be generated. No console entries are found containing the string "haxm," so I think there are no relevant console entries either.
I'm at a loss and not sure what else to try. Any advice or suggestions?

A: I had the same problem.  HAXM installation would never exit and had to use "force quit" in order to kill it.
Found a log message in /var/log/system.log that seemed to coincide with the installation.  It was from a totally different application but the same error reoccurred each time I tried to run the HAXM installer:
... com.apple.xpc.launchd[1] (com.paloaltonetworks.authorized[284]): Service exited due to signal: Segmentation fault: 11 sent by exc handler[0]

The errors referred to a daemon called "authorized" from paloaltonetworks.  Every time I tried to run the HAXM installer I would see a Segmentation Fault error logged related to the authorized daemon.
So I disabled the authorized daemon temporarily by editing the /Library/LaunchDaemons/com.paloaltonetworks.authorized.plist file and set RunAtLoad to false as well as KeepAlive to false and rebooted.  Probably would have been enough to unload and reload the daemon via launchctl but whatever.
After rebooting with the authorized daemon disabled I was able to successfully install HAXM.  No issues.
Then I re-enabled the authorized daemon by reverting the changes to /Library/LaunchDaemons/com.paloaltonetworks.authorized.plist and rebooted.
Palo Alto Networks Traps (authorized daemon is related to this application) tool is working and HAXM is installed.  All good.  Hope this helps.

A: BTW -- it traps is indeed your problem (and it was for me) you can also just disable from the command line the traps stuff if you can sudo.
$ sudo bash
# cd /Library/Application Support/PaloAltoNetworks/Traps/bin
# ./cytool runtime stop all
--- INSTALL HAXM and whatever else ---
# ./cytool runtime start all

That should do the trick without having to reboot, etc.


Q: Stop eclipse formatter from removing certain useful parts of HTML code

                  {{cellList.date}}

I have this code.
background-color: {{cellList.ColorCode}}

this part and some closing second braces are getting removed while I am formatting my code in eclipse Luna. Any suggestion how to stop this?


Q: How to serve file under root path using Nginx? I have a website laike9m.com, which is served by Nginx. I want to access a text file AAA.txt with url laike9m.com/AAA.txt. The text file is on my server, let's say it's $HOME/AAA.txt. Redirection is not allowed. Current Nginx conf file is here. Thank you.

A: location ~ ^(.*\.txt)$ {
    alias /home/laike9m/$1;
}

Solved it.


Q: CFReadStreamOpen Returns Error kCFStreamErrorDomainPOSIXDomain I want to make a MD5 of an Image so I am doing this with below code
CFStringRef FileMD5HashCreateWithPath(CFStringRef filePath, size_t chunkSizeForReadingData, BOOL *isAbort)
{
    // Declare needed variables
    CFStringRef result = NULL;
    CFReadStreamRef readStream = NULL;

    // Get the file URL
    CFURLRef fileURL =
    CFURLCreateWithFileSystemPath(kCFAllocatorDefault,
                                  (CFStringRef)filePath,
                                  kCFURLPOSIXPathStyle,
                                  (Boolean)false);
    if (!fileURL) goto done;

    // Create and open the read stream
    readStream = CFReadStreamCreateWithFile(kCFAllocatorDefault,
                                            (CFURLRef)fileURL);
    if (!readStream) goto done;
    bool didSucceed = (bool)CFReadStreamOpen(readStream);
    if (!didSucceed) goto done;

    // Initialize the hash object
    CC_MD5_CTX hashObject;
    CC_MD5_Init(&hashObject);

    // Make sure chunkSizeForReadingData is valid
    if (!chunkSizeForReadingData) {
        chunkSizeForReadingData = FileHashDefaultChunkSizeForReadingData;
    }

    // Feed the data to the hash object
    bool hasMoreData = true;
    while (hasMoreData) {

        if(*isAbort){
            NSLog(@"hasMoreData isAborted");
            if (readStream) {
                CFReadStreamClose(readStream);
                CFRelease(readStream);
            }
            if (fileURL) {
                CFRelease(fileURL);
            }
            return nil;
        }

        uint8_t buffer[chunkSizeForReadingData];
        CFIndex readBytesCount = CFReadStreamRead(readStream,
                                                  (UInt8 *)buffer,
                                                  (CFIndex)sizeof(buffer));
        if (readBytesCount == -1) break;
        if (readBytesCount == 0) {
            hasMoreData = false;
            continue;
        }
        CC_MD5_Update(&hashObject,
                      (const void *)buffer,
                      (CC_LONG)readBytesCount);
    }

    // Check if the read operation succeeded
    didSucceed = !hasMoreData;

    // Compute the hash digest
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5_Final(digest, &hashObject);

    // Abort if the read operation failed
    if (!didSucceed) goto done;

    // Compute the string result
    char hash[2 * sizeof(digest) + 1];
    for (size_t i = 0; i < sizeof(digest); ++i) {
        snprintf(hash + (2 * i), 3, "%02x", (int)(digest[i]));
    }
    result = CFStringCreateWithCString(kCFAllocatorDefault,
                                       (const char *)hash,
                                       kCFStringEncodingUTF8);
done:

    if (readStream) {
        CFReadStreamClose(readStream);
        CFRelease(readStream);
    }
    if (fileURL) {
        CFRelease(fileURL);
    }
    return result;
}

Above code is properly working in Mac OS, But I am doing the same thing in iOS and it is not working. As far as I know I am passing the fileUrl exactly right but in the CFReadStreamOpen() it returns the kCFStreamErrorDomainPOSIX and I came to know that this error no is 1 and it states that it is "Operation Not Permitted"
I have gone through this link
What to do in order to read the stream of any PHAsset of iOS device
does changing the below file ownership affects in this context:

A: PHAsset contains only metadata about image. In order to fetch image data you need to use PHImageManager.
func requestImageData(for asset: PHAsset,
              options: PHImageRequestOptions?,
        resultHandler: @escaping (Data?, String?, UIImageOrientation, [AnyHashable : Any]?) -> Void) -> PHImageRequestID

You can use CFReadStreamCreateWithBytesNoCopy to create CFReadStreamRef with data.


Q: Biblatex @misc show institution I using biblatex and Citavi. Citavi puts out for alot of the items a @misc entry. I need the instituion shown in the bibliography. How to get this done?
I use:
\usepackage[backend=biber,url=false,style=numeric]{biblatex}

The mimal exampele:
    \documentclass[ captions=tableheading, chapterprefix, BCOR=4mm, cdfont=false]{tudscrreprt}      % parskip > unbekannte Bedeutung, twoside > duplex
%====================================== Basics ==============================================================================

\usepackage[german]{varioref}               % ermöglicht Verweise mit Seitenzahl
\pdfminorversion=7                          % PDF 1.7
\usepackage{setspace}                       % line spacing                  Effekt nochmal Testen!
\onehalfspacing                             % onehalfspacing
\usepackage[T1]{fontenc}                    % European  encoding

\usepackage{csquotes}               % Zitierstil
\usepackage[backend=biber,url=false,style=numeric]{biblatex} %style=authoryear,citestyle=authoryear ,style=numeric
\addbibresource{tes.bib}        % Bibtex Quelle

\usepackage[ngerman]{babel}                                 % new German  spelling rules for automatic elements

\begin{document}
test
\cite{Streuber.2013}

    \appendix
    \printbibliography%[title=Quellen]
\end{document}

And the .bib
@misc{Streuber.2013,
author = {Bonn, Werner and Eißler, Werner and Rusche, Stefan and Streuber, Christian},
date = {2013},
title = {Formelsammlung für die Lehrveranstaltungen Wärmelehre, Strömungslehre und Wärmeübertragung},
edition = {5. Auflage},
institution = {{Hochschule RheinMain}}}

A: A look at the biblatex documentation shows that @misc supports

So institution is silently ignored.
However, the field organization is functionally equivalent. So I suggest you use that.
Most types support one of the functionally equivalent (list) fields publisher, organization and institution. So if things don't come out as you'd hoped, play around with those three terms and usually you can get what you want.
\documentclass{tudscrreprt}
\usepackage[T1]{fontenc}
\usepackage[ngerman]{babel}
\usepackage{csquotes}
\usepackage[backend=biber, style=numeric, url=false,]{biblatex}

\begin{filecontents}{\jobname.bib}
@misc{Streuber.2013,
  author       = {Bonn, Werner and Eißler, Werner and Rusche, Stefan
                  and Streuber, Christian},
  date         = {2013},
  title        = {Formelsammlung für die Lehrveranstaltungen
                  Wärmelehre, Strömungslehre und Wärmeübertragung},
  edition      = {5},
  organization = {Hochschule RheinMain},
}
\end{filecontents}
\addbibresource{\jobname.bib}

\begin{document}
  Lorem \autocite{Streuber.2013}

  \printbibliography
\end{document}

You could also look into using a different entry type. As you can see, @misc drops the edition field as well, so that piece of information is hidden.
@booklet doesn't have an edition field either, so it is probably not that useful.
I don't think I would use @report here, because that is usually used for research reports, discussion papers etc. and a formula handbook feels slightly different, but that I just my gut instinct. But you could use the version field instead of edition.
@manual as mentioned in the comments by Mico is an option, but then you might as well just use @book (which does not have an organization, but a publisher).
\documentclass{tudscrreprt}
\usepackage[T1]{fontenc}
\usepackage[ngerman]{babel}
\usepackage{csquotes}
\usepackage[backend=biber, style=numeric, url=false,]{biblatex}

\begin{filecontents}{\jobname.bib}
@book{Streuber.2013,
  author       = {Bonn, Werner and Eißler, Werner and Rusche, Stefan
                  and Streuber, Christian},
  date         = {2013},
  title        = {Formelsammlung für die Lehrveranstaltungen
                  Wärmelehre, Strömungslehre und Wärmeübertragung},
  edition      = {5},
  publisher    = {Hochschule RheinMain},
}
\end{filecontents}
\addbibresource{\jobname.bib}

\begin{document}
  Lorem \autocite{Streuber.2013}

  \printbibliography
\end{document}


Q: Telegram Menu Keyboard bot Hello i have a question about bots in telegram, 2 years ago we could create telegram bots easily with chatfual bot, now i need make a bot that has menu button from bottom and when user tap on the button it answers the user and send the message like before, is there any full tutorial about it from youtube? i searched but i didn't get answer because all of the videos talks about inlinekeyboard but i need menu keyboard buttons not inlinekeyboard, i need full tutorial of python or any other language that tells me how can i make buttons like this, or is there any website that help me make bots like i said without coding? i don't want make these type of bots from other bots of telegram i want coding way or websites.
thanks.
like this picture
also want make more buttons whithin button

A: Check that, it's tottaly what you search :
https://irazasyed.github.io/telegram-bot-sdk/usage/keyboards/#keyboards
And
https://medium.com/@chutzpah/telegram-inline-keyboards-using-google-app-script-f0a0550fde26


Q: Collatz Conjecture: Checking my reasoning about the sum of the powers of $2$ if a cycle exists Apologies on the length of this question.  I found it surprisingly difficult to take even this baby step with the Collatz Conjecture.
If you see any step that is unclear, please let me know in a comment and I will update.
Let:

*

*gcd$(a,b)$ be the greatest common divisor of $a$ and $b$

*$C(x) = \dfrac{3x+1}{2^w}$ where $w$ is the highest power of $2$ that divides $3x+1$

*$x_1>1, x_2>1, \dots, x_n>1$ be the sequence of $n$ distinct odd integers for each application of $C(x_i)$ so that:

*

*for $i > 1$,  $x_i = C(x_{i-1})$

*$x_i > 1$

*

*$C_1(x) = C(x)$

*$C_n(x) = C(C_{n-1}(x))$

*for each $x_i$, there exists $w_{x_i,1}\ge 1, w_{x_i,2} \ge 1, \dots w_{x_i,n} \ge 1$ such that:

$$C_n(x_i) = \dfrac{3^n x_i + 3^{n-1} + \sum\limits_{i=1}^{n-1}\left(3^{n-i-i}2^{\left(\sum\limits_{k=1}^i w_{x_i,k}\right)}\right)}{2^{\left(\sum\limits_{k=1}^n w_{x_i,k}\right)}}$$

Note 1: Details for this equation can be found here.

*

*$m \ge n$ be an integer with $m = \sum\limits_{k=1}^{n}w_{x_1,k}$

*Let integers $c_1 > 0, c_2 > 0, \dots, c_n > 0$ form an n-cycle so that each $c_{i+n} = c_i$

*$\text{avg}(c_1, c_2, \dots, c_n) = \dfrac{\sum\limits_{k=1}^n c_k}{n}$
Observation:

*

*Given an n-cycle: $c_1, c_2, \dots, c_n$, there exists $1 \le k \le n$ such that for all $k \le j < k+n$:

$$\sum\limits_{i=k}^{j} c_i \le \text{avg}(c_1, c_2, \dots, c_n)$$

Argument

*

*Base Case: $n=2$: either $c_1 \le \text{avg}(c_1, c_2)$ or $c_2 \le \text{avg}(c_1,c_2)$

*Assume that $k$ exists for any $n$-cycle up to $n \ge 2$

*Inductive Case:

*Let $d_1, d_2, \dots, d_n, d_{n+1}$ be an $(n+1)$-cycle with $d_{n+1+i} = d_i$

*There exists $1 \le m \le n$ with $d_m < \text{avg}(d_1, d_2, \dots, d_n, d_{n+1})$.  Otherwise, all values are equal to $\text{avg}(d_1, d_2, \dots, d_{n+1})$ and any $1 \le i \le n$ will serve as $k$.

*Let $c_1, c_2, \dots, c_n$ be an $n$-cycle such that:
$$c_i = \begin{cases}
d_i, & i < m\\
d_{i+1}-\text{avg}(d_1,\dots,d_{n+1}) + d_i, & i = m\\
d_{i+1}, & i > m\\
\end{cases}$$

*Since $c_1, c_2, \dots, c_n$ forms an $n$-cycle, there exists $1 \le k \le n$ such that for all $k \le j < k+n$:

$$\sum\limits_{i=k}^{j} c_i \le \text{avg}(c_1, c_2, \dots, c_n) = \text{avg}(d_1, d_2, \dots, d_n, d_{n+1})$$

*

*Case 1: $k = m$
$$d_k = d_m < \text{avg}(d_1, d_2, \dots, d_{n+1})$$

*Case 2: $1 \le j \le n$ and $k+j < m$

*By assumption:
$$\sum\limits_{i=k}^{k+j} c_i = \sum\limits_{i=k}^j d_i \le \text{avg}(c_1, c_2, \dots, c_n) = \text{avg}(d_1, d_2, \dots, d_n, d_{n+1})$$

*Case 3: $1 \le j \le n$ and $k+j = m$
$$\sum\limits_{i=k}^{k+j} d_i = \left(\sum\limits_{i=k}^{k+j-1} d_i\right) + d_m \le \text{avg}(d_1, d_2, \dots, d_n, d_{n+1})$$

*Case 4: $1 \le j \le n$ and $k+j > m$
$$\sum\limits_{i=k}^{k+j} d_i  = \left(\sum\limits_{t=k}^{k+j-1} c_t\right) - \text{avg}(d_1,d_2,\dots,d_{n+1}) + d_{m} \le \text{avg}(d_1, d_2, \dots, d_{n+1})$$

Question:
Does it now follow that if $x_1, x_2, \dots, x_n$ form an n-cycle, then either $2^{m-1} < 3^n$ or there exists $x_i$ where $x_i < n$
If yes, is there a simpler or more straight forward way to make the same argument?
Argument:
(1) Assume that $x_1, x_2, \dots, x_n$ forms an n-cycle.
(2) For each $x_i$, it follows that:
$$x_i = C_n(x_i) = \dfrac{3^n x_i + 3^{n-1} + \sum\limits_{i=1}^{n-1}\left(3^{n-i-i}2^{\left(\sum\limits_{k=1}^i w_{x_i,k}\right)}\right)}{2^{\left(\sum\limits_{k=1}^n w_{x_i,k}\right)}}$$
Which implies that:
$$x_i\left(2^{m}-3^n\right) = 3^{n-1} + \sum\limits_{i=1}^{n-1}\left(3^{n-i-i}2^{\left(\sum\limits_{k=1}^i w_{x_i,k}\right)}\right)$$
(3)  $2^m > 3^n$

This follows since $2^m - 3^n = \dfrac{3^{n-1} + \sum\limits_{i=1}^{n-1}\left(3^{n-i-i}2^{\left(\sum\limits_{k=1}^i w_{x_i,k}\right)}\right)}{x_i}$
Since, clearly: $\dfrac{3^{n-1} + \sum\limits_{i=1}^{n-1}\left(3^{n-i-i}2^{\left(\sum\limits_{k=1}^i w_{x_i,k}\right)}\right)}{x_i} > 0$

(4) Assume that $2^{m-1} > 3^n$
(5) $2^m - 3^n > 2^m - 2^{m-1} = 2^{m-1}$
(6) The average of each $w_{x_i,k}$ is $\dfrac{m}{n}$ with $2^{\frac{m}{n}} > 3$ since:

*

*$m \ln 2 > n \ln 3$

*$\frac{m}{n}\ln 2 > \ln 3$

*$2^{\frac{m}{n}} > 3$

(7) Since $x_1, x_2, \dots, x_n$ forms an $n$-cycle, from the Observation above, there exists an $x_i$ such that for each $1 \le u \le n$, $\left(\sum\limits_{k=1}^{u} w_{x_i,k}\right) \le \dfrac{um}{n}$
Note: The argument in the observation is derived from the solution to the well known gas stations on a circular trek problem.
(8) $2^{m-1}n > 3^{n-1} + \sum\limits_{i=1}^{n-1}\left(3^{n-i-i}2^{\left(\sum\limits_{k=1}^i w_{x_i,k}\right)}\right)$ since:

*

*$2^{m-1} > 3^{n-1}$ from step(3) above

*$2^{m-1} \ge 2^{\left(\sum\limits_{k=1}^{n-1} w_{x_i,k}\right)}$

*$2^{m-1} > 2^{(n-1)\frac{m}{n}} > 3\times2^{\left(\sum\limits_{k=1}^{n-2} w_{x_i,k}\right)}$ since: $\dfrac{m}{n} > 1$ from $2^{\frac{m}{n}} > 3$ and $\frac{m}{n} + (n-1)\frac{m}{n} = m < m-1 + \frac{m}{n}$

*$2^{(n-1)\frac{m}{n}} \ge 3^2\times2^{\left(\sum\limits_{k=1}^{n-3} w_{x_i,k}\right)}$

*$\dots$

*$2^{(n-1)\frac{m}{n}} \ge 3^{n-2}\times2^{w_{x_i,1}}$

(9) $x_i < \dfrac{2^{m-1}n}{(2^m - 3^n)} < \dfrac{2^{m-1}n}{2^{m-1}} = n$

Edit 1:
I found a mistake in my reasoning which led me to change the title slightly and change the question in order to fix the mistake in reasoning.

Edit 2:
I made changes based on comments from John Omielan.

A: from $(3+\frac{1}{e_0})(3+\frac{1}{e_1})...(3+\frac{1}{e_n})=\frac{e_{n+1}}{e_0}\prod_{k=0}^n2^{\nu_2(3e_k+1)}$
you can see that for a cycle: $$2^m\leq (3+\frac{1}{x_{min}})^n$$
If you state that $2\cdot3^n<2^m$ than you have
$$2\cdot3^n< (3+\frac{1}{x_{min}})^n$$
$$2^\frac{1}{n}\cdot3<3+\frac{1}{x_{min}}$$
$$x_{min}<\frac{1}{3(2^\frac{1}{n}-1)}<n$$


Q: Как выводить нужные слова из строки Здравствуйте у меня есть файл
< ;^; >ttx.txt,YWxpbmE=< ;^; >vfx.txt,dmFzeWE=< ;^; >pps.txt,dmljdG9y

После < ;^; > идёт название файла, а после названия через запятую идёт текст и у меня вопрос как мне вывести отдельно название файла и отдельно текст с учётом того что подобных строк может быть очень много

A: import re

s = '< ;^; >ttx.txt,YWxpbmE=< ;^; >vfx.txt,dmFzeWE=< ;^; >pps.txt,dmljdG9y'

r = re.findall(r'<\s;\^;\s>(.+?),([^<$]+)', s)

print(r) # [('ttx.txt', 'YWxpbmE='), ('vfx.txt', 'dmFzeWE='), ('pps.txt', 'dmljdG9y')]

for i in r:
    print(f'{i[0]}: {i[1]}')

# ttx.txt: YWxpbmE=
# vfx.txt: dmFzeWE=
# pps.txt: dmljdG9y

A: Как вариант:
_str = "< ;^; >ttx.txt,YWxpbmE=< ;^; >vfx.txt,dmFzeWE=< ;^; >pps.txt,dmljdG9y"

print(*[ ( [j[0], j[1]] if j[1][-1] != '=' else [j[0], j[1][:-1]])  for j in [i.split(',') for i in _str.split('< ;^; >') if i] ], sep=('\n'))

['ttx.txt', 'YWxpbmE']
['vfx.txt', 'dmFzeWE']
['pps.txt', 'dmljdG9y']


Q: Помогите решить задачу с матрицами на питон Дана квадратная целочисленная матрица. Требуется переписать все её элементы в одномерный массив по следующему правилу: выбор элементов начинается из правого верхнего и левого нижнего угла и продолжается "змейкой" в сторону главной диагонали. На первой итерации после угловых элементов выбор производится в сторону левого верхнего угла. В конце записываются элементы главной диагонали от левого верхнего угла до правого нижнего.
Входные данные: в первой строке число N - количество строк и столбцов в квадратной матрице, N не превышает 20. Далее в N строках по N чисел через пробел, каждое не превышает 100 по модулю.
Выходные данные: получившийся массив, записанный в одну строку через пробел.

мой код работает только если матрица 3*3
kol=int(input())
a=[]
for i in range(kol):
    a.append(list(map(int, input().split())))
b=[]
kol-=1
for i in range(kol):
    for j in range(kol,0,-1):
        b.append(a[i][j]), b.append(a[j][i])
print(b)

A: сделаем несколько наблюдений
во-первых, четные элементы получаются из нечетных перестановкой индексов
во-вторых. если посмотреть на правый верхний угол матрицы, то индексы элементов выглядят так
             0,m
     0, m-1        1, m
2, m        1, m-1      0, m-2

если перевернуть второй ряд, то получается простой цикл
             0,m
      1, m         0, m-1
2, m        1, m-1        0, m-2

только брать ряды надо через раз - слева-направо и справа-налево
остальное просто код
matrix= [
    [13, 11, 3, 1],
    [12, 14, 9, 5],
    [4, 10, 15, 7],
    [2, 6, 8, 16]
]

m = len(matrix[0])
left = True
for i in range(m-1):
    pairs = []
    for j in range(i+1):
        pairs.append((j, m-i+j-1))
    if left:
        pairs = pairs[::-1]
    left = not left
    for x,y in pairs:
        print(matrix[x][y])
        print(matrix[y][x])
for i in range(m):
    print(matrix[i][i])

A: #include <bits/stdc++.h>
using namespace std;
int main(){
  //ifstream cin("input.txt");
  long long n;
  cin>>n;
  vector <vector <long long> > a(n,vector <long long> (n));
  vector <long long>ans(n*n);
  for(long long i=n-1;i>=0;i--)for(long long j=0;j<n;j++)cin>>a[i][j];
  long long i=n-1;long long j=n-1;
  ans[0]=a[i][j];

  i--;
  bool dir=1;
  long long cntr=2;
  while(i+j!=n-1){long long curdiag=i+j;
    if(dir==1){
      for(;i<n;i++){
        j=curdiag-i;
        ans[cntr]=a[i][j];
        cntr+=2;
      }
      i--;
      j--;
      dir=!dir;
    }
    else {
      for(;j<n;j++){
        i=curdiag-j;
        ans[cntr]=a[i][j];
        cntr+=2;
      }
      j--;
      i--;
      dir=!dir;
    }
  }
  dir=0;
  cntr=3;
  i=0;j=0;
  ans[1]=a[i][j];
  j++;
  while(i+j!=n-1){long long curdiag=i+j;
    if(dir==1){
      for(;i>=0;i--){
        j=curdiag-i;
        ans[cntr]=a[i][j];
        cntr+=2;
      }
      i++;
      j++;
      dir=!dir;
    }
    else {
      for(;j>=0;j--){
        i=curdiag-j;
        ans[cntr]=a[i][j];
        cntr+=2;
      }
      j++;
      i++;
      dir=!dir;
    }
  }
  j=0;i=n-1;
  long long curdiag=i+j;
  cntr=n*n-n;
  for(;i>=0;i--){
        j=curdiag-i;
        ans[cntr]=a[i][j];
        cntr++;
      }
  for(long long i=0;i<ans.size();i++)cout<<ans[i]<<" ";
}


Q: Why can I invalid flag my own flagged answer? I responded to a question with a rather sarcastic answer which was flagged as not an answer. Now for some reason I was able to review my own flagged answer and set an invalid flag.
Is it normal that I can invalid flag my own answers? This kind of defeats the purpose of peer review no?


Q: How to upload canvas and image to the server with Javascript I have html code as follows:

     <canvas id="canvas"></canvas>

<button id="save-button" onclick="onSaveChanges()">Save</button>

Thus I have an image and on that image I want to draw canvas. That works fine.
But now I want to upload it to the server, but not only the canvas. I want to upload image and the canvas, together as one image. How can I do that?
Here is my js code where I try to upload it:
function onSaveChanges(){
    save_button_label.classList.add('hide');
    save_button_spinner.classList.remove('hide');

    var body = new FormData();
    var canvasData = canvas.toDataURL("image/png");
    body.append('photo', canvasData);

    var xhr = new XMLHttpRequest();
    xhr.open('POST', url);

    xhr.onload = function (e) {
        if (xhr.readyState === 4 && xhr.status === 200) {
            // const result = JSON.parse(xhr.responseText);
            renderMessage(success, upload_success_msg)
        }
    };
    xhr.onerror = function (e) {
        renderMessage(errors, upload_error_msg)
    };
    xhr.send(body);
}

But with var canvasData = canvas.toDataURL("image/png"); I get only the canvas, and not the image also.
Any idea what can I do to upload image and canvas together as one image?
Thanks in advance.
UPDATE

The red border is canvas and the blue border is the image. I want to upload it as one image, thus both together as one.

A: I changed html a little bit:

     <canvas id="canvas"></canvas>

And I used HTML2Canvas library, which takes a screenshot of the whatever you want and save it as image.
The javascript is as follows:
function upload_to_server(canvasData){

    return fetch(api_url, {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({photo: canvasData})
    }).then(function (value) {
        if(value.ok){
            return value.json().then(function (response) {
                // Do something with response
            })
        }
    }).catch(function (reason) {
        // Handle error
    })

}

function onSaveChanges(){
    save_button_label.classList.add('hide');
    save_button_spinner.classList.remove('hide');

    html2canvas(document.getElementById("result")).then(function(canvas) {
        var canvasData = canvas.toDataURL("image/" + image_type + "");
        upload_to_server(canvasData)
    });
}

I hope that it will help someone.


Q: Is there any need/advantage of calling an api using the http client service when using websockets in angular? I am trying to learn how to use socket.io by building a simple chat app using the socket.io library and MEAN stack.
From looking at some open source projects(like this one) I have seen that the client, mainly when executing the chat logic, communicates with the server via websockets and not the http client service provided by angular.
Does this mean that when using web-sockets for real time updates there is no need to use http to communicate with the server?

A: Most assuredly not. It is not a matter of angular though, it's just choosing the right tool for the right thing.
Long story short:

*

*If it is a request/response model, then use http. Why?

*

*Because it's easier to handle. Proxies, dns and load balancers need no extra configuration to handle. Web Sockets do.

*You have already setup 1 so it's not a problem. How will you handle caching, routing, gziping, SEO and all the out of the box stuff the http protocol and rest-apis handle? Everything you build, all communications will need their own security consideration, design patterns etc.

*How will you handle the stateful nature of web sockets? They are currently supporting only vertical scaling, whereas rest apis scale both horizontally and vertically.

If you really need a full duplex communication (there is server push only without sockets), then you should limit web socket usage to the cases where you really need it.
Even in this case, go through a framework like signalR. All modern browsers support websockets but a lot of users still don't have browsers that do support them. SignalR falls back to long polling in those cases. If you use it on all cases, imagine what would happen if you use such a browser and you apply long polling for each request.
I could go on, but I think you get the meaning.


Q: Prioritize Tasks in Android I have a map application, and every time that the user moves the map I have to make a new request to the back-end to receive the points.
Right now I'm already optimizing a lot the process of getting the points. But I'd like to add prioritizing functionality to my Threads.
It's executing the Threads in serial (one before the other). But my optimizations work better when I already process a larger bound thread before.
Here is how I'm implementing my AsyncTask right now:
plotPinsThread = new AsyncTask<Void, Boolean, List<Loja>>() {

                final boolean oldMy = showMyStores;
                final boolean oldOthers = showOtherStores;

                @Override
                protected List<Loja> doInBackground(Void... params) {
                    try {
                        publishProgress(true);
                        Log.d(TAG, "=====> Inicio de requisição de pontos");
                        List<Loja> lojas = new ArrayList<>();

                        publishProgress(true);
                        if (showMyStores && !isCancelled()) {
                            publishProgress(true);
                            lojas.addAll(lojasDAO.getLojasList(cliente, currentBounds, LojaJsonDAO.DEALERSHIPS, this));
                        }

                        if (showOtherStores && !isCancelled()) {
                            publishProgress(true);
                            lojas.addAll(concorrentesDAO.getLojasList(others, currentBounds, LojaJsonDAO.COMPETITORS, this));
                        }

                        return lojas;
                    } catch (JSONException e) {
                        Log.e(TAG, "Erro de Json", e);
                    }

                    return new ArrayList<>();
                }

                @Override
                protected void onProgressUpdate(Boolean... values) {
                    if (values[0]) {
                        loading.setVisibility(View.VISIBLE);
                    } else {
                        loading.setVisibility(View.GONE);
                    }
                }

                @Override
                protected void onCancelled() {
                    Log.d(TAG, "Uma Thread foi cancelada: ");
                }

                @Override
                protected void onPostExecute(List<Loja> list) {
                    publishProgress(true);
                    boolean isLojasLoaded = lojasCarregadas.containsAll(list);

                    if (!isLojasLoaded && isEnoughZoom() && oldMy == showMyStores && oldOthers == showOtherStores && !isCancelled()) {
                        clearMarkers();
                        for (Loja loja : list) {
                            publishProgress(true);
                            if (loja.getPosition() != null) {
                                mMap.addMarker(getMarker(loja));
                            }
                        }
                        lojasCarregadas.addAll(list);
                        Log.d(TAG, "=====> Final de requisição de pontos");
                    } else {
                        String msg = (isLojasLoaded) ? "já carregados." : "invalidos";
                        Log.d(TAG, "=====> Final de requisição, dados " + msg);
                    }
                    publishProgress(false);

                }
            }.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);

I read something about executors and I had the insight of creating a executor that would implement a PriorityQueue where I would make the Threads with larger bounds execute before the smaller ones. (the param currentBounds)
I don't know how to do it, or if I should implement it with another thread approach.
PS: If I implements a Executor, is there some way to get the params of the AsyncTask on it?

A: You need a custom executor.  When you call execute(), it uses a default executor that runs all tasks serially.  If you call executeOnExecutor() you can specify an executor.  The default one is serial, there's also THREAD_POOL_EXECUTOR which will run tasks in parallel.  If you want a priority queue, you'll need to write your own that keeps a priority queue of tasks and executes them serially based on priority.


Q: C++ Can't figure out arrays and functions
Possible Duplicate:
Stuck on C++ functions and arrays

Stuck on this problem: I can't get it to run and i am stuck on getting the array functions to return to main. Thanks for any help.
Requires the utilization of a 2 dimensional array to store the pounds of food eaten by 3 monkeys each of the seven days of the week.
Create a function to obtain the pounds eaten for each monkey, each day of the week.
Create a second function to determine pass through the array to calculate the total all of the moneys ate, and then the average eaten on one day.
Create a third function to determine which monkey ate the least amount of food and on what day.  Also output the amount the monkey ate on that day.
Create a fourth function to determine which monkey ate the most amount of food on a single day. Output the monkey number, the pounds eaten, and the weekday.
#include <iostream>
using namespace std;

const int monkeys = 3;
const int weekdays = 7;
double monkeyWeek[monkeys][weekdays];
double largest;
double least;
double average;
int index;
int dayCount;
double amount;

double amountEaten(double[] [weekdays], int);
double mostEaten (double[] [weekdays],int);
double leastEaten (double[][weekdays], int);

int main(){
    double mostBananas (double[] [weekdays],int);
    double leastBananas (double[][weekdays],int);
    //double bananaAverage (double[][weekdays], int);
}

double amountEaten(double array[] [weekdays], int) {
    cout << "Please enter the amount of food eaten per monkey per day." << endl;
    double amount = array[0][0];
    for (index = 0; index < monkeys; index++)
    {
        for (dayCount = 0; dayCount < weekdays; dayCount++)
        {
            cout << endl << "Please enter the amount of pounds eaten by monkey"
                         << (index +1)
                         << endl << "for day " << (dayCount +1) << ": ";
            cin >> monkeyWeek[monkeys] [weekdays] ;
            if (monkeyWeek[monkeys] [weekdays] < 1)
                cout << endl <<"Must feed positive amount" << endl;
        }
    }
}

double mostEaten( double array[] [weekdays], int size)
{
    double largest = array[0][0];
    for (int count = 0; count < size; count++)
    {
        for (int col = 0; col < count; col++)
        {
            if (array[count][weekdays] > largest)
            largest = array[count][weekdays];
        }
    }
    return largest;
}

double leastEaten(double array[] [weekdays], int size)
{
    double least = array[0][0];

    for (int count = 0; count < size; count++)
    {
        for (int col = 0; col < size; col++);
        {
            if (array[count][weekdays] < least)
            least = array[count][weekdays];
        }
    }
    return least;
}

A: You are  just  declaring the functions, you haven't made a call to any functions at all. Use the sample below and change your program accordingly.
Example:
int main()
{
    int i_array={0,1,2,3,4,5};
    function(i_array);           //  Call a function
    printf("%d",i_array[0]);    // will print 100 not 0
}

void function(int []  i_array)
{
    i_array[0]=100;
}


Q: How do I run several linear regressions at once in R? If I have a dataset with variable A, X, Y, and Z and I want to run two linear regressions - both have A as the dependent variable but one has X as the independent variable and the other has Y (note - NOT multiple regression), what can I do?
lm(A ~ X, Y, df = df)  doesn't seem to work, and obviously lm(A ~ X + Y, df = df) becomes a multiple regression. I can use lm(A ~ ., - Z, df = df) but I'm looking for a way that I could pick and choose multiple variables to use as the independent variable. Thanks.

A: lmList in nlme can run multiple regressions at once:
library(nlme)

DF <- data.frame(A = 1:10, X = 1:5, Y = 11:15, Z = 1:10)

DF2 <- cbind(A = DF$A, stack(DF[c("X", "Y")]))
lmList(A ~ values | ind, DF2)

A: Here is an alternative using formulas() from package modelr :
df <- data.frame(A = 1:10, X = 1:5, Y = 11:15, Z = 1:10)

library(modelr)

ll <- formulas(~ A,
              m1 = ~ X,
              m2 = ~ Y
)

results_list <- lapply(ll, lm, data = df)


Q: Implement search box for  dropdown in angular I want to implement search box without any third party libraries,
i want search to be inside the dropdown.
how to do this
<select class="form-control" [(ngModel)]="selected5" [ngModelOptions]="{standalone: true}"
              formControlName="manpower_requirement">
              <option selected *ngFor="let person of newArray" [ngValue]="person">{{ person.positions }} </option>
</select>

A: filter your newArray. Add an input for the search and bind it to searchValue with [(ngModel)]="searchValue" then in the setter, filter newArray.
so:
private _searchValue:string
set searchValue(value:string)
{
    this._searchValue = value;
    this.newArray = this.newArray.filter(v=>v.contains(value));
}

Note - this is unchecked, there may be typos. But this is the idea of a way to do it


Q: getting HTTP Status 500 when location href or when forwarding from Servlet? I get this error:
HTTP Status 500 -

type Exception report
message
descriptionThe server encountered an internal error () that prevented it from fulfilling this request.
exception
org.apache.jasper.JasperException: java.lang.NullPointerException
root cause
java.lang.NullPointerException
note The full stack traces of the exception and its root causes are available in the GlassFish Server Open Source Edition 3.1-b24 logs.
GlassFish Server Open Source Edition 3.1-b24
when I try to forward from a jsp to another jsp or when I forward in a servlet... The thing is that Y modify some datils from my page and I want to go back to the login-page and log in again to see if the update was successful !... Any ideas on this error ?... Thankx

A: A NullPointerException is a rather trivial exception and has actually nothing to do with JSP/Servlets, but with basic Java in general (look, it's an exception of java.lang package, not of javax.servlet package). It just means that some object is null while your code is trying to access/invoke it using the period . operator.
Something like:
SomeObject someObject = null;
someObject.doSomething(); // NullPointerException!

The 1st line of the stacktrace tells you in detail all about the class name, method name and line number where it occurred.
Fixing it is relatively easy. Just make sure that it's not null or bypass the access altogether. You should rather concentrate on why it is null and/or why your code is trying to deal with null.


Q: Why is execstack required to execute code on the heap? I wrote the code below to test shellcode (for unlinking /tmp/passwd) for an assignment in a security class.
When I compile with gcc -o test -g test.c, I get a segfault on the jump into the shellcode.
When I postprocess the binary with execstack -s test, I no longer get a segfault and the shellcode executes correctly, removing /tmp/passwd.
I am running gcc 4.7.2. It seems like it is bad idea to require the stack to be executable in order to make the heap executable, since there are many more legitimate use cases of the latter than the former.
Is this expected behavior? If so, what is the rationale?
#include <stdio.h>
#include <stdlib.h>

char* shellcode;

int main(){
    shellcode = malloc(67);
    FILE* code = fopen("shellcode.bin", "rb");
    fread(shellcode, 1, 67, code);

    int (*fp)(void) = (int (*) (void)) shellcode;
    fp();
}

Here is the output of xxd shellcode.bin:
0000000: eb28 5e89 760c 31c0 8846 0bfe c0fe c0fe  .(^.v.1..F......
0000010: c0fe c0fe c0fe c0fe c0fe c0fe c0fe c089  ................
0000020: f3cd 8031 db89 d840 cd80 e8d3 ffff ff2f  ...1...@......./
0000030: 746d 702f 7061 7373 7764                 tmp/passwd

A: The real "unexpected" behavior is that setting the flag makes the heap executable as well as the stack.  The flag is intended for use with executables that generate stack-based thunks (such as gcc when you take the address of a nested function) and shouldn't really affect the heap.  But Linux implements this by globally making ALL readable pages executable.
If you want finer-grained control, you could instead use the mprotect system call to control executable permissions on a per-page basis -- Add code like:
uintptr_t pagesize = sysconf(_SC_PAGE_SIZE);
#define PAGE_START(P) ((uintptr_t)(P) & ~(pagesize-1))
#define PAGE_END(P)   (((uintptr_t)(P) + pagesize - 1) & ~(pagesize-1))
mprotect((void *)PAGE_START(shellcode), PAGE_END(shellcode+67) - PAGE_START(shellcode),
         PROT_READ|PROT_WRITE|PROT_EXEC);

A:
Is this expected behavior?

Looking at the Linux kernel code, I think that the kernel-internal name for this flag is "read implies exec". So yes, I think that it's expected.

It seems like it is bad idea to require the stack to be executable in order to make the heap executable, since there are many more legitimate use cases of the latter than the former.

Why would you need the complete heap to be executable? If you really need to dynamically generate machine code and run it or so, you can explicitly allocate executable memory using the mmap syscall.

what is the rationale?

I think that the idea is that this flag can be used for legacy programs that expect that everything that's readable is also executable. Those programs might try to run stuff on the stack and they might try to run stuff on the heap, so it's all permitted.


Q: Meteor JS: Organizing Code for Sharing Code Between Template Helpers Inside my Meteor JS Project's client/templates/pages folder I have these files:
1.) admin_add_product.html and admin_add_product.js
2.) admin_edit_product.html and admin_edit_product.js
Inside both admin_add_product.js and admin_edit_product.js I have the same exact code that I use for both files:
var ucwords = function(str)
{
  return str.split(" ").map(function(i){return i[0].toUpperCase() + i.substring(1)}).join(" ");
};

var editForDB = function(str){

  return ucwords(str.trim());
}

var makeHidden = function(object){
  object.addClass('hidden');
}

var removeHidden = function(object){
  object.removeClass('hidden');
}

var makeDisabled = function(object){
  object.addClass('disabled');
}

var removeDisabled = function(object){
  object.removeClass('disabled');
}

I would like to organise my code so that I don't REPEAT any code unnecessarily.  I wish to put the above snippet of code somewhere where I can share between Template helpers (in this case between admin_add_product.js and admin_edit_product.js) so if ever I do need to edit it I just need to edit it in one place rather than two or more....
I already tried Template.registerHelper but I have found that that only works inside the .html file.........
How do I organise my code in Meteor JS to do this?
Is this even possible in Meteor JS given that each template helper file is supposedly enclosed inside a function(){} closure???

A: Variables declared with var have a file scope, and are indeed inside a closure like you mentioned. However, if you declare new variables without the var keyword, they are accessible throughout your project (given you load files in the right order), as Meteor declares these variables outside the closure.
In your case the solution is to declare your form functions without var, or maybe better declare a new object without var and put them as methods in there:
FormHelpers = {};

FormHelpers.ucwords = function(str)
{
  return str.split(" ").map(function(i){return i[0].toUpperCase() + i.substring(1)}).join(" ");
};

...

You can then use these helpers in both you add and edit tenplates, or anywhere else you need them.
More info on namespacing in the Meteor docs.


Q: Google Analytics with First Party Cookie I am in the process of setting up Google Analytics (GA) on a Wordpress site. As part of this, I want to include a custom cookie (for users that consent) that allows me to segment the analytics of users based on what settings they have active on the site (via a custom plugin). I have managed to successfully implement this most of the way (the cookie is included in many of the tagged events).
However, I have included the custom cookie in a Gravity Form that is being submitted on the website, and there are a number of instances of a form being submitted successfully, tagged with a cookie ID, but that cookie ID is not showing up in Google Analytics as an option to segment page views, for example. I have a record of the cookie being generated on my Apache server, but it has not made its way through to GA.
Is there a way to see all events with a specific attribute in GA? Or is this only possible with a custom report (which necessarily requires you to filter out events that don't have a specific metric).
(I'm primarily a back-end developer, and have limited experience with GA. Apologies if there is something very obvious that I have not done.)

A: You would need to create a custom dimension in Google Analytics, retrieve the cookie value and pass it to the GA code (how exactly would depend on the version of the GA code that you use, as they have recently shifted from the analytics.js library to gtag.js).


Q: IOs Swift Progress View Password Evaluacion Necesitaria poder reproducir algun componente parecido a

El cual tenga como una barra que indique con diferentes colores si la password esta muy debil , si es seguro   etc ,
Swift Xcode cualquier link de interes me ayuda, nisiquiera se como poder googlear esto gracias

A: Nunca lo he utilizado, pero tal vez esto te podría servir.
https://github.com/mattt/Navajo


Q: Question about Local Henselian Rings I have a question regarding properties/characterizations of local Henselian rings exploited in M. Artin's article "On Isolated Rational Singularities of Surfaces":
Here the relevant excerpt:

Remark: this is the continuation of the proof of Thm 4 (page 132) where we assumed that $\pi: V \to \bar{V}= Spec(A)$ is a birational map, $A$ henselian and $X \subset V$ reduced curve on normal surface $V$ with components $X_i$.
The question is if $D$ is apositive divisor which meets $X_i$ transversally why the intersections of $D$ with $X$ correspond one to one with connected components of the support of $D$? What property of Henselian rings is exploited here? I'm just familar with the lifting story of polynomials in $A[X]$ which have non multiple roots in $(A/m)[X]$.
But I don't see how it can be applied here. Is there another characterization for Henselians with more "geometric" flavour?
Remark: Some weeks ago I asked another question about properties of Henselian local rings: Henselian Schemes
Does the mysterious property of Henselian which I'm looking for in this thread provide an argument for my former thread?


Q: Image resize script I'm searching a javascript that can resize images similar to script thats available as a plugin in vBulletin CMS:

I want the script to be used in blogger blog so that all images i upload into a post are resized to a smaller res and on clicking the image should be displayed in original dimensions
Something of the sort getelementbyID("img").
are there any script providing this feature? Pls help me out
Thanks in advance.

A: Something like a lightbox, perhaps?
I know the specific interaction you're asking about, and personally, I've always found it really obnoxious.

A: If you don't want to use a server side script to automatically create a smaller version of the image that you would link to the larger version, I wouldn't recommend using JavaScript to resize an image either. I'd recommend setting the image's dimensions in CSS and then attaching a click handler with JS that showed the image in some sort of overlay (or just using HTML to link to the larger image file).


Q: How to dynamically load the material-ci-icons icon I use Material-ui@next and  material-ui-next@next
material-ui@next load one icon usage:
import AddIcon from 'material-ui-icons/AddIcon';
function AddIconButton(props) {
    return (
        <AddIcon />
    );
}

But I want dynamically load the material-ci-icons icon
For example, I have variable menus
const menus = [
  {
    Name: 'menu1',
    Icons: 'face',
  },
  {
    Name: 'menu2',
    Icon: 'extension',
  }
].

How to display the icon on the page according to the menus

A: I faced with this problem too. i use this link:
dynamically load an icon.
save my menu icon name at database and use  <Icon>{props.iconName}</Icon> but, it doesn't work for me.
so because i don't have so much time i just save the SVG format of material ui icon in my database and restore it at my JSX.
i got SVG format of icons from inspect element of browser from material ui icon web page


Q: java.lang.AbstractMethodError: org.hibernate.search.elasticsearch.analyzer.impl.ElasticsearchAnalyzerStrategy.initializeAnalyzerReferences I am trying to integrate elastic search with hibernate search.For doing this I am using following maven dependencies.
      <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.2.1.Final</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-search-orm</artifactId>
        <version>5.7.0.Final</version>
    </dependency>

    <dependency>
       <groupId>org.hibernate</groupId>
       <artifactId>hibernate-search-elasticsearch</artifactId>
      <version>5.6.1.Final</version>
    </dependency>

But while deploying the application I am getting below error.
 java.lang.AbstractMethodError: org.hibernate.search.elasticsearch.analyzer.impl.ElasticsearchAnalyzerStrategy.initializeAnalyzerReferences(Ljava/util/Collection;Ljava/util/Map;)Ljava/util/Map.
I know this question has already been asked but I am not able to find out the root cause of error.Any suggestion..........

A: You're using multiple modules of Hibernate Search, but without different versions (5.7.0.Final and 5.6.1.Final). Use the same version for each Hibernate Search module, in your case 5.7.0.Final:
  <dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>5.2.1.Final</version>
</dependency>

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-search-orm</artifactId>
    <version>5.7.0.Final</version>
</dependency>

<dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-search-elasticsearch</artifactId>
  <version>5.7.0.Final</version>
</dependency>


Q: Getting rid of unnecessary space between letters and equal sign in caption Suppose we have this code
\begin{center}
        \begin{tikzpicture}[shorten >=1pt,node distance=2cm,on grid,auto]
            \node[state,initial, accepting] (q_0)   {$q_0$};
            \node[state] [right=of q_0] (q_1) {$q_1$};
            \path[->]
            (q_0) edge node {$a,b$} (q_1)
            (q_1) edge [loop above] node {$a,b$} ();
         \end{tikzpicture}
         \captionof{figure}{This DFA represents $L_1 = \{\lambda\}$}
\end{center}

That produces:
How do I get rid of the spacing between between the L_1 = and { }?
Is this because of the centering?

A: This is not an answer but an extended comment that shows the importance of submitting a complete MWE. Without an MWE, one cannot reproduce your issue. If I compile
\documentclass{article}
\usepackage{caption}
\usepackage{tikz}
\usetikzlibrary{automata,positioning}
\begin{document}
\begin{center}
        \begin{tikzpicture}[shorten >=1pt,node distance=2cm,on grid,auto]
            \node[state,initial, accepting] (q_0)   {$q_0$};
            \node[state] [right=of q_0] (q_1) {$q_1$};
            \path[->]
            (q_0) edge node {$a,b$} (q_1)
            (q_1) edge [loop above] node {$a,b$} ();
         \end{tikzpicture}
         \captionof{figure}{This DFA represents $L_1 = \{\lambda\}$}
\end{center}
\end{document}

I get

That means that the weird behavior you are reporting does not come from the code piece that you are showing, but from something else. In many situations, when you try to write an MWE, you actually find the source of the problem yourself, and thus learn something. So

PLEASE SUMBIT A COMPLETE MWE!

The above code qualifies as an MWE: it starts with \documentclass, ends with \end{document} and can be compiled. It is also rather minimal in the sense that (as far as I can tell) no unnecessary packages are loaded.


Q: Observable in for loop? I would like to call an observable REST service in a for loop. It returns base64 encoded csv file. I would like to decode it and concatenate it into one string and return it. After that I am trying to subsrciibe to that method and click the DOM to download. I get empty string with only "\r\n" in it. Why doesn't it wait for REST to return the file before returning?
downloadFilesAndConcatenate(): Observable<any> {
    let concatenatedFileDecoded: string = '\r\n';
    for (let i = 0; i < this.fileIDs.length; i++) {
      this.restService.getFile(this.fileIDs[i]).subscribe(response => {
        this.fileResultSet = response;
        this.message = response.message;
        this.file = this.fileResultSet.result;
        let fileCSVbase64 = this.file.fileBytes
        let fileCSVDecoded = atob(fileCSVbase64);
        concatenatedFileDecoded += fileCSVDecoded;
      },
      error => {
        this.message = error.error.message;
      });

      return new Observable( observer => {
        observer.next(concatenatedFileDecoded)
        observer.complete();
      });
    }
  }

And then I subscribe to it:
download() {
    if (this.dateEnd !== null && typeof this.dateEnd !== "undefined") {
      debugger;
      this.downloadFilesAndConcatenate()  // Multiple files
        .subscribe(
          (result) => {
            debugger;
            const link = document.createElement( 'a' );
            link.style.display = 'none';
            document.body.appendChild( link );

            const blob = new Blob([result], {type: 'text/csv'});
            const objectURL = URL.createObjectURL(blob);

            link.href = objectURL;
            link.href = URL.createObjectURL(blob);
            link.download =  this.file.name;
            link.click();
          },
          (err) => {
            console.error(err);
          },
          () => console.log("download observable complete")
        );
    } else {
      this.downloadFile();  // Only one file
    }
  }

A: because it is asynchroniuos code. it is expected that sync code will be executed earlier than async.
correct code would be like this
downloadFilesAndConcatenate(): Observable<string> {
    return forkJoin(this.fileIDs.map(id => this.restService.getFile(id))).pipe(
      map(responses => '\r\n'+responses.map(r => atob(r.result.fileBytes)).join(''))
      catchError(e => this.message = e.error.message)
    );
  }


Q: how to set java web application's context root when working with reverse proxy
*

*My old way using mod_jk in apache and configure virtual host in tomcat
In the JSP file, I refer to CSS as below
/<%=request.getContextPath()%>/css/styles.css
while the home link is set to
/<%=request.getContextPath()%>/

so this worked fine when I use mod_jk in apache to work with tomcat using ajp;

*

*When I try to configure reverse proxy as below

ProxyPass / http://localhost:800/mywebapp
ProxyPassReverse / http://localhost:800/mywebapp
the home page can be retrieved fine but the css request becomes
http://mydomain.com/mywebapp/mywebapp/css/style.css
so the css file can not be retrieved correctly;

*

*I think one possible way is to always use relative path like ./style.css or ../style.css
a. since header/footer are shared, and the home page is in a different level with detail page, it's inconvenient to use relative path because they're at a different level
b. still, I think the home link will have to be /<%=request.getContextPath()%>/

so I wonder what's the way to set contextroot fine in java web and also work fine with reverse proxy?
thx a lot

A: As I know your application server (Tomcat) isn't able to be aware of a reverse proxy presence. Generally speaking, it can be contacted through any number of reverse proxies or directly by browsers. A network configuration is usually used to limit this, not HTTP or Java.
So, you must accurately rely on relative URLs to make your application work well.
When I have to deal with reverse proxy presence (almost always due to SSO architectures), I embed a "junction" configuration string item (the portion of the URL used in the proxy to map the application) and use it in the only places where I need to build an absolute URL.


Q: How to vectorize process of spltting vector I have a vector of numbers (here random). I'd like to calculate the consecutive relation of something (here means to clarify example) on the left and right side of each number in a vector.
Here is a procedural example. I'm interested in the vectorized form.
from numpy.random import rand
import numpy as np
numbers = rand(40)

k=np.zeros(numbers.shape)
for i in range(*numbers.shape):
     k[i]=np.mean(numbers[:i])/np.mean(numbers[i:])

This example will return nan in the first iteration but it is not a problem now.

A: Here's a vectorized way -
n = len(numbers)
fwd = numbers.cumsum()/np.arange(1,n+1)
bwd = (numbers[::-1].cumsum()[::-1])/np.arange(n,0,-1)
k_out = np.r_[np.nan,fwd[:-1]]/bwd

Optimizing a bit further with one cumsum, it would be -
n = len(numbers)
r = np.arange(1,n+1)

c = numbers.cumsum()
fwd = c/r
b = c[-1]-c
bwd = np.r_[1,b[:-1]]/r[::-1]
k_out = np.r_[np.nan,fwd[:-1]]/bwd

A: I spent some time and there is a simple and universal solution: numpy.vectorize with excluded parameter, where vector designated to be split must be excluded from vectorisation. The example still uses np.mean but can be replaced with any function:
def split_mean(vect,i):
    return np.mean(vect[:i])/np.mean(vect[i:])

v_split_mean = np.vectorize(split_mean)
v_split_mean.excluded.add(0)

numbers = np.random.rand(30)
indexes = np.arange(*numbers.shape)

v_split_mean(numbers,indexes)


Q: Function that reads and stores values from configuration file I'm relatively new to C++ programming and I am just trying to create a function that opens a configuration file, reads each line and column, then stores the values into some array.
So my config file will look like this which simply just stores values:
12345    10    20
67890    30    40
...
...

What I want to do is open this file, read each line and store the values into an [i][j] array. So for the above, it would be stored as:
[0][0] = 12345
[0][1] = 10
[0][2] = 20
[1][0] = 67890
[1][1] = 30
[1][2] = 40

I have been looking at the fopen function to open the file, but when I research on how to store these values how I want (using functions like fgets), I keep hitting a wall.
My attempt thus far:
#include <iostream>
using namespace std;

int main()
{
    FILE *fp;
    fp = fopen("configFile.conf","r");

    char a[20];
    char b[20];
    char c[20];

    fscanf(fp, "%s\t%s\t%s", a, b, c);
    cout << a << " " << b << " " << c << endl;
}

output:
12345    10    20

Now I want to just modify this loop through until the end of the file and store the values in an array based off the i'th element.

A: This is C code :
#include <stdio.h>

int main()
{
   FILE *fp;
   int i = 0;
   fp = fopen("configFile.conf", "r");

   if(fp == NULL) // To check for errors
   {
      printf("Error \n");
   }

   char a[20][20]; // Declared a 2D array
   char b[20][20];
   char c[20][20];

   while (fscanf(fp, "%s\t%s\t%s", a[i], b[i], c[i]) != EOF) //fscanf returns EOF if end of file (or an input error) occurs
   {
      printf("%s  %s   %s\n", a[i], b[i], c[i]);
      i++;
   }

   return 0;
}

C++ code is :
#include <iostream>
using namespace std;

int main()
{
   FILE *fp;
   int i = 0;
   fp = fopen("configFile.conf", "r");

   if(fp == NULL) // To check for errors
   {
      cout<< "Error" << endl;
   }

   char a[20][20]; // Declared a 2D array
   char b[20][20];
   char c[20][20];

   while (fscanf(fp, "%s\t%s\t%s", a[i], b[i], c[i]) != EOF) //fscanf returns EOF if end of file (or an input error) occurs
   {
      cout << a[i] << " " << b[i] << " " << c[i] << endl;
      i++;
   }

   return 0;
}


Q: Access Parent Element Within href So... this is a simple question with a simple answer, but somehow my RTFMing isn't proving any results.
I have a link within a div, like so:

 Close
I'd like to close that div with that link, and I've been trying the following code:

 Close
However, it still hasn't worked... any suggestions are greatly appreciated.

A: Change it to this:

 Close

The reason is that when using href="javascript:..., this doesn't refer to the element that received the event.
You need to be in an event handler like onclick for that.


Q: How to create this below JSON response using python DRF Since I am new to this DRF I am facing some difficulties creating this JSON. I have created an API endpoint and the output of that API endpoint is like this now as shown below
  "meta": {
    "limit": 1,
    "page_count": 1,
    "total_count": 1
  },
  "results": {
    "id": 1234567,
    "curriculum": {
      "ES Math": [
        {
          "grade_level": "ES",
          "subject": "Math",
          "subject_abbr": "Math",
          "product_id": 438,
          "product_title": "Test1",
          "ratings": [
            {
              "source": "A",
              "report_url": "********",
              "Org1_rating": [
                {
                  "name": "green_alignment_ratings",
                  "value": 12,
                  "label": "Meet Expectations",
                  "label_color": "Green"
                },
                {
                  "name": "green_usability_ratings",
                  "value": 12,
                  "label": "Meet Expectations",
                  "label_color": "Green"
                }
              ],
              "Org2_rating": [
                {
                  "name": "Overall",
                  "value": null,
                  "label": "Tier 1: Exemplifies Quality",
                  "label_color": null
                }
              ]
            }
          ]
        },
        {
          "grade_level": "ES",
          "subject": "Math",
          "subject_abbr": "Math",
          "product_id": 2085,
          "product_title": "Test2",
          "ratings": [
            {
              "source": "A",
              "report_url": "********",
              "Org1_rating": [
                {
                  "name": "green_alignment_ratings",
                  "value": 12,
                  "label": "Meet Expectations",
                  "label_color": "Green"
                },
                {
                  "name": "green_usability_ratings",
                  "value": 12,
                  "label": "Meet Expectations",
                  "label_color": "Green"
                }
              ],
              "Org_rating2": "null"
            }
          ]
        }
      ]
    }
  }
}

But I want the output to be in this format below
{
  "meta": {
    "limit": 1,
    "page_count": 1,
    "total_count": 1
  },
  "results": {
    "id": 1234567,
    "curriculum": {
      "ES Math": [
        {
          "grade_level": "ES",
          "subject": "Math",
          "subject_abbr": "Math",
          "product_id": 438,
          "product_title": "Test1",
          "ratings": [
            {
              "review_org": "Org1",
              "review_url": "url",
              "review_items": [
                {
                  "name": "green_alignment_ratings",
                  "value": 14,
                  "label": "Meets Expectations",
                  "label_color": "Green"
                },
                {
                  "name": "green_usability_ratings",
                  "value": 34,
                  "label": "Green",
                  "label_color": 38
                }
              ]
            },
            {
              "review_org": "Org2",
              "review_url": "url",
              "review_items": [
                {
                  "name": "Overall",
                  "value": null,
                  "Label": "Tier I, Exemplifies quality",
                  "scale": null
                }
              ]
            }
          ]
        },
        {
          "grade_level": "ES",
          "subject": "Math",
          "subject_abbr": "Math",
          "product_id": 2085,
          "product_title": "Test2",
          "ratings": [
            {
              "review_org": "Org1",
              "review_url": "url",
              "review_items": [
                {
                  "name":"green_alignment_ratings",
                  "value": 14,
                  "label": "Meets Expectations",
                  "label_color": "Green"
                },
                {
                  "name":"green_usability_ratings",
                  "value": 34,
                  "label": "Meets Expectations",
                  "label_color": "Green"
                }
              ]
            },
            {
              "review_org": "Org2",
              "review_url": "url",
              "review_items": []
            }
          ]
        }
      ]
    }
  }
}

And I tried something with the serializer below but this is yeilding some different JSON only.

class CurriculumSerializer(ModelSerializer):
    grade_level = serializers.CharField(source='grade_level_dim')
    subject_abbr = serializers.CharField(source='subject_abbr_dim')
    product_id = serializers.IntegerField(source='dim_id')
    product_title = serializers.CharField(source='title_dim')
    ratings = serializers.SerializerMethodField()

    class Meta:
        model = Table2
        fields = [
            'grade_level',
            'subject',
            'subject_abbr',
            'product_id',
            'product_title',
            'ratings'
        ]

    def get_ratings(self,obj):
        queryset = Table2.objects.all()
        c = queryset.filter(id=obj.id, title_dim = obj.title_dim, ratings_source__isnull=False).distinct('id',)
        if c.exists():
            serializer = RatingsSerializer(c, many=True)
            return serializer.data
        else:
            data = 'null'
            return data

class RatingsSerializer(ModelSerializer):
    review_items = serializers.SerializerMethodField()
    Louisiana_rating = serializers.SerializerMethodField()
    class Meta:
        model = Table3
        fields = ['source','report_url','review_items','Louisiana_rating']

    def get_review_items(self, obj):
        queryset = Table3.objects.all()
        c = queryset.filter(source__iexact = 'Org1', title = obj.title_dim, grade_level = obj.grade_level, subject_abbr = obj.subject_abbr_dim)
        # print(c.query)
        if c.exists():
            serializer = reportSerializer(c, many=True)
            return serializer.data
        else:
            data = 'null'
            return data

    def get_Louisiana_rating(self, obj):
        queryset = Table3.objects.all()
        c = queryset.filter(source__iexact = 'Org2', title = obj.title_dim, grade_level = obj.grade_level, subject_abbr = obj.subject_abbr_dim)
        if c.exists():
            serializer = reportSerializer(c, many=True)
            return serializer.data
        else:
            data = 'null'
            return data

class reportSerializer(ModelSerializer):
    class Meta:
        model = Table3
        fields = ['name',
                  'value',
                  'label',
                  'label_color']

class DistrictDetailSerializer(ModelSerializer):
    curriculum = serializers.SerializerMethodField()

    class Meta:
        model = Table1
        exclude = ('finance_total', 'revenue_total')

    def get_curriculum(self, obj):
        queryset_list = Table2.objects.all()
        c = queryset_list.filter(id=obj.id)\
            .distinct('col1','col2')
        if c.exists():
            serializer = CurriculumSerializer(c, many=True)
            curriculum_map = {}
            for d in serializer.data:
                key = f"{d['grade_level']} {d['subject_abbr']}"
                if key in curriculum_map:
                    curriculum_map[key].append(d)
                else:
                    curriculum_map[key] = [d, ]
            return curriculum_map
        else:
            data = 'null'
            return data

The table3 has all details for ratings like source, report_url, name,label,value,label_colour I want this values as show in the JSON below.

A: This error usually occurs if the user account was not given/assigned to the Virtual Machine User Login role on the VMs.
Please check this https://learn.microsoft.com/en-us/azure/active-directory/devices/howto-vm-sign-in-azure-ad-windows#azure-role-not-assigned to assign required roles and try login.