问:
Can't fit data to 3d convolutional U-net Keras
I have a problem. I want to make 3D convolutional U-net. For this purpose I'm using Keras.

My data are MRI images from Data Science Bowl 2017 Competition. All MRI's were saved in numpy arrays (all pixels are scaled from 0 to 1) with shape:

```<code>data_ch.shape
(94, 50, 50, 50, 1)
</code>```

94 - patients, 50 MRI slices of 50x50 images, 1 channel:

I want to make 3D Convolutional U-net, so the inputs and outputs of this net are same 3d arrays.
The 3D U-net:

```<code>input_img= Input(shape=(data_ch.shape[1], data_ch.shape[2], data_ch.shape[3], data_ch.shape[4]))
x=Conv3D(filters=8, kernel_size=(3, 3, 3), activation='relu', padding='same')(input_img)
x=MaxPooling3D(pool_size=(2, 2, 2), padding='same')(x)
x=Conv3D(filters=8, kernel_size=(3, 3, 3), activation='relu', padding='same')(x)
x=MaxPooling3D(pool_size=(2, 2, 2), padding='same')(x)

x=UpSampling3D(size=(2, 2, 2))(x)
x=Conv3D(filters=8, kernel_size=(3, 3, 3), activation='relu', padding='same')(x) # PADDING IS NOT THE SAME!!!!!
x=UpSampling3D(size=(2, 2, 2))(x)
x=Conv3D(filters=1, kernel_size=(3, 3, 3), activation='sigmoid')(x)

model=Model(input_img, x)
model.compile(optimizer='adadelta', loss='binary_crossentropy')

model.summary()
Layer (type)                 Output Shape              Param #
=================================================================
input_5 (InputLayer)         (None, 50, 50, 50, 1)     0
_________________________________________________________________
conv3d_27 (Conv3D)           (None, 50, 50, 50, 8)     224
_________________________________________________________________
max_pooling3d_12 (MaxPooling (None, 25, 25, 25, 8)     0
_________________________________________________________________
conv3d_28 (Conv3D)           (None, 25, 25, 25, 8)     1736
_________________________________________________________________
max_pooling3d_13 (MaxPooling (None, 13, 13, 13, 8)     0
_________________________________________________________________
up_sampling3d_12 (UpSampling (None, 26, 26, 26, 8)     0
_________________________________________________________________
conv3d_29 (Conv3D)           (None, 26, 26, 26, 8)     1736
_________________________________________________________________
up_sampling3d_13 (UpSampling (None, 52, 52, 52, 8)     0
_________________________________________________________________
conv3d_30 (Conv3D)           (None, 50, 50, 50, 1)     217
=================================================================
Total params: 3,913
Trainable params: 3,913
Non-trainable params: 0
</code>```

But, when I attempted to fit data to this net:

```<code>model.fit(data_ch, data_ch, epochs=1, batch_size=10, shuffle=True, verbose=1)
</code>```

the program displayed an error:

```<code>ValueError                                Traceback (most recent call last)
C:\Users\Taranov\Anaconda3\lib\site-packages\theano\compile\function_module.py in __call__(self, *args, **kwargs)
    883             outputs =\
--> 884                 self.fn() if output_subset is None else\
    885                 self.fn(output_subset=output_subset)

ValueError: CudaNdarray_CopyFromCudaNdarray: need same dimensions for dim 1, destination=13, source=14

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
<ipython-input-26-b334d38d9608> in <module>()
----> 1 model.fit(data_ch, data_ch, epochs=1, batch_size=10, shuffle=True, verbose=1)

C:\Users\Taranov\Anaconda3\lib\site-packages\keras\engine\training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, **kwargs)
   1496                               val_f=val_f, val_ins=val_ins, shuffle=shuffle,
   1497                               callback_metrics=callback_metrics,
-> 1498                               initial_epoch=initial_epoch)
   1499
   1500     def evaluate(self, x, y, batch_size=32, verbose=1, sample_weight=None):

C:\Users\Taranov\Anaconda3\lib\site-packages\keras\engine\training.py in _fit_loop(self, f, ins, out_labels, batch_size, epochs, verbose, callbacks, val_f, val_ins, shuffle, callback_metrics, initial_epoch)
   1150                 batch_logs['size'] = len(batch_ids)
   1151                 callbacks.on_batch_begin(batch_index, batch_logs)
-> 1152                 outs = f(ins_batch)
   1153                 if not isinstance(outs, list):
   1154                     outs = [outs]

C:\Users\Taranov\Anaconda3\lib\site-packages\keras\backend\theano_backend.py in __call__(self, inputs)
   1156     def __call__(self, inputs):
   1157         assert isinstance(inputs, (list, tuple))
-> 1158         return self.function(*inputs)
   1159
   1160

C:\Users\Taranov\Anaconda3\lib\site-packages\theano\compile\function_module.py in __call__(self, *args, **kwargs)
    896                     node=self.fn.nodes[self.fn.position_of_error],
    897                     thunk=thunk,
--> 898                     storage_map=getattr(self.fn, 'storage_map', None))
    899             else:
    900                 # old-style linkers raise their own exceptions

C:\Users\Taranov\Anaconda3\lib\site-packages\theano\gof\link.py in raise_with_op(node, thunk, exc_info, storage_map)
    323         # extra long error message in that case.
    324         pass
--> 325     reraise(exc_type, exc_value, exc_trace)
    326
    327

C:\Users\Taranov\Anaconda3\lib\site-packages\six.py in reraise(tp, value, tb)
    683             value = tp()
    684         if value.__traceback__ is not tb:
--> 685             raise value.with_traceback(tb)
    686         raise value
    687

C:\Users\Taranov\Anaconda3\lib\site-packages\theano\compile\function_module.py in __call__(self, *args, **kwargs)
    882         try:
    883             outputs =\
--> 884                 self.fn() if output_subset is None else\
    885                 self.fn(output_subset=output_subset)
    886         except Exception:

ValueError: CudaNdarray_CopyFromCudaNdarray: need same dimensions for dim 1, destination=13, source=14
Apply node that caused the error: GpuAlloc(GpuDimShuffle{0,2,x,3,4,1}.0, Shape_i{0}.0, TensorConstant{13}, TensorConstant{2}, TensorConstant{13}, TensorConstant{13}, TensorConstant{8})
Toposort index: 163
Inputs types: [CudaNdarrayType(float32, (False, False, True, False, False, False)), TensorType(int64, scalar), TensorType(int64, scalar), TensorType(int8, scalar), TensorType(int64, scalar), TensorType(int64, scalar), TensorType(int64, scalar)]
Inputs shapes: [(10, 14, 1, 14, 14, 8), (), (), (), (), (), ()]
Inputs strides: [(21952, 196, 0, 14, 1, 2744), (), (), (), (), (), ()]
Inputs values: ['not shown', array(10, dtype=int64), array(13, dtype=int64), array(2, dtype=int8), array(13, dtype=int64), array(13, dtype=int64), array(8, dtype=int64)]
Outputs clients: [[GpuReshape{5}(GpuAlloc.0, MakeVector{dtype='int64'}.0)]]

HINT: Re-running with most Theano optimization disabled could give you a back-trace of when this node was created. This can be done with by setting the Theano flag 'optimizer=fast_compile'. If that does not work, Theano optimizations can be disabled with 'optimizer=None'.
HINT: Use the Theano flag 'exception_verbosity=high' for a debugprint and storage map footprint of this apply node.
</code>```

I tried to follow recommendations and use theano flags:

```<code>import theano
import os
os.environ["THEANO_FLAGS"] = "mode=FAST_RUN,device=gpu,floatX=float32, optimizer='None',exception_verbosity=high"
</code>```

But it still doesn't work.

Could you help me?
Many thanks!

答:
Ok.... that sounds weird, but MaxPooling3D has some kind of bug with padding='same'. So I wrote your code without it, and added an initial padding just to make your dimensions compatible:

```<code>import keras.backend as K

inputShape = (data_ch.shape[1], data_ch.shape[2], data_ch.shape[3], data_ch.shape[4])
paddedShape = (data_ch.shape[1]+2, data_ch.shape[2]+2, data_ch.shape[3]+2, data_ch.shape[4])

#initial padding
input_img= Input(shape=inputShape)
x = Lambda(lambda x: K.spatial_3d_padding(x, padding=((1, 1), (1, 1), (1, 1))),
    output_shape=paddedShape)(input_img) #Lambda layers require output_shape

#your original code without padding for MaxPooling layers (replace input_img with x)
x=Conv3D(filters=8, kernel_size=3, activation='relu', padding='same')(x)
x=MaxPooling3D(pool_size=2)(x)
x=Conv3D(filters=8, kernel_size=3, activation='relu', padding='same')(x)
x=MaxPooling3D(pool_size=2)(x)

x=UpSampling3D(size=2)(x)
x=Conv3D(filters=8, kernel_size=3, activation='relu', padding='same')(x) # PADDING IS NOT THE SAME!!!!!
x=UpSampling3D(size=2)(x)
x=Conv3D(filters=1, kernel_size=3, activation='sigmoid')(x)

model=Model(input_img, x)
model.compile(optimizer='adadelta', loss='binary_crossentropy')
model.summary()
print(model.predict(data_ch)[1])
model.fit(data_ch,data_ch,epochs=1,verbose=2,batch_size=10)
</code>```

Body:
I have a problem. I want to make 3D convolutional U-net. For this purpose I'm using Keras.

My data are MRI images from Data Science Bowl 2017 Competition. All MRI's were saved in numpy arrays (all pixels are scaled from 0 to 1) with shape:

data_ch.shape
(94, 50, 50, 50, 1)

94 - patients, 50 MRI slices of 50x50 images, 1 channel:

I want to make 3D Convolutional U-net, so the inputs and outputs of this net are same 3d arrays.
The 3D U-net:

input_img= Input(shape=(data_ch.shape[1], data_ch.shape[2], data_ch.shape[3], data_ch.shape[4]))
x=Conv3D(filters=8, kernel_size=(3, 3, 3), activation='relu', padding='same')(input_img)
x=MaxPooling3D(pool_size=(2, 2, 2), padding='same')(x)
x=Conv3D(filters=8, kernel_size=(3, 3, 3), activation='relu', padding='same')(x)
x=MaxPooling3D(pool_size=(2, 2, 2), padding='same')(x)

x=UpSampling3D(size=(2, 2, 2))(x)
x=Conv3D(filters=8, kernel_size=(3, 3, 3), activation='relu', padding='same')(x) # PADDING IS NOT THE SAME!!!!!
x=UpSampling3D(size=(2, 2, 2))(x)
x=Conv3D(filters=1, kernel_size=(3, 3, 3), activation='sigmoid')(x)

model=Model(input_img, x)
model.compile(optimizer='adadelta', loss='binary_crossentropy')

