text:
Q: Select trazendo máximo de Colunas com algo Escrito - MYSQL Galera, tenho a seguinte estrutura numa tabela MySql:

https://prnt.sc/k0d0ev
Preciso fazer um select que me traga o máximo de postos que tenha algum registro, por exemplo, na referência 269 me traga até o posto 4, e na referência 258 me traga até posto 6.
Pode ser algo parecido com o MAX, mas que me traga o máximo de colunas que tenha algum registro daquela referência. Como posso fazer este select?

A: Faça um IF, se houver algo escrito adiciona 1 senão adiciona 0. Esse IF terá que ser feito para cada coluna, exemplo:
SELECT a.`REFERENCIA`, a.`DESCRICAO`, (
  IF(a.`POSTO1` <> '', 1, 0) +
  IF(a.`POSTO2` <> '', 1, 0) +
  IF(a.`POSTO3` <> '', 1, 0) +
  IF(a.`POSTO4` <> '', 1, 0) +
  IF(a.`POSTO5` <> '', 1, 0) +
  IF(a.`POSTO6` <> '', 1, 0) +
  IF(a.`POSTO7` <> '', 1, 0) +
  IF(a.`POSTO8` <> '', 1, 0) +
  IF(a.`POSTO9` <> '', 1, 0) +
  IF(a.`POSTO10` <> '', 1, 0)
) AS qtde
FROM nome_da_tabela a

Essa tabela não esta com uma estrutura adequada para um banco de dados relacional, Esses postos, deveriam estar em outra tabela com a referência dessa tabela.

A: Esta consulta funciona no MySQL 8.x.
Ela traz a referência, o status do posto (conteúdo das colunas posto1..posto10) e o maior número do posto.
Ela ignora qualquer vazio que tenha nessas colunas postoX e desconsidera descontinuidades nessas colunas (por exemplo, posto1 e posto3 vazios e posto2 e posto4 cheios - no caso, o maior posto será 4).
WITH q (referencia, statusposto, numposto) AS
(
    SELECT referencia, posto1, 1
    FROM tabela
    WHERE posto1 IS NOT NULL AND posto1 <> ''

    UNION

    SELECT referencia, posto2, 2
    FROM tabela
    WHERE posto2 IS NOT NULL AND posto2 <> ''

    UNION

    ...

    UNION

    SELECT referencia, posto10, 10
    FROM tabela
    WHERE posto10 IS NOT NULL AND posto2 <> ''
)
SELECT q.referencia, q.numposto maiorposto, q.statusposto
FROM q
JOIN (
    SELECT q.referencia, MAX(q.numposto) maiorposto
    FROM q
    GROUP BY q.referencia) r ON r.referencia = q.referencia
                            AND r.maiorposto = q.numposto

A: count() com group by
select referencia, count() as qtd
from tabela
group by referencia


text:
Q: Schedule a task from a short-lived thread I am new to C#, coming from C++ and would like to ask if this is a correct way of using Task Parallel Library.
I have a Web Service which queues long running operations. I don't want to use async web calls, so my idea is to use TPL, creating a task when the web operation is called. I am wondering if there is any kind of a resource leak if I schedule the task from a thread that dies right after the web operation finishes. Let's say that I would not keep a reference to the task as I don't need to check its status nor result. Thanks.
EDIT:
Sry, didn't express myself clearly on the first shot. My question is related to web service, not to a client. Client calls the web service operation that takes a long time. Web service call returns saying that operation was successfully queued/executed on background. In the web service operation, I would like to use TPL and not storing a task object returned by StartNew. Wondering, whether the task object is kept forever if I don't read its status and therefore leaking. Maybe it is just my C++ thinking that is getting in the way and I should not take care about the leak given it is managed code.

A: Forgetting about a Task doesn't cause the TPL any problems see stackoverflow.com/questions/3734280/… for more details. But, the work you want to do in that task is important--if you "forget about it" how will you know it's been done, done correctly, and doesn't need to be re-started? That's all application specific.
"completely busy" for the thread pool means that 1023 thread pool threads have been created and are executing (which would probably be really bad). Otherwise, the thread pool starts out with one thread per CPU/Core as a minimum and maintains that minimum by starting a new thread every second as long as there's isn't that number of non-running threads. So, it really doesn't "queue" anything. e.g. you could start 12 tasks and at point it "queued" 4, at another point it ran all 12...

redpajama_set_name: RedPajamaStackExchange


text:
Q: Defining a new logical operator in Ruby Very much an idle day-dream this but is it possible with some neat meta-programming trick to define a new logical operator in Ruby? I'd like to define a but operator.
For example, if I want to do something if x but not y is true I have to write something like:
if x and not y

But I would like to write
if x but not y

It should work exactly the same as and but would be down to the programmer to use sensibly to increase the legibility of code.

A: Without editing the Ruby parser and sources and compiling a new version of Ruby, you can't. If you want, you can use this ugly syntax:
class Object
  def but(other)
    self and other
  end
end

x.but (not y)

Note that you can't remove the parentheses or the space in this snippet. It will also shadow the functionality of the code to someone else reading your code. Don't do it.

A: If you really want to do this, try editing parse.y and recompiling Ruby. That's where Ruby's syntax is defined.

A: As others have already pointed out, you cannot define your own operators in Ruby. The set of operators is predefined and fixed. All you can do is influence the semantics of some of the existing operators (namely the ones that get translated into message sends) by responding to the appropriate messages.
But of course, you can implement a but method quite easily:
class Object
  def but
    self && yield
  end
end

Object.new.but { not true }


text:
Q: MVP : : Event Bus pattern instead of Listener This question more towards paradigm. Why is that we don't use Event Bus instead of listeners in an MVP environment ? Typically, the "P" part has dependency injection of view and model references. Sure this has an advantage of showing explicit contract between the view and model via presenter, which is more readable.
However, wouldn't it be a cleaner approach to have presenter listen to events from views and events carry the view payload (eg: json representation). Same is the case with presenter talking back to the view. View will listen for events from presenter. Major advantage is, we don't have to write interfaces for each contract between view and presenter. If you look at the code you will see that presenter is getting exposed to view details like Text Fields, which i believe is increasing coupling between view and presenter. Say, if i'm replacing front end JavaFx instead of Vaadin, i will have to alter presenter as well.
This class is an example from a live project. Here we have different types of events ie i don't create event  class for different cases. Eg: LoginViewEvent , DashBoardEvent etc which i believe is a maintenance pain.
public class UrayEvent {

    public static enum EventType {

        SESSION_SELECTED(1),
        DOCUMENT_SELECTED(2),
        DOCUMENT_EDIT_COMPLETE(3),
        DOCUMENT_EDIT_CANCELED(4),
        SHOW_SESSION_TABLES(5),
        SHOW_SESSION_DOCUMENTS(6),
        SHOW_SESSION_COLLABORATORS(7),
        USER_REQUESTED_REFRESH(8),
        AUTO_REFRESH(9),
        TABLE_SELECTED(10),
        DETACHED(11),
        SCHEDULER_NAVIGATION(12),
        JIRA_USER_SELECTED(13),
        DOCUMENT_SAVE_SUCCESS(14),
        DOCUMENT_SAVE_FAILURE(14);

        private final int value;

        private EventType(int value) {

            this.value = value;
        }

        public int getValue() {

            return value;
        }
    }

    public static class Event {

        private final EventType type;
        private final Object payload;

        public Event(EventType type, Object eventPayload) {

            this.type = type;
            this.payload = eventPayload;
        }

        public EventType getEventType() {

            return type;
        }

        public Object getEventPayload() {

            return payload;
        }
    }

}

Simple enough, the view send the event  DOCUMENT_EDIT_COMPLETE .The presenter layer handles this event. I found this way, a better way to decouple views from presenter.
    @Subscribe
    public void handle(UrayEvent.Event event) {

        switch (event.getEventType()) {
            case DOCUMENT_EDIT_COMPLETE:
                  // event payload contains document model data
                  // like document id etc
                 saveDocument(event.getEventPayload);
                break;
            default:
                break;
        }
    }

Advantage

*

*Less boiler plate code, for n-views we don't need n-interfaces

*New event means adding event element to enum and updating respective
subscribe methods handling this event.

Disadvantage

*

*Memory leak if we forget to unregister from eventbus (faced it plenty of time)

Questions
1) This approach means, there would larger set enum elements as the application grow. Is this approach an anti pattern ?
2) As we saw it uses Event Bus extensively are there any drawbacks of
using bus system instead of interface-listener pattern ?
Wanted your valuable suggestion on this regard. The main issue is, if i blindly apply this pattern extensively across the project i shouldn't regret doing so, what would be a possible pitfall in this approach.

A:
1) This approach means, there would larger set enum elements as the
  application grow. Is this approach an anti pattern ?

If there are many events you need many event identifiers. They can be simple ints or enums or Interfaces.
The mechanism you demonstrated is simple and works well with small applications. It has been proven many times over with multiple frameworks. Take for example Microsoft's Win32 API and MFC.
In some projects I have seen the event interceptors implemented with Annotations which provides an elegant way for handling the events. The previous time was in a project utilizing the Apache Wicket framework.

2) As we saw it uses Event Bus extensively are there any drawbacks of
  using bus system instead of interface-listener pattern ?

It is basically the same thing in a different package. In Java world it is de facto standard to use listener interfaces. Take for example Swing and Android.
The event bus approach is used in Facebook's Javascript based React framework. It is interesting to notice the similarity of Model-View-Presenter and Flux design patterns. Particularly the unidirectional data flow is highlighted in both architectures.
You mentioned the use case of replacing JavaFx with Vaadin as the UI framework. In my opinion, changing the UI framework so that you are able to reuse even some portions of it very rarely happens. I would not pay the price of added abstraction layers and complexity upfront just because the framework might change. Rather you should start with KISS and YAGNI principles. If you want to change the UI framework later, then you just implement the UI layer again from scratch.


text:
Q: Are intersections of simple subsets of $\mathbb{R}^2$ necessarily simple? Edit: Consider the notion of "simply connected," and drop the "connected". Then we obtain the following concept.
Call a subset $A$ of a topological space simple if for all $x,y \in A$ such that there exists a path between $x$ and $y$ lying completely in $A$, it holds that any two such paths are equivalent up to continuous deformation.
Is it always the case that the arbitrary intersection of simple subsets of $\mathbb{R}^2$ is itself simple? Note that this fails if $\mathbb{R}^2$ is replaced by the sphere.
If so, define that the simplification of any $A \subseteq \mathbb{R}^2$ is the intersection of all simple supersets of $A$. If $A$ is connected, is its simplification necessarily connected?

A: The result becomes easy by using a nice (not fully trivial) result:

A set $A\subseteq \mathbb R^2$ is simple if and only if its complement in $\overline{\mathbb R^2}:=\mathbb R^2\cup\{\infty\}$ is connected.

Now if $A_i$ is simple for each $i\in I$, then
$$ \overline{\mathbb R^2}\setminus \bigcap _{i\in I} A_i = \bigcup_{i\in I}\left(\overline{\mathbb R^2}\setminus A_i\right)$$
is the union of connected subsets that all have the point $\infty$ in common and hence is connected.

A: An arbitrary intersection of simple sets is simple: if $\gamma, \gamma'$ are two coterminal paths in the intersection, then they belong to each of the original sets, and so the interior of the set bounded by these paths belongs to each original set; this holds (and is well-defined to begin with) because we're dealing with $\mathbb{R}^2$. Therefore the interior belongs to the intersection, and hence the two paths can be continuously deformed to one another within the intersection.
The fact that the simplification of a connected $A$ is connected is trivial.  Suppose $S$ is its simplification. Let $S'$ be the connected component of $S$ which contains $A$; there must be a single one because $A$ is connected.  Then $S'$ is a union of path-components of $S$ (since path-connected implies connected), and thus $S'$ must be simple as well, so $S \subseteq S'$.  Well then $S = S'$, so the simplification of $A$ is connected.


