问:
Reading values from json files into a node.js file
i was asked by my senior to establish connection into database, but rather than hardcoding the values to creating connection, he asked me to store the values which are required to establish connection in a .JSON file and asked me to get the values into node.js file

This is my json code

```<code>{
    "values" : {
        "host" : "localhost",
        "user" : "root",
        "password" : "root",
        "database" : "node"
    }
}
</code>```

This following code has HARDCODED the vlues to establish connection

```<code>var mysql = require('mysql');

var con  = mysql.createConnection({
    host : "localhost",
    user : "root",
    password : "root",
    database : "node"
});

con.connect(function(err) {
    if (err) throw err;
    console.log("Connected!");
    var sql = "INSERT INTO details (name, prof) VALUES ('grijan1', 'student')";
    con.query(sql, function (err, result) {
      if (err) throw err;
      console.log("1 record inserted");
    });
  });
</code>```

How can i do it?

答:
Create config.json file where  store db connection information.

```<code>{
    "host" : "localhost",
    "user" : "root",
    "password" : "root",
    "database" : "node"

}
</code>```

In node.js

```<code>var fs = require('fs');
var mysql = require('mysql');

var configPath = './config.json';
var parsed = JSON.parse(fs.readFileSync(configPath, 'UTF-8'));

var con  = mysql.createConnection({
    host : parsed.host,
    user : parsed.user,
    password : parsed.password,
    database : parsed.database
});
</code>```

Body:
i was asked by my senior to establish connection into database, but rather than hardcoding the values to creating connection, he asked me to store the values which are required to establish connection in a .JSON file and asked me to get the values into node.js file

This is my json code

{
    "values" : {
        "host" : "localhost",
        "user" : "root",
        "password" : "root",
        "database" : "node"
    }
}

This following code has HARDCODED the vlues to establish connection

var mysql = require('mysql');

var con  = mysql.createConnection({
    host : "localhost",
    user : "root",
    password : "root",
    database : "node"
});

con.connect(function(err) {
    if (err) throw err;
    console.log("Connected!");
    var sql = "INSERT INTO details (name, prof) VALUES ('grijan1', 'student')";
    con.query(sql, function (err, result) {
      if (err) throw err;
      console.log("1 record inserted");
    });
  });

How can i do it?

Body:
Create config.json file where  store db connection information.

{
    "host" : "localhost",
    "user" : "root",
    "password" : "root",
    "database" : "node"

}

In node.js

var fs = require('fs');
var mysql = require('mysql');

var configPath = './config.json';
var parsed = JSON.parse(fs.readFileSync(configPath, 'UTF-8'));

var con  = mysql.createConnection({
    host : parsed.host,
    user : parsed.user,
    password : parsed.password,
    database : parsed.database
});


来源: stackexchange

问:
How to Send a Form post Using Ajax in Laravel 5.4
I'm trying to send a form with a POST method but I'm getting a query exception error.

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'post_id'
  cannot be null (SQL: insert into comments (comment, approved,
  user_id, post_id, updated_at, created_at) values (sdfsdfsdff,
  1, 1, , 2017-12-04 07:18:13, 2017-12-04 07:18:13))

'sdfsdfsdff' is the comment that I'm trying to send to the "comment system", 1 is the user id, the blank space is where the post id should be.

Controller

```<code><?php

$this->validate($request, [
    'comment' => 'required'
]);

$post = Post::find($post_id);
$comment = new Comment();
$comment->comment = $request->comment;
$comment->approved = true;
$comment->user_id = auth()->id();
$comment->post_id = $request->id;
$comment->save();

return response()->json([
    'comment' => $comment->comment,
    'user_id' => $comment->user_id,
    'post_id' => $comment->post_id,
    'post_slug' => $post->slug,
    'success' => true
]);
</code>```

Ajax code in the view

```<code>var urlPostComment = '{{ url('comments/store') }}';

$('.send').click(function(e){
   e.preventDefault();
   var dataSerialize = $('#comment-new').serialize();

   $.ajax({
      method: 'post',
      url: urlPostComment,
      data: dataSerialize,
      dataType: 'json', // <- La coma
      success: function (data) {
         console.log(data); // <- Revisar JSON en la consola del navegador
         if( data.success )
         {
            $('#comment-post').append(
               '<p class="store-comment">' + data.comentario + '</p>'
            );
         }

      }, // <- La coma
      error: function () {
         console.log('Error en el AJAX');
      }, // <- La coma
      complete: function () {
         console.log('Termino el ajax');
      }
   });
});
</code>```

Form

```<code><div class="row">
    <div class="col-xs-8 col-md-offset-2 form-create">
        {!! Form::open(['route' => ['comments.store', $post->id], 'method' => 'POST', 'id' => 'add-comment']) !!}
        <p class="error text-center alert alert-danger hidden"></p>
        {{ Form::label('comment', ' Comentario', ['class' => 'glyphicon glyphicon-comment pull-right label-space', 'id' => 'comment-create']) }}
        {{ Form::textarea('comment', null, ['class' => 'form-control comment-text', 'id' => 'comment-new', 'placeholder' => 'Escribe tu comentario']) }}
        <p class="error text-center alert alert-danger hidden"></p>
        {{ Form::submit('Agregar Comentario', ['class' => 'comment-message-guest-button send']) }}
        {!! Form::close() !!}
    </div>
</div>
</code>```

Comments HTML

```<code><div class="row">
        @foreach ($post->comments as $comment)
            <section class="comment-list">
                <article class="row">
                    <div class="col-md-3 col-sm-3 hidden-xs">
                        <figure class="thumbnail">
                            <img class="img-responsive" src="/uploads/avatars/{{ $comment->user->profilepic  }}"/>
                            <figcaption class="text-center">{{ $comment->user->name }}</figcaption>
                        </figure>
                    </div>
                    <div class="col-md-8 col-sm-8">
                        <div class="panel panel-default arrow left">
                            <div class="panel-body">
                                <header class="text-left">
                                    <div class="comment-user"><i class="fa fa-user"></i> {{ $comment->user->name }}
                                    </div>
                                    <time class="comment-date" datetime="{{ $comment->created_at->diffForHumans() }}"><i
                                                class="fa fa-clock-o"></i> {{ $comment->created_at->diffForHumans() }}
                                    </time>
                                </header>
                                <div id="comment-post" data-commentid="{{ $comment->id }}">
                                    <p id="display-comment"
                                       class="store-comment" {{ $comment->id }} {{ $post->id }}>{{ $comment->comment }}</p>
                                </div>
                            </div>

                            <div class="panel-footer list-inline comment-footer">
                                @if(Auth::guest())
                                    No puedes responder ningún comentario si no has ingresado.
                                @else
                                    @if(Auth::user() == $comment->user)
                                        <a href="#" data-toggle="modal" data-target="edit-comment" class="edit-comment">Editar</a>
                                        <a href="#" data-toggle="modal" data-target="delete-comment"
                                           class="delete-comment">Eliminar</a>
                                    @endif
                                    @if(Auth::user() != $comment->user)
                                        <a href="#">Responder</a>
                                    @endif
                                @endif
                            </div>
                        </div>
                    </div>
                </article>
            </section>
        @endforeach
</div>
</code>```

The main error:

POST http://localhost:8000/comments/store 500 (Internal Server Error)
  "from google chrome console"

In my comments table in the database, I do have the foreign key that worked perfectly when I wasn't using Ajax, so I don't think that's a relationship problem. Thank you in advance.

答:
Your form id is "add-comment" but in your ajax you are serializing your form through "comment-new".
And you did not define name="id" field in your form which you are getting in your controller.</p>