model.summary()
Layer (type)                 Output Shape              Param #
=================================================================
input_5 (InputLayer)         (None, 50, 50, 50, 1)     0
_________________________________________________________________
conv3d_27 (Conv3D)           (None, 50, 50, 50, 8)     224
_________________________________________________________________
max_pooling3d_12 (MaxPooling (None, 25, 25, 25, 8)     0
_________________________________________________________________
conv3d_28 (Conv3D)           (None, 25, 25, 25, 8)     1736
_________________________________________________________________
max_pooling3d_13 (MaxPooling (None, 13, 13, 13, 8)     0
_________________________________________________________________
up_sampling3d_12 (UpSampling (None, 26, 26, 26, 8)     0
_________________________________________________________________
conv3d_29 (Conv3D)           (None, 26, 26, 26, 8)     1736
_________________________________________________________________
up_sampling3d_13 (UpSampling (None, 52, 52, 52, 8)     0
_________________________________________________________________
conv3d_30 (Conv3D)           (None, 50, 50, 50, 1)     217
=================================================================
Total params: 3,913
Trainable params: 3,913
Non-trainable params: 0

But, when I attempted to fit data to this net:

model.fit(data_ch, data_ch, epochs=1, batch_size=10, shuffle=True, verbose=1)

the program displayed an error:

ValueError                                Traceback (most recent call last)
C:\Users\Taranov\Anaconda3\lib\site-packages\theano\compile\function_module.py in __call__(self, *args, **kwargs)
    883             outputs =\
--> 884                 self.fn() if output_subset is None else\
    885                 self.fn(output_subset=output_subset)

ValueError: CudaNdarray_CopyFromCudaNdarray: need same dimensions for dim 1, destination=13, source=14

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
<ipython-input-26-b334d38d9608> in <module>()
----> 1 model.fit(data_ch, data_ch, epochs=1, batch_size=10, shuffle=True, verbose=1)

C:\Users\Taranov\Anaconda3\lib\site-packages\keras\engine\training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, **kwargs)
   1496                               val_f=val_f, val_ins=val_ins, shuffle=shuffle,
   1497                               callback_metrics=callback_metrics,
-> 1498                               initial_epoch=initial_epoch)
   1499
   1500     def evaluate(self, x, y, batch_size=32, verbose=1, sample_weight=None):

C:\Users\Taranov\Anaconda3\lib\site-packages\keras\engine\training.py in _fit_loop(self, f, ins, out_labels, batch_size, epochs, verbose, callbacks, val_f, val_ins, shuffle, callback_metrics, initial_epoch)
   1150                 batch_logs['size'] = len(batch_ids)
   1151                 callbacks.on_batch_begin(batch_index, batch_logs)
-> 1152                 outs = f(ins_batch)
   1153                 if not isinstance(outs, list):
   1154                     outs = [outs]

C:\Users\Taranov\Anaconda3\lib\site-packages\keras\backend\theano_backend.py in __call__(self, inputs)
   1156     def __call__(self, inputs):
   1157         assert isinstance(inputs, (list, tuple))
-> 1158         return self.function(*inputs)
   1159
   1160

C:\Users\Taranov\Anaconda3\lib\site-packages\theano\compile\function_module.py in __call__(self, *args, **kwargs)
    896                     node=self.fn.nodes[self.fn.position_of_error],
    897                     thunk=thunk,
--> 898                     storage_map=getattr(self.fn, 'storage_map', None))
    899             else:
    900                 # old-style linkers raise their own exceptions

C:\Users\Taranov\Anaconda3\lib\site-packages\theano\gof\link.py in raise_with_op(node, thunk, exc_info, storage_map)
    323         # extra long error message in that case.
    324         pass
--> 325     reraise(exc_type, exc_value, exc_trace)
    326
    327

C:\Users\Taranov\Anaconda3\lib\site-packages\six.py in reraise(tp, value, tb)
    683             value = tp()
    684         if value.__traceback__ is not tb:
--> 685             raise value.with_traceback(tb)
    686         raise value
    687

C:\Users\Taranov\Anaconda3\lib\site-packages\theano\compile\function_module.py in __call__(self, *args, **kwargs)
    882         try:
    883             outputs =\
--> 884                 self.fn() if output_subset is None else\
    885                 self.fn(output_subset=output_subset)
    886         except Exception:

ValueError: CudaNdarray_CopyFromCudaNdarray: need same dimensions for dim 1, destination=13, source=14
Apply node that caused the error: GpuAlloc(GpuDimShuffle{0,2,x,3,4,1}.0, Shape_i{0}.0, TensorConstant{13}, TensorConstant{2}, TensorConstant{13}, TensorConstant{13}, TensorConstant{8})
Toposort index: 163
Inputs types: [CudaNdarrayType(float32, (False, False, True, False, False, False)), TensorType(int64, scalar), TensorType(int64, scalar), TensorType(int8, scalar), TensorType(int64, scalar), TensorType(int64, scalar), TensorType(int64, scalar)]
Inputs shapes: [(10, 14, 1, 14, 14, 8), (), (), (), (), (), ()]
Inputs strides: [(21952, 196, 0, 14, 1, 2744), (), (), (), (), (), ()]
Inputs values: ['not shown', array(10, dtype=int64), array(13, dtype=int64), array(2, dtype=int8), array(13, dtype=int64), array(13, dtype=int64), array(8, dtype=int64)]
Outputs clients: [[GpuReshape{5}(GpuAlloc.0, MakeVector{dtype='int64'}.0)]]

HINT: Re-running with most Theano optimization disabled could give you a back-trace of when this node was created. This can be done with by setting the Theano flag 'optimizer=fast_compile'. If that does not work, Theano optimizations can be disabled with 'optimizer=None'.
HINT: Use the Theano flag 'exception_verbosity=high' for a debugprint and storage map footprint of this apply node.

I tried to follow recommendations and use theano flags:

import theano
import os
os.environ["THEANO_FLAGS"] = "mode=FAST_RUN,device=gpu,floatX=float32, optimizer='None',exception_verbosity=high"

But it still doesn't work.

Could you help me?
Many thanks!

Body:
Ok.... that sounds weird, but MaxPooling3D has some kind of bug with padding='same'. So I wrote your code without it, and added an initial padding just to make your dimensions compatible:

import keras.backend as K

inputShape = (data_ch.shape[1], data_ch.shape[2], data_ch.shape[3], data_ch.shape[4])
paddedShape = (data_ch.shape[1]+2, data_ch.shape[2]+2, data_ch.shape[3]+2, data_ch.shape[4])

#initial padding
input_img= Input(shape=inputShape)
x = Lambda(lambda x: K.spatial_3d_padding(x, padding=((1, 1), (1, 1), (1, 1))),
    output_shape=paddedShape)(input_img) #Lambda layers require output_shape

#your original code without padding for MaxPooling layers (replace input_img with x)
x=Conv3D(filters=8, kernel_size=3, activation='relu', padding='same')(x)
x=MaxPooling3D(pool_size=2)(x)
x=Conv3D(filters=8, kernel_size=3, activation='relu', padding='same')(x)
x=MaxPooling3D(pool_size=2)(x)

x=UpSampling3D(size=2)(x)
x=Conv3D(filters=8, kernel_size=3, activation='relu', padding='same')(x) # PADDING IS NOT THE SAME!!!!!
x=UpSampling3D(size=2)(x)
x=Conv3D(filters=1, kernel_size=3, activation='sigmoid')(x)

model=Model(input_img, x)
model.compile(optimizer='adadelta', loss='binary_crossentropy')
model.summary()
print(model.predict(data_ch)[1])
model.fit(data_ch,data_ch,epochs=1,verbose=2,batch_size=10)


来源: stackexchange

问:
Using int.TryParse with nullable int
How can I use int.TryParse with nullable int?

I am trying to do something like the following, which doesn't compile, obviously.

int? nr1 = int.TryParse(str1, out nr1) ? nr1 : null;

What is the correct way to achieve it?

答:
int.tryParse will change the referenced out variable, and return a boolean, which is true if the passed argument could be parsed as an integer.

You're after something like this :

```<code>int? int1;
int tempVal;
if (!int.TryParse(str1, out tempVal))
{
    int1 = null;
}
else
{
    int1 = tempVal;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Using int.TryParse with nullable int

Body:
int.tryParse will change the referenced out variable, and return a boolean, which is true if the passed argument could be parsed as an integer.

You're after something like this :

int? int1;
int tempVal;
if (!int.TryParse(str1, out tempVal))
{
    int1 = null;
}
else
{
    int1 = tempVal;
}


问:
<XSL:for-each> skip nodes with specific values
Still having a hard time grasping some of the harder templates any help would be great.

Right now I am using a simple for-each loop that sorts and shows the data in a table. I want to do the same thing but skip over all the nodes where "State" is = to "Talking Out" below is my current style sheet and below that is my XML. I was thinking I could add a for-each inside of the current loop that ignores the nodes that meet my criteria. I am escaping single quotes since it is part of a larger php script.

```<code><?xml version="1.0" encoding="ISO-8859-1"?>

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
  <html>
  <body>
    <table cellpadding="3" cellspacing="0" width="390">
      <tr>
        <th style="text-align:left;"><span style="font:20px arial; font-weight:bold;">Agent Name</span></th>
        <th style="text-align:center;"><span style="font:20px arial; font-weight:bold;">State</span></th>
        <th style="text-align:center;"><span style="font:20px arial; font-weight:bold;">Time</span></th>
      </tr>
      <xsl:for-each select="NewDataSet/AgentSales">
<tr>
 <xsl:if test="(position() mod 2 = 1)">
    <xsl:attribute name="bgcolor">#cccccc</xsl:attribute>
    </xsl:if>

 <xsl:if test="AgentSales[State=\'Talking Out\']">

    </xsl:if>

        <td style="text-align:left;"><span style="font:14px arial; font-weight:bold;"><xsl:value-of select="AgentName"/></span></td>
        <td style="text-align:center;"><span style="font:14px arial; font-weight:bold;"><xsl:value-of select="State"/></span></td>
    <td style="text-align:center;"><span style="font:14px arial; font-weight:bold;"><xsl:value-of select="time"/></span></td>
</tr>

      </xsl:for-each>
    </table>
  </body>
  </html>
</xsl:template>
</xsl:stylesheet>
</code>```

here is my XML

```<code><?xml version="1.0" encoding="ISO-8859-1"?>
<NewDataSet>
  <AgentSales>
    <AgentName>MCCALLISTER AARON</AgentName>
    <State>Talking Out</State>
    <Reason />
    <time>9</time>
  </AgentSales>
  <AgentSales>
    <AgentName>APPELHANS BARRY</AgentName>
    <State>Talking Out</State>
    <Reason />
    <time>1</time>
  </AgentSales>
  <AgentSales>
    <AgentName>ARREDONDO KARLA</AgentName>
    <State>Talking Out</State>
    <Reason />
    <time>0</time>
  </AgentSales>
  <AgentSales>
    <AgentName>WOOTERS CHAD</AgentName>
    <State>Talking In</State>
    <Reason />
    <time>5</time>
  </AgentSales>
  <AgentSales>
    <AgentName>LANDINI EUGENE</AgentName>
    <State>Not Ready</State>
    <Reason>TRAINING</Reason>
    <time>16</time>
  </AgentSales>
  <AgentSales>
    <AgentName>BROWN EYES JONETTE</AgentName>
    <State>Not Ready</State>
    <Reason>TRAINING</Reason>
    <time>13</time>
  </AgentSales>
</NewDataSet>
</code>```

答:
Right now I am using a simple for-each
  loop that sorts and shows the data in
  a table. I want to do the same thing
  but skip over all the nodes where
  "State" is = to "Talking Out"

Just replace:

```<code>  <xsl:for-each select="NewDataSet/AgentSales">
</code>```

with

```<code><xsl:for-each select="NewDataSet/AgentSales[not(State='Talking Out')]">
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Still having a hard time grasping some of the harder templates any help would be great.

Right now I am using a simple for-each loop that sorts and shows the data in a table. I want to do the same thing but skip over all the nodes where "State" is = to "Talking Out" below is my current style sheet and below that is my XML. I was thinking I could add a for-each inside of the current loop that ignores the nodes that meet my criteria. I am escaping single quotes since it is part of a larger php script.

<?xml version="1.0" encoding="ISO-8859-1"?>

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">

        Agent Name
        State
        Time

      <xsl:for-each select="NewDataSet/AgentSales">

 <xsl:if test="(position() mod 2 = 1)">
    <xsl:attribute name="bgcolor">#cccccc</xsl:attribute>
    </xsl:if>

 <xsl:if test="AgentSales[State=\'Talking Out\']">

    </xsl:if>

        <xsl:value-of select="AgentName"/>
        <xsl:value-of select="State"/>
    <xsl:value-of select="time"/>

      </xsl:for-each>

</xsl:template>
</xsl:stylesheet>

here is my XML

<?xml version="1.0" encoding="ISO-8859-1"?>
<NewDataSet>
  <AgentSales>
    <AgentName>MCCALLISTER AARON</AgentName>
    <State>Talking Out</State>
    <Reason />
    <time>9</time>
  </AgentSales>
  <AgentSales>
    <AgentName>APPELHANS BARRY</AgentName>
    <State>Talking Out</State>
    <Reason />
    <time>1</time>
  </AgentSales>
  <AgentSales>
    <AgentName>ARREDONDO KARLA</AgentName>
    <State>Talking Out</State>
    <Reason />
    <time>0</time>
  </AgentSales>
  <AgentSales>
    <AgentName>WOOTERS CHAD</AgentName>
    <State>Talking In</State>
    <Reason />
    <time>5</time>
  </AgentSales>
  <AgentSales>
    <AgentName>LANDINI EUGENE</AgentName>
    <State>Not Ready</State>
    <Reason>TRAINING</Reason>
    <time>16</time>
  </AgentSales>
  <AgentSales>
    <AgentName>BROWN EYES JONETTE</AgentName>
    <State>Not Ready</State>
    <Reason>TRAINING</Reason>
    <time>13</time>
  </AgentSales>
</NewDataSet>

Body:
Right now I am using a simple for-each
  loop that sorts and shows the data in
  a table. I want to do the same thing
  but skip over all the nodes where
  "State" is = to "Talking Out"

Just replace:

  <xsl:for-each select="NewDataSet/AgentSales">

with

<xsl:for-each select="NewDataSet/AgentSales[not(State='Talking Out')]">


问:
How to make a div grow with content?
Pertaining to html, how do I make a div container grow with the content instead of manually defining a width and height.

```<code><div id="container">
  <div id="logo">
    <img src="someimage.png"/>
  </div>
</div>
</code>```

No matter what the dimensions of logo are, container does not grow with it. :(
How would I fix this, or can it be fixed?

答:
Use the magical css property called "flex", it is really amazing </p>

```<code>yourDiv{
display:flex;
}
</code>```

<p>Just make sure that the children are not position: absolute because this will not work with flex. </p>

ContentLicense: CC BY-SA 4.0

Title: How to make a div grow with content?

Body:
Pertaining to html, how do I make a div container grow with the content instead of manually defining a width and height.

No matter what the dimensions of logo are, container does not grow with it. :(
How would I fix this, or can it be fixed?

Body:
Use the magical css property called "flex", it is really amazing

yourDiv{
display:flex;
}

Just make sure that the children are not position: absolute because this will not work with flex.


问:
Delete duplicate rows based on a condition
I have a table that has ID and EventDate. It has duplicate rows as I used Union of two tables. Now I got to have the rows with the minimum Eventdate and remove the other duplicates.

the table for eg

ID  | Date

--- | ---

1     | 10/27/1993

1      | 10/27/1994

2      | 10/17/1993

2      | 08/15/1993

Delete duplicate rows based on condition

答:
If we talk about Firebird it is enough</p>

```<code>DELETE FROM table1 t1_1
WHERE EXISTS(
  SELECT t1_2.id FROM table1 t1_2 WHERE t1_1.EventDate>t1_2.EventDate
);
</code>```

Body:
If we talk about Firebird it is enough

DELETE FROM table1 t1_1
WHERE EXISTS(
  SELECT t1_2.id FROM table1 t1_2 WHERE t1_1.EventDate>t1_2.EventDate
);


问:
C++ Integer Division to Float
My C++ program takes in three integer inputs and does some computations including division. At first, the end result was not a decimal. After searching a little on Stack Overflow (Dividing two integers to produce a float result), I found out that I'm supposed to add a (float), like this:

```<code>int a;
int b;
float c;

a = 5;
b = 2;

c = (float)a / b;
</code>```

So I tried that but I ended up with my result being -nan(ind). First off, what does that mean? And second, how do I make my program work?

Here is the math I am trying to do in my program by the way.

```<code>int v;
int e;
int a;
float r;

r = ((float)e - v) / ((float)a / 1000);
</code>```

Edit: Sorry, my mistake. I meant to type 1000 in the second example, not c.

答:
Try converting each variable to float, and see if that fixes the problem. Also, in your second example, you never initialize your variables, which causes an error because their value is undefined, it could be anything. You also forgot to include the variable c.

See if this throws an error:

```<code>int v = 1;
int e = 1;
int a = 1;
int c = 1;
float r;

r = ((float)e - (float)v) / (float)a / (float)c;
</code>```

Also, for converting between types, I would recommend you use 'static_cast<type>(variable)' instead of '(type)variable'. It is the recommended way to cast types in c++, and it also makes conversions easier to spot when debugging. Your code would look like this:

```<code>int v = 1;
int e = 1;
int a = 1;
int c = 1;
float r;

r = (static_cast<float>(e) - static_cast<float>(v)) / static_cast<float>(a) / static_cast<float>(c);
</code>```

Title: C++ Integer Division to Float

Body:
My C++ program takes in three integer inputs and does some computations including division. At first, the end result was not a decimal. After searching a little on Stack Overflow (Dividing two integers to produce a float result), I found out that I'm supposed to add a (float), like this:

int a;
int b;
float c;

a = 5;
b = 2;

c = (float)a / b;

So I tried that but I ended up with my result being -nan(ind). First off, what does that mean? And second, how do I make my program work?

Here is the math I am trying to do in my program by the way.

int v;
int e;
int a;
float r;

r = ((float)e - v) / ((float)a / 1000);

Edit: Sorry, my mistake. I meant to type 1000 in the second example, not c.

Body:
Try converting each variable to float, and see if that fixes the problem. Also, in your second example, you never initialize your variables, which causes an error because their value is undefined, it could be anything. You also forgot to include the variable c.

See if this throws an error:

int v = 1;
int e = 1;
int a = 1;
int c = 1;
float r;

r = ((float)e - (float)v) / (float)a / (float)c;

Also, for converting between types, I would recommend you use 'static_cast<type>(variable)' instead of '(type)variable'. It is the recommended way to cast types in c++, and it also makes conversions easier to spot when debugging. Your code would look like this:

int v = 1;
int e = 1;
int a = 1;
int c = 1;
float r;

r = (static_cast<float>(e) - static_cast<float>(v)) / static_cast<float>(a) / static_cast<float>(c);


问:
Trying to get a sorted array from object values
Basically I'm trying to copy the first answer on this page (Sorting object properties based on value), and sort my object into an array. But I get this error message:

TypeError: Cannot convert undefined or null to object

What is wrong?

  const denom = {
  'ONE HUNDRED': 100.00,
  'TWENTY' : 20.00,
  'TEN' : 10.00,
  'FIVE': 5.00,
  'ONE' : 1.00,
  'QUARTER': 0.25,
  'DIME': 0.10,
  'NICKEL': 0.05,
  'PENNY': 0.01
  };

  const denomSorted = Object.keys(denom[0]).sort((a, b) => denom[0][b] - denom[0][a]);

denomSorted.forEach(x => console.log(x + ': ' + denom[0][x]));```
<pre class="snippet-code-html lang-html prettyprint-override"><code>
  </code>```

答:
you are missing those [] brackets .

  const denom = [{
  'ONE HUNDRED': 100.00,
  'TWENTY' : 20.00,
  'TEN' : 10.00,
  'FIVE': 5.00,
  'ONE' : 1.00,
  'QUARTER': 0.25,
  'DIME': 0.10,
  'NICKEL': 0.05,
  'PENNY': 0.01
  }];

  const denomSorted = Object.keys(denom[0]).sort((a, b) => denom[0][b] - denom[0][a]);

denomSorted.forEach(x => console.log(x + ': ' + denom[0][x]));```
<pre class="snippet-code-html lang-html prettyprint-override"><code>
  </code>```


问:
How to read a repetead tag in a xml with pentaho?
I am trying to load and XML file with pentaho:

```<code><?xml version="1.0" encoding="ISO-8859-1"?>
<scapplication>
<heading>
  <dispatchingcode>GML</dispatchingcode>
  <version>001</version>
  <dispatchingcompany>1232</dispatchingcompany>
</heading>
<F456>
  <reqcode>0019682125</reqcode>
  <comreferencenum>30104</comreferencenum>
  <responsedate>2017-06-29</responsedate>
</F456>
<F456>
  <reqcode>0019657723</reqcode>
  <comreferencenum>29676</comreferencenum>
  <responsedate>2017-06-29</responsedate>
</F456>
</scapplication>
</code>```

The main problem that I found loading this with pentaho is that F456 tag should be iterated in the load.
This means that I need to detect every node inside every F456 node because later I will load this in two different rows in a table output statement.

How can be readed both tags in a loop with pentaho?
I guess that if both tags were inside another one it would be easy but I do not have a tag above these two, so I do not know how to load with GET DATA FROM XML Step

I tried seeting F456 as a field in the step and set repeat option as Y. But it does not works...

答: @Maik You can use stax parser and load into tables using switch and de-normalizer. Preview the data in stax parser component . Understand xml_element_id, xml_parent_element_id in preview. Let me know if you want any help on this. Design Parent and child tables using xml_element_id, xml_parent_element_id. Identify the column which you want to keep in Parent and child both. Then update the values i child tables using xml_element_id, xml_parent_element_id.</p>

Body:
I am trying to load and XML file with pentaho:

<?xml version="1.0" encoding="ISO-8859-1"?>
<scapplication>
<heading>
  <dispatchingcode>GML</dispatchingcode>
  <version>001</version>
  <dispatchingcompany>1232</dispatchingcompany>
</heading>
<F456>
  <reqcode>0019682125</reqcode>
  <comreferencenum>30104</comreferencenum>
  <responsedate>2017-06-29</responsedate>
</F456>
<F456>
  <reqcode>0019657723</reqcode>
  <comreferencenum>29676</comreferencenum>
  <responsedate>2017-06-29</responsedate>
</F456>
</scapplication>

The main problem that I found loading this with pentaho is that F456 tag should be iterated in the load.
This means that I need to detect every node inside every F456 node because later I will load this in two different rows in a table output statement.

How can be readed both tags in a loop with pentaho?
I guess that if both tags were inside another one it would be easy but I do not have a tag above these two, so I do not know how to load with GET DATA FROM XML Step

I tried seeting F456 as a field in the step and set repeat option as Y. But it does not works...


问:
Get Bitcoin historical data in the interval of minutes
Can anybody tell me where can I download Bitcoin historical data? I'm able to find the daily price. But that is not enough for my project. It will be better if I can have the price data in the interval of minutes.</p>

答:
You can get thousands of historical datasets from https://spreadstreet.io.

All datasets are available as a tab-delimited, CSV file. The datasets are a mix between raw tick data, OHLCV, spreads, mining and economic statistics. They can be used for backtesting, analysis, and charting.

Here is an example dataset. This is from Poloniex, and is the 30 min timeframe. We have lower time frames, but the files are larger than I wanted to link in this question.

Disclaimer: I am the founder of Spreadstreet.io


问:
GA event tracking code not working
We placed the event tracking code on the form on the below page, looking for it to fire when the form is submitted.

https://www.bobbarker.com/customer/account/create/

The code can be seen below:

```<code><script type="text/javascript">
        //<![CDATA[
        var dataForm = new VarienForm('form-validate', true);

        Form.getElements('form-validate').each(function(element) {
            element.setAttribute('autocomplete', 'off');
        });

        $('form-validate').observe('submit', function(e) {
            ga('send', 'event', 'form', 'submit', 'request an account');
        });
        //]]>
    </script>
</code>```

We're not seeing events come through to GA.

Thanks,
Jacob

答:
Before use event track, try create a ga session in end of your page, like this:

ga('create', 'UA-XXXXX-Y', 'auto');
</script>
```

Title: GA event tracking code not working

Body:
We placed the event tracking code on the form on the below page, looking for it to fire when the form is submitted.

https://www.bobbarker.com/customer/account/create/

The code can be seen below:

We're not seeing events come through to GA.

Thanks,
Jacob

Body:
Before use event track, try create a ga session in end of your page, like this:

ga('create', 'UA-XXXXX-Y', 'auto');
</script>
</body>


问:
Docker for mac 1.12.0: how to connect to host from container
I've updated docker on my os x 10.10, so it's now using os x native virtualization. However, I've found it tricky to connect to my host machine from within my nginx container. I tried this:

/sbin/ip route|awk '/default/ { print $3 }'

And got the answer:

172.17.0.1

Then I used this ip in docker-compose.yml:

```<code>  extra_hosts:
    - "master:172.17.0.1"
</code>```

But nonetheless I keep getting errors:

172.17.0.1 - - [21/Jul/2016:09:33:46 +0000] "GET /api HTTP/1.1" 502 575      "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36" "-"
2016/07/21 09:33:46 [error] 7#7: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 172.17.0.1, server: soc-credit.ru, request: "GET /api HTTP/1.1", upstream: "http://172.17.0.5:8080/api", host: "localhost"

Please note this part: client: 172.17.0.1. Since I've made request from host machine, it proves that ip I got in first step was correct. But connection wasn't established anyway.

I want to stress out that I have a problem connecting FROM WITHIN container TO host and not vice versa.

What am I doing wrong? Thank you!

答:
Had the same problem and being inexperienced in Docker and network configurations I struggled to get the various proposed solutions working. However since this update to Docker for Mac:
Docker Community Edition 17.06.0-ce-mac18, 2017-06-28 (stable)

I've found using the 'experimental' hostname docker.for.mac.localhost
allows me to contact services running on the Mac host from within a container. Very useful for dev!

Body:
I've updated docker on my os x 10.10, so it's now using os x native virtualization. However, I've found it tricky to connect to my host machine from within my nginx container. I tried this:

/sbin/ip route|awk '/default/ { print $3 }'

And got the answer:

172.17.0.1

Then I used this ip in docker-compose.yml:

  extra_hosts:
    - "master:172.17.0.1"

But nonetheless I keep getting errors:

172.17.0.1 - - [21/Jul/2016:09:33:46 +0000] "GET /api HTTP/1.1" 502 575      "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36" "-"
2016/07/21 09:33:46 [error] 7#7: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 172.17.0.1, server: soc-credit.ru, request: "GET /api HTTP/1.1", upstream: "http://172.17.0.5:8080/api", host: "localhost"

Please note this part: client: 172.17.0.1. Since I've made request from host machine, it proves that ip I got in first step was correct. But connection wasn't established anyway.

I want to stress out that I have a problem connecting FROM WITHIN container TO host and not vice versa.

What am I doing wrong? Thank you!


问:
How do i use multiple files to access them in viewController?
i am trying to programically create a Stackview that contains a TextField saying "Hello world"

```<code>class stackview: UIViewController {

    func setupview() {

        // Define TextField
        let Textfield = UITextView()
        Textfield.allowsEditingTextAttributes = false
        Textfield.translatesAutoresizingMaskIntoConstraints = false
        Textfield.widthAnchor.constraint(equalToConstant: 70).isActive = true
        Textfield.heightAnchor.constraint(equalToConstant: 70).isActive = true
        Textfield.isEditable = false

        // Define the stackview, and setting up the attributes
        let stackview = UIStackView()
        stackview.axis = UILayoutConstraintAxis.horizontal
        stackview.distribution = UIStackViewDistribution.equalCentering
        stackview.alignment = UIStackViewAlignment.center
        stackview.spacing = 5
        stackview.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(stackview)
        stackview.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        stackview.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true

        Textfield.text = "hello"

        view.addSubview(Textfield)

    }
</code>```

in my Viewcontroller.swift i want to access this function in ViewDidLoad

```<code>class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        var level = stackview()
        level.setupview()
    }
</code>```

but the Hello world dosnt seem to appear!

答:
You are mixing up View Controllers with Views, subViews and StackViews...

Look at this approach:

```<code>class ViewController: UIViewController {

    // define a UITextView and its properties
    var theTextView: UITextView = {
        let textView = UITextView()
        textView.allowsEditingTextAttributes = false
        textView.translatesAutoresizingMaskIntoConstraints = false
        textView.widthAnchor.constraint(equalToConstant: 70).isActive = true
        textView.heightAnchor.constraint(equalToConstant: 70).isActive = true
        textView.isEditable = false
        return textView
    }()

    // define a UIStackView and its properties
    var theStackView: UIStackView = {
        let stackview = UIStackView()
        stackview.axis = UILayoutConstraintAxis.horizontal
        stackview.distribution = UIStackViewDistribution.equalCentering
        stackview.alignment = UIStackViewAlignment.center
        stackview.spacing = 5
        stackview.translatesAutoresizingMaskIntoConstraints = false
        return stackview
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        // add the Stack View to this view - must be done before adding relative constraints
        self.view.addSubview(theStackView)

        // add relative constraints to the Stack View
        theStackView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        theStackView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true

        // set the text of the Text View
        theTextView.text = "hello"

        // add the Text View as an Arranged Subview of the Stack View
        theStackView.addArrangedSubview(theTextView)
    }

}
</code>```

Now, later in your code, you can reference the Stack View with the theStackView variable / property - for adding additional arranged subviews, for example:

```<code>theStackView.addArrangedSubview(anotherTextView)
theStackView.addArrangedSubview(anImageView)
theStackView.addArrangedSubview(aButton)
</code>```

and you can access the Text View with the theTextView variable / property - for changing the text, for example.

Body:
i am trying to programically create a Stackview that contains a TextField saying "Hello world"

class stackview: UIViewController {

    func setupview() {

        // Define TextField
        let Textfield = UITextView()
        Textfield.allowsEditingTextAttributes = false
        Textfield.translatesAutoresizingMaskIntoConstraints = false
        Textfield.widthAnchor.constraint(equalToConstant: 70).isActive = true
        Textfield.heightAnchor.constraint(equalToConstant: 70).isActive = true
        Textfield.isEditable = false

        // Define the stackview, and setting up the attributes
        let stackview = UIStackView()
        stackview.axis = UILayoutConstraintAxis.horizontal
        stackview.distribution = UIStackViewDistribution.equalCentering
        stackview.alignment = UIStackViewAlignment.center
        stackview.spacing = 5
        stackview.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(stackview)
        stackview.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        stackview.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true

        Textfield.text = "hello"

        view.addSubview(Textfield)

    }

in my Viewcontroller.swift i want to access this function in ViewDidLoad

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        var level = stackview()
        level.setupview()
    }

but the Hello world dosnt seem to appear!

Body:
You are mixing up View Controllers with Views, subViews and StackViews...

Look at this approach:

class ViewController: UIViewController {

    // define a UITextView and its properties
    var theTextView: UITextView = {
        let textView = UITextView()
        textView.allowsEditingTextAttributes = false
        textView.translatesAutoresizingMaskIntoConstraints = false
        textView.widthAnchor.constraint(equalToConstant: 70).isActive = true
        textView.heightAnchor.constraint(equalToConstant: 70).isActive = true
        textView.isEditable = false
        return textView
    }()

    // define a UIStackView and its properties
    var theStackView: UIStackView = {
        let stackview = UIStackView()
        stackview.axis = UILayoutConstraintAxis.horizontal
        stackview.distribution = UIStackViewDistribution.equalCentering
        stackview.alignment = UIStackViewAlignment.center
        stackview.spacing = 5
        stackview.translatesAutoresizingMaskIntoConstraints = false
        return stackview
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        // add the Stack View to this view - must be done before adding relative constraints
        self.view.addSubview(theStackView)

        // add relative constraints to the Stack View
        theStackView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        theStackView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true

        // set the text of the Text View
        theTextView.text = "hello"

        // add the Text View as an Arranged Subview of the Stack View
        theStackView.addArrangedSubview(theTextView)
    }

}

Now, later in your code, you can reference the Stack View with the theStackView variable / property - for adding additional arranged subviews, for example:

theStackView.addArrangedSubview(anotherTextView)
theStackView.addArrangedSubview(anImageView)
theStackView.addArrangedSubview(aButton)

and you can access the Text View with the theTextView variable / property - for changing the text, for example.


问:
Stuck at "A merge operation in progress"

Steps

In Visual Studio

Pulled from remote repo

1 merge conflict

Merged manually, clicked 'Accept merge'

Result

Message: "A merge operation is in progress in the ... repository. Commit your changes to complete the merge operation."

However, there is nothing to commit: There are 0 pending changes, no actions apart from Abort seem to be possible.

Screenshot: https://pbs.twimg.com/media/DBOeRIiXsAEbnLP.jpg

Context

Remote git repo is hosted in Visual Studio Team Services

Visual Studio 2017 with all updates

答:
I had a very similar problem with one of my projects which gave me the same TFS message in Visual Studio 2017. I was also using git. In my case I needed to manually add a comment to the commit before posting the merge. Since I had to manually merge the conflicts, a comment was needed rather than the auto-populated message that takes place on a merge without conflicts.

I'm well aware that commits need comments but if I recall correctly, VS 2015 would auto-populate the comment on a merge, even if you manually fixed any merge issues.  Regardless, in VS 2017 you will need to add a commit comment when there are resolved conflicts.


问:
Data Driven Test using Groovy Scripting
I am using the below code to set the Property Values from Excel file to my Property Step and then pass it to the testcase.

When I run the Groovy code, the value from the last cell of the excel comes to the property step.

Please help me out to set the properties correctly.

```<code>import jxl.*

Workbook wb = Workbook.getWorkbook(new File("C:\\Users\\naraysa1\\Desktop\\Address_Doctor\\DataSource_Address_Validate\\Data_AddressValidate.xls"))
Sheet sh = wb.getSheet(0)
RowCount = sh.getRows();
ColumnCount = sh.getColumns();
for (i=1;i<RowCount;i++)
{
    for (j=0;j<ColumnCount;j++)
    {
        def c = sh.getCell(j, i).getContents();
        log.info c

        testRunner.testCase.getTestStepByName("Properties_Address").setPropertyValue("ID", c)
        testRunner.testCase.getTestStepByName("Properties_Address").setPropertyValue("AddressLine1", c)
        testRunner.testCase.getTestStepByName("Properties_Address").setPropertyValue("AddressLine2", c)
        testRunner.testCase.getTestStepByName("Properties_Address").setPropertyValue("AddressLine3", c)
        testRunner.testCase.getTestStepByName("Properties_Address").setPropertyValue("City", c)
        testRunner.testCase.getTestStepByName("Properties_Address").setPropertyValue("State ", c)
        testRunner.testCase.getTestStepByName("Properties_Address").setPropertyValue("PostalCode", c)
        testRunner.testCase.getTestStepByName("Properties_Address").setPropertyValue("Country", c)

        def TestStep =  testRunner.runTestStepByName("Search_Address")
    }
}
</code>```

答:
in your script you assign the value from each cell of excel into all properties and executing teststep for each cell.

probably you want to map cell values from one row to different properties and execute test for each row.

define the following map

(you can initialize this map from zero row of your excel table)

```<code>def header=[
  0:'ID', //means put cell0 into property `ID`
  1:'AddressLine1',
  2:'AddressLine2',
  3:'AddressLine3',
  4:'City',
  ...
]
</code>```

and now your cycle will look like:

```<code>for (i=1;i<RowCount;i++)
{
    for (j=0;j<ColumnCount;j++)
    {
        def pname = header[j]
        if(pname){
            def c = sh.getCell(j, i).getContents();
            testRunner.testCase.getTestStepByName("Properties_Address").setPropertyValue(pname, c)
        }
    }
    def TestStep =  testRunner.runTestStepByName("Search_Address")
}
</code>```

Title: Data Driven Test using Groovy Scripting

Body:
I am using the below code to set the Property Values from Excel file to my Property Step and then pass it to the testcase.

When I run the Groovy code, the value from the last cell of the excel comes to the property step.

Please help me out to set the properties correctly.

import jxl.*

Workbook wb = Workbook.getWorkbook(new File("C:\\Users\\naraysa1\\Desktop\\Address_Doctor\\DataSource_Address_Validate\\Data_AddressValidate.xls"))
Sheet sh = wb.getSheet(0)
RowCount = sh.getRows();
ColumnCount = sh.getColumns();
for (i=1;i<RowCount;i++)
{
    for (j=0;j<ColumnCount;j++)
    {
        def c = sh.getCell(j, i).getContents();
        log.info c

        testRunner.testCase.getTestStepByName("Properties_Address").setPropertyValue("ID", c)
        testRunner.testCase.getTestStepByName("Properties_Address").setPropertyValue("AddressLine1", c)
        testRunner.testCase.getTestStepByName("Properties_Address").setPropertyValue("AddressLine2", c)
        testRunner.testCase.getTestStepByName("Properties_Address").setPropertyValue("AddressLine3", c)
        testRunner.testCase.getTestStepByName("Properties_Address").setPropertyValue("City", c)
        testRunner.testCase.getTestStepByName("Properties_Address").setPropertyValue("State ", c)
        testRunner.testCase.getTestStepByName("Properties_Address").setPropertyValue("PostalCode", c)
        testRunner.testCase.getTestStepByName("Properties_Address").setPropertyValue("Country", c)

        def TestStep =  testRunner.runTestStepByName("Search_Address")
    }
}

Body:
in your script you assign the value from each cell of excel into all properties and executing teststep for each cell.

probably you want to map cell values from one row to different properties and execute test for each row.

define the following map

(you can initialize this map from zero row of your excel table)

def header=[
  0:'ID', //means put cell0 into property `ID`
  1:'AddressLine1',
  2:'AddressLine2',
  3:'AddressLine3',
  4:'City',
  ...
]

and now your cycle will look like:

for (i=1;i<RowCount;i++)
{
    for (j=0;j<ColumnCount;j++)
    {
        def pname = header[j]
        if(pname){
            def c = sh.getCell(j, i).getContents();
            testRunner.testCase.getTestStepByName("Properties_Address").setPropertyValue(pname, c)
        }
    }
    def TestStep =  testRunner.runTestStepByName("Search_Address")
}


问:
angularjs 1.2 - validation directive update on $watch
I have the following directive that I'm using for validation on a multi-select to allow for (dynamic) length validation of the number of selected items.

```<code>(function() {
    'use strict';

    angular
        .module('myModule')
        .directive('listLength', listLength);

    listLength.$inject = ['$parse'];

    function listLength($parse) {
        var directive = {
            require: 'ngModel',
            restrict: 'A',
            link: link
        };

        function link(scope, elem, attr, ngModel) {
            var length = 0;
            var exp = $parse(attr.listLength);
            if (exp.constant) {
                // Single value, no need to watch
                length = exp(scope);
            } else {
                // We have an expression, need to watch for changes
                scope.$watch(attr.listLength, function(newVal, oldVal) {
                    length = newVal;
                });
            }

            //For DOM -> model validation
            ngModel.$parsers.unshift(function(value) {
                if (!angular.isUndefined(value) && value !== "") {
                    var valid = value.length === length;
                    ngModel.$setValidity('listLength', valid);
                    return valid ? value : undefined;
                }
                return value;
            });

            //For model -> DOM validation
            ngModel.$formatters.unshift(function(value) {
                if (!angular.isUndefined(value) && value !== "") {
                    var valid = value.length === length;
                    ngModel.$setValidity('listLength', valid);
                }
                return value;
            });
        }

        return directive;
    }
})();
</code>```

In order to have it update properly, I need to trigger the validation to be run when the expression (attr.listLength) updates, but it's not obvious to me how to achieve this. I tried setting ngModel.$dirty to true but it still does not update.

答:
Looks like the only way to do this in Angular 1.2 is to use ngModel.$setViewValue, which triggers all the validation functions. So if I do

```<code>scope.$watch(attr.listLength, function(newVal, oldVal) {
    length = newVal;
    ngModel.$setViewValue(ngModel.$viewValue);  // Set view value to itself...
});
</code>```

It then triggers the validation functions. In angularjs 1.3+ this can be done with ngModel.$validate()

Body:
I have the following directive that I'm using for validation on a multi-select to allow for (dynamic) length validation of the number of selected items.

(function() {
    'use strict';

    angular
        .module('myModule')
        .directive('listLength', listLength);

    listLength.$inject = ['$parse'];

    function listLength($parse) {
        var directive = {
            require: 'ngModel',
            restrict: 'A',
            link: link
        };

        function link(scope, elem, attr, ngModel) {
            var length = 0;
            var exp = $parse(attr.listLength);
            if (exp.constant) {
                // Single value, no need to watch
                length = exp(scope);
            } else {
                // We have an expression, need to watch for changes
                scope.$watch(attr.listLength, function(newVal, oldVal) {
                    length = newVal;
                });
            }

            //For DOM -> model validation
            ngModel.$parsers.unshift(function(value) {
                if (!angular.isUndefined(value) && value !== "") {
                    var valid = value.length === length;
                    ngModel.$setValidity('listLength', valid);
                    return valid ? value : undefined;
                }
                return value;
            });

            //For model -> DOM validation
            ngModel.$formatters.unshift(function(value) {
                if (!angular.isUndefined(value) && value !== "") {
                    var valid = value.length === length;
                    ngModel.$setValidity('listLength', valid);
                }
                return value;
            });
        }

        return directive;
    }
})();

In order to have it update properly, I need to trigger the validation to be run when the expression (attr.listLength) updates, but it's not obvious to me how to achieve this. I tried setting ngModel.$dirty to true but it still does not update.

Body:
Looks like the only way to do this in Angular 1.2 is to use ngModel.$setViewValue, which triggers all the validation functions. So if I do

scope.$watch(attr.listLength, function(newVal, oldVal) {
    length = newVal;
    ngModel.$setViewValue(ngModel.$viewValue);  // Set view value to itself...
});

It then triggers the validation functions. In angularjs 1.3+ this can be done with ngModel.$validate()


问:
Keep logged in on each page
When i log in on my index.php, and then go to another page like members.php, i am a guest again. How can i do so they are logged in on each site? I know that sessions are involved, but cant figure it out. Any help is needed!

EDIT: Ok, so i have tried some stuff that you guys have commented and this is my final code:

my index.php

<?php
session_start();
?>

      <link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

      <link type="text/css" rel="stylesheet" href="css/materialize.min.css"  media="screen,projection"/>

      <meta name="viewport" content="width=device-width, initial-scale=1.0"/>

    <meta charset="utf-8">

    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

    <title><?php
$klan = fopen("klan.txt", "r") or die("En error har oppstått!!");
echo fread($klan,filesize("klan.txt"));
fclose($klan);
?></title>
    <meta name="description" content="This is the Responsive Grid System, a quick, easy and flexible way to create a responsive web site.">
    <meta name="keywords" content="responsive, grid, system, web design">

    <meta name="author" content="www.grahamrobertsonmiller.co.uk">

    <meta http-equiv="cleartype" content="on">

    <link rel="shortcut icon" href="/favicon.ico">

    <meta name="HandheldFriendly" content="True">
    <meta name="MobileOptimized" content="320">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" href="css/html5reset.css" media="all">
    <link rel="stylesheet" href="css/col.css" media="all">
    <link rel="stylesheet" href="css/2cols.css" media="all">

<link rel="stylesheet" href="demo.css">
<link rel="stylesheet" href="header-fixed.css">
<link rel="stylesheet" type="text/css" href="css/style.css">
<link href='http://fonts.googleapis.com/css?family=Cookie' rel='stylesheet' type='text/css'>

<link href="http://fonts.googleapis.com/css?family=Roboto+Condensed:400,300,700" rel="stylesheet" type="text/css">

<?php
$klan = fopen("klan.txt", "r") or die("En error har oppstått!!");
echo fread($klan,filesize("klan.txt"));
fclose($klan);
?>

            <?php
$navigasjon = fopen("navigasjon.txt", "r") or die("En error har oppstått!!");
echo fread($navigasjon,filesize("navigasjon.txt"));
fclose($navigasjon);
?>

<?php
$klan = fopen("klan.txt", "r") or die("En error har oppstått!!");
echo fread($klan,filesize("klan.txt"));
fclose($klan);
?>

Teamspeak 3: <?php
$teamspeak = fopen("teamspeak.txt", "r") or die("En error har oppstått!!");
echo fread($teamspeak,filesize("teamspeak.txt"));
fclose($teamspeak);
?>

<marquee behavior="scroll" direction="right"><?php
$infonavb = fopen("infonavb.txt", "r") or die("En error har oppstått!!");
echo fread($infonavb,filesize("infonavb.txt"));
fclose($infonavb);
?></marquee>

Månedens klanspiller

                    <?php
$topspiller = fopen("topspiller.txt", "r") or die("En error har oppstått!!");
echo fread($topspiller,filesize("topspiller.txt"));
fclose($topspiller);
?>

Klan Info

                   <?php
$klaninfo = fopen("klaninfo.txt", "r") or die("En error har oppstått!!");
echo fread($klaninfo,filesize("klaninfo.txt"));
fclose($klaninfo);
?>

Logg inn

<?php
if (!isset($_POST['submit'])){
?>

 <form action="<?=$_SERVER['PHP_SELF']?>" method="post">
  Brukernavn: <input type="text" name="username" style="margin-top: 1%;" />

  Passord: <input type="password" name="password" style="margin-top: 1%;" />

  <input type="submit" name="submit" value="Login" class="knapp" style="margin-top: 1%;" />
 </form>

    Har du ikke en bruker enda?
    <form action="register.php" method="get">
            <input type="submit" name="register" value="Registrer">
        </form>
<?php
} else {
    require_once("db_const.php");
    $mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
    # check connection
    if ($mysqli->connect_errno) {
        echo "
MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}
";
        exit();
    }

    $username = $_POST['username'];
    $password = $_POST['password'];

    $_SESSION['username'] = $username;

    $sql = "SELECT * from users WHERE username LIKE '{$username}' AND password LIKE '{$password}' LIMIT 1";
    $result = $mysqli->query($sql);
    if (!$result->num_rows == 1) {
        echo "Invalid username/password combination";
    } else {
        echo "Du har logget inn som ";
        echo $_POST['username'];
        echo "";

        ?>

<form action="index.php" method="get">
            <input type="submit" name="on" value="Logg ut">
        </form>
<?php

function onFfunc(){
         session_destroy();
       }

    if(isset($_GET['on'])) {
   onFfunc();
}

    }
}

?>

<?php
include "fusion/upload/news.php";
?>

<?php
$klan = fopen("klan.txt", "r") or die("En error har oppstått!!");
echo fread($klan,filesize("klan.txt"));
fclose($klan);
?> Bedwars Clan | GommeHD & PvPHeroes

Copyright © 2017 | Coded by Thesevs

```
</div>
</div>
</p>

<p>my members.php
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><?php
session_start();
$_SESSION['username'] = $username;

if(isset($_SESSION['username'])){
?>

 <!DOCTYPE html>
<!-- HTML5 Boilerplate -->
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->

<head>

 <!--Import Google Icon Font-->
      <link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
      <!--Import materialize.css-->
      <link type="text/css" rel="stylesheet" href="css/materialize.min.css"  media="screen,projection"/>

      <!--Let browser know website is optimized for mobile-->
      <meta name="viewport" content="width=device-width, initial-scale=1.0"/>

 <meta charset="utf-8">
 <!-- Always force latest IE rendering engine & Chrome Frame -->
 <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

 <title><?php
$klan = fopen("klan.txt", "r") or die("En error har oppstått!!");
echo fread($klan,filesize("klan.txt"));
fclose($klan);
?></title>
 <meta name="description" content="This is the Responsive Grid System, a quick, easy and flexible way to create a responsive web site.">
 <meta name="keywords" content="responsive, grid, system, web design">

 <meta name="author" content="www.grahamrobertsonmiller.co.uk">

 <meta http-equiv="cleartype" content="on">

 <link rel="shortcut icon" href="/favicon.ico">

 <!-- Responsive and mobile friendly stuff -->
 <meta name="HandheldFriendly" content="True">
 <meta name="MobileOptimized" content="320">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">

 <!-- Stylesheets -->
 <link rel="stylesheet" href="css/html5reset.css" media="all">
 <link rel="stylesheet" href="css/col.css" media="all">
 <link rel="stylesheet" href="css/2cols.css" media="all">
 <style type="text/css">

 /*
 ========================
 - Note: These styles are just to pretty the basic page up a bit.
 You should ignore these when copying and pasting into your site
 because your stylesheet should take care of making it look pretty!
 ========================
 */
 body { padding:2em; font : 100%/1.4 'Roboto Condensed', Helvetica, sans-serif;
 }
 h1 { font-size:2.2em; padding:0 0 .5em 0; }
 h2 { font-size:1.5em; }
 .header { padding:1em 0; }
 .col { background: black; color: white; padding: 1% 0; text-align: center;}

 </style>

<link rel="stylesheet" href="demo.css">
<link rel="stylesheet" href="header-fixed.css">
    <link rel="stylesheet" type="text/css" href="css/style.css">
<link href='http://fonts.googleapis.com/css?family=Cookie' rel='stylesheet' type='text/css'>

<link href="http://fonts.googleapis.com/css?family=Roboto+Condensed:400,300,700" rel="stylesheet" type="text/css">
</head>
<body>

<header class="header-fixed">

 <div class="header-limiter">

  <h1><?php
$klan = fopen("klan.txt", "r") or die("En error har oppstått!!");
echo fread($klan,filesize("klan.txt"));
fclose($klan);
?></h1>

  <nav>
   <?php
$navigasjon = fopen("navigasjon.txt", "r") or die("En error har oppstått!!");
echo fread($navigasjon,filesize("navigasjon.txt"));
fclose($navigasjon);
?>
  </nav>

 </div>

</header>

<!-- You need this element to prevent the content of the page from jumping up -->
<div class="header-fixed-placeholder"></div>

<div class="headbanner">
 <center>
<div class="headBannerText">
<?php
$klan = fopen("klan.txt", "r") or die("En error har oppstått!!");
echo fread($klan,filesize("klan.txt"));
fclose($klan);
?></center>
</div>

</div>

<div class="infonav">
    <div class="infonavText">
        <center>
        <i><div style="float: left;">Teamspeak 3: <?php
$teamspeak = fopen("teamspeak.txt", "r") or die("En error har oppstått!!");
echo fread($teamspeak,filesize("teamspeak.txt"));
fclose($teamspeak);
?></div></i>
        <i><div style="float: right;"><span id="demo"></span> <span id="txt"></span></div></i>
        <div style="width: 60%;"><marquee behavior="scroll" direction="right"><?php
$infonavb = fopen("infonavb.txt", "r") or die("En error har oppstått!!");
echo fread($infonavb,filesize("infonavb.txt"));
fclose($infonavb);
?></marquee></div>

        </center>
    </div>
</div>

<script>
var day;
switch (new Date().getDay()) {
    case 0:
        day = "Søndag";
        break;
    case 1:
        day = "Mandag";
        break;
    case 2:
        day = "Tirsdag";
        break;
    case 3:
        day = "Onsdag";
        break;
    case 4:
        day = "Torsdag";
        break;
    case 5:
        day = "Fredag";
        break;
    case  6:
        day = "Lørdag";
}
document.getElementById("demo").innerHTML = day;
</script>

    <!-- HEADER SLUTTER HER -->
    <center>

    <br><br>
      <div id="wrapper">

    <div id="right">

        <div class="parent">

            <div class="main">

                <p>Månedens klanspillere</p>

                <div class="content" style="font-size: 19px;">

                    <?php
$topspiller = fopen("topspiller.txt", "r") or die("En error har oppstått!!");
echo fread($topspiller,filesize("topspiller.txt"));
fclose($topspiller);
?>

<style>
.list-group {
    padding-left: 0;
    margin-bottom: 15px;
}

.list-group-item {
    position: relative;
    display: block;
    padding: 7px 0px;
    background-color: #fff;
    border: 1px solid #ddd;
    border-top-left-radius: 4px;
    border-top-right-radius: 4px;
    border-bottom-left-radius: 4px;
    border-bottom-right-radius: 4px;
    margin: auto;
}

.badge {
    float: right;
    min-width: 10px;
    margin-right: 2%;
    padding: 3px 5px;
    font-size: 12px;
    font-weight: 700;
    line-height: 1;
    color: #fff;
    text-align: center;
    white-space: nowrap;
    vertical-align: middle;
    background-color: #777;
    border-radius: 10px;
}
</style>

                </div>
            </div>
       </div>

        <div class="parent">

            <div class="main">

                <p>Klan Info</p>

                <div class="content">

                    <?php
$klaninfo = fopen("klaninfo.txt", "r") or die("En error har oppstått!!");
echo fread($klaninfo,filesize("klaninfo.txt"));
fclose($klaninfo);
?>

                </div>
            </div>
        </div>

    </div>

    <div id="left">

        <?php
$stab = fopen("stab.txt", "r") or die("En error har oppstått!!");
echo fread($stab,filesize("stab.txt"));
fclose($stab);
?>

  </div>
</div>

<div class="footer"><div class="footerText">
<b><?php
$klan = fopen("klan.txt", "r") or die("En error har oppstått!!");
echo fread($klan,filesize("klan.txt"));
fclose($klan);
?></b> Bedwars Clan | GommeHD & PvPHeroes<br>
Copyright © 2017 | Coded by Thesevs
</div></div>

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>

 $(document).ready(function(){

  var showHeaderAt = 150;

  var win = $(window),
    body = $('body');

  // Show the fixed header only on larger screen devices

  if(win.width() > 600){

   // When we scroll more than 150px down, we set the
   // "fixed" class on the body element.

   win.on('scroll', function(e){

    if(win.scrollTop() > showHeaderAt) {
     body.addClass('fixed');
    }
    else {
     body.removeClass('fixed');
    }
   });

  }

 });

</script>

</center>
</body>

    </html>
<?php

} else{

 header("Location: index.php");

}

?></code>```

But this is still not working, what am i doing wrong?

答:
First you need to set a session on login with the following code:

```<code>session_start();
</code>```

Then with $_SESSION you can check if the user got a session and is logged in.

```<code>If(isset($_SESSION)){
    //loged in code
} else{
    //other code
}
</code>```

assing a session variable:

$_SESSION['mySessionName'] = "yourvalue";

than you could check if it is set with

```<code>if(isset($_SESSION['mySessionName']))
</code>```

(from Richard in comments)

For more information about sessions go to http://php.net/manual/en/book.session.php

hope this helped

Title: Keep logged in on each page

Body:
When i log in on my index.php, and then go to another page like members.php, i am a guest again. How can i do so they are logged in on each site? I know that sessions are involved, but cant figure it out. Any help is needed!

EDIT: Ok, so i have tried some stuff that you guys have commented and this is my final code:

my index.php

<?php
session_start();
?>

      <link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

      <link type="text/css" rel="stylesheet" href="css/materialize.min.css"  media="screen,projection"/>

      <meta name="viewport" content="width=device-width, initial-scale=1.0"/>

    <meta charset="utf-8">

    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

    <title><?php
$klan = fopen("klan.txt", "r") or die("En error har oppstått!!");
echo fread($klan,filesize("klan.txt"));
fclose($klan);
?></title>
    <meta name="description" content="This is the Responsive Grid System, a quick, easy and flexible way to create a responsive web site.">
    <meta name="keywords" content="responsive, grid, system, web design">

    <meta name="author" content="www.grahamrobertsonmiller.co.uk">

    <meta http-equiv="cleartype" content="on">

    <link rel="shortcut icon" href="/favicon.ico">

    <meta name="HandheldFriendly" content="True">
    <meta name="MobileOptimized" content="320">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" href="css/html5reset.css" media="all">
    <link rel="stylesheet" href="css/col.css" media="all">
    <link rel="stylesheet" href="css/2cols.css" media="all">

<link rel="stylesheet" href="demo.css">
<link rel="stylesheet" href="header-fixed.css">
<link rel="stylesheet" type="text/css" href="css/style.css">
<link href='http://fonts.googleapis.com/css?family=Cookie' rel='stylesheet' type='text/css'>

<link href="http://fonts.googleapis.com/css?family=Roboto+Condensed:400,300,700" rel="stylesheet" type="text/css">

<?php
$klan = fopen("klan.txt", "r") or die("En error har oppstått!!");
echo fread($klan,filesize("klan.txt"));
fclose($klan);
?>

            <?php
$navigasjon = fopen("navigasjon.txt", "r") or die("En error har oppstått!!");
echo fread($navigasjon,filesize("navigasjon.txt"));
fclose($navigasjon);
?>

<?php
$klan = fopen("klan.txt", "r") or die("En error har oppstått!!");
echo fread($klan,filesize("klan.txt"));
fclose($klan);
?>

Teamspeak 3: <?php
$teamspeak = fopen("teamspeak.txt", "r") or die("En error har oppstått!!");
echo fread($teamspeak,filesize("teamspeak.txt"));
fclose($teamspeak);
?>

<marquee behavior="scroll" direction="right"><?php
$infonavb = fopen("infonavb.txt", "r") or die("En error har oppstått!!");
echo fread($infonavb,filesize("infonavb.txt"));
fclose($infonavb);
?></marquee>

Månedens klanspiller

                    <?php
$topspiller = fopen("topspiller.txt", "r") or die("En error har oppstått!!");
echo fread($topspiller,filesize("topspiller.txt"));
fclose($topspiller);
?>

Klan Info

                   <?php
$klaninfo = fopen("klaninfo.txt", "r") or die("En error har oppstått!!");
echo fread($klaninfo,filesize("klaninfo.txt"));
fclose($klaninfo);
?>

Logg inn

<?php
if (!isset($_POST['submit'])){
?>

 <form action="<?=$_SERVER['PHP_SELF']?>" method="post">
  Brukernavn: <input type="text" name="username" style="margin-top: 1%;" />

  Passord: <input type="password" name="password" style="margin-top: 1%;" />

  <input type="submit" name="submit" value="Login" class="knapp" style="margin-top: 1%;" />
 </form>

    Har du ikke en bruker enda?
    <form action="register.php" method="get">
            <input type="submit" name="register" value="Registrer">
        </form>
<?php
} else {
    require_once("db_const.php");
    $mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
    # check connection
    if ($mysqli->connect_errno) {
        echo "
MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}
";
        exit();
    }

    $username = $_POST['username'];
    $password = $_POST['password'];

    $_SESSION['username'] = $username;

    $sql = "SELECT * from users WHERE username LIKE '{$username}' AND password LIKE '{$password}' LIMIT 1";
    $result = $mysqli->query($sql);
    if (!$result->num_rows == 1) {
        echo "Invalid username/password combination";
    } else {
        echo "Du har logget inn som ";
        echo $_POST['username'];
        echo "";

        ?>

<form action="index.php" method="get">
            <input type="submit" name="on" value="Logg ut">
        </form>
<?php

function onFfunc(){
         session_destroy();
       }

    if(isset($_GET['on'])) {
   onFfunc();
}

    }
}

?>

<?php
include "fusion/upload/news.php";
?>

<?php
$klan = fopen("klan.txt", "r") or die("En error har oppstått!!");
echo fread($klan,filesize("klan.txt"));
fclose($klan);
?> Bedwars Clan | GommeHD & PvPHeroes

Copyright © 2017 | Coded by Thesevs

my members.php

<?php
session_start();
$_SESSION['username'] = $username;

if(isset($_SESSION['username'])){
?>

 <!DOCTYPE html>

      <link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

      <link type="text/css" rel="stylesheet" href="css/materialize.min.css"  media="screen,projection"/>

      <meta name="viewport" content="width=device-width, initial-scale=1.0"/>

 <meta charset="utf-8">

 <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

 <title><?php
$klan = fopen("klan.txt", "r") or die("En error har oppstått!!");
echo fread($klan,filesize("klan.txt"));
fclose($klan);
?></title>
 <meta name="description" content="This is the Responsive Grid System, a quick, easy and flexible way to create a responsive web site.">
 <meta name="keywords" content="responsive, grid, system, web design">

 <meta name="author" content="www.grahamrobertsonmiller.co.uk">

 <meta http-equiv="cleartype" content="on">

 <link rel="shortcut icon" href="/favicon.ico">

 <meta name="HandheldFriendly" content="True">
 <meta name="MobileOptimized" content="320">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">

 <link rel="stylesheet" href="css/html5reset.css" media="all">
 <link rel="stylesheet" href="css/col.css" media="all">
 <link rel="stylesheet" href="css/2cols.css" media="all">

<link rel="stylesheet" href="demo.css">
<link rel="stylesheet" href="header-fixed.css">
    <link rel="stylesheet" type="text/css" href="css/style.css">
<link href='http://fonts.googleapis.com/css?family=Cookie' rel='stylesheet' type='text/css'>

<link href="http://fonts.googleapis.com/css?family=Roboto+Condensed:400,300,700" rel="stylesheet" type="text/css">

<?php
$klan = fopen("klan.txt", "r") or die("En error har oppstått!!");
echo fread($klan,filesize("klan.txt"));
fclose($klan);
?>

   <?php
$navigasjon = fopen("navigasjon.txt", "r") or die("En error har oppstått!!");
echo fread($navigasjon,filesize("navigasjon.txt"));
fclose($navigasjon);
?>

<?php
$klan = fopen("klan.txt", "r") or die("En error har oppstått!!");
echo fread($klan,filesize("klan.txt"));
fclose($klan);
?>

Teamspeak 3: <?php
$teamspeak = fopen("teamspeak.txt", "r") or die("En error har oppstått!!");
echo fread($teamspeak,filesize("teamspeak.txt"));
fclose($teamspeak);
?>

<marquee behavior="scroll" direction="right"><?php
$infonavb = fopen("infonavb.txt", "r") or die("En error har oppstått!!");
echo fread($infonavb,filesize("infonavb.txt"));
fclose($infonavb);
?></marquee>

Månedens klanspillere

                    <?php
$topspiller = fopen("topspiller.txt", "r") or die("En error har oppstått!!");
echo fread($topspiller,filesize("topspiller.txt"));
fclose($topspiller);
?>

Klan Info

                    <?php
$klaninfo = fopen("klaninfo.txt", "r") or die("En error har oppstått!!");
echo fread($klaninfo,filesize("klaninfo.txt"));
fclose($klaninfo);
?>

        <?php
$stab = fopen("stab.txt", "r") or die("En error har oppstått!!");
echo fread($stab,filesize("stab.txt"));
fclose($stab);
?>

<?php
$klan = fopen("klan.txt", "r") or die("En error har oppstått!!");
echo fread($klan,filesize("klan.txt"));
fclose($klan);
?> Bedwars Clan | GommeHD & PvPHeroes

Copyright © 2017 | Coded by Thesevs

<?php

} else{

 header("Location: index.php");

}

?>

But this is still not working, what am i doing wrong?

Body:
First you need to set a session on login with the following code:

session_start();

Then with $_SESSION you can check if the user got a session and is logged in.

If(isset($_SESSION)){
    //loged in code
} else{
    //other code
}

assing a session variable:

$_SESSION['mySessionName'] = "yourvalue";

than you could check if it is set with

if(isset($_SESSION['mySessionName']))

(from Richard in comments)

For more information about sessions go to http://php.net/manual/en/book.session.php

hope this helped


问:
Segmentation Fault using SpiderMonkey (libmozjs-45.0.2) under Ubuntu 17.04 x64
I'm trying to use SpiderMonkey under Ubuntu 17.04 x64.

The SpiderMonkey project has no bug tracker, also after diligently googling I had not found any workaround about my problem, so I ask the community for help.

1) SpiderMonkey source code downloaded from official download page:

https://people.mozilla.org/~sfink/mozjs-45.0.2.tar.bz2

2) Command for build (from official documentation page):

```<code>$ cd js/src
$ autoconf2.13
$ mkdir build_OPT.OBJ
$ cd build_OPT.OBJ
$ ../configure
$ make
</code>```

3) Example code for embedding the mozjs library also from official example page, but here I bring the simplest code, which reproduce the error:

```<code>#include "jsapi.h"
#include "js/Initialization.h"

int main(int argc, const char *argv[])
{
    JS_Init();

    JSRuntime *rt = JS_NewRuntime(8L * 1024 * 1024);
    if (!rt)
        return 1;

    JSContext *cx = JS_NewContext(rt, 8192);
    if (!cx)
        return 1;

    // here I plan to evaluate JavaScript expressions...

    JS_DestroyContext(cx);
    JS_DestroyRuntime(rt);
    JS_ShutDown();
    return 0;
}
</code>```

4) I have compiled with this command, also given at official examples page:

```<code>$ g++ -std=c++11 -I~/mozjs-45.0.2/js/src/build_OPT.OBJ/dist/include -L~/mozjs-45.0.2/js/src/build_OPT.OBJ/dist/bin main.cpp -o main -lmozjs-45 -lz -lpthread -ldl
</code>```

5) After run, got Segmentation Fault at JS_NewContext call, with following backtrace:

```<code>Starting program: /home/tumick/C/cpp/main
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
[New Thread 0x7ffff5600700 (LWP 12326)]
[New Thread 0x7ffff53ff700 (LWP 12327)]
[New Thread 0x7ffff51fe700 (LWP 12328)]
[New Thread 0x7ffff4ffd700 (LWP 12329)]
[New Thread 0x7ffff4dfc700 (LWP 12330)]

Thread 1 "main" received signal SIGSEGV, Segmentation fault.
0x0000000000000000 in ?? ()
#0  0x0000000000000000 in ?? ()
#1  0x00007ffff6d62722 in js::ScriptBytecodeHasher::hash (l=<synthetic pointer>..., l=<synthetic pointer>...)
    at /home/tumick/mozjs-45.0.2/js/src/jsscript.h:2411
#2  js::detail::HashTable<js::SharedScriptData* const, js::HashSet<js::SharedScriptData*, js::ScriptBytecodeHasher, js::SystemAllocPolicy>::SetOps, js::SystemAllocPolicy>::prepareHash (l=<synthetic pointer>...) at ../../dist/include/js/HashTable.h:1126
#3  js::detail::HashTable<js::SharedScriptData* const, js::HashSet<js::SharedScriptData*, js::ScriptBytecodeHasher, js::SystemAllocPolicy>::SetOps, js::SystemAllocPolicy>::lookupForAdd (l=<synthetic pointer>..., this=<optimized out>) at ../../dist/include/js/HashTable.h:1638
#4  js::HashSet<js::SharedScriptData*, js::ScriptBytecodeHasher, js::SystemAllocPolicy>::lookupForAdd (l=<synthetic pointer>...,
this=<optimized out>) at ../../dist/include/js/HashTable.h:386
#5  SaveSharedScriptData (cx=cx@entry=0x5555557841f0, script=..., ssd=<optimized out>, nsrcnotes=1)
    at /home/tumick/mozjs-45.0.2/js/src/jsscript.cpp:2502
#6  0x00007ffff6d62c41 in JSScript::fullyInitTrivial (cx=cx@entry=0x5555557841f0, script=..., script@entry=...)
    at /home/tumick/mozjs-45.0.2/js/src/jsscript.cpp:2886
#7  0x00007ffff6d20316 in CreateFunctionPrototype (cx=0x5555557841f0, key=<optimized out>) at /home/tumick/mozjs-45.0.2/js/src/jsfun.cpp:785
#8  0x00007ffff6ddcb52 in js::GlobalObject::resolveConstructor (cx=0x5555557841f0, global=..., key=<optimized out>)
    at /home/tumick/mozjs-45.0.2/js/src/vm/GlobalObject.cpp:158
#9  0x00007ffff6ddd06e in js::GlobalObject::ensureConstructor (cx=cx@entry=0x5555557841f0, global=..., global@entry=...,
key=key@entry=JSProto_Function) at /home/tumick/mozjs-45.0.2/js/src/vm/GlobalObject.cpp:98
#10 0x00007ffff6c4fe8b in CreateObjectConstructor (cx=0x5555557841f0, key=<optimized out>)
    at /home/tumick/mozjs-45.0.2/js/src/builtin/Object.cpp:1035
#11 0x00007ffff6ddcbbe in js::GlobalObject::resolveConstructor (cx=0x5555557841f0, global=..., key=<optimized out>)
    at /home/tumick/mozjs-45.0.2/js/src/vm/GlobalObject.cpp:166
#12 0x00007ffff6ddd06e in js::GlobalObject::ensureConstructor (cx=cx@entry=0x5555557841f0, global=..., global@entry=...,
    key=key@entry=JSProto_Object) at /home/tumick/mozjs-45.0.2/js/src/vm/GlobalObject.cpp:98
