text:
Q: Large Data import with PHP, MySQL and XML I am building a script that imports the data from an uploaded XML file into MySQL, but not directly. The function itself has only one query, but it always times out. That query has to join two tables to find a single ID that would be inserted with the XML data in a third table.
Here is the function that does it:
public function imprtTVLApi($file) {
    global $db, $user;
    $ext = pathinfo($file, PATHINFO_EXTENSION);
    $message = '';
    $text = '';
    $streaming_websites = array(
        'megavideo.com' => '1',
        'vidxden' => '2',
        'videobb.com' => '4',
        'veevr.com' => '5',
        'vureel.com' => '6',
        '2gb-hosting.com' => '7',
        'videoweed.com' => '9',
        'divxhosting.net' => '11',
        'movshare.net' => '12',
        'novamov.com' => '13',
        'ovfile.com' => '14',
        'videozer.com' => '15',
        'putlocker.com' => '16',
        'sockshare.com' => '17',
        'videoweed.es' => '18',
        'uploadc.com' => '19',
        'wupload.com' => '20',
        'vidbux.com' => '21',
        'veoh.com' => '22',
        'mixturevideo.com' => '23',
        'youtube.com' => '24',
        'filebox.com' => '25',
        'filenuke.com' => '26',
        'hostingbulk.com' => '27',
        'zalaa.com' => '28',
        'nowvideo.eu' => '29',
        'vidhog.com' => '30',
        'bitshare.com' => '31',
        'muchshare.net' => '32',
        'allmyvideos.net' => '33',
        'gorillavid.in' => '34',
        'daclips.in' => '35',
        'movpod.in' => '36',
        'stream2k.eu' => '37'
    );
    if ( $ext == "xml") :
        $tv  = new DomDocument();
        $tv->recover = TRUE;
        $tv->load($file) or die("Could not load the file! " .$file);
        $tvSearch = $tv->getElementsByTagName( "url" );
        $count = 0;

        foreach( $tvSearch as $tv ) {

            // name
            $names = $tv->getElementsByTagName('name');
            $name = $names->item(0)->nodeValue;

            // seasons
            $seasons = $tv->getElementsByTagName('season');
            $season = $seasons->item(0)->nodeValue;

            // episode
            $episodes = $tv->getElementsByTagName('episode');
            $episode = $episodes->item(0)->nodeValue;

            // episode
            $links = $tv->getElementsByTagName('loc');
            $link = $links->item(0)->nodeValue;

            $user = $user->uid;
            $url  = $db->escape($link);
            $stream1 = $this->getHostFromURL($url);
            $stream = $streaming_websites[$stream1];
            $added = time();
            $status = "ok";
            $sql = 'SELECT e.id AS epid FROM ' .$this->epTable. ' AS e INNER JOIN ' .$this->tvTable. ' AS t ON e.show_ID = t.id WHERE t.title = "' .$name. '" AND e.season = "' .$season. '" AND e.episode = "' .$episode. '" LIMIT 1';
            $row = $db->first($sql);

            if( isset($row['epid'])) {

                $data = array(
                    'user_ID' => $user,
                    'url' => sanitize($url),
                    'stream_ID' => $stream,
                    'e_ID' => intval($row['epid']),
                    'added' => intval($added),
                    'status' => $status
                );

                $text .= "INSERT IGNORE INTO " .$this->lkTable. " (`user_ID`, `url`, `stream_ID`, `e_ID`, `added`, `status`) VALUES ('" .$data['user_ID']. "', '" .$data['url']. "', '" .$data['stream_ID']. "', '" .$data['e_ID']. "', '" .$data['added']. "', '" .$data['status']. "')";

            } else {
                $message = "Show not found";
            }
            $count++;

        }
        $myFile =  "export_" .$user->uid. "_" .time(). ".sql";
        $fh = fopen($myFile, 'w') or die("can't open file");
        $stringData = $text;
        fwrite($fh, $stringData);
        fclose($fh);
        parse_mysql_dump($myFile);
        unlink($myFile);
        $message = "Links: " .$count. ", Your links were added and they will show up on the site in a minute!";
    else :
        $message = "Incorrect file format! Must be XML!";
    endif;
    print($message);
}

And here is the database structure:
--
-- Table structure for table `episodes2`
--

CREATE TABLE IF NOT EXISTS `episodes2` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `title` varchar(80) NOT NULL DEFAULT 'Untitled',
  `show_ID` int(11) unsigned NOT NULL,
  `episode` bigint(3) unsigned NOT NULL DEFAULT '1',
  `season` bigint(3) unsigned NOT NULL DEFAULT '1',
  `description` text NOT NULL,
  `thumbnail` varchar(100) NOT NULL,
  `tvragepage` varchar(80) NOT NULL,
  `airdate` int(15) unsigned DEFAULT '0',
  `added` datetime DEFAULT '0000-00-00 00:00:00',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=2000117 ;

-- --------------------------------------------------------

--
-- Table structure for table `tvshows2`
--

CREATE TABLE IF NOT EXISTS `tvshows2` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `imdbid` varchar(10) CHARACTER SET latin1 NOT NULL,
  `tvrageid` varchar(125) CHARACTER SET latin1 NOT NULL,
  `poster` varchar(256) CHARACTER SET latin1 NOT NULL,
  `slider` varchar(225) NOT NULL,
  `title` varchar(128) NOT NULL,
  `tagline` varchar(128) CHARACTER SET latin1 NOT NULL,
  `plot` text CHARACTER SET latin1 NOT NULL,
  `year` year(4) NOT NULL,
  `released` varchar(18) CHARACTER SET latin1 NOT NULL,
  `country` varchar(256) CHARACTER SET latin1 NOT NULL,
  `channel` smallint(3) NOT NULL DEFAULT '0',
  `runtime` char(6) CHARACTER SET latin1 NOT NULL,
  `storyline` text CHARACTER SET latin1 NOT NULL,
  `genres` varchar(256) CHARACTER SET latin1 NOT NULL,
  `actors` text CHARACTER SET latin1 NOT NULL,
  `votes` varchar(10) CHARACTER SET latin1 NOT NULL,
  `timezone` varchar(10) CHARACTER SET latin1 NOT NULL,
  `oscars` tinyint(4) NOT NULL,
  `seasons` int(4) NOT NULL,
  `mpaa` enum('TV-14','TV-Y','TV-PG','TV-MA') CHARACTER SET latin1 NOT NULL DEFAULT 'TV-14',
  `trivia` text CHARACTER SET latin1 NOT NULL,
  `status` enum('never_aired','cancelled_ended','returning_series','new_series','on_hiatus','tbd','pilot_rejected','in_development','pilot_ordered') CHARACTER SET latin1 NOT NULL DEFAULT 'returning_series',
  `permalink` varchar(125) NOT NULL,
  `classification` varchar(35) CHARACTER SET latin1 NOT NULL DEFAULT 'Unavailable',
  `airtime` varchar(150) CHARACTER SET latin1 NOT NULL DEFAULT 'Unavailable',
  `airday` varchar(80) CHARACTER SET latin1 NOT NULL DEFAULT 'Monday',
  `ended` varchar(20) CHARACTER SET latin1 NOT NULL,
  UNIQUE KEY `id_2` (`id`),
  UNIQUE KEY `permalink` (`permalink`),
  KEY `id` (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=31994 ;

-- --------------------------------------------------------

--
-- Table structure for table `tv_links`
--

CREATE TABLE IF NOT EXISTS `tv_links` (
  `link_ID` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `user_ID` int(11) NOT NULL DEFAULT '0',
  `url` varchar(225) CHARACTER SET latin1 NOT NULL,
  `stream_ID` int(11) NOT NULL,
  `e_ID` int(11) NOT NULL DEFAULT '1',
  `added` int(11) DEFAULT NULL,
  `status` enum('ok','broken','deleted','pending') CHARACTER SET latin1 NOT NULL DEFAULT 'ok',
  PRIMARY KEY (`link_ID`),
  UNIQUE KEY `url` (`url`),
  KEY `e_ID` (`e_ID`)
) ENGINE=InnoDB

The data is sent to MySQL after a .sql file is created by the loop.
The key here is to find the episode id that would be imported in the links table.
Do you have any suggestions on how to make it faster or any ideas?


text:
Q: highstock: how to change color in areaspline when series intersect sma good morning guys,
I need your help for a problem that I can not solve.
I need to highlight the intersections between a simple data series and the related moving average.
The data of the moving average are automatically generated by HighStock and are not calculated by me (otherwise I would have almost solved the problem!).
If it is not possible to graphically highlight with different colors every time the series is above or below the moving average
I would like to calculate the difference between the two series (in this way I could draw a single line around the zero value with negative red values and values green positive for example).
After numerous researches I have not yet solved my problem. I must say that the documentation of HighChart / HighStock is very complete but it is mainly for professionals.
Thanks for your help!
This is what I need (look at the picture)
    $('#container').highcharts('StockChart', {

    title: { text: 'Relative Strenght' },
    navigator: { enabled: false },
    series: [
        {
            id: 'forza-rel',
            type: 'spline',
            name: 'Rel. Str.',
            data: forza_relativa,
        },
        {
            name: 'M.A. 5',
            type: 'sma',
            linkedTo: 'forza-rel',
            color:'#FF0000',
            dashStyle: 'line',
            marker: { enabled: false },
            params: { period: 5 }
        }
    ]
});

A:
I need to highlight the intersections between a simple data series and
  the related moving average.

It can be done, however, it requires a lot of custom code and it's a bit tricky.

I would like to calculate the difference between the two series

This can be done easily. SMA is just another series, so you have to loop through SMA series data and make a difference between its data and a basic series data. Than use series.setData() method to update the third series with calculated values (areasplie for example).
HTML:

JS:
Highcharts.stockChart('container', {

  chart: {
    height: 500,
    events: {
      load: function() {
        var chart = this,
          series = chart.series,
          data = [],
          offset,
          diff,
          i;

        offset = series[0].xData.length - series[1].xData.length;

        for (i = 0; i < series[1].xData.length; i++) {
          diff = series[0].yData[i + offset] - series[1].yData[i];
          data.push({
            x: series[1].xData[i],
            y: diff
          });
        }

        chart.series[2].setData(data);
      }
    }
  },

  rangeSelector: {
    selected: 0
  },

  title: {
    text: 'AAPL Stock Price'
  },

  legend: {
    enabled: true
  },

  plotOptions: {
    series: {
      showInLegend: true
    }
  },

  yAxis: [{
    height: '60%',
    top: '0%',
    id: '0'
  }, {
    height: '36%',
    top: '62%',
    id: '1'
  }],

  series: [{
    type: 'spline',
    id: 'aapl',
    name: 'AAPL Stock Price',
    data: data,
    yAxis: '0'
  }, {
    type: 'sma',
    linkedTo: 'aapl',
    marker: {
      enabled: false
    },
    yAxis: '0'
  }, {
    type: 'areaspline',
    yAxis: '1',
    color: 'green',
    negativeColor: 'red',
    data: []
  }]
});

Demo:
https://jsfiddle.net/wchmiel/863n241h/3/

redpajama_set_name: RedPajamaStackExchange


text:
Q: Passing multiple arguments in SQL - Python I am trying to pass two arguments into a SQL statement as below:
cursor.execute(f"""select * from table
                   where product_name = '{prod_name}' and date = '{sale_date}'"""")

I am trying to have this run through a loop for several combination so I am trying to see how I can have this altered accordingly.
prod_name = ['prod_a','prod_b']
sale_date = ['2020-01-01','2020-02-01']

I know how to pass one argument through a loop but I am not sure how to pass more than one argument together at the same.

A: It's a security danger to add variables directly to your SQL query.  cursor.execute provides sanitizing as long as you pass the arguments as the second argument of the function call.
Example:
cursor.execute("select * form table where product_name = '%s' and date = '%s'", (prod_name, sale_date))

To loop through multiple lists at once you can do the following (assuming the lists have the same amount of values):
for i in range(len(prod_name)):
    cursor.execute("select * form table where product_name = '%s' and date = '%s'", (prod_name[i], sale_date[i]))

By looping through a range I get the numbers of 0 - len(prod_name) and as I loop with the index of i I can use that to retrieve the first item in both lists.
Sam Mason had a good comment about using the zip function which combines iterators and can be used like so:
for args in zip(prod_name, sale_date):
    cursor.execute("select * form table where product_name = '%s' and date = '%s'", args)

A: try this :
results = ()

dc = ['103,4770634', '42,427752', '64,10122045', '42,13603629', '42,25516425', '103,2748102', '42,1966402', '42,30262834', '42,6667711', '18,13737683', '42,28921168', '42,26076925', '103,3733654', '42,23313527', '64,3307344', '103,3973533', '42,6360982', '48,11846077', '103,3775309', '64,10122050', '42,1965119', '103,4265810', '103,3971645', '103,4962583', '103,689615', '42,22834366', '103,761655', '95,1184', '64,9594482', '42,22855603', '48,8654764', '103,4226756', '42,23366982', '103,3897036', '42,11339650', '101,6369', '42,25830920', '103,5009291', '42,29238961', '59,6299475', '42,22931663', '42,25839056', '43,11864458', '43,41346192', '103,4261645', '42,3747082', '103,4795050', '42,9417503', '103,4245623', '42,61431911']

try:
    sql = "SELECT * FROM tbl1 WHERE id1 in (%s) AND id2 in (%s)"
    in_ids = ', '.join(map(lambda x: '%s', dc))
    in_ids = in_ids % tuple(dc)
    sql = sql % (in_ids, in_ids)
    cursor.execute(sql)
    res = cursor.fetchall()
    results = results + res
except Exception, e:
    print e


text:
Q: Using static records in dynamic zone with Samba and BIND_DLZ I've deployed Samba4 as AD controller using BIND_DLZ as a backend. It works ok. Now I have a bunch of servers with static IP's, and I would like to resolve them, but I can't find a way to do this.
So I googled for a few days, and didn't find anything really helpful. Then I decided to set up one more DNS server serving the same zone, but containing only static records - but I couldn't find a way to make this work. My idea was make this second server a forwarder in the first - but this doesn't work.
Questions are:
1) Is there any way to have static records in the dynamic zone (without fiddling around with static DHCP configuration)?
2) If no, than is it possible to make a two-server setup, where one will have dynamic records, and the other - static records? Where can I read about it?

