Magento 2 – Area code not set when running script via command line CLI

I have created module for exporting my product data to script outside of Magento2.

This is my Data.php

<?php namespace Oktarin\Nabavanet\Helper;  class Data extends \Magento\Framework\App\Helper\AbstractHelper {    protected $  markup=1.03;   protected $  markup_extra=1.02;   protected $  price_limit=1500.00;   protected $  pricefile;   protected $  prices;   protected $  pdv=0.25;   protected $  base_url="https://domain.com/index.php/catalog/product/view/id/";   protected $  base_image_url="https://domain.com/pub/media/catalog/product";   protected $  shipping_cost=35.00;   protected $  cats;   protected $  appState; /*   public function __construct(\Magento\Framework\App\Helper\Context $  context,\Magento\Framework\App\State $  state) {     $  this->appState = $  state;      parent::__construct($  context);   }      public function execute() {     $  originalArea = $  this->state->getAreaCode();     $  this->appState->setAreaCode('frontend');     //reset original code     $  this->appState->setAreaCode($  originalArea);   } */    public function getProductCollection()     {         $  collection = $  this->_productCollectionFactory->create();         return $  collection;     } // end of function getProductCollection     public function makeXml(){ /* */   //  $  originalArea = $  this->state->getAreaCode();       $  objectManager = \Magento\Framework\App\ObjectManager::getInstance();     $  this->appState= $  objectManager->create('Magento\Framework\App\State');     $  this->appState->setAreaCode('frontend');     $  productCollection = $  objectManager->create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');     $  collection = $  productCollection->create()                 ->addAttributeToSelect('*')                // ->addAttributeToFilter('sku', array('like' => '%702638%'))                 ->load();  $  product=array();     foreach ($  collection as $  product_data){       if(!empty($  product_data->getEntity_id())){           //Load the product categories         $  categories1 = $  product_data->getCategoryIds();         //Select the last category in the list         $  categoryId = end($  categories1);         $  categoryObject=\Magento\Framework\App\ObjectManager::getInstance();         $  category=$  categoryObject->create('Oktarin\Nabavanet\Helper\CategoryTree');         $  categoryTreepath=$  category->getTreeByCategoryId($  categoryId);          if(!empty($  product_data->getspecial_price())){             $  price=$  product_data->getspecial_price();             $  regular_price=$  product_data->getprice();          }         else{           $  price=$  product_data->getprice();           $  regular_price=false;         }          // Dostupnost proizvoda           switch($  product_data->getproduct_availability()){               case "3929":                 // Po narudžbi                 $  availability="Po narudžbi";                 break;               case "3930":                 // Na stanju                 $  availability="Raspoloživo";                 break;               case "3931":                 // Zalihe pri kraju                 $  availability="Raspoloživost potrebno provjeriti";                 break;                   }            $  product[]=array(             "internal_product_id" => $  product_data->getEntity_id(),             "sku" => $  product_data->getsku(),             "ean" => $  product_data->getean(),             "name" => $  product_data->getName(),             "url" => $  this->base_url.$  product_data->getEntity_id()."/s/".$  product_data->geturl_key()."/",             "availability" => $  availability,             "category" => $  categoryTreepath,             "image_url" => $  this->base_image_url.$  product_data->getimage(),             "additional_image_url" => $  this->base_image_url.$  product_data->getsmall_image(),             "description" => $  product_data->getshort_description(),             "shipping_cost" => $  this->shipping_cost,             "regular_price" => $  regular_price,             "brand" => $  product_data->getbrand(),             "part_number" => $  product_data->getpart_number(),             "warranty" => $  product_data->getgarancija_proizvoda(),             "price" => $  price,             "specialPrice" => $  product_data->getspecial_price(),             "tehnickaSpecifikacija" => $  product_data->getdescription()           );         } // end of of entity_id isnt empty       } // end of foreach          //reset original code     $  this->appState->setAreaCode($  originalArea);         return $  product;   } // end of function makeXml  } // end class 

Method makeXml() I am calling from another script in file nabavanet-export.php that is designed to be run from cron/CLI/command line:

#!/usr/bin/php <?php (PHP_SAPI !== 'cli' || isset($  _SERVER['HTTP_USER_AGENT'])) && die('cli only'); require_once __DIR__ . "/include.php";  $  nabavanet=new Xml();    /* MAGENTO start */   // calling on Magento Helpers   use Magento\Framework\App\Bootstrap;   require '../app/bootstrap.php';   $  params = $  _SERVER;   $  bootstrap = Bootstrap::create(BP, $  params);   $  obj = $  bootstrap->getObjectManager();   $  nabava = $  obj->get('\Oktarin\Nabavanet\Helper\Data');   // end of Magento Helpers   /* END Magento */  try{   $  filename="nabavaexport";   $  xml=$  nabavanet->createNabavanetXMLfile($  nabava->createXml(),$  filename); if($  xml==1){     echo "XML ".$  filename.".xml generated!\n";   copy($  filename.".xml", "../nabavanet/".$  filename.".xml"); } else{     echo "XML ".$  filename.".xml not generated\n"; }   } catch (PDOException $  e) {     // detaljan ispis grešaka slanjem     // PDOException objekta preko varijable $  e     // PDO objekta preko varijable $  db     // PDOStatement objekta preko varijable $  stmt     showPDOErrors($  e, $  db_read, $  stmt_read);     showPDOErrors($  e, $  db_write, $  stmt_write); }             ?> 

Script nabavanet-export.php was working fine when run through browser, however when I run it through command line I get this:

Fatal error: Uncaught Magento\Framework\Exception\LocalizedException: Area code is not set in /usr/www/users/shopyb/vendor/magento/framework/App/State.php:152 Stack trace: #0 /usr/www/users/shopyb/vendor/magento/framework/Session/SessionManager.php(173): Magento\Framework\App\State->getAreaCode() #1 /usr/www/users/shopyb/generated/code/Magento/Framework/Session/Generic/Interceptor.php(50): Magento\Framework\Session\SessionManager->start() #2 /usr/www/users/shopyb/vendor/magento/framework/Session/SessionManager.php(130): Magento\Framework\Session\Generic\Interceptor->start() #3 /usr/www/users/shopyb/generated/code/Magento/Framework/Session/Generic/Interceptor.php(14): Magento\Framework\Session\SessionManager->__construct(Object(Magento\Framework\App\Request\Http), Object(Magento\Framework\Session\SidResolver\Proxy), Object(Magento\Framework\Session\Config), Object(Magento\Framework\Session\SaveHandler), Object(Magento\Framework\Session\Validator), Object(Magento\Framework\Session\Storage), Object(Magento\Framework\Stdlib\C in /usr/www/users/shopyb/vendor/magento/framework/Session/SessionManager.php on line 175 

As you can see I have tried implementing fix as said many times:

  public function __construct(\Magento\Framework\App\State $  state, $  name=null) {     $  this->appState = $  state;      parent::__construct($  name);   } 

But this also generated error

So I have tried modifing it like this but without success:

  public function __construct(\Magento\Framework\App\Helper\Context $  context,\Magento\Framework\App\State $  state) {     $  this->appState = $  state;      parent::__construct($  context);   } 

I hope someone can give me pointers how to make file nabavanet-export.php run as command line. I need that outside script because it is depending on other methods required for generating xml.

tshark filtering out same vlan traffic from command line

I am looking for help on how I can filter out same VLAN traffic(i.e. src IPs 10.1.1.0/24 and dst IPs 10.1.1.0/24) out of a capture file and output all other traffic to a txt file.

I am using a batch file to process all the captures using tshark in a directory and want to use a display filter to remove this “same VLAN” traffic to reduce the size of the output.

Here is the batch file I am using:

@echo off  set cDate=captureday set cap_files="*.pcapng" set cap_folder="D:\caps\%cDate%" set outfile-udp=D:\conversations\cap-UDP-%cDate%.txt set outfile-tcp=D:\conversations\cap-TCP-%cDate%.txt set tshark_cmd="c:\Program Files\Wireshark\tshark" set tshark_udp=-Y "!(ipv6)" -q -z conv,udp set tshark_tcp=-Y "!(ip.src in {10.1.1.0/24} && ip.dst in {10.1.1.0/24})" -q -z conv,tcp  echo. > %outfile-udp% echo. > %outfile-tcp%  for /r %cap_folder% %%f in (%cap_files%) do (     echo Processing File: %%f      REM echo == File:  %%f >> %outfile%     %tshark_cmd%  -r %%f %tshark_udp% >> %outfile-udp%     %tshark_cmd%  -r %%f %tshark_tcp% >> %outfile-tcp% )  echo. echo Results in: %outfile-udp%  echo Results in: %outfile-tcp% 

This doesn’t seem to work however so I was wondering if someone out there has done this before and can tell me what I am doing incorrectly here. Basically I am still getting this 10.1.1.0/24 <-> 10.1.1.0/24 traffic.

This is for already existing captures. I have already got a capture filter running this ignores this traffic.

This is an example of the output of the text file:


================================================================================ TCP Conversations Filter:<No Filter>                                                            |       <-      | |       ->      | |     Total     |    Relative    |   Duration   |                                                            | Frames  Bytes | | Frames  Bytes | | Frames  Bytes |      Start     |              | 10.1.1.154:51087        <-> 10.1.1.202:5482           20016   1417372   13477  20140238   33493  21557610     4.393919000       124.2292 10.1.1.154:51088        <-> 10.1.1.201:5482           17479   1170181   11871  17779866   29350  18950047    10.602867000       118.3747 10.1.1.154:52765        <-> 10.1.1.194:2021            7346    584098    4201    338242   11547    922340     0.187889000       128.7159 10.1.1.154:57613        <-> 10.1.1.193:2021            7197    572273    4111    331079   11308    903352     0.182195000       128.7268 10.1.1.154:52120        <-> 10.1.1.192:2021            7180    570921    4104    330495   11284    901416     0.136573000       128.7624 10.1.1.154:61285        <-> 10.1.1.190:2021            7126    566585    4066    327231   11192    893816     0.182070000       128.7277 10.1.1.154:52738        <-> 10.1.1.191:2021            6301    500987    3602    289742    9903    790729    18.821383000       110.0925 

Alternatively if there is a way just to delete out the lines the the source and destination IP’s using SED or findstr I would be happy to do this as well 😉

Many thanks in advance

Cheers

python split file with certain conditions for each end line

I have a .txt file like this:

2019-03-29 12:03:07 line1                      line2                     line3                     .... 2019-03-30 07:05:09 line1                     line2                     .... 2019-03-31 10:03:20 line1                     line2                     .... 

I split the file into several files, like this:

inputData = 'dirname\..' numThrd  = 3 def chunkFiles():     nline = sum(1 for line in open(inputData,'r', encoding='utf-8', errors='ignore'))     chunk_size = math.floor(nline/int(numThrd))     n_thread = int(numThrd)     j = 0     with open(inputData,'r', encoding='utf-8', errors='ignore') as fileout:         for i, line in enumerate(fileout):             if (i + 1 == j * chunk_size and j != n_thread) or i == nline:                 out.close()             if i + 1 == 1 or (j != n_thread and i + 1 == j * chunk_size):                 chunkFile = 'rawData' + str(j+1) + '.txt'                 if os.path.isfile(chunkFile ):                     break                 out = open(chunkFile , 'w+', encoding='utf-8', errors='ignore')                 j = j + 1                 fLine = line[:-1]                 if not matchLine:             if out.closed != True:                 out.write(line)             if i % 1000 == 0 and i != 0: 

However, I want the split file to meet the condition that the last line in the chunk file must be right before the line that has the date.

recent output that I got:

rawData1.txt 2019-03-29 12:03:07 line1                     line2                     .... ------------------------- rawData2.txt                     line50                     line51 2019-03-30 07:05:09 line1                     line2                     ..... 

Desired output:

rawData1.txt 2019-03-29 12:03:07 line1                      line2                     line3                     .... ------------------------- rawData2.txt 2019-03-30 07:05:09 line1                     line2                     .... 

what should I add to the script above to meet that conditions?

Thank you very much

Notice: Undefined variable: from_time1 in C:\xampp\htdocs\cronometro02\response.php on line 6 00:00:00 Aviso: Variável indefinida: from_time1

<?php     session_start();     $  host = "localhost";     $  usuario = "root";     $  senha = "";     $  banco = "tempo";     $  dbcon = new MySQLi("$  host","$  usuario","$  senha","$  banco");     $  duration = "";     $  res = $  dbcon->query("SELECT * FROM timer");     while ($  row = mysqli_fetch_array($  res)){         $  duration = $  row["duration"];     }     $  _SESSION["duration"] = $  duration;     $  _SESSION["start_time"] = date("Y-m-d H:i:s");      $  end_time = $  end_time = date('Y-m-d', strtotime('+'.$  _SESSION["duration"].'minutes', strtotime($  _SESSION["start_time"])));     $  _SESSION["end_time"] = $  end_time;       $  from_time1 = date('Y-m-d H:i:s');     $  to_time1 = $  _SESSION["end_time"];      $  timefirst = strtotime($  from_time1);     $  timesecond = strtotime($  to_time1);      $  differenceinseconds = $  timesecond = $  timefirst;      echo gmdate("H:i:s", $  differenceinseconds); ?>  <div id="response"></div>  <script type="text/javascript">     setInterval(function(){         var xmlhttp = new XMLHttpRequest();         xmlhttp.open("GET","response.php", false);         xmlhttp.send(null);         document.getElementById("response").innerHTML = xmlhttp.responseText;     }, 1000); </script> 

obg: a conexão com banco de dados está funcionando!!

How to load 3MB txt file line by line to a column in postgresql?

I am trying to load some test data to a table which has a column called mytext which has the type TEXT. I have a txt format novel file which is 3MB in size. I am wondering if there is any easy and proper way to load the string line by line to the column mytext instead of looping it in a for loop from my client language. Thanks a lot.

Read 1 line for. each thread

a short time ago a simple script to find the panel of a website, I wanted to try again to do it with thread but after a while I got stuck.

My code takes 2 path files to create one with all the combinations and puts it in a “results” variable. I didn’t understand how I can (if I can) make each thread take a line of the file and execute the function that should …

//variable with site + word combination results = [site+word for site in sites for word in words]

for line in results: line2 = str(line)

def run(n, name): print(‘ {}. ‘.format(line2))

// request… status code ecc…

time.sleep(n) print('{} finish'.format(line2)) 

start = time.time() for i in range(5): t = threading.Thread(target=run, name=’thread{}’.format(i) , args=(3, ‘thread{}’.format(line2)))

thread_list.append(t) t.start() print('{} è partito'.format(t.name)) 

for t in thread_list: t.join()

end = time.time() print(“time taken : {}”.format(end-start))

Output : Hi http://uno.com/santissimo. thread0 go Hi http://uno.com/santissimo. thread1 go Hi http://uno.com/santissimo. thread2 go Hi http://uno.com/santissimo. thread3 go Hi http://uno.com/santissimo. thread4 go [OK] 200 [OK] 200 [OK] 200 [OK] 200 [OK]

I want my threads take 1 line of the result var, and start doing the run function … Where I’m wrong ? Thanks all

Surpress command line questions during package installation

I have an Ubuntu 16.04 based appliance in which packages from the public repository are installed. But not directly using the public repository. Instead an update server is used which downloads the packages and then puts them into one file. An updater on system gets that files, extracts the packages and installs them.

Recently the base-files package gives me some trouble which contains the file /etc/issue (seems it contains the Ubuntu version):

Setting up base-files (9.4ubuntu4.8) ...  Configuration file '/etc/issue'  ==> Modified (by you or by a script) since installation.  ==> Package distributor has shipped an updated version.    What would you like to do about it ?  Your options are:     Y or I  : install the package maintainer's version     N or O  : keep your currently-installed version       D     : show the differences between the versions       Z     : start a shell to examine the situation  The default action is to keep your current version. 

The updater installed the package using the following command line so far:

DEBIAN_FRONTEND=noninteractive /usr/bin/apt-get -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" --quiet --yes --force-yes install [Absolute path of the packages] 

After that problem occurred I tried the following command line:

DEBIAN_FRONTEND=noninteractive /usr/bin/apt-get -o Dpkg::Options::="--force-confnew" --quiet --yes --force-yes install [Absolute path of the packages] 

But that unfortunately didn’t change anything.

Now my question is, if there is any option out there, which would fix that behaviour.