问:
fanning records with left joins
I'm experiencing duplicates/fanning out of left joins.

Table Sales has a number of brands, but only two of the same brand names with different pricings: BRAND 2.

Table CSR Product also has two BRAND 2 brands, but for different states.

Table Product State Package doesn't have two BRAND 2.

I'm joining these three on brand field, yet I'm seeing for each BRAND 2 I add to a table, it multiplies the size. How can I fix this?

I need all Sales records, hence why I'm left joining on Sales. This is a smaller example of a larger problem I'm facing where the first left join was 3020 records, the second left join was 450,000 records.

My question is: If I'm LEFT JOINing to get all sales records, why does adding duplicate BRAND 2 to the other two joined tables multiply the sales records?

Sales:

```<code>brand   | pricing
----------------
BRAND 1    1
BRAND 2    2  <--- Brand 2
BRAND 2    7  <--- Brand 2
BRAND 3    3
BRAND 4    4
BRAND 5    5
BRAND 6    6
</code>```

Product State Package:

```<code>brand   | state
----------------
BRAND 5    WA
BRAND 4    AZ
BRAND 2    MO
BRAND 1    VT
BRAND 8    SD
</code>```

CSR Product:

```<code>brand   | state
----------------
BRAND 2    CT <--- Brand 2
BRAND 3    MA
BRAND 2    CA <--- Brand 2
BRAND 4    GA
BRAND 5    LA
BRAND 9    WA
</code>```

Query:

```<code>SELECT s.brand,
       tcp.brand as csr_brand,
       tpsp.brand as psp_brand
FROM   test_sales s
       LEFT JOIN test_csr_product tcp
              ON ( s.brand = tcp.brand )
       LEFT JOIN test_product_state_package tpsp
              ON ( s.brand = tpsp.brand );
</code>```

Output:

```<code> -- Need all sales records
 sales_brand | csr_brand | psp_brand
-------------+-----------+-----------
 BRAND 1     |           | BRAND 1
 BRAND 2     | BRAND 2   | BRAND 2
 BRAND 2     | BRAND 2   | BRAND 2
 BRAND 2     | BRAND 2   | BRAND 2
 BRAND 2     | BRAND 2   | BRAND 2
 BRAND 3     | BRAND 3   |
 BRAND 4     | BRAND 4   | BRAND 4
 BRAND 5     | BRAND 5   | BRAND 5
 BRAND 6     |           |
(9 rows)
</code>```

With three BRAND 2 in Sales: you can see there are duplicates for sale_price across the sales:

```<code>sales_brand | sale_price | csr_brand | psp_brand
-------------+------------+-----------+-----------
 BRAND 1     |          1 |           | BRAND 1
 BRAND 2     |          2 | BRAND 2   | BRAND 2
 BRAND 2     |          2 | BRAND 2   | BRAND 2
 BRAND 2     |          7 | BRAND 2   | BRAND 2
 BRAND 2     |          7 | BRAND 2   | BRAND 2
 BRAND 2     |         10 | BRAND 2   | BRAND 2
 BRAND 2     |         10 | BRAND 2   | BRAND 2
 BRAND 3     |          3 | BRAND 3   |
 BRAND 4     |          4 | BRAND 4   | BRAND 4
 BRAND 5     |          5 | BRAND 5   | BRAND 5
 BRAND 6     |          6 |           |
 (11 rows)
</code>```

答:
Does it fit?</p>

```<code>SELECT s.brand,
       tcp.brand as csr_brand,
       tpsp.brand as psp_brand
FROM   (select distinct t.brand from test_sales t) s
       LEFT JOIN test_csr_product tcp
              ON ( s.brand = tcp.brand )
       LEFT JOIN test_product_state_package tpsp
              ON ( s.brand = tpsp.brand );
</code>```

Title: fanning records with left joins

Body:
I'm experiencing duplicates/fanning out of left joins.

Table Sales has a number of brands, but only two of the same brand names with different pricings: BRAND 2.

Table CSR Product also has two BRAND 2 brands, but for different states.

Table Product State Package doesn't have two BRAND 2.

I'm joining these three on brand field, yet I'm seeing for each BRAND 2 I add to a table, it multiplies the size. How can I fix this?

I need all Sales records, hence why I'm left joining on Sales. This is a smaller example of a larger problem I'm facing where the first left join was 3020 records, the second left join was 450,000 records.

My question is: If I'm LEFT JOINing to get all sales records, why does adding duplicate BRAND 2 to the other two joined tables multiply the sales records?

Sales:

brand   | pricing
----------------
BRAND 1    1
BRAND 2    2  <--- Brand 2
BRAND 2    7  <--- Brand 2
BRAND 3    3
BRAND 4    4
BRAND 5    5
BRAND 6    6

Product State Package:

brand   | state
----------------
BRAND 5    WA
BRAND 4    AZ
BRAND 2    MO
BRAND 1    VT
BRAND 8    SD

CSR Product:

brand   | state
----------------
BRAND 2    CT <--- Brand 2
BRAND 3    MA
BRAND 2    CA <--- Brand 2
BRAND 4    GA
BRAND 5    LA
BRAND 9    WA

Query:

SELECT s.brand,
       tcp.brand as csr_brand,
       tpsp.brand as psp_brand
FROM   test_sales s
       LEFT JOIN test_csr_product tcp
              ON ( s.brand = tcp.brand )
       LEFT JOIN test_product_state_package tpsp
              ON ( s.brand = tpsp.brand );

Output:

 -- Need all sales records
 sales_brand | csr_brand | psp_brand
-------------+-----------+-----------
 BRAND 1     |           | BRAND 1
 BRAND 2     | BRAND 2   | BRAND 2
 BRAND 2     | BRAND 2   | BRAND 2
 BRAND 2     | BRAND 2   | BRAND 2
 BRAND 2     | BRAND 2   | BRAND 2
 BRAND 3     | BRAND 3   |
 BRAND 4     | BRAND 4   | BRAND 4
 BRAND 5     | BRAND 5   | BRAND 5
 BRAND 6     |           |
(9 rows)

With three BRAND 2 in Sales: you can see there are duplicates for sale_price across the sales:

sales_brand | sale_price | csr_brand | psp_brand
-------------+------------+-----------+-----------
 BRAND 1     |          1 |           | BRAND 1
 BRAND 2     |          2 | BRAND 2   | BRAND 2
 BRAND 2     |          2 | BRAND 2   | BRAND 2
 BRAND 2     |          7 | BRAND 2   | BRAND 2
 BRAND 2     |          7 | BRAND 2   | BRAND 2
 BRAND 2     |         10 | BRAND 2   | BRAND 2
 BRAND 2     |         10 | BRAND 2   | BRAND 2
 BRAND 3     |          3 | BRAND 3   |
 BRAND 4     |          4 | BRAND 4   | BRAND 4
 BRAND 5     |          5 | BRAND 5   | BRAND 5
 BRAND 6     |          6 |           |
 (11 rows)

Body:
Does it fit?

SELECT s.brand,
       tcp.brand as csr_brand,
       tpsp.brand as psp_brand
FROM   (select distinct t.brand from test_sales t) s
       LEFT JOIN test_csr_product tcp
              ON ( s.brand = tcp.brand )
       LEFT JOIN test_product_state_package tpsp
              ON ( s.brand = tpsp.brand );


来源: stackexchange

问:
How to remove line breaks with PHP or JS
I've tried about everything to delete some extra \n  characters in a web application I'm working with. I was hoping someone has encountered this issue before and knows what can be causing this. All my JS and PHP files are UTF-8 encoded with no BOM.

And yes I've tried things like

In JS:

```<code>text.replace(/\n/g,"")
</code>```

In PHP:

```<code>preg_replace("[\n]","",$result);
str_replace("\n","",$result);
</code>```

and when I try

```<code> text.replace(/\n/g,"")
</code>```

in the firebug console using the same string I get from the server it works but for reason it doesn't work in a JS file.

I'm desperate, picky and this is killing me. Any input is appreciated.

EDIT:

If it helps, I know how to use the replace functions above. I'm able to replace any other string or pattern except \n for some reason.

Answer Explanation:

Some people do and use what works because it just works. If you are like me and for the record I always like to know why what works WORKS!

In my case:

Why this works?   str_replace('\n', '', $result)

And this doesn't?   str_replace("\n", '', $result)

Looks identical right?
Well it seems that when you enclose a string with a character value like \n in double quotes "\n" it's seen as it's character value NOT as a string. On the other hand if you enclose it in single quotes '\n' it's really seen as the string \n. At least that is what i concluded in my 3 hours headache.

If what I concluded is a setup specific issue OR is erroneous please do let me know or edit.

答:
Both of the PHP functions you tried return the altered string, they do not alter their arguments:</p>

```<code>$result = preg_replace("[\n]","",$result);

$result = str_replace("\n","",$result);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've tried about everything to delete some extra \n  characters in a web application I'm working with. I was hoping someone has encountered this issue before and knows what can be causing this. All my JS and PHP files are UTF-8 encoded with no BOM.

And yes I've tried things like

In JS:

text.replace(/\n/g,"")

In PHP:

preg_replace("[\n]","",$result);
str_replace("\n","",$result);

and when I try

 text.replace(/\n/g,"")

in the firebug console using the same string I get from the server it works but for reason it doesn't work in a JS file.

I'm desperate, picky and this is killing me. Any input is appreciated.

EDIT:

If it helps, I know how to use the replace functions above. I'm able to replace any other string or pattern except \n for some reason.

Answer Explanation:

Some people do and use what works because it just works. If you are like me and for the record I always like to know why what works WORKS!

In my case:

Why this works?   str_replace('\n', '', $result)

And this doesn't?   str_replace("\n", '', $result)

Looks identical right?
Well it seems that when you enclose a string with a character value like \n in double quotes "\n" it's seen as it's character value NOT as a string. On the other hand if you enclose it in single quotes '\n' it's really seen as the string \n. At least that is what i concluded in my 3 hours headache.

If what I concluded is a setup specific issue OR is erroneous please do let me know or edit.

Body:
Both of the PHP functions you tried return the altered string, they do not alter their arguments:

$result = preg_replace("[\n]","",$result);

$result = str_replace("\n","",$result);

ContentLicense: CC BY-SA 2.5


问:
Wordpress images does not exist in upload folder but is showing in media library
I have found a very strange problem on my wordpress/woocommerce site.

I made a copy with the plugin Duplicator, to make some changes in a localhost environment.
My uploads folder is too big, so I unset it to be copied by Duplicator. To get all the images I simply copied all files and subfolders in /uploads folder to my localhost /uploads folder. After that wordpress finds only few images. The rest doesn't exist.

To make sure I haven't missed something during the copy process, I checked the /uploads folder on my live site. And there the same image files doesn't exist. Even if the path in the media library says they are in the /uploads folder.

So the big question is, where are the images they doesn't exist in the /uploads folder?
Is wordpress capable to store images in the database?

答:
Media files exist in upload folder but not showing up solution
Simply Paste this code in wpconfig.php and save it all is done :)</p>

```<code>define( 'UPLOADS', 'wp-content/'.'uploads' );
</code>```

Body:
Media files exist in upload folder but not showing up solution
Simply Paste this code in wpconfig.php and save it all is done :)

define( 'UPLOADS', 'wp-content/'.'uploads' );


问:
Django 1.8. Can't show an image in form
I'm using this package https://github.com/tomwalker/django_quiz to make a web quiz app. I need to add images to the multiplechoice answers.

So, I added to the Answers model:

```<code>image = models.ImageField(upload_to='uploads/%Y/%m/%d',
                           blank=True,
                           null=True,
                           verbose_name=_("Image"))