A: Turns out, samba-tool can be used to achieve static records in dynamic zone.
samba-tool dns add <dnsserver> <domain> <hostname> <record type> <ipaddr> -Uadministrator

i.e.:
samba-tool dns add ns1 example.com host1 A 192.168.1.160 -Uadministrator

More about samba-tool: https://www.samba.org/samba/docs/man/manpages/samba-tool.8.html


text:
Q: how to export function's result to text file in C++?  int main()
{
shape a;           //make class

ostream out;
out.open("test.txt");      // make file
out<< a.draw();           // std::ostream << void        error
                          // draw() { cout<<"ddd"<<endl; }
out.close();
}

I want to wirte draw() in to file.
can you help me?

A: You have two options.
1: Pass the stream to the function and write to that instead of std::cout
void draw(std::ostream& os) { os << "ddd\n"; }

int main()
{
    std::ofstream s("test.txt");
    draw(s);
}

2: Return the result instead of writing it
std::string draw() { return "ddd\n"; }

int main()
{
    std::ofstream s("test.txt");
    s << draw();
}


text:
Q: How to get a Map value inside for loop? I have a Map. When I try to get a value of the map it is not coming inside for loop.
Map<VEH_Vehicle__c,CST_Carset__c> VehSerQuery=getQuerySevice(VehResQuery);

code
public static Map<VEH_Vehicle__c, CST_Carset__c> getQuerySevice(Map<String, VEH_Vehicle__c> mapResponse) {

  Map<VEH_Vehicle__c, CST_Carset__c>  mVehService = new Map<VEH_Vehicle__c, CST_Carset__c>();

  //harvest ids
  Set<Id> setCarsetId  =  new Set<Id>();
  for (String strVin : mapResponse.keyset() )  {
    VEH_Vehicle__c oVeh = mapResponse.get(strVin) ;
    setCarsetId.add(oVeh.UnitOrder__r.CarSet__r.id);
  }
  Map<Id, CST_Carset__c> mCarset = new Map<Id, CST_Carset__c>(
       [SELECT Id,
                  (SELECT Code__c, Label__c, ServiceType__c
                   FROM Services__r)
        FROM CST_Carset__c
        WHERE Id IN:setCarsetId ]);

  for (String  strVin : mapResponse.keyset() ) {
    VEH_Vehicle__c oVeh = mapResponse.get(strVin) ;
    CST_Carset__c lServices = mCarset.get(oVeh.UnitOrder__r.CarSet__r.id);
    mVehService.put(oVeh, lServices);
  }

  return mVehService ;
}

Here VehSerQuery size is 4.Having both key and values''
result
VehSerQuery{
    VEH_Vehicle__c:{UnitOrder__c=a0I4E000000UJEWUA4, DueDate__c=2016-12-30 00:00:00, DepreciationDate__c=2016-08-11 00:00:00, BillingDate__c=2016-08-26 00:00:00, BlockedInvoice__c=B, RegistrationNumber__c=RN9684, VehicleOrderNumber__c=V9684, KeyCode1__c=KC9684, CarRadioCode__c=R697, BCVEnergy__c=EN1, BCVIndexPollution__c=IP1, VINNumber__c=VN15RB20A55579085, Id=a0N4E0000010V4IUAU}=CST_Carset__c:{Id=a074E000000fvVBQAY},
    VEH_Vehicle__c:{UnitOrder__c=a0I4E000000UGw1UAG, DueDate__c=2016-12-30 00:00:00, DepreciationDate__c=2016-08-11 00:00:00, BillingDate__c=2016-08-26 00:00:00, BlockedInvoice__c=B, RegistrationNumber__c=RN19, VehicleOrderNumber__c=V19, KeyCode1__c=KC19, CarRadioCode__c=R19, BCVEnergy__c=EN1, BCVIndexPollution__c=IP1, VINNumber__c=VG1JZ49BJ55611173, Id=a0N4E0000010VgfUAE}=CST_Carset__c:{Id=a074E000000fveNQAQ},
    VEH_Vehicle__c:{UnitOrder__c=a0I4E000000UI90UAG, DueDate__c=2016-12-30 00:00:00, DepreciationDate__c=2016-08-11 00:00:00, BillingDate__c=2016-08-26 00:00:00, BlockedInvoice__c=B, RegistrationNumber__c=RN5213, VehicleOrderNumber__c=V5213, KeyCode1__c=KC5213, CarRadioCode__c=R222, BCVEnergy__c=EN1, BCVIndexPollution__c=IP1, VINNumber__c=VN1RFC00555850061, Id=a0N4E0000010TZjUAM}=CST_Carset__c:{Id=a074E000000fveNQAQ},
    VEH_Vehicle__c:{UnitOrder__c=a0I4E000000UIwqUAG, DueDate__c=2016-12-30 00:00:00, DepreciationDate__c=2016-08-11 00:00:00, BillingDate__c=2016-08-26 00:00:00, BlockedInvoice__c=B, RegistrationNumber__c=RN5813, VehicleOrderNumber__c=V5813, KeyCode1__c=KC5813, CarRadioCode__c=R822, BCVEnergy__c=EN1, BCVIndexPollution__c=IP1, VINNumber__c=VN1RFB00555029195, Id=a0N4E0000010TjPUAU}=CST_Carset__c:{Id=a074E000000fveNQAQ}
}
07:55:53.3 (155641250)|USER_DEBUG|[47]|DEBUG|<<<<<<VehSerQuery.size 4

While try to get the value of CST_Carset__c am not able to get the value
apex
for(VEH_Vehicle__c Veh:VehSerQuery.keyset()) {
    system.debug('<<<<<<Inside for loop VehSerQuery'+VehSerQuery.keyset() +':::'+VehSerQuery.values());
    system.debug('## Vehiclle ---- ::'+ Veh);
    system.debug('## VEH::'+ VehSerQuery.get(Veh));
}

Inside ## VEH:: is empty !!
I am not able to get the value of specific key !!

A: Create a new subclass - say QueryServiceResult it would look something like this:
public class QueryServiceResult{
    Map<Id, VEH_Vehicle__c> vehiclesByIdMap {get;set;}
    Map<Id, CST_Carset__c> carsetsByVehicleIdMap {get;set;}

    public QueryServiceResult(){
        vehiclesByIdMap = new Map<Id, VEH_Vehicle__c>();
        carsetsByVehicleIdMap = new Map<Id, CST_Carset__c>();
    }
}

Then, in the your final loop in the getQuerySevice method, change it to:
QueryServiceResult qsr = new QueryServiceResult();

for (String  strVin : mapResponse.keyset() ) {
    VEH_Vehicle__c oVeh = mapResponse.get(strVin) ;
    CST_Carset__c lServices = mCarset.get(oVeh.UnitOrder__r.CarSet__r.id);

    qsr.vehiclesByIdMap.put(oVeh.Id,oVeh);
    qsr.carsetsByVehicleIdMap.put(oVeh.Id,lServices);
}

return qsr;

(Your will need to change the return type of your method to QueryServiceResult)
Finally, in the outer loop, extract the values like this:
for(Id vehicleId : qsr.vehiclesByIdMap.keyset()) {
    VEH_Vehicle__c vehicle = qsr.vehiclesByIdMap.get(vehicleId);
    CST_Carset__c carSet = qsr.carsetsByVehicleIdMap.get(vehicleId);
}

A word of advice. Name your variables very carefully. Minimize abbreviations. It will make your code easier to read.