text:
Q: Is it possbile to see how much heap an object is using? If I have a List<Object>, would it be possible to run some method on each Object to see how much memory each is consuming?  I know nothing about each Object it may be an entire video file loaded onto the heap or just a two-byte string.  I ultimately would like to know which objects to drop first before running out of memory.
I think Runtime.totalMemory() shows the memory currently used by the JVM, but I want to see the memory used by a single object.

A: SoftReference looks kinda like what you need. Create a list of soft references to your objects, and if those objects are not referenced anywhere and you run out of memory, JVM will delete some of them. I don't know how smart the algorithm for choosing what to delete is, but it could as well be removing those that will free most memory.

A: If you are in a container you can use Jconsole http://java.sun.com/developer/technicalArticles/J2SE/jconsole.html
The jdk since 1.5 comes with heap dump ulits... You in a container or in eclipse?  Also why do you have a List of Objects??

A: There is no clean way to do it. You can create a dummy OutputStream which will do nothing but counting number of bytes written. So, you can make some estimation about your object graph size by serializing it to such stream.
I would not advise to do it in production system. I, personally, did it once for experimenting and making estimations.

A: Actually another possible tactic is just to make a crap load of instance of the class you want to check (like a million in an array).
The sheer number of objects should negate the overhead (as in the overhead of other stuff will be much smaller than your crap load of objects).
You will want to run this in isolation of course (ie public static main()).
I will admit you will need lots of memory for this test.

A: Something you could do is make a Map<Object, Long> which maps each object to it's memory size.
Then to measure the size of a particular object, you have to do it at instantiation of each object - measure the JVM memory use before (calling Runtime.totalMemory()) and after building the object (calling Runtime.totalMemory()) and take the difference between the two - that is the size of the object in memory. Then add the Object and Long to your map. From there you should be able to loop through all of the keys in the map and find the object using the largest amount of space.
I am not sure there is a way to do it per object after you already have your List<Object>... I hope this is helpful!


text:
Q: How to speedup the unzip process in Powershell using 7zip.exe I am using 7zip exe to unzip the files in powershell script which was taking a lot of time to do simple work (almost 45 min to 1 hr 30 min for 32 files). Is there any other alternative?
Here is the code below:
Set-Alias sz "C:\Program Files\7-Zip\7z.exe"

sz x $zipfilename -o"$unzipfolder" -y
LogWrite "$zipfilename unzipped to $unzipfolder successfully"

A: I was having a similar issue where my file was around 6 GB and later i switched to 7 zip PowerShell module
and i see nearly 6X improvements.

A: You can use .NET API directly in powershell instead of using a third-party tool.
Add-Type -Assembly "System.IO.Compression.Filesystem"
[System.IO.Compression.ZipFile]::ExtractToDirectory("C:\installers\app.zip", "C:\installers\app")

Source: https://github.com/PowerShell/Microsoft.PowerShell.Archive/issues/32#issuecomment-668732081


text:
Q: Add filled rows after a condition in R I essentially want that for every unique id, there are three rows.
Each unique id has to have rows with kind=1, kind=2, kind=3.
Some already have all three but some only have a row with observations for e.g. only kind 1 and two.
I also want to fill the values A and B with "0" (not NA) for the newly added rows.
I am quite new to R, so I don't really know how to start at all.
id = c("u_1", "u_1", "b_1", "u_2", "u_2", "u_2")
kind = c("1", "2", "1", "1", "2", "3")
A = c(3, 4, 11, 3, 4, 6)
B = c(4, 1, 6, 2, 3, 8)

df <- data.frame(id, kind, A, B)

Every variation is possible. A person (id) can have kind 1 and 2 but not 3; they can have only 1, only 2, only 3; they can have only 2 and 3 but not one, etc...
So what I would want this code to look like in the end is the following:

id
kind
A
B

u_1
1
3
4

u_1
2
4
1

u_1
3
0
0

b_1
1
11
6

b_1
2
0
0

b_1
3
0
0

u_2
1
3
2

u_2
2
4
3

u_2
3
6
8

Thank you so much for taking the time to think about my problem!

A: Try with tidyr::complete:
library(tidyr)

id = c("u_1", "u_1", "b_1", "u_2", "u_2", "u_2")
kind = c("1", "2", "1", "1", "2", "3")
A = c(3, 4, 11, 3, 4, 6)
B = c(4, 1, 6, 2, 3, 8)

df <- data.frame(id, kind, A, B)

complete(df, id, kind, fill = list(A = 0, B =0))
#> # A tibble: 9 x 4
#>   id    kind      A     B
#>   <chr> <chr> <dbl> <dbl>
#> 1 b_1   1        11     6
#> 2 b_1   2         0     0
#> 3 b_1   3         0     0
#> 4 u_1   1         3     4
#> 5 u_1   2         4     1
#> 6 u_1   3         0     0
#> 7 u_2   1         3     2
#> 8 u_2   2         4     3
#> 9 u_2   3         6     8

Created on 2021-06-04 by the reprex package (v2.0.0)


text:
Q: Clean urls and database Is it an ok practice to have a URL column in my database that would store a URL such as: /this-is-a-keyword
And then use that column in my php query to get the information I need instead of using an integer column?
So basically when I went to Mysite.com/this-is-a-keyword I would return the result from that row.

A: More or less, what you are describing is called a slug and it's normally constructed by passing the most descriptive string (usually the title of the page / post) to a slugify function, like this one:
function Slug($string)
{
    return strtolower(trim(preg_replace('~[^0-9a-z]+~i', '-', html_entity_decode(preg_replace('~&([a-z]{1,2})(?:acute|cedil|circ|grave|lig|orn|ring|slash|th|tilde|uml);~i', '$1', htmlentities($string, ENT_QUOTES, 'UTF-8')), ENT_QUOTES, 'UTF-8')), '-'));
}

The problem with this, however, is that the result may not be unique, consider the following:
echo Slug('Alix Axel');          // alix-axel
echo Slug('Álix Ãxel');          // alix-axel
echo Slug('@Álix----_Ãxel!?!?'); // alix-axel

All return the same output even though the input differs. One of my favorite (and also most widespread) approaches is to do like StackOverflow does it (using the ID and slug in combination):

stackoverflow.com/questions/5845732/clean-urls-and-database

If you want to avoid this, you need to make sure the slug you are generating does not exist already in the database, if it does append an incremented number until it satisfies the unique condition.

A: Um, sure, this is usually called a slug. And you'd just store this-is-a-keyword in the database (no leading slash) to query against.


text:
Q: How to use max_by I want to find the longest number sequence in an array like this:
string = input.scan(/(\d+)/)
string.max_by(&:length)

However, in the output I get only the first value in the array.
The whole code is:
puts "Enter a string with letters and numbers"
input = gets
string = input.scan(/(\d+)/)
puts string.max_by(&:length)

I tried to use other methods, just to test how they would work and it turned out that none of them work, even those that I've copied from working examples. What can be wrong?

A: Your problem is with String#scan, not with max_by:
"12 3456 789".scan(/(\d+)/)
# [["12"], ["3456"], ["789"]]

It returns an array of arrays, because you used a matching group in the scan. For every match, it returns an array with all the groups. There's only 1 group in each match, so all those arrays have exactly 1 element.
max_by correctly returns the first array, because it has at least as many elements as all the others. You didn't notice the error because both Arrays and Strings respond to :length.
You want:
"12 3456 789".scan(/\d+/)
# ["12", "3456", "789"]

With max_by:
"12 3456 789".scan(/\d+/).max_by(&:length)
# "3456"


text:
Q: Перед переносом появился � знак Сайт на WP это виджет дополнение темы. Кодировки в норме что может быть?

Нет тут такого места с var_dump. Это код виджета. Поставил стандартный все нормально, а вот с темы все те-же ? знаки.

<?php
class listingpro_TWRecentPostWidget extends WP_Widget {
    function __construct() {
        $widget_ops = array('classname' => 'listingpro_TWRecentPostWidget', 'description' => 'listingpro recent posts.');
        parent::__construct(false, 'listingpro recent posts', $widget_ops);
    }
    function widget($args, $instance) {
        global $post;
        extract(array(
            'title' => '',
            'number_posts' => 2,
            'theme' => 'post_nothumbnailed',
            'post_order' => 'latest',
            'post_type' => 'post'
        ));
        extract($args);
        $title = apply_filters('widget_title', strip_tags($instance['title']));
        $post_count = 2;
        if (isset($instance['number_posts']))
            $post_count = strip_tags($instance['number_posts']);
        $q['posts_per_page'] = $post_count;
        $cats = (array) $instance['post_category'];
        $q['paged'] = 1;
        $q['post_type'] = strip_tags($instance['post_type']);
        if (count($cats) > 0) {
            $typ = 'category';
     if ($instance['post_type'] != 'post')
  $typ = 'catalog';
            $catq = '';
            $sp = '';
            foreach ($cats as $mycat) {
                $catq = $catq . $sp . $mycat;
                $sp = ',';
            }
            $catq = explode(',', $catq);
            $q['tax_query'] = Array(Array(
                    'taxonomy' => $typ,
                    'terms' => $catq,
                    'field' => 'id'
                )
            );
        }
        if ($instance['post_order'] == 'commented')
            $q['orderby'] = 'comment_count';
        query_posts($q);
        if (isset($before_widget))
            echo wp_kses_post($before_widget);
        if ($title != '')
            echo wp_kses_post($args['before_title'] . $title . $args['after_title']);
        echo '
';
        echo '
';
        while (have_posts ()) : the_post();
            echo '
';
                $class = "with-thumb";
                if (isset($instance['theme']) && $instance['theme'] == 'post_thumbnailed') {
                    if (has_post_thumbnail($post->ID)) {
                        $lrg_img = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'listingpro-author-thumb');
                        $feat_img = $lrg_img[0];
                        $thumb_width  = 105;
                        $thumb_height = 78;
                        echo '

';
                    } else {
                        $class = "no-thumb";
                    }
                } else {
                    $format = get_post_format() == "" ? "standard" : get_post_format();
                    echo '

';
                }
                echo '
';
                    echo '
'.substr(strip_tags(get_the_title()),0,20).'
';
                    echo '
'.substr(strip_tags(get_the_content()),0,45).'.
';
                    echo '
';
                            esc_html_e("", "listingpro");
                            echo ''.get_the_date( ' j F' ).'';
                            esc_html_e("", "listingpro");
                            echo'