</code>```

Images are uploading and saving into the DB.

The part that shows choosable answers are shown in template like this:

```<code>{% for answer in form.answers %}
  <li class="list-group-item">
    {{ answer }}
  </li>
{% endfor %}
</code>```

I changed it to:

```<code>{% for answer in form.answers %}
  <li class="list-group-item">
    {{ answer }}
    <img src="{{ answer.image.url }}" alt="" />
  </li>
{% endfor %}
</code>```

But it's doesn't work. It renders

This is forms.py:

```<code>class QuestionForm(forms.Form):
    def __init__(self, question, *args, **kwargs):
        super(QuestionForm, self).__init__(*args, **kwargs)
        choice_list = [x for x in question.get_answers_list()]
        self.fields["answers"] = forms.ChoiceField(choices=choice_list,
                                               widget=RadioSelect)
</code>```

And this is model:

```<code>def get_answers_list(self):
    return [(answer.id, answer.content) for answer in
            self.order_answers(Answer.objects.filter(question=self))]
</code>```

答:
to display image :-

add {% load static %} in template

sample snippet:-

{% block content %}

{% load static %}

 Product List

```<code>{% if product %}

    {% for prd in product %}
            <div class="gallery">
            <a target="_blank" href="{% static  prd.image1  %}">
    <img src="{% static  prd.image1  %} " alt="{{ prd.name }}" width="400" height="400">
            </a>
            <div class="desc"> <a href="{{ prd.productid }}/view"> {{ prd.name }}</a></div>
            </div>
    {% endfor %}
{% else %}
     <p>There are no products entered by you .</p>
{% endif %}
</code>```

{% endblock %}

in url.py

```<code>    from django.conf.urls import url
    from django.contrib import admin
    **from django.conf import settings**
    **from django.conf.urls.static import static**
    from . import views
    from .views import Productlistview,Productdetailview

app_name= 'product'
urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^add/$', views.addproduct, name='addproduct'),
    url(r'^addsuccess/$', views.addsuccess, name='addsuccess'),
    url(r'^productview/$', Productlistview.as_view(), name='viewproduct'),
    url(r'^productview/(?P<productid>[0-9a-f-]+)/view/$',Productdetailview.as_view(), name='productdetailview'),
] **+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)**
</code>```

in settings.py -- project setings

```<code>STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
'/dev/projects/pro_mysql_practice/product/',
'dev/projects/pro_mysql_practice/index/',
 ]
</code>```

Title: Django 1.8. Can't show an image in form

Body:
I'm using this package https://github.com/tomwalker/django_quiz to make a web quiz app. I need to add images to the multiplechoice answers.

So, I added to the Answers model:

image = models.ImageField(upload_to='uploads/%Y/%m/%d',
                           blank=True,
                           null=True,
                           verbose_name=_("Image"))

Images are uploading and saving into the DB.

The part that shows choosable answers are shown in template like this:

{% for answer in form.answers %}

    {{ answer }}

{% endfor %}

I changed it to:

{% for answer in form.answers %}

    {{ answer }}

{% endfor %}

But it's doesn't work. It renders

This is forms.py:

class QuestionForm(forms.Form):
    def __init__(self, question, *args, **kwargs):
        super(QuestionForm, self).__init__(*args, **kwargs)
        choice_list = [x for x in question.get_answers_list()]
        self.fields["answers"] = forms.ChoiceField(choices=choice_list,
                                               widget=RadioSelect)

And this is model:

def get_answers_list(self):
    return [(answer.id, answer.content) for answer in
            self.order_answers(Answer.objects.filter(question=self))]

Body:
to display image :-

add {% load static %} in template

sample snippet:-

{% block content %}

{% load static %}

 Product List

{% if product %}

    {% for prd in product %}
            <div class="gallery">
            <a target="_blank" href="{% static  prd.image1  %}">
    <img src="{% static  prd.image1  %} " alt="{{ prd.name }}" width="400" height="400">
            </a>
            <div class="desc"> <a href="{{ prd.productid }}/view"> {{ prd.name }}</a></div>
            </div>
    {% endfor %}
{% else %}
     <p>There are no products entered by you .</p>
{% endif %}

{% endblock %}

in url.py

    from django.conf.urls import url
    from django.contrib import admin
    **from django.conf import settings**
    **from django.conf.urls.static import static**
    from . import views
    from .views import Productlistview,Productdetailview

app_name= 'product'
urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^add/$', views.addproduct, name='addproduct'),
    url(r'^addsuccess/$', views.addsuccess, name='addsuccess'),
    url(r'^productview/$', Productlistview.as_view(), name='viewproduct'),
    url(r'^productview/(?P<productid>[0-9a-f-]+)/view/$',Productdetailview.as_view(), name='productdetailview'),
] **+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)**

in settings.py -- project setings

STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
'/dev/projects/pro_mysql_practice/product/',
'dev/projects/pro_mysql_practice/index/',
 ]


问:
Django does not redirect from one view/url to another
I will start with explanation of what I want to achieve.
Basically I want to display in my view(prefs) an array items on a page that each item looks like button and if clicked it redirects to a view(results) and passes an argument(i.e itself)

My views.py look like this

```<code>def prefs(request):
    if request.method == 'POST':
        for i in user_queryset(request): #this function returns an array
            if i in request.POST.values():
                    return redirect(reverse('results',kwargs={'UserChoice':i}))
    elif not request.user.is_authenticated():
        return HttpResponse('Please login or sign-up to use this feature')
    else:
        uid = request.user
        return render(request,'test.html',{'form':user_queryset(request,uid)})

def results(request,UserChoice):
        if request.method =='GET':
            return render(request,'test2.html',{'objects':request_places(request,UserChoice)}) #another function that I need to use the arguments in
        else:
            return HttpResponse('Hello, World!')
</code>```

my urls.py

```<code>url(r'places/$',views.prefs,name='prefs'),
url(r'^places/results/(?P<UserChoice>[^\/]*)/$', views.results, name='results')
</code>```

and my templates

test.html

```<code>    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<ul>
    <li>
            <form action="" >
                        {% for obj in  form %}
     <!--<input type="text" name="{{ obj }} ">-->
            <input type="submit" value="{{ obj }}">
            </form>
    </li>
    {% endfor %}
</ul>
</body>
</html>
    </ul>
</code>```

and test2.html

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello, World!</title>
    <li>
        {% for items in objects %}
        <h>{{ items.name }} - {{ items.formatted_address }}</h>
     </li>
    {% endfor %}
</head>
<body>

</body>
</html>
</code>```

答:
First. As a matter of style I recommend that you use the login decorator in your views.py:

```<code>from django.contrib.auth.decorators import login_required
@login_required
</code>```

Second. If you aim to do a POST method you should declare it in your HTML file, plus add the needed crsf token.

```<code><form method="POST">{% csrf_token %}
</code>```

Third. Why would a simple link tag with an href attribute would not suffice you for any given object?

```<code><a href="results/{{obj.pk}}/">{{obj}}</a>
</code>```

In urls.py:

```<code>urls.py: url(r'^places/results/(?P<UserChoice>[0-9]+)/$', views.results, name='results')
</code>```

In views.py:

```<code>obj='object_name'.objects.get(pk=UserChoice)
</code>```

Then your desired object is called obj you can either passed it in a HttpResponse or in a context

I hope it helps!

Body:
I will start with explanation of what I want to achieve.
Basically I want to display in my view(prefs) an array items on a page that each item looks like button and if clicked it redirects to a view(results) and passes an argument(i.e itself)

My views.py look like this

def prefs(request):
    if request.method == 'POST':
        for i in user_queryset(request): #this function returns an array
            if i in request.POST.values():
                    return redirect(reverse('results',kwargs={'UserChoice':i}))
    elif not request.user.is_authenticated():
        return HttpResponse('Please login or sign-up to use this feature')
    else:
        uid = request.user
        return render(request,'test.html',{'form':user_queryset(request,uid)})

def results(request,UserChoice):
        if request.method =='GET':
            return render(request,'test2.html',{'objects':request_places(request,UserChoice)}) #another function that I need to use the arguments in
        else:
            return HttpResponse('Hello, World!')

my urls.py

url(r'places/$',views.prefs,name='prefs'),
url(r'^places/results/(?P<UserChoice>[^\/]*)/$', views.results, name='results')

and my templates

test.html

    <!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>

            <form action="" >
                        {% for obj in  form %}

            <input type="submit" value="{{ obj }}">
            </form>

    {% endfor %}

and test2.html

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Hello, World!</title>

        {% for items in objects %}
        <h>{{ items.name }} - {{ items.formatted_address }}</h>

    {% endfor %}

Body:
First. As a matter of style I recommend that you use the login decorator in your views.py:

from django.contrib.auth.decorators import login_required
@login_required

Second. If you aim to do a POST method you should declare it in your HTML file, plus add the needed crsf token.

<form method="POST">{% csrf_token %}

Third. Why would a simple link tag with an href attribute would not suffice you for any given object?

<a href="results/{{obj.pk}}/">{{obj}}</a>

In urls.py:

urls.py: url(r'^places/results/(?P<UserChoice>[0-9]+)/$', views.results, name='results')

In views.py:

obj='object_name'.objects.get(pk=UserChoice)

Then your desired object is called obj you can either passed it in a HttpResponse or in a context

I hope it helps!


问:
How to create a local pypi mirror?
I want to create a local pypi mirror according to the web tutorial.

set local pypi mirror

Here is my way.

```<code>wget https://bootstrap.pypa.io/get-pip.py
sudo python2.7   get-pip.py
sudo pip2.7 install  pep381client
mkdir  mirror
pep381run  /tmp/mirror
</code>```

An error info occurs here:

```<code>Traceback (most recent call last):
  File "/usr/local/bin/pep381run", line 23, in <module>
    state = pep381client.Synchronization.initialize(targetdir)
  File "/usr/local/lib/python2.7/dist-packages/pep381client/__init__.py", line 96, in initialize
    status.projects_to_do = set(xmlrpc().list_packages())
  File "/usr/lib/python2.7/xmlrpclib.py", line 1243, in __call__
    return self.__send(self.__name, args)
  File "/usr/lib/python2.7/xmlrpclib.py", line 1602, in __request
    verbose=self.__verbose
  File "/usr/lib/python2.7/xmlrpclib.py", line 1283, in request
    return self.single_request(host, handler, request_body, verbose)
  File "/usr/lib/python2.7/xmlrpclib.py", line 1331, in single_request
    response.msg,
xmlrpclib.ProtocolError: <ProtocolError for pypi.python.org/pypi: 403 Must access using HTTPS instead of HTTP>
</code>```

How to create a local pypi mirror ?

答: pep381client seems to be quite outdated (last updated in 2011). You need something more fresh like devpi or pypi-server.

Title: How to create a local pypi mirror?

Body:
I want to create a local pypi mirror according to the web tutorial.

set local pypi mirror

Here is my way.

wget https://bootstrap.pypa.io/get-pip.py
sudo python2.7   get-pip.py
sudo pip2.7 install  pep381client
mkdir  mirror
pep381run  /tmp/mirror

An error info occurs here:

Traceback (most recent call last):
  File "/usr/local/bin/pep381run", line 23, in <module>
    state = pep381client.Synchronization.initialize(targetdir)
  File "/usr/local/lib/python2.7/dist-packages/pep381client/__init__.py", line 96, in initialize
    status.projects_to_do = set(xmlrpc().list_packages())
  File "/usr/lib/python2.7/xmlrpclib.py", line 1243, in __call__
    return self.__send(self.__name, args)
  File "/usr/lib/python2.7/xmlrpclib.py", line 1602, in __request
    verbose=self.__verbose
  File "/usr/lib/python2.7/xmlrpclib.py", line 1283, in request
    return self.single_request(host, handler, request_body, verbose)
  File "/usr/lib/python2.7/xmlrpclib.py", line 1331, in single_request
    response.msg,
xmlrpclib.ProtocolError: <ProtocolError for pypi.python.org/pypi: 403 Must access using HTTPS instead of HTTP>

How to create a local pypi mirror ?


问:
change a code from flipping "8bpp .bmp image" horizontally to flip a "1bpp .bmp image" horizontally in x86
Hello here I have developed the code for Mirror/flipping an 8 bpp .BMP image horizontally. Handling any width properly, not only multiples of 4. Now I have to convert this code to do the same but for a 1 bpp . bmp image(grayscale) using x86. The difficult part is that I dont know how to excess the individual bit maybe someone can edit this code..

```<code>        section     .text
    global      mirrorbmp8
mirrorbmp8:
    push        ebp
    mov     ebp, esp
    push        ebx
    push        esi
    push        edi

    mov     ebx, [ebp+12]       ;width - without padding
    and     ebx, 11b
    je      init            ;checking if there is a padding
    mov     edi, 4
    sub     edi, ebx
    add     [ebp+12], edi       ;width - with padding

init:
    mov     ebx, [ebp+16]
    ;calculating the distance between top&bottom pixel
    dec     ebx
    mov     eax, [ebp+12]
    mul     ebx
    mov     esi, eax

    mov     edi, [ebp+8]    ;the first bottom pixel
    mov     edx, edi            ;the first top pixel
    mov     eax, edi
    add     eax, esi
    mov     ecx, [ebp+12]
            ;register responsible for calc left columns

loop0:
    push        esi
    mov     esi, [ebp+12]

loop1:
    mov     bl, [edi]               ;changing pixels
    xchg        bl, [eax]
    mov     [edi], bl

    add     edi, esi        ;next pixel in this column
    sub     eax, esi
    cmp     edi, eax
    jl      loop1

    inc     edx             ;next bottom pixel
    mov     edi, edx

    mov     eax, edi                ;next top pixel
    pop     esi
    add     eax, esi

    dec     ecx         ;decrement number of columns left
    jnz     loop0           ;was that the last column?

end:
    pop     edi
    pop     esi
    pop     ebx

    mov     esp, ebp
    pop     ebp
    ret
</code>```

Any help will be appreciated.
Thanks in advance :)

p.s if i will be able to do this version then I have to convert the whole code for x86-64 version also, any hints in this regard will also be helpful..

答:
Bitmaps are stored in scanlines with one line of pixels per scan line. All you really have to do is reverse the order of these lines. The firs step would be to copy the headers of the bitmap into another file. Then you should calculate the length of each scanline. Because each scanline is always 32-bit padded, you'll need some math:

```<code>scanlineLength = imageWidth / 8
IF imageWidth % 32 != 0
  scanlineLength += 1
ENDIF
</code>```

Next, copy scanlineLength bytes from the old file into the new file. Move up one scanline and repeat the process until they are all copied.

Edit: After rereading your question I'm still not sure which way you're flipping the images so I'm not sure if this applies.

Body:
Hello here I have developed the code for Mirror/flipping an 8 bpp .BMP image horizontally. Handling any width properly, not only multiples of 4. Now I have to convert this code to do the same but for a 1 bpp . bmp image(grayscale) using x86. The difficult part is that I dont know how to excess the individual bit maybe someone can edit this code..

        section     .text
    global      mirrorbmp8
mirrorbmp8:
    push        ebp
    mov     ebp, esp
    push        ebx
    push        esi
    push        edi

    mov     ebx, [ebp+12]       ;width - without padding
    and     ebx, 11b
    je      init            ;checking if there is a padding
    mov     edi, 4
    sub     edi, ebx
    add     [ebp+12], edi       ;width - with padding

init:
    mov     ebx, [ebp+16]
    ;calculating the distance between top&bottom pixel
    dec     ebx
    mov     eax, [ebp+12]
    mul     ebx
    mov     esi, eax

    mov     edi, [ebp+8]    ;the first bottom pixel
    mov     edx, edi            ;the first top pixel
    mov     eax, edi
    add     eax, esi
    mov     ecx, [ebp+12]
            ;register responsible for calc left columns

loop0:
    push        esi
    mov     esi, [ebp+12]

loop1:
    mov     bl, [edi]               ;changing pixels
    xchg        bl, [eax]
    mov     [edi], bl

    add     edi, esi        ;next pixel in this column
    sub     eax, esi
    cmp     edi, eax
    jl      loop1

    inc     edx             ;next bottom pixel
    mov     edi, edx

    mov     eax, edi                ;next top pixel
    pop     esi
    add     eax, esi

    dec     ecx         ;decrement number of columns left
    jnz     loop0           ;was that the last column?

end:
    pop     edi
    pop     esi
    pop     ebx

    mov     esp, ebp
    pop     ebp
    ret

Any help will be appreciated.
Thanks in advance :)

p.s if i will be able to do this version then I have to convert the whole code for x86-64 version also, any hints in this regard will also be helpful..

Body:
Bitmaps are stored in scanlines with one line of pixels per scan line. All you really have to do is reverse the order of these lines. The firs step would be to copy the headers of the bitmap into another file. Then you should calculate the length of each scanline. Because each scanline is always 32-bit padded, you'll need some math:

scanlineLength = imageWidth / 8
IF imageWidth % 32 != 0
  scanlineLength += 1
ENDIF

Next, copy scanlineLength bytes from the old file into the new file. Move up one scanline and repeat the process until they are all copied.

Edit: After rereading your question I'm still not sure which way you're flipping the images so I'm not sure if this applies.


问:
Dealing with special characters in pandas Data Frame´s column Name
I am importing an excel worksheet that has the following columns name:

```<code>N° Pedido
   1234
   6424
   4563
</code>```

The column name ha a special character (°). Because of that, I can´t merge this with another Data Frame or rename the column. I don´t get any error message just the name stays the same. What should I do?

This is the code I am using and the result of the Dataframes:

```<code>    import pandas as pd
    import numpy as np
    # Importando Planilhas
    CRM = pd.ExcelFile(r'C:\Users\Michel\Desktop\Relatorio de
    Vendas\relatorio_vendas_CRM.xlsx', encoding= 'utf-8')
    protheus = pd.ExcelFile(r'C:\Users\Michel\Desktop\Relatorio de
    Vendas\relatorio_vendas_protheus.xlsx', encoding= 'utf-8')
    #transformando em Data Frame
    df_crm = CRM.parse('190_pedido_export (33)')
    df_protheus = protheus.parse('Relatorio de Pedido de Venda')]
    # Transformando Campos em float o protheus
    def turn_to_float(x):
    return np.float(x)

    df_protheus["TES"] = df_protheus["TES"].apply(turn_to_float)
    df_protheus["Qtde"] = df_protheus["Qtde"].apply(turn_to_float)
    df_protheus["Valor"] = df_protheus["Valor"].apply(turn_to_float)
    #Tirando Tes de não venda do protheus
    # tirando valores com código errado 6
    df_protheus_1 = df_protheus[df_protheus.TES != 513.0]
    df_protheus_2 = df_protheus_1[df_protheus_1.TES != 576.0]

    **df_crm.columns = df_crm.columns.str.replace('N° Pedido', 'teste')
    df_crm.columns**

    Orçamento Origem    N° Pedido   Nº Pedido ERP   Estabelecimento Tipo de
    Pedido  Classificação(Tipo) Aplicação   Conta   CNPJ/CPF    Contato ...
    Aprovação Parcial   Antecipa Entrega    Desconto da Tabela de Preço
    Desconto do Cliente Desconto Informado  Observações Observações NF  Vl
    Total Bruto Vl Total    Completo
    0   20619.0 23125   NaN Optitex 1 - Venda   NaN Industrialização/Revenda
    XAVIER E ARAUJO LTDA ME 7970626000170   NaN ... N   N   0   0   0
</code>```

Note that I used other codes for the bold part with the same result:

```<code>#renomeando tabela para dar Merge
#df_crm['proc'] = df_crm['N\xc2\xb0 Pedido']

#df_crm['N Pedido'] = df_crm['N° Pedido']
#df_crm.drop('N° Pedido',inplace=True,axis=1)
#df_crm

#df_crm['N Pedido'] = df_crm['N° Pedido']
#df.drop('N° Pedido',inplace=True,axis=1)
#df_crm

#df_crm_1 = df_crm.rename(columns={"N°Pedido": "teste"})
#df_crm_1
</code>```

答:
Thanks for posting the link to the Google Sheet. I downloaded it and loaded it via pandas:

```<code>df = pd.read_excel(r'~\relatorio_vendas_CRM.xlsx', encoding = 'utf-8')
df.columns = df.columns.str.replace('°', '')
df.columns = df.columns.str.replace('º', '')
</code>```

Note that the two replace statements are replacing different characters, although they look very similar.

Help from: Why do I get a SyntaxError for a Unicode escape in my file path?

Body:
I am importing an excel worksheet that has the following columns name:

N° Pedido
   1234
   6424
   4563

The column name ha a special character (°). Because of that, I can´t merge this with another Data Frame or rename the column. I don´t get any error message just the name stays the same. What should I do?

