text:
Q: PHP Javascript Array Hi I'm a novice PHP developer to say the least and I'm pretty stuck.
I'm trying to get the below code working I know I need a foreach loop or similar but I'm way out of my depth, I'm really not sure how to get this working, I know to most of you this is basic stuff but I'm lost.
Basically this is a receipt when a tab is settled. It searches the MySql Database for the relevant items and should print them on the receipt.
I know the MySql Query is not linked to the output at the bottom but I don't know how to do it.

  <title>Receipt</title>

  <?php

   $invoicenum = $_POST['invoicenum'];
   $name = $_POST['name'];

   $netrev=$invoicenum - 1;

  ?>
  Items:
  <?
   $itemQuery = mysql_query("SELECT * FROM sales WHERE invoicenum = '$netrev' AND tabname = '$name'");
 $result = array();

 while($row = mysql_fetch_array($itemQuery))
 {
  $result[] = $row['itemname'];
 }

 echo json_encode($result);

   $amounts = json_decode($result['amounts']);
   $items = json_decode($result['items']);
   $prices = json_decode($result['prices']);
  ?>

   <?
    for ($i = 0; $i < count($items); $i++)
    {
     echo $amounts[$i] . "x " . $items[$i] . " - " . $prices[$i] . "
";
    }
   ?>

I've removed code that isn't relevant to this array, if you can help I'd be forever grateful.

A: no need of encode and decode.
$itemQuery = mysql_query("SELECT * FROM sales WHERE invoicenum = '$netrev' AND tabname = '$name'");

while($row = mysql_fetch_array($itemQuery))
{
    echo $row['amounts'] . "x " . $row['items'] . " - " . $row['prices'] . "
";
}
 ?>

A: Forget all json_decode/encode after filling $result then:
First do:
$result[] = $row;
Then:
foreach ($result as $set){
   echo $set['amount'] . "x " . $set['itemname'] . " - " . $set['price'] . "
";
   #do var_dump($set); here for checking the keys
}


text:
Q: Expansion vs Sparsest cut let $G=(V,E)$ and $S\subsetneq V$ then expansion of set $S$ is
$$\alpha(S)=\frac{|E(S,\overline{S})|}{\min\{|S|,|\overline{S}|)\}}$$
where $\bar{S}=V\setminus{S}$ and $E(S,\bar{S})$ are edges between S and $\bar{S}$.
Expansion of graph G is
$$\alpha(G)=\min_{\emptyset\neq S\subsetneq {V}}\alpha(S)$$
Sparsity $\mathcal S_G$ of graph G is
$$\mathcal S_G=\min_{\emptyset\neq S\subsetneq {V}}\frac{|E(S,\overline S)|}{|S||\overline S|} $$
It is easy to see, that
$$\frac{n}{2} \mathcal{S}_G\leq \alpha(G) \leq (n-1)\mathcal{S}_G$$
where $n=|V|\.$
Solution for Expansion Problem is to find set $S\subsetneq V$ such that $\alpha(S)=\alpha(G)$
Solution for Uniform Sparsest Cut Problem is to find set $S\subsetneq V$ such that
$$\frac{|E(S,\overline S)|}{|S||\overline S|}=\mathcal S_G$$.
My question is, is there a graph for which there are different solution for Expansion Problem and for Uniform Sparsest Cut Problem?
Thank you for any ideas ..

redpajama_set_name: RedPajamaStackExchange


text:
Q: Error using sci-kit learn MLPClassifier: 'str' object has no attribute 'decode' I am creating, tuning, and fitting various sci-kit learn models for a classification problem. The structure of the code below works fine for all other methods (SVM, Logistic Regression, Random Forest, Decision Tree, etc.)
When running the MLPClassifier() and its hyperparameter tuning, I get the error message originating from the last line where I fit:
AttributeError                            Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_8160/4102235488.py in <module>
     19
     20 reverse_mlp_en_clf = GridSearchCV(reverse_mlp_en, reverse_mlp_en_hyperparameters, cv = 5, verbose = 1, n_jobs = 5, scoring = 'f1')
---> 21 reverse_mlp_en_best_model = reverse_mlp_en_clf.fit(X_en, y_en)

~\AppData\Roaming\Python\Python38\site-packages\sklearn\model_selection\_search.py in fit(self, X, y, groups, **fit_params)
    737             refit_start_time = time.time()
    738             if y is not None:
--> 739                 self.best_estimator_.fit(X, y, **fit_params)
    740             else:
    741                 self.best_estimator_.fit(X, **fit_params)