text:
Q: How do I make custom URLs using django? Right now my urls.py file looks like so:
re_path(r'^product-offers/(?P<product_item_id>[-\w]+)$', views.ProductOffersListView.as_view(),

This takes a user to the page: www.shop.com/product/1234
However, is there any way to display the URL with the title (even if that URL doesn't change the dispatching). I want the URL to look like this:
www.shop.com/product/1234/toy-truck
The "toy-truck" part doesn't have to do anything, but it looks professional and would be nice to have.

A: You can add a slug to your model

Slug is a newspaper term. A slug is a short label for something, containing only letters, numbers, underscores or hyphens. They're generally used in URLs

https://docs.djangoproject.com/en/2.1/ref/models/fields/#slugfield
Then add it to the url and pass it together with the item id when you call the url
re_path(r'^product-offers/(?P<product_item_id>[0-9]+/(?P<product_item_slug>[\w-]+)/$


text:
Q: customize a field in automapper public string AdjustTimezoneForDisplay(DateTime date)
{
    //.......
}

automapper config
Mapper.Initialize(config =>
{
     config.CreateMap<EquipmentOther, KMEquipmentOthers>()
               .ForMember(x=>x.Status,opt=>opt.Ignore())
               .ForMember(x => x.CreatedOn, opt => opt.MapFrom(src =>src.CreatedOn));
}

what am trying to achieve is to adjust time zone for CreatedOn field like the below code
ObjKMEquipmentOthers.CreatedOn = this._Utility.AdjustTimezoneForDisplay(EquipmentOtherDetails.CreatedOn);

would anybody please help me to achieve this
ps:AdjustTimezoneForDisplay is function to adjust time zone and return with local time

A: this worked for me ,hope this will help anybody in future
.ForMember(x => x.CreatedOn, opt => opt.MapFrom(x => AdjustTimezoneForDisplay(x.CreatedOn)));

and ps : AdjustTimezoneForDisplay must be static one .(initialy it was non static this is my problem ),again mapping initilizer  also be static
public static string AdjustTimezoneForDisplay(DateTime date)
{
 //.......
}
public static void RegisterMaps()
{
  Mapper.Initialize(config =>
  {
   config.CreateMap<EquipmentOther, KMEquipmentOthers>()
           .ForMember(x=>x.Status,opt=>opt.Ignore())
           .ForMember(x => x.CreatedOn, opt => opt.MapFrom(x => AdjustTimezoneForDisplay(x.CreatedOn)));
  }
}


text:
Q: How to retrieve a column from a nested sub-query in left join? I have a store procedure in which I have to retrieve a column from the nested sub-query. I know how to get it if it is only nested once but for my this situation, the column I need to display is double nested.
SELECT a.vendor,
a.last,
MaxInv
FROM
    (
    SELECT vendor, day
    FROM tblvendor) a

    LEFT JOIN (SELECT vendor, tblarinv.arinv, tblardetail.arddate
    Sum([MaxQty]*[ActualCost]) AS MaxInv,
    FROM tblarinv
    INNER JOIN tblardetail
    ON tblarinv.id= tblardetail.id)
group by a.vendor,a.last

In above example, I have to retrieve two columns from the left join LEFT JOIN (SELECT vendor,tblarinv.arinv, tblardetail.arddate. Originally, there is only vendor in the select statement but since I need tblarinv.arinv, tblardetail.arddate, I added them in that select statement inside left join. And then, when I try to add this field in first SELECT statement it doesn't recognize giving error 'Multi-part identifier could not be bound'.
Can anyone help me out here?
Here is my edited query:
SELECT
a.Vendor,
,CASE WHEN sum(GP)<>0 THEN GP ELSE 0 END GP
,a.ThreeMonths
,CASE WHEN sum(GP)<>0 THEN GP/@WorkDaysElapsed ELSE 0 END AS AvgDailyGP
,CurrentInv
,MaxInv
,Inventory_Variance

FROM
(Select Vendor, sum(GrossProfit) ThreeMonths,
    (Select sum(GrossProfit) From dbo.MonthlySales with (nolock) Where EndOfMonth Between dateadd(m,-3,@First) and @First-1) as AllThreeMonths
    FROM MonthlySales with (nolock)
    Where EndOfMonth>=dateadd(m,-3,@First)
    Group By Vendor
    Having sum(GrossProfit)<>0) a

LEFT JOIN (Select tblMaterial.Vendor, tblARDetail.ARInvoiceID, tblARDetail.ARInvoiceDetailID, tblARInv.ARInvoiceDate
,(Sum(SplitAmount))-(Sum((CASE WHEN SplitAmount<0 THEN -1*ABS([Quantity]) ELSE ABS([Quantity]) END)*dbo.fn_CalculatePrice_Decimal(tblARDetail.UnitCost,tblARDetail.ProductDiscountPct))) AS GP

            FROM tblARInv with (nolock)
            INNER JOIN tblARDetail with (nolock) ON tblARDetail.ARInvoiceID = tblARInv.ARInvoiceID
            INNER JOIN tblMaterial with (nolock) ON tblMaterial.MaterialID = tblARDetail.MaterialID
            INNER JOIN [dbo].[tblCust]
                ON [tblCust].[CustomerID] = [tblARInv].[CustomerID]
            Where tblARInv.Date>= '' + cast(Month(GetDate()) as varchar(2)) + '/1/' + cast(year(GetDate()) as varchar(4)) + ''
                AND [tblCust].[Status] != 8 --Internal
            Group By tblMaterial.Vendor, tblARDetail.ARInvoiceID, tblARDetail.ARInvoiceDetailID, tblARInv.ARInvoiceDate)
            ThisMonth ON ThisMonth.Vendor=a.Vendor

Group By
a.Vendor
,GP
,a.ThreeMonths
,AllThreeMonths
,CurrentInv
,MaxInv
,Inventory_Variance
END

So, I need to retrieve tblARDetail.ARInvoiceID, tblARDetail.ARInvoiceDetailID, tblARInv.ARInvoiceDate which I added in above edited query.

A: There are alot of problems with your example query, but the first part is if*you do not need to "nest" joins, don't do it. (This is a bad habit some people pick up from Microsoft Access, where you have to use that sort of mess).
Your pseudo-query could be simplified down to something like this:
select
    v.vendor
  , v.last
  , sum(d.[MaxQty]*d.[ActualCost]) as MaxInv
from tblvendor v
  left join tblarinv i
    on v.vendor = i.vendor
  left join tblardetail d
    on i.id= d.id
group by v.vendor, v.last

From your edited question, it does not look like those columns are nested, they are available in ThisMonth which is joined to a.
select
    a.Vendor
  , case when sum(GP) <> 0 then GP else 0 end GP
  , a.ThreeMonths
  , case when sum(GP) <> 0 then GP / @WorkDaysElapsed else 0 end as AvgDailyGP
  , CurrentInv
  , MaxInv
  , Inventory_Variance
  /* Include the desired columns in the select */
  , ThisMonth.ARInvoiceID
  , ThisMonth.ARInvoiceDetailID
  , ThisMonth.ARInvoiceDate
from (
  select
      Vendor
    , sum(GrossProfit) ThreeMonths
    , (
      select sum(GrossProfit)
      from dbo.MonthlySales with (nolock)
      where EndOfMonth between dateadd(month, - 3, @First) and @First - 1
      ) as AllThreeMonths
  from MonthlySales with (nolock)
  where EndOfMonth >= dateadd(month, - 3, @First)
  group by Vendor
  having sum(GrossProfit) <> 0
  ) a
left join (
  select
       tblMaterial.Vendor
     , tblARDetail.ARInvoiceID
     , tblARDetail.ARInvoiceDetailID
     , tblARInv.ARInvoiceDate
     , (Sum(SplitAmount))
       - (Sum((case when SplitAmount < 0 then - 1 * ABS([Quantity]) else ABS([Quantity]) end) * dbo.fn_CalculatePrice_Decimal(tblARDetail.UnitCost, tblARDetail.ProductDiscountPct)))
         as GP
  from tblARInv with (nolock)
    inner join tblARDetail with (nolock)
     on tblARDetail.ARInvoiceID = tblARInv.ARInvoiceID
    inner join tblMaterial with (nolock)
     on tblMaterial.MaterialID = tblARDetail.MaterialID
    inner join [dbo].[tblCust]
       on [tblCust].[CustomerID] = [tblARInv].[CustomerID]
  where [tblCust].[Status] != 8 --Internal
   -- and tblARInv.date >= '' + cast(Month(GetDate()) as varchar(2)) + '/1/' + cast(year(GetDate()) as varchar(4)) + ''
   /* easier way to get start of the month */
   and tblARInv.date >= dateadd(month, datediff(month, 0, getdate() )  , 0)
  group by tblMaterial.Vendor
   , tblARDetail.ARInvoiceID
   , tblARDetail.ARInvoiceDetailID
   , tblARInv.ARInvoiceDate
  ) ThisMonth on ThisMonth.Vendor = a.Vendor
left join (
 select Vendor
  , Sum(case when [InStock] > [MaxQty] then [MaxQty] * [ActualCost] else [Instock] * [ActualCost] end) as CurrentInv
  , Sum([MaxQty] * [ActualCost]) as MaxInv
  , ((Sum(case when [InStock] > [MaxQty] then [MaxQty] * [ActualCost] else [Instock] * [ActualCost] end) / Sum(case when [MaxQty] * [ActualCost] <> 0 then [MaxQty] * [ActualCost] else 1 end)) - 0.75) / 0.75 as Inventory_Variance
 from tblMaterial with (nolock)
 where (((MaxQty) > 0))
 group by Vendor
 ) as Inventory on Inventory.Vendor = a.Vendor
group by
    a.Vendor
  , GP
  , a.ThreeMonths
  , AllThreeMonths
  , CurrentInv
  , MaxInv
  , Inventory_Variance
  /* Include the desired columns in the group by too */
  , ThisMonth.ARInvoiceID
  , ThisMonth.ARInvoiceDetailID
  , ThisMonth.ARInvoiceDate
end

Reference:

*

*Bad habits to kick : mis-handling date / range queries - Aaron Bertrand

*Bad Habits to Kick : Using shorthand with date/time operations - Aaron Bertrand

*#BackToBasics : Dating Responsibly - Aaron Bertrand

*What do between and the devil have in common? - Aaron Bertrand


text:
Q: How do I print the first few lines of a makefile (-Wall -g flags)? How do I get the first n lines of the output of a makefile (specifically, my complier is g++). Either a script in linux or in the makefile would work (if you could provide both, that'll be even better).
I have tried

make | head -n 5

but it's not working.
Currently, the process I go through is tedious; I'm piping the output to a text file before using head on it (then having to delete the file).

A: Given that the messages from the compiler appear on standard error rather than standard output, you need to redirect both:
make 2>&1 | head -n 20

(I think 5 lines will be too small to be useful.)


text:
Q: cannot access to hessian remote service at [http://0.0.0.0:8080/SpringDemo-Server/remoting/NotifierService] Can someone help me with my problem?
I have following error:
Tests in error:
   testCreateNewCustomer(eu.ibacz.swsc.spring.di.testdependencyinjection.BankServiceTest): Cannot connect to Hessian remote service at [http://0.0.0.0:8080/SpringDemo-Server/remoting/NotifierService]; nested exception is com.caucho.hessian.client.HessianConnectionException: HessianProxy cannot connect to 'http://0.0.0.0:8080/SpringDemo-Server/remoting/NotifierService

   testGetAllCustomers(eu.ibacz.swsc.spring.di.testdependencyinjection.BankServiceTest): Cannot connect to Hessian remote service at [http://0.0.0.0:8080/SpringDemo-Server/remoting/NotifierService]; nested exception is com.caucho.hessian.client.HessianConnectionException: HessianProxy cannot connect to 'http://0.0.0.0:8080/SpringDemo-Server/remoting/NotifierService

I dont know where can be problem.
This is my applicationContext.xml
   <?xml version="1.0" encoding="UTF-8"?>
   <beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:aop="http://www.springframework.org/schema/aop"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-
   aop-3.0.xsd">``

  <import resource="spring-db-config.xml"/>
  <aop:aspectj-autoproxy/>
  <bean
   class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/>

  <bean id="jdbcTemplateDatasource" class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource" ref="dataSource"/>
  </bean>

  <bean id="springJdbcCustomerDao"
   class="eu.ibacz.swsc.spring.di.testdependencyinjection.dao.impl.JdbcTemplateCustomerDaoImpl">
    <property name="jdbcTemplate" ref="jdbcTemplateDatasource"/>
  </bean>

  <bean id="bankService"
   class="eu.ibacz.swsc.spring.di.testdependencyinjection.service.impl.BankServiceImpl">
    <property name="customerDao" ref="springJdbcCustomerDao"/>
  </bean>

  <bean id="notifier" class="eu.ibacz.swsc.spring.commons.springdemocommons.SysOutNotifier" />

  <bean
   class="eu.ibacz.swsc.spring.di.testdependencyinjection.aspect.BankServiceLoggingAspect">
    <property name="notifier" ref="remoteNotifier"/>
  </bean>

  <bean id="remoteNotifier" class="org.springframework.remoting.caucho.HessianProxyFactoryBean">
    <property name="serviceUrl" value="${url.adress}" />
    <property name="serviceInterface"
     value="eu.ibacz.swsc.spring.commons.springdemocommons.Notifier"/>
  </bean>

  <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location">
        <value>urlconfig.properties</value>
    </property>
  </bean>

urlconfing.properties looks this way:
   url.adress=http://0.0.0.0:8080/SpringDemo-Server/remoting/NotifierService

I have already started Jetty Server using command prompt.
thx for help


text:
Q: Querydsl - How to get sum of columns These below is my STOCK TABLE info
id, bigint(20)
available_quantity, int(11)
allocation_quantity, int(11)
stop_quantity, int(11)
damage_quantity, int(11)
standby_quantity, int(11)

I'd like to do a query than in sql it's:
SELECT
 available_quantity,
 allocation_quantity,
 stop_quantity,
 damage_quantity,
 standby_quantity,
 available_quantity + allocation_quantity + standby_quantity
FROM STOCK

I tried searching for the solution, but the closest I get was:
     return queryFactory
                .select(new QStockResponseDto(
                        stock.availableQuantity,
                        stock.standbyQuantity,
                        stock.allocationQuantity,
                        stock.availableQuantity + stock.standbyQuantity + stock.allocationQuantity
                )).from(stock)

but this indicates below error
Operator '+' cannot be applied to 'com.querydsl.core.types.dsl.NumberPath<java.lang.Integer>', 'com.querydsl.core.types.dsl.NumberPath<java.lang.Integer>'

i don't know how to get this 'available_quantity + allocation_quantity + standby_quantity' in QueryDSL:

A: The error message gives you a great hint about the issue.  The value stock.availableQuantity, stock.standbyQuantity, and stock.allocationQuantity are all objects of type NumberExpression.  Read the NumberExpression documentation here:
https://querydsl.com/static/querydsl/latest/apidocs/com/querydsl/core/types/dsl/NumberExpression.html
I do not have QueryDSL set up local at this time to validate this, but I think you simply need to replace:
stock.availableQuantity + stock.standbyQuantity + stock.allocationQuantity

with this:
stock.availableQuantity.add(stock.standbyQuantity).add(stock.allocationQuantity)

If you need to provide an alias for that result, append the .as(Path<>) method after the second add() method.  Let us know if this works.


text:
Q: Docker - Send multiple images to registry I have a project that has 2 Dockerfiles; one for the frontend and another for the backend.However in my local machine, I've created a docker-compose.yml file that will build the respective Dockerfiles inside respective folders and run them in the prescribed order
Current structure
.
+-- api
|   +-- Dockerfile
|   +-- ...
+-- frontend
|   +-- Dockerfile
|   +-- ...
+-- docker-compose.yml

So, locally the stack is started through docker-compose up.
I'm now planning to get the entire stack into a private registry.
What would be the best way to get the images up, making it easy for dev and CI/CD routines?

*

*Can each Dockerfile images pushed individually and pulled into a new server? or

*Is there a way the different images can be combined to one and used?

or let me know the most efficient method to deploy this.

A: To push multiple images that are build by your compose you can use docker-compose push command. Remember that image names in your compose should be in appropriate format. Your docker compose could look like :
version: '3'
services:
  sv1:
    build: .
    image: localhost:4000/imgename:tag  # for local registry

  sv2:
    build: .
    image: hubusername/imagename:tag  # for DockerHub registry

With this command you can push all images at once, but you can also specify service name, whose image you want to push. You can then download those images from your repository separately.


text:
Q: Why does this programmer in particular passes pointers in functions by reference? I saw this particular code:
void GetMe(User& user) {
     std::cout << user.getName() << std::endl;
}

main(...) {
     User* user = new User("Joe");
     GetMe(*user);
     getchar();
     return EXIT_SUCCESS;
}

I cannot find an example for this in particular on any question here on Stack overflow only some with (&*) instead of (&) and I don't understand what is the point behind it, is it for safety in case the pointer is deleted somewhere else ? (It's a multi threaded app)

A: When you pass a user defined type to a function, you can use one of the following approaches:

*

*Pass by value:
void GetMe(User user) { ... }

*Pass by pointer:
void GetMe(User* userPtr) { ... }
void GetMe(User const* userPtr) { ... }

*Pass by reference:
void GetMe(User& user) { ... }
void GetMe(User const& userPtr) { ... }

As a rule of thumb, passing by reference is preferable to passing by value or passing by pointer.
When you pass by reference instead of by value, the cost of copying an object is avoided.
When you pass by pointer, you cannot assume that a nullptr won't be passed. So, you have add checks in GetMe to account for that case. You don't worry about that when you pass by reference.

A: I believe you are asking why the code wasn't written as:
void GetMe(User* user) {
     std::cout << user->getName() << std::endl;
}

main(...) {
     User* user = new User("Joe");
     GetMe(user);
     getchar();
     return EXIT_SUCCESS;
}

But a lot of experienced programmers would instead ask why it wasn't.
void GetMe(User const& user) {
     std::cout << user.getName() << std::endl;
}

main(...) {
     User* user = new User("Joe");
     GetMe(*user);
     getchar();
     return EXIT_SUCCESS;
}

In both examples, I am ignoring the more serious issue of the memory leaking non-smart pointer and just looking at how user is passed to GetMe.
The original vs. the way I think you are asking about is largely a style question.  I don't see a multi-threading or other functional difference (as you asked about) nor a strong argument for either style.
But I do see strong arguments for tagging it const when passed either by pointer or reference.  If getName() is not const (causing it to be harder to make user const) then that likely should also be fixed.

A: As I see it, there are two parts to your question:

*

*Why the interface, void GetMe(User& user) { } instead of void GetMe(User* user) {}?  There can be several reasons:
void GetMe(User& user) { } implies a malleable non-null input and output user.  If you want non-malleable or input-only, use void GetMe(User const& user) { }.  If you want nullable, use pointers, etc...
How you pass parameters in C++ has very specific semantics, so you must be careful how you do it.  They all have different meanings: passing by reference, by pointer, by const reference, by const pointer, etc...

*Why User* user = new User("Joe"); instead of User user("Joe");?  There may be reasons why you want to allocate memory dynamically on the heap rather than locally on the stack.  For example, if you want the lifetime of the object to be longer than the closing brace.  Another reason used to be that if User is a really large object, then you want it on the heap (with modern CPUs, this may be less of an issue).

Note that multi-threading is an entirely different can of worms.  You have to worry about memory visibility, synchronisation, mutexes, race conditions, etc...  ...most of those issues are orthogonal to the two points above.  I recommend that you get a good handle basic C++ semantics before you head down that road, if you don't want to end up wasting a ton of time debugging threading problems.

A: By  default, parameters pass by value to function, i.e.without & , you have a copy of your parameter  in function - just copy of  its value ,not its reference- i.e. you don't have your real parameter in function and if you have to do some operations with address(refrence) of parameters, everything going to wrong.
Consider this example: a function that could not be to allocate memory to its parameter (char) :
void al(char * c) //wrong way: pass by value
{
c =new char[10];
}
main()
{
char * x;
al(x);//don't allocated because pass by value/.
 *x='a';//memory error//
 }

but this function declaration can do this because pass by reference:
 void al(char * & c)


text:
Q: Set _ENV from C++ for string function In my project I'm executing some lua functions contained in an XML file. I read the XML from C++, parse the code strings, execute them and get the result.
All of the related questions I have found either used a dedicated .lua file or did it in Lua directly and I couldn't find a solution that worked for my case.
I can't modify the functions in the file and they all have the following signature:
function() --or function ()
    --do stuff
    return foo
end

from C++ i load them like so:
lua_State *L = luaL_newstate();
luaL_openlibs(L);
std::string code = get_code_from_XML();
std::string wrapped_code = "return " + code;
luaL_loadstring(L, wrapped_code.c_str());
if (lua_pcall(L, 0, 1, 0)){
    return 1;
}

argNum = load_arg_number();

if (lua_pcall(L, argNum, 1, 0)){
    return 1;
}
return 0;

Everything works but running arbitrary Lua code from an XML string doesn't seem very safe so i wanted to set up a whitelist of functions that the code can use.
Following this lua-users discussion i created my list of allowed functions like:
// Of course my list is bigger
std::string whitelist = "sandbox_env = {ipairs = ipairs} _ENV = sandbox_env"

The problem is that I don't understand how to load it to be available in the functions that I'm calling.
I tried doing it like on the lua-users  website:

std::string Lua_sandboxed_script_to_run( Lua_sandboxing_script + Lua_script_to_run )

if (luaL_dostring(sandboxed_L, Lua_sandboxed_script_to_run))
{
   // error checking
}

But this results in the function not being loaded correctly and the Lua error

Trying to execute a string value

I also tried to do:
luaL_loadstring(L, whitelist.c_str());
lua_getglobal(L, "_ENV");
lua_setupvalue(L, -2, 1);

Before executing the loaded XML function, this doesn't crash the program but doesn't set the _ENV for the called function either.
The only way I have found to have what I want is to parse the function string with C++ searching for (), insert whitelist after it and then luaL_loadstring and lua_pcall it twice to execute it.
Like this:
.
.
size_t n = code.find("()") + 2;
code.insert(n, whitelist);
std::string wrapped_code = "return " + code;
.
.

This works and sets my custom _ENV for the function but seems to me like a really hacky way to go about it.
How can I set the _ENV variable for a string function loaded from C in a nicer way?
Bonus points if there is a way to save it once for the whole lua_State instead of every time I call a function.

A: Before we dive into examples let's explain how (and at what level) we can more-or-less sandbox code in Lua:

*

*Globally - remove or never add unwanted modules/functions into the global environment.

*Chunk(ly) - modify the _ENV upvalue of a chunk.

*Locally - modify _ENV through a local or upvalue in Lua script. It can be propagated then to children via upvalue.
Looking at the examples provided in the question you tried to do either 2 or 3.
I'm not sure what are your needs but I will try to provide you examples for each of the approaches listed above. Please note that those examples are not the ultimate ones, are not the only possible approaches and do not take yours return function () ... end wrapper. Pick any that suits you.
Globally
This one is very straight-forward. If you don't plan to use all of the libraries provided...
lua_State * L = luaL_newstate();
luaL_openlibs(L); // <-- Remove this

... then just don't load them:
lua_State * L = luaL_newstate();
// Instead of luaL_openlibs:
luaL_requiref(L, "_G", luaopen_base, 1);
luaL_requiref(L, LUA_MATHLIBNAME, luaopen_math, 1);
luaL_requiref(L, LUA_TABLIBNAME, luaopen_table, 1);
// luaL_requiref pushes to stack - clean it up:
lua_pop(L, 3);
// Load and execute desired scripts here.

Refer to 6 Standard Libraries and linit.c for list of available libraries. See also: luaL_requiref.
In addition to selective library loading you can also remove selected globals by setting them to nil:
lua_pushnil(L);
lua_setglobal(L, "print");

You set this once for the lua_State.
Chunk(ly)
Let's limit ourselves to a very basic operation of changing the first upvalue of loaded main chunk. The first upvalue of such chunk is expected to be _ENV (reference below).
Note that I said main chunk. In general you will rarely load chunks that expect something else than _ENV as their first upvalue but it is always nice to remember about such case.
Anyway, consider following example:
lua_State * L = luaL_newstate();
luaL_openlibs(L);
luaL_loadstring(L, "print2 \"Hello there\"");
// (A) Create a table with desired environment and place it at the top of the stack.
//     Replace this comment with any of the options described below
lua_setupvalue(L, -2, 1);
lua_call(L, 0, 0);

You can achieve (A) in various ways. You could use Lua C API:
lua_newtable(L);
lua_pushliteral(L, "print2");
lua_getglobal(L, "print");
lua_settable(L, -3);

Or you could do it via dostring:
lua_dostring(L, "return { print2 = print }");

Or you could try yet another approach, similar to one from the question:
lua_dostring(L, "sandbox_env = { print2 = print }"); // Without _ENV = sandbox_env
lua_getglobal(L, "sandbox_env");

General reference on environments: 2.2 Environments and the Global Environment.
See lua_setupvalue documentation for usage details.
See another example in load_aux. Note that this is part of the source code for load function available in Lua. This function allows to set environment of loaded chunk through one of its arguments (see load).
Locally
You could either modify upvalue _ENV or override it with a local directly in the Lua script. Let's do the latter:
local _ENV = { print2 = print }
(function ()
   print2("Hello there")
end)()

This means you could wrap loaded script and run it like this:
std::string loaded_script /* = ... */;
std::string wrapped_script = "local _ENV = { print2 = print }; (" + loaded_script + ")()";
luaL_loadstring(L, wrapped_script.c_str());
lua_call(L, 0, 0);

This will work with return function () ... end wrap, too (instead of (...)()). That's because local _ENV will be passed as upvalue to returned anonymous function.
Refer to Environments Tutorial for more verbose explanation on environments manipulation inside Lua.


text:
Q: How do I tell if a file does not exist in Bash? This checks if a file exists:
#!/bin/bash

FILE=$1
if [ -f $FILE ]; then
   echo "File $FILE exists."
else
   echo "File $FILE does not exist."
fi

How do I only check if the file does not exist?

A: Bash File Testing
-b filename - Block special file
-c filename - Special character file
-d directoryname - Check for directory Existence
-e filename - Check for file existence, regardless of type (node, directory, socket, etc.)
-f filename - Check for regular file existence not a directory
-G filename - Check if file exists and is owned by effective group ID
-G filename set-group-id - True if file exists and is set-group-id
-k filename - Sticky bit
-L filename - Symbolic link
-O filename - True if file exists and is owned by the effective user id
-r filename - Check if file is a readable
-S filename - Check if file is socket
-s filename - Check if file is nonzero size
-u filename - Check if file set-user-id bit is set
-w filename - Check if file is writable
-x filename - Check if file is executable
How to use:
#!/bin/bash
file=./file
if [ -e "$file" ]; then
    echo "File exists"
else
    echo "File does not exist"
fi

A test expression can be negated by using the ! operator
#!/bin/bash
file=./file
if [ ! -e "$file" ]; then
    echo "File does not exist"
else
    echo "File exists"
fi

A: I prefer to do the following one-liner, in POSIX shell compatible format:
$ [ -f "/$DIR/$FILE" ] || echo "$FILE NOT FOUND"

$ [ -f "/$DIR/$FILE" ] && echo "$FILE FOUND"

For a couple of commands, like I would do in a script:
$  [ -f "/$DIR/$FILE" ] || { echo "$FILE NOT FOUND" ; exit 1 ;}

Once I started doing this, I rarely use the fully typed syntax anymore!!

A: The simplest way
FILE=$1
[ ! -e "${FILE}" ] && echo "does not exist" || echo "exists"

A: To test file existence, the parameter can be any one of the following:
-e: Returns true if file exists (regular file, directory, or symlink)
-f: Returns true if file exists and is a regular file
-d: Returns true if file exists and is a directory
-h: Returns true if file exists and is a symlink

All the tests below apply to regular files, directories, and symlinks:
-r: Returns true if file exists and is readable
-w: Returns true if file exists and is writable
-x: Returns true if file exists and is executable
-s: Returns true if file exists and has a size > 0

Example script:
#!/bin/bash
FILE=$1

if [ -f "$FILE" ]; then
   echo "File $FILE exists"
else
   echo "File $FILE does not exist"
fi

A: This shell script also works for finding a file in a directory:
echo "enter file"

read -r a

if [ -s /home/trainee02/"$a" ]
then
    echo "yes. file is there."
else
    echo "sorry. file is not there."
fi

A: sometimes it may be handy to use && and || operators.
Like in (if you have command "test"):
test -b $FILE && echo File not there!

or
test -b $FILE || echo File there!

A: The test command (written as [ here) has a "not" logical operator, ! (exclamation mark):
if [ ! -f /tmp/foo.txt ]; then
    echo "File not found!"
fi

A: You can do this:
[[ ! -f "$FILE" ]] && echo "File doesn't exist"

or
if [[ ! -f "$FILE" ]]; then
    echo "File doesn't exist"
fi

If you want to check for file and folder both, then use -e option instead of -f. -e returns true for regular files, directories, socket, character special files, block special files etc.

A: You should be careful about running test for an unquoted variable, because it might produce unexpected results:
$ [ -f ]
$ echo $?
0
$ [ -f "" ]
$ echo $?
1

The recommendation is usually to have the tested variable surrounded by double quotation marks:
#!/bin/sh
FILE=$1

if [ ! -f "$FILE" ]
then
   echo "File $FILE does not exist."
fi

A: You can also group multiple commands in the one liner
[ -f "filename" ] || ( echo test1 && echo test2 && echo test3 )
or
[ -f "filename" ] || { echo test1 && echo test2 && echo test3 ;}
If filename doesn't exit, the output will be
test1
test2
test3

Note: ( ... ) runs in a subshell, { ... ;} runs in the same shell.

A: If you want to use test instead of [], then you can use ! to get the negation:
if ! test "$FILE"; then
  echo "does not exist"
fi

A: Negate the expression inside test (for which [ is an alias) using !:
#!/bin/bash
FILE=$1

if [ ! -f "$FILE" ]
then
    echo "File $FILE does not exist"
fi

The relevant man page is man test or, equivalently, man [ -- or help test or help [ for the built-in bash command.
Alternatively (less commonly used) you can negate the result of test using:
if ! [ -f "$FILE" ]
then
    echo "File $FILE does not exist"
fi

That syntax is described in "man 1 bash" in sections "Pipelines" and "Compound Commands".

A: In
[ -f "$file" ]

the [ command does a stat() (not lstat()) system call on the path stored in $file and returns true if that system call succeeds and the type of the file as returned by stat() is "regular".
So if [ -f "$file" ] returns true, you can tell the file does exist and is a regular file or a symlink eventually resolving to a regular file (or at least it was at the time of the stat()).
However if it returns false (or if [ ! -f "$file" ] or ! [ -f "$file" ] return true), there are many different possibilities:

*

*the file doesn't exist

*the file exists but is not a regular file (could be a device, fifo, directory, socket...)

*the file exists but you don't have search permission to the parent directory

*the file exists but that path to access it is too long

*the file is a symlink to a regular file, but you don't have search permission to some of the directories involved in the resolution of the symlink.

*... any other reason why the stat() system call may fail.

In short, it should be:
if [ -f "$file" ]; then
  printf '"%s" is a path to a regular file or symlink to regular file\n' "$file"
elif [ -e "$file" ]; then
  printf '"%s" exists but is not a regular file\n' "$file"
elif [ -L "$file" ]; then
  printf '"%s" exists, is a symlink but I cannot tell if it eventually resolves to an actual file, regular or not\n' "$file"
else
  printf 'I cannot tell if "%s" exists, let alone whether it is a regular file or not\n' "$file"
fi

To know for sure that the file doesn't exist, we'd need the stat() system call to return with an error code of ENOENT (ENOTDIR tells us one of the path components is not a directory is another case where we can tell the file doesn't exist by that path). Unfortunately the [ command doesn't let us know that. It will return false whether  the error code is ENOENT, EACCESS (permission denied), ENAMETOOLONG or anything else.
The [ -e "$file" ] test can also be done with ls -Ld -- "$file" > /dev/null. In that case, ls will tell you why the stat() failed, though the information can't easily be used programmatically:
$ file=/var/spool/cron/crontabs/root
$ if [ ! -e "$file" ]; then echo does not exist; fi
does not exist
$ if ! ls -Ld -- "$file" > /dev/null; then echo stat failed; fi
ls: cannot access '/var/spool/cron/crontabs/root': Permission denied
stat failed

At least ls tells me it's not because the file doesn't exist that it fails. It's because it can't tell whether the file exists or not. The [ command just ignored the problem.
With the zsh shell, you can query the error code with the $ERRNO special variable after the failing [ command, and decode that number using the $errnos special array in the zsh/system module:
zmodload zsh/system
ERRNO=0
if [ ! -f "$file" ]; then
  err=$ERRNO
  case $errnos[err] in
    ("") echo exists, not a regular file;;
    (ENOENT|ENOTDIR)
       if [ -L "$file" ]; then
         echo broken link
       else
         echo does not exist
       fi;;
    (*) syserror -p "can't tell: " "$err"
  esac
fi

(beware the $errnos support was broken with some versions of zsh when built with recent versions of gcc).

A: There are three distinct ways to do this:

*

*Negate the exit status with bash (no other answer has said this):
if ! [ -e "$file" ]; then
    echo "file does not exist"
fi

Or:
! [ -e "$file" ] && echo "file does not exist"

*Negate the test inside the test command [ (that is the way most answers before have presented):
if [ ! -e "$file" ]; then
    echo "file does not exist"
fi

Or:
[ ! -e "$file" ] && echo "file does not exist"

*Act on the result of the test being negative (|| instead of &&):
Only:
[ -e "$file" ] || echo "file does not exist"

This looks silly (IMO), don't use it unless your code has to be portable to the Bourne shell (like the /bin/sh of Solaris 10 or earlier) that lacked the pipeline negation operator (!):
if [ -e "$file" ]; then
    :
else
    echo "file does not exist"
fi

A: envfile=.env

if [ ! -f "$envfile" ]
then
    echo "$envfile does not exist"
    exit 1
fi

A: [[ -f $FILE ]] || printf '%s does not exist!\n' "$FILE"

Also, it's possible that the file is a broken symbolic link, or a non-regular file, like e.g. a socket, device or fifo. For example, to add a check for broken symlinks:
if [[ ! -f $FILE ]]; then
    if [[ -L $FILE ]]; then
        printf '%s is a broken symlink!\n' "$FILE"
    else
        printf '%s does not exist!\n' "$FILE"
    fi
fi

A: To reverse a test, use "!".
That is equivalent to the "not" logical operator in other languages. Try this:
if [ ! -f /tmp/foo.txt ];
then
    echo "File not found!"
fi

Or written in a slightly different way:
if [ ! -f /tmp/foo.txt ]
    then echo "File not found!"
fi

Or you could use:
if ! [ -f /tmp/foo.txt ]
    then echo "File not found!"
fi

Or, presing all together:
if ! [ -f /tmp/foo.txt ]; then echo "File not found!"; fi

Which may be written (using then "and" operator: &&) as:
[ ! -f /tmp/foo.txt ] && echo "File not found!"

Which looks shorter like this:
[ -f /tmp/foo.txt ] || echo "File not found!"

A: It's worth mentioning that if you need to execute a single command you can abbreviate
if [ ! -f "$file" ]; then
    echo "$file"
fi

to
test -f "$file" || echo "$file"

or
[ -f "$file" ] || echo "$file"

A: The test thing may count too. It worked for me (based on Bash Shell: Check File Exists or Not):
test -e FILENAME && echo "File exists" || echo "File doesn't exist"

A: This code also working .
#!/bin/bash
FILE=$1
if [ -f $FILE ]; then
 echo "File '$FILE' Exists"
else
 echo "The File '$FILE' Does Not Exist"
fi


text:
Q: Autoplay tag not working on chrome and firefox So I have a music which only plays automatically on edge chromium. On firefox and chrome, it doesn't work. Any solution? THANKS
<audio id="music" autoplay loop style="display:none">
<source src="Music1.mp3" type="audio/mp3">
<source src="Msic1.ogg" type="audio/ogg">
</audio>

A: visit this
i think you should use iframe and audio tag as well for non-chrome browsers.

A: Try this, it worked for me. Just need to add the preload attribute.
Keep in mind the user must interact with the domain, so click something in any page of the site, once he interacts everything should work fine.

<audio id="music" autoplay loop preload>
<source src="Music1.mp3" type="audio/mp3">
<source src="Msic1.ogg" type="audio/ogg">
</audio>


text:
Q: Center slice a responsive svg image on resize I have been trying to center slice the responsive Svg image on resize.
I have used preserveAspectRatio="xMidYMax slice" to achieve the output but the image width doesn't retain the width my screen.

body{
  margin:0;padding:0;
}

.wrapper {
 position: relative;
 width: 100%;
 min-width: 100%;
 vertical-align: middle;
 margin: 0;
}

.bg-svg {
 display: inline-block;
 position: absolute;
 top: 0; left: 0;
 width: 100%;
}

   <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"  d="0px" y="0px"
     width="1920px" height="1080px" viewBox="0 0 1920 1080" preserveAspectRatio="xMidYMax slice" class="bg-svg">
  <rect fill="#DACFB9" width="1920" height="1080"/>
  <rect x="719" y="296" fill="#EF6544" stroke="#FFFFFF" stroke-miterlimit="10" width="482" height="482"/>
  <rect x="1438" y="296" fill="#AFFF84" stroke="#D3D2D2" stroke-miterlimit="10" width="482" height="482"/>
  <rect x="1" y="296" fill="#7AEEFF" stroke="#D3D2D2" stroke-miterlimit="10" width="482" height="482"/>
  <text transform="matrix(1 0 0 1 841 557)" font-family="'GothamBlack'" font-size="60">MIDDLE</text>
  </svg>

I am trying to achieve output like this Codepen demo  but i dont want to use a background image.

A: Your main problem was that your SVG needed to have:
width="100%" height="100%"

so that it fills the wrapper.  There was some other unnecessary CSS as well.

body{
  margin:0;
  padding:0;
}

.wrapper {
  width: 100%;
  height: 100vh;
}

   <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100%" height="100%"
     viewBox="0 0 1920 1080" preserveAspectRatio="xMidYMid slice" class="bg-svg">
  <rect fill="#DACFB9" width="1920" height="1080"/>
  <rect x="719" y="296" fill="#EF6544" stroke="#FFFFFF" stroke-miterlimit="10" width="482" height="482"/>
  <rect x="1438" y="296" fill="#AFFF84" stroke="#D3D2D2" stroke-miterlimit="10" width="482" height="482"/>
  <rect x="1" y="296" fill="#7AEEFF" stroke="#D3D2D2" stroke-miterlimit="10" width="482" height="482"/>
  <text transform="matrix(1 0 0 1 841 557)" font-family="'GothamBlack'" font-size="60">MIDDLE</text>
  </svg>

A: The result you are trying to achieve and have linked to uses background-image. In order to make this work correctly, use this simplified svg. Make sure you have the viewBox, xmls and at least a width or height property (set as an integer without unit only). Then the svg will handle just like any other background-image. I cannot show this here as I cannot link from SO, but heres the amended SVG:
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="1920" height="1080" viewBox="0 0 1920 1080">
    <rect fill="#DACFB9" width="1920" height="1080"/>
    <rect x="719" y="296" fill="#EF6544" stroke="#FFFFFF" stroke-miterlimit="10" width="482" height="482"/>
    <rect x="1438" y="296" fill="#AFFF84" stroke="#D3D2D2" stroke-miterlimit="10" width="482" height="482"/>
    <rect x="1" y="296" fill="#7AEEFF" stroke="#D3D2D2" stroke-miterlimit="10" width="482" height="482"/>
    <text transform="matrix(1 0 0 1 841 557)" font-family="'GothamBlack'" font-size="60">MIDDLE</text>
</svg>

We could simulate this background as such:

svg {
  min-width: 100%;
  min-height: 100%;
  position: absolute;
  left: 50%;
  top: 50%;
  -webkit-transform: translate(-50%,-50%);
  transform: translate(-50%,-50%);
}
 <svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="1920" height="1080" viewBox="0 0 1920 1080">
    <rect fill="#DACFB9" width="1920" height="1080"/>
    <rect x="719" y="296" fill="#EF6544" stroke="#FFFFFF" stroke-miterlimit="10" width="482" height="482"/>
    <rect x="1438" y="296" fill="#AFFF84" stroke="#D3D2D2" stroke-miterlimit="10" width="482" height="482"/>
    <rect x="1" y="296" fill="#7AEEFF" stroke="#D3D2D2" stroke-miterlimit="10" width="482" height="482"/>
    <text transform="matrix(1 0 0 1 841 557)" font-family="'GothamBlack'" font-size="60">MIDDLE</text>
</svg>

If you save this out as an SVG file, you can simply use background-image:
background-image: url(path/to/vector.svg) repeat 50% 50%;


text:
Q: in_category() works in single.php but not in page.php? I'm using in_category(array) inside The Loop to detect whether a post is categorised into the Discussion category (or has one of a couple of slugs). This works beautifully on single.php but doesn't even seem to be evaluated when used inside page.php?
FWIW, here's my code:
<?php if ( in_category( array( 'Discussions', 'discussion', 'discussion-article' ) )) :?>

This is an article from our Discussions series - read more in the Discussions section.

<?php endif;?>

On the borked page.php instance, I've also tried
<?php elseif:?>

This post does not meet the category criteria.

<?php endif;?>

but that doesn't show either leading me to believe the code's not being evaluated. This code snippet was, in both instances, inserted directly before <?php the_content(''); ?> (the_content() in single.php); it just doesn't eval or show up in page.php. Intentional behaviour or am I doing it wrong?

A: Unless you have added the functionality with a plugin or custom code, Pages are not placed in Categories. Pages are organized with Parent Pages and Children Pages. This is why (I suspect) in_category() does not work in page.php
The following code in functions.php will add categories to Pages.
/**
*   Add categories to Pages.
*   from http://shibashake.com/wordpress-theme/add-tags-and-categories-to-your-wordpress-page
*/

    function add_custom_tags_box() {
        add_meta_box(   'categorydiv', __('Categories'), 'post_categories_meta_box',
                'page', 'side', 'low');
       register_taxonomy_for_object_type('category', 'page');
    }

Hope this helps.


text:
Q: how to get a array class using classloader in java? I define a classloader name MyClassLoader as such.
cl = new MyClassLoader();

I could use cl to load my class A.
Class c = cl.loadClass();

but how to load a class which is A[].class?

A: I think you want to use java.lang.reflect.Array.newInstance() like this -
A[] arr = java.lang.reflect.Array.newInstance(A.class, 10); /* for example */

A: Assuming your ClassLoader implementation, MyClassLoader is properly implemented, you'd simply pass the canonical name of the array class to the loadClass method. For example, if you were trying to load the Class for the class com.something.Foo, you'd use
cl.loadClass("[Lcom.something.Foo");

You have to know that the class name for Array types is the character [ appended X number of times, where X is the number of array dimensions, then the character L. You then append the qualified class name of the type of the array. And finally, you append the character ;.
Therefore
Class<?> clazz = Class.forName("[Lcom.something.Examples;");

would get you the Class instance returned by A[].class if it was loaded by the same ClassLoader.
Note that you won't be able to instantiate this type this way. You'll have to use Array.newInstance() passing in the Class object for A, for a one dimensional array, the Class object for A[] for a two dimensional array and so on.

A: In Java 12, you can call someClass.arrayType() to get the "array of someClass" class. If you need a two dimensional array, that will be someClass.arrayType().arrayType(). Of course, you can load someClass itself like Class<?> someClass = someClassLoader.loadClass("com.example.A").
I couldn't find a solution in the standard API of earlier Java versions, so I have written this utility method:
/**
 * Returns the array type that corresponds to the element type and the given number of array dimensions.
 * If the dimension is 0, it just returns the element type as is.
 */
public static Class<?> getArrayClass(Class<?> elementType, int dimensions) {
    return dimensions == 0 ? elementType : Array.newInstance(elementType, new int[dimensions]).getClass();
}

And then you can do this:
Class<?> arrayClass = getArrayClass(someClass, 1);

Kind of an ugly workaround, but... unlike with Class.forName, you control what  ClassLoader is used, and you don't have to write another utility to generate funny names like "[[I" or "[Lcom.example.A;".


text:
Q: SPARK SQL not in or NOT EXISTS I have a scenario where there are two sheets(csv). Created two tables for it.
When there s a good data I could map it with a value( id statistic value) from the second table. If I have bad data I should map it with id statistic value again (but a different value). however, I'm unable to use not exists in spark SQL. And I get the error below:
mismatched input 'from' expecting {, 'WHERE', 'GROUP', 'ORDER', 'HAVING', 'LIMIT', 'LATERAL', 'WINDOW', 'UNION', 'EXCEPT', 'INTERSECT', 'SORT', 'CLUSTER', 'DISTRIBUTE'}(line 1, pos 386)
at org.apache.spark.sql.catalyst.parser.ParseException.withCommand(ParseDriver.scala:197)
at org.apache.spark.sql.catalyst.parser.AbstractSqlParser.parse(ParseDriver.scala:99)
at org.apache.spark.sql.execution.SparkSqlParser.parse(SparkSqlParser.scala:45)

CODE:
select
  a.ptf_id,a.ptf_code,a.share_id,a.share_code,a.bench_id,a.bench_code
  , a.l1_calculation_date,a.l1_begin_date,a.l1_end_date,a.l1_running_date
  , a.l1_frequency,a.l1_calculation_step,a.l1_performance_currency
  , a.l1_configuration,a.l1_valuation_source,a.l1_nav_valuation_type
  , a.l1_setting_reference_type, a.l1_setting_valuation_type
  , a.l1_sharpe_ratio_annualized as value,b.id_statistic
from
  parquetFile a,
  pairRDD b,
  stats c
where
  a.l1_nav_valuation_type= b.l1_nav_valuation_type
  and a.l1_valuation_source = b.l1_valuation_source
  and b.l1_Perf = 'l1_sharpe_ratio_annualized'
  OR (a.ptf_id not EXISTS (
       select e.ptf_id from pairRDD d, parquetFile e
       where d.l1_valuation_source = e.l1_valuation_source
       AND d.l1_nav_valuation_type = e.l1_nav_valuation_type)
  and b.l1_valuation_source ='')

this query works in SQL if I use "NOT in"
please help me on what other options to use in this scenario other than not exists.

A: The query is a bit hard to follow as written.  It's not clear (to me anyway) what your intentions are for the stats table since you don't select anything from it so I removed it.  Obviously I haven't tried this myself but at a glance, you might try something like this instead:
select
    a.PTF_ID,
    a.PTF_CODE,
    a.SHARE_ID,
    a.SHARE_CODE,
    a.BENCH_ID,
    a.BENCH_CODE,
    a.L1_CALCULATION_DATE,
    a.L1_BEGIN_DATE,
    a.L1_END_DATE,
    a.L1_RUNNING_DATE,
    a.L1_FREQUENCY,
    a.L1_CALCULATION_STEP,
    a.L1_PERFORMANCE_CURRENCY,
    a.L1_CONFIGURATION,
    a.L1_VALUATION_SOURCE,
    a.L1_NAV_VALUATION_TYPE,
    a.L1_SETTING_REFERENCE_TYPE,
    a.L1_SETTING_VALUATION_TYPE,
    a.L1_SHARPE_RATIO_ANNUALIZED as VALUE,
    b.ID_STATISTIC
from
    PARQUETFILE a
inner join
    PAIRRDD b
on
    a.L1_NAV_VALUATION_TYPE = b.L1_NAV_VALUATION_TYPE and
    a.L1_VALUATION_SOURCE = b.L1_VALUATION_SOURCE
left outer join (
    select
        e.PTF_ID
    from
        PAIRRDD d
    inner join
        PARQUETFILE e
    on
        d.L1_VALUATION_SOURCE = e.L1_VALUATION_SOURCE AND
        d.L1_NAV_VALUATION_TYPE = e.L1_NAV_VALUATION_TYPE
    where
        b.L1_VALUATION_SOURCE = ''
    ) x
on
    a.PTF_ID = x.PTF_ID
where
    b.L1_PERF = 'l1_sharpe_ratio_annualized' or
    x.PTF_ID is null


text:
Q: OSGI-Karaf-REST API I am following the camunda guide on github and successfully able to start my Process_1 by using @PostDeploy method in my ExampleProcessApplication class.
Now I want to use a REST API in the karaf environment so that I can start a process when I get some external triggering.
I installed camunda-bpm-karaf-feature-minimal by following the github helper.
I am not able to call feature:install camunda-bpm-karaf-feature-full (I am using Apache karaf 3.0.7) error msg is as follows:
Missing requirements osgi.wiring.package=javax.transaction

I couldn't find how to install version 1.3.
Do I need to install any other bundle to use a REST API in karaf environment?

A: I have noticed that they changed their javax.transaction api from com.springsource.javax.transaction to javax.transaction-api when they changed from 1.3 to 2.0. I recommend you to use their 2.0 version feature.


text:
Q: Why jest mock not working if it isn't declared in 'it' scope I created a simple typescript project with create-react-app..
And I try to create unit test with a jest's mock.
the class, I want to mock :
export class RestUserAPI {
  public constructor() {}
    getName(): string {
      return "MyUser";
    }
  }
}

the class I want to test
import {RestUserAPI} from "./RestUserAPI";

export class UserService {
  private userAPI: RestUserAPI;
  public constructor() {
    this.userAPI = new RestUserAPI();
  }

  getName(): string {
    return this.userAPI.getName();
  }
}

And my test which is not working
import { UserService } from './UserService';
import {RestUserAPI} from "./RestUserAPI";

const mockedUserName = 'mocked user name'

jest.mock('./RestUserAPI');
const RestUserAPIMock = RestUserAPI as jest.MockedClass<typeof RestUserAPI>;
RestUserAPIMock.mockImplementation(() => {
   return {
     getName: jest.fn().mockReturnValue(mockedUserName),
   };
});

describe("User Service", () => {
  let instance: UserService;
  beforeAll(() => {
    RestUserAPIMock.mockClear()
  });

  it("should get user name", () => {
    instance = new UserService();
    expect(instance.getName()).toBe(mockedUserName);
    expect(RestUserAPIMock).toHaveBeenCalledTimes(1);
  });
});

this code work, butt this is not what I want
import { UserService } from './UserService';
import {RestUserAPI} from "./RestUserAPI";

const mockedUserName = 'mocked user name'

jest.mock('./RestUserAPI');
const RestUserAPIMock = RestUserAPI as jest.MockedClass<typeof RestUserAPI>;

describe("User Service", () => {
  let instance: UserService;
  beforeAll(() => {
    RestUserAPIMock.mockClear()
  });

  it("should get user name", () => {
    RestUserAPIMock.mockImplementation(() => {
      return {
        getName: jest.fn().mockReturnValue(mockedUserName),
      };
    });

    instance = new UserService();
    expect(instance.getName()).toBe(mockedUserName);
    expect(RestUserAPIMock).toHaveBeenCalledTimes(1);
  });
});

What is my mistake?
How can I create a mock implementation for all my 'it' blocks?

A: All of your assignment code should be inside a beforeEach or a beforeAll block, so if you move the mockImplementation code into the beforeAll, or into a separate beforeEach block inside your describe block, it should work.
You actually don't need to clear the mocks in your beforeAll so you could remove that and replace it with the mocking code.


text:
Q: Git asking for password, but not for username I'm working in a team and we use bitbucket for our code. We also have one live server that we use for testing our app. Everyone in team has an SSH access to this server. To publish newest code on server, a member of team should login via SSH and execute git pull command.
However, when I open my bitbucket repo, it shows cloning URL in this format https://MY-USERNAME@bitbucket.org/MY-TEAM-NAME/REPO-NAME
and I used it to clone the repo. Now, when I use git clone, git uses MY-USERNAME and asks for password only. But I want it to ask for username as well, because another member of the team might ssh into this server and do git pull.
Looks like I'm using wrong URL, because it has got my username in it. Where do I get a generic one without username?

A: Simply remove MY-USERNAME@ from the beginning of the URL, then Git will ask for both. HTTP lets you authenticate with user:pass@host.com at the beginning of a URL, and BitBucket tries to be helpful by supplying you with your personal URL to save you typing.
Proof of concept using BitBucket's example app:
$ git clone https://newuserme@bitbucket.org/newuserme/bb101repo.git
Cloning into 'bb101repo'...
Password for 'https://newuserme@bitbucket.org':

$ git clone https://bitbucket.org/newuserme/bb101repo.git
Cloning into 'bb101repo'...
Username for 'https://bitbucket.org': someoneelse
Password for 'https://someoneelse@bitbucket.org':


text:
Q: Can you create a "Comments" section in a SharePoint wiki? I'm trying to create a Comments section in my wiki.  There's one solution on the Web involving the creation of a "column," but that seemed to just create a second text block under the main article block.  This is impractical, because subsequent edits don't create new comments - they seem to just edit the existing comment.  There are a few others asking this question out there.  Has anyone done anything like this before?

A: My first recommendation would be to try and get a different wiki solution.  I tried to get the Sharepoint wiki adopted and it failed in a much bigger way then expected.  Then I convinced my company that it was the wiki that was the problem.  After switching wiki's we experienced a much greater adoption.
That said, the way that I did comments on the Sharepoint wiki was to make a separate page for every page that I wanted comments on.  Then at the top of the page I would have a standard table.
The Page   |  Comments

This table would link you to a talk like page on wikipedia.  This solved the issue to a certain extent for me.
Check out Confluence, it's my favorite wiki software out there right now.

A: Adding the following line to the page layout of the enterprise wiki worked for me
<SharePointPortalControls:SocialCommentWebPart id="noteboard" ChromeType="None" runat="server" />


text:
Q: How to stop Rainlendar from hiding on the Linux Mint desktop? Rainlendar is a great tool to keep events and tasks on the desktop (I did not find a better solution yet).
The problem is that the application completely hides if you press:

*

*The "Show Desktop" button of Mint's panel (taskbar)

*Special-Key + d / CTRL + ALT + d
Possible Rainlendar position settings:

*

*On Top - Does not work

*Normal - Does not work

*On Bottom - Does not work

*On Desktop - With this option, the application won't hide, but would be on top of every window. So this isn't really a solution.

Is it possible to prevent Rainlendar from hiding or is there at least a command to show Rainlendar again (at the moment I have to kill the process and start it again) or any other solution?
I'm using:

*

*Linux Mint 15 "Olivia" with Cinnamon 1.8.8

*Rainlendar 2.11.1

Everything is up-to-date at the moment.

A: According to the Rainlendar FAQ:

Rainlendar gets hidden when I click the "Show Desktop" button.
Written by Kimmo Pekkola
Change the window position to "On Desktop". If that doesn't work, use the "On Top" position or learn to use Win+M to minimize the applications (Shift+Win+M brings them back).

A: After trying a lot of different things, I ended up with this:
Just do right click on the application's tray icon (usually a little calendar) and click "Refresh". This will make the application visible again.
On Linux Mint with the Cinnamon desktop: The tray icon is only visible if the App Indicator Icon option is disabled (which is enabled by default)!
To disable the App Indicator Icon go to: Options->Advanced->"Show app indicator icon"

A: This was the solution that worked for me.

*

*Choose "On Desktop" as Position

*Go to options -> Advanced -> Windows
Change "transparency type" parameters to "copy".

Voila, widget now will always stand on the desktop.
Even if you hide all windows or do cmd/win + d command.


text:
Q: How do you implement a fixed left pane for an Android tablet layout? I'm porting an iPhone+iPad app to Android.  It uses a Split View Controller for tablets which in Android lingo allows you to present two Activities side by side simultaneously (Edit: Android only allows one Activity on screen as mentioned by @commonsware below.  The next best thing is to use fragments, but the Action Bar can only exist at the Activity level, meaning it will have to expand the entire width of the screen.  It wonder if a Split Activity Controller will be coming to the Android Platform.)
The tablet landscape layout has a fixed left pane for statistics that never changes.  The right hand pane functions just like the phone version of the app.  Transitions occur exclusively on the right hand pane.  i.e. the whole screen doesn't slide when changing activities, only the right pane.  How would you recommend implementing this in Android?
Should I use a single activity and manually perform transitions between fragments in the right panel?  This app has 25 screens and will have an alternate layout for phones, so I'm trying to plan ahead and do this right the first time :)  Thanks for your help!

A:
It uses a Split View Controller for tablets which in Android lingo allows you to present two Activities side by side simultaneously.

No. In "Android lingo", you cannot "present two Activities side by side simultaneously". You can present two fragments side by side simultaneously.

How would you recommend implementing this in Android?

Use fragments. Use a FragmentTransaction to replace the right-hand fragment as needed based on user input. Your overall activity layout could have a horizontal LinearLayout (with android:layout_weight to control the sizes for the left and right sides), with a <fragment> element for the left and a FrameLayout for the right.

Should I use a single activity and manually perform transitions between fragments in the right panel?

Yes, to achieve what you ask for.


text:
Q: PowerBuilder MySQL Connection How do I connect my PowerBuilder to MySQL?
First I would like to use Database Painter to conenct to my local MySQL Database so I can create my datawindows.
Then I would like to make a DSNLESS connection so I can just add .ini and ProfileString my connection.

A: To create a DSN-less connection, I pulled this syntax from http://www.connectionstrings.com/
ODBC:
SQLCA.DBMS = "ODBC"
SQLCA.DBParm = "Driver={MySQL ODBC 5.1 Driver};Server=myServerAddress;Database=myDataBase;User=myUsername;Password=myPassword;Option=3;"

Note that you might have to tweak the version number (5.1) to match the version you download.

A: // Profile Transporter3
SQLCA.DBMS = "JDBC"
SQLCA.LogPass = "tss"
SQLCA.LogId = "root"
SQLCA.AutoCommit = False
SQLCA.DBParm = "Driver='com.mysql.jdbc.Driver',URL='jdbc:mysql://localhost:3306/mydb'"

the only thing is you need to set classpath of the jar file for which i posted in Linked in please refer
now it connect to MySQL the big problem arises is Ignore space after Function name
I dont understand how to set option for this in JDBC for odbc there is option. i go through documentation
of connector J but no such option. This problem arises only for PowerBuilder so i request you if you know the solution please provide it.

A: i resolve this issue mysql option -i or --ignore-spaces is going to work so i set that option in configuration files i.e. my.ini
sql-mode="STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION,IGNORE_SPACE"
stop MySQL service and then started it works smoothly

A: You have to configurare db profile like servername, database, etc., . In this preview tabpage check the connection and copy &paster the commands in application open event.
By PB team


text:
Q: Build a graph that works with variable batch size using Tensorflow I use tf.placeholders() ops for feeding variable batch size of input which are 2D tensors and use the feed mechanism to supply different values for those tensors when I call run().
I got

TypeError: 'Tensor' object is not iterable.

Following is my code:
with graph.as_default():
    train_index_input = tf.placeholder(tf.int32, shape=(None, window_size))
    train_embeddings = tf.Variable(tf.random_uniform([vocabulary_size, embedding_dimension], -1.0, 1.0))
    embedding_input = [tf.nn.embedding_lookup(train_embeddings, x) for x in train_index_input]
    ......
    ......

As I can not see the content of the tensor "train_index_input" without running the graph,  so the error of "'Tensor' object is not iterable" raises for the code:
embedding_input = [tf.nn.embedding_lookup(train_embeddings, x) for x in train_index_input]

What I want to obtain is an embedding matrix "embedding_input" that is of shape [batch_size, embedding_dimension] where batch_size is not fixed. Do I have to define a new operation in Tensorflow for embedding lookup for 2D tensors? Or any other ways to do it?Thanks

A: You're trying to do a python-level list comprehension (for x in train_index_input) over a Tensorflow placeholder.  That won't work - Python has no idea what's inside a tf object.
To accomplish a batch embedding lookup, what you can do is just flatten your batch:
train_indexes_flat = tf.reshape(train_index_input, [-1])

run it through embedding lookup:
looked_up_embeddings = tf.nn.embedding_lookup(train_embeddings, train_indexes_flat)

and then reshape it back into the right groups:
embedding_input = tf.reshape(looked_up_embeddings, [-1, window_size])


text:
Q: php-aria2 JSONRPC Empty reply from server I use php-aria2 to download remote files. But all request to 127.0.0.1:8100/jsonrpc returns null. aria2c works fine from command line.
When I run this from command line
curl http://127.0.0.1:6800/jsonrpc -H "Content-Type: application/json" -H "Accept: application/json" --data '{{"jsonrpc": "2.0","id":1, "method": "aria2.getGlobalStat", "params":[]}' -G

I got:

curl: (52) Empty reply from server

Somebody  knows how to fix this?

A: The simple fix is remove redundant "{" and use POST instead of GET:
curl http://127.0.0.1:6800/jsonrpc -H "Content-Type: application/json" -H "Accept: application/json" --data '{"jsonrpc": "2.0","id":1, "method": "aria2.getGlobalStat", "params":[]}'

aria2 supports JSON-RPC in GET request, but it needs to be encoded properly. See http://aria2.sourceforge.net/manual/en/html/aria2c.html#json-rpc-using-http-get

A: curl -H 'Content-Type:application/json' -d '{"jsonrpc":"2.0","id":"qwer","method":"aria2.getGlobalStat", "params": []}' http://localhost:6800/jsonrpc

if us --rpc-secret=TOKEN need this
curl -H 'Content-Type:application/json' -d '{"jsonrpc":"2.0","id":"qwer","method":"aria2.getGlobalStat", "params": ["token:TOKEN"]}' http://localhost:6800/jsonrpc

A: curl http://127.0.0.1:6800/jsonrpc --data "{\"jsonrpc\": \"2.0\",\"id\":1, \"method\": \"aria2.getGlobalStat\", \"params\":[]}"

or
curl http://127.0.0.1:6800/jsonrpc --data "{"""jsonrpc""": """2.0""","""id""":1, """method""": """aria2.getGlobalStat""", """params""":[]}"


text:
Q: CodeIgniter Encryption Library I'm building a quick site with CodeIgniter and currently I'm making use of the CI 'encrypt' library. Reading through here it sounds like I just throw on a quick:
$this->encrypt->encode($secret_data);

and do this when you want to use it:
$this->encrypt->decode($encripted_string);

Then the magic of CI and Mcrypt do the rest.
Well I'm not sure I can sleep without knowing what is going on in the background. So I have two questions...

*

*How is this working? Or is there a good resource to explain to me how this is working that I can read up on it?

*Is this generally thought of as a safe way to encrypt data? If not where else should I be looking.

A: You're reading the "wrong" thing ...
The CodeIgniter documentation on EllisLab's website is outdated and no longer the official one. It's also for CodeIgniter 2.x, which is itself no longer supported.
The official documentation is on codeigniter.com, and you should be using CodeIgniter 3.x, which deprecates that old CI_Encrypt library and replaces it with a new one, which is far better and more well-documented, here:
http://www.codeigniter.com/userguide3/libraries/encryption.html

A: 1. How is it working:
codeigniter 2.x
The CodeIgniter Encryption Class provides a two-way keyed encoding using XOR Hashing and Mcrypt.
interesting about XOR Hashing: https://stackoverflow.com/a/27952689/2275490
the php manual about Mcrypt: http://php.net/manual/en/book.mcrypt.php
Also you might want to check in system->libraries for the encrypt.php file and discover what it does.
codeigniter 3.x
Provides two-way keyed encoding using Mcrypt
the php manual about Mcrypt: http://php.net/manual/en/book.mcrypt.php
the CI manual: http://www.codeigniter.com/userguide3/libraries/encryption.html
2. thought as safe way to encrypt data:
that's opinion based, I think definitely yes for a "quick site"


text:
Q: const id, operator= and vector erase - can they work together? I have a vector of Persons. At the time i thought it would be a good idea to give every person a unique id. And so i did:
class Person {
    Person::Person(): id(currentID++){
    }
    const int id;
}

After a while i wanted to build a vector of persons and so i learned that i'd have to provide a few more functions:

An element of vector must be:
Copyable, i.e. have a constructor compatible with T(const T&)
Assignable, i.e. have an operator= compatible with operator=(const T&).
Default-constructible, i.e. have a constructor compatible with T().

And so i did my best and came up with
Person::Person(const Person& other): id(other.id) {
}
Person& Person::operator=(const Person& other)
}

Everything seemed to be working splendidly.
But one day i tried to erase an element from my vector just like i learned
vector<Person> persons;
persons.push_back(Person()); //id 0
persons.push_back(Person()); //id 1
persons.push_back(Person()); //id 2

vector<Person>::iterator it;
for(it = persons.begin() ; it != persons.end() ; ) {
    if(it->getID() == 1) {
        it = persons.erase(it);
    } else {
        it++;
    }
}
//persons.size() == 1

I checked the debugger and saw that erase uses the operator= to move the elements after the call to erase. Obviously id wasn't changed and so i deleted every element after id 1 in my vector.
Why is that the case? I always thought vector erase just would move the pointer from element 0 to 2 to drop element 1.
How should i deal with my const id? Should i include it in operator=?
I read about a move operator in C+11 (which i use), would vector use this special operator if i provide it?


text:
Q: When should I use semaphores? When would one use semaphores ?
Only example I can think of is limiting the number of threads accessing the same data/code simultaneously...
Any other scenarios in which semaphores would be the best solution ?

A: Semaphores might be appropriate for signaling between processes. For multithreaded programming, semaphores should be avoided. If you need exclusive access to a resource, use mutex. If you need to wait for a signal, use condition variable.
Even the most often mentioned case of a resource pool can be implemented simpler and safer with a condition variable than with a semaphore. Let's look at this case. A naive implementation with a semaphore would look like (pseudocode):
wait for semaphore to open
take a resource out of the pool
use the resource
put it back to the pool
open the semaphore for one more thread

The first problem is that semaphore does not protect the pool from being accessed by several threads. So, another protection is required. Let it be a lock:
wait for semaphore to open
acquire the lock for the pool
take a resource out of the pool
release the lock
use the resource
acquire the lock
put the resource back to the pool
release the lock
open the semaphore for one more thread

Additional measures need to be taken to ensure the pool is not empty when accessed. Technically it is possible to access the pool bypassing the semaphore, but it would break resource availability guarantees for the acquisition procedure above. So the pool should be only accessed via that procedure.
So far so good, but what if a thread does not want to wait passively for a resource? Can non-blocking resource acquisition be supported? It's easy if the semaphore itself supports non-blocking acquisition; otherwise (e.g. on Windows) this will be problematic. The semaphore cannot be bypassed, because it would break the blocking case. Passing through the semaphore only if the pool is not empty may lead to a deadlock if done under the lock, but as soon as the lock is released, the result of the check for emptiness becomes useless. It is probably doable (I did not try), but surely leads to significant additional complexity.
With condition variable, this is solved easily. Here is the pseudocode with blocking acquisition:
acquire the lock
while the resource pool is empty,
    wait for condition variable to be signaled
take a resource out of the pool
release the lock
use the resource
acquire the lock
put the resource back to the pool
release the lock
signal the condition variable

And in this case there is no problem to add non-blocking acquisition:
acquire the lock
if the resource pool is not empty,
    take a resource out of the pool
release the lock
if the pool was empty, return

As you may see, it does not even need to access condition variable, and makes no harm to the blocking case. To me, it's clearly superior to the use of semaphore.

A: Connection Pools.
I.e. you have 20 connections and 150 threads. In that case you would have a semaphore to control access to the 20 connections.

A: Semaphores can be acquired by one thread and released in another. Locks typically cannot do this. I have used this when thread A finishes using a resource and passes control of the resource to thread B. I had to control the order to avoid deadlocks in this particular situation.


text:
Q: Mobile Push test message I'm trying to send mobile push test messages through marketing cloud.
How can I add my device ID to mobile push so I can send a test message to only "me", not all of the subscribers? Please kindly share the mobile push notification testing method.
Where can I find my device ID?
Currently, there are no contacts in my account since i haven't linked my contacts yet.
Thank you

A: If you have the SDK configured correctly then it will register itself. Once your device is registered you can create an audience list for your device or your contactKey.

A: You can import a CSV file with a test record, hence you use the new contact for your test send.
Note: your CSV file would need these fields: Contact Key, DeviceID, Platform,   System Token
I put these steps here for your reference:

*

*Go to Mobile Push: Mobile Studio >> Mobile Push

*On the top right corner: click Add Contacts.

*Select the destination for the imported contacts.

*Select the file to upload.

*Before uploading, certify whether you have opt-in permission from contacts in the file.

*Click Next.

*Select the application to associate with the contacts.

*Click Next.

*Map the column headings in the file to the supported MobilePush columns

*Click Next.

*Review the import mapping. Make sure that the column headings match the data in the columns. Click Back to change.

*Enter your email address for notification when the import completes.

*Click Finish.

Reference: Import Contacts into MobilePush


text:
Q: Efficiency problem i am trying to make my algorithm more efficient but for some reason its not working correctly could someone tell me if my logic is correct. The general problem is that if u have a height of 'x', and you can jump 'u' distance but you fall 'd' distance if you havent cleared the height already. i have to calculate the number of jumps.
Initial code works correctly
while(x-u>0) {
    x=x-u+d;
    i++;
}
i++;

more efficient code (for some reason fails some cases, I don't know which cases though)
int k=u-d;
if(x-u<=0){
    i++;
} else {
    int z=x/k;
    if (x-((z-1)*k)-u <= 0) {
        i+=z;
    } else {
        i=i+z+1;
    }
}

let me try and clarify the problem you have a wall of height X, you can jump up distance U but every time you jump you also slip down distance D.
so lets say if u have a wall of height x=4, u=4, d=1. Then you would only have to jump once because the first time you jump you have cleared the wall, so you dont slip down at all. now lets say x=6, u=4,d=1. Then you would have to jump twice because the first time you would jump up to 4 but fall 1 so you are at 3 then the next jump you clear the wall.

A: Okay, let's see. The last jump comes from the height of x - u or higher. The rest you have to cover in (u - d)-size steps, the number of such steps is of course (x - u)/(u - d).
After i-th step you are at height i * (u - d) + u (and falling down). So, in approx. (x - u)/(u - d) steps you are at height x - u + u = x. Recalling that the number of steps should be a whole number, we get the final result:
if (u >= x)
    return 1;
if (u <= d)
    throw "Impossible";
return ceil((x - u)/(u - d));

(ceil is a mathematical function returning the smallest integer not less than the given number.)


text:
Q: How make iframe take a whole height of the modal on mobile devices? I've tried a lot of solutions I found on stack overflow, but nothing works for me.
I have a modal with iframe that works very well, but doesn't work on mobile devices.

All I want is for iframe to take a whole height so it would look something like this:

My code for the modal that doesn't work as I want it to:

I tried to put position: fixed and also height: 100% on .modal fade I did height: 100% on iframe, but doesn't work.

A: I changed the height of iframe to pixels and it worked. So instead of:
40vw i did 550px.
Personally I don't really like that solution since it doesn't seem to be perfectly responsive, but it is definitely better.


text:
Q: Draw a circle boundary? In a test for a developer job, I was asked to solve this problem which I had no idea about. Would someone please help me.
Draw a dotted line circle boundary using void draw(int x, int y) to draw one point. Use the formula x2 + y2 = r2. You can use sqrt method, but don't use sin, cos or tan etc.
Void DrawCircle(int centerX, int centerY, int radius) {…}

PS: This is not at all a college assignment, so please reply.

A: i wrote a quick code that could solve your problem, but havent tested it.
void DrawCircle(int centerX, int centerY, int radius)
{
    int x,y;
    x=-radius;
    while(x < radius)
    {
        y=sqrt(radius*radius-x*x);
        draw(x+centerX,y+centerY);
        y=-y;
        draw(x+centerX,y+centerY);
        x++;
    }
}

A: Here's a function that finds the dots on the border of your circle (there's an infinite number of points, the smaller dDensity is, the more points you'll get.)
double dDensity = 1.0;
double y, x;
for (x = -radius; x <= radius; x += dDensity)
{
   y = sqrt(-pow(x, 2.0f) + pow(r, 2.0f))
   Console.WriteLine("(" + (x+centerX).ToString() + ","
                     + (y+centerY).ToString() + ")");
}

That will produce you the Points of which the circle consists of.
'Painting' a circle is a different issue, but thats a good start for you IMO.