This is the code I am using and the result of the Dataframes:

    import pandas as pd
    import numpy as np
    # Importando Planilhas
    CRM = pd.ExcelFile(r'C:\Users\Michel\Desktop\Relatorio de
    Vendas\relatorio_vendas_CRM.xlsx', encoding= 'utf-8')
    protheus = pd.ExcelFile(r'C:\Users\Michel\Desktop\Relatorio de
    Vendas\relatorio_vendas_protheus.xlsx', encoding= 'utf-8')
    #transformando em Data Frame
    df_crm = CRM.parse('190_pedido_export (33)')
    df_protheus = protheus.parse('Relatorio de Pedido de Venda')]
    # Transformando Campos em float o protheus
    def turn_to_float(x):
    return np.float(x)

    df_protheus["TES"] = df_protheus["TES"].apply(turn_to_float)
    df_protheus["Qtde"] = df_protheus["Qtde"].apply(turn_to_float)
    df_protheus["Valor"] = df_protheus["Valor"].apply(turn_to_float)
    #Tirando Tes de não venda do protheus
    # tirando valores com código errado 6
    df_protheus_1 = df_protheus[df_protheus.TES != 513.0]
    df_protheus_2 = df_protheus_1[df_protheus_1.TES != 576.0]

    **df_crm.columns = df_crm.columns.str.replace('N° Pedido', 'teste')
    df_crm.columns**

    Orçamento Origem    N° Pedido   Nº Pedido ERP   Estabelecimento Tipo de
    Pedido  Classificação(Tipo) Aplicação   Conta   CNPJ/CPF    Contato ...
    Aprovação Parcial   Antecipa Entrega    Desconto da Tabela de Preço
    Desconto do Cliente Desconto Informado  Observações Observações NF  Vl
    Total Bruto Vl Total    Completo
    0   20619.0 23125   NaN Optitex 1 - Venda   NaN Industrialização/Revenda
    XAVIER E ARAUJO LTDA ME 7970626000170   NaN ... N   N   0   0   0

Note that I used other codes for the bold part with the same result:

#renomeando tabela para dar Merge
#df_crm['proc'] = df_crm['N\xc2\xb0 Pedido']

#df_crm['N Pedido'] = df_crm['N° Pedido']
#df_crm.drop('N° Pedido',inplace=True,axis=1)
#df_crm

#df_crm['N Pedido'] = df_crm['N° Pedido']
#df.drop('N° Pedido',inplace=True,axis=1)
#df_crm

#df_crm_1 = df_crm.rename(columns={"N°Pedido": "teste"})
#df_crm_1

Body:
Thanks for posting the link to the Google Sheet. I downloaded it and loaded it via pandas:

df = pd.read_excel(r'~\relatorio_vendas_CRM.xlsx', encoding = 'utf-8')
df.columns = df.columns.str.replace('°', '')
df.columns = df.columns.str.replace('º', '')

Note that the two replace statements are replacing different characters, although they look very similar.

Help from: Why do I get a SyntaxError for a Unicode escape in my file path?


问:
How to combine work from more than one developer before checking into TFS?
My team's policy is to not check in broken code into TFS. But what if two team members are working on the same file and each member's work represents a partial solution ? One members changes won't work without the other.

How is the best way to combine the code and still follow policy of not checking in broken code ?

答: Consider allowing broken code on branches. The team members could commit code to branches and merge those branches together before merging into master. Your primary or master branch should require a passing build before a pull request can be merged in.


问:
Fetching users with delta and memberOf filter from Microsoft Graph
Is there a way to filter users based on MemberOf when doing a delta query?

I've tried the following (and a numerous variations on OData syntax) but with no success.

```<code>https://graph.microsoft.com/beta/users/delta?$filter=MemberOf eq '1f3f7dec-679c-4e3a-bc0b-aa43000c5a31'

https://graph.microsoft.com/beta/users/delta?$filter=MemberOf/any(g:g, Id eq '1f3f7dec-679c-4e3a-bc0b-aa43000c5a31')
</code>```

Error:

```<code>{
    "error": {
        "code": "BadRequest",
        "message": "Invalid filter clause",
        "innerError": {
            "request-id": "906cdcb0-cf3d-4eda-8c0b-2cdd9002cc4f",
            "date": "2017-12-07T10:45:41"
        }
    }
}
</code>```

答: Unfortunately memberOf is not a supported filter. The Microsoft Graph delta API only supports filtering based on immutable properties.</p>

Body:
Is there a way to filter users based on MemberOf when doing a delta query?

I've tried the following (and a numerous variations on OData syntax) but with no success.

https://graph.microsoft.com/beta/users/delta?$filter=MemberOf eq '1f3f7dec-679c-4e3a-bc0b-aa43000c5a31'

https://graph.microsoft.com/beta/users/delta?$filter=MemberOf/any(g:g, Id eq '1f3f7dec-679c-4e3a-bc0b-aa43000c5a31')

Error:

{
    "error": {
        "code": "BadRequest",
        "message": "Invalid filter clause",
        "innerError": {
            "request-id": "906cdcb0-cf3d-4eda-8c0b-2cdd9002cc4f",
            "date": "2017-12-07T10:45:41"
        }
    }
}


问:
How to make jQuery countdown a constant one
I created a little countdown (I know it is not the correct term but don't know what is). It counts from one number to another for a specific time.

```<code><div class="headline">
  <p> How much remains to meet the goal? </p>
  </div>
<div class="loader">
  <span class="count">350000</span>
</div>

$('.count').each(function () {
    $(this).prop('Counter',336123).animate({
        Counter: $(this).text()
    }, {
        duration: 1728000000,
        easing: 'swing',
        step: function (now) {
            $(this).text(Math.ceil(now));
        }
    });
});
</code>```

You can see the code here:

The problem is that whenever the countdown is opened, these 20 days will start from this moment and from the originally assigned number.

How do I make the time start running from one moment run continuously, and when someone opens the page to see only the numbers that remain at the time of opening.

Excuse me for this bad explanation!

答:
Ok, so you can take adventage of the Date() function which is available even on Vanilla javascript.

The Date object is used to work with dates and times.

Date objects are created with new Date().

I created a code for you, the only thing you need to do is to tweak the specific date that you want to countdown to on the second line.

// Set the date we're counting down to
var countDownDate = new Date("Dec 09, 2017 19:49:00").getTime(); //CHANGE HERE<----

// Update the count down every 1 second
var x = setInterval(function() {

  // Get todays date and time
  var now = new Date().getTime();

  // Find the distance between now an the count down date
  var distance = countDownDate - now;

  // Time calculations for days, hours, minutes and seconds
  var seconds = Math.floor((distance % (1000 * 60))/1000 )+ //seconds
  (Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)))*60+ // min to sec
  (Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)))*60*60+ // hours to sec
  (Math.floor(distance / (1000 * 60 * 60 * 24)))*60*60*60; // days to sec

  // Display the result in the element with id="demo"
  document.getElementById("demo").innerHTML =  seconds + "s ";

  // If the count down is finished, write some text
  if (distance < 0) {
    clearInterval(x);
    document.getElementById("demo").innerHTML = "EXPIRED";
  }
}, 1000);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@background-color: #4684ee;
@loader-color: #fff;
@loader-size: 40vh;
@import '//fonts.googleapis.com/css?family=Bangers';
@headline: 40vh;

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

body {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: blue;
}

.loader {
  color: #fff;

  font-family: Bangers, Menlo, Monaco, monospace;
  font-weight: bold;
  font-size: @loader-size;
  letter-spacing: 0.6rem;
  opacity: 0.9;
}

.headline {
  font-family: Bangers, Menlo, Monaco, monospace;
  color: #fff;
  font-size: 20vh;
}</code>```

 How much remains to meet the goal?

```

Body:
I created a little countdown (I know it is not the correct term but don't know what is). It counts from one number to another for a specific time.

 How much remains to meet the goal?

  350000

$('.count').each(function () {
    $(this).prop('Counter',336123).animate({
        Counter: $(this).text()
    }, {
        duration: 1728000000,
        easing: 'swing',
        step: function (now) {
            $(this).text(Math.ceil(now));
        }
    });
});

You can see the code here:

The problem is that whenever the countdown is opened, these 20 days will start from this moment and from the originally assigned number.

How do I make the time start running from one moment run continuously, and when someone opens the page to see only the numbers that remain at the time of opening.

Excuse me for this bad explanation!

Body:
Ok, so you can take adventage of the Date() function which is available even on Vanilla javascript.

The Date object is used to work with dates and times.

Date objects are created with new Date().

I created a code for you, the only thing you need to do is to tweak the specific date that you want to countdown to on the second line.

// Set the date we're counting down to
var countDownDate = new Date("Dec 09, 2017 19:49:00").getTime(); //CHANGE HERE<----

// Update the count down every 1 second
var x = setInterval(function() {

  // Get todays date and time
  var now = new Date().getTime();

  // Find the distance between now an the count down date
  var distance = countDownDate - now;

  // Time calculations for days, hours, minutes and seconds
  var seconds = Math.floor((distance % (1000 * 60))/1000 )+ //seconds
  (Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)))*60+ // min to sec
  (Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)))*60*60+ // hours to sec
  (Math.floor(distance / (1000 * 60 * 60 * 24)))*60*60*60; // days to sec

  // Display the result in the element with id="demo"
  document.getElementById("demo").innerHTML =  seconds + "s ";

  // If the count down is finished, write some text
  if (distance < 0) {
    clearInterval(x);
    document.getElementById("demo").innerHTML = "EXPIRED";
  }
}, 1000);

@background-color: #4684ee;
@loader-color: #fff;
@loader-size: 40vh;
@import '//fonts.googleapis.com/css?family=Bangers';
@headline: 40vh;

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

body {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: blue;
}

.loader {
  color: #fff;

  font-family: Bangers, Menlo, Monaco, monospace;
  font-weight: bold;
  font-size: @loader-size;
  letter-spacing: 0.6rem;
  opacity: 0.9;
}

.headline {
  font-family: Bangers, Menlo, Monaco, monospace;
  color: #fff;
  font-size: 20vh;
}

<body>
<div class="headline">
  <p> How much remains to meet the goal? </p>
 </div>
  <p class="loader" id="demo"></p>
</body>


问:
Converting Complex c function to fortran
I am converting some c functions to fortran. In my c routine , there are two structures definitions like below

```<code>typedef struct heapnode {
              double c;
              int n;
                    } heapnode;

typedef struct heap {
                int n;
                int sz;
                heapnode *d;
                    } heap;
</code>```

I converted above two type definitions to fortran as follows and it works well.

```<code>type heapnode

    real*8 :: c
    integer*4 :: n

   endtype heapnode

  type heap

    integer*4 :: n
    integer*4 :: sz
    type(heapnode), pointer :: d

  endtype heap
</code>```

My question is about initiating of above two structures.  The requirement here is we should have one heap type variable and with-in that heap  type variable we should have multiple heap nodes.

To demonstrate this I show below c code to print heap elements

```<code>int i;

   FILE *f = stdout;
   fprintf(f, "Printing heap\n");

   for (i=0; i<h->n; i++) {
     fprintf(f, "[%4d]: n = %5d, c = %17.12lg\n", i, h->d[i].n, h->d[i].c);
   }
</code>```

In above code h is heap type variable
h->n is number of heap nodes in heap variable h

Here we can see accessing heap node variables as    h->d[i]

I show  c code to create this heap variable and nodes below

```<code> void *vspace, *oldvspace;

   heap *h  /* heap */
   heapnode *d; /* heap node */

   h->n = 0;
   h->sz = 8;

   oldvspace = (void *) h;
   vspace = (void *)(h + 1); / * address of next node */

   d = (heapnode *)vspace; / *point heapnode to above address */
   h->d = d;  /  *assign heapnode to new node */
</code>```

what we can see above is create a variable (this time heapnode)in a particular memory location and point a pointer variable to that.

I want to know , how we can do this using fortran. Could you please give me some hints to do this.

答: Pointer arithmetic is not available in standard Fortran. However there is a non-standard extension in come compilers called a 'Cray pointer' which will allow for limited pointer arithmetic. Note that Cray pointer arithmetic is not the same as C-style pointer arithmetic - incrementing a pointer to a derived type using a Cray pointer will not produce a pointer value equal to the original memory location plus the number of bytes needed to store the derived type. So statements like vspace = (void *)(h + 1); cannot be emulated exactly. If you wish your code to be portable then I don't recommend the Cray pointer.

Body:
I am converting some c functions to fortran. In my c routine , there are two structures definitions like below

typedef struct heapnode {
              double c;
              int n;
                    } heapnode;

typedef struct heap {
                int n;
                int sz;
                heapnode *d;
                    } heap;

I converted above two type definitions to fortran as follows and it works well.

type heapnode

    real*8 :: c
    integer*4 :: n

   endtype heapnode

  type heap

    integer*4 :: n
    integer*4 :: sz
    type(heapnode), pointer :: d

  endtype heap

My question is about initiating of above two structures.  The requirement here is we should have one heap type variable and with-in that heap  type variable we should have multiple heap nodes.

To demonstrate this I show below c code to print heap elements