               '.esc_html_e("By", "listingpro").' '.get_the_author().'
              ';
                    echo '
';
                echo '
';
            echo '
';
        endwhile;
        echo '
';
        echo '
';
        if (isset($after_widget))
            echo wp_kses_post($after_widget);
        wp_reset_query();
    }

    function update($new_instance, $old_instance) {
        $instance = $old_instance;
        /* Strip tags (if needed) and update the widget settings. */
        $instance['title'] = strip_tags($new_instance['title']);
        if ($new_instance['post_type'] == 'post') {
     $instance['post_category'] = $_REQUEST['post_category'];
 } else {
     $tax = get_object_taxonomies($new_instance['post_type']);
     $instance['post_category'] = $_REQUEST['tax_input'][$tax[0]];
 }
        $instance['number_posts'] = strip_tags($new_instance['number_posts']);
        $instance['post_type'] = strip_tags($new_instance['post_type']);
        $instance['post_order'] = strip_tags($new_instance['post_order']);
        $instance['theme'] = strip_tags($new_instance['theme']);
        return $instance;
    }

    function form($instance) {
        //Output admin widget options form
        extract(shortcode_atts(array(
                    'title' => '',
                    'theme' => 'post_nothumbnailed',
                    'number_posts' => 2,
                    'post_order' => 'latest',
                    'post_type' => 'post'
                        ), $instance));
        $defaultThemes = Array(
            Array("name" => 'Thumbnailed posts', 'user_func' => 'post_thumbnailed'),
            Array("name" => 'Default posts', 'user_func' => 'post_nonthumbnailed')
        );
        $themes = apply_filters('jw_recent_posts_widget_theme_list', $defaultThemes);
        $defaultPostTypes = Array(Array("name" => 'Post', 'post_type' => 'post')); ?>

            <label for="<?php echo esc_attr($this->get_field_id('title')); ?>"><?php esc_html_e("Title:", "listingpro");?>
            <input class="widefat" id="<?php echo esc_attr($this->get_field_id('title')); ?>" name="<?php echo esc_attr($this->get_field_name('title')); ?>" value="<?php echo esc_attr($title); ?>"  />

            <label for="<?php echo esc_attr($this->get_field_id('post_order')); ?>"><?php esc_html_e("Post order:", "listingpro");?>
            <select class="widefat" id="<?php echo esc_attr($this->get_field_id('post_order')); ?>" name="<?php echo esc_attr($this->get_field_name('post_order')); ?>">
                <option value="latest" <?php if ($post_order == 'latest') print 'selected="selected"'; ?>><?php esc_html_e("Latest posts", "listingpro");?></option>
                <option value="commented" <?php if ($post_order == 'commented') print 'selected="selected"'; ?>><?php esc_html_e("Most commented posts", "listingpro");?></option>
            </select>

            <label for="<?php echo esc_attr($this->get_field_id('theme')); ?>"><?php esc_html_e("Post theme:", "listingpro");?>
            <select class="widefat" id="<?php echo esc_attr($this->get_field_id('theme')); ?>" name="<?php echo esc_attr($this->get_field_name('theme')); ?>">
                <option value="post_thumbnailed" <?php if ($theme == 'post_thumbnailed') print 'selected="selected"'; ?>><?php esc_html_e("Thumbnail", "listingpro");?></option>
                <option value="post_nothumbnailed" <?php if ($theme == 'post_nothumbnailed') print 'selected="selected"'; ?>><?php esc_html_e("No Thumbnail", "listingpro");?></option>
            </select>

<?php
        $customTypes = apply_filters('jw_recent_posts_widget_type_list', $defaultPostTypes);
        if (count($customTypes) > 0) { ?>

                <label for="<?php echo esc_attr($this->get_field_id('post_type')); ?>"><?php esc_html_e("Post from:", "listingpro");?>
                <select rel="<?php echo esc_attr($this->get_field_id('post_cats')); ?>" onChange="jw_get_post_terms(this);" class="widefat" id="<?php echo esc_attr($this->get_field_id('post_type')); ?>" name="<?php echo esc_attr($this->get_field_name('post_type')); ?>"><?php
                    foreach ($customTypes as $postType) { ?>
                        <option value="<?php print $postType['post_type'] ?>" <?php echo selected($post_type, $postType['post_type']); ?>><?php print $postType['name'] ?></option><?php
                    } ?>
                </select>

<?php
        } ?>

<?php esc_html_e("If you were not selected for cats, it will show all categories.", "listingpro");?>

        <div id="<?php echo esc_attr($this->get_field_id('post_cats')); ?>" class="recent-post-plugins-style"><?php
            $post_type='post';
            $tax = get_object_taxonomies($post_type);

            $selctedcat = false;
            if (isset($instance['post_category']) && $instance['post_category'] != ''){
                $selctedcat = $instance['post_category'];
            }
            wp_terms_checklist(0, array('taxonomy' => $tax[0], 'checked_ontop' => false, 'selected_cats' => $selctedcat)); ?>

            <label for="<?php echo esc_attr($this->get_field_id('number_posts')); ?>"><?php esc_html_e("Number of posts to show:", "listingpro");?>
            <input  id="<?php echo esc_attr($this->get_field_id('number_posts')); ?>" name="<?php echo esc_attr($this->get_field_name('number_posts')); ?>" value="<?php echo esc_attr($number_posts); ?>" size="3"  />

<?php
    }
}
add_action('widgets_init', create_function('', 'return register_widget("listingpro_TWRecentPostWidget");'));
add_action('wp_ajax_themewave_recent_post_terms', 'get_post_type_terms');
function get_post_type_terms() {
    $cat = 'post';
    if (isset($_REQUEST['post_format']) && $_REQUEST['post_format'] != '')
        $cat = $_REQUEST['post_format'];
    $tax = get_object_taxonomies($cat);
    wp_terms_checklist(0, array('taxonomy' => $tax[0], 'checked_ontop' => false, 'selected_cats' => false));
    die;
} ?>

A: Тексты у вас в уникоде, а место, где обрезаются названия, не учитывает уникод. Русские символы в уникоде состоят из нескольких байт. Если не учитывать уникод и обрезать строку по байтам, то можно отрезать строку посередине символа. Такие дефектные символы обозначаются символом-заполнителем в виде ромба с вопросом.
Воспроизвести проблему очень просто:
var_dump(substr('Проверка', 0, 7));

Такой код выведет:
string(7) "Про�"

Такой проблемы нет у функции mb_substr, которая работаем с символами (или рунами, как их называл в Go один из создателей UTF-8):
var_dump(mb_substr('Проверка', 0, 7));
// выведет string(14) "Проверк"

Поищите по коду где укорачиваются названия постов. Там замените функцию substr на mb_substr. В приведённом примере кода эта функция встречается ровно два раза.
echo '
';
    echo '
'.substr(strip_tags(get_the_title()),0,20).'
';
    echo '
'.substr(strip_tags(get_the_content()),0,45).'.
';
//             ^^^^^^                             ^^^^^^

Если вы по какой-то причине не можете воспользоваться функцией поиска и замены вашего редактора, задайте другой вопрос на эту тему.


text:
Q: Poi4Xpages - write file to document during postGeneration as per a suggestion recently received from Stwissel, I am using the following code to convert a file to mime and attach to a notes document during the post generation process of POI4Xpages.
EDITED NEW CODE:
The following code attaches to document, but throws an error: 502 Bad Gateway - The server returned an invalid or incomplete response.
public void saveExcel(Workbook a, Document newDoc) throws NotesException, IOException{

    newDoc.replaceItemValue("Form", "Provider");

    // Create the stream
    Session session = DominoUtils.getCurrentSession();
    Stream stream = session.createStream();
    // Write the workbook to a ByteArrayOutputStream
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    a.write(bos);
    // Convert the output stream to an input stream
    InputStream is = new ByteArrayInputStream(bos.toByteArray());
    stream.setContents(is);

MIMEEntity m = newDoc.createMIMEEntity("body");
MIMEHeader header = m.createHeader("content-disposition");
header.setHeaderVal("Mime attachment");
m.setContentFromBytes(stream, "application/vnd.ms-excel", MIMEEntity.ENC_IDENTITY_BINARY);
m.decodeContent();
newDoc.save(true, true);
}

ORIGINAL CODE:
var stream:NotesStream = session.createStream();

// Do not automatically convert MIME to rich text
session.setConvertMIME(false);
var doc:NotesDocument = database.createDocument();
doc.replaceItemValue("Form", "Provider");
var body:NotesMIMEEntity = doc.createMIMEEntity();
var header:NotesMIMEHeader = body.createHeader("Subject");
header.setHeaderVal("MIME attachment");
if (stream.open("c:\\notes\\data\\abc.xlsx", "binary")) {
    if (stream.getBytes() != 0) {
        body.setContentFromBytes(stream, "application/vnd.ms-excel",
        NotesMIMEEntity.ENC_IDENTITY_BINARY);
    } else requestScope.status = "File was not found.";
} else requestScope.status = "Could not open file.";
stream.close();
doc.save(true, true);
// Restore conversion
session.setConvertMIME(true);

However, this code is only attaching a file which is already stored on the server's local directory. How can I get this code to take the POI fileOutputStream and attach that?

A: It's a mix of what what Knut and I've commented about. The important part is that you'll use the write() method to pass the workbook data to an output stream.
// Create the stream
Stream stream = session.createStream();
// Write the workbook (you haven't clarified) to a ByteArrayOutputStream
ByteArrayOutputStream bos = new ByteArrayOutputStream();
workbook.write(bos);
// Convert the output stream to an input stream
InputStream is = new ByteArrayInputStream(bos.toByteArray());
stream.setContents(is);


text:
Q: TensorFlow on Windows CPU version: ImportError: No module named '_pywrap_tensorflow_internal' i have followed all the instructions in this similar question, i am using the latest version of tensor flow CPU version for windows gotten from
here but i am still getting the module not found error, i ran the script in the previous answer and installed the latest version of Microsoft C++ Runtime
i have attached the error message any help would be appreciated
stack trace
    >>> import tensorflow as tf
Traceback (most recent call last):
  File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\pywrap_ten
sorflow_internal.py", line 18, in swig_import_helper
    return importlib.import_module(mname)
  File "C:\Program Files\Python36\lib\importlib\__init__.py", line 126, in impor
t_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 978, in _gcd_import
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load
  File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 648, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 560, in module_from_spec
  File "<frozen importlib._bootstrap_external>", line 922, in create_module
  File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
ImportError: DLL load failed with error code -1073741795

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\pywrap_ten
sorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\pywrap_ten
sorflow_internal.py", line 21, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\pywrap_ten
sorflow_internal.py", line 20, in swig_import_helper
    return importlib.import_module('_pywrap_tensorflow_internal')
  File "C:\Program Files\Python36\lib\importlib\__init__.py", line 126, in impor
t_module
    return _bootstrap._gcd_import(name[level:], package, level)
ModuleNotFoundError: No module named '_pywrap_tensorflow_internal'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Program Files\Python36\lib\site-packages\tensorflow\__init__.py", lin
e 24, in <module>
    from tensorflow.python import *
  File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\__init__.p
y", line 49, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\pywrap_ten
sorflow.py", line 74, in <module>
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\pywrap_ten
sorflow_internal.py", line 18, in swig_import_helper
    return importlib.import_module(mname)
  File "C:\Program Files\Python36\lib\importlib\__init__.py", line 126, in impor
t_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 978, in _gcd_import
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load
  File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 648, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 560, in module_from_spec
  File "<frozen importlib._bootstrap_external>", line 922, in create_module
  File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
ImportError: DLL load failed with error code -1073741795

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\pywrap_ten
sorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\pywrap_ten
sorflow_internal.py", line 21, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\pywrap_ten
sorflow_internal.py", line 20, in swig_import_helper
    return importlib.import_module('_pywrap_tensorflow_internal')
  File "C:\Program Files\Python36\lib\importlib\__init__.py", line 126, in impor
t_module
    return _bootstrap._gcd_import(name[level:], package, level)
ModuleNotFoundError: No module named '_pywrap_tensorflow_internal'

Failed to load the native TensorFlow runtime.

See https://www.tensorflow.org/install/install_sources#common_installation_probl
ems

for some common reasons and solutions.  Include the entire stack trace
above this error message when asking for help.

A: I found an easy solution. Althoug the setup worked on another computer, here I needed to install an older version of tensorflow.

*

*just run below command it will clear all dependencies and then update it. This worked for me

pip install tensorflow==1.5