```<code>$comment->post_id   = $request->id;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to send a form with a POST method but I'm getting a query exception error.

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'post_id'
  cannot be null (SQL: insert into comments (comment, approved,
  user_id, post_id, updated_at, created_at) values (sdfsdfsdff,
  1, 1, , 2017-12-04 07:18:13, 2017-12-04 07:18:13))

'sdfsdfsdff' is the comment that I'm trying to send to the "comment system", 1 is the user id, the blank space is where the post id should be.

Controller

<?php

$this->validate($request, [
    'comment' => 'required'
]);

$post = Post::find($post_id);
$comment = new Comment();
$comment->comment = $request->comment;
$comment->approved = true;
$comment->user_id = auth()->id();
$comment->post_id = $request->id;
$comment->save();

return response()->json([
    'comment' => $comment->comment,
    'user_id' => $comment->user_id,
    'post_id' => $comment->post_id,
    'post_slug' => $post->slug,
    'success' => true
]);

Ajax code in the view

var urlPostComment = '{{ url('comments/store') }}';

$('.send').click(function(e){
   e.preventDefault();
   var dataSerialize = $('#comment-new').serialize();

   $.ajax({
      method: 'post',
      url: urlPostComment,
      data: dataSerialize,
      dataType: 'json', // <- La coma
      success: function (data) {
         console.log(data); // <- Revisar JSON en la consola del navegador
         if( data.success )
         {
            $('#comment-post').append(
               '
' + data.comentario + '
'
            );
         }

      }, // <- La coma
      error: function () {
         console.log('Error en el AJAX');
      }, // <- La coma
      complete: function () {
         console.log('Termino el ajax');
      }
   });
});

Form

        {!! Form::open(['route' => ['comments.store', $post->id], 'method' => 'POST', 'id' => 'add-comment']) !!}

        {{ Form::label('comment', ' Comentario', ['class' => 'glyphicon glyphicon-comment pull-right label-space', 'id' => 'comment-create']) }}
        {{ Form::textarea('comment', null, ['class' => 'form-control comment-text', 'id' => 'comment-new', 'placeholder' => 'Escribe tu comentario']) }}

        {{ Form::submit('Agregar Comentario', ['class' => 'comment-message-guest-button send']) }}
        {!! Form::close() !!}

Comments HTML

        @foreach ($post->comments as $comment)

                            user->profilepic  }}"/>

{{ $comment->user->name }}

 {{ $comment->user->name }}

                                    <time class="comment-date" datetime="{{ $comment->created_at->diffForHumans() }}"> {{ $comment->created_at->diffForHumans() }}
                                    </time>

id }}">

id }} {{ $post->id }}>{{ $comment->comment }}

                                @if(Auth::guest())
                                    No puedes responder ningún comentario si no has ingresado.
                                @else
                                    @if(Auth::user() == $comment->user)
                                        Editar
                                        Eliminar
                                    @endif
                                    @if(Auth::user() != $comment->user)
                                        Responder
                                    @endif
                                @endif

        @endforeach

The main error:

POST http://localhost:8000/comments/store 500 (Internal Server Error)
  "from google chrome console"

In my comments table in the database, I do have the foreign key that worked perfectly when I wasn't using Ajax, so I don't think that's a relationship problem. Thank you in advance.

Body:
Your form id is "add-comment" but in your ajax you are serializing your form through "comment-new".
And you did not define name="id" field in your form which you are getting in your controller.

$comment->post_id   = $request->id;

ContentLicense: CC BY-SA 3.0


问:
PWA - manifest attribute "display": "standalone" not working on Android
I've noticed a really weird behaviour of my PWA. I can launch it in "standalone" mode on Windows, but when I'm trying to do the same on my Android device it's ignoring the "standalone" value and opens the url in Chrome (Android 7.0, Chrome-Android v62.x). It also doesn't work in Chrome-Android Beta v63.x (relating to this post what refers to a bug in chrome 62.x ). I've checked the manifest file with the Manifest Validator and Lighthouse. Both tools validated the file and don't show me any errors/problems. The "Add to Homescreen" dialog is shown directly (on every first launch) and I can add the PWA to my Homescreen. The service-worker works as expected and I don't have any problems running the app offline (on Windows and Android).

I'm testing on my Android device with a proxy on my notebook (just in case this could be relevant). I also tried different Android devices, but the same problem occurs.

Note: different PWAs work as expected, e.g. 2048 as PWA

Here is my manifest.json :

```<code>{
  "icons": [
    {
      "src": "assets/android-chrome-36x36.png",
      "sizes": "36x36",
      "type": "image\/png"
    },
    {
      "src": "assets/android-chrome-48x48.png",
      "sizes": "48x48",
      "type": "image\/png"
    },
    {
      "src": "assets/android-chrome-72x72.png",
      "sizes": "72x72",
      "type": "image\/png"
    },
    {
      "src": "assets/android-chrome-96x96.png",
      "sizes": "96x96",
      "type": "image\/png"
    },
    {
      "src": "assets/android-chrome-144x144.png",
      "sizes": "144x144",
      "type": "image\/png"
    },
    {
      "src": "assets/android-chrome-192x192.png",
      "sizes": "192x192",
      "type": "image\/png"
    },
    {
      "src": "assets/android-chrome-512x512.png",
      "sizes": "512x512",
      "type": "image\/png"
    }
  ],
  "short_name": "My short name",
  "name": "My not sooooo short name",
  "theme_color": "#337ab7",
  "start_url": "/index.html",
  "background_color": "#ffffff",
  "display": "standalone",
  "orientation": "portrait"
}
</code>```

The manifest file is linked in the header of my index.html with additional mobile:

```<code><meta name="mobile-web-app-capable" content="yes">
<meta name="theme-color" content="#337ab7">
<link rel="manifest" href="manifest.json">
</code>```

The web app is build with angular2 (angular-seeds), just in case someone faced similar problems..

Thanks for your time and comments!

UPDATE 1:

When I'm not using a proxy to access my PWA from my mobile device and instead accessing it via an opened port from my local network, the standalone feature works just fine (but service-worker registration fails..). I'm still not sure why this "bug" occurs with a proxy.

UPDATE 2:

My real question is, why is this happening? And the other one is, how can I really test the behaviour and feeling of my PWA on a real mobile device if all solutions I found have compromises? Concerning the development environment..

My ways of testing on an Android device:

open a port of my notebook and access inside in my local network over the ip adress of my notebook (service worker are not working since not https and no localhost, but pwa starts in standalone mode -.-)

set a proxy on the Android device to the ip of my notebook (service worker works, standalone mode fails)

答:
I found a solution to test my PWA on any mobile device without any of the listed compromises. I'm using now ngrok what allows me to create a tunnel to my localhost to make it accessible via https from anywhere. Thereby, I can test on any smartphone, tablet or emulator.
ngrok can be downloaded here and is very easy to setup. With a single command you can create the tunnel to a specific port (e.g. 8080):

```<code>ngrok http 8080
</code>```

Nevertheless, I'm still not sure why the fullscreen option didn't work when setting a proxy to my android device.

Body:
I've noticed a really weird behaviour of my PWA. I can launch it in "standalone" mode on Windows, but when I'm trying to do the same on my Android device it's ignoring the "standalone" value and opens the url in Chrome (Android 7.0, Chrome-Android v62.x). It also doesn't work in Chrome-Android Beta v63.x (relating to this post what refers to a bug in chrome 62.x ). I've checked the manifest file with the Manifest Validator and Lighthouse. Both tools validated the file and don't show me any errors/problems. The "Add to Homescreen" dialog is shown directly (on every first launch) and I can add the PWA to my Homescreen. The service-worker works as expected and I don't have any problems running the app offline (on Windows and Android).

I'm testing on my Android device with a proxy on my notebook (just in case this could be relevant). I also tried different Android devices, but the same problem occurs.

Note: different PWAs work as expected, e.g. 2048 as PWA

Here is my manifest.json :

{
  "icons": [
    {
      "src": "assets/android-chrome-36x36.png",
      "sizes": "36x36",
      "type": "image\/png"
    },
    {
      "src": "assets/android-chrome-48x48.png",
      "sizes": "48x48",
      "type": "image\/png"
    },
    {
      "src": "assets/android-chrome-72x72.png",
      "sizes": "72x72",
      "type": "image\/png"
    },
    {
      "src": "assets/android-chrome-96x96.png",
      "sizes": "96x96",
      "type": "image\/png"
    },
    {
      "src": "assets/android-chrome-144x144.png",
      "sizes": "144x144",
      "type": "image\/png"
    },
    {
      "src": "assets/android-chrome-192x192.png",
      "sizes": "192x192",
      "type": "image\/png"
    },
    {
      "src": "assets/android-chrome-512x512.png",
      "sizes": "512x512",
      "type": "image\/png"
    }
  ],
  "short_name": "My short name",
  "name": "My not sooooo short name",
  "theme_color": "#337ab7",
  "start_url": "/index.html",
  "background_color": "#ffffff",
  "display": "standalone",
  "orientation": "portrait"
}

The manifest file is linked in the header of my index.html with additional mobile:

<meta name="mobile-web-app-capable" content="yes">
<meta name="theme-color" content="#337ab7">
<link rel="manifest" href="manifest.json">

The web app is build with angular2 (angular-seeds), just in case someone faced similar problems..

Thanks for your time and comments!

UPDATE 1:

When I'm not using a proxy to access my PWA from my mobile device and instead accessing it via an opened port from my local network, the standalone feature works just fine (but service-worker registration fails..). I'm still not sure why this "bug" occurs with a proxy.

UPDATE 2:

My real question is, why is this happening? And the other one is, how can I really test the behaviour and feeling of my PWA on a real mobile device if all solutions I found have compromises? Concerning the development environment..

My ways of testing on an Android device:

open a port of my notebook and access inside in my local network over the ip adress of my notebook (service worker are not working since not https and no localhost, but pwa starts in standalone mode -.-)

set a proxy on the Android device to the ip of my notebook (service worker works, standalone mode fails)

Body:
I found a solution to test my PWA on any mobile device without any of the listed compromises. I'm using now ngrok what allows me to create a tunnel to my localhost to make it accessible via https from anywhere. Thereby, I can test on any smartphone, tablet or emulator.
ngrok can be downloaded here and is very easy to setup. With a single command you can create the tunnel to a specific port (e.g. 8080):

ngrok http 8080

Nevertheless, I'm still not sure why the fullscreen option didn't work when setting a proxy to my android device.


问:
How to mock partial fields in Mockito

I am writing unit tests for My service layer. My service layer have multiple fields that are autowired. I want to Mock only one of them and others to initialize as autowired.

Service Interface

```<code>public interface ProductSupplierService {

    Map<String, List<? extends BaseDTO>> getProductSuppliers(Long productId, Long tenantId);

    ProductSupplierDTO addProductSupplier(Long productId, Long tenantId, ProductSupplierDTO productSupplierDTO);

    ProductSupplierDTO editProductSupplier(Long productId, Long supplierId, Long tenantId,
            ProductSupplierDTO productSupplierDTO);

    void deleteProductSupplier(Long productId, Long supplierId, Long tenantId);
}
</code>```

Service Implementation

```<code>@Service
public class ProductSupplierServiceImpl implements ProductSupplierService {

    private MapperFacade mapper;

    @Autowired
    public void setMapperFactory(MapperFactory mapperFactory) {
        this.mapper = mapperFactory.getMapperFacade();
    }

    @Autowired
    private ProductRepository productRepository;

    @Autowired
    private ProductManager productManager;

    private static final Logger log = LoggerFactory.getLogger(ProductSupplierServiceImpl.class);

    @Override
    public Map < String, List << ? extends BaseDTO >> getProductSuppliers(Long productId, Long tenantId) {
        Product product = fetchProductByProductIdAndTenantId(productId, tenantId);
        ListResponse listResponse = new ListResponse();
        if (CollectionUtil.nonNullNonEmpty(product.getProductSuppliers())) {
            List < ProductSupplierDTO > productSupplierDTOS = new ArrayList < > (0);
            product.getProductSuppliers().stream().filter(Objects::nonNull)
                .forEach(productSupplier - > productSupplierDTOS
                    .add(productSupplier.toDTO(ProductSupplierDTO.class, mapper)));
            listResponse.addResponse("product_suppliers", productSupplierDTOS);
        }
        return listResponse.getResponse();
    }