int i;

   FILE *f = stdout;
   fprintf(f, "Printing heap\n");

   for (i=0; i<h->n; i++) {
     fprintf(f, "[%4d]: n = %5d, c = %17.12lg\n", i, h->d[i].n, h->d[i].c);
   }

In above code h is heap type variable
h->n is number of heap nodes in heap variable h

Here we can see accessing heap node variables as    h->d[i]

I show  c code to create this heap variable and nodes below

 void *vspace, *oldvspace;

   heap *h  /* heap */
   heapnode *d; /* heap node */

   h->n = 0;
   h->sz = 8;

   oldvspace = (void *) h;
   vspace = (void *)(h + 1); / * address of next node */

   d = (heapnode *)vspace; / *point heapnode to above address */
   h->d = d;  /  *assign heapnode to new node */

what we can see above is create a variable (this time heapnode)in a particular memory location and point a pointer variable to that.

I want to know , how we can do this using fortran. Could you please give me some hints to do this.


问:
How to merge/pick/update specific parts from different repositories

The scenario

My main project has the following text (code actually):

```<code>Lorem ipsum dolor sit amet, consectetur adipiscing elit. (...) Cras ullamcorper in lorem nec finibus.

Suspendisse . (...) Vestibulum ex nunc, facilisis pulvinar lorem eu, convallis volutpat tortor.

In hac habitasse platea dictumst. (...) Cras quis ex accumsan, aliquet odio pulvinar, pellentesque ante.
</code>```

My friend has a side project (also in a different repository):

```<code>Fusce iaculis vulputate rhoncus. (...) Duis ac gravida nisl.

Suspendisse potenti. (...) Vestibulum ex nunc, facilisis pulvinar lorem eu, convallis volutpat tortor.

Nulla a nibh egestas, condimentum erat vitae, auctor est. (...) Sed aliquet mi eget nunc ullamcorper egestas.
</code>```

Objective

I want to pick only the second line (portion of the code) to merge into my main branch because it has a fixed content. All the other content should be ignored.

I've already added his repository:

```<code>git remote add side-project /foo/path
git pull side-project master:john-project
</code>```

I have no idea of what to use, if it is either merge, or cherry-pick.

The real life

My project can make use of a specific function from a different repository. Whenever the other repository is updated, I would pull the function with updated/patches.

答:
You can't cherry-pick lines of code to merge with git. Besides the second line, one of you should generally have the right lines that you want e.g. the 'master' branch or main repository.

In this situation, I think it's best if your friend pulls your code (since it seems like the main repository) and then merges it with his code. Fix any merge conflicts, etc, so that it looks like this in his repository:

```<code>Lorem ipsum dolor sit amet, consectetur adipiscing elit. (...) Cras ullamcorper in lorem nec finibus.

Suspendisse potenti. (...) Vestibulum ex nunc, facilisis pulvinar lorem eu, convallis volutpat tortor.

In hac habitasse platea dictumst. (...) Cras quis ex accumsan, aliquet odio pulvinar, pellentesque ante.
</code>```

(1st and 3rd lines are from your repo, 2nd is from his)

Then, he can submit a pull request to your main project and it will have the fixed code, where only the second line is changed.

Body:
The scenario

My main project has the following text (code actually):

Lorem ipsum dolor sit amet, consectetur adipiscing elit. (...) Cras ullamcorper in lorem nec finibus.

Suspendisse . (...) Vestibulum ex nunc, facilisis pulvinar lorem eu, convallis volutpat tortor.

In hac habitasse platea dictumst. (...) Cras quis ex accumsan, aliquet odio pulvinar, pellentesque ante.

My friend has a side project (also in a different repository):

Fusce iaculis vulputate rhoncus. (...) Duis ac gravida nisl.

Suspendisse potenti. (...) Vestibulum ex nunc, facilisis pulvinar lorem eu, convallis volutpat tortor.

Nulla a nibh egestas, condimentum erat vitae, auctor est. (...) Sed aliquet mi eget nunc ullamcorper egestas.

Objective

I want to pick only the second line (portion of the code) to merge into my main branch because it has a fixed content. All the other content should be ignored.

I've already added his repository:

git remote add side-project /foo/path
git pull side-project master:john-project

I have no idea of what to use, if it is either merge, or cherry-pick.

The real life

My project can make use of a specific function from a different repository. Whenever the other repository is updated, I would pull the function with updated/patches.

Body:
You can't cherry-pick lines of code to merge with git. Besides the second line, one of you should generally have the right lines that you want e.g. the 'master' branch or main repository.

In this situation, I think it's best if your friend pulls your code (since it seems like the main repository) and then merges it with his code. Fix any merge conflicts, etc, so that it looks like this in his repository:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. (...) Cras ullamcorper in lorem nec finibus.

Suspendisse potenti. (...) Vestibulum ex nunc, facilisis pulvinar lorem eu, convallis volutpat tortor.

In hac habitasse platea dictumst. (...) Cras quis ex accumsan, aliquet odio pulvinar, pellentesque ante.

(1st and 3rd lines are from your repo, 2nd is from his)

Then, he can submit a pull request to your main project and it will have the fixed code, where only the second line is changed.


问:
Deshuffle text with C
I wanted to get an opinion here. Would it be possible to write a C program that deshuffles a text file? What do I mean by that? Say I have the following data in a textfile:

```<code>1  X
4  T
3  Z
2  L
</code>```

And I wanted to deshuffle it and output another file as so:

```<code>1  X
2  L
3  Z
4  T
</code>```

Such that all of the data following the number is preserved with the actual index number. Do know that I have 40,500 shuffled entities, so that should probably be taken into account since that could take a long time if the program needs to loop through all of the entities for each entity...And I only used letters for representation. The actual data files don't have letters, but rather have floats. Sorry if this causes any confusion

So, bottom line, would this be possible with C? And if so, could I get a hint at where to start? I could obviously input all of the textfile data into an array dat[][], but how should I deshuffle it then?

Thanks!
Amit

答: Look up qsort, its part of stdlib.</p>

Title: Deshuffle text with C

Body:
I wanted to get an opinion here. Would it be possible to write a C program that deshuffles a text file? What do I mean by that? Say I have the following data in a textfile:

1  X
4  T
3  Z
2  L

And I wanted to deshuffle it and output another file as so:

1  X
2  L
3  Z
4  T

Such that all of the data following the number is preserved with the actual index number. Do know that I have 40,500 shuffled entities, so that should probably be taken into account since that could take a long time if the program needs to loop through all of the entities for each entity...And I only used letters for representation. The actual data files don't have letters, but rather have floats. Sorry if this causes any confusion

So, bottom line, would this be possible with C? And if so, could I get a hint at where to start? I could obviously input all of the textfile data into an array dat[][], but how should I deshuffle it then?

Thanks!
Amit

Body: Look up qsort, its part of stdlib.


问:
javascript (boolean ^ boolean)
I'm working on rewriting some Javascript-code to work in Excel VBA.
I've manage to translate almost all of the Javascript-code thanks to searching on this website! However, there is some code I can't understand what it's doing precisely.
This is the bit of Javascript-code:

```<code>var k = x % y;
return (k != 0 && (k > 0 ^ y > 0) && isFinite(y)) ? k + y : k;
</code>```

The first line is clear to me. k is the remainder of x/y.
In the second line, modulo gets the value of either k+y or k. This is decided by (k!=0 && (k > 0 ^ y > 0) && isFinite(y))

Could somebody explain to me step by step how I should be reading this code? Especially the &&(k>0^y>0)&& is puzzling me.

This is how far I seem to be getting till now:

Example 1: x=9 and y=4

```<code>k = 9%4 = 9/4=2 with remainder 1    So: k=1
(1!=0&&(1>0^4>0)&&isFinite(4))   (True AND (True^True) AND True)  =  True?
</code>```

Example 1: x=9 and y=1

```<code>k = 9%1 = 9/1=9 with remainder 0    So: k=0
(0!=0&&(0>0^1>0)&&isFinite(1))  (False AND (False^True) AND True)  =  False?
</code>```

If I would think purely mathematically, then I would guess that the part (False^True) should be read like (0^1) = 0 = False.

答:
Step by step explanation of the critical part as evaluated by the language:

(k != 0 && (k > 0 ^ y > 0) && isFinite(y)) ? k + y : k;

(k != 0 && (k > 0 ^ y > 0): true if and only if 1. and 2. below is true

k != 0: true if k is not in 0, '0', 0.0, '0.0'

(k > 0 ^ y > 0): true if and only if one of 1. and 2. is true

k > 0: true if and only if k is a Number or numeric String above 0

y > 0: true if and only if y is a Number or numeric String above 0

isFinite(y)): true if y is not one of undefined, Object, Array, Infinity, -Infinity, ... (further native objects) or a non-numeric String

(k != 0 && (k > 0 ^ y > 0) && isFinite(y)): true if and only if both parts above were true. The ternary ? operator will return the 1st post-expression k + y if the pre-expression is true and the 2nd post-expression k otherwise.

In more general terms the take-away lessons are:

comparisons in JS are complex: String is often cast to Number and different functions have different behavior on native objects (isFinite(null) === true but isFinite(undefined) === false). Therefore generally always prefer using === and !==.

JS uses short-circuiting on boolean operators

^ is the exclusive OR aka XOR operator

? is the ternary if operator which equals if ... do ... else do ...

Title: javascript (boolean ^ boolean)

Body:
I'm working on rewriting some Javascript-code to work in Excel VBA.
I've manage to translate almost all of the Javascript-code thanks to searching on this website! However, there is some code I can't understand what it's doing precisely.
This is the bit of Javascript-code:

var k = x % y;
return (k != 0 && (k > 0 ^ y > 0) && isFinite(y)) ? k + y : k;

The first line is clear to me. k is the remainder of x/y.
In the second line, modulo gets the value of either k+y or k. This is decided by (k!=0 && (k > 0 ^ y > 0) && isFinite(y))

Could somebody explain to me step by step how I should be reading this code? Especially the &&(k>0^y>0)&& is puzzling me.

This is how far I seem to be getting till now:

Example 1: x=9 and y=4

k = 9%4 = 9/4=2 with remainder 1    So: k=1
(1!=0&&(1>0^4>0)&&isFinite(4))   (True AND (True^True) AND True)  =  True?

Example 1: x=9 and y=1

k = 9%1 = 9/1=9 with remainder 0    So: k=0
(0!=0&&(0>0^1>0)&&isFinite(1))  (False AND (False^True) AND True)  =  False?

If I would think purely mathematically, then I would guess that the part (False^True) should be read like (0^1) = 0 = False.


问:
Objective-C: naming practice for blocks used as sub-functions
I want to determine the best current naming practice for a blocks use as a sub-functions.

Unfortunately I'm dealing with some code where blocks are being put inside of methods because objective-c does not have sub-functions.

Is there currently a naming practice for these?

```<code> - (void) foo {
    int k=100;

    int (^badIdeaFunc)(int) = ^(int a) { return a+k; };

    NSLog(@"%d", badIdeaFunc (5));

 }
</code>```

答: No, there is no standard convention.</p>

Body:
I want to determine the best current naming practice for a blocks use as a sub-functions.

Unfortunately I'm dealing with some code where blocks are being put inside of methods because objective-c does not have sub-functions.

Is there currently a naming practice for these?

 - (void) foo {
    int k=100;

    int (^badIdeaFunc)(int) = ^(int a) { return a+k; };

    NSLog(@"%d", badIdeaFunc (5));

 }

