问:
Unable to call objects methods in django ''function' object has no attribute 'objects'"
Im trying to display some objects from django. When I use the administrator my objects are created but when I try to display it is impossible.

I tryed to make a render but when I initialize the screen never is called, then i tryed to make it with a GET button, now the function is called but when arrives to alumnos = Alumno.objects.all() throws
'function' object has no attribute 'objects'.

models.py

```<code>class Alumno(models.Model):
    dni = models.CharField(max_length=9,primary_key=True)
    nombre = models.CharField(max_length=100)
    apellido1 = models.CharField('Primer apellido',max_length=50)
    apellido2 = models.CharField('Segundo apellido',max_length=50)
    email = models.EmailField("Correo electronico",null=True)
    repetidor = models.BooleanField()
    curs = models.ManyToManyField(Curso, blank=True, related_name="Historico_de_cursos")
    Nivel = models.ManyToManyField('Nivel', through = 'Completado',through_fields=('Alumno','Nivel'))
    Practica = models.ManyToManyField('Practica', through = 'Nota',through_fields=('Alumno','Practica'))
    Curso = models.ManyToManyField('Curso',through = 'Curso_alumno',through_fields=('Alumno','Curso'))

objects = models.Manager()

def __str__(self):
    return self.dni

class Meta:
    db_table = "Alumno"
    verbose_name = 'Alumno'
    verbose_name_plural = 'Alumnos'
    unique_together = ("nombre", "apellido1", "apellido2")
</code>```

view.py

```<code>def mostrar_alumnos(request):
    alumnos = Alumno.objects.all()
    return render(request, 'mostrar_alumnos.html', {'alumnos': alumnos}
</code>```

mostrar_alumnos.html

```<code>{% if alumnos %}
    <ul>
    {% for alumno in alumnos %}
    <td>{{ alumno.dni }}</td>
    <td>{{ alumno.nombre }}</td>
    <td>{{ alumno.apellido1 }}</td>
    <td>
     <a class="btn btn-secondary" href="{% url 'actualizar_alumno' alumno.dni %}"> Editar</a>
    <a class="btn btn-danger" href="{% url 'eliminar_alumno' alumno.dni %}"> Esborrar</a> </td>
{% endfor %}
    </ul>
{% else %}
    <p>No hay alumnos disponibles.</p>
{% endif %}
</code>```

url.py

```<code>url(r'^mostrar_alumnos/$', TemplateView.as_view(template_name='mostrar_alumnos.html'),name='mostrar_alumnos'),
url(r'^mostrar_alumnos/$', views.mostrar_alumnos,name='mostrar_alumnos'),
url(r'^mostrar_alumnos2/$', views.mostrar_alumnos2,name='mostrar_alumnos2')
</code>```

答:
Based on the error message, and your comment, you have constructed a view function with the name Alumno, as in:

```<code># app/views.py

from app.models import Alumno

def <b><s>Alumno</s></b>(request):
    # ...
    pass

def mostrar_alumnos(request):
    alumnos = <b>Alumno</b>.objects.all()
    return render(request, 'mostrar_alumnos.html', {'Alumno': alumnos})</code>```

This means that if you write Alumno.objects, you are referring to the Alumno function, even if you imported the model, since you simply have set the Alumno identifier to that function when you defined it.

The simplest way to solve this is to rename your Alumno view to alumno, which is, according to PEP-8 the recommended way to name your function. In that case Alumno will thus refer to your imported model.

```<code># app/views.py

from app.models import <b>Alumno</b>

def <i>alumno</i>(request):
    # ...
    pass

def mostrar_alumnos(request):
    alumnos = <b>Alumno</b>.objects.all()
    return render(request, 'mostrar_alumnos.html', {<b>'alumnos'</b>: alumnos})</code>```

The name of the template variable probably should be 'alumnos' instead of Alumno, in your template you can then render this with:

```<code>{% if <b>alumnos</b> %}
<ul>

    {% for alumno in <b>alumnos</b> %}
        <td>{{ Alumno.dni }}</td>
        <td>{{ Alumno.nombre }}</td>
        <td>{{ Alumno.apellido1 }}</td>
        <td>
         <a class="btn btn-secondary" href="{% url 'actualizar_alumno' alumno.dni %}"> Editar</a>
        <a class="btn btn-danger" href="{% url 'eliminar_alumno' alumno.dni %}"> Esborrar</a> </td>
    {% endfor %}
</ul>
{% endif %}</code>```

Note that you do not have to define an objects = models.Manager() in your models. If you do not specify another manager, Django will automatically add a manager named objects to it.

Body:
Im trying to display some objects from django. When I use the administrator my objects are created but when I try to display it is impossible.

I tryed to make a render but when I initialize the screen never is called, then i tryed to make it with a GET button, now the function is called but when arrives to alumnos = Alumno.objects.all() throws
'function' object has no attribute 'objects'.

models.py

class Alumno(models.Model):
    dni = models.CharField(max_length=9,primary_key=True)
    nombre = models.CharField(max_length=100)
    apellido1 = models.CharField('Primer apellido',max_length=50)
    apellido2 = models.CharField('Segundo apellido',max_length=50)
    email = models.EmailField("Correo electronico",null=True)
    repetidor = models.BooleanField()
    curs = models.ManyToManyField(Curso, blank=True, related_name="Historico_de_cursos")
    Nivel = models.ManyToManyField('Nivel', through = 'Completado',through_fields=('Alumno','Nivel'))
    Practica = models.ManyToManyField('Practica', through = 'Nota',through_fields=('Alumno','Practica'))
    Curso = models.ManyToManyField('Curso',through = 'Curso_alumno',through_fields=('Alumno','Curso'))

objects = models.Manager()

def __str__(self):
    return self.dni

class Meta:
    db_table = "Alumno"
    verbose_name = 'Alumno'
    verbose_name_plural = 'Alumnos'
    unique_together = ("nombre", "apellido1", "apellido2")

view.py