    @Override
    public ProductSupplierDTO addProductSupplier(Long productId, Long tenantId, ProductSupplierDTO productSupplierDTO) {
        Product product = fetchProductByProductIdAndTenantId(productId, tenantId);
        ProductSupplier productSupplier = productSupplierDTO.toModel(ProductSupplier.class, mapper);
        if (product.getProductSuppliers().add(productSupplier)) {
            productManager.applyProductSupplier(product, tenantId, productSupplier);
            product.setModified(new Date());
            try {
                productRepository.save(product);
                Optional < ProductSupplier > savedProductSupplier = product.getProductSuppliers().stream()
                    .filter(Objects::nonNull)
                    .filter(ps - > ps.getSupplierId().equals(productSupplierDTO.getSupplierId())).findFirst();
                if (savedProductSupplier.isPresent()) {
                    return savedProductSupplier.get().toDTO(ProductSupplierDTO.class, mapper);
                } else {
                    throw new UnexpectedException();
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                throw new UnexpectedException();
            }
        } else {
            throw new BusinessValidationException("supplier already exists");
        }
    }

    @Override
    public ProductSupplierDTO editProductSupplier(Long productId, Long supplierId, Long tenantId,
        ProductSupplierDTO productSupplierDTO) {
        Product product = fetchProductByProductIdAndTenantId(productId, tenantId);
        Optional < ProductSupplier > productSupplierOptional = product.getProductSuppliers().stream()
            .filter(Objects::nonNull)
            .filter(productSupplier - > productSupplier.getSupplierId().equals(supplierId)).findFirst();
        if (productSupplierOptional.isPresent()) {
            ProductSupplier productSupplier = productSupplierOptional.get();
            if (Objects.nonNull(productSupplierDTO.getBuyPrice())) {
                productSupplier.setBuyPrice(productSupplierDTO.getBuyPrice());
            }
            if (Objects.nonNull(productSupplierDTO.isDefaultSupplier())) {
                if (productSupplierDTO.isDefaultSupplier()) {
                    product.getProductSuppliers().forEach(supplier - > supplier.setDefaultSupplier(false));
                    productSupplier.setDefaultSupplier(true);
                } else {
                    productSupplier.setDefaultSupplier(false);
                }
            }
            productSupplier.setModified(new Date());

            product.setModified(new Date());
            try {
                productRepository.save(product);
                return productSupplier.toDTO(ProductSupplierDTO.class, mapper);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                throw new UnexpectedException();
            }
        } else {
            throw new EntityNotFoundException(ProductSupplier.class, String.valueOf(supplierId));
        }
    }

    @Override
    public void deleteProductSupplier(Long productId, Long supplierId, Long tenantId) {
        Product product = fetchProductByProductIdAndTenantId(productId, tenantId);
        Optional < ProductSupplier > productSupplierOptional = product.getProductSuppliers().stream()
            .filter(Objects::nonNull)
            .filter(productSupplier - > productSupplier.getSupplierId().equals(supplierId)).findFirst();
        if (productSupplierOptional.isPresent()) {
            product.getProductSuppliers().remove(productSupplierOptional.get());
            product.setModified(new Date());
            try {
                productRepository.save(product);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                throw new UnexpectedException();
            }
        } else {
            throw new EntityNotFoundException(ProductSupplier.class, String.valueOf(supplierId));
        }
    }

    private Product fetchProductByProductIdAndTenantId(Long productId, Long tenantId) {
        Product product = productRepository.findByIdAndTenantId(productId, tenantId);
        if (Objects.nonNull(product)) {
            return product;
        } else {
            throw new EntityNotFoundException(Product.class, String.valueOf(productId));
        }
    }
}
</code>```

Test class

```<code>@RunWith(MockitoJUnitRunner.class)
public class ProductSupplierServiceUnitTest {

    @Mock
    private ProductRepository productRepository;

    @Autowired
    @InjectMocks
    private ProductSupplierServiceImpl productSupplierService;

    @Test(expected = EntityNotFoundException.class)
    public void productNotFound() {
        Mockito.when(productRepository.findByIdAndTenantId(invalidProductId, tenantId)).thenReturn(null);
        productSupplierService.getProductSuppliers(invalidProductId, tenantId);
    }

    @Test
    public void getProductSuppliersSuccess() {

        initProduct();
        initProductSupplier();

        Set < ProductSupplier > productSuppliers = new HashSet < > (Collections.singletonList(productSupplierBuilder.get()));
        Product product = productBuilder.setProductSuppliers(productSuppliers).get();
        product.setId(validProductId);

        Mockito.when(productRepository.findByIdAndTenantId(validProductId, tenantId)).thenReturn(product);

        Map < String, List << ? extends BaseDTO >> result = productSupplierService.getProductSuppliers(validProductId,
            tenantId);
        Assert.assertEquals(result.size(), 1);
        Assert.assertTrue(result.containsKey("product_suppliers"));
    }