text:
Q: Stop ability to post to Asp.Net WebForm Page externally In our system we use ASP.Net WebForms pages.
We have a self registration web page in our system where a user can come along and register to start using our system.
We have recently discovered that one of our clients are posting form data to that page from their website which in turn submits the form on the page.
We want to stop this from happening. We don't mind if they embed the page into an IFrame because it won't work correctly anyway. But we need to stop them from posting form data to that page from their system / website.
Is there an attribute that we can set or something which stop external posting to that page? Or perhaps an other alternative, Ajax seems to jump to mind?
Not quote sure what to search for, did a quick search online but couldn't find anything.
Reason for wanting to Prevent this:
When something goes wrong on that page, the user trying to register does not get any error messages back from our system so we are getting a ton of support about this. Surely we can add functionality to support but we would rather not. Also want to prevent bot attacks on that page because each submit will create a user if they do not exist.

A: Starting with Visual Studio 2012, Microsoft added built-in CSRF protection to new web forms application projects. To utilize this code, add a new ASP .NET Web Forms Application to your solution and view the Site.Master code behind page. This solution will apply CSRF protection to all content pages that inherit from the Site.Master page.
The following requirements must be met for this solution to work:
All web forms making data modifications must use the Site.Master page. All requests making data modifications must use the ViewState. The web site must be free from all Cross-Site Scripting (XSS) vulnerabilities. See how to fix Cross-Site Scripting (XSS) using Microsoft .Net Web Protection Library for details. and also see it
   public partial class SiteMaster : MasterPage
   {
   private const string AntiXsrfTokenKey = "__AntiXsrfToken";
   private const string AntiXsrfUserNameKey = "__AntiXsrfUserName";
   private string _antiXsrfTokenValue;

 protected void Page_Init(object sender, EventArgs e)
 {
//First, check for the existence of the Anti-XSS cookie
var requestCookie = Request.Cookies[AntiXsrfTokenKey];
Guid requestCookieGuidValue;

//If the CSRF cookie is found, parse the token from the cookie.
//Then, set the global page variable and view state user
//key. The global variable will be used to validate that it matches in the view state form field in the Page.PreLoad
//method.
if (requestCookie != null
&& Guid.TryParse(requestCookie.Value, out requestCookieGuidValue))
{
    //Set the global token variable so the cookie value can be
    //validated against the value in the view state form field in
    //the Page.PreLoad method.
    _antiXsrfTokenValue = requestCookie.Value;

    //Set the view state user key, which will be validated by the
    //framework during each request
    Page.ViewStateUserKey = _antiXsrfTokenValue;
}
//If the CSRF cookie is not found, then this is a new session.
else
{
    //Generate a new Anti-XSRF token
    _antiXsrfTokenValue = Guid.NewGuid().ToString("N");

    //Set the view state user key, which will be validated by the
    //framework during each request
    Page.ViewStateUserKey = _antiXsrfTokenValue;

    //Create the non-persistent CSRF cookie
    var responseCookie = new HttpCookie(AntiXsrfTokenKey)
    {
        //Set the HttpOnly property to prevent the cookie from
        //being accessed by client side script
        HttpOnly = true,

        //Add the Anti-XSRF token to the cookie value
        Value = _antiXsrfTokenValue
    };

    //If we are using SSL, the cookie should be set to secure to
    //prevent it from being sent over HTTP connections
    if (FormsAuthentication.RequireSSL &&
    Request.IsSecureConnection)
    responseCookie.Secure = true;

    //Add the CSRF cookie to the response
    Response.Cookies.Set(responseCookie);
}

    Page.PreLoad += master_Page_PreLoad;
}

protected void master_Page_PreLoad(object sender, EventArgs e)
{
    //During the initial page load, add the Anti-XSRF token and user
    //name to the ViewState
    if (!IsPostBack)
    {
        //Set Anti-XSRF token
        ViewState[AntiXsrfTokenKey] = Page.ViewStateUserKey;

        //If a user name is assigned, set the user name
        ViewState[AntiXsrfUserNameKey] =
        Context.User.Identity.Name ?? String.Empty;
    }
    //During all subsequent post backs to the page, the token value from
    //the cookie should be validated against the token in the view state
    //form field. Additionally user name should be compared to the
    //authenticated users name
    else
    {
        //Validate the Anti-XSRF token
        if ((string)ViewState[AntiXsrfTokenKey] != _antiXsrfTokenValue
        || (string)ViewState[AntiXsrfUserNameKey] !=
        (Context.User.Identity.Name ?? String.Empty))
    {
    throw new InvalidOperationException("Validation of
    Anti-XSRF token failed.");
    }
}
}
}

A: It's not that hard to roll something basic, you can generate a Guid into a hidden field, then check you get the same one back, it's not as secure as a CAPTCHA, but would prevent random things posting to you without filling the form in, but wouldn't prevent scripts that do actually fill the form in and post from the page.
<asp:Hidden ID="Validation" runat="server" />

Page Load:
var guid = Guid.NewGuid();
Validation.Text = guid.ToString();
Session["Token"] = guid;

Then on postback check you get the same one back...

Alternatively, take a look at the Captcha NuGet package. It works on both webforms and MVC.
Show a Captcha:
<%@ Register Assembly="BotDetect" Namespace="BotDetect.Web.UI"
  TagPrefix="BotDetect" %>

  […]

<BotDetect:Captcha ID="SampleCaptcha" runat="server" />
<asp:TextBox ID="CaptchaCodeTextBox" runat="server" />

Validate post:
if (IsPostBack)
{
    // validate the Captcha to check we're not dealing with a bot
    bool isHuman = SampleCaptcha.Validate(CaptchaCodeTextBox.Text);

    CaptchaCodeTextBox.Text = null; // clear previous user input

    if (!isHuman)
    {
      // TODO: Captcha validation failed, show error message
    }
    else
    {
      // TODO: Captcha validation passed, proceed with protected action
    }
}

Examples from the documentation.


text:
Q: R (Loop) Error in data frame, replacement has x rows, data has y rows So I'm working on a project that requires me to create multiple plots using air quality data given for 30+ seperate days/files.
I've learned and copied from a person who has already done it but somehow I'm having problems integrating it with the data I have, any help is appreciated.
Here is the code:
#---START OF THE FOR LOOP---
all_dates = seq(begin_date, end_date, 1)
for (j in 1:length(all_dates)) {
  selected_date = all_dates[j]

  #read data from the file with (id, lat, lon, elev, value... enter your attributes here) columns
  datapointfile = paste(variable,"_",aggregate,"_",format.Date(selected_date,"%Y-%m-%d"),".txt",sep="")

  datapoints_wgs84 = read.table(datapointfile, header=TRUE)
  coordinates(datapoints_wgs84) = ~lon + lat
  proj4string(datapoints_wgs84) <- CRS("+init=epsg:4326")
  datapoints <- spTransform(datapoints_wgs84, CRS(projection))

  #INTERPOLATION STARTS HERE!

  #calculate linear regression intercept and slope(observ=B+A*elev)
  observlm <- lm(value ~ elev, datapoints)
  datapoints$res = observlm$residuals

  #calculate observ value raster using linear model (elevation / observ value)
  intercept = observlm$coefficients[1]
  slope = observlm$coefficients[2]
  regression_grid <- intercept + srtm * slope

  #interpolate the residuals using idw
  idw_test = idw(res~1, datapoints, defaultgrid)
  residual_grid = raster(idw_test, "var1.pred")

  #add regression grid and residuals
  finalgrid <- regression_grid + residual_grid

  #INTERPOLATION ENDS HERE!

  #START OF THE PLOT!
  layout = list(vrstvastudyarea)
  outfile = paste("Output", selected_date, ".png", sep="")
  png(filename = outfile, width = 1500, height = 1000, pointsize = 25, bg = "white", res = 150)
  nadpis = paste("Air Quality", selected_date)
  print(spplot(finalgrid, at=intervaly, col.regions = grid_colors,
               sp.layout=layout,
               main=list(nadpis, cex=2, col="black", font=2),
               colorkey=list(at=intervaly2, labels = list( at=intervaly2, cex = 1.5, labels = intervaly, lab = intervaly2), space="bottom")))
  dev.off()
  #END OF THE PLOT!

#---OUTPUT---

[inverse distance weighted interpolation]
Error in `[[<-.data.frame`(`*tmp*`, name, value = c(8.66783923397599,  :
  replacement has 14 rows, data has 18

So basically instead of getting 30+ outputs I get 1 output (for some reason!?) and then I get the error which is given above as the output :/. If I got no output I would understand but given first data file and the second data file has almost no difference in format I should not have any error in formatting...
Couple more information I think that might help solving the issue are:

*

*My data files look like this:

"id"    "elev"  "lon"   "lat"   "value"
Afyon   1027    30.54277778 38.75166667 108.2903226
Aydin   54  27.83666667 37.84027778 122.7096774
.
.
.

*And the person I copied the data from has a data as the following:

"id"    "lat"   "lon"   "elev"  "value"
2   50.69205    15.72876    816 37
3   49.735  16.0336 737 19
.
.
.
Thank you for your time.

A: So apparently it was caused by my data having some "NA" entries in it. Fixed it by giving them appropriate values. Although I'm still clueless how the code would've worked if I would like it to work with those NA values included.


text:
Q: pandas merging two multi-level series I have two multi-level Series and would like to merge them according to both index. The first Series looks like this:
                                              # of restaurants
BORO           CUISINE
BRONX          American                                425
               Chinese                                 330
               Pizza                                   206
BROOKLYN       American                               1254
               Chinese                                 750
               Cafe/Coffee/Tea                         350

The second one has more rows and is like this:
                                                # of votes
BORO           CUISINE
BRONX          American                                2425
               Caribbean                               320
               Chinese                                 3130
               Pizza                                   3336
BROOKLYN       American                               21254
               Caribbean                               2320
               Chinese                                 7250
               Cafe/Coffee/Tea                         3350
               Pizza                                   13336

A: Setup:
s1 = pd.Series({('BRONX', 'American'): 425, ('BROOKLYN', 'Chinese'): 750, ('BROOKLYN', 'Cafe/Coffee/Tea'): 350, ('BRONX', 'Pizza'): 206, ('BROOKLYN', 'American'): 1254, ('BRONX', 'Chinese'): 330})
s2 = pd.Series({('BRONX', 'Caribbean'): 320, ('BRONX', 'American'): 2425, ('BROOKLYN', 'Chinese'): 7250, ('BROOKLYN', 'Cafe/Coffee/Tea'): 3350, ('BRONX', 'Pizza'): 3336, ('BROOKLYN', 'American'): 21254, ('BROOKLYN', 'Pizza'): 13336, ('BRONX', 'Chinese'): 3130, ('BROOKLYN', 'Caribbean'): 2320})
s1 = s1.rename_axis(['BORO','CUISINE']).rename('restaurants')
s2 = s2.rename_axis(['BORO','CUISINE']).rename('votes')

print (s1)
BORO      CUISINE
BRONX     American            425
          Chinese             330
          Pizza               206
BROOKLYN  American           1254
          Chinese             750
          Cafe/Coffee/Tea     350
Name: restaurants, dtype: int64

print (s2)
BORO      CUISINE
BRONX     American            2425
          Caribbean            320
          Chinese             3130
          Pizza               3336
BROOKLYN  American           21254
          Caribbean           2320
          Chinese             7250
          Cafe/Coffee/Tea     3350
          Pizza              13336
Name: votes, dtype: int64

Use concat with parameter join if need inner join:
print (pd.concat([s1,s2], axis=1, join='inner'))
                          restaurants  votes
BORO     CUISINE
BRONX    American                 425   2425
         Chinese                  330   3130
         Pizza                    206   3336
BROOKLYN American                1254  21254
         Cafe/Coffee/Tea          350   3350
         Chinese                  750   7250

#join='outer' is by default, so can be omited
print (pd.concat([s1,s2], axis=1))
                          restaurants  votes
BORO     CUISINE
BRONX    American               425.0   2425
         Caribbean                NaN    320
         Chinese                330.0   3130
         Pizza                  206.0   3336
BROOKLYN American              1254.0  21254
         Cafe/Coffee/Tea        350.0   3350
         Caribbean                NaN   2320
         Chinese                750.0   7250
         Pizza                    NaN  13336

Another solution is use merge with reset_index:
#by default how='inner', so can be omited
print (pd.merge(s1.reset_index(), s2.reset_index(), on=['BORO','CUISINE']))
       BORO          CUISINE  restaurants  votes
0     BRONX         American          425   2425
1     BRONX          Chinese          330   3130
2     BRONX            Pizza          206   3336
3  BROOKLYN         American         1254  21254
4  BROOKLYN          Chinese          750   7250
5  BROOKLYN  Cafe/Coffee/Tea          350   3350

#outer join
print (pd.merge(s1.reset_index(), s2.reset_index(), on=['BORO','CUISINE'], how='outer'))
       BORO          CUISINE  restaurants  votes
0     BRONX         American        425.0   2425
1     BRONX          Chinese        330.0   3130
2     BRONX            Pizza        206.0   3336
3  BROOKLYN         American       1254.0  21254
4  BROOKLYN          Chinese        750.0   7250
5  BROOKLYN  Cafe/Coffee/Tea        350.0   3350
6     BRONX        Caribbean          NaN    320
7  BROOKLYN        Caribbean          NaN   2320
8  BROOKLYN            Pizza          NaN  13336


text:
Q: How to put my stop loss on the previous swing low before entrance? I want to put my stop loss on the low of last swing low before entrance in long position. I want this stop keep fix before next long entrance position. but it does not work. Can you please tell me how to solve this problem? Here is my code. please check this picture  to understand clearly

//@version=5
 strategy(title="Stop order exits", overlay=true)

// Calculate and plot the Exponential Moving Averages (EMAs)
fastEMA = ta.ema(close, 10)
slowEMA = ta.ema(close, 30)

plot(fastEMA, color=color.orange, title="Fast EMA")
plot(slowEMA, color=color.teal, linewidth=2, title="Slow EMA")

// Go long when the fast average crosses above the slow one
if ta.crossover(fastEMA, slowEMA)
    strategy.entry("Enter Long", strategy.long)
    strategy.exit("Exit Long", from_entry="Enter Long", stop=ta.lowest(low,5))


text:
Q: MongoDB complex select count group by function I have a collection called 'my_emails' where are stored email addresses :
[
    { email:"russel@gmail.com"},
    { email:"mickey@yahoo.com"},
    { email:"john@yahoo.com"},
]

and I try to get the top 10 hostnames used...
[
{host: "gmail.com", count: 1000},
{host: "yahoo.com", count: 989}, ...
]

if I had MySQL, I'll do this query :
SELECT substr(email,locate('@',email)+1,255) AS host,count(1) AS count
FROM my_emails
WHERE email like '%@%'
GROUP BY substr(email,locate('@',email)+1,255)
ORDER BY count(1) DESC
LIMIT 10

how can I do with mongodb ?
I try without result something like this :
db.my_emails.aggregate([ { $group : {_id : "$host", count : { $sum : 1 }}}]);

I don't know how to make the $host value without adding a new property to my records

A: MongoDB doesn't provide any operator like locate but you can use .mapReduce to do this:
db.collection.mapReduce(
    function() {
        emit(this.email.substr(this.email.indexOf('@') + 1), 1);
    },
    function(host, count) {
        return Array.sum(count) ; },
    { out: "hosts" }
)

Then db.hosts.find().sort({ 'value': -1 }).limit(10) returns top 10 hostname:
{ "_id" : "yahoo.com", "value" : 2 }
{ "_id" : "gmail.com", "value" : 1 }

A: An alternative workaround would be to modify your data structure by introducing another field in your schema which holds only the domain value of the email address. This can be done with a bulk update using the Bulk API operations that give a better write response i.e. useful information about what actually happened during the update:
var bulk = db.my_emails.initializeUnorderedBulkOp(),
    count = 0;

db.my_emails.find().forEach(function(doc) {
    var domain = doc.email.replace(/.*@/, ""),
        update = { domain: domain };
    bulk.find({ "_id": doc._id }).updateOne({
        "$set": update
    })
    count++;
    if (count % 1000 == 0) {
        bulk.execute();
        bulk = db.my_emails.initializeUnorderedBulkOp();
    }
})

if (count % 1000 != 0) { bulk.execute(); }

Bulk update response from sample:
BulkWriteResult({
    "writeErrors" : [ ],
    "writeConcernErrors" : [ ],
    "nInserted" : 0,
    "nUpserted" : 0,
    "nMatched" : 3,
    "nModified" : 3,
    "nRemoved" : 0,
    "upserted" : [ ]
})

After this update, a query on the collection db.my_emails.find().pretty() will yield:
{
    "_id" : ObjectId("561618af645a64b1a70af2c5"),
    "email" : "russel@gmail.com",
    "domain" : "gmail.com"
}
{
    "_id" : ObjectId("561618af645a64b1a70af2c6"),
    "email" : "mickey@yahoo.com",
    "domain" : "yahoo.com"
}
{
    "_id" : ObjectId("561618af645a64b1a70af2c7"),
    "email" : "john@yahoo.com",
    "domain" : "yahoo.com"
}

Now, having the domain field will make it easier for the aggregation framework to give you the host count through the $sum operator in the $group pipeline. The following pipeline operation will return the desired outcome:
db.my_emails.aggregate([
    {
        "$group": {
            "_id": "$domain",
            "count": { "$sum": 1 }
        }
    }
])

Output:
{ "_id" : "yahoo.com", "count" : 2 }
{ "_id" : "gmail.com", "count" : 1 }


text:
Q: Everytime I draw list item in SFML it crashes? So I am having a small issue with creating a list and having it write to my window using the SFML library. Basically what happens is that when I execute the fire() function the game freezes & crashes.
Variable code:
 sf::Sprite laser;

The list code is:
 std::list<sf::Sprite>laserList;

The fire code is (called when I click button):
 bool fire(void)
 {
   laserList.push_back(laser);
   return true;
 }

This is the drawing code to window:
//This is code for running through and drawing each sprite in list
for(std::list<sf::Sprite>::iterator it = laserList.begin(); it != laserList.end(); laserList;)
{
    app.draw(*it);
}

A: Your for loop is a bit strange here:
for(std::list<sf::Sprite>::iterator it = laserList.begin(); it != laserList.end(); laserList;)

You'll find that this will form an infinite loop as the value of it never changes. This may be what leads to your crash. To fix it you want to increment the iterator after every loop:
for(std::list<sf::Sprite>::iterator it = laserList.begin(); it != laserList.end(); ++laserList)

There was an edit that suggested the following but was rejected for some reason. I have added it here for completeness
You could avoid any confusion over this syntax by using the Range Based for loop introduced in C++11:
for(sf::Sprite spr : laserList){
    app.draw(spr);
}


text:
Q: Assembly, registers and return values -m32 / linux I'm trying to make some simple codes in assembly so I easily can understand more. To start with I want to make a function that takes a parameter.
I want to add a value to the parameter, for example the letter 'A', (has value 65 in ascii).
    I want the function to return the A, but since eax holds 4 bytes and this letter only needs ONE byte, I'm trying to use the AL part of the EAX register.
The problem here is that this function doesn't work when I use it. I get four strange-looking characters as a return value. Anyone knows why?
this is how my code looks like:
        .globl  letterprinter
# Name:             letterprinter
# Synopsis:         prints the character 'A' (or at least, it is supposed to)
# C-signature:      int letterprinter(unsigned char *res);
# Registers:        %EDX: for the argument that is supposed to get the value
#                   %EAX: for the return value(s)
#

letterprinter:                      # letterprinter

    pushl       %ebp                # start of
    movl        %esp, %ebp          # function

    movl        8(%ebp), %edx       # first argument

    movl        $65, %dl            # the value 'A' in lowest part of edx, dl

    movb        (%dl), %al          # moves it to the return register eax
    jmp     exit                    # ending function

exit:

    popl        %ebp                # popping - standard end of a function
                                    # 0-byte ? should there be one?
    ret                             # return

A:                     .globl  char

# Name:         char
# Synopsis:         A simplified sprintf
# C-signature:      int sprinter(unsigned char *res, unsigned char);
# Registers:        %EDX: first argument
#               %EBX: second argument
#

char:                   # char

    pushl       %ebp            # start of
    movl        %esp, %ebp      # function

    movl        8(%ebp), %edx           # first argument
    movl        12(%ebp), %eax          # second argument

add_res:
    movb        %al, (%edx)     # eax low gets the val at edx
    movb        $65, (%edx)     # puts A to the string
    jmp     exit            # jump to exit

exit:

    popl        %ebp            # popping standard end of function
    movb        $0,1(%edx)      # adds the zero-byte at end
    ret                 # return


text:
Q: Is asyncio.wait order guaranteed? I'm trying to implement fair queuing in my library that is based on asyncio.
In some function, I have a statement like (assume socketX are tasks):
done, pending = asyncio.wait(
    [socket1, socket2, socket3],
    return_when=asyncio.FIRST_COMPLETED,
)

Now I read the documentation for asyncio.wait many times but it does not contain the information I'm after. Mainly, I'd like to know if:

*

*socket1, socket2 and socket3 happened to be already ready when I issue the call. Is it guaranteed that done will contain them all or could it be that it returns only one (or two) ?

*In the second case, does the order of the tasks passed to wait() matter ?

I'm trying to assert if I can just apply fair-queuing in the set of done tasks (by picking one and leaving the other tasks for later resolution) or if I also need to care about the order I pass the tasks in.
The documentation is kinda silent about this. Any idea ?

A: This is only taken according to the source code of Python 3.5.
If the future is done before calling wait, they will all be placed in the done set:
import asyncio

async def f(n):
    return n

async def main():
    (done, pending) = await asyncio.wait([f(1), f(2), f(3)], return_when=asyncio.FIRST_COMPLETED)
    print(done)     # prints set of 3 futures
    print(pending)  # prints empty set

loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()


text:
Q: How to send direct email by Flutter web I Am Building a flutter web i have to send form Data by email to my Gmail email address How Can i. Please Help Me.
I had User "mailer 3.0.4" and flutter_email_sender: ^2.2.2
But They Both are not working...
Here Is My Code:
  // Perform login or signup
  Future<void> _validateAndSubmitForInformationForm() async {
    print('1');
    final MailOptions mailOptions = MailOptions(
      body: 'a long body for the email
 with a subset of HTML',
      subject: 'the Email Subject',
      recipients: ['bc160201844@vu.edu.pk'],
      isHTML: true,
      bccRecipients: ['bc160201844@vu.edu.pk'],
      ccRecipients: ['bc160201844@vu.edu.pk'],
//      attachments: [
//        'path/to/image.png',
//      ],
    );
    print('3');

    await FlutterMailer.send(mailOptions);
    print('2');
  }

A: You can use something like SendGrid to send an e-mail from flutter mobile with something like this: sorry for the bad formatting.
import 'package:http/http.dart' as http;

class SendGridUtil {
  static sendRegistrationNotification(String email) async {
    Map<String, String> headers = new Map();
    headers["Authorization"] =
        "Bearer $$$SENDGRIDAPIKEY$$$";
    headers["Content-Type"] = "application/json";

    var url = 'https://api.sendgrid.com/v3/mail/send';
    var response = await http.post(url,
        headers: headers,
        body:
            "{\n          \"personalizations\": [\n            {\n              \"to\": [\n                {\n                  \"email\": \"jerrod@liftaixxx.com\"\n                },\n                {\n                  \"email\": \"darran@gmailxxx.com\"\n                }\n              ]\n            }\n          ],\n          \"from\": {\n            \"email\": \"app@liftaixxx.com\"\n          },\n          \"subject\": \"New user registration\",\n          \"content\": [\n            {\n              \"type\": \"text\/plain\",\n              \"value\": \"New user register: $email\"\n            }\n          ]\n        }");
    print('Response status: ${response.statusCode}');
    print('Response body: ${response.body}');
  }
}

To send an e-mail from flutter web you can use something like a firebase cloud function - this is a function that is executed when a new user is created in firebase auth:
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
const sgMail = require('@sendgrid/mail')

admin.initializeApp(functions.config().firebase);

exports.sendWelcomeEmail = functions.auth.user().onCreate(user => {

console.log("User with email created: " + user.email);

sgMail.setApiKey("$$$SENDGRIDKEY$$$");
const liftAiMsg = {
  to: 'jerrod@liftaixxx.com',
  from: 'app@liftaixxx.com',
  subject: 'New user created',
  text: 'New user created with email: ' +user.email,
  html: "New user created with email:  "+user.email+"",
};

sgMail.send(liftAiMsg);

const customerMsg = {
  to: user.email,
  from: 'app@liftaixxx.com',
  subject: 'Welcome to LiftAI',
  text: 'Welcome to LiftAI',
  html: 'Welcome to LiftAI!',
};

sgMail.send(customerMsg);

});

A: EDIT: This won't work because SendGrid (and MailJet) was designed to work only on servers and not on clients.
As @dazza500 said, you need to:
1) Register at https://app.sendgrid.com/
2) Create an API key
3) Optional: check documentation (https://sendgrid.com/docs/API_Reference/Web_API_v3/index.html)
4) And use this code (replacing SENDGRIDAPIKEY with your API key):
import 'package:http/http.dart' as http;

class SendGridUtil {
  static sendRegistrationNotification(String email) async {
    Map<String, String> headers = new Map();
    headers["Authorization"] =
        "Bearer SENDGRIDAPIKEY";
    headers["Content-Type"] = "application/json";

    var url = 'https://api.sendgrid.com/v3/mail/send';
    var response = await http.post(url,
        headers: headers,
        body:
            "{\n          \"personalizations\": [\n            {\n              \"to\": [\n                {\n                  \"email\": \"jerrod@liftaixxx.com\"\n                },\n                {\n                  \"email\": \"darran@gmailxxx.com\"\n                }\n              ]\n            }\n          ],\n          \"from\": {\n            \"email\": \"app@liftaixxx.com\"\n          },\n          \"subject\": \"New user registration\",\n          \"content\": [\n            {\n              \"type\": \"text\/plain\",\n              \"value\": \"New user register: $email\"\n            }\n          ]\n        }");
    print('Response status: ${response.statusCode}');
    print('Response body: ${response.body}');
  }
}

A: You can create a specific (secured with a token for eg) WebAPI in your flavour language, and then make a simple POST call to it with the appropriate parameters.
In Flutter :
Future sendEmail(elementType elementoSent) async {
    var body = "Blabla, " + elementoSent.prpoerties;

    try {
        await http.post(
            "https://yourapiUrl.net/api/method",
            headers: {
                'Content-type': 'application/json',
                'Accept': 'application/json'
            },
            body: jsonEncode({"emailbody": '$body'}));
    } catch (e) {
        print(e);
    }
}

Here is an Web API code bloc for e.g. (in C#):
// POST api/<EmailsController>
[HttpPost]
public void Post([FromBody] EmailsModel model)
{
    if (model.Typemail == "1")
        _emailSender.SendEmailtoUserAsync("mail@gmail.com", "mail object", model.EmailBody);
}

The _emailSender.SendEmailtoUserAsync uses an specific or an external mail service like MailJet or SendGrid.


text:
Q: How to read an input then write on same line? I'm working on Visual Basic and would like to ask how can I input in this format?
"First name: Abdul, Second name: Sharif"
I wrote this code:
    Console.Write("First name: ")
    FirstName = Console.ReadLine()
    Console.Write(", Second name: ")
    SecondName = Console.ReadLine()

However, after I input the first value, it jumps to next line.
So what is the way to input and write on the same line?
Thank you.

A: ReadLine() reads a line, this is why it goes to the next line.
You need to use ReadKey() instead.  But then you will need a loop to add it to the FirstName variable and you will have to process special characters (like Enter/Return).

A: Unlike Console.Write() and Console.WriteLine(), the Console.Read() method DOESN'T do the same as it's counterpart, Console.ReadLine() without going down a line. Instead, it reads the next character. Console.Read() and Console.ReadKey() can be used to achieve what you want,
But there's another approach that I find better suiting your need;
Subtract 1 from the Console.CursorTop variable, and then set the Console.CursorLeft variable to the position (in the X axis) you want to print to.
Then, print the string. When changing the cursor's X position, remember to take in mind the length of the input as it is echoed, as well as any characters in the previous line in general.
One might say that Console.SetCursorPosition() can be used here and that's currect, but it is less efficient, as you will need to get the current Y position of the cursor + call a method.

A: Thank you! It works now.
    Console.Write("First name: ")
    FirstName = Console.ReadLine()
    Console.CursorTop = Console.CursorTop - 1
    Console.SetCursorPosition(Len("First name; " & FirstName), Console.CursorTop)
    Console.Write(", Second name: ")
    SecondName = Console.ReadLine()


text:
Q: How to indentation lines in VSCode like PhpStorm I'm using both PhpStorm and VSCode, they are both really good IDE. One of the most features I like in PhpStorm is Format Code, for example with this below code:
$full_name = 'Stackoverflow';
$age = 10;

When I select those lines and hit Command + Alt + L, it's automatically reformatted to
$full_name = 'Stackoverflow';
$age       = 10;

I have tried to use some extensions that support to format code in VSCode but none of them can do like PhpStorm.
Any suggestion?

A: Extension Alignment.

*

*select text

*alt+=


text:
Q: Why destructor cannot be template? I wan't to disable user declared destructor using SFINAE in union-like class as do it usual for constructors in classes:
#include <type_traits>
#include <cstdlib>

template< typename A, typename B >
struct U
{
    constexpr U() = default;
    constexpr U(A _a) : a(_a), s{false} {}
    constexpr U(B _b) : b(_b), s{true}  {}

    union
    {
        A a;
        B b;
    };

    bool s;

    template< typename = std::enable_if_t< !(std::is_trivially_destructible< A >{} && std::is_trivially_destructible< B >{}) >, // disable if A and B is trivially destructible
              bool is_noexcept = (noexcept(std::declval< A >().~A()) && noexcept(std::declval< B >().~B())) > // disable if A or B is not destructible
    ~U() noexcept(is_noexcept)
    {
        if (s) {
            b.~B();
        } else {
            a.~A();
        }
    }
};

int main()
{
    struct A {};
    struct B {};
    U< A, B > u;
    static_assert(std::is_literal_type< A >{});
    static_assert(std::is_literal_type< B >{}); // =>
    static_assert(std::is_literal_type< U< A, B > >{});
    return EXIT_SUCCESS;
}

but got an error:
main.cpp:24:5: error: destructor cannot be declared as a template
    ~U() noexcept(is_noexcept)
    ^
1 error generated.
Failure!

Is there theoretical reason for this restriction in C++? Or is it just a "legacy"?

A: As a work around, you may add layer and specialization, something like:
template <typename A, typename B,
          bool trivially_destructible = std::is_trivially_destructible<A>{}
                                    && std::is_trivially_destructible<B>{},
          bool is_no_except = noexcept(std::declval<A>().~A())
                        && noexcept(std::declval<B>().~B())>
struct UdestructorImpl;

template <typename A, typename B, bool is_no_except>
struct UdestructorImpl<A, B, true, is_no_except>
{
    ~UdestructorImpl() noexcept(is_no_except) = default;
}

template <typename A, typename B, bool is_no_except>
struct UdestructorImpl<A, B, false, is_no_except>
{
    ~UdestructorImpl() noexcept(is_no_except) = delete;
}

template< typename A, typename B > struct U : UdestructorImpl<A, B>
{
    // Implementation
};

A: Any class, U, can have one and only one destructor, which is declared within that class with the name ~U() and accepts exactly no parameters.
A template function specifies a family of functions, where a "family" describes a set containing one or more, with no upper limit on the number of members.
The two concepts are mutually exclusive.   A class cannot simultaneously have exactly one destructor and a family of destructors.


text:
Q: Access Azure Blob using Python without Azure Storage Blob package I need to upload a JSON file to Azure blob using Python, using below code:
from azure.storage.blob import BlobClient

blob = BlobClient(account_url=ACCOUNT_URL,
                  container_name=CONTAINER_NAME,
                  blob_name = folder1/folder2/sample.json,
                  credential=CREDENTIAL)

blob.upload_blob(json.dumps(sample_json),overwrite=True)

This code works well.
Only problem is, the package azure.storage.blob installs chardet package which is of LGPL license and its not acceptable for my project. Is there any other way we can upload the data to blob on Azure without using the above mentioned package?

A: SDKs are simply a wrapper over Azure Storage REST API. If using the SDK is not possible for you, you can write your own code that consumes REST API.
For uploading blob, the REST API operation would be Put Blob: https://learn.microsoft.com/en-us/rest/api/storageservices/put-blob.
Considering the SDKs are open source, you can take a look at the SDK code and see how REST APIs are consumed in the SDK. This is where you can find the source code: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/storage/azure-storage-blob/azure/storage/blob.


text:
Q: Laravel 4 with bootstrap-datepicker I'm using Laravel PHP Framework with Bootstrap. I want to know how to insert a datepicker in to a form.
I already have the bootstrap-datepicker installed but do not know how I will use.
Here is the code of my form:
{{ Form::open(array('action' => 'HomeController@postRegister')) }}

{{ Form::text('first_name', '', array('class' => 'form-control','placeholder' => 'primeiro nome')) }}

{{ Form::text('last_name', '', array('class' => 'form-control','placeholder' => 'último nome')) }}

{{ Form::text('email', '', array('class' => 'form-control','placeholder' => 'email')) }}

{{ Form::text('phone_number', '', array('class' => 'form-control','placeholder' => 'o teu número de telemóvel')) }}

        **
{{ Form::text('date_of_birth', '', array('class' => 'form-control','placeholder' => 'a tua data de nascimento')) }}
**

{{ Form::password('password', array('class' => 'form-control','placeholder' => 'a tua palavra-passe')) }}

{{ Form::password('password', array('class' => 'form-control','placeholder' => 'reintroduzir palavra-passe')) }}

{{ Form::submit('regista-te', array('class' => 'btn btn-danger')) }}

        {{ Form::close() }}

I need to replace this code for a datepicker:

{{ Form::text('date_of_birth', '', array('class' => 'form-control','placeholder' => 'a tua data de nascimento')) }}

Like this:
As a componet:

I hope someone can help me :)
Thanks!

A: Twitter bootstrap uses
 data-datepicker="datepicker"

to show the date picker. Laravel will allow you to use this is the same array as the class and placeholder.

{{ Form::text('date_of_birth', '', array('class' => 'form-control','placeholder' => 'a tua data de nascimento','data-datepicker' => 'datepicker')) }}

A: The following has worked for me. Difference between @Marco's and my answer is data-provide instead of data-datepicker.
{{ Form::text('startingDate', null, array('class' => 'form-control input-sm','placeholder' => 'Starting Date','data-provide' => 'datepicker')) }}


text:
Q: Macro That Detects More than 5 characters in Cell (zip code) I have created a function that retrieves a Range based on column name. Here is my code:
Sub sep_Filter()

    Dim zip_rng As String

    With Sheet2
        zip_rng = getColRangeFunction("postalcode")
          If Len(Range(zip_rng)) > 5 Then
            Range(zip_rng).Interior.Color = RGB(255, 0, 0)
            Range(zip_rng).Select
          Else
            Range(zip_rng).Interior.Color = xlNone
          End If
    End With
End Sub

Sheet2 Input Column D
Sheet2 Output Column D
Sheet3 Output Column D

088762598

088762598

06610-5000

06610-5000

330161898

330161898

970152880

970152880

112202570

112202570

127420800

127420800

062262040

062262040

07631
07631

10029
10029

11803
11803

99336
99336

A: EDIT I misunderstood what you were asking, I updated my answer to be tied to your question.
Here's a basic approach that will do what you're asking. It skips row one.
Sub onlyfirst5()

Const pRange As String = "D1"

Dim ws As Worksheet
Set ws = ActiveSheet

Dim crng As Range, cValues()

Set crng = Intersect(ws.UsedRange.Offset(1, 0), ws.UsedRange, ws.Range("D:D"))

cValues = crng.Value

Dim i As Long, j As Long

For i = LBound(cValues) To UBound(cValues)
    For j = LBound(cValues, 2) To UBound(cValues, 2)

    cValues(i, j) = Left(cValues(i, j), 5)
    Next j
Next i

'for same sheet different column
ws.Range("F2").Resize(UBound(cValues), UBound(cValues, 2)) = Application.Transpose(cValues)

'different sheet
Sheets("Sheet2").Range("F2").Resize(UBound(cValues), UBound(cValues, 2)) = Application.Transpose(cValues)

'different file
Workbooks("Zip Code Question.xlsb").Sheets("Sheet3").Range("F2").Resize(UBound(cValues), UBound(cValues, 2)) = Application.Transpose(cValues)

End Sub

A: Copy Entire Rows If Criteria Met
Option Explicit

Sub Postal5()

    ' Define constants.
    Const srcName As String = "Sheet2"
    Const srcFirst As String = "D2"
    Const dstName As String = "Sheet3"
    Const dstFirst As String = "A2"  ' do not change the 'A' (entire row).
    Const pLen As Long = 5

    ' Define workbook.
    Dim wb As Workbook: Set wb = ThisWorkbook ' Workbook containing this code.

    ' Define Source Range.
    Dim LastRow As Long
    Dim srg As Range
    With wb.Worksheets(srcName).Range(srcFirst)
        LastRow = .Offset(.Worksheet.Rows.Count - .Row).End(xlUp).Row
        Set srg = .Resize(LastRow - .Row + 1)
    End With

    ' 'Combine' critical cells into a range.
    Dim brg As Range ' Built Range
    Dim cel As Range ' Current Cell Range
    For Each cel In srg.Cells
        If Len(cel.Value) > pLen Then
            If brg Is Nothing Then
                Set brg = cel
            Else
                Set brg = Union(brg, cel)
            End If
        End If
    Next cel
    If brg Is Nothing Then Exit Sub

    Application.ScreenUpdating = False

    ' Copy and delete critical rows of Source Range.
    With wb.Worksheets(dstName).Range(dstFirst)
        .Resize(.Worksheet.Rows.Count - .Row + 1, _
            .Worksheet.Columns.Count).Clear
        Set brg = brg.EntireRow ' 'Convert' cells into rows.
        brg.Copy .Offset ' Copy. 'Offset' because range is in 'With'.
        brg.Delete ' Delete.
    End With

    Application.ScreenUpdating = False

End Sub

A: Text the next code, please. It uses arrays and it should be very fast for a big range:
Sub testSplitZiPCodeStrings()
 Dim sh2 As Worksheet, sh3 As Worksheet, lastR As Long
 Dim i As Long, arr, arrZip, arrNoZip, kZ As Long, kN As Long

 Set sh2 = ActiveSheet ' Worksheets("Sheet2")
 Set sh3 = sh2.Next ' Worksheets("Sheet3")
 lastR = sh2.Range("D" & sh2.Rows.count).End(xlUp).row 'last row

 arr = sh2.Range("D2:D" & lastR).Value 'put the range in an array
  ReDim arrZip(UBound(arr) - 1)   'redim the array to surely have place for all elements
  ReDim arrNoZip(UBound(arr) - 1) 'redim the array to surely have place for all elements

  For i = 1 To UBound(arr)       ' iterate between the array elements
    If Len(arr(i, 1)) = 5 Then
        arrZip(kZ) = arr(i, 1): kZ = kZ + 1
    Else
        arrNoZip(kN) = arr(i, 1): kN = kN + 1
    End If
  Next i
  ReDim Preserve arrZip(kZ - 1) 'keep only the array elements having values
  ReDim Preserve arrZip(kN - 1) 'keep only the array elements having values
  sh2.Range("D2:D" & lastR).Clear 'Clear the initial range
  'Drop the Zip array content at once:
  sh2.Range("D2").Resize(UBound(arrZip), 1).Value = Application.Transpose(arrZip)
  'Drop the NoZip array content at once:
  sh3.Range("D2").Resize(UBound(arrNoZip), 1).Value = Application.Transpose(arrNoZip)
End Sub

A: Here's 2 samples.  The first one is more intuitive and uses ranges.  The second one is less intuitive but faster by using arrays.
Simple but Slower:
'The easy way, but can be slow if you have lots of zip codes
Sub TrimRange()
    Dim InputWorksheet As Worksheet, OutputWorksheet As Worksheet
    Dim RangeInput As Range, RangeOutput As Range, Column As Range
    Dim HeaderRow As Integer, ColumnNumber As Integer, LastRow As Integer, i As Integer
    Dim OutputColumn As Range
    Dim ColumnFound As Boolean
    Dim fullzipcode As String

    Set InputWorksheet = Worksheets("Sheet2")
    Set OutputWorksheet = Worksheets("Sheet3")
    HeaderRow = 1

    'Get Input and Output Range
    ColumnNumber = 0
    ColumnFound = False
    For Each Column In InputWorksheet.Columns
        ColumnNumber = ColumnNumber + 1
        If Column.Cells(HeaderRow, 1) = "postalcode" Then
            LastRow = Column.End(xlDown).Row
            'I assume the Output column will be in the same position as the input column
            Set OutputColumn = OutputWorksheet.Columns(ColumnNumber)
            'If OutputColumn is always in Column 'D' then replace previous line with:
            'Set OutputColumn = OutputWorksheet.Columns(4)
            Set RangeInput = InputWorksheet.Range(Column.Cells(HeaderRow + 1, 1), Column.Cells(LastRow, 1))
            Set RangeOutput = OutputWorksheet.Range(OutputColumn.Cells(HeaderRow + 1, 1), OutputColumn.Cells(LastRow, 1))
            ColumnFound = True
            Exit For
        End If
    Next

    If ColumnFound Then
        'Initialize Interior color to nothing
        'and remove values from output column
        RangeInput.Interior.ColorIndex = 0
        RangeOutput.ClearContents

        'Change values and formatting
        For i = 1 To RangeInput.Rows.Count
            fullzipcode = RangeInput.Cells(i, 1).Value
            If Len(fullzipcode) > 5 Then
                RangeInput.Cells(i, 1).Interior.Color = RGB(255, 0, 0)
                RangeInput.Cells(i, 1).Value = Left(fullzipcode, 5)
            End If
            RangeOutput.Cells(i, 1).Value = fullzipcode
        Next
    End If
End Sub

Faster but Less Intuitive
'The harder way, but faster
Sub TrimRange2()
    Dim InputWorksheet As Worksheet, OutputWorksheet As Worksheet
    Dim RangeInput As Range, RangeOutput As Range, Column As Range
    Dim HeaderRow As Integer, ColumnNumber As Integer, LastRow As Integer, i As Integer
    Dim InputValues() As Variant, OutputValues() As Variant
    Dim OutputColumn As Range
    Dim ColumnFound As Boolean
    Dim fullzipcode As String

    Set InputWorksheet = Worksheets("Sheet2")
    Set OutputWorksheet = Worksheets("Sheet3")
    HeaderRow = 1

    'Get Input and Output Range
    ColumnNumber = 0
    ColumnFound = False
    For Each Column In InputWorksheet.Columns
        ColumnNumber = ColumnNumber + 1
        If Column.Cells(HeaderRow, 1) = "postalcode" Then
            LastRow = Column.End(xlDown).Row
            'I assume the Output column will be in the same position as the input column
            Set OutputColumn = OutputWorksheet.Columns(ColumnNumber)
            'If OutputColumn is always in Column 'D' then replace previous line with:
            'Set OutputColumn = OutputWorksheet.Columns(4)
            Set RangeInput = InputWorksheet.Range(Column.Cells(HeaderRow + 1, 1), Column.Cells(LastRow, 1))
            Set RangeOutput = OutputWorksheet.Range(OutputColumn.Cells(HeaderRow + 1, 1), OutputColumn.Cells(LastRow, 1))
            ColumnFound = True
            Exit For
        End If
    Next

    If ColumnFound Then
        'Initialize Interior color to nothing
        'and remove values from output column
        RangeInput.Interior.ColorIndex = 0
        RangeOutput.ClearContents
        'Initialize Arrays (much faster than working with ranges)
        InputValues = RangeInput.Value2
        OutputValues = RangeOutput.Value2

        'Change values and formatting
        For i = 1 To RangeInput.Rows.Count
            fullzipcode = InputValues(i, 1)
            If Len(fullzipcode) > 5 Then
                RangeInput.Cells(i, 1).Interior.Color = RGB(255, 0, 0)
                InputValues(i, 1) = Left(fullzipcode, 5)
            End If
            OutputValues(i, 1) = fullzipcode
        Next
        'Save arrays to ranges
        RangeInput.Value2 = InputValues
        RangeOutput.Value2 = OutputValues
    End If

End Sub


text:
Q: Python Pool Map() Gives ether Pickle Error Or Does Not Iterate List Properly I have a function that takes a list of urls and adds a header to each url. The url_list can be about 25,000 long lists. So, I want to use multiprocessing. I have tried 2 ways both with failure:
First way- the url_list is not passing correctly...the function only gets the first letter 'h' of the url_list url:
headers = {}
header_token = {}

def do_it(url_list):
    for i in url_list:
    print "adding header to: \n" + i
    requests.post(i, headers=headers)
    print "done!"

 value = raw_input("Proceed? Enter [Y] for yes: ")
    if value == "Y":
        pool = multiprocessing.Pool(processes=8)
    pool.map(do_it, url_list)
        pool.close()
        pool.join()

Traceback (most recent call last):
  File "head.py", line 95, in <module>
    pool.map(do_it, url_list)
  File "/usr/lib64/python2.7/multiprocessing/pool.py", line 250, in map
    return self.map_async(func, iterable, chunksize).get()
  File "/usr/lib64/python2.7/multiprocessing/pool.py", line 554, in get
    raise self._value
requests.exceptions.MissingSchema: Invalid URL u'h': No schema supplied

The second way...the way I prefer since I don't have to make headers dictionary global. But I get a pickle error:
def wrapper(headers):
    def do_it(url_list):
    for i in url_list:
        print "adding header to: \n" + i
        requests.post(i, headers=headers)
    print "done!"
    return do_it

    value = raw_input("Proceed? Enter [Y] for yes: ")
    if value == "Y":
        pool = multiprocessing.Pool(processes=8)
    pool.map(wrapper(headers), url_list)
        pool.close()
        pool.join()

Traceback (most recent call last):
  File "/usr/lib64/python2.7/threading.py", line 808, in __bootstrap_inner
    self.run()
  File "/usr/lib64/python2.7/threading.py", line 761, in run
    self.__target(*self.__args, **self.__kwargs)
  File "/usr/lib64/python2.7/multiprocessing/pool.py", line 342, in _handle_tasks
    put(task)
PicklingError: Can't pickle <type 'function'>: attribute lookup __builtin__.function failed
Traceback (most recent call last):
  File "/usr/lib64/python2.7/threading.py", line 808, in __bootstrap_inner
    self.run()
  File "/usr/lib64/python2.7/threading.py", line 761, in run
    self.__target(*self.__args, **self.__kwargs)
  File "/usr/lib64/python2.7/multiprocessing/pool.py", line 342, in _handle_tasks
    put(task)
PicklingError: Can't pickle <type 'function'>: attribute lookup __builtin__.function failed

A: If you are looking to use your second implementation, then I think you should be able to use dill to serialize your wrapper function. Dill can serialize almost anything in python. Dill also has some good tools for helping you understand what is causing your pickling to fail when your code fails. Dill has the same interface as python's pickle, but also provides some additional methods.  If you want to use dill for serialization with multiprocessing, all you have to do is:
>>> import dill
>>> # your code goes here (as above)

And, if that doesn't work for some reason, you could swap out multiprocessing with pathos... which is built to do multiprocessing using dill -- and provides a multi-*args map function (exactly like the standard python map).

A: You need to use a Queue from the multiprocessing package. The datatype that your pulling from or adding to needs to be thread and process safe; a Queue is both.
http://docs.python.org/2/library/queue.html
http://docs.python.org/2/library/multiprocessing.html#exchanging-objects-between-processes


text:
Q: How to kill all processes with a given partial name? I want to kill all processes that I get by:
ps aux | grep my_pattern

How to do it?
This does not work:
pkill my_pattern

A: If you judge pkill -f PATTERN a bit too dangerous, I wrote ezkill a bash script that prompt you to choose which processes amongst those that match the PATTERN you want to kill.
Warning: This project is no more maintained.

A: You can use the following command to
kill -9 $(ps aux | grep 'process' | grep -v 'grep' | awk '{print $2}')

A: If you do not want to take headache of finding process id, use regexp to kill process by name. For example, to kill chrome following code will do the trick.
killall -r chrome

A: If you need more flexibility in selecting the processes use
for KILLPID in `ps ax | grep 'my_pattern' | awk ' { print $1;}'`; do
  kill -9 $KILLPID;
done

You can use grep -e etc.

A: Found the best way to do it  for a server which does not support pkill
kill -9 $(ps ax | grep My_pattern| fgrep -v grep | awk '{ print $1 }')

You do not have to loop.

A: This is the way:
kill -9 $(pgrep -d' ' -f chrome)

The pgrep searches for all processes related to chrome and returns them in a list separated by spaces.
This is passed to the kill application that can safely kill all the related chrome processes.
This is still dangerous, be careful.

A: You can use the following command to:
ps -ef | grep -i myprocess | awk {'print $2'} | xargs kill -9

or
ps -aux | grep -i myprocess | awk {'print $2'} | xargs kill -9

It works for me.

A: Kill all processes matching the string "myProcessName":
ps -ef | grep 'myProcessName' | grep -v grep | awk '{print $2}' | xargs -r kill -9

Source: http://www.commandlinefu.com/commands/view/1138/ps-ef-grep-process-grep-v-grep-awk-print-2-xargs-kill-9
Why "ps pipe kill" from terminal is evil:
The Piping of integers you scraped from ps -ef to kill -9 is bad, and you should feel bad, doubly so if you're root or a user with elevated privileges, because it doesn't give your process a chance to cleanly shut down socket connections, clean up temp files, inform its children that it is going away or reset its terminal characteristics.
Instead send 15, and wait a second or two, and if that doesn't
work, send 2, and if that doesn't work, send 1.  If that doesn't,
REMOVE THE BINARY because the program is badly behaved.
As a general principle we don't use Unix Railgun to trim the hedges.  https://porkmail.org/era/unix/award.html#kill
Explanation of above command:
ps -ef produces a list of process id's on the computer visible to this user.  The pipe grep filters that down for rows containing that string.  The grep -v grep says don't match on the process itself doing the grepping.  The pipe awk print says split the rows on default delimiter whitespace and filter to the second column which is our process id.  The pipe xargs spins up a new process to send all those pid's to kill -9, ending them all.
Why ps pipe kill is bad, dangerous, ugly and hackish:

*

*There's a small possibility that you will accidentally end the operating system or cause undefined behavior in an unrelated process, leading to whole system instability because ps -ef lists thousands of processes, and you can't be sure some 3rd party process shares your process name, or that in the time between read and execute kill -9, the processid had changed to something else, and now you've ended some random necessary process unrelated to yours.

*If the code being force-ended is doing any database ops or secure transactions with low probability race conditions, some fraction of a percent of the time, atomicity of that transaction will be wrecked, producing undefined behavior.  kill -9 takes no prisoners.  If your code is sensitive to this, try replacing the xargs kill part with a transmitted flag that requests a graceful shutdown, and only if that request is denied, last-resort to kill -9
But, if you understand all the risks and control for them with unique names, and you're ok with a few dropped transactions or occasional corruption, then 99.9% of the time yer gonna be fine. If there's a problem, reboot the computer, make sure there aren't any process collisions.  It's because of code like this that makes the tech support script: "Have you tried restarting your computer" a level 5 meme.  "A Rogue Robot scraped ps to find integers and sent those to kill -9, so reboot the computer to clear the problem.
Why not just use pkill which is easier?
The above gives me manual control because ps, grep, awk, kill and xargs are multi-platform standard.  It gives full control to which regex engine to use, which part of the process name to match, handling case sensitivity and exception management.
pkill -f -e -c myProcessName

Does the same thing for me, but see man pkill has different behaviors, flags and regex engines between variants of Linux, Mac, Zune-Bash and my opensource router.  So yes, put your 35000 Watt Unix-Railgun into the capable hands of pkill to trim the hedges.  See what happens.

A: you can use the following command to list the process
ps aux | grep -c myProcessName

if you need to check the count of that process then run
ps aux | grep -c myProcessName |grep -v grep

after which you can kill the process using
kill -9 $(ps aux | grep -e myProcessName | awk '{ print $2 }')

A: Sounds bad?
 pkill `pidof myprocess`

example:
# kill all java processes
pkill `pidof java`

A: Also you can use killall -r my_pattern. -r Interpret process name pattern as an extended regular expression.
killall -r my_pattern

A: Use pkill -f, which matches the pattern for any part of the command line
pkill -f my_pattern

Just in case it doesn't work, try to use this one as well:
pkill -9 -f my_pattern

A: it's best and safest to use pgrep -f with kill, or just pkill -f, greping ps's output can go wrong.
Unlike using ps | grep with which you need to filter out the grep line by adding | grep -v or using pattern tricks, pgrep just won't pick itself by design.
Moreover, should your pattern appear in ps's UID/USER, SDATE/START or any other column, you'll get unwanted processes in the output and kill them, pgrep+pkill don't suffer from this flaw.
also I found that killall -r/ -regexp didn't work with my regular expression.
pkill -f "^python3 path/to/my_script$"
man pkill

A: I took Eugen Rieck's answer and worked with it. My code adds the following:

*

*ps ax includes grep, so I excluded it with grep -Eiv 'grep'

*Added a few ifs and echoes to make it human-readable.

I've created a file, named it killserver, here it goes:
#!/bin/bash
PROCESS_TO_KILL=bin/node
PROCESS_LIST=`ps ax | grep -Ei ${PROCESS_TO_KILL} | grep -Eiv 'grep' | awk ' { print $1;}'`
KILLED=
for KILLPID in $PROCESS_LIST; do
  if [ ! -z $KILLPID ];then
    kill -9 $KILLPID
    echo "Killed PID ${KILLPID}"
    KILLED=yes
  fi
done

if [ -z $KILLED ];then
    echo "Didn't kill anything"
fi

Results
➜  myapp git:(master) bash killserver
Killed PID 3358
Killed PID 3382
Killed
➜  myapp git:(master) bash killserver
Didn't kill anything


text:
Q: Distance of set of points to straight line going through 0 in $R^n$ Here is an old exercise I found, I've been going at it for the better part of 2 hours now and can't seem to find the correct proof.
Suppose $a_1, \ldots, a_m \in R^n$ is a set of point satisfying $\sum_i a_i = 0$.
Define
$$
L_{z,v} = \{ z+ \lambda v: \lambda \in R\}.
$$
Show that
$$
\sum_i d(a_i, L_{0,v})^2 \leq \sum_i d(a_i, L_{z,v})^2 \quad \forall z \in R^n.
$$
I've tried using induction on $n$ as well as $m$, I've tried to project all the elements into a plane perpendicular to $L_{0,v}$ and yet, I can't seem to figure it out.
Any tips would be greatly appreciated, thanks.

A: First notice that we may always assume $|v|=1$, so that we have a neat formula for the projection of $a_i$ onto $v$ and so
$$
d(a_i,L_{0,v})^2= |a_i-\langle a_i,v\rangle v|^2= |a_i|^2-2\langle a_i,v\rangle^2+ \langle a_i,v\rangle^2.
$$
Summing over $i$ the middle term vanishes by the condition on the $a_i$, so
$$
\sum_{i=1}^m d(a_i,L_{0,v})= \sum_{i=1}^m (|a_i|^2-\langle a_i,v\rangle^2).
$$
Now we use the same idea to compute the distances $d(a_i,L_{z,v})$, the only difference being that we have to first translate our reference system by $z$, so that our line passes through the origin and we can repeat the above:
$$
d(a_i,L_{z,v})^2= |a_i-z - \langle a_i-z, v\rangle v|^2 = |a_i-z|^2-\langle a_i-z,v\rangle^2= |a_i|^2-2\langle a_i,z\rangle +|z|^2- \langle a_i, v\rangle^2 + 2 \langle a_i,v\rangle\langle z,v\rangle -\langle z,v\rangle^2.
$$
Summing over $i$, we see that
$$
\sum_{i=1}^m d(a_i,L_{z,v})^2= \sum_{i=1}^m (|a_i|^2-\langle a_i,v\rangle^2) + m[|z|^2-\langle z,v\rangle^2],
$$
and the quantity in brackets is nonnegative by Cauchy-Schwarz.


text:
Q: Can't boot WINDOWS 10 from SSD in hp probook 450 g3 I am trying to go from HDD to SSD so I cloned boot disk to SSD. Although I have changed the boot order and checked other boot options as 'disabled', it keeps booting from HDD.
Boot menu
Bios Setup -> Boot Options


text:
Q: uploadify button does not display upload button in IE i'm in big trouble while using jquery uploadify plugin. It works with google chrome and firefox but in IE 7/8 upload file button not displaying. Anyone have idea about this?
    i've latest flash player installed.

A: There is a uploadifive member, who posted on the old forum, a method to detect, hide , show either the upload'ifive' or the upload'ify' version to make this more cross browser compatible.
I can not contact him/her as the forum is shut down.
http://www.uploadify.com/forum/#/discussion/comment/16896
Is anyone skilled enough to make sense of this post by user "chopstick" and implement his code?
EDIT go to themeforest they have lots of alternatives that work from ie6 and up >