Body: No, there is no standard convention.


问:
Custom select with css not working in Firefox
I wish to change the button (arrow down) in the right corner of the select box. My html is like this:

```<code><div class="buscaSelect">
    <select name="oper">
        <option value="value1">Value 1</option>
        <option value="value2">Value 2</option>
    </select>
</div>
</code>```

Than the CSS:

```<code>.buscaSelect {
    display: inline-block;
    margin: 18px 0px 0px 0px;
    width: 120px;
    height: 27px;
    border-radius: 0px;
    overflow: hidden;
    background: white url("btnSelect.png") no-repeat right center;
}

.buscaSelect select {
    padding: 4px;
    width: 100%;
    border: none;
    box-shadow: none;
    background: transparent;
    background-image: none;
    -webkit-appearance: none;
}
</code>```

In Safari, the result is perfect, the default button is changed by "btnSelect.png", but in Firefox (58.0b9), the default button is still there, overlapping my button. As the default button got smaller width, the corner of my button is appearing behind... the result is terrible!

How can I deactivate the Firefox default button and show only mine?

答:
I think you're looking for this, hope it helps. I have given the comparison of both with dropdown and without dropdown arrow side by side.The webkit-appearance:none works well with firefox and chrome but for IE you might need to use this:

```<code>select::-ms-expand {
    display: none;
}
</code>```

.buscaSelect {
    display: inline-block;
    margin: 18px 0px 0px 0px;
    width: 120px;
    height: 27px;
    border-radius: 0px;
    overflow: hidden;
    background: white url("btnSelect.png") no-repeat right center;
}

.buscaSelect select {
    padding: 4px;
    width: 100%;
    border: none;
    box-shadow: none;
    background: transparent;
    background-image: none;
    -webkit-appearance: none;
}

#noarrow {
    -webkit-appearance: none;
    -moz-appearance: none;
    text-indent: 1px;
    text-overflow: '';
}
select::-ms-expand {
    display: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="buscaSelect">
    <select name="oper" id="noarrow">
        <option value="value1">Value 1</option>
        <option value="value2">Value 2</option>
    </select>
</div>
<div class="buscaSelect">
    <select name="oper">
        <option value="value1">Value 1</option>
        <option value="value2">Value 2</option>
    </select>
</div></code>```

Body:
I wish to change the button (arrow down) in the right corner of the select box. My html is like this:

    <select name="oper">
        <option value="value1">Value 1</option>
        <option value="value2">Value 2</option>
    </select>

Than the CSS:

.buscaSelect {
    display: inline-block;
    margin: 18px 0px 0px 0px;
    width: 120px;
    height: 27px;
    border-radius: 0px;
    overflow: hidden;
    background: white url("btnSelect.png") no-repeat right center;
}

.buscaSelect select {
    padding: 4px;
    width: 100%;
    border: none;
    box-shadow: none;
    background: transparent;
    background-image: none;
    -webkit-appearance: none;
}

In Safari, the result is perfect, the default button is changed by "btnSelect.png", but in Firefox (58.0b9), the default button is still there, overlapping my button. As the default button got smaller width, the corner of my button is appearing behind... the result is terrible!

How can I deactivate the Firefox default button and show only mine?

Body:
I think you're looking for this, hope it helps. I have given the comparison of both with dropdown and without dropdown arrow side by side.The webkit-appearance:none works well with firefox and chrome but for IE you might need to use this:

select::-ms-expand {
    display: none;
}

.buscaSelect {
    display: inline-block;
    margin: 18px 0px 0px 0px;
    width: 120px;
    height: 27px;
    border-radius: 0px;
    overflow: hidden;
    background: white url("btnSelect.png") no-repeat right center;
}

.buscaSelect select {
    padding: 4px;
    width: 100%;
    border: none;
    box-shadow: none;
    background: transparent;
    background-image: none;
    -webkit-appearance: none;
}

#noarrow {
    -webkit-appearance: none;
    -moz-appearance: none;
    text-indent: 1px;
    text-overflow: '';
}
select::-ms-expand {
    display: none;
}

<div class="buscaSelect">
    <select name="oper" id="noarrow">
        <option value="value1">Value 1</option>
        <option value="value2">Value 2</option>
    </select>
</div>
<div class="buscaSelect">
    <select name="oper">
        <option value="value1">Value 1</option>
        <option value="value2">Value 2</option>
    </select>
</div>


问:
Bootstrap Togglable tabs only working one time?
I have been using rails for create the site.
So I use Bootstrap Togglable tabs in the part of my homepage.

The problem is every navigation tabs buttons seem working only one time.
For example, when i click the second tab navigation then the second tab appear correctly, so after that i click the third tab navigation, then the third section seem fine.

But when i click the second tab navigation again nothing happened it still be on the third tab content. Same situation when i move from third tab to the forth one.

This is some of my code.

```<code><div id="tabs-menu-box" class="insurance-tab-menu-box">
  <div class="row">
    <div class="services">
      <!-- one service -->
      <div class="one-service color1">
        <ul>
          <li>
            <a href="#carInsurance"
               aria-controls="carInsurance"
               role="tab">
              <h3>ประกันภัยรถยนต์</h3>
            </a>
          </li>
        </ul>
      </div>
      <!-- one service end -->
      <!-- one service -->
      <div class="one-service color2">
        <ul>
          <li>
            <a href="#prbInsurance"
               aria-controls="prbInsurance"
               role="tab">
              <h3>พรบ.</h3>
            </a>
          </li>
        </ul>
      </div>
      <!-- one service end -->
      <!-- one service -->
      <div class="one-service color3">
        <ul>
          <li>
            <a href="#fireInsurance"
               aria-controls="fireInsurance"
               role="tab">
              <h3>ประกันอัคคีภัย</h3>
            </a>
          </li>
        </ul>
      </div>
      <!-- one service end -->
      <!-- one service -->
      <div class="one-service color4">
        <ul>
          <li>
            <a href="#acidentInsurance"
               aria-controls="acidentInsurance"
               role="tab">
              <h3>ประกันอุบัติเหตุ (PA)</h3>
            </a>
          </li>
        </ul>
      </div>
      <!-- one service end -->
      <!-- one service -->
      <div class="one-service color6">
        <ul>
          <li>
            <a href="#generalInsurance"
               aria-controls="generalInsurance"
               role="tab">
              <!--<img src="images/icon-health.png" alt="">-->
              <h3>ประกันภัยอื่นๆ</h3>
            </a>
          </li>
        </ul>
      </div>
      <!-- one service end -->
    </div>
  </div>
</div>

<div class="insurance-tab-content-box">
  <div class="container small-container">
    <!-- Tab panes -->
    <div class="tab-content">
        <div role="tabpanel" class="tab-pane active" id="carInsurance">
            content
        </div>
        <div role="tabpanel" class="tab-pane" id="prbInsurance">
            content
        </div>
        <div role="tabpanel" class="tab-pane" id="fireInsurance">
            content
        </div>
        <div role="tabpanel" class="tab-pane" id="acidentInsurance">
            content
        </div>
        <div role="tabpanel" class="tab-pane" id="generalInsurance">
            content
        </div>
    </div>
  </div>
</div>
</code>```

My js

```<code>$('#tabs-menu-box a').click(function (e) {
    e.preventDefault();
    $(this).tab('show');
});
</code>```

Anyone know how to fix this?

Thanks!

答:
Since bootstrap 4 as a whole is rewritten to avoid issues/clashes with other javascript libraries.

Even I had the same issue but solved by disabling
smooth-scroll.min.js

In your case try to disable few JS files and try your luck until stable BS4 releases.

Body:
I have been using rails for create the site.
So I use Bootstrap Togglable tabs in the part of my homepage.

The problem is every navigation tabs buttons seem working only one time.
For example, when i click the second tab navigation then the second tab appear correctly, so after that i click the third tab navigation, then the third section seem fine.

But when i click the second tab navigation again nothing happened it still be on the third tab content. Same situation when i move from third tab to the forth one.

This is some of my code.

ประกันภัยรถยนต์

พรบ.

ประกันอัคคีภัย

ประกันอุบัติเหตุ (PA)

ประกันภัยอื่นๆ

            content

            content

            content

            content

            content

My js

$('#tabs-menu-box a').click(function (e) {
    e.preventDefault();
    $(this).tab('show');
});

Anyone know how to fix this?

Thanks!


问:
Add CSS Class to html element in a TagHelper
In an ASP.NET Core View I have the following:

```<code><div class="message" message=""></div>
</code>```

And I the a Tag Helper with the following TagHelper:

```<code>[HtmlTargetElement("div", Attributes = MessageName)]
public class MessageTagHelper : TagHelper {

  private const String MessageName = "message";

  [HtmlAttributeName(MessageName)]
  public String Message { get; set; }

  [HtmlAttributeNotBound, ViewContext]
  public ViewContext ViewContext { get; set; }

  public override void Process(TagHelperContext context, TagHelperOutput output) {

    String message;
    Boolean defined = ViewContext.HttpContext.Request.Cookies.TryGetValue("_message", out message);

    if (defined) {
      ViewContext.HttpContext.Response.Cookies.Delete("_message");
      output.Attributes.Add("class", "active");
      output.Content.Append(message);
    }
  }
}
</code>```

On the following code line I need to add "active" as CSS Class.

```<code>output.Attributes.Add("class", "active");
</code>```

However, this does nothing. Message remains only with class "message".

What am I missing?

答:
@Shyju's answer is mostly correct, but there's a lot of extraneous code that's unnecessary. The following is enough to handle it in ASP.NET Core 2.0:</p>

```<code>var classes = output.Attributes.FirstOrDefault(a => a.Name == "class")?.Value;
output.Attributes.SetAttribute("class", $"active {classes}");
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In an ASP.NET Core View I have the following:

And I the a Tag Helper with the following TagHelper:

[HtmlTargetElement("div", Attributes = MessageName)]
public class MessageTagHelper : TagHelper {

  private const String MessageName = "message";

  [HtmlAttributeName(MessageName)]
  public String Message { get; set; }

  [HtmlAttributeNotBound, ViewContext]
  public ViewContext ViewContext { get; set; }

  public override void Process(TagHelperContext context, TagHelperOutput output) {

    String message;
    Boolean defined = ViewContext.HttpContext.Request.Cookies.TryGetValue("_message", out message);

    if (defined) {
      ViewContext.HttpContext.Response.Cookies.Delete("_message");
      output.Attributes.Add("class", "active");
      output.Content.Append(message);
    }
  }
}

On the following code line I need to add "active" as CSS Class.

output.Attributes.Add("class", "active");

However, this does nothing. Message remains only with class "message".

What am I missing?

Body:
@Shyju's answer is mostly correct, but there's a lot of extraneous code that's unnecessary. The following is enough to handle it in ASP.NET Core 2.0:

var classes = output.Attributes.FirstOrDefault(a => a.Name == "class")?.Value;
output.Attributes.SetAttribute("class", $"active {classes}");


问:
UICollectionView - How to display Items with different heights in the same section?
I'm having trouble while displaying more items (with different values of height but with the same width) in the same section of a UICollectionView. The problem is the one shown below (the first image is what I'm trying to get, the second is what I actually have):

UICollectionView

I've already implemented those 2 methods for the line spacing that I don't want:

```<code>func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 0
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
    return 0
}
</code>```

But I really don't know which other method I need to implement in order to achieve what I need. Any suggestion? Thanks!

