问:
How to Bulk insert with a dynamic value for a column
the situation is this:

I have 200 txt files with different names like 601776.txt each file's name is actually an ID_foo and it contains some data like this (2 columns):

```<code>04004 Albánchez
04006 Albox
04008 Alcóntar
04009 Alcudia de Monteagud
.
.
.
</code>```

now I wanna BULK INSERT these TXT files into a SQL Server Table which has 3 column one of these columns should be the name of the txt file. I'm using a PHP script, so I made a loop to get the file names and then what?

```<code>BULK INSERT Employee_Table
    FROM '../home/601776.txt'
    WITH (
         FIELDTERMINATOR ='\t',
         ROWTERMINATOR = ''\n''
        )
</code>```

how can i set the third column while bulk inserting with $file_name variable in each loop?

Do you think it is a better idea if it is possible to insert the table by reading the txt file line by line? And how?

Thanks

答:
This is one of the few times that a cursor is actually ideal in SQL Server. Here's a way. Once you see the PRINT statement and are satisfied you can comment it out and uncomment out the two lines below it. I put some logic in to add the file name and a processed date which is usually needed, but your table definition would need these columns. It should get the idea across. </p>

```<code>---------------------------------------------------------------------------------------------------------------
--Set some variables
---------------------------------------------------------------------------------------------------------------

DECLARE @dt VARCHAR(10)                                                         --date variable but stored as VARCHAR for formatting of file name
DECLARE @fileLocation VARCHAR(128) = 'E:\DATA_TRANSFERS\'                       --production location which is \\issqlstd01 but the xp_dirtree didn't like this
DECLARE @sql NVARCHAR(4000)                                                     --dynamic sql variable
DECLARE @fileName VARCHAR(128)                                                  --full file name variable

---------------------------------------------------------------------------------------------------------------
--Get a list of all the file names in the directory
---------------------------------------------------------------------------------------------------------------

IF OBJECT_ID('tempdb..#FileNames') IS NOT NULL DROP TABLE #FileNames
CREATE TABLE #FileNames (
    id int IDENTITY(1,1)
    ,subdirectory nvarchar(512)
    ,depth int
    ,isfile bit)
INSERT #FileNames (subdirectory,depth,isfile)
EXEC xp_dirtree @fileLocation, 1, 1

---------------------------------------------------------------------------------------------------------------
--Create a cursor to fetch the file names
---------------------------------------------------------------------------------------------------------------

DECLARE c CURSOR FOR
select subdirectory from #FileNames where isfile = 1

OPEN c
FETCH NEXT FROM c INTO @fileName

---------------------------------------------------------------------------------------------------------------
--For each file, bulk insert
---------------------------------------------------------------------------------------------------------------

WHILE @@FETCH_STATUS = 0
    BEGIN

        SET @sql = 'BULK INSERT Employee_Table FROM '''+ @fileLocation + @fileName +''' WITH (FIELDTERMINATOR = ''\t'',KEEPNULLS,ROWTERMINATOR = ''0x0a'')'

        --Try the bulk insert, if error is thrown log the error
        --Also update the Table Columns which aren't a part of the original file (load date and original file name)
        BEGIN TRY
            PRINT(@sql)
            --EXEC(@sql)
            --UPDATE Employee_Table SET OrigFile = @fileName, LoadDate = GETDATE() WHERE OrigFile IS NULL
        END TRY
        BEGIN CATCH
            SELECT ERROR_MESSAGE()
        END CATCH

        FETCH NEXT FROM c INTO @fileName
    END

CLOSE c
DEALLOCATE c

GO
</code>```

Body:
the situation is this:

I have 200 txt files with different names like 601776.txt each file's name is actually an ID_foo and it contains some data like this (2 columns):

04004 Albánchez
04006 Albox
04008 Alcóntar
04009 Alcudia de Monteagud
.
.
.

now I wanna BULK INSERT these TXT files into a SQL Server Table which has 3 column one of these columns should be the name of the txt file. I'm using a PHP script, so I made a loop to get the file names and then what?

BULK INSERT Employee_Table
    FROM '../home/601776.txt'
    WITH (
         FIELDTERMINATOR ='\t',
         ROWTERMINATOR = ''\n''
        )

how can i set the third column while bulk inserting with $file_name variable in each loop?

Do you think it is a better idea if it is possible to insert the table by reading the txt file line by line? And how?

Thanks

Body:
This is one of the few times that a cursor is actually ideal in SQL Server. Here's a way. Once you see the PRINT statement and are satisfied you can comment it out and uncomment out the two lines below it. I put some logic in to add the file name and a processed date which is usually needed, but your table definition would need these columns. It should get the idea across.

---------------------------------------------------------------------------------------------------------------
--Set some variables
---------------------------------------------------------------------------------------------------------------

DECLARE @dt VARCHAR(10)                                                         --date variable but stored as VARCHAR for formatting of file name
DECLARE @fileLocation VARCHAR(128) = 'E:\DATA_TRANSFERS\'                       --production location which is \\issqlstd01 but the xp_dirtree didn't like this
DECLARE @sql NVARCHAR(4000)                                                     --dynamic sql variable
DECLARE @fileName VARCHAR(128)                                                  --full file name variable

---------------------------------------------------------------------------------------------------------------
--Get a list of all the file names in the directory
---------------------------------------------------------------------------------------------------------------

IF OBJECT_ID('tempdb..#FileNames') IS NOT NULL DROP TABLE #FileNames
CREATE TABLE #FileNames (
    id int IDENTITY(1,1)
    ,subdirectory nvarchar(512)
    ,depth int
    ,isfile bit)
INSERT #FileNames (subdirectory,depth,isfile)
EXEC xp_dirtree @fileLocation, 1, 1

---------------------------------------------------------------------------------------------------------------
--Create a cursor to fetch the file names
---------------------------------------------------------------------------------------------------------------

DECLARE c CURSOR FOR
select subdirectory from #FileNames where isfile = 1

OPEN c
FETCH NEXT FROM c INTO @fileName

---------------------------------------------------------------------------------------------------------------
--For each file, bulk insert
---------------------------------------------------------------------------------------------------------------