#13 0x00007ffff6a05f92 in js::GlobalObject::getOrCreateObjectPrototype (cx=0x5555557841f0, this=<optimized out>)
    at /home/tumick/mozjs-45.0.2/js/src/vm/GlobalObject.h:342
#14 CreateArrayPrototype (cx=0x5555557841f0, key=<optimized out>) at /home/tumick/mozjs-45.0.2/js/src/jsarray.cpp:3235
#15 0x00007ffff6ddebe1 in InitBareBuiltinCtor (cx=cx@entry=0x5555557841f0, global=..., global@entry=...,
    protoKey=protoKey@entry=JSProto_Array) at /home/tumick/mozjs-45.0.2/js/src/vm/GlobalObject.cpp:368
#16 0x00007ffff6ddee10 in js::GlobalObject::initSelfHostingBuiltins (cx=cx@entry=0x5555557841f0, global=global@entry=...,
    builtins=builtins@entry=0x7ffff7da9520 <intrinsic_functions>) at /home/tumick/mozjs-45.0.2/js/src/vm/GlobalObject.cpp:413
#17 0x00007ffff6e6ffcb in JSRuntime::createSelfHostingGlobal (cx=cx@entry=0x5555557841f0)
    at /home/tumick/mozjs-45.0.2/js/src/vm/SelfHosting.cpp:1730