    @Test
    public void getProductSuppliersEmpty() {

        initProduct();
        initProductSupplier();

        Product product = productBuilder.setProductSuppliers(Collections.emptySet()).get();
        product.setId(validProductId);

        Mockito.when(productRepository.findByIdAndTenantId(validProductId, tenantId)).thenReturn(product);

        Map < String, List << ? extends BaseDTO >> result = productSupplierService.getProductSuppliers(validProductId,
            tenantId);

        Assert.assertTrue(result.isEmpty());
    }

}
</code>```

I want only productRepository field to be mocked but productManager & mapper fields must be initialized automatically.

Problem is productManager & mapper fields are null when running tests.

Is it possible to initialize them automatically? Like they are initialized when running spring boot application with fully loaded context.

答:
If "productManager" & "mapper" are simple classes just add:

```<code>@Spy
ProductManager productManager = new ProductManager();

@Spy
Mapper mapper = new Mapper();
</code>```

Mockito knows to objects annotated with @Spy for @InjectMocks. If those classes have @Autowired fields of their own it is beyond capabilities of Mockito and common solution is to use SpringJUnit4ClassRunner and use Mockito in Spring context config:

```<code><bean id="mockBean" class="org.mockito.Mockito" factory-method="mock">
    <constructor-arg value="some.real.bean.Class" />
</bean>
</code>```

Title: How to mock partial fields in Mockito

Body:
I am writing unit tests for My service layer. My service layer have multiple fields that are autowired. I want to Mock only one of them and others to initialize as autowired.

Service Interface

public interface ProductSupplierService {

    Map<String, List<? extends BaseDTO>> getProductSuppliers(Long productId, Long tenantId);

    ProductSupplierDTO addProductSupplier(Long productId, Long tenantId, ProductSupplierDTO productSupplierDTO);

    ProductSupplierDTO editProductSupplier(Long productId, Long supplierId, Long tenantId,
            ProductSupplierDTO productSupplierDTO);

    void deleteProductSupplier(Long productId, Long supplierId, Long tenantId);
}

Service Implementation

@Service
public class ProductSupplierServiceImpl implements ProductSupplierService {

    private MapperFacade mapper;

    @Autowired
    public void setMapperFactory(MapperFactory mapperFactory) {
        this.mapper = mapperFactory.getMapperFacade();
    }

    @Autowired
    private ProductRepository productRepository;

    @Autowired
    private ProductManager productManager;

    private static final Logger log = LoggerFactory.getLogger(ProductSupplierServiceImpl.class);

    @Override
    public Map < String, List << ? extends BaseDTO >> getProductSuppliers(Long productId, Long tenantId) {
        Product product = fetchProductByProductIdAndTenantId(productId, tenantId);
        ListResponse listResponse = new ListResponse();
        if (CollectionUtil.nonNullNonEmpty(product.getProductSuppliers())) {
            List < ProductSupplierDTO > productSupplierDTOS = new ArrayList < > (0);
            product.getProductSuppliers().stream().filter(Objects::nonNull)
                .forEach(productSupplier - > productSupplierDTOS
                    .add(productSupplier.toDTO(ProductSupplierDTO.class, mapper)));
            listResponse.addResponse("product_suppliers", productSupplierDTOS);
        }
        return listResponse.getResponse();
    }

    @Override
    public ProductSupplierDTO addProductSupplier(Long productId, Long tenantId, ProductSupplierDTO productSupplierDTO) {
        Product product = fetchProductByProductIdAndTenantId(productId, tenantId);
        ProductSupplier productSupplier = productSupplierDTO.toModel(ProductSupplier.class, mapper);
        if (product.getProductSuppliers().add(productSupplier)) {
            productManager.applyProductSupplier(product, tenantId, productSupplier);
            product.setModified(new Date());
            try {
                productRepository.save(product);
                Optional < ProductSupplier > savedProductSupplier = product.getProductSuppliers().stream()
                    .filter(Objects::nonNull)
                    .filter(ps - > ps.getSupplierId().equals(productSupplierDTO.getSupplierId())).findFirst();
                if (savedProductSupplier.isPresent()) {
                    return savedProductSupplier.get().toDTO(ProductSupplierDTO.class, mapper);
                } else {
                    throw new UnexpectedException();
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                throw new UnexpectedException();
            }
        } else {
            throw new BusinessValidationException("supplier already exists");
        }
    }

    @Override
    public ProductSupplierDTO editProductSupplier(Long productId, Long supplierId, Long tenantId,
        ProductSupplierDTO productSupplierDTO) {
        Product product = fetchProductByProductIdAndTenantId(productId, tenantId);
        Optional < ProductSupplier > productSupplierOptional = product.getProductSuppliers().stream()
            .filter(Objects::nonNull)
            .filter(productSupplier - > productSupplier.getSupplierId().equals(supplierId)).findFirst();
        if (productSupplierOptional.isPresent()) {
            ProductSupplier productSupplier = productSupplierOptional.get();
            if (Objects.nonNull(productSupplierDTO.getBuyPrice())) {
                productSupplier.setBuyPrice(productSupplierDTO.getBuyPrice());
            }
            if (Objects.nonNull(productSupplierDTO.isDefaultSupplier())) {
                if (productSupplierDTO.isDefaultSupplier()) {
                    product.getProductSuppliers().forEach(supplier - > supplier.setDefaultSupplier(false));
                    productSupplier.setDefaultSupplier(true);
                } else {
                    productSupplier.setDefaultSupplier(false);
                }
            }
            productSupplier.setModified(new Date());

            product.setModified(new Date());
            try {
                productRepository.save(product);
                return productSupplier.toDTO(ProductSupplierDTO.class, mapper);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                throw new UnexpectedException();
            }
        } else {
            throw new EntityNotFoundException(ProductSupplier.class, String.valueOf(supplierId));
        }
    }

    @Override
    public void deleteProductSupplier(Long productId, Long supplierId, Long tenantId) {
        Product product = fetchProductByProductIdAndTenantId(productId, tenantId);
        Optional < ProductSupplier > productSupplierOptional = product.getProductSuppliers().stream()
            .filter(Objects::nonNull)
            .filter(productSupplier - > productSupplier.getSupplierId().equals(supplierId)).findFirst();
        if (productSupplierOptional.isPresent()) {
            product.getProductSuppliers().remove(productSupplierOptional.get());
            product.setModified(new Date());
            try {
                productRepository.save(product);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                throw new UnexpectedException();
            }
        } else {
            throw new EntityNotFoundException(ProductSupplier.class, String.valueOf(supplierId));
        }
    }

    private Product fetchProductByProductIdAndTenantId(Long productId, Long tenantId) {
        Product product = productRepository.findByIdAndTenantId(productId, tenantId);
        if (Objects.nonNull(product)) {
            return product;
        } else {
            throw new EntityNotFoundException(Product.class, String.valueOf(productId));
        }
    }
}

Test class

@RunWith(MockitoJUnitRunner.class)
public class ProductSupplierServiceUnitTest {

    @Mock
    private ProductRepository productRepository;

    @Autowired
    @InjectMocks
    private ProductSupplierServiceImpl productSupplierService;

    @Test(expected = EntityNotFoundException.class)
    public void productNotFound() {
        Mockito.when(productRepository.findByIdAndTenantId(invalidProductId, tenantId)).thenReturn(null);
        productSupplierService.getProductSuppliers(invalidProductId, tenantId);
    }

    @Test
    public void getProductSuppliersSuccess() {

        initProduct();
        initProductSupplier();

        Set < ProductSupplier > productSuppliers = new HashSet < > (Collections.singletonList(productSupplierBuilder.get()));
        Product product = productBuilder.setProductSuppliers(productSuppliers).get();
        product.setId(validProductId);

        Mockito.when(productRepository.findByIdAndTenantId(validProductId, tenantId)).thenReturn(product);

        Map < String, List << ? extends BaseDTO >> result = productSupplierService.getProductSuppliers(validProductId,
            tenantId);
        Assert.assertEquals(result.size(), 1);
        Assert.assertTrue(result.containsKey("product_suppliers"));
    }

    @Test
    public void getProductSuppliersEmpty() {

        initProduct();
        initProductSupplier();

        Product product = productBuilder.setProductSuppliers(Collections.emptySet()).get();
        product.setId(validProductId);

        Mockito.when(productRepository.findByIdAndTenantId(validProductId, tenantId)).thenReturn(product);

        Map < String, List << ? extends BaseDTO >> result = productSupplierService.getProductSuppliers(validProductId,
            tenantId);

        Assert.assertTrue(result.isEmpty());
    }

}

I want only productRepository field to be mocked but productManager & mapper fields must be initialized automatically.

Problem is productManager & mapper fields are null when running tests.

Is it possible to initialize them automatically? Like they are initialized when running spring boot application with fully loaded context.

Body:
If "productManager" & "mapper" are simple classes just add:

@Spy
ProductManager productManager = new ProductManager();

@Spy
Mapper mapper = new Mapper();

Mockito knows to objects annotated with @Spy for @InjectMocks. If those classes have @Autowired fields of their own it is beyond capabilities of Mockito and common solution is to use SpringJUnit4ClassRunner and use Mockito in Spring context config:

<bean id="mockBean" class="org.mockito.Mockito" factory-method="mock">
    <constructor-arg value="some.real.bean.Class" />
</bean>


问:
How to Generate both X509Data and KeyValue within KeyInfo Element with WSS4J
I need to generate the KeyInfo element of a SAML assertion that has both the X509Data element with the X509 certificate and the KeyValue element with the public key. It should look like this:

```<code>                        <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
                            <ds:X509Data>
                                <ds:X509Certificate>MIIGLTCquvS ... </ds:X509Certificate>
                            </ds:X509Data>
                            <ds:KeyValue>
                                <ds:RSAKeyValue>
                                    <ds:Modulus>vOksZtPkaxkdxN ..... </ds:Modulus>
                                    <ds:Exponent>AQAB</ds:Exponent>
                                </ds:RSAKeyValue>
                            </ds:KeyValue>
                        </ds:KeyInfo>
</code>```

I'm using Wss4jOutInterceptor and CXF with a SAMLCallback to generate the Assertion. I can get it to generate either the X509Data or the KeyValue but not both. This has to be in both the SubjectConfirmationData as well as in the Signature of the Assertion. I've seen some answers where you do this using OpenSAML and building it all up by hand, but I'm hoping there's a simpler way using WSS4J.

Thanks in Advance

答:
You can add a custom KeyInfo Element by setting a DOM Element on KeyInfoBean.setElement(). There is not currently a way to do the same though for Signature KeyInfos. I've fixed this in the current code-base:

https://issues.apache.org/jira/browse/WSS-619

Here is the commit including test:

http://svn.apache.org/viewvc?view=revision&revision=1817084

It might take some effort wiring this through with CXF's WSS4JOutInterceptor though.

Body:
I need to generate the KeyInfo element of a SAML assertion that has both the X509Data element with the X509 certificate and the KeyValue element with the public key. It should look like this:

                        <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
                            <ds:X509Data>
                                <ds:X509Certificate>MIIGLTCquvS ... </ds:X509Certificate>
                            </ds:X509Data>
                            <ds:KeyValue>
                                <ds:RSAKeyValue>
                                    <ds:Modulus>vOksZtPkaxkdxN ..... </ds:Modulus>
                                    <ds:Exponent>AQAB</ds:Exponent>
                                </ds:RSAKeyValue>
                            </ds:KeyValue>
                        </ds:KeyInfo>

I'm using Wss4jOutInterceptor and CXF with a SAMLCallback to generate the Assertion. I can get it to generate either the X509Data or the KeyValue but not both. This has to be in both the SubjectConfirmationData as well as in the Signature of the Assertion. I've seen some answers where you do this using OpenSAML and building it all up by hand, but I'm hoping there's a simpler way using WSS4J.

Thanks in Advance


问:
Manipulating a factor and category in R
So i have a data set i am trying to manipulate and i cant seem to find the right way to do this. Iv looked into using dcast and spread but not sure how to get the right manipulation.

so i have something like:

```<code>ID var1 var2 var3 category
--------------------------
1  x    x    x     a
1  x    x    x     b
1  x    x    x     b
2  y    y    y     a
2  y    y    y     b
2  y    y    y     c
3  z    z    z     b
3  z    z    z     b
3  z    z    z     c
</code>```

Id like it to look like this:

```<code>ID var1 var2 var3  a  b  c
--------------------------------
1  x    x    x     1  1  0
2  y    y    y     1  1  1
3  z    z    z     0  1  1
</code>```

Easy example data

```<code>ID <- c(1,1,1,2,2,2,3,3,3)
var1 <- c('x','x','x','y','y','y','z','z','z')
var2 <- c('x','x','x','y','y','y','z','z','z')
var3 <- c('x','x','x','y','y','y','z','z','z')
category <- c('a','b','b','a','b','c','b','b','c')

dat <- data.frame(ID,var1,var2,var3,category)
</code>```

答:
As the question is tagged with dcast, I feel obliged to post a concise solution using dcast().

The OP has not explained how the columns in the wide format should be computed. From the expected result it seems that the OP is not interested in counting the number of occurrences but to indicate presence or absence of each unique combination (1/0 in place of TRUE/FALSE).

Therefore, only unique rows are included in the reshape operation. length() is still used as aggregation function because it fills empty cells with 0 as requested.

```<code>library(reshape2)
dcast(unique(dat), ... ~ category, length)
</code>```

```<code>  ID var1 var2 var3 a b c
1  1    x    x    x 1 1 0
2  2    y    y    y 1 1 1
3  3    z    z    z 0 1 1
</code>```

Title: Manipulating a factor and category in R

Body:
So i have a data set i am trying to manipulate and i cant seem to find the right way to do this. Iv looked into using dcast and spread but not sure how to get the right manipulation.

so i have something like:

ID var1 var2 var3 category
--------------------------
1  x    x    x     a
1  x    x    x     b
1  x    x    x     b
2  y    y    y     a
2  y    y    y     b
2  y    y    y     c
3  z    z    z     b
3  z    z    z     b
3  z    z    z     c

Id like it to look like this:

ID var1 var2 var3  a  b  c
--------------------------------
1  x    x    x     1  1  0
2  y    y    y     1  1  1
3  z    z    z     0  1  1

Easy example data

ID <- c(1,1,1,2,2,2,3,3,3)
var1 <- c('x','x','x','y','y','y','z','z','z')
var2 <- c('x','x','x','y','y','y','z','z','z')
var3 <- c('x','x','x','y','y','y','z','z','z')
category <- c('a','b','b','a','b','c','b','b','c')

dat <- data.frame(ID,var1,var2,var3,category)

Body:
As the question is tagged with dcast, I feel obliged to post a concise solution using dcast().

The OP has not explained how the columns in the wide format should be computed. From the expected result it seems that the OP is not interested in counting the number of occurrences but to indicate presence or absence of each unique combination (1/0 in place of TRUE/FALSE).

Therefore, only unique rows are included in the reshape operation. length() is still used as aggregation function because it fills empty cells with 0 as requested.

library(reshape2)
dcast(unique(dat), ... ~ category, length)

  ID var1 var2 var3 a b c
1  1    x    x    x 1 1 0
2  2    y    y    y 1 1 1
3  3    z    z    z 0 1 1


问:
Insert Path of a file with \\ in mysql using java
I am making a standalone application using java,and in that i need to insert the path of the image that user chooses from file chooser.
I am getting the path of the file but when i store it in the database(mysql) it doesn't stores the \,so when i retrieve that path,the file doesn't show up.

How to store the path of file with \\ so that one gets escaped using java code?

i tried using replaceall method but its giving an error of illegal character set.

```<code>filename.replaceall("\","\\");
</code>```

But this didn't work out.

答: Use Prepared statement to store path containing \.PreparedStatement doesn't escape anything

Body:
I am making a standalone application using java,and in that i need to insert the path of the image that user chooses from file chooser.
I am getting the path of the file but when i store it in the database(mysql) it doesn't stores the \,so when i retrieve that path,the file doesn't show up.

How to store the path of file with \\ so that one gets escaped using java code?

i tried using replaceall method but its giving an error of illegal character set.

filename.replaceall("\","\\");

But this didn't work out.

ContentLicense: CC BY-SA 2.5


问:
How to handle assertion failure on NSButton lockFocus when using modalWindow on quit?
a button's IBAction in windowA calls runModalForWindow:windowB.

windowB becomes key and modal.

windowB has a popUpWindowDatePicker which calls stopModal upon display, and then popUpWindowDatePicker becomes key, and windowB resigns key and is not modal. no window is modal at this point.

when popUpWindowDatePicker is dismissed, its didResignFirstResponder method sets a boolean to YES. windowB then becomes key, and windowB's windowController windowDidBecomeKeyNotification fires, checks the boolean value and if it is YES calls runModalForWindow:self.window.

now windowB is modal and key. windowA is still open, but not key.

windowB has Okay and Cancel buttons which call:
[NSApp stopModalWithCode:returnCode] and then orderOut: and close on windowB.

if the popUpWindowDatePicker is used, and then any time after that windowB is closed with Okay or Cancel, an Assertion Failure is called involving the Okay or Cancel buttons:

```<code>*** Assertion failure in -[NSButton lockFocus], /SourceCache/AppKit/AppKit-1038.29/AppKit.subproj/NSView.m:5237

-[NSButton(0x20021cd60) lockFocus] failed with window=0x20021c0c0, windowNumber=-1, [self isHiddenOrHasHiddenAncestor]=0
</code>```

if windowB is closed with Okay or Cancel and popUpWindowDatePicker has not been used, there is no assertion failure.

it seems that the sequence runModal-stopModal-runModal-stopModal on windowB is involved in the failure of lockFocus on the button pressed, but i can't find a way to trace down more than this to solve this problem.

can anyone offer any hints or thoughts?

答: I added a canDraw method to make sure lockFocus is available. This solved the problem in my case.

Body:
a button's IBAction in windowA calls runModalForWindow:windowB.

windowB becomes key and modal.

windowB has a popUpWindowDatePicker which calls stopModal upon display, and then popUpWindowDatePicker becomes key, and windowB resigns key and is not modal. no window is modal at this point.

when popUpWindowDatePicker is dismissed, its didResignFirstResponder method sets a boolean to YES. windowB then becomes key, and windowB's windowController windowDidBecomeKeyNotification fires, checks the boolean value and if it is YES calls runModalForWindow:self.window.

now windowB is modal and key. windowA is still open, but not key.

windowB has Okay and Cancel buttons which call:
[NSApp stopModalWithCode:returnCode] and then orderOut: and close on windowB.

if the popUpWindowDatePicker is used, and then any time after that windowB is closed with Okay or Cancel, an Assertion Failure is called involving the Okay or Cancel buttons:

*** Assertion failure in -[NSButton lockFocus], /SourceCache/AppKit/AppKit-1038.29/AppKit.subproj/NSView.m:5237

-[NSButton(0x20021cd60) lockFocus] failed with window=0x20021c0c0, windowNumber=-1, [self isHiddenOrHasHiddenAncestor]=0

if windowB is closed with Okay or Cancel and popUpWindowDatePicker has not been used, there is no assertion failure.

it seems that the sequence runModal-stopModal-runModal-stopModal on windowB is involved in the failure of lockFocus on the button pressed, but i can't find a way to trace down more than this to solve this problem.

can anyone offer any hints or thoughts?


问:
PostgreSQL installation dockerfile
I was trying to create docker image of postgresql installation from sources, however, I have got some errors I do not know how to fix. And I was wondering whether there is an alternative way to build this image without using standard postgres docker image?

I would be grateful for any resources and help!

答:
Regarding the errors that you are facing I have shared the answer here.

As you have asked for docker image, all the open source docker images are stored at https://hub.docker.com which is a central repository for public images. You can search any docker image that you are specifically looking for. Even look for Dockerfiles, available for most of the images, for these images to get an Idea of how the application is built.

You can try this postgres docker image which is available here : https://hub.docker.com/_/postgres/

Title: PostgreSQL installation dockerfile


问:
Website homepage as a directory. Running joomla and wordpress side to side
Hope you can help me with this.

We got joomla in my root folder, thats our default website now.

We have just installed wordpress inside a subfolder 'wp'

Now we want to point our homepage (just our homepage alone) to show the wordpress content eg: www.xyz.com will show content from www.xyz.com/wp while we want url in the browser to show just www.xyz.com

Thats the only change we want to do.

Rest of what we had till now, all the urls, functioning for joomla will remain as it is. So only the joomla root homepage will be replaced by wordpress homepage

Also all other joomla and wordpress urls will work as it is.

So we just want the homepage alone to point to the wordpress mainpage. Currently it is using the joomla homepage.

Is this possible? Will this cause any problems ?

Thanks guys

答:
This seems to do the job

RewriteRule ^$  http://localhost/xyz/ [L]

or

RewriteRule ^$  /xyz/ [L]

This will also mask the url.


问:
XML generated by JaxB has other schema's namespace as well
I have two XSDs.

XSD1 has namespace abc.com and XSD2 has namespace xyz.com
XSD1 also has a binding file binding.xjb similar to below -

```<code><?xml version="1.0"?>
<jxb:bindings version="1.0"
              xmlns:jxb="http://java.sun.com/xml/ns/jaxb"
              xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
              jxb:extensionBindingPrefixes="xjc"
              xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <jxb:bindings schemaLocation="XSD1.xsd" node="/xs:schema">
    <jxb:globalBindings>
      <xjc:simple />
    </jxb:globalBindings>
  </jxb:bindings>
</jxb:bindings>
</code>```

My Gradle file in another service imports the XSD contract project as this -

```<code>task extractPackagedXml(type: Copy) {
    from configurations.packagedXml.collect {
        zipTree(it)
    }
    into "${buildDir}/xsd"
}

task jaxb(dependsOn: 'extractPackagedXml') << {
    jaxbTargetDir.mkdirs()
    ant.taskdef(name: 'xjc', classname: 'com.sun.tools.xjc.XJCTask', classpath: configurations.jaxb.asPath)

    ant.xjc(extension: 'true', destdir: jaxbTargetDir, package: 'com.test.contract', binding: "${buildDir}/xsd/binding.xjb") {
        schema(dir: "$buildDir/xsd", includes: "**/*.xsd")
    }
}
</code>```

Now when I do use jaxb to convert the XSD2 classes to XML, the resultant xml has not only xsd2's namespace but also xsd1's namespace.

Am I missing something here?

答: Nop. it is not about xjc. I'm not sure about ant and gradle... I do not work with them. Xjc does all good - generates Java classes from XSDs. Deal is about runtime when objects of such classes marshal to XML by JAXB marshaller. Marshaller creates by JAXBContext where those classes/packages defined. All given namespaces to that JAXBContext are in resulting XML.  It is not a big deal really, but just annoying and unneeded namespaces made XML more larger.</p>

Body:
I have two XSDs.

XSD1 has namespace abc.com and XSD2 has namespace xyz.com
XSD1 also has a binding file binding.xjb similar to below -

<?xml version="1.0"?>
<jxb:bindings version="1.0"
              xmlns:jxb="http://java.sun.com/xml/ns/jaxb"
              xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
              jxb:extensionBindingPrefixes="xjc"
              xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <jxb:bindings schemaLocation="XSD1.xsd" node="/xs:schema">
    <jxb:globalBindings>
      <xjc:simple />
    </jxb:globalBindings>
  </jxb:bindings>
</jxb:bindings>

My Gradle file in another service imports the XSD contract project as this -

task extractPackagedXml(type: Copy) {
    from configurations.packagedXml.collect {
        zipTree(it)
    }
    into "${buildDir}/xsd"
}

task jaxb(dependsOn: 'extractPackagedXml') << {
    jaxbTargetDir.mkdirs()
    ant.taskdef(name: 'xjc', classname: 'com.sun.tools.xjc.XJCTask', classpath: configurations.jaxb.asPath)

    ant.xjc(extension: 'true', destdir: jaxbTargetDir, package: 'com.test.contract', binding: "${buildDir}/xsd/binding.xjb") {
        schema(dir: "$buildDir/xsd", includes: "**/*.xsd")
    }
}

Now when I do use jaxb to convert the XSD2 classes to XML, the resultant xml has not only xsd2's namespace but also xsd1's namespace.

Am I missing something here?


问:
@Basic(fetch = FetchType.LAZY) does not work?
I use JPA (Hibernate) with Spring.
When I want to lazy load a String property, i use this syntax:

```<code>@Lob
@Basic(fetch = FetchType.LAZY)
public String getHtmlSummary() {
    return htmlSummary;
}
</code>```

But when I look at the sql that hibernate creates, it seems this property is not lazy loaded? I also use this class org.hibernate.tool.instrument.javassist.InstrumentTask in ANT script to instrument this property but it seems it does not work.

答:
I think that it would be similar to EclipseLink, there you need to have enabled weaving otherwise, the fetch setting takes no effect.
The weaving requires bytecode access.
This could help: https://stackoverflow.com/a/18423704/7159396</p>

Body:
I use JPA (Hibernate) with Spring.
When I want to lazy load a String property, i use this syntax:

@Lob
@Basic(fetch = FetchType.LAZY)
public String getHtmlSummary() {
    return htmlSummary;
}

But when I look at the sql that hibernate creates, it seems this property is not lazy loaded? I also use this class org.hibernate.tool.instrument.javassist.InstrumentTask in ANT script to instrument this property but it seems it does not work.


问:
How to make a proper Javascript regex?
I would like to make regular expression so it matches only value as bellow, but I want to make it so you have to have at least one (i know it works with the "+" symbol) a-z letter, but I don't know where to put the "+" to make it work correctly. Any help on this?

```<code>.match(/^[0-9a-z]{3,10}$/i)
</code>```

Edit:
It should match for string like "12a", but it shouldn't match for "123" cause it has to have at least one a-z in it.

```<code>if( ! ($Username.match(/^[0-9a-z]{3,10}$/i) && $Username.match(/[a-z]/i)) ) {
    return false;
}
</code>```

Edit:
Thanks to Felix now the example code above works perfect.

答: You can't do it in a single step. The expression you talk about is not regular. You have to make it in several steps. Just match with your current expression and combine to the match with a /[a-z]/ expression.

Title: How to make a proper Javascript regex?

Body:
I would like to make regular expression so it matches only value as bellow, but I want to make it so you have to have at least one (i know it works with the "+" symbol) a-z letter, but I don't know where to put the "+" to make it work correctly. Any help on this?

.match(/^[0-9a-z]{3,10}$/i)

Edit:
It should match for string like "12a", but it shouldn't match for "123" cause it has to have at least one a-z in it.

if( ! ($Username.match(/^[0-9a-z]{3,10}$/i) && $Username.match(/[a-z]/i)) ) {
    return false;
}

Edit:
Thanks to Felix now the example code above works perfect.


问:
Check if mountpoint exists but file does not
I am saving a list of files (absolute paths to a file). It can be of an internal storage or may be external storage.

While syncing those file to the Cloud (i.e. Google Drive), I am checking if file is exists or not at local(File.exists()), and if it does not delete it from the cloud.

But, when the external storage is not mounted, that is causing me to delete the file from the cloud. But, that should not happen. If the mount point is not available it should not check for the file. How can I check that condition?

For example, Files in the internal & external storage looks something like:

Internal: /storage/emulated/0/internal.txt

External: /storage/4XXX-1234/Android/media/com.example/Documents/external.txt

How can I check if storage is mounted only then check for the file existence?

答:
I found a way to find if file is on the mounted path or not. </p>

```<code>File localFile = new File("/storage/4XXX-1234/Android/media/com.example/Documents/external.txt");

if(Environment.getExternalStorageState(new File(localFile.getAbsolutePath()))
         .equalsIgnoreCase("mounted"))) {
    Log.d(TAG,"File is on the mounted path");
}
</code>```

Body:
I found a way to find if file is on the mounted path or not.

File localFile = new File("/storage/4XXX-1234/Android/media/com.example/Documents/external.txt");

if(Environment.getExternalStorageState(new File(localFile.getAbsolutePath()))
         .equalsIgnoreCase("mounted"))) {
    Log.d(TAG,"File is on the mounted path");
}


问:
MySQL showing corresponding value in second column based on condition
I have table with data in following structure:

```<code>    CallNumber  | Duration
    1112            30
    1112            null
    1112            null
    1119            10
    1175            null
    1132            59
    1175            190
</code>```

I want result of select query as:

```<code>    CallNumber  | Duration
    1112            30
    1112            30
    1112            30
    1119            10
    1175            190
    1132            59
    1175            190
</code>```

I do not know how to achieve the above result I am using MySQL database.

答:
you can use the sql code:</p>

```<code>select
  t.CallNumber,
  if (Duration is null, (select Duration from test  where t.CallNumber = CallNumber and Duration is not null limit 1), Duration) as Duration
from
  test t
</code>```

Body:
I have table with data in following structure:

    CallNumber  | Duration
    1112            30
    1112            null
    1112            null
    1119            10
    1175            null
    1132            59
    1175            190

I want result of select query as:

    CallNumber  | Duration
    1112            30
    1112            30
    1112            30
    1119            10
    1175            190
    1132            59
    1175            190

I do not know how to achieve the above result I am using MySQL database.

Body:
you can use the sql code:

select
  t.CallNumber,
  if (Duration is null, (select Duration from test  where t.CallNumber = CallNumber and Duration is not null limit 1), Duration) as Duration
from
  test t


问:
How to interpret the method with set type in C++
I have work on C++ with set method data type. Method is

```<code>set < string, cmp > genPerm ( const string& );
</code>```

here cmp is a class

I don't know how to interpret these type of methods, from 4 hours I have search and understand the set but each time problem occurs and task is not solved. Any one help me guide me about

答:
That is a function declaration of type std::set<std::string, cmp> accepting one std::string parameter by reference to const. The std::set container is also a type. So your function is of that type. The first parameter in <std::string, cmp> template determines the type of elements stored in a set which is a std::string. Set is a sorted container of unique elements. The second parameter in the set template is a key comparison function that determines how the elements are sorted. In your case the custom sorting is provided by your cmp class which probably overloads the () operator and is actually a functor. The return type of the function is:

```<code>std::set<std::string, cmp, std::allocator<std::string>>
</code>```

which is equivalent to:

```<code>std::set<std::string, cmp>
</code>```

If you didn't have the custom comparator cmp the return type would probably be:

```<code>std::set<std::string, std::less<std::string>, std::allocator<std::string>>
</code>```

which is actually:

```<code>std::set<std::string>
</code>```

for short.

Body:
I have work on C++ with set method data type. Method is

set < string, cmp > genPerm ( const string& );

here cmp is a class

I don't know how to interpret these type of methods, from 4 hours I have search and understand the set but each time problem occurs and task is not solved. Any one help me guide me about

Body:
That is a function declaration of type std::set<std::string, cmp> accepting one std::string parameter by reference to const. The std::set container is also a type. So your function is of that type. The first parameter in <std::string, cmp> template determines the type of elements stored in a set which is a std::string. Set is a sorted container of unique elements. The second parameter in the set template is a key comparison function that determines how the elements are sorted. In your case the custom sorting is provided by your cmp class which probably overloads the () operator and is actually a functor. The return type of the function is:

std::set<std::string, cmp, std::allocator<std::string>>

which is equivalent to:

std::set<std::string, cmp>

If you didn't have the custom comparator cmp the return type would probably be:

std::set<std::string, std::less<std::string>, std::allocator<std::string>>

which is actually:

std::set<std::string>

for short.


问:
SQL - Select top n grouped by multiple fields, ordered by count
I am attempting to find the top n records when grouped by multiple attributes. I believe it is related to this problem, but I am having difficulty adapting the solution described  to my situation.

To simplify, I have a table with columns (did is short for device_id):

```<code>id int
did int
dateVal dateTime
</code>```

I am trying to find the top n device_id's for each day with the most rows.

For example (ignoring id and the time part of dateTime),

```<code>did dateVal
1   2017-01-01
1   2017-01-01
1   2017-01-01
2   2017-01-01
3   2017-01-01
3   2017-01-01

1   2017-01-02
1   2017-01-02
2   2017-01-02
2   2017-01-02
2   2017-01-02
3   2017-01-02
</code>```

Finding the top 2 would yield...

```<code>1, 2017-01-01
3, 2017-01-01
2, 2017-01-02
1, 2017-01-02
</code>```

My current naive approach is only giving me the top 2 across all dates.

```<code>--Using SQLite
select date(dateVal) || did
from data
group by date(dateVal), did
order by count(*) desc
limit 2
</code>```

I'm using the concatenation operator so that I can later extract the rows.

I am using SQLite, but any general SQL explanation would be appreciated.

答:
Similarly to this question, define a CTE that computes all device counts for your desired groups, then use it in a WHERE ... IN subquery, limited to the top 2 devices for that date:

WITH device_counts AS (
  SELECT did, date(dateval) AS dateval, COUNT(*) AS device_count
  FROM data
  GROUP BY did, date(dateval)
)
SELECT did, date(dateval) FROM device_counts DC_outer
WHERE did IN (
  SELECT did
  FROM device_counts DC_inner
  WHERE DC_inner.dateval = DC_outer.dateval
  GROUP BY did, date(dateval)
  ORDER BY DC_inner.device_count DESC LIMIT 2
)
ORDER BY date(dateval), did
```

Body:
I am attempting to find the top n records when grouped by multiple attributes. I believe it is related to this problem, but I am having difficulty adapting the solution described  to my situation.

To simplify, I have a table with columns (did is short for device_id):

id int
did int
dateVal dateTime

I am trying to find the top n device_id's for each day with the most rows.

For example (ignoring id and the time part of dateTime),

did dateVal
1   2017-01-01
1   2017-01-01
1   2017-01-01
2   2017-01-01
3   2017-01-01
3   2017-01-01

1   2017-01-02
1   2017-01-02
2   2017-01-02
2   2017-01-02
2   2017-01-02
3   2017-01-02

Finding the top 2 would yield...

1, 2017-01-01
3, 2017-01-01
2, 2017-01-02
1, 2017-01-02

My current naive approach is only giving me the top 2 across all dates.

--Using SQLite
select date(dateVal) || did
from data
group by date(dateVal), did
order by count(*) desc
limit 2

I'm using the concatenation operator so that I can later extract the rows.

I am using SQLite, but any general SQL explanation would be appreciated.


问:
Set rows' values for the next 5 rows when value of the row is X (SQL table)

The table has three columns. (1) UserID, (2) Date, (3) Status.

There are X users, each has the same date ranges log of their statuses.

Statuses (currently) are either "Active" or null.

It could be that there are 5 "Active" days in the row, or it could be 20 days between them.

The goal I'm trying to achieve is: on the date when user's status is "Active", set statuses of the next 5 dates as "Phantom" (or whatever else).

Before:

```<code>UserID   Date      Status
000001   01-01-17  null
000001   02-01-17  Active
000001   03-01-17  null
000001   04-01-17  null
000001   05-01-17  null
000001   06-01-17  null
000001   07-01-17  null
000001   08-01-17  null
000001   09-01-17  Active
000001   10-01-17  null
</code>```

After:

```<code>UserID   Date      Status
000001   01-01-17  null
000001   02-01-17  Active
000001   03-01-17  Phantom
000001   04-01-17  Phantom
000001   05-01-17  Phantom
000001   06-01-17  Phantom
000001   07-01-17  null
000001   08-01-17  null
000001   09-01-17  Active
000001   10-01-17  Phantom
</code>```

I've tried to approach the problem from two angles:
a) As a cycle, that would check whether within the previous X rows 'Active' value is present
b) To select rows that where status is 'Active' and the X rows after them into temp table and to join them afterwards