答:
you can use below way
first implement UICollectionViewDelegateFlowLayout protocol in your class then override

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {}
function in your class and return your size for cell for any cell you want

Body:
I'm having trouble while displaying more items (with different values of height but with the same width) in the same section of a UICollectionView. The problem is the one shown below (the first image is what I'm trying to get, the second is what I actually have):

UICollectionView

I've already implemented those 2 methods for the line spacing that I don't want:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 0
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
    return 0
}

But I really don't know which other method I need to implement in order to achieve what I need. Any suggestion? Thanks!


问:
How to select all text and change spelling language?
I need to select the entire text in the email I'm typing, and change the spelling language.

The following works in Word but doesn't in Outlook 2013.

I added Microsoft Word 15 Object library, with tools -> references, from the VBA editor window.

Selection.WholeStory
Selection.LanguageID = wdEnglishUK
Selection.NoProofing = False
Application.CheckLanguage = False
```

答:
Methods and properties specific to one application's VBA language can't be used in other applications like that.

There is a lot of information out there, try a search for "Outlook VBA Change Message Body Language" and variations of that.

Some resources to get you started:

Stack Overflow: Outlook VBA Set language of selection

MSDN: Working with Item Bodies with Outlook/VBA

MSDN: MailItem Object (Outlook)

Stack Overflow: Display email body of selected email in Outlook as a message box in Excel

MSDN: Introduction to Outlook VBA


问:
Valgrind finds a leak in my code, could anybody help me find it?
I have the following code for a function.
It reads a file, line per line, without knowing the size in advance.

It is a learning exercise in my school. I have run the valgrind command on it and I have this output (the full log is here => valgrind log):

```<code>==21166== 44 bytes in 1 blocks are definitely lost in loss record 14   of 42
==21166==    at 0x1000CB606: malloc (in /Users/cbaillat/.brew/Cellar/valgrind/3.13.0/lib/valgrind/vgpreload_memcheck-amd64-darwin.so)
==21166==    by 0x100000F0C: ft_strnew (in ./get_next_line)
==21166==    by 0x10000061C: get_next_line (get_next_line.c:71)
==21166==    by 0x10000058A: main (main.c:31)
</code>```

I don't know where that could come from. Here is the function that provokes the leak:

```<code>#include "get_next_line.h"

/*
** If newline is null, it means it hasn't found a new line in the string.
** It means we have reach the end of line.
*/

static int  ft_copy_leftover(char **line, char fd_buffer[BUFF_SIZE], char *nl)
{
    if (nl == NULL)
        return (1);
    ft_strcpy(fd_buffer, &nl[1]);
    (*line)[nl - (*line)] = '\0';
    return (1);
}

/*
** 1- We keep reading unless we find a new line or we reach the end of file
** 2- We reallocate the old pointer with buffer size
** 3- As long as there are characters to read and we haven't encountered a
**  new line, we keep copying the data into line
**  We store the buffer in line, and then erase it
** 4- If we have already reached the end of file, we do not need to copy the
**  buffer. Otherwise we copy it to line.
*/

static int  read_line(const int fd, char fd_buffer[BUFF_SIZE], char **line)
{
    int32_t     status;
    char        *newline;
    uint32_t    len;

    while (((newline = ft_strchr(*line, '\n')) == NULL)
        && ((status = read(fd, fd_buffer, BUFF_SIZE)) > FILE_READ))
    {
        len = ft_strlen(*line) + 1;
        if ((*line = ft_realloc(*line, len, len + BUFF_SIZE)) == NULL)
            return (ERROR);
        ft_strcat(*line, fd_buffer);
        ft_bzero(fd_buffer, BUFF_SIZE);
    }
    if ((**line != '\0') && (status >= FILE_READ))
        return (ft_copy_leftover(line, fd_buffer, newline));
    return (status);
}

/*
** 1- If the buffer is not empty, we allocate a new string and copy the buffer
**  contents
** 2- We loop in the buffer in case we have multiple new lines inside
*/

int         get_next_line(const int fd, char **line)
{
    static char fd_array[ULIMIT_N][BUFF_SIZE + 1];
    int8_t      status;

    if (fd < 0 || fd > ULIMIT_N || line == NULL
        || !(*line = ft_strnew(BUFF_SIZE + 1)))
        return (ERROR);
    if (fd_array[fd][0] != '\0')
        *line = ft_strcpy(*line, fd_array[fd]);
    ft_bzero(fd_array[fd], BUFF_SIZE + 1);
    status = read_line(fd, fd_array[fd], line);
    return (status);
}
</code>```

The function 'ft_strnew' just mallocs memory for a string and memsets it to 0:

```<code>#include "libft.h"

char    *ft_strnew(size_t size)
{
    char    *str;

    if ((str = (char *)malloc(sizeof(*str) * (size + 1))) == NULL)
        return (NULL);
    ft_memset((void *)str, (int)'\0', (size + 1));
    return (str);
}
</code>```

Could anybody help me find it?
By the way, this is how I call my function in the main:

```<code>int main(int ac, char **av)
{
    int32_t i;
    int32_t fd;
    int32_t status;
    char    *line_read;

    if (ac <= 1)
        return (0);
    fd = open(av[1], O_RDONLY);
    i = 0;
    line_read = NULL;
    while (1)
    {
        status = get_next_line(fd, &line_read);
        // printf("status: %d\n", status);
        if (status == ERROR)
            return (ERROR);
        if (status == FILE_READ)
            return (SUCCESS);
        ft_putstr(line_read);
        free (line_read);
    }
    return (SUCCESS);
}
</code>```

I free the malloc line (ft_strnew) everytime I call the function, so I am at a loss. If you need more information to help, I'd be glap to provide it. It is my first question on stack, I hope it is clear enough.

Thanks to all of you!

EDIT:

I simply forgot to free the line in the while loop of my main, when returning some values. Adding a couple of free solved my problem! Thanks to all of you!

```<code>while (1)
    {
        status = get_next_line(fd, &line_read);
        // printf("status: %d\n", status);
        if (status == ERROR)
        {
            free (line_read);
            return (ERROR);
        }
        if (status == FILE_READ)
        {
            free (line_read);
            return (SUCCESS);
        }
        ft_putstr(line_read);
        free (line_read);
    }
</code>```

答:
In your ft_strnew function you malloc a new string but you never free it.
I would suggest that you free line before returning status in your get_next_line function!</p>

Body:
I have the following code for a function.
It reads a file, line per line, without knowing the size in advance.

It is a learning exercise in my school. I have run the valgrind command on it and I have this output (the full log is here => valgrind log):

==21166== 44 bytes in 1 blocks are definitely lost in loss record 14   of 42
==21166==    at 0x1000CB606: malloc (in /Users/cbaillat/.brew/Cellar/valgrind/3.13.0/lib/valgrind/vgpreload_memcheck-amd64-darwin.so)
==21166==    by 0x100000F0C: ft_strnew (in ./get_next_line)
==21166==    by 0x10000061C: get_next_line (get_next_line.c:71)
==21166==    by 0x10000058A: main (main.c:31)

I don't know where that could come from. Here is the function that provokes the leak:

#include "get_next_line.h"

/*
** If newline is null, it means it hasn't found a new line in the string.
** It means we have reach the end of line.
*/

static int  ft_copy_leftover(char **line, char fd_buffer[BUFF_SIZE], char *nl)
{
    if (nl == NULL)
        return (1);
    ft_strcpy(fd_buffer, &nl[1]);
    (*line)[nl - (*line)] = '\0';
    return (1);
}

/*
** 1- We keep reading unless we find a new line or we reach the end of file
** 2- We reallocate the old pointer with buffer size
** 3- As long as there are characters to read and we haven't encountered a
**  new line, we keep copying the data into line
**  We store the buffer in line, and then erase it
** 4- If we have already reached the end of file, we do not need to copy the
**  buffer. Otherwise we copy it to line.
*/

static int  read_line(const int fd, char fd_buffer[BUFF_SIZE], char **line)
{
    int32_t     status;
    char        *newline;
    uint32_t    len;

    while (((newline = ft_strchr(*line, '\n')) == NULL)
        && ((status = read(fd, fd_buffer, BUFF_SIZE)) > FILE_READ))
    {
        len = ft_strlen(*line) + 1;
        if ((*line = ft_realloc(*line, len, len + BUFF_SIZE)) == NULL)
            return (ERROR);
        ft_strcat(*line, fd_buffer);
        ft_bzero(fd_buffer, BUFF_SIZE);
    }
    if ((**line != '\0') && (status >= FILE_READ))
        return (ft_copy_leftover(line, fd_buffer, newline));
    return (status);
}

/*
** 1- If the buffer is not empty, we allocate a new string and copy the buffer
**  contents
** 2- We loop in the buffer in case we have multiple new lines inside
*/

int         get_next_line(const int fd, char **line)
{
    static char fd_array[ULIMIT_N][BUFF_SIZE + 1];
    int8_t      status;

    if (fd < 0 || fd > ULIMIT_N || line == NULL
        || !(*line = ft_strnew(BUFF_SIZE + 1)))
        return (ERROR);
    if (fd_array[fd][0] != '\0')
        *line = ft_strcpy(*line, fd_array[fd]);
    ft_bzero(fd_array[fd], BUFF_SIZE + 1);
    status = read_line(fd, fd_array[fd], line);
    return (status);
}

The function 'ft_strnew' just mallocs memory for a string and memsets it to 0:

#include "libft.h"

char    *ft_strnew(size_t size)
{
    char    *str;

    if ((str = (char *)malloc(sizeof(*str) * (size + 1))) == NULL)
        return (NULL);
    ft_memset((void *)str, (int)'\0', (size + 1));
    return (str);
}

Could anybody help me find it?
By the way, this is how I call my function in the main:

int main(int ac, char **av)
{
    int32_t i;
    int32_t fd;
    int32_t status;
    char    *line_read;

    if (ac <= 1)
        return (0);
    fd = open(av[1], O_RDONLY);
    i = 0;
    line_read = NULL;
    while (1)
    {
        status = get_next_line(fd, &line_read);
        // printf("status: %d\n", status);
        if (status == ERROR)
            return (ERROR);
        if (status == FILE_READ)
            return (SUCCESS);
        ft_putstr(line_read);
        free (line_read);
    }
    return (SUCCESS);
}

I free the malloc line (ft_strnew) everytime I call the function, so I am at a loss. If you need more information to help, I'd be glap to provide it. It is my first question on stack, I hope it is clear enough.

Thanks to all of you!

EDIT:

I simply forgot to free the line in the while loop of my main, when returning some values. Adding a couple of free solved my problem! Thanks to all of you!

while (1)
    {
        status = get_next_line(fd, &line_read);
        // printf("status: %d\n", status);
        if (status == ERROR)
        {
            free (line_read);
            return (ERROR);
        }
        if (status == FILE_READ)
        {
            free (line_read);
            return (SUCCESS);
        }
        ft_putstr(line_read);
        free (line_read);
    }


问:
Trigger ItemSend when item is being sent from outbox using addon
I'm writing an outlook addon that triggers when the Send button is sent on an email, if certain conditions are met a pop up comes up asking if the user is sure they want to send the email.

This works perfectly. However, A lot of emails that get sent are passed into outlook through another program and go into the drafts folder and are slowly sent out. Is there an Event handler for when an email is sent that doesn't rely on the send button being clicked?

EDIT:

I've found that the Send() method can be called to send an email - would it be possible to check if this method is called and when it is to run my code?

答: If the external app is using the Outlook Object Model to send the messages, Application.ItemSend event will still fire. Otherwise the best you can of is use Items.ItemAdd event on the Sent Items folder - it will trigger after a message is actually sent and moved to the Sent Items folder.


问:
how to show closest div on hover?
i want to hover over a child element for it to show the NEAREST footer div on tumblr.

```<code><div class="entry">
{block:Posts}
<div class="container">
{block:Text}{/block:Text}
{block:Photo}{/block:Photo}
{block:Text}{/block:Text}
</div>
<div class="footer"></div>
{/block:Posts}
</div>
</code>```

the footer class is to be hidden but i want it so that when i hover over any one of the post type, only the footer of that post shows.

example :

i hover over my text post about something, it'll show the footer of THAT post specifically!

any help would be appreciated!

edit : i think my circumstances weren't properly explained so i updated!

答:
Use jquery next() function and mouseneter, mouseleave to simulate hover effect:

CSS:

```<code>.one {}
.two {display:none;}
</code>```

javascript:

```<code>jQuery('.one').on('mouseenter', function(){
    $(this).next('.two').css('display', 'block');
});