WHILE @@FETCH_STATUS = 0
    BEGIN

        SET @sql = 'BULK INSERT Employee_Table FROM '''+ @fileLocation + @fileName +''' WITH (FIELDTERMINATOR = ''\t'',KEEPNULLS,ROWTERMINATOR = ''0x0a'')'

        --Try the bulk insert, if error is thrown log the error
        --Also update the Table Columns which aren't a part of the original file (load date and original file name)
        BEGIN TRY
            PRINT(@sql)
            --EXEC(@sql)
            --UPDATE Employee_Table SET OrigFile = @fileName, LoadDate = GETDATE() WHERE OrigFile IS NULL
        END TRY
        BEGIN CATCH
            SELECT ERROR_MESSAGE()
        END CATCH

        FETCH NEXT FROM c INTO @fileName
    END

CLOSE c
DEALLOCATE c

GO


来源: stackexchange

问:
How to copy a large file in Windows XP?
I have a large file in windows XP - its 38GB. (a VM image)

I cannot seem to copy it.

Dragging on the desktop - gives error of "Insufficient system resources exist to complete the requested service"

Using Java - FileChannel.transferTo(0, fileSize, dest) fails for all files > 2GB

Using Java - FileChannel.transferTo() in chunks of 100Mb fails after ~18Gb

```<code>java.io.IOException: Insufficient system resources exist to complete the requested service
at sun.nio.ch.FileDispatcher.write0(Native Method)
at sun.nio.ch.FileDispatcher.write(FileDispatcher.java:44)
at sun.nio.ch.IOUtil.writeFromNativeBuffer(IOUtil.java:72)
at sun.nio.ch.IOUtil.write(IOUtil.java:28)
at sun.nio.ch.FileChannelImpl.write(FileChannelImpl.java:198)
at sun.nio.ch.FileChannelImpl.transferToTrustedChannel(FileChannelImpl.java:439)
at sun.nio.ch.FileChannelImpl.transferTo(FileChannelImpl.java:510)
</code>```

I mean - the computer has 3GB of RAM. A 100GB buffer should be enough!?!?

Apparently the DOS commands "copy" and "xcopy" also fail.

(edit) I've tried COPY & XCOPY - these fail with the same error. XCOPY seems to take a really really long time about it too.

I've heard of Robocopy, but it doesn't copy single files?

I'm really feeling that Windows is for the lose right now. Surely microsoft have heard of files larger than a few GB?

Thanks!

答:
There may be a hardware issue as well..
I suspect you don't have much time, however you may try dumber stream solution and don't set large buffers (8-16MB should be enough):</p>

```<code>public static void copy(InputStream input, OutputStream output) throws IOException {
     byte[] buffer = new byte[1024 * 1024 * 8]; // 8MB
     int n = 0;
     while (-1 != (n = input.read(buffer))) {
         output.write(buffer, 0, n);
     }
}

public static void main(String args[]) {

    if (args.length != 2) {
        System.err.println("wrong argument count");
        System.exit(1);
    }

    FileInputStream in = null;
    FileOutputStream out = null;

    try {
        in = new FileInputStream(new File(args[0]));
        out = new FileOutputStream(new File(args[1]));
        copy(in, out);
    } catch (Exception e) {
        e.printStackTrace();
    }

    if (in != null) { try { in.close(); } catch (Exception e) {}}
    if (out != null) { try { out.close(); } catch (Exception e) {}}

}
</code>```

ContentLicense: CC BY-SA 2.5

Title: How to copy a large file in Windows XP?

Body:
I have a large file in windows XP - its 38GB. (a VM image)

I cannot seem to copy it.

Dragging on the desktop - gives error of "Insufficient system resources exist to complete the requested service"

Using Java - FileChannel.transferTo(0, fileSize, dest) fails for all files > 2GB

Using Java - FileChannel.transferTo() in chunks of 100Mb fails after ~18Gb

java.io.IOException: Insufficient system resources exist to complete the requested service
at sun.nio.ch.FileDispatcher.write0(Native Method)
at sun.nio.ch.FileDispatcher.write(FileDispatcher.java:44)
at sun.nio.ch.IOUtil.writeFromNativeBuffer(IOUtil.java:72)
at sun.nio.ch.IOUtil.write(IOUtil.java:28)
at sun.nio.ch.FileChannelImpl.write(FileChannelImpl.java:198)
at sun.nio.ch.FileChannelImpl.transferToTrustedChannel(FileChannelImpl.java:439)
at sun.nio.ch.FileChannelImpl.transferTo(FileChannelImpl.java:510)

I mean - the computer has 3GB of RAM. A 100GB buffer should be enough!?!?

Apparently the DOS commands "copy" and "xcopy" also fail.

(edit) I've tried COPY & XCOPY - these fail with the same error. XCOPY seems to take a really really long time about it too.

I've heard of Robocopy, but it doesn't copy single files?

I'm really feeling that Windows is for the lose right now. Surely microsoft have heard of files larger than a few GB?

Thanks!

Body:
There may be a hardware issue as well..
I suspect you don't have much time, however you may try dumber stream solution and don't set large buffers (8-16MB should be enough):

public static void copy(InputStream input, OutputStream output) throws IOException {
     byte[] buffer = new byte[1024 * 1024 * 8]; // 8MB
     int n = 0;
     while (-1 != (n = input.read(buffer))) {
         output.write(buffer, 0, n);
     }
}

public static void main(String args[]) {

    if (args.length != 2) {
        System.err.println("wrong argument count");
        System.exit(1);
    }

    FileInputStream in = null;
    FileOutputStream out = null;

    try {
        in = new FileInputStream(new File(args[0]));
        out = new FileOutputStream(new File(args[1]));
        copy(in, out);
    } catch (Exception e) {
        e.printStackTrace();
    }

    if (in != null) { try { in.close(); } catch (Exception e) {}}
    if (out != null) { try { out.close(); } catch (Exception e) {}}

}


问:
Is there a way to call a function on closing the server process in shiny?
I have a shiny application in which I am making some connections to databases and other components. I wish to close these connections when the app is brought down. Is there a way to execute a function when the shiny app is closed?</p>

答:
As mentioned in the comments by @jdharrison you can us session$onSessionEnded in the shiny server.

This extremely simple example will print a message to the console when you close the app, but you can replace that print statement with some statements that close the database connections.

```<code>library(shiny)
ui <- fluidPage(
   #Empty UI
)

server <- function(input, output,session) {

  session$onSessionEnded(function() {
    print('hello, the session has ended')
  })
}

shinyApp(ui = ui, server = server)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
As mentioned in the comments by @jdharrison you can us session$onSessionEnded in the shiny server.

This extremely simple example will print a message to the console when you close the app, but you can replace that print statement with some statements that close the database connections.

library(shiny)
ui <- fluidPage(
   #Empty UI
)

server <- function(input, output,session) {

  session$onSessionEnded(function() {
    print('hello, the session has ended')
  })
}

shinyApp(ui = ui, server = server)


问:
PHP/Laravel file existence verification not working
I have a <form> with a multiple file input that stores those files into the server. The names of the files must follow a numeric standard and that's why I rename them before storing. Each post has an ID an can have more than one file so the pattern is: post-id + dash and a number + file extension, this way, if the same post has two file with the same extensions, the dash + number will avoid them to be overwriten. So, before I store the files I run a loop to find the proper number to the name. The problem is, the function to verify the existence of the file seems not to be returning true when it should. The code:

```<code>$counter = 0;
do{
  $nomeArquivo = $post->id . "-{$counter}"  . "." . $arq->extension();

  $counter++;
//these commented are other ways of verification I tried
//}while(Storage::exists($nomeArquivo));
//}while(file_exists("/storage/" . $nomeArquivo));
}while(is_file("/storage/" . $post->id . "-{$counter}"));

Storage::putFileAs('/public', $arq, $nomeArquivo);
</code>```

This code above runs inside a foreach($files as $arq) where $files are the files from the form input.

Reference: https://laravel.com/docs/5.4/filesystem and https://laravel.com/api/5.4/Illuminate/Filesystem/Filesystem.html

答: As user @fubar pointed in the comments, I was referencing the wrong path to verify the existence of the file. I change the while condition to while(\File::exists(public_path() . '/storage/' . $nomeArquivo)) and it worked well. Thanks

Body:
I have a <form> with a multiple file input that stores those files into the server. The names of the files must follow a numeric standard and that's why I rename them before storing. Each post has an ID an can have more than one file so the pattern is: post-id + dash and a number + file extension, this way, if the same post has two file with the same extensions, the dash + number will avoid them to be overwriten. So, before I store the files I run a loop to find the proper number to the name. The problem is, the function to verify the existence of the file seems not to be returning true when it should. The code:

$counter = 0;
do{
  $nomeArquivo = $post->id . "-{$counter}"  . "." . $arq->extension();

  $counter++;
//these commented are other ways of verification I tried
//}while(Storage::exists($nomeArquivo));
//}while(file_exists("/storage/" . $nomeArquivo));
}while(is_file("/storage/" . $post->id . "-{$counter}"));

Storage::putFileAs('/public', $arq, $nomeArquivo);

This code above runs inside a foreach($files as $arq) where $files are the files from the form input.

Reference: https://laravel.com/docs/5.4/filesystem and https://laravel.com/api/5.4/Illuminate/Filesystem/Filesystem.html


问:
Rename third party shared library has no effect?
I have a library that is provided by a third party, the file name is libPXTrader.so. But I want to rename it to trader.so in my project. So I just renamed it. The weird things is that after I compiled my main file using

```<code>gcc main.o third_party/lib/trader.so -o main
</code>```

the executable file main is still link to libPXTrader.so.
using command

```<code>ldd main
</code>```

It shows that libPXTrader.so cannot be found. I used strings trader.so and find the string libPXTrader.so, I guest this shared library name is hardcoded into the so file. How can I deal with it?

答: Ok, let me answer my own question. In libPXTrader.so, there is a .dynamic section, where there is an optional field called SONAME, if SONAME is set to an non-empty string, even if you rename libPXTrader.so, the main file is still linked to libPXTrader.so.</p>

Body:
I have a library that is provided by a third party, the file name is libPXTrader.so. But I want to rename it to trader.so in my project. So I just renamed it. The weird things is that after I compiled my main file using

gcc main.o third_party/lib/trader.so -o main

the executable file main is still link to libPXTrader.so.
using command

ldd main

It shows that libPXTrader.so cannot be found. I used strings trader.so and find the string libPXTrader.so, I guest this shared library name is hardcoded into the so file. How can I deal with it?


问:
How to fix integration issue Magento store with POS system after site migration?
We migrated our Magento site (Magento 1.8.1.0) from old server to a new server.

But, we can't use the Winepos integration extension any more.

Our site is connected with Winepos system, and this Magento extension had been operated before migrating work.

This is Winepos API manual.

At this time, we think some PHP modules were not installed on our new server.

But, we don't know which PHP modules were not installed. It seems all PHP modules were installed on our new server.

The Magento extension to integrate with Winepos are as follow. This extension is consisted with two files.

Config.xml

```<code><config>
 <global>
   <events>
     <checkout_onepage_controller_success_action>
       <observers>
         <igor_winepos_order_success_observer>
           <type>singleton</type>
           <class>igor_Winepos_Model_Wineposobserver</class>
           <method>checkoutSuccessObserve</method>
         </igor_winepos_order_success_observer>
       </observers>
     </checkout_onepage_controller_success_action>
    </events>
   </global>
  </config>
</code>```

wineposobserver.php

```<code>class igor_Winepos_Model_Wineposobserver extends Varien_Event_Observer {

  function customlog($obj) {
    ob_start();
    var_dump($obj);
    $out1 = ob_get_contents();
    ob_end_clean();
    $f = fopen('/tmp/log.txt', 'ab');
    fwrite($f, $out1);
    fclose($f);
  }

  public function __construct() {
  }

  public function checkoutSuccessObserve($observer) {
    // $event = $observer->getEvent();
    $order_ids = $observer->getData('order_ids');
    if(gettype($order_ids) == 'array' && count($order_ids) == 1) {
       $the_order = Mage::getModel('sales/order')->load($order_ids[0]);
       Mage::helper('globalfunc')->registerOrderWithWinePOSAsynchronousWithTimeout($the_order);
    }
 }
}
</code>```

I am getting the following in the Apache log:

PHP Warning: PHP Startup: apc.shm_segments setting ignored in MMAP mode in Unknown on line 0 [Sun Apr 30 06:32:30 2017] [notice] Apache/2.2.22 (Ubuntu) mod_ssl/2.2.22 OpenSSL/1.0.1 configured -- resuming normal operations

```<code> 285:   function registerOrderWithWinePOSAsynchronousWithTimeout($the_order) {
 286      try {
 287        $items = $the_order->getAllItems();
 ...
 426          $ordered_raw_item = $ordered_products_raw_items[$ordered_product_id];
 428:         $product_winepos_id = trim(strval($product->getResource()->getAttribute('winepos_id')->getFrontend()->getValue($product)));
 429
 430          $item_element = $doc->createElement('item');
 432          $item_num_element = $doc->createElement('item-num');
 433:         $item_num_element->appendChild($doc->createTextNode(strval($product_winepos_id)));
 434          $item_element->appendChild($item_num_element);
 ...
 466        $the_xml = $doc->saveXML();
 468:       // $post_result = Mage::helper('globalfunc')->post_to_api_winepos('https://wines-in-november.vznlink.com/orders', $the_xml, 'admin276975', '8dc670fb943dc2c0a1415405cdf00e3ec579c4e6', 8, 10);
 470:       return Mage::helper('globalfunc')->delayed_post_to_winepos($the_xml);
 471      } catch(Exception $e) {
 472        $this->customlog($e);
 ...
 475    }
</code>```

答:
I created a new module to integrate with POS system and implemented inventory synchronization successfully.
This work should be done by cron job. To do it, I created three individual script files.
Also, POS provider should provide ordered product information including inventory information as txt file via ftp in every time interval.

```<code>lftp -u [username],[password] -e'set ftp:passive-mode false; cd files; put data.txt; quit' [folder name]
</code>```

The cron job operating blocks are as follow.

cron_file_mover.php

```<code>  $start = microtime(true);
  shell_exec('cp /home/files/data.txt /var/www/vhosts/magento/');
  shell_exec('chown -R www-data:www-data /var/www/vhosts/magento/');
  $end = microtime(true);
  echo 'Run time: '.round($end-$start, 4).'s';
</code>```

cron_pos_post_script.php

```<code>Utils::initMagento(); $MAX_RETRIES = 5;
$delayed_jobs = Utils::mageGetRows("select * from delayed_jobs where job_type = 'pos_order' and status = 'todo' order by created_at DESC");
$current_index = 0;
foreach($delayed_jobs as $delayed_job) {
  $current_index += 1;
  $retry_count = intval($delayed_job['retry_count']);
  $retry_count += 1;
  $post_result = Mage::helper('globalfunc')->post_to_api_pos('https://vznlink.com/orders', $delayed_job['job_details'], 'admin', 'fd93d2de58ab', 8, 10);
   Utils::mageSqlExecute("update delayed_jobs set status = 'done' where id = " . $delayed_job['id']);

Utils::mageSqlExecute("update delayed_jobs set status = '" . $new_status . "', retry_count = " . $retry_count . " where id = " . $delayed_job['id']);
}
</code>```

cron_pos_update_script.php

```<code>$PATH_TO_FILE = '/var/www/vhosts/magento/data.txt';

function read_pos_file($path_to_file) {
  $min_count_required_for_product = 12;
  $f = fopen($path_to_file, 'rb');
  $text = trim(fread($f, 100000000));
  fclose($f);
  $lines = preg_split('/\r\n|\r|\n/i', $text);
  $products = array();
  foreach($lines as $line) {
  $product = preg_split('/\t/i', trim($line));
  if(count($product) >= $min_count_required_for_product) {
      $product[0] = strval(trim($product[0]));
      $product[1] = strval(trim($product[1]));
      $product[2] = strval(trim($product[2]));
      $product[11] = intval(strval(trim($product[11])));
      $products []= $product;
  }
}
  return $products;
}

function update_stock_for_stock_item($product_id, $new_stock) {
   $stock_item = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product_id);
   $stock_item->setData('qty', $new_stock);
   if($new_stock > 0) {
      $stock_item->setData('is_in_stock', 1);
   }
   $stock_item->save();
}
   $products = read_pos_file($PATH_TO_FILE);
   $total_count = 0; $processed_count = 0;
   foreach($products as $product) {
     $total_count += 1;
     $item_number = $product[0];
     $new_stock = $product[11];
     if($new_stock < 0) {
        $new_stock = 0;
     }
   $products_matching_item_number = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect('pos_id')->addFieldToFilter('pos_id', $item_number)->getItems();
   if(count($products_matching_item_number) == 1) {
      $products_matching_item_number = array_values($products_matching_item_number);
      $matching_product = $products_matching_item_number[0];
      $matching_product_id = $matching_product->getId();
      update_stock_for_stock_item($matching_product_id, $new_stock);
      $processed_count += 1;
   }
}
</code>```

The cron job settings are as follows.

```<code>10 * * * * /usr/bin/php /var/www/vhosts/magento/pos/cron_winepos_post_script.php &> /dev/null
10 * * * * /usr/bin/php /var/www/vhosts/magento/pos/cron_winepos_update_script.php &> /dev/null
20 * * * * /usr/bin/php /var/www/vhosts/magento/pos/cron_pos_file_mover.php &> /dev/null
</code>```

Keep in mind, checking POS data provided from POS system, cron job setting, checking update script operations.

Body:
We migrated our Magento site (Magento 1.8.1.0) from old server to a new server.

But, we can't use the Winepos integration extension any more.

Our site is connected with Winepos system, and this Magento extension had been operated before migrating work.

This is Winepos API manual.

At this time, we think some PHP modules were not installed on our new server.

But, we don't know which PHP modules were not installed. It seems all PHP modules were installed on our new server.

The Magento extension to integrate with Winepos are as follow. This extension is consisted with two files.

Config.xml

<config>
 <global>
   <events>
     <checkout_onepage_controller_success_action>
       <observers>
         <igor_winepos_order_success_observer>
           <type>singleton</type>
           <class>igor_Winepos_Model_Wineposobserver</class>
           <method>checkoutSuccessObserve</method>
         </igor_winepos_order_success_observer>
       </observers>
     </checkout_onepage_controller_success_action>
    </events>
   </global>
  </config>

wineposobserver.php

class igor_Winepos_Model_Wineposobserver extends Varien_Event_Observer {

  function customlog($obj) {
    ob_start();
    var_dump($obj);
    $out1 = ob_get_contents();
    ob_end_clean();
    $f = fopen('/tmp/log.txt', 'ab');
    fwrite($f, $out1);
    fclose($f);
  }

  public function __construct() {
  }

  public function checkoutSuccessObserve($observer) {
    // $event = $observer->getEvent();
    $order_ids = $observer->getData('order_ids');
    if(gettype($order_ids) == 'array' && count($order_ids) == 1) {
       $the_order = Mage::getModel('sales/order')->load($order_ids[0]);
       Mage::helper('globalfunc')->registerOrderWithWinePOSAsynchronousWithTimeout($the_order);
    }
 }
}

I am getting the following in the Apache log:

PHP Warning: PHP Startup: apc.shm_segments setting ignored in MMAP mode in Unknown on line 0 [Sun Apr 30 06:32:30 2017] [notice] Apache/2.2.22 (Ubuntu) mod_ssl/2.2.22 OpenSSL/1.0.1 configured -- resuming normal operations

 285:   function registerOrderWithWinePOSAsynchronousWithTimeout($the_order) {
 286      try {
 287        $items = $the_order->getAllItems();
 ...
 426          $ordered_raw_item = $ordered_products_raw_items[$ordered_product_id];
 428:         $product_winepos_id = trim(strval($product->getResource()->getAttribute('winepos_id')->getFrontend()->getValue($product)));
 429
 430          $item_element = $doc->createElement('item');
 432          $item_num_element = $doc->createElement('item-num');
 433:         $item_num_element->appendChild($doc->createTextNode(strval($product_winepos_id)));
 434          $item_element->appendChild($item_num_element);
 ...
 466        $the_xml = $doc->saveXML();
 468:       // $post_result = Mage::helper('globalfunc')->post_to_api_winepos('https://wines-in-november.vznlink.com/orders', $the_xml, 'admin276975', '8dc670fb943dc2c0a1415405cdf00e3ec579c4e6', 8, 10);
 470:       return Mage::helper('globalfunc')->delayed_post_to_winepos($the_xml);
 471      } catch(Exception $e) {
 472        $this->customlog($e);
 ...
 475    }

Body:
I created a new module to integrate with POS system and implemented inventory synchronization successfully.
This work should be done by cron job. To do it, I created three individual script files.
Also, POS provider should provide ordered product information including inventory information as txt file via ftp in every time interval.

lftp -u [username],[password] -e'set ftp:passive-mode false; cd files; put data.txt; quit' [folder name]

The cron job operating blocks are as follow.

cron_file_mover.php

  $start = microtime(true);
  shell_exec('cp /home/files/data.txt /var/www/vhosts/magento/');
  shell_exec('chown -R www-data:www-data /var/www/vhosts/magento/');
  $end = microtime(true);
  echo 'Run time: '.round($end-$start, 4).'s';

cron_pos_post_script.php

Utils::initMagento(); $MAX_RETRIES = 5;
$delayed_jobs = Utils::mageGetRows("select * from delayed_jobs where job_type = 'pos_order' and status = 'todo' order by created_at DESC");
$current_index = 0;
foreach($delayed_jobs as $delayed_job) {
  $current_index += 1;
  $retry_count = intval($delayed_job['retry_count']);
  $retry_count += 1;
  $post_result = Mage::helper('globalfunc')->post_to_api_pos('https://vznlink.com/orders', $delayed_job['job_details'], 'admin', 'fd93d2de58ab', 8, 10);
   Utils::mageSqlExecute("update delayed_jobs set status = 'done' where id = " . $delayed_job['id']);

Utils::mageSqlExecute("update delayed_jobs set status = '" . $new_status . "', retry_count = " . $retry_count . " where id = " . $delayed_job['id']);
}

cron_pos_update_script.php

$PATH_TO_FILE = '/var/www/vhosts/magento/data.txt';

function read_pos_file($path_to_file) {
  $min_count_required_for_product = 12;
  $f = fopen($path_to_file, 'rb');
  $text = trim(fread($f, 100000000));
  fclose($f);
  $lines = preg_split('/\r\n|\r|\n/i', $text);
  $products = array();
  foreach($lines as $line) {
  $product = preg_split('/\t/i', trim($line));
  if(count($product) >= $min_count_required_for_product) {
      $product[0] = strval(trim($product[0]));
      $product[1] = strval(trim($product[1]));
      $product[2] = strval(trim($product[2]));
      $product[11] = intval(strval(trim($product[11])));
      $products []= $product;
  }
}
  return $products;
}

function update_stock_for_stock_item($product_id, $new_stock) {
   $stock_item = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product_id);
   $stock_item->setData('qty', $new_stock);
   if($new_stock > 0) {
      $stock_item->setData('is_in_stock', 1);
   }
   $stock_item->save();
}
   $products = read_pos_file($PATH_TO_FILE);
   $total_count = 0; $processed_count = 0;
   foreach($products as $product) {
     $total_count += 1;
     $item_number = $product[0];
     $new_stock = $product[11];
     if($new_stock < 0) {
        $new_stock = 0;
     }
   $products_matching_item_number = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect('pos_id')->addFieldToFilter('pos_id', $item_number)->getItems();
   if(count($products_matching_item_number) == 1) {
      $products_matching_item_number = array_values($products_matching_item_number);
      $matching_product = $products_matching_item_number[0];
      $matching_product_id = $matching_product->getId();
      update_stock_for_stock_item($matching_product_id, $new_stock);
      $processed_count += 1;
   }
}

The cron job settings are as follows.

10 * * * * /usr/bin/php /var/www/vhosts/magento/pos/cron_winepos_post_script.php &> /dev/null
10 * * * * /usr/bin/php /var/www/vhosts/magento/pos/cron_winepos_update_script.php &> /dev/null
20 * * * * /usr/bin/php /var/www/vhosts/magento/pos/cron_pos_file_mover.php &> /dev/null

Keep in mind, checking POS data provided from POS system, cron job setting, checking update script operations.


问:
Unable to 'Grant admin consent to the add-in' when enabling SSO for OfficeJS app
I'm attempting the build a Microsoft first party app using OfficeJS.  In trying to enable the app to retrieve an SSO token, I can't "grant admin consent to the add-in".  When I try to navigate to

https://login.microsoftonline.com/common/adminconsent?client_id={application_ID}&state=12345

with my app_id plugged in, I get a permissions denied message.  {App name} needs permission to access resources in your organization that only an admin can grant. Please ask an admin to grant permission to this app before you can use it.

I am attempting this through a Microsoft work account.  Is this feature strictly limited to O365 accounts?

答: The feature is currently in preview and only works with Office 365 (work or school) accounts at this time. (Not Microsoft Accounts.) To grant admin consent you must be logged in as an admin of the O365 tenancy. </p>


问:
Best way of adding SNMP support to your own application on Debian
I am working on Debian and I have this server we want to monitor.

The application is ours and there are around a hundred real-time counters we want to export for monitoring purposes, graphs and alarms.

I've been looking at the Debian way of doing this because we do use Debian packaging to install the app, and Debian uses snmpd daemon, based on net-snmp, to export SNMP.
So far every approach I've seen looks very complicated, from recompiling snmpd to load a dynamic library into it, and compiling a form of subagent that replicates what snmpd does.

While all of those options make me think I should go for something else than SNMP I don't want to give up that early and I was wondering if anybody has found a feasible implementation.

Ideally it should be coded in C or C++ as the app is in C++, but I'm open to wrappers or other kind of suggestions.

答: Have you tried net-snmp?</p>

Body: Have you tried net-snmp?


问:
keycode conversions, consider using Xvfb
Google Chrome last version from official repository

ChromeDriver last version installed

Selenium last version installed

My wdio.conf.js

```<code>desiredCapabilities: {
    browserName: process.env.BROWSER || 'chrome',
    chromeOptions: {
      args: [
            '--disable-gpu',
            '--headless',
            '--no-sandbox',
          ],
      prefs: {
        'download.default_directory': __dirname + '/tmp/test/download',
        'download.prompt_for_download': false
      }
    }
  },
</code>```

My error

Some test working and after get error.

```<code>  ✓ restore password (500ms)

[07:07:40]  COMMAND POST     "/wd/hub/session/21b26bbb-c9ee-4a4e-89de-ac6e8180fe9c/element/34/value"
[07:07:40]  DATA         {"value":["s","i","m","u","l","a","t","i","o","n"]}
[07:07:41]  INFO    Retry #1
[07:07:41]  ERROR   ServerError unknown error: an X display is required for keycode conversions, consider using Xvfb
[07:07:41]  INFO    Retry #2
[07:07:41]  ERROR   ServerError unknown error: an X display is required for keycode conversions, consider using Xvfb
[07:07:41]  INFO    Gave up after 3 tries
</code>```

How to fix this?

答:
Sending keys currently does not work without a (virtual) XServer.

There is an open ticket: https://bugs.chromium.org/p/chromedriver/issues/detail?id=1772

And also a workaround, replace the sendkeys call with JavaScript: https://github.com/Automattic/wp-e2e-tests/issues/515#issuecomment-301165065

Or you have to use Xvfb, like the driver error message and the other answer suggested.

Body:
Google Chrome last version from official repository

ChromeDriver last version installed

Selenium last version installed

My wdio.conf.js

desiredCapabilities: {
    browserName: process.env.BROWSER || 'chrome',
    chromeOptions: {
      args: [
            '--disable-gpu',
            '--headless',
            '--no-sandbox',
          ],
      prefs: {
        'download.default_directory': __dirname + '/tmp/test/download',
        'download.prompt_for_download': false
      }
    }
  },

My error

Some test working and after get error.

  ✓ restore password (500ms)

[07:07:40]  COMMAND POST     "/wd/hub/session/21b26bbb-c9ee-4a4e-89de-ac6e8180fe9c/element/34/value"
[07:07:40]  DATA         {"value":["s","i","m","u","l","a","t","i","o","n"]}
[07:07:41]  INFO    Retry #1
[07:07:41]  ERROR   ServerError unknown error: an X display is required for keycode conversions, consider using Xvfb
[07:07:41]  INFO    Retry #2
[07:07:41]  ERROR   ServerError unknown error: an X display is required for keycode conversions, consider using Xvfb
[07:07:41]  INFO    Gave up after 3 tries

How to fix this?


问:
JIRA API: Get epic for issue
Is there a way in which I could get the epic for an issue ?

The api returns a lot of information about an issue, but the epic is not included.

I'm using the JIRA REST API (https://developer.atlassian.com/display/JIRADEV/JIRA+REST+APIs).

答:
I wanted to extract the epic name for an issue and this stumped me for a few days.
The key was to realise that an epic is just a parent issue, and the epic name is the summary field of the parent issue.

So:

Step 1

Find the custom field of where the epic is stored by using the editmeta query:

https://[your-jira-hostname]/jira/rest/api/2/issue/[issue-number]/editmeta

This will yield something like below which reveals the custom field Id we need

```<code>{
  "fields": {
    <SNIP>
    "customfield_12360": {
      "required": false,
      "schema": {
        "type": "any",
        "custom": "com.pyxis.greenhopper.jira:gh-epic-link",
        "customId": 12360
      },
      "name": "Epic Link",
      "operations": [
        "set"
      ]
    }
    <SNIP>
  }
}
</code>```

Step 2

Query your issue, pulling out the custom field value

https://[your-jira-hostname]/jira/rest/api/2/issue/[issue-number]?fields=customfield_12360,summary

if our issue is JIRA-34 say, this will yield something like

```<code>{
  "expand": "renderedFields,names,schema,operations,editmeta,changelog,versionedRepresentations",
  "id": "39080",
  "key": "JIRA-34",
  "fields": {
    "summary": "Write heavily upvoted answers for stack overflow",
    "customfield_12360": "JIRA-33"
  }
}
</code>```

Step 3

Now we know the issue number of our epic is JIRA-33, so now query the epic...

https://[your-jira-hostname]/jira/rest/api/2/issue/JIRA-33?fields=summary

```<code>{
      "expand": "renderedFields,names,schema,operations,editmeta,changelog,versionedRepresentations",
      "id": "39080",
      "key": "JIRA-33",
      "fields": {
        "summary": "Improve StackOverflow reptuation"
      }
    }
</code>```

The name of the epic for JIRA-34 is "Improve StackOverflow reptuation"

Done.

Title: JIRA API: Get epic for issue

Body:
I wanted to extract the epic name for an issue and this stumped me for a few days.
The key was to realise that an epic is just a parent issue, and the epic name is the summary field of the parent issue.

So:

Step 1

Find the custom field of where the epic is stored by using the editmeta query:

https://[your-jira-hostname]/jira/rest/api/2/issue/[issue-number]/editmeta

This will yield something like below which reveals the custom field Id we need

{
  "fields": {
    <SNIP>
    "customfield_12360": {
      "required": false,
      "schema": {
        "type": "any",
        "custom": "com.pyxis.greenhopper.jira:gh-epic-link",
        "customId": 12360
      },
      "name": "Epic Link",
      "operations": [
        "set"
      ]
    }
    <SNIP>
  }
}

Step 2

Query your issue, pulling out the custom field value

https://[your-jira-hostname]/jira/rest/api/2/issue/[issue-number]?fields=customfield_12360,summary

if our issue is JIRA-34 say, this will yield something like

{
  "expand": "renderedFields,names,schema,operations,editmeta,changelog,versionedRepresentations",
  "id": "39080",
  "key": "JIRA-34",
  "fields": {
    "summary": "Write heavily upvoted answers for stack overflow",
    "customfield_12360": "JIRA-33"
  }
}

Step 3

Now we know the issue number of our epic is JIRA-33, so now query the epic...

https://[your-jira-hostname]/jira/rest/api/2/issue/JIRA-33?fields=summary

{
      "expand": "renderedFields,names,schema,operations,editmeta,changelog,versionedRepresentations",
      "id": "39080",
      "key": "JIRA-33",
      "fields": {
        "summary": "Improve StackOverflow reptuation"
      }
    }

The name of the epic for JIRA-34 is "Improve StackOverflow reptuation"

Done.


问:
Include text on the splash screen Android
I am using this popular method from this site to make a splash screen:
Splash Screens the Right Way.

And I want to display a translated text "loading" to different languages. This was asked earlier in the comments section, and the author replied, but I do not know how to do what he says. Here is what he replied: https://www.bignerdranch.com/blog/splash-screens-the-right-way/#comment-2633426495

How can i draw the text on the screen? (If it's posible) Or as it says there, How to "include" it in the drawable?

Is another method preferable?

答:
```<code>Here is my splash activity xml
This is an easy solution and places the text bellow the image.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:background="@color/colorIcons"
tools:context=".SplashActivity">

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_centerVertical="true"
    android:gravity="center"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/splashImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="30dp"
        android:gravity="center_horizontal"
        android:scaleType="fitCenter"
        android:src="@mipmap/ic_launcher">
    </ImageView>

    <TextView
        android:id="@+id/splashText"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:text="@string/app_name"
        android:textColor="@color/colorPrimary_text"
        android:textSize="36sp" />
</LinearLayout>
</code>```


问:
SlideUp / SlideDown causes a jump
I am using a slideUp and slideDown JQuery slide effect on one of my webpages to get the Basic Search and Advanced Search with More/Less option. It is functioning perfectly. I am using this code. But the problem is when I click more option, it jumps while sliding. But When I use the same in Admin mode (after logging in to website as Admin), it works smoothly. I have tried many methods which I found on Internet, but couldn't work out. Can anyone check my code if it has any problem?

Thanks for your time.

EDIT: When does it jumps?
 - By default there is a basic search and a "More Option Button" When I
   click More Option, It slides up the Basic Search and slidesDown the
   Advanced Search simultaneously, and when slideDown of Advanced Search
   is about to complete, it suddenly jumps. I hope it makes sense.

EDIT2: Here is the
fiddle. This is sample code, As I have some select statements in Advanced Search, we can clearly see when it jumps.

```<code><script>
    jQuery.noConflict();
    jQuery(document).ready(function($) {
        $(".view-filters").hide();
        $(".more").click(function() {

            $(".search-form").slideUp("slow");
            $(".view-filters").slideDown("slow");
        });
        $(".less").click(function() {
            $(".view-filters").slideUp("slow");
            $(".search-form").slideDown("slow");
        });
    });
</script>

<< There is some code here for Search form. >>

<div class = "search-form more"><b>More Options</b> <img src = "images/down_arrow.jpg"></img></div>
<div class = "view-filters less"><b>Less Options</b> <img src = "images/up_arrow1.jpg"></img></div>

<style>
    .search-form
    {
        overflow: hidden;

    }
    .view-filters
    {
        display:block;
    }
    .pager
    {
        display:none;
    }
    table
    {
        display:none;
    }
</style>

<< There is some code here for Advanced Search Form>>
</code>```

答:
For anyone who has a similar issue, the overarching problem seems to be in the value of margin on certain elements.

On a page that included Bootstrap 3.3.7 I was using slideUp() on a div that contained an
 as well as some other stuff.

The key to stopping the jump that occured as soon as I called slideUp() on the div was to set margin-top:0px on the
 it contained.

Title: SlideUp / SlideDown causes a jump

Body:
I am using a slideUp and slideDown JQuery slide effect on one of my webpages to get the Basic Search and Advanced Search with More/Less option. It is functioning perfectly. I am using this code. But the problem is when I click more option, it jumps while sliding. But When I use the same in Admin mode (after logging in to website as Admin), it works smoothly. I have tried many methods which I found on Internet, but couldn't work out. Can anyone check my code if it has any problem?

Thanks for your time.

EDIT: When does it jumps?
 - By default there is a basic search and a "More Option Button" When I
   click More Option, It slides up the Basic Search and slidesDown the
   Advanced Search simultaneously, and when slideDown of Advanced Search
   is about to complete, it suddenly jumps. I hope it makes sense.

EDIT2: Here is the
fiddle. This is sample code, As I have some select statements in Advanced Search, we can clearly see when it jumps.

<< There is some code here for Search form. >>

More Options

Less Options

<< There is some code here for Advanced Search Form>>

Body:
For anyone who has a similar issue, the overarching problem seems to be in the value of margin on certain elements.

On a page that included Bootstrap 3.3.7 I was using slideUp() on a div that contained an <h3> as well as some other stuff.

The key to stopping the jump that occured as soon as I called slideUp() on the div was to set margin-top:0px on the <h3> it contained.

ContentLicense: CC BY-SA 4.0


问:
Is it possible to re-generate Lucene index in background?
Sometimes there is need to re-generate a lucene index, e.g. when something changes in the Compass mapping or in the way boosts are applied, or if something went corrupt for whatever reason.

In my case, generation of the index takes about 5 to 6 hours, clearing the index before leads to data not being complete for this interval. I. e. doing a search in this time returns an incomplete result.

Is there any standard way to have lucene generate the index in the background? E.g. write index to a temporary directory and (when indexing is finished without exceptions etc) replace the existing index with the new one?

Of course, one could implement this "manually", but does one have to? Sounds like a common use case to me.

Best regards + Thanks for your opinion,

Peter :)

答:
We have a similar problem. Our data is indexed in Lucene, but the original source is DB and content repo.

So if an index goes out of sync (or data type changes, etc.), we simply iterate over all existing entries in the index and re-generate the data so each document gets updated. It is not really a complex thing to do.


问:
Model inheritance in Laravel without plugins
What i am trying to achieve is a base model that has certain fields and sub models that have even more custom fields. I found some hacky solutions that used a field in the table to define the subtype, but that does not feel right.

So here is an example of what i need:
I have a model Pet that has common fields like name, age, gender. However, i do not wanna use this model directly (so it is okay if it is e.g. abstract).

Then i have sub models like for example:

Bird that has the field lengthOfWings

Spider that has numberOfEyes

Dog that has breed

How can this be done cleanly?

答:
Create a class animal.

ex:

class animal extends Model

{

//some statement here

}

Then create another class or model

class Dog extends Animal
{

// statement here

}

i hope this helps


问:
How to get listview position?
I have problem in Listview onListItemClick() method. I am not getting the position of the list.
Here is my code Pls help me

coverletterselection.xml

```<code>    <RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/bgg"     />
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:orientation="vertical"
        android:layout_height="wrap_content">
        <ImageView
            android:layout_width="fill_parent"
            android:background="@drawable/blackstrip"
            android:layout_height="wrap_content" />
        <ImageView
            android:layout_width="fill_parent"
            android:id="@+id/coverletterbgView"
            android:background="@drawable/imgselectcoverltrresume"
            android:layout_height="wrap_content" />
        <ListView
            android:id="@+id/list"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"    />
    </LinearLayout>
    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
        <ImageButton
            android:layout_width="wrap_content"
            android:layout_marginLeft="5sp"
            android:background="@drawable/submission"
            android:layout_height="wrap_content" />
        <ImageButton
            android:layout_width="wrap_content"
            android:background="@drawable/iconaddplus"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_marginRight="10sp"/>
    </RelativeLayout>
</RelativeLayout>
</code>```

Java File

```<code> public class MainActivity extends ListActivity implements OnItemClickListener
{
    int ht,wt;
ListView list;
    DataHelperCoverLetter dbcl;
    ArrayList<String> coverLetterTitle = new ArrayList<String>();

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.coverletterselection);

        dbcl = new DataHelperCoverLetter(this);
        DisplayMetrics displaymetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
        ht = displaymetrics.heightPixels;
        wt = displaymetrics.widthPixels;
        bg = (ImageView)findViewById(R.id.coverletterbgView);
        bg.setLayoutParams(new LinearLayout.LayoutParams(wt, ht/3));

        coverLetterTitle = dbcl.fetchCoverLetter();

            //get the listView from your layout and define the listener on it
            list = (ListView)findViewById(R.id.list);
            list.setOnItemClickListener(this);

        addCoverLetterBtn = (ImageButton)findViewById(R.id.addCoverLetter);
        addCoverLetterBtn.setOnClickListener(this);
        setListAdapter(new CoverLetterAdaptor(this,ht,wt,coverLetterTitle));
    }
    @Override
    public void onListItemClick(ListView parent, View view, int position, long id)
    {
        Log.i("OnClick", "position = "+position);

    }
}

public class CoverLetterAdaptor extends BaseAdapter
{
    private LayoutInflater mInflater;
    ArrayList<String> coverLetterItems;
    Context context;
    int ht,wt;

    public CoverLetterAdaptor(Context context,int ht,int wt,ArrayList<String> coverLetterItems)
    {
        this.context = context;
        this.coverLetterItems = new ArrayList<String>();
        this.coverLetterItems = coverLetterItems ;
        this.ht = ht;
        this.wt = wt;
        mInflater = LayoutInflater.from(context);
    }

    public int getCount() {
        return coverLetterItems.size();
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent)
    {
        ViewHolder holder;

        convertView = mInflater.inflate(R.layout.coverletteradaptor, null);
        holder = new ViewHolder();

        holder.coverLetterTxt = (TextView) convertView.findViewById(R.id.coverLetterAdaptorTxt);
        holder.bgImageCCAdaptor = (ImageView)convertView.findViewById(R.id.bgimageCoverLetter);
        holder.bgImageCCAdaptor.setLayoutParams(new RelativeLayout.LayoutParams(wt, ht/7));

        convertView.setTag(holder);
        holder = (ViewHolder) convertView.getTag();
        holder.coverLetterTxt.setText(coverLetterItems.get(position));
        return convertView;
    }

    static class ViewHolder
    {
        TextView coverLetterTxt;
        ImageView bgImageCCAdaptor;
    }
}
</code>```

答:
I had the same problems, and this helped me</p>

```<code>protected void populateView(View v, String s, int position) {
    ListUserNames.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            TextView textView = (TextView) view.findViewById(R.id.discr_for_task);
            String username = ListUserNames.getItemAtPosition(position).toString().trim();
        }
    }
}
</code>```

Title: How to get listview position?

Body:
I have problem in Listview onListItemClick() method. I am not getting the position of the list.
Here is my code Pls help me

coverletterselection.xml

    <RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/bgg"     />
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:orientation="vertical"
        android:layout_height="wrap_content">
        <ImageView
            android:layout_width="fill_parent"
            android:background="@drawable/blackstrip"
            android:layout_height="wrap_content" />
        <ImageView
            android:layout_width="fill_parent"
            android:id="@+id/coverletterbgView"
            android:background="@drawable/imgselectcoverltrresume"
            android:layout_height="wrap_content" />
        <ListView
            android:id="@+id/list"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"    />
    </LinearLayout>
    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
        <ImageButton
            android:layout_width="wrap_content"
            android:layout_marginLeft="5sp"
            android:background="@drawable/submission"
            android:layout_height="wrap_content" />
        <ImageButton
            android:layout_width="wrap_content"
            android:background="@drawable/iconaddplus"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_marginRight="10sp"/>
    </RelativeLayout>
</RelativeLayout>

Java File

 public class MainActivity extends ListActivity implements OnItemClickListener
{
    int ht,wt;
ListView list;
    DataHelperCoverLetter dbcl;
    ArrayList<String> coverLetterTitle = new ArrayList<String>();

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.coverletterselection);

        dbcl = new DataHelperCoverLetter(this);
        DisplayMetrics displaymetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
        ht = displaymetrics.heightPixels;
        wt = displaymetrics.widthPixels;
        bg = (ImageView)findViewById(R.id.coverletterbgView);
        bg.setLayoutParams(new LinearLayout.LayoutParams(wt, ht/3));

        coverLetterTitle = dbcl.fetchCoverLetter();

            //get the listView from your layout and define the listener on it
            list = (ListView)findViewById(R.id.list);
            list.setOnItemClickListener(this);

        addCoverLetterBtn = (ImageButton)findViewById(R.id.addCoverLetter);
        addCoverLetterBtn.setOnClickListener(this);
        setListAdapter(new CoverLetterAdaptor(this,ht,wt,coverLetterTitle));
    }
    @Override
    public void onListItemClick(ListView parent, View view, int position, long id)
    {
        Log.i("OnClick", "position = "+position);

    }
}

public class CoverLetterAdaptor extends BaseAdapter
{
    private LayoutInflater mInflater;
    ArrayList<String> coverLetterItems;
    Context context;
    int ht,wt;

    public CoverLetterAdaptor(Context context,int ht,int wt,ArrayList<String> coverLetterItems)
    {
        this.context = context;
        this.coverLetterItems = new ArrayList<String>();
        this.coverLetterItems = coverLetterItems ;
        this.ht = ht;
        this.wt = wt;
        mInflater = LayoutInflater.from(context);
    }

    public int getCount() {
        return coverLetterItems.size();
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent)
    {
        ViewHolder holder;

        convertView = mInflater.inflate(R.layout.coverletteradaptor, null);
        holder = new ViewHolder();

        holder.coverLetterTxt = (TextView) convertView.findViewById(R.id.coverLetterAdaptorTxt);
        holder.bgImageCCAdaptor = (ImageView)convertView.findViewById(R.id.bgimageCoverLetter);
        holder.bgImageCCAdaptor.setLayoutParams(new RelativeLayout.LayoutParams(wt, ht/7));

        convertView.setTag(holder);
        holder = (ViewHolder) convertView.getTag();
        holder.coverLetterTxt.setText(coverLetterItems.get(position));
        return convertView;
    }

    static class ViewHolder
    {
        TextView coverLetterTxt;
        ImageView bgImageCCAdaptor;
    }
}

Body:
I had the same problems, and this helped me

protected void populateView(View v, String s, int position) {
    ListUserNames.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            TextView textView = (TextView) view.findViewById(R.id.discr_for_task);
            String username = ListUserNames.getItemAtPosition(position).toString().trim();
        }
    }
}


问:
Property initialization using "by lazy" vs. "lateinit"
In Kotlin, if you don't want to initialize a class property inside the constructor or in the top of the class body, you have basically these two options (from the language reference):

Lazy Initialization

lazy() is a function that takes a lambda and returns an instance of Lazy<T> which can serve as a delegate for implementing a lazy property: the first call to get() executes the lambda passed to lazy() and remembers the result, subsequent calls to get() simply return the remembered result.

Example

```<code>public class Hello {

   val myLazyString: String by lazy { "Hello" }

}
</code>```

So, the first call and the subsequential calls, wherever it is, to myLazyString will return Hello

Late Initialization

Normally, properties declared as having a non-null type must be initialized in the constructor. However, fairly often this is not convenient. For example, properties can be initialized through dependency injection, or in the setup method of a unit test. In this case, you cannot supply a non-null initializer in the constructor, but you still want to avoid null checks when referencing the property inside the body of a class.

To handle this case, you can mark the property with the lateinit modifier:

```<code>public class MyTest {

   lateinit var subject: TestSubject

   @SetUp fun setup() { subject = TestSubject() }

   @Test fun test() { subject.method() }
}
</code>```

The modifier can only be used on var properties declared inside the body of a class (not in the primary constructor), and only when the property does not have a custom getter or setter. The type of the property must be non-null, and it must not be a primitive type.

So, how to choose correctly between these two options, since both of them can solve the same problem?

答:
If you are using Spring container and you want to initialize non-nullable bean field, lateinit is better suited.

    @Autowired
    lateinit var myBean: MyBean
```

Body:
In Kotlin, if you don't want to initialize a class property inside the constructor or in the top of the class body, you have basically these two options (from the language reference):

Lazy Initialization

lazy() is a function that takes a lambda and returns an instance of Lazy<T> which can serve as a delegate for implementing a lazy property: the first call to get() executes the lambda passed to lazy() and remembers the result, subsequent calls to get() simply return the remembered result.

Example

public class Hello {

   val myLazyString: String by lazy { "Hello" }

}

So, the first call and the subsequential calls, wherever it is, to myLazyString will return Hello

Late Initialization

Normally, properties declared as having a non-null type must be initialized in the constructor. However, fairly often this is not convenient. For example, properties can be initialized through dependency injection, or in the setup method of a unit test. In this case, you cannot supply a non-null initializer in the constructor, but you still want to avoid null checks when referencing the property inside the body of a class.

To handle this case, you can mark the property with the lateinit modifier:

public class MyTest {

   lateinit var subject: TestSubject

   @SetUp fun setup() { subject = TestSubject() }

   @Test fun test() { subject.method() }
}

The modifier can only be used on var properties declared inside the body of a class (not in the primary constructor), and only when the property does not have a custom getter or setter. The type of the property must be non-null, and it must not be a primitive type.

So, how to choose correctly between these two options, since both of them can solve the same problem?


问:
Disabling the flickering of overlapping planes
You know, when there are for example two planes in the same position, in different colors, they will start kind of battling against each other so some parts are another texture and some parts other.

I think that Scenekit's renderingOrder should fix this, but i couldn't get it to work. I gave planeA 0 for renderingOrder and planeB 1, but nothing happened.

So basically i want to have two planes in the same position, but i want another to be "dominative" so that the dominative plane will be rendered, and not the other.

答:
This is commonly referred to as Z-fighting, and has been an issue in 3D for as long as 3D has existed.

There are two basic, and not ideal, ways to deal with this, for what I currently understand of your situation:

1. Remove the plane you don't want to be seeing, until you need it, probably when the camera goes around the other side, or some other condition changes, at which point you'll need to add the plane you need, and remove the other.

2. Ever so slightly separate them in "Z space", or whatever space makes sense to push them just so slightly apart. This can be an incredibly small amount, so small that it's impossible for the viewer to perceive that the planes are not in exactly the same space.


问:
How to Use array[i] in for loop
I am trying to search for a value in an array. Does the array need a definative number? How would I search for the number? Thanks for helping!</p>

```<code>#include <stdio.h>
#include <conio.h>
#include <iostream>
#include "windows.h"

using namespace std;
int main() {
    int userinput;

    int arrayofnumber[10] = { 5, 3, 77, 43, 6, 22, 7, 9, 84, 26 };

    int NumberInArray = sizeof(arrayofnumber) / sizeof(arrayofnumber[0]);

    cout << "What Number Would You Like To Search For? \n";
    cout << "Number of Values in Array = " << NumberInArray << endl;
    cin >> userinput;

    for (int i = 0; i >= NumberInArray; i++) {

        if (userinput == NumberInArray[i]) {
            cout << "We Found IT! It = " << NumberInArray[i] << endl;
        }

    }

    return 0;
}
</code>```

答:
The standard provides us with find to do this. So I'd suggest using C++'s implementation rather than trying to write it yourself, doing so will also eliminate your need for NumberInArray:

```<code>if(cend(arrayofnumber) != find(cbegin(arrayofnumber), cend(arrayofnumber), userinput)) cout << "We Found IT! It = " << userinput << endl;
</code>```

Live Example

Title: How to Use array[i] in for loop

Body:
I am trying to search for a value in an array. Does the array need a definative number? How would I search for the number? Thanks for helping!

#include <stdio.h>
#include <conio.h>
#include <iostream>
#include "windows.h"

using namespace std;
int main() {
    int userinput;

    int arrayofnumber[10] = { 5, 3, 77, 43, 6, 22, 7, 9, 84, 26 };

    int NumberInArray = sizeof(arrayofnumber) / sizeof(arrayofnumber[0]);

    cout << "What Number Would You Like To Search For? \n";
    cout << "Number of Values in Array = " << NumberInArray << endl;
    cin >> userinput;

    for (int i = 0; i >= NumberInArray; i++) {

        if (userinput == NumberInArray[i]) {
            cout << "We Found IT! It = " << NumberInArray[i] << endl;
        }

    }

    return 0;
}

Body:
The standard provides us with find to do this. So I'd suggest using C++'s implementation rather than trying to write it yourself, doing so will also eliminate your need for NumberInArray:

if(cend(arrayofnumber) != find(cbegin(arrayofnumber), cend(arrayofnumber), userinput)) cout << "We Found IT! It = " << userinput << endl;

Live Example