I assume it should be a way to check "whether the value X is present between Date and Date+X" yet I failed to achieve this so far.

Would very much appreciate help on how to achieve that! (MSSQL)

答:
Eventually I managed to find a solution. Two steps. First, I create a temp table (#active_dates) where I put only rows with 'Active' status. Then, I run the following script:

```<code>update   table_name
set      status='Phantom'
from     #active_dates as a
where    a.userid=table_name.userid and
         (table_name.[date] between a.[date] and dateadd(day,5,a.[date])) and
         (table_name.status is null)
</code>```

Where 5 is just a number of rows after 'Active' one want's to update.

Thank you for your time if you read this. :)

Body:
The table has three columns. (1) UserID, (2) Date, (3) Status.

There are X users, each has the same date ranges log of their statuses.

Statuses (currently) are either "Active" or null.

It could be that there are 5 "Active" days in the row, or it could be 20 days between them.

The goal I'm trying to achieve is: on the date when user's status is "Active", set statuses of the next 5 dates as "Phantom" (or whatever else).

Before:

UserID   Date      Status
000001   01-01-17  null
000001   02-01-17  Active
000001   03-01-17  null
000001   04-01-17  null
000001   05-01-17  null
000001   06-01-17  null
000001   07-01-17  null
000001   08-01-17  null
000001   09-01-17  Active
000001   10-01-17  null