#18 0x00007ffff6e70115 in JSRuntime::initSelfHosting (this=this@entry=0x5555557693f0, cx=cx@entry=0x5555557841f0)
    at /home/tumick/mozjs-45.0.2/js/src/vm/SelfHosting.cpp:1754
#19 0x00007ffff6cd3e23 in js::NewContext (rt=0x5555557693f0, stackChunkSize=<optimized out>)
    at /home/tumick/mozjs-45.0.2/js/src/jscntxt.cpp:122
#20 0x000055555555499b in main ()
</code>```

6) Finally, some information about versions:

```<code>$ uname -r
4.10.0-20-generic
$ gcc --version
gcc (Ubuntu 6.3.0-12ubuntu2) 6.3.0 20170406
$ ld --version
GNU lg (GNU Binutils for Ubuntu) 2.28
</code>```

Because the code is extremely simple, I suppose something's wrong with my environment, but I have no idea about the reason.

So, maybe You've meet the same problem and know the workaround to solve it, please, help me to deal with it.

Thank You :)

答:
This is old issue: MOZ_GLUE_IN_PROGRAM breaks stand-alone builds(at last on Linux platform).
To disable MOZ_GLUE_IN_PROGRAM edit js/src/configure.in and replace

```<code>case "${OS_TARGET}" in
Android|WINNT|Darwin)
  MOZ_GLUE_IN_PROGRAM=
  ;;