~\AppData\Roaming\Python\Python38\site-packages\sklearn\neural_network\_multilayer_perceptron.py in fit(self, X, y)
    992         self : returns a trained MLP model.
    993         """
--> 994         return self._fit(X, y, incremental=(self.warm_start and
    995                                             hasattr(self, "classes_")))
    996

~\AppData\Roaming\Python\Python38\site-packages\sklearn\neural_network\_multilayer_perceptron.py in _fit(self, X, y, incremental)
    372         # Run the LBFGS solver
    373         elif self.solver == 'lbfgs':
--> 374             self._fit_lbfgs(X, y, activations, deltas, coef_grads,
    375                             intercept_grads, layer_units)
    376         return self

~\AppData\Roaming\Python\Python38\site-packages\sklearn\neural_network\_multilayer_perceptron.py in _fit_lbfgs(self, X, y, activations, deltas, coef_grads, intercept_grads, layer_units)
    468                 },
    469                 args=(X, y, activations, deltas, coef_grads, intercept_grads))
--> 470         self.n_iter_ = _check_optimize_result("lbfgs", opt_res, self.max_iter)
    471         self.loss_ = opt_res.fun
    472         self._unpack(opt_res.x)

~\AppData\Roaming\Python\Python38\site-packages\sklearn\utils\optimize.py in _check_optimize_result(solver, result, max_iter, extra_warning_msg)
    241                 "    https://scikit-learn.org/stable/modules/"
    242                 "preprocessing.html"
--> 243             ).format(solver, result.status, result.message.decode("latin1"))
    244             if extra_warning_msg is not None:
    245                 warning_msg += "\n" + extra_warning_msg

AttributeError: 'str' object has no attribute 'decode'

Code is as follows:
# Reverse hyperparameter tuning - MLP English

# Create model

reverse_mlp_en = MLPClassifier()

# Define parameters, store in dictionary

reverse_mlp_en_hidden_layer_sizes = [(50,),(100,),(150,), (200,)]
reverse_mlp_en_activation = ['logistic', 'tanh', 'relu']
reverse_mlp_en_alpha = [0.0001, 0.05]
reverse_mlp_en_learning_rate = ['constant','adaptive']

reverse_mlp_en_hyperparameters = dict(hidden_layer_sizes = reverse_mlp_en_hidden_layer_sizes, activation = reverse_mlp_en_activation
                                    , solver = reverse_mlp_en_solver, alpha = reverse_mlp_en_alpha, learning_rate =reverse_mlp_en_learning_rate )

# Get model with the best parameters

reverse_mlp_en_clf = GridSearchCV(reverse_mlp_en, reverse_mlp_en_hyperparameters, cv = 5, verbose = 1, n_jobs = 5, scoring = 'f1')
reverse_mlp_en_best_model = reverse_mlp_en_clf.fit(X_en, y_en)

Libraries are up to date if I am not mistaken.
If anyone has an idea that would be greatly appreciated - I just find it weird how:

*

*The same code, but using different models, works fine and

*how the error is only shown after fitting everything (which is taking 40 minutes or so)


text:
Q: JComponent for images with no zoom for HiDPI I'd like to have a component that shows an image in Java without zooming on HiDPI screens.
The obvious candidate is to use a JLabel. I've succesfully done it by overwriting the AffineTransform in paintComponent but it remains the problem that the label preferred size is incorrect on HiDPI.
The following example seems to work even when I move the window from HiDPI (4K scaled 1.75) to FullHD (scale 1.0) except for the size of the component on HiDPI which is larger than the image displayed.
How can I achieve to have the preferred size of a component not to be zoomed on a HiDPI screen?
public class UnscaledImage extends JPanel {

    private AffineTransform noChangeTransform = new AffineTransform();
    private JLabel imageLabel;
    private JLabel colorLabel = new JLabel("Color");
    private BufferedImage image;
    private double scale = 1.0;

    public UnscaledImage() {
        initUI();
        packAndShow("Unscaled Image");
    }

    public void initUI() {
        setLayout(new BorderLayout());
        ImageIcon imageIcon = (ImageIcon) UIManager.getIcon("OptionPane.warningIcon");
        image = new BufferedImage(imageIcon.getIconWidth(), imageIcon.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = image.createGraphics();
        g2d.drawImage(imageIcon.getImage(), 0, 0, null);
        g2d.dispose();
        imageLabel = new JLabel() {
            @Override
            public void paintComponent(Graphics g) {
                Graphics2D g2d = (Graphics2D) g;
                AffineTransform oldTransform = g2d.getTransform();
                scale = oldTransform.getScaleX();
                Dimension labelPrefSize = imageLabel.getPreferredSize();
                if (scale != 1.0 && labelPrefSize.width == image.getWidth()) {
                    imageLabel.setSize(new Dimension((int) (labelPrefSize.width / scale), (int) (labelPrefSize.height / scale)));
                    SwingUtilities.windowForComponent(imageLabel).pack();
                }
                g2d.setTransform(noChangeTransform);
                super.paintComponent(g);
                g2d.setTransform(oldTransform);
            }
        };
        imageLabel.setIcon(imageIcon);
        imageLabel.addMouseMotionListener(new MouseMotionAdapter() {
            @Override
            public void mouseMoved(MouseEvent me) {
                int mouseX = (int) (me.getX() * scale);
                int mouseY = (int) (me.getY() * scale);
                if (mouseX < image.getWidth() && mouseY < image.getHeight()) {
                    int color = image.getRGB(mouseX, mouseY);
                    colorLabel.setBackground(new Color(color));
                }
            }
        });
        colorLabel.setOpaque(true);
        colorLabel.setBackground(Color.WHITE);
        add(imageLabel, BorderLayout.CENTER);
        add(colorLabel, BorderLayout.SOUTH);
    }

    public void packAndShow(String title) {
        JFrame frame = new JFrame(title);
        frame.add(this);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    public final static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new UnscaledImage());
    }
}


text:
Q: Intercept the view/response in Spring MVC 3 I am new to Spring MVC 3 and I understand the basic concepts. I am able to do simple things like create controllers and services and views. However, I haven't made a foray into more advanced territory. Hence, I apologize if this question seems silly (or impossible).
I am wondering if there is a way to intercept the view and/or response and modify it before it gets sent to the client? I imagine this is how Spring performs data binding to form elements on the way out to the client. What I would like to do is inspect annotations on elements within a domain class and modify the view according to those annotations. This will involve injecting new code (HTML or Javascript) into the response.
UPDATE
As I thought about this a bit more, I realized that the final rendering is done by the JSP. So I guess the question is if there is a way to intercept the model before it moves out to the page and to figure out the annotations on the bean that the data is being bound to.
Is there a way to do this?

A: The class you're probably looking for is org.springframework.web.servlet.HandlerInterceptor  You can implement the postHandle method on that interface and, as the signature implies, have access to both the request and the response, as well as the map of model objects that your controller created.  (and the controller itself, that's what the Object handler parameter is.)
You 'turn them on' by adding them to the handler mapping in your dispatcher servlet.
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
    <property name="interceptors">
        <list>
            <bean class="a.package.MyHandlerInterceptor"/>
        </list>
    </property>
</bean>

Incidentally, binding is actually done inside the HandlerAdapter that locates Controller methods and invokes them, it's not an interceptor.
Edit:
To answer your edit, yes this is where you have a chance to grab the model object and work with it more, after the controller is done, but before it goes to JSP rendering.  So you could do something like add myCustomScript to the ModelMap and toss ${myCustomScript} in the <head> of your jsp, get a backing object out of the ModelMap and examine it, etc etc.

A: Yes, a number of ways actually:

*

*spring mvc interceptors (search for them in the mvc docs) - you can define the preHandle / postHandle methods and apply the interceptor to a number of controllers

*spring aop - define an aspect to be executed before/after the methods of a given controller

*servlet filters - this is the least desirable option, since it is not integrated with spring - you can't inject dependencies.


text:
Q: Is it better to use a separate commit message for a git merge? I come from an SVN background so I'm not sure what the typical git workflow looks like. When you merge in SVN, you provide a commit message describing the merge. This is necessary because SVN's merge-tracking has historically been poor.
I noticed that git's default behavior is to automatically commit the results of the merge if it is successful. This means that the log normally won't show merges, so everything in the history looks like it was developed in one branch. Is this preferable to showing merges as additional commits? I can think of several reasons why and why not, but I'd like some input from other users.

A: I think you are mistaking two situations (or I do not understand what you are asking about).

*

*If you merge a side branch which is direct child of the branch you are currently on, it results in so called fast forward situation. Ordinary git wouldn't create a merge commit, but just advance branch tip, but you can prevent it with --no-ff option.
The default is to avoid such pointless merges because it plays better in truly distributed development.

*If the branch you are on and the branch you are merging are truly divergent, i.e there are on each branch commits which are not on other branch, the git would do a merge, and if it can do a merge without conflict, it would automatically create a merge commit. Such merge commit would have automated commit message, subject to merge.log config variable (formerly merge.summary). You can prevent comitting such an automated commit with --no-commit option.
Of course "git log" would show merge commits, unless you use "git log --no-merges".
I hope that this explanation would help a bit.

A: Unless you supply the --no-merges option to git log, it will normally show merges which are given a brief auto-generated commit description.
This is usually fine as git records the parentage of the commit and the interesting features of a merge are its constituent branches.
Try a git log --graph --oneline or use a graphical history viewer and you may (should!) be convinced that the way that git records merges is much more important and useful than a long winded merge commit message.
Merges only really need a detailed commit message if there was something 'magical' that was done in the resolve. As this means manual intervention this is easy to add at the this point.


text:
Q: Print out a certain section of a file So, I could be going about this the wrong way and if so, I'd appreciate a different way at looking at solving the problem, but here is what I am trying to do, and how I'm attempting to do it.
I am making a simple address-book based on some beginner project suggestions I found and I'm slowly implementing it, but I cannot figure how to get it to search for a certain section of the file. I want it to print the name, address, phone and mobile. All of which are on a separate line, 4 lines total.
I'm using the following code to accomplish this:
def search_entries():
    found = 0
    search = raw_input("Please enter the person's name: ")
    for line in open('addbook.txt', 'r').readlines():
        if search in line:
            found = 1
        if found >= 1:
            print line
            if found == 4: break

However, instead of printing just printing those 4 lines from the person's name it prints the rest of the file. Any help is appreciated, thanks.

A: found never changes after being set to 1.

A: Realized that I forgot to add a counter to the code:
def search_entries():
    found = 0
    search = raw_input("Please enter the person's name: ")
    for line in open('addbook.txt', 'r').readlines():
        if search in line:
            found = 1
        if found >= 1:
            print line
            found = found + 1
            if found == 4: break

A: There's a slightly better way of writing this (un-tested):
from itertools import islice

with open('input.txt') as fin:
    for line in fin:
        if 'bob' in line:
            next_3 = list(islice(fin, 3))
            print line, next_3
            break


text:
Q: Multiple intervals in PHP - return last continued item I have multiple intervals in PHP and I want to know what is maximum end_date in continuing intervals.
Example 1 (we have 3 intervals):
start_date - end_date
2017-01-01 - 2018-01-01
2018-01-01 - 2019-01-01
2019-02-01 - 2020-02-01

Result of function is 2019-01-01, because our date continues to there. Then  there is 1 month gap.
Example 2 (5 intervals):
start_date - end_date
2017-01-01 - 2017-02-01
2017-01-05 - 2017-01-10
2017-01-30 - 2017-02-05
2017-02-03 - 2017-02-04
2017-02-08 - 2017-02-12

Result here is 2017-02-05
I am not sure if there is some helpfull function for this. I was trying to search like intervals or something like that without any solution.
Thank you for any clues.

A: Use the date_diff() function:
$datetime1 = date_create('2009-10-11');
$datetime2 = date_create('2009-10-13');
$interval = date_diff($datetime1, $datetime2);

A: I didn't find anything helpfull in PHP or any clue for this anywhere, so I program it myself:
<?php
$example1 = [
    ['start' => '2017-01-01', 'end' => '2018-01-01'],
    ['start' => '2018-01-01', 'end' => '2019-01-01'],
    ['start' => '2019-02-01', 'end' => '2020-02-01']
];

$example2 = [
    ['start' => '2017-01-01', 'end' => '2017-02-01'],
    ['start' => '2017-01-05', 'end' => '2017-01-10'],
    ['start' => '2017-01-30', 'end' => '2017-02-05'],
    ['start' => '2017-02-03', 'end' => '2017-02-04'],
    ['start' => '2017-02-08', 'end' => '2017-02-12']
];

// @param intervals are ordered by start date
function getMaxContinuingEndDate($intervals)
{

    if (empty($intervals)) return NULL;

    $result = ['start' => $intervals[0]['start'], 'end' => $intervals[0]['end']];

    foreach($intervals as $interval) {
        if ($interval['start'] <= $result['start'] && $interval['end'] >= $result['start']) {
            $result['start'] = $interval['start'];
        }

        if ($interval['end'] >= $result['end'] && $interval['start'] <= $result['end']) {
            $result['end'] = $interval['end'];
        }
    }

    return $result['end'];
}

echo getMaxContinuingEndDate($example1);
echo "\n";
echo getMaxContinuingEndDate($example2);


text:
Q: JQuery: Add a style to Regex-matches I want to show HTML-Code as text in my website. I have following sample-text in my html:

    <p>Hello</p>

    <p>Hello2</p>

which shows:

Hello

Hello2

on my website.
Now I want to change the color of the tags. I found the idea on the internet of replacing a RegExp with the same text wrapped in a span with a class to change the style of that span.
I tried following in JQuery:
$(document).ready(function ()
{
    var oldHtml = $("#test").html();
    var newHtml = oldHtml.replace(new RegExp("(<){1}.*(&gt){1};","g"), "$1");
    $("#test").html(newHtml);
});

And got the following:
<
<

What am I doing wrong?

A: The capture groups are in the wrong place. You are capturing the opening bracket into $1 and the closi closing bracket into $2, which you never use.

(<){1}.*(&gt){1};

You also don't need the quantifier.
<(.*?)>

With this pattern and the same substitution it should work. The *? quantifier makes it not greedy, so it stops as early as possible with the match for anything.
Note that parsing HTML with regex is a bad idea. Even if parts of the HTML is escaped, it's still a hard language that is not regular. It's eventually not going to work. Use a parser instead. Or for your usecase, just use one of many easy to find and use syntax highlighting libraries.


text:
Q: Django -- Custom filter or SQL raw I have an application with a model which has three tables implementing the toxi tagging model.
One table for jobs, one table for skills and one table to map them, in the form of jobid -- skillid.
Due to the number of mappings if I use the following:
{% for job in jobs %}

{{ job.job_title }}

                        {% for skill in skillmaps %}
                        {% if job.id == skill.job_id.id %}
                                #{{ skill.skill_id|title }}
                        {% endif %}
                        {% endfor %}
{% endwith %}

It just simply uses all the processor and takes a very long time, in the order of 30 minutes.
If I query the DB for all the skillids in the mapping table where jobid = "nnn", the query is really fast.
I was wondering what would be the best approach, as I would like something like this:
{% for job in jobs %}

{{ job.job_title }}

  {{ print all skills for job.job_id}}
{% endwith %}

I've tried with custom filters, but I can't get the code above to work, as it seems I have to filter a value from a for skillmaps foor lop, which it's just the same problem.
Is it possible to define a class with a raw query and pass a variable from the for loop in the template?
Or what would be the best approach?
The model:
class Job(models.Model):
    job_title = models.CharField(max_length=200)
    job_identifier = models.CharField(max_length=140)
    job_site = models.URLField(max_length=200)
    job_url = models.URLField(max_length=400)
    job_salary = models.PositiveIntegerField(default=0, blank=True, null=True)
    def __unicode__(self):
        return self.job_title[:200]

class Skill(models.Model):
    skill_name = models.CharField(max_length=200)
    def __unicode__(self):
        return self.skill_name[:200]

class SkillMap(models.Model):
        job_id = models.ForeignKey(Job)
        skill_id = models.ForeignKey(Skill)
        def get_skills_mod(self, *args):
                return SkillMap.objects.filter(job_id = args)

Thanks,
Isaac

A: This is not very clean solution, but you can fetch all SkillMap at once in your view, create a dictionary with job_id as a key and then inject them into Job :p
from collections import defaultdict

def my_view(request):
    skills = SkillMap.objects.all()
    skills_dict = defaultdict(list)
    for x in skills:
        skills_dict[x.job_id].append(x)

    jobs = Job.objects.all()
    for job in jobs:
        job.injected_skills = skills_dict.get(job.id, [])

    template_context = {
        'jobs': jobs,
    }

template:
{% for job in jobs %}

{{ job.job_title }}

    {% for skill in job.injected_skills %}
         {{ skill }}
    {% endfor %}
{% endwith %}


text:
Q: Objective C MKMapView EXC_BAD_ACCESS I'm a novice ObjC programmer (started learning last week); I'm having some unexpected results trying to get the lat and long from the centre of an MKMapView.
I have the following method that gets called when the map changes region:
- (void)mapView:(MKMapView*)mapView regionDidChangeAnimated:(BOOL)animated {
    NSLog(@"------> %@", mapView);
    latLabel.text = [[NSString alloc] initWithFormat:@"%@", [mapView centerCoordinate]];
}

In the log I'm not getting (null), I'm getting the printout of an MKMapView object; but on the very next line I get an unhandled EXC_BAD_ACCESS.
Any help appreciated, and I'd be happy to offer more info if it's requested.
Thanks.

A: CLLocationCoordinate2D is not an Objective-C object, it's a C structure. You can't directly convert it to an NSString like that.
Try:
CLLocationCoordinate2D center = [mapView centerCoordinate];
latLabel.text = [NSString stringWithFormat:@"(%f, %f)", center.latitude, center.longitude];

Edit: Since you're new to Objective-C, thought you might like some insight into how this problem occurs and why the error message is so non-descriptive.
[NSString stringWithFormat:...] takes a format string and an arbitrary number of parameters. It then parses the format string and fills in the parameters as they're needed.
The %@ token in the format string designates an Objective-C object; i.e. an NSObject * or subclass thereof. NSObject defines the description method that provides an NSString * description of the object. stringWithFormat: calls description on the argument provided for the %@ token to fill it in the format string.
The result of this is a call is made to objc_msgSend with your CLLocationCoordinate2D struct to make the description call because NSString assumes you've provided the right kind of parameter. Then the crash occurs because objc_msgSend treats the struct as if it's an NSObject * pointer and tries to access memory at a bad location. Hence the EXC_BAD_ACCESS.
Disclaimer: This is based on my understanding of Objective-C after only a couple of years, so if I'm wrong about anything, feel free to correct me.


text:
Q: Analyze the continuity of $f(x, y) = \lfloor x\rfloor + \lfloor y\rfloor$ and $f(x, y) = \lfloor x + y\rfloor$ I think that this functions may have discontinuties at integer values.

A: The first function is continuous at $\Bbb R^2\setminus((\Bbb R\times\Bbb Z)\cup(\Bbb Z\times\Bbb R))$.
The second one at $\{(x,y)\in\Bbb R^2:x+y\notin \Bbb Z\}$.
For a proof, consider a point at the guessed set of continuity. They are open sets, so take a neighbourhood of that point. At that neighbourhood the function is constant. Now we must show that the functions are not continuous at any point of the complement. Again take a point and a connected neighbourhood (an open ball, for example). The image of the function in that neighbourhood is a set with more than one integer. This shows discontinuity, since the image of some connected set is not connected.


text:
Q: Set the WordPress thumbnail in php code (automatically) I'm struggling with this for a while now...
I have written a function that automatically gets the thumbnail of the youtube video that i embed in my code. i saved this to a variable $img.
My question now is how can i set $img to be my post thumbnail.
Thank you!

A: Easy process should be save the thumbnail as an custom field, for say "image". Then call this custom field in theme where you need like
<img src="<?php echo get_post_meta($post->ID, "image", true); ?>" alt="" />

You could also attach that image with post.

A: Another alternative is to display your image in your post before any other image. Display it either in your editor, or inside your single.php loop. then use http://wordpress.org/extend/plugins/auto-post-thumbnail/.
You can even hide it using CSS or img tag attributes.


text:
Q: Custom adapter creation in SAP PI 7.1 We have a requirement to create Custom Adapter in PI. Can you guys help me out sharing your ideas, experiences regarding this?
I am using PI 7.1.
And as you know users with less than 1500 reputation can't create new tags. The tag 'sap-pi' is new. So I have used sap-xi tag

A: the task for writing Receiver is relatively simple (as far as I know). For writing Sender, there is more troubles. Look at sourceforge.net, there was an open-source adapter with some docs.
If you want, I can help you in writing but I have no out-of-the-box experience.


text:
Q: javascript function works without argument, function change_tag(url){
  $('.filter_button_confirm').unbind('click').on('click', function(){
    ...
    console.log(url);

    $.ajax({
      url: url,
      type: 'POST',
      data: {
        ...
      },
      beforeSend: function(){
        ...
      }
    })
      .done(function(data){
        ...
      })
  });
};

When I call the function with argument change_tag('/some_url/') of course it works.
But, change_tag() also works perfectly.
It brings data from the url that I set in the past.
console.log(url) shows 'undefined' so I don't know how it knows the url.

A: Since you're not passing in a parameter to the function, url is undefined and so the ajax call gets called with url: undefined. This is the same as not providing an url, and makes it post to the url you're currently on.
For more info you can check the jQuery page: http://api.jquery.com/jquery.ajax/


text:
Q: Getting List of POJOs after executing a native query I am working with Stored Procedures and Views. I call these using entityManager.createNativeQuery . The problem is that createNativeQuery method returns a List<Object[]> but I would rather like to get List<PojoName>. How to achieve this. I am using Hibernate, Spring Data Jpa.
I have heard SqlResultsetMapping annotation can achieve this, but I have not found any example to this.
Please help

A: Have you tried using @Query annotation instead of createNativeQuery method?
You can annotate method in your repository and use native query:
@Query(value = "SELECT * FROM pojo_name p WHERE p.id between ?1 and ?2", nativeQuery = true)
List<PojoName> findByPojos(Long from, Long to);

A: I'm facing a similar problem withnative query with multiple joins and found this ticket DATAJPA-223. Looks like you can't return a type that's not a entity if it's a native query, even using SqlResultsetMapping.


text:
Q: AdvancedDataGrid Flex - Row not getting added under correct column I'm dynamically adding rows and they don't seem to go under the proper column. I have all of my headers in 'headerArray' and the data i need to add is in the string 'item'.
//create an item to work with
var chartItem:Object = new Object();
for( var j:int = 0; j < columnResult.length ; j++ )
{

    var item:String = removeformat(removetd(columnResult[j]));
    //grab the header (this is which column the value will be added
    var head:String = headerArray[j];
    //set the value to header (pair)
    chartItem[head] = item;
}
//add the chartItem (row) to the main collection
arr.addItem(chartItem);
tableCollection = arr;

It's getting all the headers properly and setting the chartItem (from inspection with debugger). When it gets to a row (building from html) where there is an item that only has values for some of the columns, it doesn't add the information under the right column, it just goes from left to right and adds it in the next one.
The behaviour is kind of strange because the chartItem clearly has the right header value and corresponding item value in it, but like I said they don't end up under the right column.
tableCollection gets set as the dataprovider for the grid later (not modified since)

A: var chartItem:Object = new Object();
var span:int = 0;
for( var j:int = 0; j < columnResult.length ; j++ )
{
    var colSpan:int = this.getColSpan(columnResult[j]);
    var item:String = removeformat(removetd(columnResult[j]));
    //grab the header (this is which column the value will be added
    var head:String;
    if (colSpan >1){
        head = headerArray[j];
        span = colSpan;
    } else {
        if (span == 0){
            head = headerArray[j];
        } else {
            head = headerArray[j+span-1]
        }
    }
    //set the value to header (pair)
    chartItem[head] = item;
}
//add the chartItem (row) to the main collection
arr.addItem(chartItem);

If i read the span attribute for the row, i set the NEXT row to be at column+previous colspan. then all the rows line up properly.


text:
Q: How to get the value of a range within a range So I need to extract information from a sheet with only certain values. From about 550 rows down to 50 which are spread across the entire sheet.
So I used autofilter for that. Now I only see the rows which match to my criteria but how can I get the values of a specific range from?
This far I came:
I know that I have to use
RangeINamed.SpecialCells(xlCellTypeVisible)

to work with only the visible information.
It worked for getting the starting and last row
startRow = bulkbatchRange.SpecialCells(xlCellTypeVisible).row
endRow = startRow + bulkbatchRange.SpecialCells(xlCellTypeVisible).rows.Count

But now I need to get the value of a specific column, I want to use a For loop so I can loop through all visible rows.
So I tried to do
RangeINamed.SpecialCells(xlCellTypeVisible).range("U" & rowNumber).value

That didn't work it gave me nothing. Now I'm rather clueless so does someone maybe know how I get the value of that row in column U in RangeINamed?
Thank you

A: You can always retrieve the value in a specific cell like U10 with:
Range("U10").Value

whether the row is hidden or not.
EDIT#1:
Here is a little example that loops down thru column A of an AutoFiltered table.  It looks for the third visible row (not including the header row):
Sub GoDownFilter()
    Dim rLook As Range, r As Range
    Set rLook = Intersect(ActiveSheet.UsedRange, Range("A:A").Cells.SpecialCells(xlCellTypeVisible))
    rLook.Select
    K = 0
    For Each r In rLook
        If K = 3 Then
            r.Select
            MsgBox "The third visible row has been selected"
            Exit Sub
        End If
        K = K + 1
    Next r
End Sub

A: I think you need to choose if you want to get a specific cell like:
Range("U10").Value
Or a relative cell using something like
RangeINamed.SpecialCells(xlCellTypeVisible)(2,3).Value

Or
RangeINamed.SpecialCells(xlCellTypeVisible)(2,3).Address 'To see if you are getting it right

EDIT:
A complete code to Filter and Iterate.
Sub Filter()
Dim tableRange As Range, var, actualRow As Integer, lastRow As Integer

Set tableRange = Range("PUT_THE_TABLE_RANGE_HERE")

' Filter
With tableRange
    Call .AutoFilter(5, "SPECIFIC_FILTER")
End With

Set f = tableRange.SpecialCells(xlCellTypeVisible)

With tableRange
    Call .AutoFilter(5)
End With

For Each var In f.Cells.Rows
    actualRow = var.Row
    If actualRow <> 1 Then
        ' Do something
    End If
Next
End Sub


text:
Q: Are sum types defined with UnboxedSums more efficient than plain enum? For example, here is simple Haskell enum data type:
data Bool = False | True

There's -XUnboxedSums extension since GHC-8.2.1 that allows to define sum types in more memory-efficient way. Here is a quote from documentation:

In the degenerate case where all the alternatives have zero width, such as the Bool-like (# (# #) | (# #) #), the unboxed sum layout only has an Int32 tag field (i.e., the whole thing is represented by an integer).

I wonder, whether this representation is more efficient than using simple plain Haskell enum data type?
And here is the full documentation:

*

*https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/glasgow_exts.html#unboxed-sums

A: Semantics and Representation
The two types cannot be used interchangeable.
The type
data Bool = False | True

is a lifted type. This means that a variable x :: Bool can still be unevaluated (e.g. a thunk). It will therefore be represented as a pointer.
In contrast
(# (# #) | (# #) #)

is unlifted, and really can only have the two values, and will be represented as just a machine integer.
Space efficiency
This does, however not mean that the latter is more space efficient: Because True and False are nullary constructors (they take no arguments), they exist once and for all in the static code of your program, and the pointers just point to them. So the cost is one machine word in all cases.
Run time efficiency
The unboxed variant may be slightly more efficient than Bool:

*

*For Bool, the code first has to check is this already evaluated?, and then it can branch on which constructor it is.
The branching is pretty efficient: The code does not have to follow the pointer for that: The "pointer tag" in the low few bits of the pointer address will indicate which constructor it is. There is a slight cost for masking the other bits, though.

*In the unboxed variant, well, it's just 0 or 1, and no thunk check is needed.
Things that might be true one day
jberryman says: as of Jan 2021 the following don't appear to be implemented yet, but this is how things might one day work.
Unboxing in data types
If you define a data type like this
data Foo = Foo {-# UNPACK #-} !Bool

you should get exactly the same result as if you'd write
data Foo = Foo (# (# #) | (# #) #)

as that was the main purpose of the unboxed sum extension.
Unboxing in functions
If you define a function that is strict in a Bool argument, e.g.
foo True = "Hello"
foo False = "World!"

then I could imagine (but did not check) that the compiler optimizes that into a worker that takes a (# (# #) | (# #) #) and a wrapper that takes care of the thunk-check. The wrapper might then inline in use-sites where foo is used, and everything might end up in terms of (# (# #) | (# #) #).
Conclusion
Don't bother.


text:
Q: extracting all .com, .in, .co.in from all elements I have data in csv which contains following column
ARTICLE_URL
http://twitter.com/aviryadsh/statuses/528219883872337920
http://www.ibtimes.co.in/2014

I want to create an another columns next to this column where I can have only the web address like twitter.com, team-bhp.com, ibtimes.co.in,broadbandforum.co.
I have tried
text$ne=str_extract(Brand$ARTICLE_URL, '\\w+(.com)')

but this is giving only url which are ending with .com how to fetch all other also.

A: I'd recommend using string replacement as opposed to string extraction in this instance. It's possible to do with string extraction, but the regular expression is kind of messy and not as readable as a two-step string replacement method. Here's how I'd do it:
urls <- c("http://twitter.com/aviryadsh/statuses/528219883872337920", "http://www.ibtimes.co.in/2014", "https://www.ibtimes.co.in/2014")
tmp <- stringr::str_replace_all(urls, "https?://|www.", "")
domains <- stringr::str_replace_all(tmp, "/.*", "")

And then looking at our output:
domains
# [1] "twitter.com"   "ibtimes.co.in" "ibtimes.co.in"


text:
Q: Can't see "Install alongside Windows" option I am new to Ubuntu and very confused. I have installed  Ubuntu 14.04.3 onto a USB flashdrive and tried it from that. I must say I like what I saw BUT I have a few initial questions. First is that when I run install (to install it on my laptop, a Spanish Compaq CQ57) where I expect to see a window giving me a choice of 'Install Ubuntu alongside Windows 7', 'Replace Windows 7 with Ubuntu'  or 'Something else' there is a different window which doesn't have the 'Install alongside' option. Which option in this window should I select if I want to install alongside Windows 7? And then what do I do?
Secondly, the keyboard on my laptop doesn't have a number pad and it seems as though none of the numerous configurations available are compatible with my machine. I have seen lots of advice on forums but most seem to be beyond the scope of a non-techie, wary novice like me.
I would really like to move away from Windows (I have tried and don't like Windows 10, although I have quite happily used 7 for several years) but I am beginning to wonder if Ubuntu is beyond me and if I should give up and stick to Windows.
Thanks for any help you can give

A: You only get to see the "install alongside" if there is place to create a system alongside what is currently there. So ... use your favorite partitioning tool to create "unallocated space" (for Ubuntu 25Gb or more) and it will show up.


text:
Q: Do unranked games have matchmaking by skill/level? I play League of Legends since a few month casually on-and-off doing quite ok. I only played a few ranked matches last season (3 wins, 2 losses, 1339 rating) and recently just farm easy IP via coop (yay for noone raging in those games) and do the occasional unranked match.
Recently, my colleagues started playing League of Legends, too, and... well, they are bad. Really, really bad, as in 0/17 bad (not feeding intentionally)... BUT... somehow they still manage to win games with that score.
My matches are usually decided by someone going 0/2 or similar which basically ends up being game over right there, so i'm wondering if they are just playing far worse opponents or if they just have good teammates.
Note:
I'm level 30, they are between level 8-12.

A:
League of Legends uses a mathematical system to match up players of similar skill in the "Normal" and "Ranked" game types. Source

So just like in "Ranked," "Normal" uses its own Elo for matchmaking. It's just hidden.
Most likely, though, because your colleagues are new, their opponents aren't as good as the ones you're facing now. In other words, your colleagues' opponents don't capitalize on mistakes as much as your opponents might, because you're a better player, and the people you play against scale accordingly.
That's why your colleagues can get scores like 0/17 and still win a game.


text:
Q: how can I comment a line with php short echo tag? In my yii2 framework there are lots of line with php short echo tags <?=
for example:
<?= Html::a('Create Medicine', ['create'], ['class' => 'btn btn-success']) ?>
<?= $form->field($model, 'medicine_name')->textInput(['maxlength' => 50]) ?>

I couldn't make out an easy way to comment out this lines without first changing the opening tag. is there an easy way to this?
Thanks.

A: I figure the easiest thing to do is replace <?= with <?php //, though it does change the opening tag...
for example
<?php //= Html::a('Create Medicine', ['create'], ['class' => 'btn btn-success']) ?>
<?php //= $form->field($model, 'medicine_name')->textInput(['maxlength' => 50]) ?>

A: This should work for you:
<?= ""; stuff here ?>

A: try this:
<? //= Html::a('Create Medicine', ['create'], ['class' => 'btn btn-success']) ?>
<? //= $form->field($model, 'medicine_name')->textInput(['maxlength' => 50]) ?>

A: <?= ''??Previous expression here ?>
<?= ''??Html::a('Create Medicine', ['create'], ['class' => 'btn btn-success']) ?>
<?= ''??$form->field($model, 'medicine_name')->textInput(['maxlength' => 50]) ?>


text:
Q: How to conclude the order of $G$ is $p^{m+n}$. I have this exact sequence $$
0\to \mathbb{Z}_{p^m}\overset{f}\to G\overset{g}\to \mathbb{Z}_{p^n}{\to} 0
$$
where $G$ is finitely generated. I want to prove that $|G|=p^{m+n}$ and a friend told me to look to $f(1_{\mathbb{Z}_{p^m}})$ and $g^{-1}(1_{\mathbb{Z}_{p^n}})$, where $1_{\mathbb{Z}_{p^m}}$ and $1_{\mathbb{Z}_{p^m}}$ are the generators of $\mathbb{Z}_{p^m}$ and $\mathbb{Z}_{p^m}$.
In fact, I see an image and preimage of generators are generators.
I've already proven that the image and the preimage are, indeed, generators. The main question is how to prove that they not generate the same group (I think that we use the fact of $im(f)=ker(g)$, but cannot concluded yet) and $f(1_{\mathbb{Z}_{p^m}})$ and $g^{-1}(1_{\mathbb{Z}_{p^n}})$ generate $G$.


text:
Q: Errors when creating layer in GeoServer I am trying to create raster layer mosaic time dimension plugin. I have created datastore, timeregex and indexer files based on settings in existing working layers. After creating layer, I can't see any data in layer preview, only black pixels and gray_index set to zero.
Edit:
I switched to verbose logging and tried to reproduce error with layer consisting of rasters already running behind existing layers, but everything worked fine. I guess this narrows It down to actual problem with rasters.
Output from GeoServer working layers:
2022-06-12 09:35:43,999 DEBUG [geotools.jdbc] - CREATE CONNECTION
2022-06-12 09:35:44,003 DEBUG [data.jdbc] - exporting PropertyName
2022-06-12 09:35:44,003 DEBUG [geotools.jdbc] - SELECT min("ingestion") FROM "public"."t2m"
2022-06-12 09:35:44,005 DEBUG [geotools.jdbc] - CLOSE CONNECTION
2022-06-12 09:35:44,017 INFO [geoserver.wms] -
Request: getMap
    Angle = 0.0
    BaseUrl = http://localhost:8080/geoserver/
    Bbox = SRSEnvelope[12.672434907113352 : 35.97501363262053, 34.464999543113265 : 47.54499877841993]
    BgColor = java.awt.Color[r=255,g=255,b=255]
    Buffer = 0
    Clip = null
    CQLFilter = null

Output from GeoServer not working layer:
2022-06-12 09:15:28,910 DEBUG [geotools.jdbc] - CREATE CONNECTION
2022-06-12 09:15:28,910 DEBUG [data.jdbc] - exporting LogicFilter
2022-06-12 09:15:28,910 DEBUG [data.jdbc] - exporting PropertyName
2022-06-12 09:15:28,910 DEBUG [data.util] - CRSConverterFactory can be applied from Strings to CRS  only.
2022-06-12 09:15:28,910 DEBUG [data.util] - InterpolationConverterFactory can be applied from Strings to Interpolation only.
2022-06-12 09:15:28,910 DEBUG [data.jdbc] - exporting SQL ComparisonFilter
2022-06-12 09:15:28,910 DEBUG [data.jdbc] - exporting PropertyName
2022-06-12 09:15:28,910 DEBUG [data.jdbc] - exporting PropertyName
2022-06-12 09:15:28,910 DEBUG [geotools.jdbc] - SELECT "location","ingestion",ST_AsEWKB("the_geom") as "the_geom" FROM "public"."sp" WHERE ("the_geom" && ST_GeomFromWKB(?, 4326) AND "ingestion" = ? AND "ingestion" IS NOT NULL )
2022-06-12 09:15:28,910 DEBUG [geotools.jdbc] - 1 = POLYGON ((13.273016488845716 34.045000000000115, 30.26948593598513 34.045000000000115, 30.26948593598513 46.61500000000059, 13.273016488845716 46.61500000000059, 13.273016488845716 34.045000000000115))
2022-06-12 09:15:28,910 DEBUG [geotools.jdbc] - 2 = 2022-06-05 12:00:00.0
2022-06-12 09:15:28,910 DEBUG [gce.imagemosaic] - Trying to resolve path:
type:RELATIVE
parentLocation:file:/home/user/geoserver/geoserver-2.19.0-bin/bin/../data_dir/data/sp/
location:sp_2022060512.tiff
2022-06-12 09:15:28,911 INFO [gce.imagemosaic] - Unable to read image for file file:/home/user/geoserver/geoserver-2.19.0-bin/bin/../data_dir/data/sp/sp_2022060512.tiff
2022-06-12 09:15:28,911 DEBUG [imagemosaic.catalog] - Skipping invalid granule
java.lang.IllegalArgumentException: Illegal argument: "granuleLocation=sp_2022060512.tiff".

How can I resolve this?

A: Eventually, it turned out that it was an issue with metadata.
gdalinfo of correct tiff was:
Metadata:
  AREA_OR_POINT=Area

whereas problematic one was:
Metadata:
  AREA_OR_POINT=Area
  GRIB_cfName=surface_air_pressure
  GRIB_cfVarName=sp
  GRIB_gridDefinitionDescription=Latitude/Longitude Grid
  GRIB_gridType=regular_ll
  GRIB_iDirectionIncrementInDegrees=0.03
  GRIB_iScansNegatively=0
  GRIB_jDirectionIncrementInDegrees=0.03
  GRIB_jPointsAreConsecutive=0
  GRIB_jScansPositively=1

After applying:
   raster=rasterio.open(output_filename)
   data=raster.read()
   nds=rasterio.open(
        output_filename,
        'w',
        driver='GTiff',
        compress="LZW",
        blockxsize=128,
        blockysize=128,
        height=height,
        width=width,
        count=1,
        dtype=data.dtype,
        crs='+proj=latlong',
        transform=transform,
        tags={'AREA_OR_POINT': 'Area'},
        )
    nds.write(data)
    nds.close()

everything worked fine.


text:
Q: Flag as spam not working I am trying to flag this post as spam, but after selecting "It is spam" and hitting the "Flag answer" button it just hangs. I've tried many times and let it sit for several minutes before posting here.
I'm using Firefox 4 stable on Ubuntu.

A: I'm prepared to take the blame :)
Fixed now.


text:
Q: Microsoft , Hotmail , Live , MSN, Outlook , unable to send emails and no support received from microsoft in 3 months we are trying asking for that Ok this is somenthing unbelievable, we have a website, users sign up and receives links to confirm they signed up BUT:
 1 - microsoft blocked our IP (no one with microsoft email account can receive our emails)
 2 - we tryed contacting microsoft submitting the detailed form about our problem
 3 - we posted 3 times in their community about our problem
 4 - we tweeted they about our problem
 5 - we tryed finding out some telephone support number (the few there are arent' helping at all)

Do you think we solved?  the answer is NO :/
We still unable to send emails from our IP to microsoft email accounts, since 3 months back.
Our emails are perfect we checked all the email headers following microsoft guidelines  but it seems not enought, checking our IP reputation it seems everythings ok, indeed we can send email easly to any other provider , gmail, yahoo, etc
Do you know any other way to try to get help ?
FULL STACK ERROR FROM MICROSOFT:
 host mx1.hotmail.com[65.55.37.120] said: 550
    SC-001 (COL0-MC4-F28) Unfortunately, messages from 94.23.***** weren't
    sent. Please contact your Internet service provider since part of their
    network is on our block list. You can also refer your provider to
    http://mail.live.com/mail/troubleshooting.aspx#errors. (in reply to MAIL
    FROM command)

We are running a Virtual Private Server , so no HOSTING SITE, using NGINX too

A: Microsoft ban whole /24 IP ranges they do not usually block a single IP, as a service provider I can tell you that it is near impossible to get MS to budge on such problems even more so when other people in the same IP range as you could be sending spam or poorly constructed emails from badly configured servers.
The best solution to this is to pipe your emails through another IP/service such as authsmtp or alter things on your site so that any emails going to a hotmail email address come from a hotmail email address.
Also keep in mind that if your website is just a standard hosting package you are sharing the IP with 100's if not 1000's of others who could be hurting your chances, to be blunt, Microsoft don't care about your site and no amount of complaining will make them care, if email delivery is vital for you find an assured method of delivery instead.


text:
Q: Clear floats not working I have a website that is working as expected in FF 19 (when did it get so high?), IE, Opera but not in Chrome or Safari.  Sometimes it is layed out properly in Chrome/Safari but if you hit F5 enough eventually one of the renderings will lay it out unexpectedly.
Here is the link http://www.spokanewastewater.org/Businesses.aspx
The left sidebar is float:left, the content is all in a div with display:inline-block and all 3 link lists are float:left so then at "the Role of Industry" it has a
 before it.  Yet sometimes chrome/safari likes to put the paragraph above the "important links" section??  Is this something to do with webkit rendering??  It's odd that it is only broken sometimes and hitting f5 enough breaks it.

A: Don't use a br to control clear. Change your br to be something more appropriate (a div realistically):

Making that change using the dev tools in Chrome on your site rectifies the issue.

A: Using extra markup for clearing floats in this day and age is pretty archaic.  There are 2 widely accepted techniques for clearing floats that don't require additional markup.
http://codepen.io/cimmanon/pen/qDjdr
Overflow:
.parent {
    overflow: hidden;
}

Micro Clearfix:
http://nicolasgallagher.com/micro-clearfix-hack/
.parent:before,
.parent:after {
    content: " "; /* 1 */
    display: table; /* 2 */
}

.parent:after {
    clear: both;
}

/**
 * For IE 6/7 only
 * Include this rule to trigger hasLayout and contain floats.
 */
.parent {
    *zoom: 1;
}


text:
Q: PHP socket with jQuery/AJAX user-end I've been working on sockets, generally in PHP for a while. Currently I have a PHP client for connecting to a chat server, and output every each data sent from server it's connected to.
To explain that in a wider matter, I accomplished this using flush() function in PHP to write out every each buffer waiting in the loop. Buffer reader is withing a while where the condition is the status of the connection socket. But this matters less.
Now to what I want to accomplish. I want to keep socket handling to server side and data from server outputted to client, via AJAX/jQuery. So far, my researches always returned me HTML5 WebSocket and node.js, however, I "have to" be real picky about this, as for users of this, my minimal dependency might be:

*

*WinXP IE6 users(Already disables jQuery, even)

*Users without JAVA/Flash installed

So I have to think of possibilities in this, which is why I can't use a Flash/Java backend or a new technology like WebSockets, and neither I want to handle server stuff in the client. I really hate to be stuck in old technology but for this it's a must.
As I was searching around, I found this one being as similiar to my needs.
Is PHP socket a viable option for making PHP jQuery based chat?
And to quick review the answers, they all point to one direction, PHP multi-process and memory eating. I know this is a minus, but it's the best I can take for now. But yet still, there'll be timeout disconnects for inactive connections within a certain delay, and extension of the delay if wanted. So I'm not much onto this one.
Secondly, the last answer pointing to "Ajax Chat Application Tutorial", I made an overall review but whoa, writing each line into an html file and re-including it each time, that is which I could do without using an extra file but, is it really necessary? Plus re-reading the file from server side, and re-importing the whole read file into document every each time, isn't that just worse for "both sides"?
Either ways that's about it, I wasn't able to come to a conclusion for a while, and it happened, here I am again. (:P) Waiting for your answers/suggestions/ideas, thanks by now.
Regards.

A: There is server software available that specializes in such matters. Is called a push server/service. There's for example APE (http://www.ape-project.org/); according to their website, it's compatible with all web browsers and they even got a demo chat there. I'd suggest you to go for that solution.


text:
Q: Akka-Streams: At-Least-Once-Delivery behaviour with Kafka and Cassandra I'm starting with Akka Streams and so far everything is going well. However, I have met with a use case that I don't know how to approach. The scenario is a stream with an ActorPublisher as a source that is consuming messages from Kafka and a subscriber as a sink that updates a Cassandra table.
Kafka ~> some mapping operations ~> Cassandra
The point is that I'd like to explicitly confirm to Kafka every time a message has been successfully processed and inserted into Cassandra so that I could re-read the message in case a disaster happens and the service fails, i.e. some kind of at least once delivery behaviour. How could I approach this in terms of Akka Streams?. Is a supported scenario?.
It's true that I always can configure the Kafka consumer with auto-commit behaviour but I'd rather take control of how I'm reading the messages.
Update
Regarding this topic, we're currently evaluating Reactive Kafka where they've included manual commit in kafka as of 0.8 version (kudos for these guys). This feature would allow us implement the alod behaviour we need.

A: I think you could use a custom stream processing using a PushPullStage as explained in akka streams documentation


text:
Q: Using big matrix in Matlab I want to use some big matrix that can't fit in RAM memory.My matrix is not sparse.
I need this for some batch\chunk processing or online machine learning algorithms.
What I need:
1.Read some chunk of data(that can fit in RAM) from big matrix stored on hard drive and preferably I want to access it like ordinary matlab matrix.
2.Append some chunk of data to end of the big matrix stored on disc.

A: You will find an answer here on reading/writing part of a .mat matrix.
%read
matObj = matfile('myBigData.mat');
loadedData = matObj.X(1:4,1:4);

%write
matObj.X(81:100,81:100) = magic(20);

EDIT
Here is some code showing the append function
A = ones(10,10);
save('A.mat', 'A','-v7.3');
clear A

matObj = matfile('A.mat','Writable',true);
matObj.A(8:10,8:10) = ones(3,3) * 3;       %modify
matObj.A(11,:) = ones(1,10)*4;             %append

disp(matObj.A)

The full matlab help for .mat (including limitations) is here.

A: There is an excellent project on Matlab Central File Exchange that addresses the problem of large number of data points (or large matrices).
It's Project Waterloo File and Matrix Utilities by Malcolm Lidierth
http://www.mathworks.co.uk/matlabcentral/fileexchange/12250-project-waterloo-file-and-matrix-utilities

A: @geek_girl
Thanks for those comments. The code for the File and Matrix Utilities is on SourceForge:
https://sourceforge.net/projects/waterloo/files/Waterloo%20MATLAB%20File%20and%20Matrix%20Utilities/
A Git repo for the whole project is at:
https://sourceforge.net/p/waterloo/beta/ci/master/tree/


text:
Q: How to Target Web Parts to an Audience Hi i am new in sharepoint. How to progammatically Target Web Parts to an Audience suggest any answer.

A: As per this link:
To provide permission to a sharepoint web part for specific SharePoint Group, we have to use AudienceManager as shown below
SPWeb currentSite = SPContext.Current.Site.RootWeb;
SPSite spSite = currentSite.Site;

SPServiceContext sc = SPServiceContext.GetContext(spSite);
AudienceManager am = new AudienceManager(sc);

Microsoft.SharePoint.WebPartPages.SPLimitedWebPartManager mgr = null;
mgr = currentSite.GetLimitedWebPartManager("SitePages" + "/" + page,
      System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
foreach (System.Web.UI.WebControls.WebParts.WebPart webPart in mgr.WebParts)
{
     if (webPart.Title == "WebPartTitle")
     {
          //Get the Existing Audience for the Web Part
          string audWebPart = webPart.AuthorizationFilter;
          //If there is no Audience for the Web Part just add it
          if (audWebPart == "")
          {
               webPart.AuthorizationFilter = ";;;;" + NewAudience;
          }
          //If already Audiences are exist for the Web Part then append new Audience
          else
          {
               webPart.AuthorizationFilter = audWebPart + "," + NewAudience;
          }
          mgr.SaveChanges(webPart);
          lblMessage.Text = "Succeeded...";
     }
}

If we just set the value for AuthorizationFilter property, then the existing Audiences will be overwritten.
To avoid it first we have to check whether already audiences exists for that web part. If so we have to append it.
The SharePoint Server 2010 framework requires that three kinds of values be separated by a pair of semicolons (";;"). Multiple values for global audiences and SharePoint groups are delimited by commas, and multiple values for distribution lists are delimited by newline characters ("\n"). Therefore in the above example we used ";;;;" to provide valid string to the AuthorizationFilter property.


text:
Q: Dapper map multiple joins Sql Query I want to map complex object to dapper result from query which has two inner joins. I know we've solution to map one inner join but I want to map two inner joins result.
Here is the Scenario:
My Classes are:
public class Order
{
    public int id { get; set; }
    public string order_reference { get; set; }
    public string order_status { get; set; }
    public List<OrderLine> OrderLines { get; set; }
}

public class OrderLine
{
    public int id { get; set; }
    public int order_id { get; set; }
    public string product_number { get; set; }
    public List<OrderLineSize> OrderLineSizes { get; set; }
}

public class OrderLineSize
{
    public int id { get; set; }
    public int order_line_id { get; set; }
    public string size_name { get; set; }
}

Order has OrderLines as List and OrderLine as OrderLineSizes as List.

Now, Here is my query base on that I want to populate List<Order> with correct data:
SELECT *
FROM orders_mstr o
INNER JOIN order_lines ol ON o.id = ol.order_id
INNER JOIN order_line_size_relations ols ON ol.id = ols.order_line_id

Here is what I tried so far:
var lookup = new Dictionary<int, Order>();
            connection.Query<Order, OrderLine, Order>(@"
                    SELECT o.*, ol.*
                    FROM orders_mstr o
                    INNER JOIN order_lines ol ON o.id = ol.order_id
                    ", (o, ol) => {
                    Order orderDetail;
                    if (!lookup.TryGetValue(o.id, out orderDetail))
                    {
                        lookup.Add(o.id, orderDetail = o);
                    }
                    if (orderDetail.OrderLines == null)
                        orderDetail.OrderLines = new List<OrderLine>();
                    orderDetail.OrderLines.Add(ol);
                    return orderDetail;
                }).AsQueryable();

            var resultList = lookup.Values;

Using this, I can successfully map order object with OrderLine but I want to populate OrderLineSizes as well with correct data.

A: I don't know what is class 'OrderDetail' you don't provide it so I used Order class.
This can also be done by QueryMultiple but because your question includes INNER JOIN I don't use it.
public Dictionary<int, Order> GetOrderLookup()
{
    var lookup = new Dictionary<int, Order>();

    const string sql = @"   SELECT  o.id,
                                    o.order_reference,
                                    o.order_status,

                                    ol.id,
                                    ol.order_id,
                                    ol.product_number,

                                    ols.id,
                                    ols.order_line_id,
                                    ols.size_name
                            FROM    orders_mstr o
                            JOIN    order_lines ol ON o.id = ol.order_id
                            JOIN    order_line_size_relations ols ON ol.id = ols.order_line_id";

    List<Order> orders = null;
    using (var connection = OpenConnection(_connectionString))
    {
        orders = connection.Query<Order, OrderLine, OrderLineSize, Order>(sql, (order, orderLine, orderLizeSize) =>
        {
            orderLine.OrderLineSizes = new List<OrderLineSize> { orderLizeSize };
            order.OrderLines = new List<OrderLine>() { orderLine };
            return order;
        },
        null, commandType: CommandType.Text).ToList();
    }

    if (orders == null || orders.Count == 0)
    {
        return lookup;
    }

    foreach (var order in orders)
    {
        var contians = lookup.ContainsKey(order.id);
        if (contians)
        {
            var newLinesToAdd = new List<OrderLine>();
            var existsLines = lookup[order.id].OrderLines;
            foreach (var existsLine in existsLines)
            {
                foreach (var newLine in order.OrderLines)
                {
                    if (existsLine.id == newLine.id)
                    {
                        existsLine.OrderLineSizes.AddRange(newLine.OrderLineSizes);
                    }
                    else
                    {
                        newLinesToAdd.Add(newLine);
                    }
                }
            }
            existsLines.AddRange(newLinesToAdd);
        }
        else
        {
            lookup.Add(order.id, order);
        }
    }

    return lookup;
}

A: I decided to use Dapper to get a big data for calculating somethings. This is my dapper extension method to join 3 table in _RepositoryBase.cs file.
    public List<Tuple<T, T2, T3, T4>> QueryMultiple<T2, T3, T4>(string sql, object param)
        where T2 : class
        where T3 : class
    {
        using (var con = new SqlConnection(GetConnStr()))
        {
            if (con.State == ConnectionState.Closed)
                con.Open();

            var query = con.Query<T, T2, T3, T4, Tuple<T, T2, T3, T4>>(sql, (t, t2, t3, t4) => Tuple.Create(t, t2, t3, t4), param);

            //if (query.Count() == 0)
            //    return new List<T>();

            var data = query.ToList();

            con.Close();
            con.Dispose();

            return data;
        }
    }

Then, this function will help you to get sql joined data via dapper.
    public List<Table1> GetSqlJoinedDataViaDaper(int customerId)
    {
        var repo = new GenericRepository<T_LOOKUP>();
        var sql = @"select table1.ID Table1ID, table1.*,
                    table2.ID Table2ID, table2.*,
                    table3.ID Table3ID, table3.*
                    from dbo.Table1 table1 (nolock)
                    left outer join dbo.Table2 table2 (nolock) on table2.ID=table1.FKTable2ID
                    left outer join dbo.Table3 table3 (nolock) on table3.ID=table1.FKTable3ID
                    where table1.CustomerID=@p1 ";

        var resultWithJoin = repo.QueryMultiple<Table1, Table2, Table3>(sql,
            new { p1 = 1, splitOn = "Table1ID,Table2ID,Table3ID" }).ToList();

        var retval = new List<Table1>();
        foreach (var item in resultWithJoin)
        {
            Table1 t1 = item.Item2; //After first split
            t1.Table2 = item.Item3; //After Table2ID split
            t1.Table3 = item.Item4; //After Table3ID split

            retval.Add(t1);
        }
        return retval;
    }

Summary:
Write your select and insert split between tables. Say splits to Dapper and get your data. I used this and worked better than Entity Framework.

A: I tried my best and solve it.
Here is the more easy and accurate solution as per me.:
var lookup = new Dictionary<int, OrderDetail>();
            var lookup2 = new Dictionary<int, OrderLine>();
            connection.Query<OrderDetail, OrderLine, OrderLineSize, OrderDetail>(@"
                    SELECT o.*, ol.*, ols.*
                    FROM orders_mstr o
                    INNER JOIN order_lines ol ON o.id = ol.order_id
                    INNER JOIN order_line_size_relations ols ON ol.id = ols.order_line_id
                    ", (o, ol, ols) =>
            {
                OrderDetail orderDetail;
                if (!lookup.TryGetValue(o.id, out orderDetail))
                {
                    lookup.Add(o.id, orderDetail = o);
                }
                OrderLine orderLine;
                if (!lookup2.TryGetValue(ol.id, out orderLine))
                {
                    lookup2.Add(ol.id, orderLine = ol);
                    orderDetail.OrderLines.Add(orderLine);
                }
                orderLine.OrderLineSizes.Add(ols);
                return orderDetail;
            }).AsQueryable();

            var resultList = lookup.Values.ToList();


text:
Q: Cisco RV220W - No route to host between devices on the same subnet I have a problem where devices cannot connect to each other using their respective IP addresses, but if a device uses it's own IP address it can connect.  When you try and connect to a remote device you get a no route to host.  Pinging the device by their IP address also doesn't work.  The router is configured to use half duplex and we have 3 access points configured on it.  The devices are connected on the same wifi access point so they should be able to see each other.
So any ideas on what is preventing devices from seeing each other?

A: Check your access point for a 'Wireless Separation' option.
Some access points are configured by default to restrict traffic between wireless devices.


text:
Q: WebSocket сервер на C# Требуется написать WebSocket сервер. Сначала я попробовал использовать Socket и получил много проблем: handshake, декодирование данных и т.д. Стал искать что-нибудь готовое, узнал, что в .net есть System.Net.WebSockets, стал разбираться и ничего не понятно. Кто-нибудь знает как им пользоваться без использования asp? Может примерчик какой-нибудь...гугл не помогает.

A: Готовая реализация декодирования фреймов WebSocket обсуждалась в этом вопросе. Если вас интересует всё решение, внизу есть ссылка. В нем так же есть рукопожатие, декодирование сообщений для клиента - это полностью работающий сервер WebSocket


text:
Q: Dependence of streamlined flow on viscosity My teacher told true class the following statement:-

Streamlined flow is more likely for liquid with more viscosity as sturdy flow can only be achieved with slow speed.

It's true that viscosity causes slow speed of liquid but viscosity is due to relative motion of layers of fluid from a fixed point. Then shouldn't viscosity causes a non sturdy flow due to relative motion of layers of fluid even though the speed is slow causing disruption to streamlined flow?

A: What your teacher told the class is true, though it's more complicated than that.
For any flowing fluid there are two types of force. The viscous force is due to the viscosity of the fluid, and that's the obvious force that everyone thinks about. However a fluid has a mass, and therefore when it's moving it has a momentum, and therefore whenever the fluid changes direction the momentum changes and this produces a force. These forces are known as inertial forces.
As a general rule, when viscous forces dominate the flow is laminar, and this tends to happen at high viscosities and low flow rates. When inertial forces dominate the flow is turbulent, and this happens at low viscosities and high flow rates.
We define a parameter called the Reynolds number, which is basically the ratio of the inertial forces to viscous forces. So a high Reynolds number means turbulent flow and a low Reynolds number means laminar flow. The expression for the Reynolds number varies depending on the system, but for example the equation for the Reynolds number of a fluid flowing in a pipe is:
$$ Re = \frac{\rho v D_H}{\mu} $$
where $\rho$ is the density, $v$ is the flow velocity, $D_H$ is the effective pipe area and $\mu$ is the viscosity. So the dependance on viscosity is:
$$ RE \propto \frac{1}{\mu} $$
and as your teacher says, high viscosity means a low Reynolds number and therefore the flow is more likely to be laminar.


text:
Q: How can I create object of certain (big) size? I wonder if there's a way to create let's say 1 MB object other than a very big list. It could be anything as long as it's reference type.
I want to use it in memory profiler tests so I don't need any special behavior. Maybe some unit test engine or Moq have such feature?

A: An array is pretty straightforward to create.
Console.WriteLine($"Allocated memory: {GC.GetTotalMemory(false)}");
var array = new byte[1024 * 1024];
Console.WriteLine($"Allocated memory: {GC.GetTotalMemory(false)}");

Output:
Allocated memory: 160872
Allocated memory: 1209504


text:
Q: Using Array.prototype.sort.call to sort a HTMLCollection var down=function(a,b){alert(a)}
Array.prototype.sort.call(table.tBodies[0].childNodes,down)
Array.prototype.sort.call([0,1,2,3],down)

Why do I not get alerts from the first sort call?

A: My proposal to sort an HTMLCollection is:

window.onload = function() {
  var parentNode = document.getElementById('test-list');
  var e = document.getElementById('test-list').children;
  [].slice.call(e).sort(function(a, b) {
    return a.textContent.localeCompare(b.textContent);
  }).forEach(function(val, index) {
    parentNode.appendChild(val);
  });
}

Scheme

JavaScript

Python

Ruby

Haskell

A: Convert the NodeList to an array first:
var elements = [].slice.call(table.tBodies[0].childNodes);

and then call sort normally:
elements.sort(down);

It seems sort cannot handle array-like objects. This is probably because NodeList does not provide any methods to change the list, but sort sorts the array in-place.
Update: For more information, from the specification:

Perform an implementation-dependent sequence of calls to the [[Get]] , [[Put]], and [[Delete]] internal methods of obj.

I assume NodeLists don't have these internal methods. But this is really just an assumption. It could also be that this is implementation dependent.
I also suggest you use .children [MDN] instead of .childNodes to only get element nodes. Update: Or .rows [DOM Spec] as @patrick suggests.

A: I correct the code of gaetanoM, this one works with IE :

window.onload = function() {
  var parentNode = document.getElementById('test-list');
  var e = document.getElementById('test-list').children;
  [].slice.call(e).sort(function(a, b) {
   if (a.textContent > b.textContent) return 1;
  if (a.textContent < b.textContent) return -1;
  return 0;
   }).forEach(function(val) {
    parentNode.appendChild(val);
  });
}

Scheme

JavaScript

Python

Ruby

Haskell

Tata

Aaaaa

Drue


text:
Q: How to merge Excel column with dynamic value I trying to merge the excel column when there is same value in the first 2 row. The value is coming from my database query. Currently what I had generated is like this:

I want to merge the column like this:

Here is my function code:
 public static async Task<MemoryStream> getNewListingExcelWithContentColumnMerge<T>(List<T> list, List<string> header, string name, string headerTitle)
    {
        try
        {
            int row = 3;
            int col = 1;

            MemoryStream output = new MemoryStream();
            using (ExcelPackage package = new ExcelPackage())
            {
                ExcelWorksheet ws = package.Workbook.Worksheets.Add(name);
                ws.PrinterSettings.PaperSize = ePaperSize.A4;
                ws.PrinterSettings.FitToPage = true;

                ws.Cells["A1:D1"].Merge = true;
                ws.Cells["A1:D1"].Value = headerTitle;

                for (int i = 0; i < header.Count(); i++)
                {
                    ws.Cells[row, col].Value = header[i];
                    col++;

                }

                ws.Cells[1, 1, 1, col].Style.Font.Bold = true;

                col = 1;
                row++;
                for (int i = 0; i < list.Count(); i++)
                {
                    Type type = list[i].GetType();
                    PropertyInfo[] properties = type.GetProperties();
                    foreach (PropertyInfo property in properties)
                    {
                        object asd = property.GetValue(list[i], null);
                        //Add data to the next line if consist of '\n'.
                        if (asd != null && asd.ToString().Contains(Environment.NewLine))
                        {
                            var splitValue = asd.ToString().Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
                            var sameValuePlacementList = new List<int>();
                            for (var j = 0; j < splitValue.Count(); j++)
                            {
                                if (j == 0)
                                {
                                    ws.Cells[row, col].Value = splitValue[j];
                                    ws.Cells[row, col].Style.WrapText = true;
                                }
                                else
                                {
                                    ws.Cells[row, col].RichText.Add(Environment.NewLine + splitValue[j]);
                                }
                            }
                        }
                        else
                        {
                            ws.Cells[row, col].Value = asd;
                        }
                        col++;
                    }
                    col = 1;
                    row++;
                }

                ws.Cells[3, 1, ws.Dimension.End.Row, ws.Dimension.End.Column - 1].AutoFitColumns();
                ws.Cells[3, 1, ws.Dimension.End.Row, ws.Dimension.End.Column - 1].Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
                ws.Cells[3, 1, ws.Dimension.End.Row, ws.Dimension.End.Column - 1].Style.Border.Top.Style = ExcelBorderStyle.Thin;
                ws.Cells[3, 1, ws.Dimension.End.Row, ws.Dimension.End.Column - 1].Style.Border.Right.Style = ExcelBorderStyle.Thin;
                ws.Cells[3, 1, ws.Dimension.End.Row, ws.Dimension.End.Column - 1].Style.Border.Left.Style = ExcelBorderStyle.Thin;

                package.SaveAs(output);

                return output;
            }
        }
        catch (Exception ex)
        {
            return null;
        }
    }

What can I try next?

A: You can do it this way:
ws.Range[ws.Cells[1, 1], ws.Cells[4, 1]].Merge();

It will merge rows from 1 to 4 in column 1.

A:                 int tempRow = startRowForMerge;
                int firstSameRowIndex = 0;
                int lastSameRowIndex = 0;
                int maxCount = tempRow + list.Count() - 1; // -1 because array start from 0
                bool needToMerge = false;

                foreach(int tempColumn in mergeColumnList)
                {
                    tempRow = startRowForMerge;
                    for (int i = 0; i < list.Count(); i++)
                    {
                        if (tempRow < maxCount)
                        {
                            if (row > 4 && ws.Cells[tempRow, tempColumn].Value.ToString() == ws.Cells[tempRow - 1, tempColumn].Value.ToString())
                            {
                                needToMerge = true;
                                if (firstSameRowIndex == 0)
                                {
                                    firstSameRowIndex = tempRow - 1;
                                }
                                    lastSameRowIndex = tempRow;
                            }
                            else
                            {
                                if (needToMerge == true)  // to merge data in between the list
                                {
                                    ws.Cells[firstSameRowIndex, tempColumn, lastSameRowIndex, tempColumn].Merge = true;
                                    ws.Cells[firstSameRowIndex, tempColumn, lastSameRowIndex, tempColumn].Style.VerticalAlignment = ExcelVerticalAlignment.Center;
                                    needToMerge = false;
                                    firstSameRowIndex = 0;
                                    lastSameRowIndex = 0;
                                }
                            }
                        }
                        else
                        {
                            if (needToMerge == true)  // to merge data in last row
                            {
                                ws.Cells[firstSameRowIndex, tempColumn, lastSameRowIndex, tempColumn].Merge = true;
                                ws.Cells[firstSameRowIndex, tempColumn, lastSameRowIndex, tempColumn].Style.VerticalAlignment = ExcelVerticalAlignment.Center;
                                needToMerge = false;
                                firstSameRowIndex = 0;
                                lastSameRowIndex = 0;
                            }
                        }

                        tempRow++;
                    }
                }


text:
Q: Removing duplicates in a Spinner in java when data comes from mySQL I am Using hashsetList to create a new list for my spinner without duplicates but java gives errors when I add this within the Spinner. Ithe project works fine when duplicates are shown from mySQL.
Here is the extract of MainActivity.java before I created the hashsetList.
  @Override
    protected void onPostExecute(Void args) {
        // Locate spinner1 in activity_main.xml
        Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);

        // Spinner adapter

        spinner1.setAdapter(new ArrayAdapter<String>(MainActivity.this,
                android.R.layout.simple_spinner_dropdown_item,typesofjobs));

       Collections.sort(typesofjobs);

When I added the following hashsetList code to eliminate duplicates and run it, the project crashes.
  @Override
    protected void onPostExecute(Void args) {
        // Locate spinner1 in activity_main.xml
        Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);

        Set<String> hashsetList = new HashSet<String>(typesofjobs);
        // Spinner adapter

        spinner1.setAdapter(new ArrayAdapter<String>(MainActivity.this,
                android.R.layout.simple_spinner_dropdown_item, (List<String>) hashsetList));

        Collections.sort(typesofjobs);

Am I putting hashsetList in the wrong place or using it incorrectly? I am just trying to replace "typesofjobs" with the non duplicate version. Is there a better way I could eliminate my spinner duplicates?

A: You were on the right track when you used HashSet with your list to remove the duplicates.  However, you made a mistake when you tried to cast this Set to a List, which won't work.  Instead, in the code below I pass a LinkedHashSet created from your list of jobs into an ArrayList constructor.  The resulting List will have all duplicate String job values removed.
@Override
protected void onPostExecute(Void args) {
    // Locate spinner1 in activity_main.xml
    Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);

    List<String> typesofjobsunique = new ArrayList<>(new LinkedHashSet<>(typesofjobs));
    spinner1.setAdapter(new ArrayAdapter<String>(MainActivity.this,
            android.R.layout.simple_spinner_dropdown_item, typesofjobsunique));

    // not sure if you want to keep original list
    Collections.sort(typesofjobs);

Hat tip to this great SO post which discusses ways to remove duplicates from Java Lists.


text:
Q: Puppeteer on Heroku: Failed to launch the browser process I'm using Puppeteer on Heroku and I receive the following error:
Failed to launch the browser process! /usr/src/app/node_modules/puppeteer/.local-chromium/linux-756035/chrome-linux/chrome: error while loading shared libraries: libX11-xcb.so.1: cannot open shared object file: No such file or directory TROUBLESHOOTING: https://github.com/puppeteer/puppeteer/blob/master/docs/troubleshooting.md

A: May be this could help (copied from Puppeteer official website)
Running Puppeteer on Heroku (https://github.com/puppeteer/puppeteer/blob/main/docs/troubleshooting.md#running-puppeteer-on-heroku)
Running Puppeteer on Heroku requires some additional dependencies that aren't included on the Linux box that Heroku spins up for you. To add the dependencies on deploy, add the Puppeteer Heroku buildpack to the list of buildpacks for your app under Settings > Buildpacks.
The url for the buildpack is https://github.com/jontewks/puppeteer-heroku-buildpack
Ensure that you're using '--no-sandbox' mode when launching Puppeteer. This can be done by passing it as an argument to your .launch() call: puppeteer.launch({ args: ['--no-sandbox'] });.
When you click add buildpack, simply paste that url into the input, and click save. On the next deploy, your app will also install the dependencies that Puppeteer needs to run.
If you need to render Chinese, Japanese, or Korean characters you may need to use a buildpack with additional font files like https://github.com/CoffeeAndCode/puppeteer-heroku-buildpack
There's also another simple guide from @timleland that includes a sample project: https://timleland.com/headless-chrome-on-heroku/.

A: *

*Declare browser as:
const browser = await puppeteer.launch({
                  headless: true,
                  args: ['--no-sandbox','--disable-setuid-sandbox']
                })

*Install heroku buildpack puppeteer heroku buildpack

*Must clear heroku cache

*git add .

*git commit -m "some  text"

*git push heroku master

A: Adding this github repo to my heroku buildpack worked for me
https://github.com/jontewks/puppeteer-heroku-buildpack

A: You cant run Puppeteer on Heroku with headless: false because it doesn't have GUI to show.
You need to use headless: true that's because it's running on a Linux without GUI
If you have another errors, you may want to read the official Puppeteer troubleshooting guide: Running Puppeteer on Heroku.


text:
Q: How to store historical data i I have a Mysql database with a large product table (ca. 700k rows and 35 columns) where every record (except for the PK variable) can be updated biweekly. Currently I included it in my database with the latest update. I want to store historical data for each update (e.g. from 1st of April 2021, 15th of April 2021, 1st of May 2021 ...). Is there a clever way to store such historical data in a run time friendly way without saving the 700k records of each biweekly update in a separate table?
Thanks!


text:
Q: which way is better for passing arguments between activities in android
Possible Duplicate:
Passing data between activities in Android

Ok Lets say that in my Activity1.java there is a variable called date
If I declare it as static, in my Activity2 I can recall its value just by writing Activity1.date.
If it's not static I can when starting activity2 pass the value of date via Bundle.
Both ways are working.
My question is which is most preffered and has less disadvantages?

A: Certainly passed in the bundle is far less coupled.
With a static Activity2 cannot exist without Activity1. Activities are meant to be highly reusable, but via a static, you are highly coupling the activities.

A: Static is bad for many reasons, primarily because it is umm... static. It means that it will be always taking memory and also you will have only one instance of your field to share across all instances of your activity.
Because of this it can you bite your in so many places in so many subtle ways. For instance - if you write several unit tests for the same activity, the value will be shared, therefore your tests will not be independent. Or another use case: you have several instances of your activity on the stack - they all will share the value, which in many cases is not what you want.
The bottom line: do not do static. Static can save you a line or two of code but can introduce a lot of trouble. By the way it is not specific to android, it is true for any platform


text:
Q: Disable Notification for specific Account in Messages Is there a way to disable the Notifications for a specific Account in Mountain Lion's Messages App?

A: There isn't a way to accomplish this at the moment.


text:
Q: Pass parameter to Ressource's method callback I'm trying to change some model data if I sucessfully update something in my API :
this.saveProject = function(project) {
  var editedProjectSupport = {
        /* some data */
  };
  SupportTimeTracks.update({id: project.backendId}, editedProjectSupport,
    function() {
      // There :
      project.department = controllerScope.edit.project.department;
      project.timetrack = controllerScope.edit.project.timetrack;
      growl.success('Project support successfully edited');
    },
    function(result) {
      growl.error('Project support couldn\'t be edited.');
      console.log(result);
    });
  this.edit.project = {};
  $scope.$broadcast('edit.project');
};

But I can't access project in my success callback function(). Is there anyway to pass it in parameter or something else.
How can I update my project.department & project.timetrack ?
The function is called from the view, project is local in the function (although it references to an element present in the scope)

A: this.saveProject = function(project) {

  SupportTimeTracks.update({id: project.backendId}, editedProjectSupport,
    function() {
      // There : if you are not *shadowing* project variable, you MUST have access to project variable.
    }
  );
};

Your function is a closure, project is a variable defined in this.saveProject, so if you are not having another variable defined inside with the same name (shadowing your first variable) project have to be defined and with the value you have passed to this.saveProject and you have to have access to it.
Code example:

var closure = function(project){
  // I grab project var here
  setTimeout(function(){
    alert('there is no project shadowing: '+ project);
  }, 100);
};

closure('my project var');

var closureWithShadowing = function(project){
  // I grab project var here ... but
  setTimeout(function(){
    var project = 'I eat project variables'; // I have created a new var with the same name
             // so, I'm shadowing the original one.
    alert('project shadowing: '+ project);
  }, 500);
};

closureWithShadowing('my project var');


text:
Q: Migrating Postgres from 9.2 to 9.3 I have 2 CentOS servers, one is running PostgreSQL 9.2 and the other, 9.3.
I'm trying to migrate the database but I'm getting 'relation  does not exist' errors.
What I did was on the 9.2 server:
pg_dump -h localhost -W -U postgres --clean DBName > dbname.dump

copied the dbname.dump file to the 9.3 server and then:
pgsql -h localhost -W -U postgres -f dbname.dump

Am I doing something wrong?
Other misc info, I am using the postgis extension and have some foreign key restraints.

A: I would do something like:
pg_dump -h localhost -W -U postgres --clean -f dbname.dump DBName

The move the file to the new server, create the new database with
createdb DBName

then restore with:
psql -d DBName -f dbname.dump -v ON_ERROR_STOP=1

Remember that if you have tablespaces created on the old DB you will have to manually recreate them in the new DB before importing the dump.


text:
Q: Using PDO to insert data into database I'm trying to use PDO to insert data into my database but I'm getting the error "0 results". I already used PDO to select data from my database but this is the first time I use it to insert data so any help with the below code would be appreciated!
My form:

<form name="blog post" action="insert.php" method="post">

Id:
<input type="text" name="id">

Title:
<input type="text" name="title">

Year:
<input type="text" name="year">

Text:
<textarea rows="10" cols="50" name="text"></textarea>

<button type="submit">Submit</button>
</form>

My insert.php code:
<?php

$pdo = new PDO('mysql:host=localhost;dbname=dbexample', 'userexample', 'paswexample', array(\PDO::MYSQL_ATTR_INIT_COMMAND =>"SET NAMES utf8;SET time_zone = 'Europe/London'"));

$sql = "INSERT INTO `tableexample` (id, title, year, text)
                                        VALUES (:id, :title, :year, :text)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(":id", $id);
$stmt->bindParam(":title", $title);
$stmt->bindParam(":year", $year);
$stmt->bindParam(":text", $text);

$form = $_POST;
$id = $form[ 'id' ];
$title= $form[ 'title' ];
$year= $form[ 'year' ];
$text= $form[ 'text' ];

$stmt->execute();

$result = $stmt->execute(array(':id'=>$id, ':title'=>$title, ':year'=>$year, ':text'=>$text));

if($result) {
    echo "Your text has been posted";

    }// end if
else {
    echo '0 results';
    }// end else

?>

A: Replace this:
$stmt->execute();

$result = $stmt->execute(array(':id'=>$id, ':title'=>$title, ':year'=>$year, ':text'=>$text));

with this:
$result = $stmt->execute();

or...use only:
$result = $stmt->execute(array(':id'=>$id, ':title'=>$title, ':year'=>$year, ':text'=>$text));

and remove all of $stmt->bindParam

A:   try{
        $stmt = null;
        $stmt = $conn->prepare("INSERT INTO mst_finish (id, title, year, text) VALUES (:title, ':year', :text)");
        $data = array(
            ':title' => ucwords($_REQUEST['title']),
            ':year' => strtoupper($_REQUEST['year']),
            ':text' => $_REQUEST['text']);
        $stmt->execute($data);
        $_SESSION['_msg'] = "Finish succesfully saved..!";
     }
     catch (Exception $e)
     {
        $str= filter_var($e->getMessage(), FILTER_SANITIZE_STRING);
        $_SESSION['_msg_err'] = $str;
     }


text:
Q: WPF MDi With Background Element How can add Elements inside wpf MDIcontainer section(Like background).
I need this

A: I would suggest using a DataGrid for your MDI. Bind an ObservableCollection as its ItemSource. Then you can add a new Employee to that Collection. If INotifyPropertyChanged is implemented correctly it will AutoUpdate your Collection and the Content will be shown.
NOTE: Your Employee window has NOT to be shown via .ShowDialog() cause this will freeze the background Window.
This is no problem at all when hitting the save button is closing your employee window.


text:
Q: Why can't I use my newly created user with chown? So I am attempting to create a new user and group, and then change ownership of a directory to that new user/group. However, when I do, chown comes back with an "illegal user name" message.
Here's a simplified shell script that shows what I'm trying to do:
#!/usr/bin/bash

# Create Group
dscl . create /Groups/_jira
dscl . create /Groups/_jira gid 301"

# Create User
dscl . create /Users/_jira
dscl . append /Groups/_jira GroupMembership _jira

# Change Ownership
chown -R _jira:_jira /Some/random/directory

... and the output I get is:
chown: _jira: illegal user name

Am I missing a step? Is it because the username is prefixed with an underscore?
Note: I can list all the existing users and groups and can see the _jira user and _jira group, and also see that the user is assigned to that group.

A: You haven't assigned a user ID number (what dscl calls UniqueID) to the _jira user, and since file ownership is recorded by user ID, there's no way to chown files to an account without one. Add something like:
dscl . create /Users/_jira UniqueID 301

You should also set the user's PrimaryGroupID, and I'd use that to assign it to the _jira group rather than adding the user to the group:
dscl . create /Users/_jira PrimaryGroupID 301

If you want to stick with adding a secondary membership in the _jira group, you should assign some other group ID as the primary, and then add the secondary membership with dseditgroup:
sudo dseditgroup -o edit -a _jira -t user _jira

This not only adds "_jira" to the group's GroupMembership list, it also adds the user's UUID to the group's GroupMembers list -- doing both is recommended, and while it's possible to do with dscl it's simpler with dseditgroup.


text:
Q: Pass Variable to "Relation" parameter in Excel Solver VBA I am attempting to change the relation in VBA solver based on a formula found in cell (I28). Sometimes I want the constraint relationship to be "=" and sometimes ">=". The output from the formula in I28 is either (2) or (3) My idea is summarized below in line 7:
Dim relI As Range
Set relI = Value.Range("i28")
With relI
    SolverReset
    SolverAdd CellRef:="$m$3", Relation:=1, FormulaText:="$e$25"
    SolverAdd CellRef:="$g$21", Relation:=2, FormulaText:="$C$19"
    SolverAdd CellRef:="$I$21", Relation:=relI, FormulaText:="$I$22"
    SolverAdd CellRef:="$C$9:$C$17", Relation:=2, FormulaText:="$D$9:$D$17"
    SolverOk SetCell:="$h$21", MaxMinVal:=1, ValueOf:=0, ByChange:="$g$8:$g$17", _
        Engine:=1, EngineDesc:="GRG Nonlinear"
End With

How do I / Can I pass that variable to the solver in this way?

A: @BigBen helped solve this problem. This solution will call the variable from within a cell. For me, this is a better solution than declaring a variable in VBA.
SolverReset
SolverAdd CellRef:="$M$3", Relation:=1, FormulaText:="$E$25"
SolverAdd CellRef:="$G$21", Relation:=2, FormulaText:="$C$19"
SolverAdd CellRef:="$I$21", Relation:=Range("I28").Value, FormulaText:="$I$22"
SolverAdd CellRef:="$C$9:$C$17", Relation:=2, FormulaText:="$D$9:$D$17"
SolverOk SetCell:="$H$21", MaxMinVal:=1, ValueOf:=0, ByChange:="$G$8:$G$17", _
    Engine:=1, EngineDesc:="GRG Nonlinear"


text:
Q: TFS2010 - Teambuild detailed logfile With msbuild you can configure multiple loggers using different logging levels, e.g. errors are logged to console and all detailed information gets logged to a file.
Is there a similar option to configure the teambuild of TFS2010 to have "Normal" logs within my build summary "View Log" and to have a "Detailed" log within the output folder?

A: Try to add additional command line arguments for MSBuild. On the build definition's Process->Advanced settings page change "MSBuild arguments" value. Try to use
/fileLogger /flp:LogFile=c:\DiagnosticBuild.log;Verbosity=diagnostic

Change your build log file name and location after successful test. If you need to log per MsBuild node, try to use distributedFileLogger instead of fileLogger.

A: What you are looking for is not available for the 2010 release, but a similar feature has been added for the next release. You just need to wait a bit :-)