After:

UserID   Date      Status
000001   01-01-17  null
000001   02-01-17  Active
000001   03-01-17  Phantom
000001   04-01-17  Phantom
000001   05-01-17  Phantom
000001   06-01-17  Phantom
000001   07-01-17  null
000001   08-01-17  null
000001   09-01-17  Active
000001   10-01-17  Phantom

I've tried to approach the problem from two angles:
a) As a cycle, that would check whether within the previous X rows 'Active' value is present
b) To select rows that where status is 'Active' and the X rows after them into temp table and to join them afterwards

I assume it should be a way to check "whether the value X is present between Date and Date+X" yet I failed to achieve this so far.

Would very much appreciate help on how to achieve that! (MSSQL)

Body:
Eventually I managed to find a solution. Two steps. First, I create a temp table (#active_dates) where I put only rows with 'Active' status. Then, I run the following script:

update   table_name
set      status='Phantom'
from     #active_dates as a
where    a.userid=table_name.userid and
         (table_name.[date] between a.[date] and dateadd(day,5,a.[date])) and
         (table_name.status is null)

Where 5 is just a number of rows after 'Active' one want's to update.

Thank you for your time if you read this. :)


问:
Qt and UI Skinning
I wanted to consult with the sages here regarding Qt and skinning, get your opinion and chart a path for my development. My requirements are as follows:

My Qt/C++ application (cross platform with Mac, Windows and Linux versions) needs to have modular skins.

A skin is defined as a set of one or more elements: - Window background texture - Look/feel of UI controls such as edit boxes, drop down, radio buttons, buttons etc. - Look/feel of window "caption", resize grips etc.

Skins will be installed with the application installer, allowing the user to choose which one he/she wants to use. Users should be able to change skins on the fly.

Can I go the QML route? should this be custom and based on simple resources which are built into the application? Any design advice will be appreciated.

Thanks.

答:
QML, if I understand correctly, doesn't really skin the widgets, it mainly deals with GUI layout etc etc.

QStyle is used to change the looks. It is a bit low-level though, and requires programming, so if you want to load different user-created skins (from an XML or so) it might be tricky to support extensive skinning. Chaining colors and a few items are easy enough though. (There might be someone else who've done something you could re-use.. not sure.)

For modifying widgets, use QStyle::polish(). You could use that to change the background picture (if it's a top-level window, or of a certain class). There are numerous repaint method to change almost every part of every widget.

Store/load the style using QSettings, by reading and setting the desired Style just after QApplication but before your main window is constructed.

Title: Qt and UI Skinning


问:
403 forbidden while uploading image via AJAX
I am trying to find a solution to my problem, while I am trying to upload an image via AJAX.

I am using this code:

```<code>document.getElementById('file').addEventListener('change', function(e) {
        var file = this.files[0];
        console.log(file);
        var xhr = new XMLHttpRequest();
        (xhr.upload || xhr).addEventListener('progress', function(e) {
            var done = e.position || e.loaded
            var total = e.totalSize || e.total;
            console.log('xhr progress: ' + Math.round(done/total*100) + '%');
        });
        xhr.addEventListener('load', function(e) {
            console.log('xhr upload complete', e, this.responseText);
        });
        xhr.open('post', 'http://webpage.com/images', true);
        var data = new FormData;
        data.append('file', file);
        xhr.send(data);
    });
</code>```

I found it here: jQuery Upload Progress and AJAX file upload

by @Rudie

I am getting 403 forbidden error and tried everything.. I am using opencart MVC archritecture to build my custom dashboard..
My website is hosted at goddady
i) I do not have any .htaccess file on this folder
ii) there is an option at cpanel of godaddy "hotlink protextion", I have also placed the URL in there! (http://webpage.com/images)
iii) tried 777 as folder permission

but still same error.. I think this is the most appropriate code to my solution.. Any suggestions? what I am doing wrong?

答:
I found my solution... I have also changed the above code actually..
 1. First of all, inside the image folder that I have, I have created a HTML file called index.html
This is very important in order to avoid errors that is type of:
No matching DirectoryIndex (index.html.var,index.htm,index.html,index.xhtml.. ..e.t.c.). I found this error through error log file of my hosting provider (goddady), and here is the article that made me to understood and gave me mre information to found it:

https://www.liquidweb.com/kb/apache-error-no-matching-directoryindex-index-html-found-solved/

Article says: "...meaning that Apache will only look for directory index files that are named index.html"

That solved my problem!

I have also changed my code in order to upload images through ajax, using openCart architecture, as I mentioned in another question I have made here in stackoverflow. you could find it here upload image file through ajax and php , in case someone stack on the same problem

Body:
I am trying to find a solution to my problem, while I am trying to upload an image via AJAX.

I am using this code:

document.getElementById('file').addEventListener('change', function(e) {
        var file = this.files[0];
        console.log(file);
        var xhr = new XMLHttpRequest();
        (xhr.upload || xhr).addEventListener('progress', function(e) {
            var done = e.position || e.loaded
            var total = e.totalSize || e.total;
            console.log('xhr progress: ' + Math.round(done/total*100) + '%');
        });
        xhr.addEventListener('load', function(e) {
            console.log('xhr upload complete', e, this.responseText);
        });
        xhr.open('post', 'http://webpage.com/images', true);
        var data = new FormData;
        data.append('file', file);
        xhr.send(data);
    });

I found it here: jQuery Upload Progress and AJAX file upload

by @Rudie

I am getting 403 forbidden error and tried everything.. I am using opencart MVC archritecture to build my custom dashboard..
My website is hosted at goddady
i) I do not have any .htaccess file on this folder
ii) there is an option at cpanel of godaddy "hotlink protextion", I have also placed the URL in there! (http://webpage.com/images)
iii) tried 777 as folder permission

but still same error.. I think this is the most appropriate code to my solution.. Any suggestions? what I am doing wrong?


问:
Activity Indicator called from another class not Stopping
I am using activity indicator from "https://github.com/erangaeb/dev-notes/blob/master/swift/ViewControllerUtils.swift". I tried using it in my view but indicator doesn't seem to stop.I have included it in my view as below:

```<code>ActivityIndicatorView().showActivityIndicator(uiView: self.view)
</code>```

I using the below code to stop:

```<code>ActivityIndicatorView().hideActivityIndicator(uiView: self.view)
</code>```

But I don't know why the indicator is stoping.
More of my code is as below:

```<code>Alamofire.request(diaryViewUrl, method: .get, parameters: [:]).responseJSON {
        response in
        if response.result.isSuccess{

            ActivityIndicatorView().showActivityIndicator(uiView: self.view)

            let dataFetched : JSON = JSON(response.result.value!)

            self.diaryDateTimeText = dataFetched["diary_datetime"].string
            self.diaryLocText = dataFetched["diary_loc"].string
            self.diaryText = dataFetched["diary_text"].string
            self.diaryTags = dataFetched["tags"].arrayObject as? [String]

            ActivityIndicatorView().hideActivityIndicator(uiView: self.view)

            self.topBar()
            self.showViews()

            self.scrollView.addSubview(self.containerView)

            self.view.addSubview(self.scrollView)

        }else{
            print("Error \(String(describing: response.result.error))")

        }
    }
</code>```

答:
It works fine for me. Please try it </p>

```<code>ActivityIndicatorView().showActivityIndicator(uiView: self.view)

Alamofire.request(diaryViewUrl, method: .get, parameters: [:]).responseJSON {
    response in

    ActivityIndicatorView().hideActivityIndicator(uiView: self.view)

    if response.result.isSuccess{

        let dataFetched : JSON = JSON(response.result.value!)

        self.diaryDateTimeText = dataFetched["diary_datetime"].string
        self.diaryLocText = dataFetched["diary_loc"].string
        self.diaryText = dataFetched["diary_text"].string
        self.diaryTags = dataFetched["tags"].arrayObject as? [String]

        self.topBar()
        self.showViews()

        self.scrollView.addSubview(self.containerView)

        self.view.addSubview(self.scrollView)

    }else{
        print("Error \(String(describing: response.result.error))")

    }
}
</code>```

Body:
I am using activity indicator from "https://github.com/erangaeb/dev-notes/blob/master/swift/ViewControllerUtils.swift". I tried using it in my view but indicator doesn't seem to stop.I have included it in my view as below:

ActivityIndicatorView().showActivityIndicator(uiView: self.view)

I using the below code to stop:

ActivityIndicatorView().hideActivityIndicator(uiView: self.view)

But I don't know why the indicator is stoping.
More of my code is as below:

Alamofire.request(diaryViewUrl, method: .get, parameters: [:]).responseJSON {
        response in
        if response.result.isSuccess{

            ActivityIndicatorView().showActivityIndicator(uiView: self.view)

            let dataFetched : JSON = JSON(response.result.value!)

            self.diaryDateTimeText = dataFetched["diary_datetime"].string
            self.diaryLocText = dataFetched["diary_loc"].string
            self.diaryText = dataFetched["diary_text"].string
            self.diaryTags = dataFetched["tags"].arrayObject as? [String]

            ActivityIndicatorView().hideActivityIndicator(uiView: self.view)

            self.topBar()
            self.showViews()

            self.scrollView.addSubview(self.containerView)

            self.view.addSubview(self.scrollView)

        }else{
            print("Error \(String(describing: response.result.error))")

        }
    }

Body:
It works fine for me. Please try it

ActivityIndicatorView().showActivityIndicator(uiView: self.view)

Alamofire.request(diaryViewUrl, method: .get, parameters: [:]).responseJSON {
    response in

    ActivityIndicatorView().hideActivityIndicator(uiView: self.view)

    if response.result.isSuccess{

        let dataFetched : JSON = JSON(response.result.value!)

        self.diaryDateTimeText = dataFetched["diary_datetime"].string
        self.diaryLocText = dataFetched["diary_loc"].string
        self.diaryText = dataFetched["diary_text"].string
        self.diaryTags = dataFetched["tags"].arrayObject as? [String]

        self.topBar()
        self.showViews()

        self.scrollView.addSubview(self.containerView)

        self.view.addSubview(self.scrollView)

    }else{
        print("Error \(String(describing: response.result.error))")

    }
}