jQuery('.one').on('mouseleave', function(){
    $(this).next('.two').css('display', 'none');
});
</code>```

jsfiddle

Title: how to show closest div on hover?

Body:
i want to hover over a child element for it to show the NEAREST footer div on tumblr.

{block:Posts}

{block:Text}{/block:Text}
{block:Photo}{/block:Photo}
{block:Text}{/block:Text}

{/block:Posts}

the footer class is to be hidden but i want it so that when i hover over any one of the post type, only the footer of that post shows.

example :

i hover over my text post about something, it'll show the footer of THAT post specifically!

any help would be appreciated!

edit : i think my circumstances weren't properly explained so i updated!

Body:
Use jquery next() function and mouseneter, mouseleave to simulate hover effect:

CSS:

.one {}
.two {display:none;}

javascript:

jQuery('.one').on('mouseenter', function(){
    $(this).next('.two').css('display', 'block');
});

jQuery('.one').on('mouseleave', function(){
    $(this).next('.two').css('display', 'none');
});

jsfiddle


问:
How to display wrapping flex items as space-between with last row aligned left?
I have a fixed-width container into which several variable-width elements must appear in a row, which can spill over into additional rows as necessary.

However, the beginning of each element must be aligned with the one on top of it, so in ASCII art it would look like so (say, padding of 1):

```<code>    /----------------------------------\
    |                                  |
    | # One    # Two   # Three  # Four |
    | # Five   # Six                   |
    |                                  |
    \----------------------------------/
</code>```

In other words:

The first element of every row must be left-aligned

The last element of every row (except for the final row) must be right-aligned

Every element must be left-aligned to the element above it

I'm trying to use flexbox for this without success.

This is the best I've come so far, using flex-wrap: wrap for the container and flex-grow: 1 for the elements.

Problem is that the last row fills out to the edge.

```<code>justify-content: flex-start; // this does nothing
</code>```

If I take away flow-grow: 1 then the elements aren't distributed equally. I also tried fiddling around with last-of-type on the elements but it's also not enough.

Is this even possible with flexbox, or am I going about it the wrong way?

答:
You could try it with a fixed-with-pseudo-element:</p>

```<code>.container {
 display:flex;
 justify-content:space-between;
}
.container:after {
  content: '';
  flex-grow: 0;
  width: 25%;
}
.container .element {
  width: 25%;
}
</code>```

Body:
I have a fixed-width container into which several variable-width elements must appear in a row, which can spill over into additional rows as necessary.

However, the beginning of each element must be aligned with the one on top of it, so in ASCII art it would look like so (say, padding of 1):

    /----------------------------------\
    |                                  |
    | # One    # Two   # Three  # Four |
    | # Five   # Six                   |
    |                                  |
    \----------------------------------/

In other words:

The first element of every row must be left-aligned

The last element of every row (except for the final row) must be right-aligned

Every element must be left-aligned to the element above it

I'm trying to use flexbox for this without success.

This is the best I've come so far, using flex-wrap: wrap for the container and flex-grow: 1 for the elements.

Problem is that the last row fills out to the edge.

justify-content: flex-start; // this does nothing

If I take away flow-grow: 1 then the elements aren't distributed equally. I also tried fiddling around with last-of-type on the elements but it's also not enough.

Is this even possible with flexbox, or am I going about it the wrong way?

Body:
You could try it with a fixed-with-pseudo-element:

.container {
 display:flex;
 justify-content:space-between;
}
.container:after {
  content: '';
  flex-grow: 0;
  width: 25%;
}
.container .element {
  width: 25%;
}


问:
In RabbitMQ, how to handle the conflict between prefetch and 'redelivered'
Basically I have the similar issue as here:

http://rabbitmq.1065348.n5.nabble.com/Consumer-crash-redelivery-and-prefetch-td34103.html

I want to prefetch some messages for performance.
At the same time, if one message fails, I do want to give it a second chance (retry twice) and currently I use the 'redelivered' flag to implement this. If 'redelivered' is not set, I will re-queue the message, otherwise I will abandon the message.
This will cause a problem for those prefetched messages (not yet processed) if the consumer crashes as they have not been processed yet but the 'redelivered' flag will be set.

Is there any solution for this? Or any other better way to implement retry logic for the RabbitMQ message?
Thanks,

答:
I see a couple of issues with this logic, one of which you've identified. First, the redelivered flag is a pretty useless field- it provides an indication of state for a stateless operation (processing a message should not require any "outside" information to be supplied). In general, your message processor should not care whether a message has been delivered 1, 10, or 100 times - the processing of the message and related behavior should not depend upon the number of times it was delivered.

The other issue, and this is more subtle, is that you have several different failure modes with differing effects, and you're finding that it's not a good idea to reduce all of these down to a single redelivered boolean.

There are a couple of things you can do:

First, you should make an attempt to distinguish between failures caused by malformed messages as opposed to those caused by a temporary condition with the server.  The former will never be able to be processed (and should be rejected outright), while the latter will potentially be able to be processed after the condition resolves. Right now, how do you decide between the two? How do you decide how long is long enough to wait before trying again?

Second, if you do need to understand prior failures, you can add a header to the message and re-publish (as opposed to doing a basic.reject).  The message will go to the back of the queue, but this state information will now be part of the message and available to future processors.

If this is a request-reply scenario, then just reject the message and make the client retry the request. Obviously this is not desirable if the client has no way of knowing when/if the message was processedd.


问:
Issue in connecting mongodatabase
I am using mongoose version 4.13.6 and mongodb from compose, and below is my code for connecting to mongo database.

```<code>mongoose.createConnection('mongodb://[user]:[pass]@[host1]:[port1],[host2]:[port2]/dbnamme?ssl=true', {});
</code>```

But when I run this am getting error,

```<code>MongoError: no primary found in replicaset
</code>```

Dont know why is that, can anyone help me in this?

答:
So the short answer is this:

... all drivers are not equal and some make assumptions when multiple hosts are specified. For example, the Meteor/Node.js MongoDB driver sees two hosts and assumes it is talking to a replicaset. Upon connecting the driver asks which host is master and then errors out because neither of them are. The simple fix for this is to use one host in the URI ..

https://www.compose.com/articles/connecting-to-the-new-mongodb-at-compose/#drivingtoyourfirstdatabase

So when you create a connection, simply use one of the connection URIs for the database you want to connect to like:

```<code>var uri = "mongodb://<username>:<password>@[host]:[port]/<db_name>?ssl=true";

mongoose.createConnection(uri);
</code>```

Title: Issue in connecting mongodatabase

Body:
I am using mongoose version 4.13.6 and mongodb from compose, and below is my code for connecting to mongo database.

mongoose.createConnection('mongodb://[user]:[pass]@[host1]:[port1],[host2]:[port2]/dbnamme?ssl=true', {});

But when I run this am getting error,

MongoError: no primary found in replicaset

Dont know why is that, can anyone help me in this?

Body:
So the short answer is this:

... all drivers are not equal and some make assumptions when multiple hosts are specified. For example, the Meteor/Node.js MongoDB driver sees two hosts and assumes it is talking to a replicaset. Upon connecting the driver asks which host is master and then errors out because neither of them are. The simple fix for this is to use one host in the URI ..

https://www.compose.com/articles/connecting-to-the-new-mongodb-at-compose/#drivingtoyourfirstdatabase

So when you create a connection, simply use one of the connection URIs for the database you want to connect to like:

var uri = "mongodb://<username>:<password>@[host]:[port]/<db_name>?ssl=true";

mongoose.createConnection(uri);


问:
Cordova plugin from private GitHub repository
What is the preferred way to install a Cordova plugin from a private GitHub repository?

I have purchased a private plugin from a provider who granted my git account access to their private git repository.  Normally I install plugins from the cordova cli with:

```<code>cordova plugin add https://github.com/somePrivateRepo/purchasedPlugin.git
</code>```

But this yielded the following error:

```<code>    Error: Failed to fetch plugin https://github.com/somePrivateRepo/purchasedPlugin.git via git.
    Either there is a connection problems, or plugin spec is incorrect:
    Error: C:\Program Files\Git\cmd\git.exe: Command failed with exit code 1
    28 Error output:
    Cloning into 'C:\Users\xxxx\AppData\Local\Temp\git\1459346362064'...
    bash: /dev/tty: No such device or address
    error: failed to execute prompt script (exit code 1)
    fatal: could not read Username for 'https://github.com': Invalid argument
</code>```

I know the URL is good as the GitHub desktop was able to clone the repository.

The software provider who sold me the plugin told me this was a problem between me and GitHub.

Should I be able to install the plugin from the Cordova plugin add command?

Is there a better solution that I have not thought of?

Should I just clone from the GitHub desktop GUI then copy and paste the files into my project?

Is this a GitHub problem?

Is this a Cordova problem?

Is this a problem for the seller of the private plugin?

Feels like I am missing a key piece of information to make this work.

答:
I had the same issue.
Cordova changed its plugin loading at Cordova 7, so you should try using the --nofetch option to use the old loading method.

Your private plugin provider could also update his plugin to work with the new method; I found it just needed a package.json file creating to get mine working again.

Body:
What is the preferred way to install a Cordova plugin from a private GitHub repository?

I have purchased a private plugin from a provider who granted my git account access to their private git repository.  Normally I install plugins from the cordova cli with:

cordova plugin add https://github.com/somePrivateRepo/purchasedPlugin.git

But this yielded the following error:

    Error: Failed to fetch plugin https://github.com/somePrivateRepo/purchasedPlugin.git via git.
    Either there is a connection problems, or plugin spec is incorrect:
    Error: C:\Program Files\Git\cmd\git.exe: Command failed with exit code 1
    28 Error output:
    Cloning into 'C:\Users\xxxx\AppData\Local\Temp\git\1459346362064'...
    bash: /dev/tty: No such device or address
    error: failed to execute prompt script (exit code 1)
    fatal: could not read Username for 'https://github.com': Invalid argument

I know the URL is good as the GitHub desktop was able to clone the repository.

The software provider who sold me the plugin told me this was a problem between me and GitHub.

Should I be able to install the plugin from the Cordova plugin add command?

Is there a better solution that I have not thought of?

Should I just clone from the GitHub desktop GUI then copy and paste the files into my project?

Is this a GitHub problem?

Is this a Cordova problem?

Is this a problem for the seller of the private plugin?

Feels like I am missing a key piece of information to make this work.