def mostrar_alumnos(request):
    alumnos = Alumno.objects.all()
    return render(request, 'mostrar_alumnos.html', {'alumnos': alumnos}

mostrar_alumnos.html

{% if alumnos %}

    {% for alumno in alumnos %}
    {{ alumno.dni }}
    {{ alumno.nombre }}
    {{ alumno.apellido1 }}

      Editar
     Esborrar
{% endfor %}

{% else %}

No hay alumnos disponibles.

{% endif %}

url.py

url(r'^mostrar_alumnos/$', TemplateView.as_view(template_name='mostrar_alumnos.html'),name='mostrar_alumnos'),
url(r'^mostrar_alumnos/$', views.mostrar_alumnos,name='mostrar_alumnos'),
url(r'^mostrar_alumnos2/$', views.mostrar_alumnos2,name='mostrar_alumnos2')

Body:
Based on the error message, and your comment, you have constructed a view function with the name Alumno, as in:

# app/views.py

from app.models import Alumno

def <s>Alumno</s>(request):
    # ...
    pass

def mostrar_alumnos(request):
    alumnos = Alumno.objects.all()
    return render(request, 'mostrar_alumnos.html', {'Alumno': alumnos})

This means that if you write Alumno.objects, you are referring to the Alumno function, even if you imported the model, since you simply have set the Alumno identifier to that function when you defined it.

The simplest way to solve this is to rename your Alumno view to alumno, which is, according to PEP-8 the recommended way to name your function. In that case Alumno will thus refer to your imported model.

# app/views.py

from app.models import Alumno

def alumno(request):
    # ...
    pass

def mostrar_alumnos(request):
    alumnos = Alumno.objects.all()
    return render(request, 'mostrar_alumnos.html', {'alumnos': alumnos})

The name of the template variable probably should be 'alumnos' instead of Alumno, in your template you can then render this with:

{% if alumnos %}
<ul>

    {% for alumno in alumnos %}
        <td>{{ Alumno.dni }}</td>
        <td>{{ Alumno.nombre }}</td>
        <td>{{ Alumno.apellido1 }}</td>
        <td>
         <a class="btn btn-secondary" href="{% url 'actualizar_alumno' alumno.dni %}"> Editar</a>
        <a class="btn btn-danger" href="{% url 'eliminar_alumno' alumno.dni %}"> Esborrar</a> </td>
    {% endfor %}
</ul>
{% endif %}

Note that you do not have to define an objects = models.Manager() in your models. If you do not specify another manager, Django will automatically add a manager named objects to it.


来源: stackexchange

问:
How to create link on image using Javascript
```<code><div id="mydiv">
<img src="myimage.jpg" />
</div>
<script language="javascript">
var a=document.createElement('a');
a.href='http://mylink.com';
document.getElementById('mydiv').appendChild(a);
</script>
</code>```

<p>The script doesn't work to create link on image </p>

```<code><div id="mydiv">
    <a href="http://mylink.com"><img src="myimage.jpg" /></a>
</div>
</code>```

答:
For single images

Where you can pass the image by element object, ID, or the first src substring match. Takes an optional target attribute, like "_blank". No jQuery required.

```<code>// By img element object
// (used by the functions below)
var addImageLink = function( elem, target ){
    if( !elem || !( 'tagName' in elem ) ){ return; }
    var image = elem;
    var parent = image.parentElement;
    var a = document.createElement( 'a' );
    a.href = image.getAttribute( 'src' );
    if( target ){ a.setAttribute( 'target', target ); }
    a.appendChild( image );
    parent.appendChild( a );
};

// By img element id
// <img src="images/gallery/1.jpg" id="image1" />
// <script> addImageLinkById( 'image1' ); </script>
var addImageLinkById = function( id, target ){
    addImageLink( document.getElementById( id ), target );
};

// By img element src (first match)
// <img src="images/gallery/1.jpg"/>
// <script> addImageLinkBySrc( '/1.jpg' ); </script>
var addImageLinkBySrc = function( src, target ){
    var image, images = document.getElementsByTagName( 'img' );
    if( typeof src == 'undefined' ){ src = ''; }
    for( var i = 0; i < images.length; i++ ){
        if( images[ i ].src.indexOf( src ) < 0 ){ continue; }
        addImageLink( images[ i ], target ); return;
    }
};
</code>```

For looping through all images

This solution puts a link around every image. It's an expanded version of Falko's answer.

Doesn't use jQuery

Optionally whitelist images by href substring, like "images/gallery/"

Specify an optional target attribute, like "_blank"

Won't skip the second half of the images
(I experienced this issue when trying his code, but it could be something I did wrong)

```<code>var addImageLinks = function( filter, target ){

    var parent, a, image;
    var images = document.getElementsByTagName( 'img' );
    var hasTarget = ( typeof target != 'undefined' );
    var hasFilter = ( typeof filter != 'undefined' );

    for( var i = 0; i < images.length; i++ ){

        image = images[ i ];
        if( hasFilter && ( image.src.indexOf( filter ) < 0 ) ){ continue; }

        // Skip over already-wrapped images, by adding an attribute
        if( image.getAttribute( 'data-wrapped-link' ) ){ continue; }
        image.setAttribute( 'data-wrapped-link', '1' );

        // Add the link
        parent = image.parentElement;
        a = document.createElement( 'a' );
        a.href = image.getAttribute( 'src' );
        if( hasTarget ){ a.setAttribute( 'target', target ); }
        a.appendChild( image );
        parent.appendChild( a );

        // We inserted a "new" image, so go back one step so we don't miss any
        // (due to being inside the "i < images.length" loop)
        i--;

    }

};

// Then:
// <img src="images/gallery/a.jpg"/>
// <img src="images/gallery/b.jpg"/>
// <img src="images/gallery/c.jpg"/>
// <img src="images/icons/a.gif"/> <- ignored

// Near bottom of the page (or in an onLoad handler, etc):
// </script> addImageLinks( 'images/gallery/', '_blank' ); </script>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
For single images

Where you can pass the image by element object, ID, or the first src substring match. Takes an optional target attribute, like "_blank". No jQuery required.

// By img element object
// (used by the functions below)
var addImageLink = function( elem, target ){
    if( !elem || !( 'tagName' in elem ) ){ return; }
    var image = elem;
    var parent = image.parentElement;
    var a = document.createElement( 'a' );
    a.href = image.getAttribute( 'src' );
    if( target ){ a.setAttribute( 'target', target ); }
    a.appendChild( image );
    parent.appendChild( a );
};

// By img element id
// <img src="images/gallery/1.jpg" id="image1" />
// <script> addImageLinkById( 'image1' ); </script>
var addImageLinkById = function( id, target ){
    addImageLink( document.getElementById( id ), target );
};

// By img element src (first match)
// <img src="images/gallery/1.jpg"/>
// <script> addImageLinkBySrc( '/1.jpg' ); </script>
var addImageLinkBySrc = function( src, target ){
    var image, images = document.getElementsByTagName( 'img' );
    if( typeof src == 'undefined' ){ src = ''; }
    for( var i = 0; i < images.length; i++ ){
        if( images[ i ].src.indexOf( src ) < 0 ){ continue; }
        addImageLink( images[ i ], target ); return;
    }
};

For looping through all images

This solution puts a link around every image. It's an expanded version of Falko's answer.

Doesn't use jQuery

Optionally whitelist images by href substring, like "images/gallery/"

Specify an optional target attribute, like "_blank"

Won't skip the second half of the images
(I experienced this issue when trying his code, but it could be something I did wrong)

var addImageLinks = function( filter, target ){

    var parent, a, image;
    var images = document.getElementsByTagName( 'img' );
    var hasTarget = ( typeof target != 'undefined' );
    var hasFilter = ( typeof filter != 'undefined' );

    for( var i = 0; i < images.length; i++ ){

        image = images[ i ];
        if( hasFilter && ( image.src.indexOf( filter ) < 0 ) ){ continue; }

        // Skip over already-wrapped images, by adding an attribute
        if( image.getAttribute( 'data-wrapped-link' ) ){ continue; }
        image.setAttribute( 'data-wrapped-link', '1' );

        // Add the link
        parent = image.parentElement;
        a = document.createElement( 'a' );
        a.href = image.getAttribute( 'src' );
        if( hasTarget ){ a.setAttribute( 'target', target ); }
        a.appendChild( image );
        parent.appendChild( a );

        // We inserted a "new" image, so go back one step so we don't miss any
        // (due to being inside the "i < images.length" loop)
        i--;

    }

};

// Then:
// <img src="images/gallery/a.jpg"/>
// <img src="images/gallery/b.jpg"/>
// <img src="images/gallery/c.jpg"/>
// <img src="images/icons/a.gif"/> <- ignored

// Near bottom of the page (or in an onLoad handler, etc):
// </script> addImageLinks( 'images/gallery/', '_blank' ); </script>

ContentLicense: CC BY-SA 4.0


问:
source error message="Index '('d1', 'i1')' is not valid for indexed component 'NFix'"
I am trying to solve an Abstract model in PYOMO and I am having trouble importing the data into the model to create an instance.

I've looked online for documentation/examples importing data and I don't see how mine is different than the examples found online that do work.
'''
    ## call PYOMO
    from pyomo.environ import *

```<code>## Define Model
model = AbstractModel()

# Define index sets

# I= set if calculation steps where investments are possible
model.I = Set(dimen=1)
model.I.construct()

# D = set of DERs
model.D = Set(dimen=1)
model.D.construct()

## Define Parameters
a = 0.5
model.NFix = Param(model.D, model.I, within=PositiveReals)
model.NVar = Param(model.D, model.I, within=PositiveReals)
model.RFix = Param(model.D, model.I, within=PositiveReals)
model.RVar = Param(model.D, model.I, within=PositiveReals)
model.y = Param(model.I, within=PositiveReals)

## Define variables
model.n = Var(model.D, model.I, within = Binary)
model.r = Var(model.D, model.I, within = Binary)
model.NCap = Var(model.D, model.I, within = PositiveReals)
model.RCap = Var(model.D, model.I, within = PositiveReals)

## Define objective value
model.cost = Objective(sum((sum(model.n[d,i]*model.NFix[d,i]+ model.NCap[d,i]*model.NVar[d,i] +
model.r[d,i]*model.RFix[d,i] +model.RCap[d,i]*model.RVar[d,i] for d in model.D))/(1+a)**y[i]) for i in model.I)

instance = model.create_instance('data.dat')
opt = pyo.SolverFactory('glpk')
opt.solve(instance)
</code>```

For the data.dat file I have the following:

```<code>set I := i1 i2 i3;

set D := d1 d2;

param NFix : i1 i2 i3 :=
d1 1 1 3
d2 1 3 5
;

param NVar : i1 i2 i3 :=
d1 1 1 3
d2 1 3 5
;

param RFix : i1 i2 i3 :=
d1 1 1 3
d2 1 3 5
;

param RVar : i1 i2 i3 :=
d1 1 1 3
d2 1 3 5
;

param y := 1 2 ;
</code>```

I get the following error message:

ERROR: Constructing component 'NFix' from data={('d1', 'i1'): 1, ('d2', 'i1'):
    1, ('d1', 'i2'): 1, ('d2', 'i2'): 3, ('d1', 'i3'): 3, ('d2', 'i3'): 5}
    failed:
        RuntimeError: Failed to set value for param=NFix, index=('d1', 'i1'),
        value=1.
        source error message="Index '('d1', 'i1')' is not valid for indexed
        component 'NFix'"

答:
I found a couple minor errors in both your model file and your dat file.

In your model file, you should never manually call the construct method on a Pyomo component. In your objective function, you had misplaced parenthesis and you need to make sure to use a rule to define the objective function when using an Abstract model. I also noticed that you forgot the model. before referencing y. A corrected version of this file is below:

```<code>## Define Model
model = AbstractModel()

# Define index sets

# I= set if calculation steps where investments are possible
model.I = Set(dimen=1)

# D = set of DERs
model.D = Set(dimen=1)

## Define Parameters
a = 0.5
model.NFix = Param(model.D, model.I, within=PositiveReals)
model.NVar = Param(model.D, model.I, within=PositiveReals)
model.RFix = Param(model.D, model.I, within=PositiveReals)
model.RVar = Param(model.D, model.I, within=PositiveReals)
model.y = Param(model.I, within=PositiveReals)

## Define variables
model.n = Var(model.D, model.I, within = Binary)
model.r = Var(model.D, model.I, within = Binary)
model.NCap = Var(model.D, model.I, within = PositiveReals)
model.RCap = Var(model.D, model.I, within = PositiveReals)

## Define objective value
def _obj(model):
    return sum((sum(model.n[d,i]*model.NFix[d,i]+ model.NCap[d,i]*model.NVar[d,i] + \
                    model.r[d,i]*model.RFix[d,i] +model.RCap[d,i]*model.RVar[d,i] for d in model.D)) \
               /(1+a)**model.y[i] for i in model.I)
model.cost = Objective(rule=_obj)

instance = model.create_instance('abstract.dat')
opt = SolverFactory('glpk')
opt.solve(instance, tee=True)
</code>```

The only issue in your dat file is that you haven't defined the y parameter properly. In the model it looks like y is indexed by I which means you need to define your parameter something like:

```<code>param y :=
i1 1
i2 2
i3 3 ;
</code>```

Body:
I am trying to solve an Abstract model in PYOMO and I am having trouble importing the data into the model to create an instance.

I've looked online for documentation/examples importing data and I don't see how mine is different than the examples found online that do work.
'''
    ## call PYOMO
    from pyomo.environ import *

## Define Model
model = AbstractModel()

# Define index sets

# I= set if calculation steps where investments are possible
model.I = Set(dimen=1)
model.I.construct()

# D = set of DERs
model.D = Set(dimen=1)
model.D.construct()

## Define Parameters
a = 0.5
model.NFix = Param(model.D, model.I, within=PositiveReals)
model.NVar = Param(model.D, model.I, within=PositiveReals)
model.RFix = Param(model.D, model.I, within=PositiveReals)
model.RVar = Param(model.D, model.I, within=PositiveReals)
model.y = Param(model.I, within=PositiveReals)

## Define variables
model.n = Var(model.D, model.I, within = Binary)
model.r = Var(model.D, model.I, within = Binary)
model.NCap = Var(model.D, model.I, within = PositiveReals)
model.RCap = Var(model.D, model.I, within = PositiveReals)

## Define objective value
model.cost = Objective(sum((sum(model.n[d,i]*model.NFix[d,i]+ model.NCap[d,i]*model.NVar[d,i] +
model.r[d,i]*model.RFix[d,i] +model.RCap[d,i]*model.RVar[d,i] for d in model.D))/(1+a)**y[i]) for i in model.I)

instance = model.create_instance('data.dat')
opt = pyo.SolverFactory('glpk')
opt.solve(instance)

For the data.dat file I have the following:

set I := i1 i2 i3;

set D := d1 d2;

param NFix : i1 i2 i3 :=
d1 1 1 3
d2 1 3 5
;

param NVar : i1 i2 i3 :=
d1 1 1 3
d2 1 3 5
;

param RFix : i1 i2 i3 :=
d1 1 1 3
d2 1 3 5
;

param RVar : i1 i2 i3 :=
d1 1 1 3
d2 1 3 5
;

param y := 1 2 ;

I get the following error message:

ERROR: Constructing component 'NFix' from data={('d1', 'i1'): 1, ('d2', 'i1'):
    1, ('d1', 'i2'): 1, ('d2', 'i2'): 3, ('d1', 'i3'): 3, ('d2', 'i3'): 5}
    failed:
        RuntimeError: Failed to set value for param=NFix, index=('d1', 'i1'),
        value=1.
        source error message="Index '('d1', 'i1')' is not valid for indexed
        component 'NFix'"

Body:
I found a couple minor errors in both your model file and your dat file.

In your model file, you should never manually call the construct method on a Pyomo component. In your objective function, you had misplaced parenthesis and you need to make sure to use a rule to define the objective function when using an Abstract model. I also noticed that you forgot the model. before referencing y. A corrected version of this file is below:

## Define Model
model = AbstractModel()

# Define index sets

# I= set if calculation steps where investments are possible
model.I = Set(dimen=1)

# D = set of DERs
model.D = Set(dimen=1)

## Define Parameters
a = 0.5
model.NFix = Param(model.D, model.I, within=PositiveReals)
model.NVar = Param(model.D, model.I, within=PositiveReals)
model.RFix = Param(model.D, model.I, within=PositiveReals)
model.RVar = Param(model.D, model.I, within=PositiveReals)
model.y = Param(model.I, within=PositiveReals)

## Define variables
model.n = Var(model.D, model.I, within = Binary)
model.r = Var(model.D, model.I, within = Binary)
model.NCap = Var(model.D, model.I, within = PositiveReals)
model.RCap = Var(model.D, model.I, within = PositiveReals)

## Define objective value
def _obj(model):
    return sum((sum(model.n[d,i]*model.NFix[d,i]+ model.NCap[d,i]*model.NVar[d,i] + \
                    model.r[d,i]*model.RFix[d,i] +model.RCap[d,i]*model.RVar[d,i] for d in model.D)) \
               /(1+a)**model.y[i] for i in model.I)
model.cost = Objective(rule=_obj)

instance = model.create_instance('abstract.dat')
opt = SolverFactory('glpk')
opt.solve(instance, tee=True)

The only issue in your dat file is that you haven't defined the y parameter properly. In the model it looks like y is indexed by I which means you need to define your parameter something like:

param y :=
i1 1
i2 2
i3 3 ;


问:
One macro running , the other does not
I am importing currency data from a website on a click event.

The import works and its called by this code:

```<code>Option Explicit

 Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Selection.Count = 1 Then
    If Not Intersect(Target, Range("F13")) Is Nothing Then
        Call GetCurrency
    End If
End If
If Selection.Count = 1 Then
    If Not Intersect(Target, Range("F14")) Is Nothing Then
        Call UpdateCurrency
    End If
End If
End Sub
</code>```

If the cell F13 is clicked, the GetCurrency macro runs, imports the data, wonderful.

But clicking F14 causes nothing.

The update currency macro looks like this

```<code>Sub UpdateCurrency()

Range("N15").Value = Range("I19").Value
Range("N14").Value = Range("I26").Value
Range("N16").Value = Range("I22").Value

 End Sub
</code>```

This should just update some other cells in order to make another formula work properly. Question is, why does clicking the cell F14 not run the UpdateCurrency function?

答:
It think you need to change the if statements a bit.</p>

```<code>Option Explicit

 Private Sub Worksheet_SelectionChange(ByVal Target As Range)

 If Selection.Count = 1 Then
    If Target = Range("F13") Then
        If Not Intersect(Target, Range("F13")) Is Nothing Then
            Call GetCurrency
        End If
     Else
            If Not Intersect(Target, Range("F14")) Is Nothing Then
                Call UpdateCurrency
            End If
        End If
    End If
End Sub
</code>```

Title: One macro running , the other does not

Body:
I am importing currency data from a website on a click event.

The import works and its called by this code:

Option Explicit

 Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Selection.Count = 1 Then
    If Not Intersect(Target, Range("F13")) Is Nothing Then
        Call GetCurrency
    End If
End If
If Selection.Count = 1 Then
    If Not Intersect(Target, Range("F14")) Is Nothing Then
        Call UpdateCurrency
    End If
End If
End Sub

If the cell F13 is clicked, the GetCurrency macro runs, imports the data, wonderful.

But clicking F14 causes nothing.

The update currency macro looks like this

Sub UpdateCurrency()

Range("N15").Value = Range("I19").Value
Range("N14").Value = Range("I26").Value
Range("N16").Value = Range("I22").Value

 End Sub

This should just update some other cells in order to make another formula work properly. Question is, why does clicking the cell F14 not run the UpdateCurrency function?

Body:
It think you need to change the if statements a bit.

Option Explicit

 Private Sub Worksheet_SelectionChange(ByVal Target As Range)

 If Selection.Count = 1 Then
    If Target = Range("F13") Then
        If Not Intersect(Target, Range("F13")) Is Nothing Then
            Call GetCurrency
        End If
     Else
            If Not Intersect(Target, Range("F14")) Is Nothing Then
                Call UpdateCurrency
            End If
        End If
    End If
End Sub


问:
Gtk Terminal Widget
Simple question: Is there a linux-style terminal widget for GTK? Preferably for Haskell, too, as I want to use gtk2hs</p>

答: Pretty much the best and only candidate is VTE. Not sure if you would need an explicit Haskell wrapper for the native library or not.</p>

Title: Gtk Terminal Widget


问:
Terminating all unnecessary processes using a batch script?
As a security precaution, I would like a way where I can force terminate all processes that are not required for the Windows operating system to operate. I additionally want to make sure that no new process starts, and print all terminated processes so I know where to look.
This is so that in case I accidentally download malware and it is still in its early stages, I can possibly revert possible damages and more easily remove the source.
I do not know how to approach this issue, and thus I seek help with my own question. Thank you in advance :)

PS: If there can be a way to provide an exit button to the batch script that would be great, but not necessary! :)

答:
You can do this with a combination of tasklist and taskkill.

Make a list of safe programs, and crosscheck it against every task currently running, killing it if it isn't on the list.

```<code>@echo off
setlocal enabledelayedexpansion

set safeArray="system idle process" "system" "registry" "svchost.exe" & rem etc

for /f "tokens=1,2 delims=," %%i in ('tasklist /fo csv /nh') do (
    set tmp=0
    for /f %%k in ('echo %safeArray% ^| find /i /c "%%~i"') do set /a tmp+=%%k
    if !tmp! lss 1 echo I want to taskkill - %%~i  PID: %%~j
)

pause
</code>```

I've left the actual killing out of the script right now as you will want to set up you safe array first.

Replace echo I want to taskkill… line with taskkill /pid %%~j.

Body:
You can do this with a combination of tasklist and taskkill.

Make a list of safe programs, and crosscheck it against every task currently running, killing it if it isn't on the list.

@echo off
setlocal enabledelayedexpansion

set safeArray="system idle process" "system" "registry" "svchost.exe" & rem etc

for /f "tokens=1,2 delims=," %%i in ('tasklist /fo csv /nh') do (
    set tmp=0
    for /f %%k in ('echo %safeArray% ^| find /i /c "%%~i"') do set /a tmp+=%%k
    if !tmp! lss 1 echo I want to taskkill - %%~i  PID: %%~j
)

pause

I've left the actual killing out of the script right now as you will want to set up you safe array first.

Replace echo I want to taskkill… line with taskkill /pid %%~j.


问:
Python GET request with a nested parameters
I'm trying to write API client for Jira with Python requests lib according reference:
https://developer.atlassian.com/server/jira/platform/jira-rest-api-examples/

Request to be generated:

http://localhost:8080/rest/api/2/search?jql=assignee=charlie&startAt=2&maxResults=2

As I know, parameters to GET request should be passed as dictionary like:

```<code> params = {'assignee':'charlie', 'startAt':'2'}
</code>```

But all main parameters are nested in jql parameter, so I assume there is should be a nested dict like:

```<code> params = {'jql': {'assignee': 'charlie'}}
</code>```

But that's doesn't work - as a result I've got request to

```<code>/rest/api/2/search?jql=assignee
</code>```

As expect /rest/api/2/search?jql=assignee=charlie
using

```<code>r = requests.get(url, params=params)
</code>```

How to manage such request?

UPD:

To be more clear, I'd like to wrap request in a method with kwargs, like:

```<code>search_query(assignee='charlie', startAt=1, etc...)
</code>```

And then generate a query using this params, but maybe there are any other ideas.

答:
You are missing couple of key parameters, mainly if you are pushing data via requests, the data go into the data argument. Also the moment you push JSON data, you need to set the headers correctly as well. The last thing is authentication. Have you tried to post it in this manner?

```<code>import json
requests.post(url=url, headers={"Content-Type": "application/json"},
              auth=('username', 'password'), # your username and password
              data=json.dumps(params)
              )
</code>```

Also by the JIRA documentation you've provided (https://developer.atlassian.com/server/jira/platform/jira-rest-api-examples/) if you want to push query as data, the url you want is /rest/api/2/search.

Body:
I'm trying to write API client for Jira with Python requests lib according reference:
https://developer.atlassian.com/server/jira/platform/jira-rest-api-examples/

Request to be generated:

http://localhost:8080/rest/api/2/search?jql=assignee=charlie&startAt=2&maxResults=2

As I know, parameters to GET request should be passed as dictionary like:

 params = {'assignee':'charlie', 'startAt':'2'}

But all main parameters are nested in jql parameter, so I assume there is should be a nested dict like:

 params = {'jql': {'assignee': 'charlie'}}

But that's doesn't work - as a result I've got request to

/rest/api/2/search?jql=assignee

As expect /rest/api/2/search?jql=assignee=charlie
using

r = requests.get(url, params=params)

How to manage such request?

UPD:

To be more clear, I'd like to wrap request in a method with kwargs, like:

search_query(assignee='charlie', startAt=1, etc...)

And then generate a query using this params, but maybe there are any other ideas.

Body:
You are missing couple of key parameters, mainly if you are pushing data via requests, the data go into the data argument. Also the moment you push JSON data, you need to set the headers correctly as well. The last thing is authentication. Have you tried to post it in this manner?

import json
requests.post(url=url, headers={"Content-Type": "application/json"},
              auth=('username', 'password'), # your username and password
              data=json.dumps(params)
              )

Also by the JIRA documentation you've provided (https://developer.atlassian.com/server/jira/platform/jira-rest-api-examples/) if you want to push query as data, the url you want is /rest/api/2/search.


问:
Convert data type string to float in DataFrame
I have a data in string format, when I use DataFrame, it will be in Substring format, but I want it in Float format. What should I do?

```<code>x  = defect_positions[1:3]
>>>SubString{String}["4.71801", "17.2815", "0.187765"]
>>>SubString{String}["17.3681", "17.1425", "6.13644"]
>>>SubString{String}["0.439987", "0.00231646", "0.404172"]
DataFrame(permutedims(reduce(hcat, x))

x1  x2  x3
SubStrin…   SubStrin…   SubStrin…
1   4.71801 17.2815 0.187765
2   17.3681 17.1425 6.13644
3   0.439987    0.00231646  0.404172
</code>```

How can I convert my DataFrame to float?

答:
DataFrame uses the element types of the input collections You should convert your strings to a floating point number type before creating a DataFrame. You can parse a string as a floating number type of your choice with parse.

```<code># we map each `SubString` array in x (`SubString` arrays)
# and parse each entries as `Float64` by broadcasting `parse`
parsed_x = map(i -> parse.(Float64, i), x)
DataFrame(permutedims(reduce(hcat, parsed_x)))
</code>```

You may also choose to do the conversion after creating the DataFrame with strings.

```<code>df = DataFrame(permutedims(reduce(hcat, x))
for i in 1:size(df, 2)
   df[i] = parse.(Float64, df[i])
end
df
</code>```

Both methods give

```<code>│ Row │ x1      │ x2      │ x3       │
│     │ Float64 │ Float64 │ Float64  │
├─────┼─────────┼─────────┼──────────┤
│ 1   │ 4.71801 │ 17.2815 │ 0.187765 │
...
</code>```

Body:
I have a data in string format, when I use DataFrame, it will be in Substring format, but I want it in Float format. What should I do?

x  = defect_positions[1:3]
>>>SubString{String}["4.71801", "17.2815", "0.187765"]
>>>SubString{String}["17.3681", "17.1425", "6.13644"]
>>>SubString{String}["0.439987", "0.00231646", "0.404172"]
DataFrame(permutedims(reduce(hcat, x))

x1  x2  x3
SubStrin…   SubStrin…   SubStrin…
1   4.71801 17.2815 0.187765
2   17.3681 17.1425 6.13644
3   0.439987    0.00231646  0.404172

How can I convert my DataFrame to float?

Body:
DataFrame uses the element types of the input collections You should convert your strings to a floating point number type before creating a DataFrame. You can parse a string as a floating number type of your choice with parse.

# we map each `SubString` array in x (`SubString` arrays)
# and parse each entries as `Float64` by broadcasting `parse`
parsed_x = map(i -> parse.(Float64, i), x)
DataFrame(permutedims(reduce(hcat, parsed_x)))

You may also choose to do the conversion after creating the DataFrame with strings.

df = DataFrame(permutedims(reduce(hcat, x))
for i in 1:size(df, 2)
   df[i] = parse.(Float64, df[i])
end
df

Both methods give

│ Row │ x1      │ x2      │ x3       │
│     │ Float64 │ Float64 │ Float64  │
├─────┼─────────┼─────────┼──────────┤
│ 1   │ 4.71801 │ 17.2815 │ 0.187765 │
...


问:
Pytorch datasets.ImageFolder flag FileNotFoundError: [Errno 2] No such file or directory: '\u2068/
Trying to load data from the local directory in Pytorch using dataset.ImageLoader but getting FileNotFoundError...

import torch
from torchvision import datasets, transforms

data_dir = '/Users/Desktop/Udacity/AI for Trading/deep-learning-v2-pytorch/intro-to-pytorch/data/Cat_Dog_data/train'

transform = transforms.Compose([transforms.Resize(255),
                                transforms.CenterCrop(224),
                                transforms.ToTensor()])

dataset = datasets.ImageFolder(root=data_dir, transform=transform)
dataloader = torch.utils.data.DataLoader(dataset, batch_size=32, shuffle=True)
```

FileNotFoundError: [Errno 2] No such file or directory: '\u2068/Users/Desktop/Udacity/AI for Trading/deep-learning-v2-pytorch/intro-to-pytorch/data\u2069/Cat_Dog_data\u2069/\u2068train\u2069'

Answer: Retyping the Image Dir Path manually instead of copy-pasting solved the problem.

答:
This error is not related to pytorch or dataset library, it seems getting reported by python's OS library..

I tried loading the simple path like

```<code>import os

data_dir = '/Users'
os.chdir(data_dir)
</code>```

Even above code failed, post researching it seems, the error is because of the below reasons:

There are some invisible 'LEFT-TO-RIGHT MARK' (u200e) and 'FIRST STRONG ISOLATE' (u2068) characters in the st

And retyping the path manually (instead of copy-pasting) solved the problem

This stackoverflow helped me fix the problem, I still thought to post it again, as a problem in the context of pytorch was not reported and hopefully, this help folks connects the dots.

Body:
Trying to load data from the local directory in Pytorch using dataset.ImageLoader but getting FileNotFoundError...

import torch
from torchvision import datasets, transforms

data_dir = '/Users/Desktop/Udacity/AI for Trading/deep-learning-v2-pytorch/intro-to-pytorch/data/Cat_Dog_data/train'

transform = transforms.Compose([transforms.Resize(255),
                                transforms.CenterCrop(224),
                                transforms.ToTensor()])

dataset = datasets.ImageFolder(root=data_dir, transform=transform)
dataloader = torch.utils.data.DataLoader(dataset, batch_size=32, shuffle=True)

FileNotFoundError: [Errno 2] No such file or directory: '\u2068/Users/Desktop/Udacity/AI for Trading/deep-learning-v2-pytorch/intro-to-pytorch/data\u2069/Cat_Dog_data\u2069/\u2068train\u2069'

Answer: Retyping the Image Dir Path manually instead of copy-pasting solved the problem.

Body:
This error is not related to pytorch or dataset library, it seems getting reported by python's OS library..

I tried loading the simple path like

import os

data_dir = '/Users'
os.chdir(data_dir)

Even above code failed, post researching it seems, the error is because of the below reasons:

There are some invisible 'LEFT-TO-RIGHT MARK' (u200e) and 'FIRST STRONG ISOLATE' (u2068) characters in the st

And retyping the path manually (instead of copy-pasting) solved the problem

This stackoverflow helped me fix the problem, I still thought to post it again, as a problem in the context of pytorch was not reported and hopefully, this help folks connects the dots.


问:
Get column value onClick in nested HTML Table [Javascript]
I have a nested HTML table which expands on click. When I click inner row, I would like to get column value. Right now, I am getting the column value on click of outer row.
For instance in the below image, when I click coding/testing, I would like to pass an alert as "Place". Right now, I get alert as "place" when I click city.

Component:

```<code> trigger(){
  var table: any = document.getElementById("table");
  var rows = table.rows;
  for (var i = 0; i < rows.length; i++) {
  rows[i].onclick = (function (e) {
    var j = 0;
    var td = e.target;
    while( (td = td.previousElementSibling) != null )
        j++;
    alert(rows[0].cells[j].innerHTML);
 });
 }
 }
</code>```

Demo

答:
You don't need any DOM manipulation, you can simplify your solution as below:

app.component.ts

```<code>// .......
export class AppComponent {
  trigger(columnName: string) {
    alert(columnName);
  }
// .......
}
</code>```

app.component.html

```<code><table class="table table-hover table-bordered table-responsive-xl" id="table">
    <tr>
        <td> Name </td>
        <td> Place </td>
        <td> Phone </td>
    </tr>

    <tbody>

        <ng-container *ngFor="let data of data1">
            <tr (click)="data.expanded = !data.expanded">
                <td (click)="trigger('Name outer')"> {{ data.expanded ? '–' : '+'}} {{data.name}} </td>
                <td (click)="trigger('Place outer')"> {{data.place}} </td>
                <td (click)="trigger('Phone outer')"> {{data.phone}} </td>
                <td (click)="trigger('Hobbies Outer')"> {{data.hobbies}} </td>
                <td (click)="trigger('Profession outer')"> {{data.profession}} </td>
            </tr>

            <ng-container *ngIf="data.expanded">
                <tr *ngFor="let data of findDetails(data)">
                    <td style="padding-left: 12px" (click)="trigger('Name inner')"> {{data.datades.name}} </td>
                    <td (click)="trigger('Hobbies inner')"> {{data.datades.hobbies}} </td>
                    <td (click)="trigger('Profession inner')"> {{data.datades.profession}} </td>
                </tr>
            </ng-container>
        </ng-container>
    </tbody>
</table>
</code>```

Body:
I have a nested HTML table which expands on click. When I click inner row, I would like to get column value. Right now, I am getting the column value on click of outer row.
For instance in the below image, when I click coding/testing, I would like to pass an alert as "Place". Right now, I get alert as "place" when I click city.

Component:

 trigger(){
  var table: any = document.getElementById("table");
  var rows = table.rows;
  for (var i = 0; i < rows.length; i++) {
  rows[i].onclick = (function (e) {
    var j = 0;
    var td = e.target;
    while( (td = td.previousElementSibling) != null )
        j++;
    alert(rows[0].cells[j].innerHTML);
 });
 }
 }

Demo

Body:
You don't need any DOM manipulation, you can simplify your solution as below:

app.component.ts

// .......
export class AppComponent {
  trigger(columnName: string) {
    alert(columnName);
  }
// .......
}

app.component.html

<table class="table table-hover table-bordered table-responsive-xl" id="table">
    <tr>
        <td> Name </td>
        <td> Place </td>
        <td> Phone </td>
    </tr>

    <tbody>

        <ng-container *ngFor="let data of data1">
            <tr (click)="data.expanded = !data.expanded">
                <td (click)="trigger('Name outer')"> {{ data.expanded ? '&ndash;' : '+'}} {{data.name}} </td>
                <td (click)="trigger('Place outer')"> {{data.place}} </td>
                <td (click)="trigger('Phone outer')"> {{data.phone}} </td>
                <td (click)="trigger('Hobbies Outer')"> {{data.hobbies}} </td>
                <td (click)="trigger('Profession outer')"> {{data.profession}} </td>
            </tr>

            <ng-container *ngIf="data.expanded">
                <tr *ngFor="let data of findDetails(data)">
                    <td style="padding-left: 12px" (click)="trigger('Name inner')"> {{data.datades.name}} </td>
                    <td (click)="trigger('Hobbies inner')"> {{data.datades.hobbies}} </td>
                    <td (click)="trigger('Profession inner')"> {{data.datades.profession}} </td>
                </tr>
            </ng-container>
        </ng-container>
    </tbody>
</table>


问:
Alternate color with Angular Material mat-table with parent child rows
I have an Angular Material mat-table which I used CSS styling for alternate row colors. Here is the CSS styling:

.mat-row:nth-child(even){
    background-color: #e4f0ec;
}

.mat-row:nth-child(odd){
    background-color:#ffffff;
}
```

<p>This works when my mat-table does not have defined child rows. When I added another <code>ng-container</code> which is specified with "expandedDetail", this does not work anymore. All the rows is white but the expanded child rows are colored.</p>

<p>I followed the example from material.angular.io</p>

<p>I see other example for row styling but they use tr tags. In the example and my code, I used an <code>ng-container</code>, th and td tags for each column.</p>

<p>Any help is appreciated.</p>

<p>I added the project to stackblitz</p>

<p>https://stackblitz.com/edit/angular-4bcxtv</p>

<p>Here is the HTML code I used</p>

<pre class="lang-html prettyprint-override"><code><table mat-table
       [dataSource]="dataSource" multiTemplateDataRows
       class="mat-elevation-z8">
  <ng-container matColumnDef="{{column}}" *ngFor="let column of columnsToDisplay">
    <th mat-header-cell *matHeaderCellDef> {{column}} </th>
    <td mat-cell *matCellDef="let element"> {{element[column]}} </td>
  </ng-container>

  <!-- Expanded Content Column - The detail row is made up of this one column that spans across all columns -->
  <ng-container matColumnDef="expandedDetail">
    <td mat-cell *matCellDef="let element" [attr.colspan]="columnsToDisplay.length">
      <div class="example-element-detail"
           [@detailExpand]="element == expandedElement ? 'expanded' : 'collapsed'">
        <div class="example-element-diagram">
          <div class="example-element-position"> {{element.position}} </div>
          <div class="example-element-symbol"> {{element.symbol}} </div>
          <div class="example-element-name"> {{element.name}} </div>
          <div class="example-element-weight"> {{element.weight}} </div>
        </div>
        <div class="example-element-description">
          {{element.description}}
          <span class="example-element-description-attribution"> -- Wikipedia </span>
        </div>
      </div>
    </td>
  </ng-container>

  <tr mat-header-row *matHeaderRowDef="columnsToDisplay"></tr>
  <tr mat-row *matRowDef="let element; columns: columnsToDisplay;"
      class="example-element-row"
      [class.example-expanded-row]="expandedElement === element"
      (click)="expandedElement = expandedElement === element ? null : element">
  </tr>
  <tr mat-row *matRowDef="let row; columns: ['expandedDetail']" class="example-detail-row"></tr>
</table>
</code>```

答:
You could set your own class on the row and then target it, so as to not mess around with n-depth and complex selectors that break as your html changes.</p>

```<code>.my-row {
    background-color: #e4f0ec;
}

.my-row__alternate {
    background-color:#ffffff;
}

<tr mat-row *matRowDef="let element; columns: columnsToDisplay; let i = index"
  class="my-row"
  [class.my-row__alternate]="i % 2">
</tr>
</code>```

Body:
I have an Angular Material mat-table which I used CSS styling for alternate row colors. Here is the CSS styling:

.mat-row:nth-child(even){
    background-color: #e4f0ec;
}

.mat-row:nth-child(odd){
    background-color:#ffffff;
}

This works when my mat-table does not have defined child rows. When I added another ng-container which is specified with "expandedDetail", this does not work anymore. All the rows is white but the expanded child rows are colored.

I followed the example from material.angular.io

I see other example for row styling but they use tr tags. In the example and my code, I used an ng-container, th and td tags for each column.

Any help is appreciated.

I added the project to stackblitz

https://stackblitz.com/edit/angular-4bcxtv

Here is the HTML code I used

  <ng-container matColumnDef="{{column}}" *ngFor="let column of columnsToDisplay">
     {{column}}
     {{element[column]}}
  </ng-container>

  <ng-container matColumnDef="expandedDetail">

 {{element.position}}

 {{element.symbol}}

 {{element.name}}

 {{element.weight}}

          {{element.description}}
           -- Wikipedia

  </ng-container>

Body:
You could set your own class on the row and then target it, so as to not mess around with n-depth and complex selectors that break as your html changes.

.my-row {
    background-color: #e4f0ec;
}

.my-row__alternate {
    background-color:#ffffff;
}

<tr mat-row *matRowDef="let element; columns: columnsToDisplay; let i = index"
  class="my-row"
  [class.my-row__alternate]="i % 2">
</tr>


问:
implicit declaration of function ‘gmtime_r’
What do I need to do to make gcc include the declaration of gmtime_r(3) from time.h? Looking at /usr/include/time.h, gmtime_r and localtime_r are inside #ifdef __USE_POSIX.

Do I need to do something to turn __USE_POSIX on, like a command-line option? I'm running with -std=c99 now. I understand that __USE_* macros are not intended to be set directly by user code.

```<code>/* Return the `struct tm' representation of *TIMER
   in Universal Coordinated Time (aka Greenwich Mean Time).  */
extern struct tm *gmtime (const time_t *__timer) __THROW;

/* Return the `struct tm' representation
   of *TIMER in the local timezone.  */
extern struct tm *localtime (const time_t *__timer) __THROW;

#ifdef __USE_POSIX
/* Return the `struct tm' representation of *TIMER in UTC,
   using *TP to store the result.  */
extern struct tm *gmtime_r (const time_t *__restrict __timer,
                struct tm *__restrict __tp) __THROW;

/* Return the `struct tm' representation of *TIMER in local time,
   using *TP to store the result.  */
extern struct tm *localtime_r (const time_t *__restrict __timer,
                   struct tm *__restrict __tp) __THROW;
#endif  /* POSIX */

</code>```

答:
Actually, gmtime_r is not part of the ISO C99 standard, it’s a POSIX extension. To enable that, use std=gnu99 standard.

You can always verify which features are available for which standard on your system by applying technique from this Pixelbeat article:

It can be quite confusing sometimes to know exactly
  what is #defined in your program, and this is especially
  true for glibc's "feature" macros. These macros are documented
  (info libc "feature test macros"), but it's much easier
  to see what's defined directly using "cpp -dD" like:

```<code>$ echo "#include <features.h>" | cpp -dN | grep "#define __USE_"
    #define __USE_ANSI
    #define __USE_POSIX
    #define __USE_POSIX2
    #define __USE_POSIX199309
    #define __USE_POSIX199506
    #define __USE_MISC
    #define __USE_BSD
    #define __USE_SVID

$ echo "#include <features.h>" | cpp -dN -std=c99 | grep "#define __USE_"
    #define __USE_ANSI
    #define __USE_ISOC99
</code>```

Also to see all the predefined macros one can do:

```<code>$ cpp -dM /dev/null
</code>```

Note also for compiler specific macros you can do:

```<code>$ gcc -E -dM - < /dev/null
</code>```

Body:
What do I need to do to make gcc include the declaration of gmtime_r(3) from time.h? Looking at /usr/include/time.h, gmtime_r and localtime_r are inside #ifdef __USE_POSIX.

Do I need to do something to turn __USE_POSIX on, like a command-line option? I'm running with -std=c99 now. I understand that __USE_* macros are not intended to be set directly by user code.

/* Return the `struct tm' representation of *TIMER
   in Universal Coordinated Time (aka Greenwich Mean Time).  */
extern struct tm *gmtime (const time_t *__timer) __THROW;

/* Return the `struct tm' representation
   of *TIMER in the local timezone.  */
extern struct tm *localtime (const time_t *__timer) __THROW;

#ifdef __USE_POSIX
/* Return the `struct tm' representation of *TIMER in UTC,
   using *TP to store the result.  */
extern struct tm *gmtime_r (const time_t *__restrict __timer,
                struct tm *__restrict __tp) __THROW;

/* Return the `struct tm' representation of *TIMER in local time,
   using *TP to store the result.  */
extern struct tm *localtime_r (const time_t *__restrict __timer,
                   struct tm *__restrict __tp) __THROW;
#endif  /* POSIX */

Body:
Actually, gmtime_r is not part of the ISO C99 standard, it’s a POSIX extension. To enable that, use std=gnu99 standard.

You can always verify which features are available for which standard on your system by applying technique from this Pixelbeat article:

It can be quite confusing sometimes to know exactly
  what is #defined in your program, and this is especially
  true for glibc's "feature" macros. These macros are documented
  (info libc "feature test macros"), but it's much easier
  to see what's defined directly using "cpp -dD" like:

$ echo "#include <features.h>" | cpp -dN | grep "#define __USE_"
    #define __USE_ANSI
    #define __USE_POSIX
    #define __USE_POSIX2
    #define __USE_POSIX199309
    #define __USE_POSIX199506
    #define __USE_MISC
    #define __USE_BSD
    #define __USE_SVID

$ echo "#include <features.h>" | cpp -dN -std=c99 | grep "#define __USE_"
    #define __USE_ANSI
    #define __USE_ISOC99

Also to see all the predefined macros one can do:

$ cpp -dM /dev/null

Note also for compiler specific macros you can do:

$ gcc -E -dM - < /dev/null


问:
Counting multidimensional array in PHP
I have a large multidimensional array, which is output into an HTML table. Each second-level array has the same number of values. I need to count how many of the key/value pairs in the first array, which is [247326] in this example. Is there a way to do it without looping through?</p>

```<code>Array
(
    [247326] => Array
        (
            [144784] => 0
            [144785] => 0
            [144787] => 1
            [144815] => 0
            ...
            [144909] => 0
        )

    [247327] => Array
        (
            [144784] => 0
            [144785] => 0
            [144787] => 1
            [144788] => 0
            ...
            [144909] => 0
        )

    [247328] => Array
        (
            [144784] => 0
            [144785] => 0
            [144787] => 1
            [144788] => 0
            ...
            [144789] => 0
        )

)
</code>```

答:
If all of them are the same size, you can just call the last one and check it's size:

count(end($arr));

Title: Counting multidimensional array in PHP

Body:
I have a large multidimensional array, which is output into an HTML table. Each second-level array has the same number of values. I need to count how many of the key/value pairs in the first array, which is [247326] in this example. Is there a way to do it without looping through?

Array
(
    [247326] => Array
        (
            [144784] => 0
            [144785] => 0
            [144787] => 1
            [144815] => 0
            ...
            [144909] => 0
        )

    [247327] => Array
        (
            [144784] => 0
            [144785] => 0
            [144787] => 1
            [144788] => 0
            ...
            [144909] => 0
        )

    [247328] => Array
        (
            [144784] => 0
            [144785] => 0
            [144787] => 1
            [144788] => 0
            ...
            [144789] => 0
        )

)


问:
How to get the last index of a comboBox when size isn't constant?
In an input form, I have two drop down boxes. The option selected in the first one determines what options will populate the second one. There will always be a 'Default' option in the last index of the drop down, but the number of items will change, so 'Default' is not always at a constant index. For the other options, I can just use it's index for other stuff without knowing what it was, but if default is selected I need to do a special action.

My current solution is a bit bulky because I have to check for the index I know will be the default for each case.

```<code>switch( comboBoxOne.SelectedIndex )
{
    case 0:
        if( comboBoxTwo.SelectedIndex == 6 )
            //special action
        break;
    case 1:
    case 2:
        if( comboBoxTwo.SelectedIndex== 4 )
            //special action
        break;
    case 3:
    case 4:
        if( comboBoxTwo.SelectedIndex== 5 )
            //special action
        break;
}
</code>```

I can't use comboBoxTwo.MaxDropDownHeight because that's just a limit for how many items you can potentially have.

NOTE**
I can't set 'Default' to index 0 because it causes the other indices to be wrong, so I'd have to do more work mapping them to the correct index. Also, the way the second options are populated is complicated (there's actually 50 different cases) so default is always appended to the last index. How can I get the last valid item index from a comboBox?

答:
Well, it's actually pretty simple...

Something like this shoudl work :

```<code>if (ComboBox1.GetItemText(this.ComboBox1.SelectedItem)) == "Default")
 {

  ///Your code goes here

 };
</code>```

Body:
In an input form, I have two drop down boxes. The option selected in the first one determines what options will populate the second one. There will always be a 'Default' option in the last index of the drop down, but the number of items will change, so 'Default' is not always at a constant index. For the other options, I can just use it's index for other stuff without knowing what it was, but if default is selected I need to do a special action.

My current solution is a bit bulky because I have to check for the index I know will be the default for each case.

switch( comboBoxOne.SelectedIndex )
{
    case 0:
        if( comboBoxTwo.SelectedIndex == 6 )
            //special action
        break;
    case 1:
    case 2:
        if( comboBoxTwo.SelectedIndex== 4 )
            //special action
        break;
    case 3:
    case 4:
        if( comboBoxTwo.SelectedIndex== 5 )
            //special action
        break;
}

I can't use comboBoxTwo.MaxDropDownHeight because that's just a limit for how many items you can potentially have.

NOTE**
I can't set 'Default' to index 0 because it causes the other indices to be wrong, so I'd have to do more work mapping them to the correct index. Also, the way the second options are populated is complicated (there's actually 50 different cases) so default is always appended to the last index. How can I get the last valid item index from a comboBox?

Body:
Well, it's actually pretty simple...

Something like this shoudl work :

if (ComboBox1.GetItemText(this.ComboBox1.SelectedItem)) == "Default")
 {

  ///Your code goes here

 };


问:
Calculate logarithm of factorial
Here are three methods to calculate logarithm of factorial N: lgN!
The first method uses recursion and store each recursive value in an array
The second method uses recursive without array
The third method uses FOR loop.

After some testing, the third method has best performance, then the second one, the first one has bad performance.

My question is why first method is worse than second one
and though the third method has best performance, its value is different to the others,there is anything wrong in it?

```<code>/**
 * method 1
 * calculate lgN! with recursion and keep every recursive value
     * in an array. It has bad performance, once n reached about 6000, it
     * will throw stackoverflow exception
 * @param a
 * @param n
 * @return
 */
private static double lgNFact1(double[] a ,int n){
    if(n==1)
        a[n-1]=0;
    else
        a[n-1]=Math.log(n) + lgNFact1(a,n-1);
    return a[n-1];
}

/**
 * Method 2 have a little better performance, in my case n can reach 10000!,than throws stackoverflow exception
 * @param n
 * @return
 */
private static double lgNFact2(int n) {
    if(n==1)
        return 0;
    return Math.log(n)+lgNFact2(n-1);
}
/**
     * Method 3, based on logarithm formula, we can use for loop to get lgN!
 * log5!=log5+log4+log3+log2+log1

 * @param n
 * @return
 */
private static double lgNFact3(int n) {
    double sum = 0;
    for(int i=1;i<=n;i++) {
        sum+=Math.log(n);
    }
    return sum;
}
</code>```

Below is test, when n equals 10, we can see the third one is different to above two cases

case1 n=10, result:15.104412573075518

case2 n= 10, result:15.104412573075518

case3 n=10, result:23.025850929940464

答:
Which of method 3 or a tail call variant of method 2 will be most efficient depends on the language. As it stands, method 2 does not use tail call recursion. A simple change to make it use tail call:

```<code>/**
 * Tail call method 2 may or may not throw a stackoverflow exception, depending
 * on whether the language supports tail call optimization.
 */
private static double tailLgNFact2 (int n, double sum=0.0)
{
    if (n <= 1) return sum;
    return tailLgNFact2(n-1, Math.log(n)+sum);
}
</code>```

Based on other questions at stack overflow, Java compilers apparently do not support tail call optimization, but some Java runtimes apparently do. With functional programming languages that do support tail call optimization, the tail call version may have better performance than the looped version.

Title: Calculate logarithm of factorial

Body:
Here are three methods to calculate logarithm of factorial N: lgN!
The first method uses recursion and store each recursive value in an array
The second method uses recursive without array
The third method uses FOR loop.

After some testing, the third method has best performance, then the second one, the first one has bad performance.

My question is why first method is worse than second one
and though the third method has best performance, its value is different to the others,there is anything wrong in it?

/**
 * method 1
 * calculate lgN! with recursion and keep every recursive value
     * in an array. It has bad performance, once n reached about 6000, it
     * will throw stackoverflow exception
 * @param a
 * @param n
 * @return
 */
private static double lgNFact1(double[] a ,int n){
    if(n==1)
        a[n-1]=0;
    else
        a[n-1]=Math.log(n) + lgNFact1(a,n-1);
    return a[n-1];
}

/**
 * Method 2 have a little better performance, in my case n can reach 10000!,than throws stackoverflow exception
 * @param n
 * @return
 */
private static double lgNFact2(int n) {
    if(n==1)
        return 0;
    return Math.log(n)+lgNFact2(n-1);
}
/**
     * Method 3, based on logarithm formula, we can use for loop to get lgN!
 * log5!=log5+log4+log3+log2+log1

 * @param n
 * @return
 */
private static double lgNFact3(int n) {
    double sum = 0;
    for(int i=1;i<=n;i++) {
        sum+=Math.log(n);
    }
    return sum;
}

Below is test, when n equals 10, we can see the third one is different to above two cases

case1 n=10, result:15.104412573075518

case2 n= 10, result:15.104412573075518

case3 n=10, result:23.025850929940464

Body:
Which of method 3 or a tail call variant of method 2 will be most efficient depends on the language. As it stands, method 2 does not use tail call recursion. A simple change to make it use tail call:

/**
 * Tail call method 2 may or may not throw a stackoverflow exception, depending
 * on whether the language supports tail call optimization.
 */
private static double tailLgNFact2 (int n, double sum=0.0)
{
    if (n <= 1) return sum;
    return tailLgNFact2(n-1, Math.log(n)+sum);
}

Based on other questions at stack overflow, Java compilers apparently do not support tail call optimization, but some Java runtimes apparently do. With functional programming languages that do support tail call optimization, the tail call version may have better performance than the looped version.


问:
Dump array in perl
I need to fill some array with data and dump it to the screen.
Here is the code:

```<code>my @a;

@a[0] = 69;
foreach $sibling ($someotherlist){
    my $cha = $sibling->{"id"} * 1;

    if (defined @a[$cha]){
        @a[$cha] = 0;
    }

    @a[$cha] = @a[$cha] + 1;
}
print Dumper(@a);
</code>```

The problem is that it only prints $VAR1 = 69;

It should be something like:

```<code>$VAR1 = {
   0 => 69,
   1 => 30,
   20 => 90
}
</code>```

答:
I've become a big fan of

```<code>use JSON;
warn to_json(\%data,{canonical=>1,pretty=>1});
</code>```

even though it's a mess of typing.

Title: Dump array in perl

Body:
I need to fill some array with data and dump it to the screen.
Here is the code:

my @a;

@a[0] = 69;
foreach $sibling ($someotherlist){
    my $cha = $sibling->{"id"} * 1;

    if (defined @a[$cha]){
        @a[$cha] = 0;
    }

    @a[$cha] = @a[$cha] + 1;
}
print Dumper(@a);

The problem is that it only prints $VAR1 = 69;

It should be something like:

$VAR1 = {
   0 => 69,
   1 => 30,
   20 => 90
}

Body:
I've become a big fan of

use JSON;
warn to_json(\%data,{canonical=>1,pretty=>1});

even though it's a mess of typing.


问:
Conditionally set a URL to redirect to after authentication
In my app, a post author can set an otherwise public post to private. If an unauthenticated user tries to visit that post, they will be prompted to login.

After they authenticate, I want to redirect them back to the original post URL, so they can read that private post.

This behavior is normally handled by Laravel's default auth middleware. However, because the posts are often public, I can't use that in this case.

Here's my current, non-functioning middleware:

```<code>    public function handle($request, Closure $next)
    {
        $post = $request->route('post');
        if ($post->isPrivate()) {
            $request->session()->setPreviousUrl($request->url());
            return redirect()->guest('login');
        }
        return $next($request);
    }
</code>```

My hope is that I can set a custom URL to redirect to (/posts/{id}). However, when I try to login, I'm redirected to my default $redirectTo property (/dashboard).

Is this something that's feasible? Am I even thinking about this in the correct way?

答:
@adam, thanks for the assist!

For anyone else looking, here's my final code:

Middleware:

```<code>    public function handle($request, Closure $next)
    {

        if (auth()->check()) {
            return $next($request);
        }

        $post = $request->route('post');
        if ($post->isPrivate()) {
            $request->session()->setPreviousUrl($request->path());
            return redirect()->guest('login');
        }

        return $next($request);
    }
</code>```

LoginController:

```<code>    protected function authenticated(Request $request, $user)
    {
        if ($request->session()->has('url.intended')) {
            return redirect($request->session()->get('url.intended'));
        }
    }
</code>```

Body:
In my app, a post author can set an otherwise public post to private. If an unauthenticated user tries to visit that post, they will be prompted to login.

After they authenticate, I want to redirect them back to the original post URL, so they can read that private post.

This behavior is normally handled by Laravel's default auth middleware. However, because the posts are often public, I can't use that in this case.

Here's my current, non-functioning middleware:

    public function handle($request, Closure $next)
    {
        $post = $request->route('post');
        if ($post->isPrivate()) {
            $request->session()->setPreviousUrl($request->url());
            return redirect()->guest('login');
        }
        return $next($request);
    }

My hope is that I can set a custom URL to redirect to (/posts/{id}). However, when I try to login, I'm redirected to my default $redirectTo property (/dashboard).

Is this something that's feasible? Am I even thinking about this in the correct way?

Body:
@adam, thanks for the assist!

For anyone else looking, here's my final code:

Middleware:

    public function handle($request, Closure $next)
    {

        if (auth()->check()) {
            return $next($request);
        }

        $post = $request->route('post');
        if ($post->isPrivate()) {
            $request->session()->setPreviousUrl($request->path());
            return redirect()->guest('login');
        }

        return $next($request);
    }

LoginController:

    protected function authenticated(Request $request, $user)
    {
        if ($request->session()->has('url.intended')) {
            return redirect($request->session()->get('url.intended'));
        }
    }


问:
Failed to compile: Cannot find file './containers/App/App' in './src'
I have been having a hard time pushing a React.js app to Heroku because I keep getting a failed to build message with the following amplifying information.

Heroku Build Console:

```<code>-----> Build
       Running build

       > veterinfo@0.1.0 build /tmp/build_2456efea678b82d24203cb2e2c7bcbd5
       > react-scripts build

       Creating an optimized production build...
       Failed to compile.

       ./src/index.js
       Cannot find file './containers/App/App' in './src'.
</code>```

My index.js file:

```<code>import App from './containers/App/App'
import * as serviceWorker from './serviceWorker'
import { BrowserRouter } from 'react-router-dom'
import { Provider } from 'react-redux'
import { createStore, applyMiddleware } from 'redux'
import rootReducer from './reducers'
import { composeWithDevTools } from 'redux-devtools-extension'
import thunk from 'redux-thunk'

const store = createStore(rootReducer, composeWithDevTools(applyMiddleware(thunk)))

const router = (
    <Provider store={store}>
        <BrowserRouter>
            <App />
        </BrowserRouter>
    </Provider>
)
</code>```

File Structure:

```<code>src
  -->containers
    -->App
      -->__snapshots__
      -->App.js
      -->App.scss
      -->App.test.js
  -->index.js
</code>```

I have tried deleting node_modules and reinstalling them,
I have tried clearing the build cache in heroku,
I have tried specifying App.js in the relative path,
I have tried specifying the node version in the yml and package.json files,
The Build passes locally with npm run build,
I have tried just passing in each component into the router's position and I have found that all of the components work but all of the containers do not (could this be a redux issue somehow?)

I am about out of ideas :/

答: Rename containers to Containers and components to Components

Body:
I have been having a hard time pushing a React.js app to Heroku because I keep getting a failed to build message with the following amplifying information.

Heroku Build Console:

-----> Build
       Running build

       > veterinfo@0.1.0 build /tmp/build_2456efea678b82d24203cb2e2c7bcbd5
       > react-scripts build

       Creating an optimized production build...
       Failed to compile.

       ./src/index.js
       Cannot find file './containers/App/App' in './src'.

My index.js file:

import App from './containers/App/App'
import * as serviceWorker from './serviceWorker'
import { BrowserRouter } from 'react-router-dom'
import { Provider } from 'react-redux'
import { createStore, applyMiddleware } from 'redux'
import rootReducer from './reducers'
import { composeWithDevTools } from 'redux-devtools-extension'
import thunk from 'redux-thunk'

const store = createStore(rootReducer, composeWithDevTools(applyMiddleware(thunk)))

const router = (
    <Provider store={store}>
        <BrowserRouter>
            <App />
        </BrowserRouter>
    </Provider>
)

File Structure:

src
  -->containers
    -->App
      -->__snapshots__
      -->App.js
      -->App.scss
      -->App.test.js
  -->index.js

I have tried deleting node_modules and reinstalling them,
I have tried clearing the build cache in heroku,
I have tried specifying App.js in the relative path,
I have tried specifying the node version in the yml and package.json files,
The Build passes locally with npm run build,
I have tried just passing in each component into the router's position and I have found that all of the components work but all of the containers do not (could this be a redux issue somehow?)

I am about out of ideas :/


问:
converting csv to xlsx numbers stored as text issue in mixed type data
I have a large dataset, which consists of both floats, ints, and strings in cells.
My original data set is csv format. when converting to xlsx, I get numbers stored as text error.

I have seen this which gives script if you are manually writing to cells.

as well as this which shows how to convert csv to text.

This is my splicing of the two scripts:

```<code>import csv
import os
import glob
import xlsxwriter

from xlsxwriter import Workbook
workbook = xlsxwriter.Workbook('file.xlsx', {'strings_to_numbers': True})

for csvfile in glob.glob(os.path.join('.', '*.csv')):
    workbook = Workbook(csvfile[:-4] + '.xlsx')
    worksheet = workbook.add_worksheet()
    with open(csvfile, 'rt', encoding='utf8') as f:
        reader = csv.reader(f)
        for r, row in enumerate(reader):
            for c, col in enumerate(row):
                worksheet.write(r, c, col)

workbook.close()
</code>```

Which doesn't work for resolving the numbers stored as text issue. That issue persists.

I want to write numbers as numbers as it is converting the csv to xlsx

答:
The first line of your for loop is overriding the workbook variable that you have defined using the "strings_to_numbers". Try removing that line since it looks like you want to add worksheets to a single workbook, correct?

Based on the examples you linked, it looks like this is just a small copy/paste error :).

Body:
I have a large dataset, which consists of both floats, ints, and strings in cells.
My original data set is csv format. when converting to xlsx, I get numbers stored as text error.

I have seen this which gives script if you are manually writing to cells.

as well as this which shows how to convert csv to text.

This is my splicing of the two scripts:

import csv
import os
import glob
import xlsxwriter

from xlsxwriter import Workbook
workbook = xlsxwriter.Workbook('file.xlsx', {'strings_to_numbers': True})

for csvfile in glob.glob(os.path.join('.', '*.csv')):
    workbook = Workbook(csvfile[:-4] + '.xlsx')
    worksheet = workbook.add_worksheet()
    with open(csvfile, 'rt', encoding='utf8') as f:
        reader = csv.reader(f)
        for r, row in enumerate(reader):
            for c, col in enumerate(row):
                worksheet.write(r, c, col)

workbook.close()

Which doesn't work for resolving the numbers stored as text issue. That issue persists.

I want to write numbers as numbers as it is converting the csv to xlsx


问:
facebook image fetch problem
i added an addthis button to this website:

http://www.merchzilla.com/shop/php/products.php?id=148&SHOP=webshop

now i've got a problem with sharing the site's images with facebook. doesn't work with the addthis button, neither by pasting the link into a wall post.

i wonder why, thanks for your help

答:
Just for reference, all my sites use this line of code in the  tags:

```<code><link rel="image_src" href="site-meta-image.png" />
</code>```

I have never included an absolute image url and they all work absolutely fine with Facebook.

ContentLicense: CC BY-SA 2.5

Title: facebook image fetch problem

Body:
Just for reference, all my sites use this line of code in the <head> tags:

<link rel="image_src" href="site-meta-image.png" />

I have never included an absolute image url and they all work absolutely fine with Facebook.


问:
Form Always submitting with Javascript Confirm
The form was working for a while but I moved some code around and can't revert (A lesson learned), now the code isn't working like it's supposed to.  In a nutshell, User clicks delete button > Delete button sends specific Entry ID to function, Function gets form ID, "Confirms delete", then should send to my delete_entry.php code.  Now, form is always submitting even when I hit "NO" and I added an alert to tell me which route it goes.

I've tried commenting out the form, and it still submits, so I don't think it's explicitly tied to the confirm function (Could be crazy though)

```<code>if ($entry['SubEntryID'] == "0") { ?>
<div id="post"><!-- This is the main post-->
    <div id="main">
        <div id="title">
            <?php echo $entry['EntryID']; ?>
            <?php echo $entry['Title']; ?>
        </div><br />
        <p><?php echo $entry['Body']; ?></p><br />
        <div id="postinfo">
          At: <?php echo $entry['CreateDate']; ?><br/>
          Posted by - <?php echo $entry['UserName']; ?>
        </div>
<!-- Start the form for the delete button -->
<form action="Delete_entry.php" method="post" id="Delete<?php echo $entry['EntryID'];?>">
<input type="hidden" readonly="true" name="EntryID" value="<?php echo $entry['EntryID']; ?>" />
<input type="hidden" readonly="true" name="UserID" value="<?php echo $entry['UserID']; ?>" />
<?php if ($userid == 1 || $userid == $entry['UserID']) { ?>
    <input onclick="confirmdelete('Delete<?php echo $entry['EntryID'];?>')" type="image" src="redx.png" alt="Delete Post" id="btnDelete" value="Delete Post"/>
<?php } ?><br />
        </form>
</div>
</code>```

```<code>function confirmdelete(eid) {

    var retval = confirm("Are you sure you want to delete?" + eid + "?");

    if (retval == true) {
        alert("You said Yes");
        document.getElementById(eid).submit();
        }
    else
    {
        alert("You said No");
    }
}
</code>```

I want the delete button to call the function, the function to respond by submitting the form if it's true, and cancelling the form submission if false. The form page should only get called if confirm is true, and then submit()

答:
Firstly the confirmdelete() is not returning any true/false back so there is no code that stops the form from submission. Secondly, a form will submit anyway even if the function returns false because you have 2 submits (the form and the onclick).

Move the function call to onsubmit() of the form. Remove the onclick because the input type image submits the form by default. Here is the code:

Form:

```<code><form action="Delete_entry.php" method="post"
   id="Delete<?php echo $entry['EntryID'];?>"
   onsubmit="return confirmdelete(<?php echo $entry['EntryID'];?>)">
</code>```

Then the button (onclick removed):

```<code><input type="image" src="redx.png" alt="Delete Post" id="btnDelete" value="Delete Post" />
</code>```

Finally the JavaScript (returns true/false):

```<code>function confirmdelete(eid) {

    if (confirm("Are you sure you want to delete?" + eid + "?")) {
        alert("You said Yes");
        return true;
    }
    else
    {
        alert("You said No");
        return false;
    }
}
</code>```

Body:
The form was working for a while but I moved some code around and can't revert (A lesson learned), now the code isn't working like it's supposed to.  In a nutshell, User clicks delete button > Delete button sends specific Entry ID to function, Function gets form ID, "Confirms delete", then should send to my delete_entry.php code.  Now, form is always submitting even when I hit "NO" and I added an alert to tell me which route it goes.

I've tried commenting out the form, and it still submits, so I don't think it's explicitly tied to the confirm function (Could be crazy though)

if ($entry['SubEntryID'] == "0") { ?>

            <?php echo $entry['EntryID']; ?>
            <?php echo $entry['Title']; ?>

<?php echo $entry['Body']; ?>

          At: <?php echo $entry['CreateDate']; ?>

          Posted by - <?php echo $entry['UserName']; ?>

<form action="Delete_entry.php" method="post" id="Delete<?php echo $entry['EntryID'];?>">
<input type="hidden" readonly="true" name="EntryID" value="<?php echo $entry['EntryID']; ?>" />
<input type="hidden" readonly="true" name="UserID" value="<?php echo $entry['UserID']; ?>" />
<?php if ($userid == 1 || $userid == $entry['UserID']) { ?>
    <input onclick="confirmdelete('Delete<?php echo $entry['EntryID'];?>')" type="image" src="redx.png" alt="Delete Post" id="btnDelete" value="Delete Post"/>
<?php } ?>

        </form>

function confirmdelete(eid) {

    var retval = confirm("Are you sure you want to delete?" + eid + "?");

    if (retval == true) {
        alert("You said Yes");
        document.getElementById(eid).submit();
        }
    else
    {
        alert("You said No");
    }
}

I want the delete button to call the function, the function to respond by submitting the form if it's true, and cancelling the form submission if false. The form page should only get called if confirm is true, and then submit()

Body:
Firstly the confirmdelete() is not returning any true/false back so there is no code that stops the form from submission. Secondly, a form will submit anyway even if the function returns false because you have 2 submits (the form and the onclick).

Move the function call to onsubmit() of the form. Remove the onclick because the input type image submits the form by default. Here is the code:

Form:

<form action="Delete_entry.php" method="post"
   id="Delete<?php echo $entry['EntryID'];?>"
   onsubmit="return confirmdelete(<?php echo $entry['EntryID'];?>)">

Then the button (onclick removed):

<input type="image" src="redx.png" alt="Delete Post" id="btnDelete" value="Delete Post" />

Finally the JavaScript (returns true/false):

function confirmdelete(eid) {

    if (confirm("Are you sure you want to delete?" + eid + "?")) {
        alert("You said Yes");
        return true;
    }
    else
    {
        alert("You said No");
        return false;
    }
}


问:
How to handle an Excel file after data exported to SQL Server?
I have 1000's of Excel files, and the data stored in them needs to be imported into SQL Server. The minimum size of 250 kb to 50mb.

Currently, I am storing the files in the server location and importing each file content to SQL Server. Once the data imported, the physical file still remains in the system for future reference.

But now the file occupies more than 25Gb of our server space. I don't want to delete the source files.

Can anyone help me sort out this problem?

I'm planning to convert the source file into bytes and store those bytes in SQL Server. But I don't know it is the right way of handling it.

答: CSV is the best way for keep your files .You should try convert your .xls to .csv ...That happend to me and I resolved with this method.</p>


问:
How big is too big for an array stored in state with ngrx?
I have an array of around 4000 to 5000 objects that I need to work with throughout the life cycle of my angular app. I use ngrx for state management in this app and would load this data using an effect with the startWith operator. I was wondering how big is too big for an array of objects to be loaded and stored in state in this way.</p>

答:
You could try creating a simple test using stackblitz.com (or similar) and seeing what performance impact 5000 items inside an Ngrx store has.

You can mock a large array with

```<code>Array.from(
  new Array(5000),
  (c, i) => ({ test: `This is test object #${i}` })
)
</code>```

Body:
You could try creating a simple test using stackblitz.com (or similar) and seeing what performance impact 5000 items inside an Ngrx store has.

You can mock a large array with

Array.from(
  new Array(5000),
  (c, i) => ({ test: `This is test object #${i}` })
)


问:
Adding missing date rows to a BigQuery Table
I have a table where 1 of the rows is an integer that represents the rows time. Problem is the table isn't full, there are missing timestamps.

I would like to fill missing values such that every 10 seconds there is a row. I want the rest of the columns to be nuns (later I'll forward fill these nuns).

10 secs is basically 10,000.
If this was python the range would be:

```<code>   range(
      min(table[column]),
      max(table[column]),
      10000
   )
</code>```

答:
If your values are strictly parted by 10 seconds, and there are just some multiples of 10 seconds intervals which are missing, you can go by this approach to fill your data holes:

```<code>WITH minsmax AS (
   SELECT
     MIN(time) AS minval,
     MAX(time) AS maxval
   FROM `dataset.table`
)

SELECT
   IF (d.time <= i.time, d.time, i.time) as time,
   MAX(IF(d.time <= i.time, d.value, NULL)) as value
FROM (
  SELECT time FROM minsmax m, UNNEST(GENERATE_ARRAY(m.minval, m.maxval+100, 100)) AS time
) AS i
LEFT JOIN `dataset.table` d ON 1=1
WHERE ABS(d.time - i.time) >= 100
GROUP BY 1
ORDER BY 1
</code>```

Hope this helps.

Body:
I have a table where 1 of the rows is an integer that represents the rows time. Problem is the table isn't full, there are missing timestamps.

I would like to fill missing values such that every 10 seconds there is a row. I want the rest of the columns to be nuns (later I'll forward fill these nuns).

10 secs is basically 10,000.
If this was python the range would be:

   range(
      min(table[column]),
      max(table[column]),
      10000
   )

Body:
If your values are strictly parted by 10 seconds, and there are just some multiples of 10 seconds intervals which are missing, you can go by this approach to fill your data holes:

WITH minsmax AS (
   SELECT
     MIN(time) AS minval,
     MAX(time) AS maxval
   FROM `dataset.table`
)

SELECT
   IF (d.time <= i.time, d.time, i.time) as time,
   MAX(IF(d.time <= i.time, d.value, NULL)) as value
FROM (
  SELECT time FROM minsmax m, UNNEST(GENERATE_ARRAY(m.minval, m.maxval+100, 100)) AS time
) AS i
LEFT JOIN `dataset.table` d ON 1=1
WHERE ABS(d.time - i.time) >= 100
GROUP BY 1
ORDER BY 1

Hope this helps.


问:
Is this class Threadsafe?
Hi

Is the class below threadsafe?

```<code>class ImmutablePossiblyThreadsafeClass<K, V> {

    private final Map<K, V> map;

    public ImmutablePossiblyThreadsafeClass(final Map<K, V> map) {
        this.map = new HashMap<K, V>();

        for (Entry<K, V> entry : map.entrySet()) {
            this.map.put(entry.getKey(), entry.getValue());
        }
    }

    public V get(K key) {
        return this.map.get(key);
    }
}
</code>```

答:
If this is the whole class definition, i.e. there are no other setter/modifier methods, the usage of the map itself is thread safe:

its initialization and visibility is safeguarded by declaring it final,

the containing class has only a getter, no modifier methods,

the contents of the map are copied from the constructor parameter map, so there can be no outside references through which it can be modified.

(Note though that this refers to the structure of the map only - the individual elements inside the map may still be unsafe.)

Update

Regarding the claim that the class is not guarded from the constructor parameter being concurrently modified during construction, I tend to agree with others (incl. @Bozho) who have already pointed out that

there is no known way to guard against this (not even using a ConcurrentHashMap as @Grundlefleck suggested - I checked the source code and its constructor just calls putAll(), which is not guarded against this either),

it is the caller's responsibility rather than the callee's to ensure that the constructor parameter is not being concurrently modified. In fact, can anyone define the "right" behaviour for processing a constructor parameter which is being concurrently modified? Should the created object contain the original elements in the parameter map, or the latest elements?... If one starts to think about this, IMHO it is not difficult to realize that the only consistent solution is to disallow concurrent modification of the constructor parameter, and this can only be ensured by the caller.

Title: Is this class Threadsafe?

Body:
Hi

Is the class below threadsafe?

class ImmutablePossiblyThreadsafeClass<K, V> {

    private final Map<K, V> map;

    public ImmutablePossiblyThreadsafeClass(final Map<K, V> map) {
        this.map = new HashMap<K, V>();

        for (Entry<K, V> entry : map.entrySet()) {
            this.map.put(entry.getKey(), entry.getValue());
        }
    }

    public V get(K key) {
        return this.map.get(key);
    }
}


问:
How do I make a sorted list of items based on multiple list of sorted items?
I am trying to get a sorted master list from smaller lists. This can be in python or R.

in R, I have

```<code>l1<-c("a","c","d")
l2<-c("a","b","e")
l3<-c("a","c","e")
l4<-c("a","b","c","e")
l5<-c("b","c","d")

m<-unique(c(l1,l2,l3,l4,l5))
</code>```

The output I was expecting is a,b,c,d,e.

In python

```<code>l1=["a","c","d"]
l2=["a","b","e"]
l3=["a","c","e"]
l4=["a","b","c","e"]
l5=["b","c","d"]
</code>```

expected result is ["a","b","c","d","e"]
I started with making a set and going over each list and checking with index but it started getting complex.

Thank you for help.

EDIT:
I think I confused you with having a alphabetically sorted list. Those list items could be random. the real order may not be a,b,c,d,e.

```<code>l1=["e","a"]
l2=["e","b","d"]
l3=["b","d","a"]
</code>```

in this case expected order is ["e","b","d","a"] not ["a","b","d","e"]

for more clarity, think about few people trying to name US states from east to west.

```<code>person 1 says, Florida, Louisiana, Nevada,California.
person 2 says  Alabama, Mississippi, Louisiana, new Mexico, Nevada
person 3 says Florida, Alabama, Texas, New Mexico, California
person 4 says Alabama, Mississippi, Texas, Nevada
person 5 says Mississippi Louisiana, Nevada
</code>```

and I am trying to get right order from information above.

So, here, We will start with Florida, Louisiana, Nevada, California. Now, adding second, it would be, (Alabama, Florida),Louisiana,New Mexico, Nevada, California. Adding 3rd (breaks the tie of Alabama/Florida),Florida, Alabama, Louisiana, Texas, New Mexico, Nevada, California and adding 4th makes Florida, Alabama, (Mississippi/Louisiana), Texas, New Mexico, Nevada, California. adding 5th breaks tie of Mississippi and Louisiana.

答:
My solution has complexity O(n). Other solutions can have O(n log n):

Python: (For R it is similar)

```<code>l1=["a","c","d"]
l2=["a","b","e"]
l3=["a","c","e"]
l4=["a","b","c","e"]
l5=["b","c","d"]

lsts = [l1, l2, l3, l4, l5]

solve = []
for p in range(130):
    solve.append(0)

for lst in lsts:
    for p in lst:
        solve[ord(p)] += 1

for idx, value in enumerate(solve):
    if value != 0:
        print chr(idx)

</code>```

This solution is based in values from table ascii.

For your update:

```<code>l1=["z","c","d"]
l2=["a","b","e"]
l3=["a","c","e"]
l4=["a","b","c","e"]
l5=["b","c","d"]

mySet = set()

mySet.update(l1, l2, l3, l4, l5)

result = sorted(mySet)
print(result)
</code>```

Body:
I am trying to get a sorted master list from smaller lists. This can be in python or R.

in R, I have

l1<-c("a","c","d")
l2<-c("a","b","e")
l3<-c("a","c","e")
l4<-c("a","b","c","e")
l5<-c("b","c","d")

m<-unique(c(l1,l2,l3,l4,l5))

The output I was expecting is a,b,c,d,e.

In python

l1=["a","c","d"]
l2=["a","b","e"]
l3=["a","c","e"]
l4=["a","b","c","e"]
l5=["b","c","d"]

expected result is ["a","b","c","d","e"]
I started with making a set and going over each list and checking with index but it started getting complex.

Thank you for help.

EDIT:
I think I confused you with having a alphabetically sorted list. Those list items could be random. the real order may not be a,b,c,d,e.

l1=["e","a"]
l2=["e","b","d"]
l3=["b","d","a"]

in this case expected order is ["e","b","d","a"] not ["a","b","d","e"]

for more clarity, think about few people trying to name US states from east to west.

person 1 says, Florida, Louisiana, Nevada,California.
person 2 says  Alabama, Mississippi, Louisiana, new Mexico, Nevada
person 3 says Florida, Alabama, Texas, New Mexico, California
person 4 says Alabama, Mississippi, Texas, Nevada
person 5 says Mississippi Louisiana, Nevada

and I am trying to get right order from information above.

So, here, We will start with Florida, Louisiana, Nevada, California. Now, adding second, it would be, (Alabama, Florida),Louisiana,New Mexico, Nevada, California. Adding 3rd (breaks the tie of Alabama/Florida),Florida, Alabama, Louisiana, Texas, New Mexico, Nevada, California and adding 4th makes Florida, Alabama, (Mississippi/Louisiana), Texas, New Mexico, Nevada, California. adding 5th breaks tie of Mississippi and Louisiana.

Body:
My solution has complexity O(n). Other solutions can have O(n log n):

Python: (For R it is similar)

l1=["a","c","d"]
l2=["a","b","e"]
l3=["a","c","e"]
l4=["a","b","c","e"]
l5=["b","c","d"]

lsts = [l1, l2, l3, l4, l5]

solve = []
for p in range(130):
    solve.append(0)

for lst in lsts:
    for p in lst:
        solve[ord(p)] += 1

for idx, value in enumerate(solve):
    if value != 0:
        print chr(idx)

This solution is based in values from table ascii.

For your update:

l1=["z","c","d"]
l2=["a","b","e"]
l3=["a","c","e"]
l4=["a","b","c","e"]
l5=["b","c","d"]

mySet = set()

mySet.update(l1, l2, l3, l4, l5)

result = sorted(mySet)
print(result)


问:
What causes '_tkinter.TclError: can't invoke "update" command: application has been destroyed'?
I've created a chat GUI. The problem is, outside pycharm it's not working properly. By "not working properly" I mean the font it displays is not the one of my choice. Also the size of that font and display box isn't the one I've chosen. The error displayed in the program using this GUI is the one in the title. I think conda may be responsible for this, but I'm not sure. Am I right about this, or is this something else? And also how can I fix this? Thanks in advance!</p>

```<code>import tkinter
window = tkinter.Tk()
window.geometry("430x720")
window.config(bg="#2b2929")

message_box = tkinter.Text(window, height=32, state="disabled")
message_box.pack(side=tkinter.TOP, padx=15,pady=5, fill=tkinter.Y)
message_box.config(bg="#595959", fg="#ffffff", font=("Impact", 12))

input_user = tkinter.StringVar()
text_box = tkinter.Text(window, height=5)
text_box.pack(side=tkinter.BOTTOM,  padx=15, pady=8)
text_box.config(bg="#595959", fg="#ffffff", font=("Impact", 12))

def send_message(event):
    input_get = text_box.get('1.0', tkinter.END)
    if input_get.isspace():
        input_user.set('')
        text_box.delete('1.0', tkinter.END)
        return "break"

    message_box.configure(state='normal')
    message_box.insert(tkinter.INSERT, input_get)
    message_box.see("end")
    message_box.configure(state='disabled')
    input_user.set('')
    text_box.delete('1.0', tkinter.END)
    return "break"

text_box.bind("<Return>", send_message)
window.mainloop()
</code>```

答:
For me it works, I've only indent last rows.

```<code>import tkinter
window = tkinter.Tk()
window.geometry("430x720")
window.config(bg="#2b2929")

message_box = tkinter.Text(window, height=32, state="disabled")
message_box.pack(side=tkinter.TOP, padx=15,pady=5, fill=tkinter.Y)
message_box.config(bg="#595959", fg="#ffffff", font=("Impact", 12))

input_user = tkinter.StringVar()
text_box = tkinter.Text(window, height=5)
text_box.pack(side=tkinter.BOTTOM,  padx=15, pady=8)
text_box.config(bg="#595959", fg="#ffffff", font=("Impact", 12))

def send_message(event):
    input_get = text_box.get('1.0', tkinter.END)
    if input_get.isspace():
        input_user.set('')
        text_box.delete('1.0', tkinter.END)
        return "break"

    message_box.configure(state='normal')
    message_box.insert(tkinter.INSERT, input_get)
    message_box.see("end")
    message_box.configure(state='disabled')
    input_user.set('')
    text_box.delete('1.0', tkinter.END)
    return "break"

text_box.bind("<Return>", send_message)
window.mainloop()
</code>```

Body:
I've created a chat GUI. The problem is, outside pycharm it's not working properly. By "not working properly" I mean the font it displays is not the one of my choice. Also the size of that font and display box isn't the one I've chosen. The error displayed in the program using this GUI is the one in the title. I think conda may be responsible for this, but I'm not sure. Am I right about this, or is this something else? And also how can I fix this? Thanks in advance!

import tkinter
window = tkinter.Tk()
window.geometry("430x720")
window.config(bg="#2b2929")

message_box = tkinter.Text(window, height=32, state="disabled")
message_box.pack(side=tkinter.TOP, padx=15,pady=5, fill=tkinter.Y)
message_box.config(bg="#595959", fg="#ffffff", font=("Impact", 12))

input_user = tkinter.StringVar()
text_box = tkinter.Text(window, height=5)
text_box.pack(side=tkinter.BOTTOM,  padx=15, pady=8)
text_box.config(bg="#595959", fg="#ffffff", font=("Impact", 12))

def send_message(event):
    input_get = text_box.get('1.0', tkinter.END)
    if input_get.isspace():
        input_user.set('')
        text_box.delete('1.0', tkinter.END)
        return "break"

    message_box.configure(state='normal')
    message_box.insert(tkinter.INSERT, input_get)
    message_box.see("end")
    message_box.configure(state='disabled')
    input_user.set('')
    text_box.delete('1.0', tkinter.END)
    return "break"

text_box.bind("<Return>", send_message)
window.mainloop()

Body:
For me it works, I've only indent last rows.

import tkinter
window = tkinter.Tk()
window.geometry("430x720")
window.config(bg="#2b2929")

message_box = tkinter.Text(window, height=32, state="disabled")
message_box.pack(side=tkinter.TOP, padx=15,pady=5, fill=tkinter.Y)
message_box.config(bg="#595959", fg="#ffffff", font=("Impact", 12))

input_user = tkinter.StringVar()
text_box = tkinter.Text(window, height=5)
text_box.pack(side=tkinter.BOTTOM,  padx=15, pady=8)
text_box.config(bg="#595959", fg="#ffffff", font=("Impact", 12))

def send_message(event):
    input_get = text_box.get('1.0', tkinter.END)
    if input_get.isspace():
        input_user.set('')
        text_box.delete('1.0', tkinter.END)
        return "break"

    message_box.configure(state='normal')
    message_box.insert(tkinter.INSERT, input_get)
    message_box.see("end")
    message_box.configure(state='disabled')
    input_user.set('')
    text_box.delete('1.0', tkinter.END)
    return "break"

text_box.bind("<Return>", send_message)
window.mainloop()