问:
Why this Javascript code not adding the rows in the table
Here is the code which i think should insert the same rows again because we are using append() here. and not removing the rows first.

jQuery(document).ready(function(){
 jQuery('#add_rows').click(function(){

    var table = jQuery("#myTable");
    var rows = table.find('tr:gt(0)').toArray();
    for (var i = 0; i < rows.length; i++){table.append(rows[i])}
})

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<title>Sort a HTML Table Alphabetically</title>
</head>
<body>
<button id ="add_rows">Add rows </button>

<table id="myTable">
  <tr>
    <th class="sort_table">Name</th>
    <th class="sort_table">Country</th>
  </tr>
  <tr>
    <td>Berglunds snabbkop</td>
    <td>Sweden</td>
  </tr>
  <tr>
    <td>North/South</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Koniglich Essen</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Magazzini Alimentari Riuniti</td>
    <td>Italy</td>
  </tr>
  <tr>
    <td>Paris specialites</td>
    <td>France</td>
  </tr>
  <tr>
    <td>Island Trading</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>Laughing Bacchus Winecellars</td>
    <td>Canada</td>
  </tr>
</table></code>```

If i use for (var i = 0; i < rows.length; i++){table.append('
data1	data2
')}

Then it actually add the rows (As i expected), but in first case it doesn't do the same, i think it has to do something with the fact that we are using objects there but i am not sure

Could someone explain the reason ?

thanks

答:
Appending a child that already exists in the document moves it.

If you want to "clone" those rows, use table.find("tr:gt(0)").clone(); and append those.

Body:
Here is the code which i think should insert the same rows again because we are using append() here. and not removing the rows first.

jQuery(document).ready(function(){
 jQuery('#add_rows').click(function(){

    var table = jQuery("#myTable");
    var rows = table.find('tr:gt(0)').toArray();
    for (var i = 0; i < rows.length; i++){table.append(rows[i])}
})

});

<!DOCTYPE html>

<title>Sort a HTML Table Alphabetically</title>

<button id ="add_rows">Add rows </button>

    Name
    Country

    Berglunds snabbkop
    Sweden

    North/South
    UK

    Alfreds Futterkiste
    Germany

    Koniglich Essen
    Germany

    Magazzini Alimentari Riuniti
    Italy

    Paris specialites
    France

    Island Trading
    UK

    Laughing Bacchus Winecellars
    Canada

If i use for (var i = 0; i < rows.length; i++){table.append('
data1	data2
')}

Then it actually add the rows (As i expected), but in first case it doesn't do the same, i think it has to do something with the fact that we are using objects there but i am not sure

Could someone explain the reason ?

thanks


问:
Scraping with out Selenium Webdriver stealing focus
I am using Selenium to automate a website. First, I open the main website with C#.
Then, I manually click to open new windows from the main site. Now, I want to scrape the data of these new windows. This is not an issue. The problem lies in the fact that Selenium seems to need a window to be focused to scrape it. I use the SwitchTo method currently before scraping. When you switch, the new windows pop to the front and steal focus from other windows. Is there a way to scrape a window without giving it focus?</p>

答:
Saying that “Selenium requires focus when scraping a page” is a gross oversimplification at best, and a complete misassignment if responsibility at worst. Whether a driver used by Selenium to automate a page requires focus is highly dependent on the driver’s implementation. You haven’t said what browser you’re using, but if it’s Chrome or Firefox, those implementations are created and maintained by the browser vendors (Google and Mozilla, respectively).

There are alternatives in both cases, as both browsers officially support a “headless” mode, which can be used with Selenium. Note, however, that use of that mode would require you to automate the steps you’re currently doing manually.


问:
why adding a new id column with monotonically increasing id break after 352
I am using pyspark 2.2.0. To add a new column of incrementing value.  I have used following code:

```<code>new_df = df.withColumn('Id', monotonically_increasing_id())
</code>```

But it breaks after row number 352 like this:

Any option to fix this ?

答:
As per mic4ael answer the generated ID is only guaranteed to be monotonically increasing and unique, but not consecutive. You can generate consecutive and monotonically increasing ids using row_number, however, this approach does not scale very well and should be avoided for larger datasets. For example, taking this as the input data:

```<code>from pyspark.sql.window import Window
from pyspark.sql.functions import col,row_number
df = spark.createDataFrame([('33004', ''),('33004', ''),('33010', 'Muxia'), ('33020','Fuensanta'),('33020','Fuensanta')], ("Zip", "PostalRegion"))
</code>```

You can add a sequential ID column using the following approach:

```<code>from pyspark.sql.window import Window
w = Window().orderBy("PostalRegion")
df = df.select(row_number().over(w).alias("ID"), col("*"))
df.show()
</code>```

This gives as output:

```<code>+---+-----+------------+
| ID|  Zip|PostalRegion|
+---+-----+------------+
|  1|33004|            |
|  2|33004|            |
|  3|33020|   Fuensanta|
|  4|33020|   Fuensanta|
|  5|33010|       Muxia|
+---+-----+------------+
</code>```

Body:
I am using pyspark 2.2.0. To add a new column of incrementing value.  I have used following code:

new_df = df.withColumn('Id', monotonically_increasing_id())

But it breaks after row number 352 like this:

Any option to fix this ?

Body:
As per mic4ael answer the generated ID is only guaranteed to be monotonically increasing and unique, but not consecutive. You can generate consecutive and monotonically increasing ids using row_number, however, this approach does not scale very well and should be avoided for larger datasets. For example, taking this as the input data:

from pyspark.sql.window import Window
from pyspark.sql.functions import col,row_number
df = spark.createDataFrame([('33004', ''),('33004', ''),('33010', 'Muxia'), ('33020','Fuensanta'),('33020','Fuensanta')], ("Zip", "PostalRegion"))

You can add a sequential ID column using the following approach:

from pyspark.sql.window import Window
w = Window().orderBy("PostalRegion")
df = df.select(row_number().over(w).alias("ID"), col("*"))
df.show()

This gives as output:

+---+-----+------------+
| ID|  Zip|PostalRegion|
+---+-----+------------+
|  1|33004|            |
|  2|33004|            |
|  3|33020|   Fuensanta|
|  4|33020|   Fuensanta|
|  5|33010|       Muxia|
+---+-----+------------+


问:
Meteor server response slow when importing collection
I have a MongoDB collection Foods in my Meteor app with about 8000 entries with almost 1000 fields each.

For some reason, since I included it, the response time when I call a server method from the client is very slow (seconds). For debugging, I've been removing things one by one. Now, I don't use the collection in any of the functions involved (I've even replaced the server method with just a console.log), and yet if I add the line import { Foods } from '../imports/collections.js'; to the server, the response is slow, and if I don't it is fast.

Does anyone have any idea why this could be?

答:
So the answer was easy.

As said in the Meteor docs,

By default, Meteor automatically publishes every document in your collection to each connected client. To turn this behavior off, remove the autopublish package

So, simply by importing the collection, Meteor interprets that you want to publish it all, and that is what was making it slow, even if I wasn't explicitly using it.


问:
High memory usage in Ionic app
recently I have observed thath my android app uses too much of RAM.
When i open it it takes ~~120mb and after few changes of pages it goes to 400mb.
What can I do?

To change page I use popover with:

```<code>        this.navCtrl.setRoot(StatisticsPage);
</code>```

Some data from profiler:
link to data

答:
Whenever you need to go into the child component then instead of using this.navCtrl.setRoot(StatisticsPage); you can use this.navCtrl.push(StatisticsPage);

this could be one point of improvement.

Title: High memory usage in Ionic app

Body:
recently I have observed thath my android app uses too much of RAM.
When i open it it takes ~~120mb and after few changes of pages it goes to 400mb.
What can I do?

To change page I use popover with:

        this.navCtrl.setRoot(StatisticsPage);

Some data from profiler:
link to data


问:
HLF v1.0 - does the peer support PKCS11 in the BCCSP config?
as the Admin I would avoid to store private keys as regular files located in subdirs of "mspConfigPath" since it can be a security problem for some use cases. It'd be great to keep all sensitive crypto material inside HSM.

According to the documentation of the Fabric CA server it is possible to configure server to use a software version of PKCS11 called softhsm.

Q: is it supported by the peer to use PKCS11 in BCCSP section of core.yaml config file?

as it is done in BCCSP section of Fabric CA server configuration file.

答: Yes - there is a BCCSP section in core.yaml - https://github.com/hyperledger/fabric/blob/release/sampleconfig/core.yaml#L228</p>


问:
Clojure: built-in or one-line solution to insert nil into a collection
Consider the following function call: (into [] (some_expression))

Let's say that (some_expression) may either yield nil, or some valid vector (e.g. [1 2 3]). What I would like to achieve is, that if the result of (some_expression) is nil, then I end up with [nil], instead of [] (after executing into). (Of course, if it is some valid vector, like [1 2 3], then I would like to have [1 2 3].)

Possibilities I've considered so far:

vec: wrong, because (vec nil) = [], thus the end result is still []

vector: wrong, since (vector [1 2 3]) = [[1 2 3]], thus, the end result will be [[1 2 3]]. (It would work for nil, though.)

custom function, like ensure-vector or as-vector in this related question: that would solve the problem, but I'm asking if there is something shorter (maybe built into Clojure) that achieves the same

I'm also aware of the following work-around, but it is a bit clumsy for me: (into [] (let [result (some_expression)] (if (nil? result) [nil] result)))

I'm afraid there is no short solution, because otherwise it would have been mentioned in that question; still that one is quite old, so I'm hoping maybe they added that feature to Clojure since then.

Also, there are some key differences with that question:

As stated above, the "ensure-vector" I'm looking for has to work only for nil. (I.e., it is fine if (ensure-vector 2) returns 2 and not [2].) I guess this does not really count, but who knows.

An approach, which is completely different than "ensure-vector" would be fine too. E.g., if into had some special parameter that caused it to interpret the from argument as a value to be inserted, instead of the source collection, that would also solve my problem. (This is more for the sake of making an example: as far as I understand the documentation of into, it does not have such form. Although, frankly, I'm not quite sure what xform means in (into to xform from). But I guess it is something else...)

答:
or allows you to specify a fallback of [nil] if some-expression yields nil or false:

(into [] (or (some-expression) [nil]))

https://clojuredocs.org/clojure.core/or