*)
  dnl On !Android !Windows !OSX, we only want to link executables against   mozglue
  MOZ_GLUE_IN_PROGRAM=1
  AC_DEFINE(MOZ_GLUE_IN_PROGRAM)
;;
esac
</code>```

By

```<code>dnl In stand-alone builds we always only want to link executables against mozglue.
if test "$JS_STANDALONE"; then
  MOZ_GLUE_IN_PROGRAM=
else
  case "${OS_TARGET}" in
  Android|WINNT|Darwin)
    MOZ_GLUE_IN_PROGRAM=
    ;;
  *)
    dnl On !Android !Windows !OSX, we only want to link executables against      mozglue
    MOZ_GLUE_IN_PROGRAM=1
    AC_DEFINE(MOZ_GLUE_IN_PROGRAM)
  ;;
  esac
fi
</code>```

See Bugzilla Bug 1176787 for details.

Body:
I'm trying to use SpiderMonkey under Ubuntu 17.04 x64.

The SpiderMonkey project has no bug tracker, also after diligently googling I had not found any workaround about my problem, so I ask the community for help.

1) SpiderMonkey source code downloaded from official download page:

https://people.mozilla.org/~sfink/mozjs-45.0.2.tar.bz2

2) Command for build (from official documentation page):

$ cd js/src
$ autoconf2.13
$ mkdir build_OPT.OBJ
$ cd build_OPT.OBJ
$ ../configure
$ make

3) Example code for embedding the mozjs library also from official example page, but here I bring the simplest code, which reproduce the error:

#include "jsapi.h"
#include "js/Initialization.h"

int main(int argc, const char *argv[])
{
    JS_Init();

    JSRuntime *rt = JS_NewRuntime(8L * 1024 * 1024);
    if (!rt)
        return 1;

    JSContext *cx = JS_NewContext(rt, 8192);
    if (!cx)
        return 1;

    // here I plan to evaluate JavaScript expressions...

    JS_DestroyContext(cx);
    JS_DestroyRuntime(rt);
    JS_ShutDown();
    return 0;
}

4) I have compiled with this command, also given at official examples page:

$ g++ -std=c++11 -I~/mozjs-45.0.2/js/src/build_OPT.OBJ/dist/include -L~/mozjs-45.0.2/js/src/build_OPT.OBJ/dist/bin main.cpp -o main -lmozjs-45 -lz -lpthread -ldl

5) After run, got Segmentation Fault at JS_NewContext call, with following backtrace:

Starting program: /home/tumick/C/cpp/main
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
[New Thread 0x7ffff5600700 (LWP 12326)]
[New Thread 0x7ffff53ff700 (LWP 12327)]
[New Thread 0x7ffff51fe700 (LWP 12328)]
[New Thread 0x7ffff4ffd700 (LWP 12329)]
[New Thread 0x7ffff4dfc700 (LWP 12330)]

Thread 1 "main" received signal SIGSEGV, Segmentation fault.
0x0000000000000000 in ?? ()
#0  0x0000000000000000 in ?? ()
#1  0x00007ffff6d62722 in js::ScriptBytecodeHasher::hash (l=<synthetic pointer>..., l=<synthetic pointer>...)
    at /home/tumick/mozjs-45.0.2/js/src/jsscript.h:2411
#2  js::detail::HashTable<js::SharedScriptData* const, js::HashSet<js::SharedScriptData*, js::ScriptBytecodeHasher, js::SystemAllocPolicy>::SetOps, js::SystemAllocPolicy>::prepareHash (l=<synthetic pointer>...) at ../../dist/include/js/HashTable.h:1126
#3  js::detail::HashTable<js::SharedScriptData* const, js::HashSet<js::SharedScriptData*, js::ScriptBytecodeHasher, js::SystemAllocPolicy>::SetOps, js::SystemAllocPolicy>::lookupForAdd (l=<synthetic pointer>..., this=<optimized out>) at ../../dist/include/js/HashTable.h:1638
#4  js::HashSet<js::SharedScriptData*, js::ScriptBytecodeHasher, js::SystemAllocPolicy>::lookupForAdd (l=<synthetic pointer>...,
this=<optimized out>) at ../../dist/include/js/HashTable.h:386
#5  SaveSharedScriptData (cx=cx@entry=0x5555557841f0, script=..., ssd=<optimized out>, nsrcnotes=1)
    at /home/tumick/mozjs-45.0.2/js/src/jsscript.cpp:2502
#6  0x00007ffff6d62c41 in JSScript::fullyInitTrivial (cx=cx@entry=0x5555557841f0, script=..., script@entry=...)
    at /home/tumick/mozjs-45.0.2/js/src/jsscript.cpp:2886
#7  0x00007ffff6d20316 in CreateFunctionPrototype (cx=0x5555557841f0, key=<optimized out>) at /home/tumick/mozjs-45.0.2/js/src/jsfun.cpp:785
#8  0x00007ffff6ddcb52 in js::GlobalObject::resolveConstructor (cx=0x5555557841f0, global=..., key=<optimized out>)
    at /home/tumick/mozjs-45.0.2/js/src/vm/GlobalObject.cpp:158
#9  0x00007ffff6ddd06e in js::GlobalObject::ensureConstructor (cx=cx@entry=0x5555557841f0, global=..., global@entry=...,
key=key@entry=JSProto_Function) at /home/tumick/mozjs-45.0.2/js/src/vm/GlobalObject.cpp:98
#10 0x00007ffff6c4fe8b in CreateObjectConstructor (cx=0x5555557841f0, key=<optimized out>)
    at /home/tumick/mozjs-45.0.2/js/src/builtin/Object.cpp:1035
#11 0x00007ffff6ddcbbe in js::GlobalObject::resolveConstructor (cx=0x5555557841f0, global=..., key=<optimized out>)
    at /home/tumick/mozjs-45.0.2/js/src/vm/GlobalObject.cpp:166
#12 0x00007ffff6ddd06e in js::GlobalObject::ensureConstructor (cx=cx@entry=0x5555557841f0, global=..., global@entry=...,
    key=key@entry=JSProto_Object) at /home/tumick/mozjs-45.0.2/js/src/vm/GlobalObject.cpp:98
#13 0x00007ffff6a05f92 in js::GlobalObject::getOrCreateObjectPrototype (cx=0x5555557841f0, this=<optimized out>)
    at /home/tumick/mozjs-45.0.2/js/src/vm/GlobalObject.h:342
#14 CreateArrayPrototype (cx=0x5555557841f0, key=<optimized out>) at /home/tumick/mozjs-45.0.2/js/src/jsarray.cpp:3235
#15 0x00007ffff6ddebe1 in InitBareBuiltinCtor (cx=cx@entry=0x5555557841f0, global=..., global@entry=...,
    protoKey=protoKey@entry=JSProto_Array) at /home/tumick/mozjs-45.0.2/js/src/vm/GlobalObject.cpp:368
#16 0x00007ffff6ddee10 in js::GlobalObject::initSelfHostingBuiltins (cx=cx@entry=0x5555557841f0, global=global@entry=...,
    builtins=builtins@entry=0x7ffff7da9520 <intrinsic_functions>) at /home/tumick/mozjs-45.0.2/js/src/vm/GlobalObject.cpp:413
#17 0x00007ffff6e6ffcb in JSRuntime::createSelfHostingGlobal (cx=cx@entry=0x5555557841f0)
    at /home/tumick/mozjs-45.0.2/js/src/vm/SelfHosting.cpp:1730
#18 0x00007ffff6e70115 in JSRuntime::initSelfHosting (this=this@entry=0x5555557693f0, cx=cx@entry=0x5555557841f0)
    at /home/tumick/mozjs-45.0.2/js/src/vm/SelfHosting.cpp:1754
#19 0x00007ffff6cd3e23 in js::NewContext (rt=0x5555557693f0, stackChunkSize=<optimized out>)
    at /home/tumick/mozjs-45.0.2/js/src/jscntxt.cpp:122
#20 0x000055555555499b in main ()

6) Finally, some information about versions:

$ uname -r
4.10.0-20-generic
$ gcc --version
gcc (Ubuntu 6.3.0-12ubuntu2) 6.3.0 20170406
$ ld --version
GNU lg (GNU Binutils for Ubuntu) 2.28

Because the code is extremely simple, I suppose something's wrong with my environment, but I have no idea about the reason.

So, maybe You've meet the same problem and know the workaround to solve it, please, help me to deal with it.

Thank You :)

Body:
This is old issue: MOZ_GLUE_IN_PROGRAM breaks stand-alone builds(at last on Linux platform).
To disable MOZ_GLUE_IN_PROGRAM edit js/src/configure.in and replace

case "${OS_TARGET}" in
Android|WINNT|Darwin)
  MOZ_GLUE_IN_PROGRAM=
  ;;
*)
  dnl On !Android !Windows !OSX, we only want to link executables against   mozglue
  MOZ_GLUE_IN_PROGRAM=1
  AC_DEFINE(MOZ_GLUE_IN_PROGRAM)
;;
esac

By

dnl In stand-alone builds we always only want to link executables against mozglue.
if test "$JS_STANDALONE"; then
  MOZ_GLUE_IN_PROGRAM=
else
  case "${OS_TARGET}" in
  Android|WINNT|Darwin)
    MOZ_GLUE_IN_PROGRAM=
    ;;
  *)
    dnl On !Android !Windows !OSX, we only want to link executables against      mozglue
    MOZ_GLUE_IN_PROGRAM=1
    AC_DEFINE(MOZ_GLUE_IN_PROGRAM)
  ;;
  esac
fi

See Bugzilla Bug 1176787 for details.


问:
Tensorflow has no attribute 'svd'
The documentation indicate that tensorflow has a svd operator.
However, I can't find it in my tensorflow with pip for python2.7
I used these command on Mac:

```<code> pip install https://storage.googleapis.com/tensorflow/mac/tensorflow-0.8.0-py2-none-any.whl
</code>```

Any suggestion would be appreciated.

答: You are trying to install tensorflow 0.8. The SVD was introduced in tensorflow 0.10. Try installing a more recent version. (Current version is 1.2).</p>

Title: Tensorflow has no attribute 'svd'

Body:
The documentation indicate that tensorflow has a svd operator.
However, I can't find it in my tensorflow with pip for python2.7
I used these command on Mac:

 pip install https://storage.googleapis.com/tensorflow/mac/tensorflow-0.8.0-py2-none-any.whl

Any suggestion would be appreciated.


问:
Link to first image attachment in a wordpress post
How would I create a text link to the first image attachment page in a wordpress post without trying to figure out what the slug will be after it is published.  I realize that I can link the images to their attachment page but I wan't to be able to create a text link.  Is this possible?</p>

答:
Figured it out:</p>

```<code><?php
$args = array(
    'post_type' => 'attachment',
    'numberposts' => -1,
    'offset' => 0,
    'orderby' => 'menu_order',
    'order' => 'asc',
    'post_status' => null,
    'post_parent' => $post->ID,
    );
$attachments = get_posts($args);
if ($attachments) {
    foreach ($attachments as $attachment) {
        if(wp_attachment_is_image( $attachment->ID )) {
        echo '<a href="'. get_attachment_link($attachment->ID) . '">LINK TEXT HERE</a>';
        break;
    }
}
}

?>
</code>```

Body:
Figured it out:

<?php
$args = array(
    'post_type' => 'attachment',
    'numberposts' => -1,
    'offset' => 0,
    'orderby' => 'menu_order',
    'order' => 'asc',
    'post_status' => null,
    'post_parent' => $post->ID,
    );
$attachments = get_posts($args);
if ($attachments) {
    foreach ($attachments as $attachment) {
        if(wp_attachment_is_image( $attachment->ID )) {
        echo '<a href="'. get_attachment_link($attachment->ID) . '">LINK TEXT HERE</a>';
        break;
    }
}
}

?>