text:
Q: Oracle SQL - creating a loop I have a script that shows delivery qty data for several manufacturing components. Each component has a different new release date so data will run from a different start date (earliest date is 01/07/2007).
Full script is posted below. The script that I would like to add is ...
* SCRIPT REMOVED *
... this shows the sum of the delivered qty from new release date for a 91 day period (3 months). I could repeat this sub select for each 3 month period but, I would have to add more sub selects as time goes on to keep data running to date.
Is there a way to run a loop so to return the delivered qty every 91 days from the new release to date?
* SCRIPT REMOVED *

OK ... thanks for all your advice re: JOIN's and subqueries.
I have revised the JOINS in the script and removed many of the subqueries (full script below).
My question now goes back to the creation of a loop in SQL. Instead of creating dozens of subqueries to show the delivery qty for specified periods of time, could I create a loop that will return the sum delivery qty, per month from the new release date (NR_DATE) to the current date. Subquery would potentially look like the following (and then repeated for each required period)...
(select nvl(sum(dp.del_qty),0) from bds_dhead@sid_to_cdsuk dh, bds_dline@sid_to_cdsuk dp where dp.dhead_no = dh.dhead_no and dh.d_status = '9' and dp.article_no = '9'||nrb.p_catnr and trunc(dh.actshpdate) > trunc(sysdate - 30)) sum_CDS_delqty_30_days

I'm hoping I'm making some sense ... apologies if I'm not clear. I've only been writing SQL for a few months and have taught myself using existing, OLD, reports.
Thanks
FULL SCRIPT
select pd.part_no,
   pd.catnr,
   pd.prodtyp,
   pd.packtyp,
   pd.description,
   ip.purchase_type,
   nvl(pd.fod_idc, 'N'),
   (select max(acp.qty_free_idc)
      from oes_fod_match acp
     where pd.part_no = acp.part_no
       and acp.type = 'SUP'
       and acp.cre_dat = (select max(acp1.cre_dat)
                            from oes_fod_match acp1
                           where acp.part_no = acp1.part_no
                             and acp1.qty_free > 0
                             and acp1.type = 'SUP')) qty_free_idc,
   (select nvl(sum(pl.qty_onhand), 0)
      from part_loc pl
     where pl.part_no = pd.part_no
       and pl.location_type = 'IN'
       and pl.plant in ('A',
           'T',
           'L')) current_stock_at_comp,
   (select nvl(sum(pl.qty_onhand), 0)
      from part_loc pl
     where pl.part_no = pd.part_no
       and pl.location_type = 'IN'
       and pl.plant in ('Z',
           'V')) current_stock_cz_comp,
   (select nvl(sum(pl.qty_onhand), 0)
      from part_loc pl
     where pl.part_no = pd.part_no
       and pl.location_type = 'IN'
       and pl.plant in ('W',
           '2')) current_stock_uk_comp,
   (select nvl(sum(pl.qty_onhand), 0)
      from part_loc pl
     where pl.part_no = pd.part_no
       and pl.location_type = 'IN') total_stock_comp,
   (select nvl(max(val_strg1), 0)
      from sd_domainval dv
     where dv.val_strg = pd.part_no) min_stock_lvl,
   (select nvl(max(val_strg2), 0)
      from sd_domainval dv
     where dv.val_strg = pd.part_no) min_order_qty,
   (select nvl(max(val_strg3), 'ND')
      from sd_domainval dv
     where dv.val_strg = pd.part_no) pref_assembly_plant,
   (select nvl(max(pp.qty), 0)
      from oes_purpos pp
     where pp.av_part_no = pd.part_no
       and pp.c_status != 'D'
       and pp.datneu = (select max(pp1.datneu)
                          from oes_purpos pp1
                         where pp1.av_part_no = pp.av_part_no
                           and pp1.c_status != 'D')) last_aw_po_qty,
   (select nvl(sum(ps.requ_qty - nvl(ps.del_qty, 0)), 0)
      from oes_purpos pp,
           oes_purseg ps
     where ps.headnr = pp.headnr
       and ps.posnr = pp.posnr
       and pp.av_part_no = pd.part_no
       and ps.c_status not in ('9',
           'D')
       and ps.o_status not in ('D',
           '9')) open_aw_po_qty,
   (select nvl(sum(al.qty_onhand), 0)
      from bds_location@sid_to_cdsuk l,
           bds_article_location@sid_to_cdsuk al
     where al.article_no = '9' || nrb.p_catnr
       and al.qty_onhand <> 0
       and l.location_no = al.location_no
       and l.location_no like '  1             DCMS%'
       and l.location_class not in ('D',
           'C')) onhand_CDS,
   (select nvl(sum(st.qty_in_process), 0)
      from BDS_ARTICLE_INVLEVEL_ORG@sid_to_cdsuk st
     where st.article_no = '9' || nrb.p_catnr) allocated_CDS,
   (select nvl(sum(st.qty_in_process), 0)
      from BDS_ARTICLE_INVLEVEL_ORG@sid_to_cdsuk st
     where st.article_no = '9' || nrb.p_catnr) allocated_CDS,
   (select min(selection_relse_date)
      from BDS_SELECTION_ORG@sid_to_cdsuk st
     where substr(selection_no, 2, 99) = pd.catnr) NR_DATE,
   (select sum(ds.planqty - nvl(ds.delqty, 0))
      from oes_opos op,
           oes_oposdelseg ds,
           ncf_comppart nc,
           oes_nrbom nb
     where ds.ordnr = op.ordnr
       and ds.posnr = op.posnr
       and nc.item_part_no = pd.part_no
       and nb.c_catnr = nc.catnr
       and nb.c_prodtyp = nc.prodtyp
       and nb.c_packtyp = nc.packtyp
       and nb.c_vernr = nc.vernr
       and op.catnr = nb.p_catnr
       and op.prodtyp = nb.p_prodtyp
       and op.packtyp = nb.p_packtyp
       and op.vernr = nb.p_vernr
       and ds.c_status not in ('9',
           'D')
       and op.ol_typ = 'XX') sum_open_xx_order,
   (select nvl(sum(pl.qty_onhand), 0)
      from ncf_comppart nc,
           oes_nrbom nb,
           part_description pd1,
           part_loc pl
     where nc.item_part_no = pd.part_no
       and nb.c_catnr = nc.catnr
       and nb.c_prodtyp = nc.prodtyp
       and nb.c_packtyp = nc.packtyp
       and nb.c_vernr = nc.vernr
       and pd1.catnr = nb.p_catnr
       and pd1.prodtyp = nb.p_prodtyp
       and pd1.packtyp = nb.p_packtyp
       and pd1.vernr = nb.p_vernr
       and pl.part_no = pd1.part_no) onhand_avalon_fp,
   (select unique sv.gps_planshpdate
      from oes_delsegview sv,
           oes_opos op,
           oes_oposdelseg ds,
           oes_nrbom nb,
           ncf_comppart cp
     where cp.item_part_no = pd.part_no
       and nb.c_catnr = cp.catnr
       and nb.c_prodtyp = cp.prodtyp
       and nb.c_packtyp = cp.packtyp
       and nb.c_vernr = cp.vernr
       and sv.ordnr = ds.ordnr
       and sv.posnr = ds.posnr
       and sv.catnr = nb.p_catnr
       and sv.prodtyp = nb.p_prodtyp
       and sv.packtyp = nb.p_packtyp
       and op.ordnr = ds.ordnr
       and op.posnr = ds.posnr
       and op.catnr = nb.p_catnr
       and op.prodtyp = nb.p_prodtyp
       and op.packtyp = nb.p_packtyp
       and op.vernr = nb.p_vernr
       and nb.active = 'Y'
       and op.ol_typ in ('XX',
           'CO')
       and sv.gps_planshpdate = (select max(sv1.gps_planshpdate)
                                   from oes_delsegview sv1,
                                        oes_opos op1,
                                        oes_oposdelseg ds1,
                                        oes_nrbom nb1,
                                        ncf_comppart cp1
                                  where cp1.item_part_no = cp.item_part_no
                                    and nb1.c_catnr = cp1.catnr
                                    and nb1.c_prodtyp = cp1.prodtyp
                                    and nb1.c_packtyp = cp1.packtyp
                                    and nb1.c_vernr = cp1.vernr
                                    and sv1.ordnr = ds1.ordnr
                                    and sv1.posnr = ds1.posnr
                                    and sv1.catnr = nb1.p_catnr
                                    and sv1.prodtyp = nb1.p_prodtyp
                                    and sv1.packtyp = nb1.p_packtyp
                                    and op1.ordnr = ds1.ordnr
                                    and op1.posnr = ds1.posnr
                                    and op1.catnr = nb1.p_catnr
                                    and op1.prodtyp = nb1.p_prodtyp
                                    and op1.packtyp = nb1.p_packtyp
                                    and op1.vernr = nb1.p_vernr
                                    and nb1.active = 'Y'
                                    and sv1.ord_o_status = '9'
                                    and op1.ol_typ in ('XX',
                                        'CO'))) last_ship_date_manufacturing,
   (select unique nvl(max(sv.delqty), 0)
      from oes_delsegview sv,
           oes_opos op,
           oes_oposdelseg ds,
           oes_nrbom nb,
           ncf_comppart cp
     where cp.item_part_no = pd.part_no
       and nb.c_catnr = cp.catnr
       and nb.c_prodtyp = cp.prodtyp
       and nb.c_packtyp = cp.packtyp
       and nb.c_vernr = cp.vernr
       and sv.ordnr = ds.ordnr
       and sv.posnr = ds.posnr
       and sv.catnr = nb.p_catnr
       and sv.prodtyp = nb.p_prodtyp
       and sv.packtyp = nb.p_packtyp
       and op.ordnr = ds.ordnr
       and op.posnr = ds.posnr
       and op.catnr = nb.p_catnr
       and op.prodtyp = nb.p_prodtyp
       and op.packtyp = nb.p_packtyp
       and op.vernr = nb.p_vernr
       and nb.active = 'Y'
       and op.ol_typ in ('XX',
           'CO')
       and sv.gps_planshpdate = (select max(sv1.gps_planshpdate)
                                   from oes_delsegview sv1,
                                        oes_opos op1,
                                        oes_oposdelseg ds1,
                                        oes_nrbom nb1,
                                        ncf_comppart cp1
                                  where cp1.item_part_no = cp.item_part_no
                                    and nb1.c_catnr = cp1.catnr
                                    and nb1.c_prodtyp = cp1.prodtyp
                                    and nb1.c_packtyp = cp1.packtyp
                                    and nb1.c_vernr = cp1.vernr
                                    and sv1.ordnr = ds1.ordnr
                                    and sv1.posnr = ds1.posnr
                                    and sv1.catnr = nb1.p_catnr
                                    and sv1.prodtyp = nb1.p_prodtyp
                                    and sv1.packtyp = nb1.p_packtyp
                                    and op1.ordnr = ds1.ordnr
                                    and op1.posnr = ds1.posnr
                                    and op1.catnr = nb1.p_catnr
                                    and op1.prodtyp = nb1.p_prodtyp
                                    and op1.packtyp = nb1.p_packtyp
                                    and op1.vernr = nb1.p_vernr
                                    and nb1.active = 'Y'
                                    and sv1.ord_o_status = '9'
                                    and op1.ol_typ in ('XX',
                                        'CO'))) last_ship_qty_manufacturing,
   case when case when (select max(psd.conf_date)
                          from oes_purseg psd,
                               OES_PURSEGVIEW psv
                         where psv.headnr = psd.headnr
                           and psv.posnr = psd.posnr
                           and psv.segnr = psd.segnr
                           and psv.av_part_no = pd.part_no
                           and psv.ps_o_status in ('1', '2', '7')
                           and psv.ps_c_status not in ('D', '9')) is null then (select max(psd.requ_date)                                                                                from oes_purseg psd,
                                                                                OES_PURSEGVIEW psv
                                                                                where psv.headnr = psd.headnr
                                                                                and psv.posnr = psd.posnr
                                                                                and psv.segnr = psd.segnr
                                                                                and psv.av_part_no = pd.part_no
                                                                                and psv.ps_o_status in ('0', '1', '2', '7')
                                                                                and psv.ps_c_status not in ('D', '9'))
                  else (select max(psd.conf_date)
                          from oes_purseg psd,
                               OES_PURSEGVIEW psv
                         where psv.headnr = psd.headnr
                           and psv.posnr = psd.posnr
                           and psv.segnr = psd.segnr
                           and psv.av_part_no = pd.part_no
                           and psv.ps_o_status in ('1', '2', '7')
                           and psv.ps_c_status not in ('D', '9')) end is null then (select max(ps1.del_date)
                                                                                from oes_purseg ps1
                                                                                where ps1.headnr || ps1.posnr || ps1.segnr = (select rq.pur_headnr || rq.pur_posnr || rq.pur_segnr
                                                                                from oes_requisition rq
                                                                                where rq.seqnr = (select fm.req_seqnr
                                                                                from oes_fod_match fm
                                                                                where fm.part_no = pd.part_no
                                                                                and fm.qty_free_idc = 'Y'
                                                                                and fm.cre_dat = (select max(fM1.cre_dat)
                                                                                from oes_fod_match fm1
                                                                                where fm.part_no = fm1.part_no
                                                                                and fm1.qty_free_idc = 'Y'))))
        else case when (select max(psd.conf_date)
                          from oes_purseg psd,
                               OES_PURSEGVIEW psv
                         where psv.headnr = psd.headnr
                           and psv.posnr = psd.posnr
                           and psv.segnr = psd.segnr
                           and psv.av_part_no = pd.part_no
                           and psv.ps_o_status in ('1', '2', '7')
                           and psv.ps_c_status not in ('D', '9')) is null then (select max(psd.requ_date)
                                                                                from oes_purseg psd,
                                                                                OES_PURSEGVIEW psv
                                                                                where psv.headnr = psd.headnr
                                                                                and psv.posnr = psd.posnr
                                                                                and psv.segnr = psd.segnr
                                                                                and psv.av_part_no = pd.part_no
                                                                                and psv.ps_o_status in ('1', '2', '7')
                                                                                and psv.ps_c_status not in ('D', '9'))
                  else (select /*+ ORDERED */ max(psd.conf_date)
                          from oes_purseg psd,
                               OES_PURSEGVIEW psv
                         where psv.headnr = psd.headnr
                           and psv.posnr = psd.posnr
                           and psv.segnr = psd.segnr
                           and psv.av_part_no = pd.part_no
                           and psv.ps_o_status in ('1', '2', '7')
                           and psv.ps_c_status not in ('D', '9')) end end ACP_start_date,
   (select max(acp2.cre_dat)
      from oes_fod_match acp2
     where pd.part_no = acp2.part_no
       and acp2.type = 'SUP'
       and acp2.cre_usr = 'SOX9347') ACP_migration_date,
   (select round(nvl(avg(dp.del_qty), 0))
      from bds_dhead@sid_to_cdsuk dh,
           bds_dline@sid_to_cdsuk dp
     where dp.dhead_no = dh.dhead_no
       and dh.d_status = '9'
       and dp.article_no = '9' || nrb.p_catnr
       and dh.actshpdate > sysdate - 365) * 90 avg_CDS_delqty_last_2_mths,
   nrb.p_catnr used_in_catnr
  FROM part_description pd
   INNER JOIN inventory_purchase ip
      ON ip.part_no = pd.part_no
   INNER JOIN scm_prodtyp pt
      ON pt.prodtyp = pd.prodtyp
   INNER JOIN oes_fod_match acp
      ON acp.part_no = pd.part_no
   INNER JOIN part_description pd3
      ON pd3.part_no = pd.part_no
   INNER JOIN NCF_COMPPART ncf
      ON ncf.item_part_no = pd3.part_no
   INNER JOIN oes_nrbom nrb
      ON ncf.catnr = nrb.c_catnr
         AND ncf.prodtyp = nrb.c_prodtyp
         AND ncf.packtyp = nrb.c_packtyp
         AND ncf.vernr = nrb.c_vernr
 WHERE pd.cunr in ('649830', 'W30000')
   and pd.catnr = '2EDVD0017'
   and pd.fod_idc = 'Y'
   and pt.prodgrp = 'AW'

A: I had trouble deciding where to start, but I decided on this: JOINS
I seems to me, that if you try to apply ANSI join syntax that you have a table in your query with NO JOIN CONDITIONS and hence you may have a Cartesian product in effect which will just multiply the number of result rows.
i.e. in attempting to move from your original:
FROM part_description pd
   , inventory_purchase ip
   , scm_prodtyp pt
   , oes_fod_match acp
   , NCF_COMPPART ncf
   , part_description pd3
   , oes_nrbom nrb
WHERE ip.part_no = pd.part_no
      AND pt.prodtyp = pd.prodtyp
      AND pt.prodgrp = 'AW'
      AND pd.cunr IN ('649830', 'W30000')
      AND pd.catnr IN ('BBCDVD3285', 'BBCDVD3297', 'BBCDVD2816', '2EDVD0146', 'BBCDVD1020', 'BBCDVD2687', 'BBCDVD1106')
      AND pd.fod_idc = 'Y'
      AND ncf.item_part_no = pd3.part_no
      AND ncf.catnr = nrb.c_catnr
      AND ncf.prodtyp = nrb.c_prodtyp
      AND ncf.packtyp = nrb.c_packtyp
      AND ncf.vernr = nrb.c_vernr
      AND pd3.part_no = pd.part_no

to a variant using explict join syntax:
FROM part_description pd
INNER JOIN inventory_purchase ip ON ip.part_no = pd.part_no
INNER JOIN scm_prodtyp pt        ON pt.prodtyp = pd.prodtyp
                                     AND pt.prodgrp = 'AW'

CROSS JOIN oes_fod_match acp --<< NO join conditions given

INNER JOIN part_description pd3 ON pd3.part_no = pd.part_no
INNER JOIN NCF_COMPPART ncf     ON ncf.item_part_no = pd3.part_no

INNER JOIN oes_nrbom nrb ON ncf.catnr = nrb.c_catnr
                                   AND ncf.prodtyp = nrb.c_prodtyp
                                   AND ncf.packtyp = nrb.c_packtyp
                                   AND ncf.vernr = nrb.c_vernr

WHERE  pd.cunr IN ('649830', 'W30000')
      AND pd.catnr IN ('BBCDVD3285', 'BBCDVD3297', 'BBCDVD2816', '2EDVD0146', 'BBCDVD1020', 'BBCDVD2687', 'BBCDVD1106')
      AND pd.fod_idc = 'Y'

There is no specified join conditions for table: oes_fod_match (acp)
This will most probably be having a large adverse effect on performance of this query and which is perhaps why you use SELECT UNIQUE at the outset. "SELECT UNIQUE" will also make it slower by the way. Then multiply all of this by running 63 correlated subqueries, on many unnecessary rows. Wow! AND you want to add more subqueries.
Please stop for a moment and reconsider just the joins. I may be wrong, and I hope for your sake that I am, but please make sure oes_fod_match is joined correctly before adding anything.

A: Regarding the large number of "correlated subqueries" (63 I believe):
These are usually not an efficient way to query, and often they can be replaced by more efficient methods. I believe this is the situation here.
Here is an example for 6 of those subqueries (from the original unedited question):
   (select nvl(sum(ps.requ_qty),0) from oes_purpos pp, oes_purseg ps where ps.headnr = pp.headnr and ps.posnr = pp.posnr and pp.av_part_no = pd.part_no and ps.c_status != 'D' and ps.requ_date > sysdate - 90) sum_aw_po_qty_3_mths,
   (select nvl(sum(ps.requ_qty),0) from oes_purpos pp, oes_purseg ps where ps.headnr = pp.headnr and ps.posnr = pp.posnr and pp.av_part_no = pd.part_no and ps.c_status != 'D' and ps.requ_date > sysdate - 180) sum_aw_po_qty_6_mths,
   (select nvl(sum(ps.requ_qty),0) from oes_purpos pp, oes_purseg ps where ps.headnr = pp.headnr and ps.posnr = pp.posnr and pp.av_part_no = pd.part_no and ps.c_status != 'D' and ps.requ_date > sysdate - 270) sum_aw_po_qty_9_mths,
   (select nvl(sum(ps.requ_qty),0) from oes_purpos pp, oes_purseg ps where ps.headnr = pp.headnr and ps.posnr = pp.posnr and pp.av_part_no = pd.part_no and ps.c_status != 'D' and ps.requ_date > sysdate - 365) sum_aw_po_qty_12_mths,
   (select nvl(sum(ps.requ_qty),0) from oes_purpos pp, oes_purseg ps where ps.headnr = pp.headnr and ps.posnr = pp.posnr and pp.av_part_no = pd.part_no and ps.c_status != 'D' and ps.requ_date > sysdate - 540) sum_aw_po_qty_18_mths,
   (select nvl(sum(ps.requ_qty),0) from oes_purpos pp, oes_purseg ps where ps.headnr = pp.headnr and ps.posnr = pp.posnr and pp.av_part_no = pd.part_no and ps.c_status != 'D' and ps.requ_date > sysdate - 730) sum_aw_po_qty_24_mths,

which I believe can be replaced by a more efficient single "derived table" like this:
...
FROM part_description pd
INNER JOIN (
            select
                  pp.av_part_no
                , SUM(case when ps.requ_date > TRUNC(sysdate) - 90   then requ_qty else 0 end)  sum_aw_po_qty_3_mths
                , SUM(case when ps.requ_date > TRUNC(sysdate) - 180  then requ_qty else 0 end)  sum_aw_po_qty_6_mths
                , SUM(case when ps.requ_date > TRUNC(sysdate) - 270  then requ_qty else 0 end)  sum_aw_po_qty_9_mths
                , SUM(case when ps.requ_date > TRUNC(sysdate) - 365  then requ_qty else 0 end)  sum_aw_po_qty_12_mths
                , SUM(case when ps.requ_date > TRUNC(sysdate) - 540  then requ_qty else 0 end)  sum_aw_po_qty_18_mths
                , SUM(requ_qty)                                                                 sum_aw_po_qty_24_mths
            from oes_purpos pp
            inner join oes_purseg ps ON  ps.headnr = pp.headnr and ps.posnr = pp.posnr
            where ps.c_status != 'D' and ps.requ_date > TRUNC(sysdate) - 730
            group by
                  pp.av_part_no
           ) pp on pp.av_part_no = pd.part_no

Instead of joining, scanning and filtering tables oes_purpos pp, oes_purseg ps 6 times, we do it once.
This same logic can be applied to several other (probably all) of the original 63 subqueries

by the way, you should use TRUNC(sysdate) so that the time component of sysdate is ignored (i.e. all date comparisons use midnight)


text:
Q: Scramble String in Swift I would like to scramble a string containing a users UID, so this cannot be tracked using the database.
I would also like that this should be a consistant pattern, so no random shuffling of letters - If the user changes the device, the result coming out from this function should still be the same.
Yet, i wouldn't want to add CryptoSwift just for this
This is only to make readability harder, but also to make sure that the same user posts to the same place in the database basically. So there will be no security issues connected to this. It will only be used to anonymize some data.
A UID could look like this "0bb0fca0-1e89-429f-901a-1413894d9f59"
How can i achieve this in the best way?
I'm thinking something like adding prime numbers or having some kind of "black box" for just sending a string to the function and getting another string back. Size of the string or how it should be done doesn't really matter

A: I found a good solution to this. There was a guy who made a single file MD5-converter without any third party libraries named MD5 Digest
Then this library can be used like this
let input = "0bb0fca0-1e89-429f-901a-1413894d9f59"
let md5 = input.utf8.md5
print(md5)

this gives the result:
4a89b58cb43b3eecd289c1d093b48bd0

This is exactly what I wanted, something that can be re-created, but still makes a result based on the string I sent in that the user can't connect to the string being sent in.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sortable with Bootstrap and 2 row fluid columns I am actually coding a kind dashboard page with some widgets i'd like to be sortable. The main structure of the page is based on Twitter Bootstrap 3.0.
The interesting part is as follow :

            Widget 1

            Widget 2

            Widget 3

            Widget 4

            Widget 5

            Widget 6

And the JS code like :
$( ".sortable" ).sortable();
$( ".sortable" ).disableSelection();

My problem is that I can sort the widget in the same column, but I can't do the sorting from one column to another.
Any idea ?

A: You need to use connectWith parameter. Check out this example: http://jqueryui.com/sortable/#portlets
So this is what you need:
$(".sortable").sortable({connectWith: ".sortable"}).disableSelection();

Here's a working jsFiddle for your particular case: http://jsfiddle.net/SvxGb/


text:
Q: SQL - Is it possible to use alias in where? I tried the following SQL on this example playground page from W3Schools.
SELECT CustomerID AS Id, CustomerName AS Customer
FROM Customers
WHERE Customer="Alfreds Futterkiste";

But I get No value given for one or more required parameters. as response.
It works if I use CustomerName instead of the alias.
Is this a fail of the playground test page or is it just not possible?

A: Looking at your code:
SELECT CustomerID AS Id, CustomerName AS Customer
FROM Customers
WHERE Customer="Alfreds Futterkiste";

To alias the customer table you can do something like:
SELECT c.CustomerID AS Id, c.CustomerName AS Customer
    FROM Customers c
    WHERE c.CustomerName="Alfreds Futterkiste";

Where c is now the alias for Customers
It is not possible to use a column alias in a where clause because the where clause executes BEFORE the select.

A: Ugly, but can be convenient in larger, more complex queries
SELECT * FROM
(SELECT CustomerID AS ID, CustomerName AS Customer
FROM Customers) as A

WHERE Customer = "Alfreds Futterkiste";

A: The WHERE clause is evaluated before select. Hence the where clause is not aware of the aliases you used.
So you need to use the original column name:
SELECT CustomerID AS Id, CustomerName AS Customer
FROM Customers
WHERE CustomerName="Alfreds Futterkiste";

If you must use alias in the where clause, you may use subquery or CTE (an overkill and may result in slower query):
SELECT * from (
    SELECT CustomerID AS Id, CustomerName AS Customer
    FROM Customers
) t WHERE Customer = "Alfreds Futterkiste";

A: No you can't reference the column alias in the WHERE clause.


text:
Q: IntelliJ @IfProfileValue default value In most projects that use Spring extensively there are a few tests that use @IfProfileValue to mark it as integration test, performance test or similar. When you run these with maven you do something like this:
mvn install -Dperformance-test=true

for a class annotated like this:
@IfProfileValue(name = "performance-test", value = "true")

But if I run this test in IntelliJ I get:
Test '.Tests in Progress.MyTest' ignored

which I can go around in IntelliJ by commenting out the annotation, but I would prefer if the test just ran without having to remove the line, so I don't accidentally commit/push the class without the marker.
Is that possible?

A: Edit the run-configurations and set your parameter -Dperformance-test=true
 as VM option.
See the IDEA Run Config for detailed info.


text:
Q: I can not download data from NASA's website with python script I have been trying to download a set of files from NASA's website https://search.earthdata.nasa.gov/search. I was able to sign in and request the file but I get error.
Succesfully logged in
.
.
.
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 401: Unauthorized

I tried requests, wget, urllib2
import requests
import os
import urllib2

destination = r'C:\PROJECTS\ShallowGW\MODIS\\'
os.chdir(destination)

session_req = requests.session()

home_url = 'https://urs.earthdata.nasa.gov/home'
response0 = session_req.get(home_url)

login_url = 'https://urs.earthdata.nasa.gov/login'
login_data = {'authenticity_token': '????',
          'username': '*******',
          'password': '*******'}

response1 = session_req.post(login_url, data=login_data,
headers=dict(referer=login_url))

try:
    response1.raise_for_status()
    print("Succesfully logged in")
except Exception as e:
    print('Login failed')

response3 = session_req.get('https://search.earthdata.nasa.gov/search')
filepath = r'C:\PROJECTS\ShallowGW\MODIS\MODIS_LST_Links_2016.txt'

with open(filepath) as f_obj:
    for line in f_obj:
        urllib2.urlopen(line)
        print(line)

I do not understand why it says I logged in then gives 401 HTTP ERROR. Text file has the links (e.g., https://e4ftl01.cr.usgs.gov//MODV6_Dal_E/MOLT/MOD11A1.006/2016.06.30/MOD11A1.A2016182.h12v04.006.2016241041516.hdf) to download the file. I can manually download them with the same line if I am signed in but it does not work with python. It is supposed to go through the loop and download each file.
Please help!

A: It looks like NASA wants you to include your API key in the request parameters (based on this webpage).
apiKey = # YOUR API KEY HERE
requestParams = {'api_key':apiKey}

response = requests.get('https://search.earthdata.nasa.gov/search', params = requestParams)

There are other request parameters listed here which might be useful. I hope this helps!

A: In my case it worked to create a .netrc file (as specified on https://cddis.nasa.gov/Data_and_Derived_Products/CreateNetrcFile.html)
This is your earthdata login info. You need to register to get it.
If on Unix, change permissions to user-only with chmod 600 .netrc.
Place this file in your HOME directory.
Then copy and paste the code provided by NASA (https://cddis.nasa.gov/Data_and_Derived_Products/CDDIS_Archive_Access.html) for the Python download:
import requests
import sys

# Reads the URL from the command line argument
url = sys.argv[1]

# Assigns the local file name to the last part of the URL
filename = url.split('/')[-1]

# Makes request of URL, stores response in variable r
r = requests.get(url)

# Opens a local file of same name as remote file for writing to
with open(filename, 'wb') as fd:
for chunk in r.iter_content(chunk_size=1000):
fd.write(chunk)

# Closes local file
fd.close()

Or, you could use this python package: https://pypi.org/project/slrfield/


text:
Q: Send array list to Twig View without headers in Symfony 2 I need help sending query list to Twig without headers. I have already query my data and I am stuck. I had to have this data in JSON structure.
This is name of my root: 'AdminBundle:Note:viewPdf.html.twig'
And here is name of query class in propel - it is empty now: MnNoteCommentQuery.
Here is my code:
$noteQuery = MnNoteCommentQuery::create()->find();
$responsed = new JSonResponse($noteQuery);
return $this->render('AdminBundle:Note:viewPdf.html.twig', array('notes' => $responsed));

A: Just use json_encode in twig
return $this->render('AdminBundle:Note:viewPdf.html.twig', array('notes' => $notes));

Twig:
{{ notes | json_encode() }}

You can customize json representation by implementing JsonSerializable interface


text:
Q: How can I transfer bytes in chunks to clients? SignalR loses many messages when I transfer chunks of bytes from client over server to client (or client to server; or server to client).
I read the file into a stream and sent it over a hub or persistent connection to other client. This runs very fast, but there are always messages dropped or lost.
How can I transfer large files (in chunks or not) from client to client without losing messages?

A: As @dfowler points out, it's not the right technology for the job. What I would recommend doing is sending a message that there is a file to be downloaded that includes the link and then you can download that file using standard GET requests against either static files or some web service written with ASP.NET WebAPI.

A: SignalR isn't for file transfer, it's for sending messages.

A: Why isn't it the right technology? If a client needs to send some data to a signalR hub it should be able to over the signalR connection without requiring additional stuff.
In fact it works fine when sending a byte array, at least for me, however I encountered similar problems when transferring chunks.
Perhaps you can do some tests to check if the order in which you send the chunks is the same as the order they are received.
UPDATE
I did a test myself and in my case the order was indeed the problem. Modified the hub method receiving the chunks to accept an order parameter which I then use to reconstruct the byte array at the end and it works fine. Having said this I however now understand that this wouldn't work well with large file transfers.
In my case I don't need to transfer very large amounts of data, I just wanted to give my UI  an indication of progress, requiring the data to be sent in chunks.


text:
Q: Как превратить обычное дропдаун меню в мультиселект дропдаун меню? Есть такое меню:
<select>
 <option value="0" >Select</option>
 <option value="1" >1</option>
 <option value="2" >2</option>
 <option value="3" >3</option>
</select>

Как сделать из него chechbox меню на чистом html/js/css? Например, чтобы я мог выбрать 1,3 или 1,2.
Нужно что-то вроде этого.

A: Нашёл вот такое решение:

var expanded = false;

function showCheckboxes() {
  var checkboxes = document.getElementById("checkboxes");
  if (!expanded) {
    checkboxes.style.display = "block";
    expanded = true;
  } else {
    checkboxes.style.display = "none";
    expanded = false;
  }
}
.multiselect {
  width: 200px;
}

.selectBox {
  position: relative;
}

.selectBox select {
  width: 100%;
  font-weight: bold;
}

.overSelect {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
}

#checkboxes {
  display: none;
  border: 1px #dadada solid;
}

#checkboxes label {
  display: block;
}

#checkboxes label:hover {
  background-color: #1e90ff;
}
<form>

      <select>
        <option>Select an option</option>
      </select>

        <input type="checkbox" id="one" />First checkbox

        <input type="checkbox" id="two" />Second checkbox

        <input type="checkbox" id="three" />Third checkbox

</form>


text:
Q: Elixir map dig functionality like Ruby Hash#Dig Is there an Elixir equivalent for Hash#Dig in Ruby ?
Ruby dig example
h = { foo: {bar: {baz: 1}}}

h.dig(:foo, :bar, :baz)           #=> 1
h.dig(:foo, :zot)                 #=> nil

A: get_in works fine with maps. To make something that works with both maps and structs, you have to make it yourself:
def dig(nil, _), do: nil
def dig(struct, []), do: struct
def dig(struct, [head | tail]) do
  struct
  |> Map.get(head)
  |> dig(tail)
end

> m = %{foo: %{bar: %{baz: 1}}}
> dig m, [:foo, :bar, :baz]
1
> dig m, [:foo, :zot]
nil
> dig m, [:foo, :zot, :qux]
nil

A: Use Kernel.get_in/2:
iex(1)> m = %{foo: %{bar: %{baz: 1}}}
%{foo: %{bar: %{baz: 1}}}
iex(2)> get_in m, [:foo, :bar, :baz]
1
iex(3)> get_in m, [:foo, :zot]
nil

A: Although @Dogbert answer is correct, it will NOT work with structs as they do not implement the Access behavior by default. However I needed a quick and easy way to access a deeply nested state structure of one of my GenServers in one of my test cases (yeah, I know). The module below did the trick for me:
dig.exs
defmodule Dig do
  def dig(data, [key | keys]) when is_map(data) do
    dig(Map.get(data, key), keys)
  end

  def dig(data, [key | keys]) when is_list(data) do
    dig(Enum.at(data, key), keys)
  end

  def dig(data, []) do
    data
  end
end

Usage
import Dig

some_pid
|> :sys.get_state()
|> dig([:nested, :structure, 0, :some, :value])


text:
Q: Force + Drag + Zoom : freeze after few seconds First, I'm quite new in D3.
I'm trying to implement different behaviors in a single D3 graph, using these examples :

*

*Drag + Zoom

*Force-directed Graph

But my graph freezes after few seconds and I don't understand why...
Here is my code : http://jsfiddle.net/blt909/aVhd8/20/ [WORKING FINE VERSION]
 var margin = {top: -5, right: -5, bottom: -5, left: -5};
    var width = 500 - margin.left - margin.right,
height = 400- margin.top - margin.bottom;

    var color = d3.scale.category20();

var force = d3.layout.force()
        .charge(-200)
        .linkDistance(50)
        .size([width + margin.left + margin.right, height + margin.top + margin.bottom]);

    var zoom = d3.behavior.zoom()
        .scaleExtent([1, 10])
        .on("zoom", zoomed);

    var drag = d3.behavior.drag()
        .origin(function(d) { return d; })
        .on("dragstart", dragstarted)
        .on("drag", dragged)
        .on("dragend", dragended);

    var svg = d3.select("#map").append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.right + ")")
        .call(zoom);

    var rect = svg.append("rect")
        .attr("width", width)
        .attr("height", height)
        .style("fill", "none")
        .style("pointer-events", "all");

    var container = svg.append("g");

            force
                .nodes(graph.nodes)
                .links(graph.links)
                .start();

            var tooltip = d3.select("body")
                .append("foreignObject")
                .append("xhtml:div")
                .attr("id", "tooltip")
                .style("position", "absolute")
                .style("z-index", "10")
                .style("color", "#eeeeee")
                .style("visibility", "hidden")
                .text("");

    var link = container.append("g")
                    .attr("class", "links")
                    .selectAll(".link")
        .data(graph.links)
                    .enter().append("line")
        .attr("class", "link")
        .style("stroke-width", function(d) { return Math.sqrt(d.value); });

    var node = container.append("g")
                    .attr("class", "nodes")
                    .selectAll(".node")
        .data(graph.nodes)
        .enter().append("g")
        .attr("class", "node")
                    .attr("cx", function(d) { return d.x; })
                    .attr("cy", function(d) { return d.y; })
                    .call(drag);

    node.append("circle")
        .attr("r", function(d) { return d.weight * 2+ 12; })
        .style("fill", function(d) { return color(1/d.rating); });

            force.on("tick", function() {
                link.attr("x1", function(d) { return d.source.x; })
                    .attr("y1", function(d) { return d.source.y; })
                    .attr("x2", function(d) { return d.target.x; })
                    .attr("y2", function(d) { return d.target.y; });

                node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
            });

            var linkedByIndex = {};
            graph.links.forEach(function(d) {
                linkedByIndex[d.source.index + "," + d.target.index] = 1;
            });

            function isConnected(a, b) {
                return linkedByIndex[a.index + "," + b.index] || linkedByIndex[b.index + "," + a.index];
            }

    node.on("mouseover", function(d){

                    node.classed("node-active", function(o) {
                        thisOpacity = isConnected(d, o) ? true : false;
                        this.setAttribute('fill-opacity', thisOpacity);
                        return thisOpacity;
                    });

                    link.classed("link-active", function(o) {
                        return o.source === d || o.target === d ? true : false;
                    });

                    d3.select(this).classed("node-active", true);
                    d3.select(this).select("circle").transition()
                            .duration(750)
                            .attr("r", (d.weight * 2+ 12)*1.5);
            })

    .on("mouseout", function(d){

                    node.classed("node-active", false);
                    link.classed("link-active", false);

                    d3.select(this).select("circle").transition()
                            .duration(750)
                            .attr("r", d.weight * 2+ 12);
            });

    function dottype(d) {
      d.x = +d.x;
      d.y = +d.y;
      return d;
    }

    function zoomed() {
      container.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
    }

    function dragstarted(d) {
      d3.event.sourceEvent.stopPropagation();

      d3.select(this).classed("dragging", true);

//ADDING force.start(); HERE SOLVES THE ISSUE
 force.start();
    }

    function dragged(d) {

      d3.select(this).attr("cx", d.x = d3.event.x).attr("cy", d.y = d3.event.y);

    }

    function dragended(d) {

      d3.select(this).classed("dragging", false);
    }

Thanks for your help

A: Putting force.start(); inside dragstarted function stops freezing.
function dragstarted(d) {
      d3.event.sourceEvent.stopPropagation();
      d3.select(this).classed("dragging", true);
      force.start();
};

Here is fiddle


text:
Q: CMake Could NOT find OpenMP in Clion I am trying to compile an OpenMP prject in Clion on Mac.
I have tried
How to set up basic openMP project in CLion
How to set linker flags for OpenMP in CMake's try_compile function
CMake cannot find OpenMP
But they all don't work for me. Clion just says:
-- Could NOT find OpenMP_C (missing: OpenMP_C_FLAGS OpenMP_C_LIB_NAMES)
-- Could NOT find OpenMP_CXX (missing: OpenMP_CXX_FLAGS OpenMP_CXX_LIB_NAMES)
-- Could NOT find OpenMP (missing: OpenMP_C_FOUND OpenMP_CXX_FOUND)
I also tried compile it using "gcc -o main -fopenmp main.c" in the command line and it works fine.
Here is the code:
#include <stdio.h>
#include <omp.h>
int main() {
printf("Hello, World!\n");
#pragma omp parallel
printf("Hello world from thread %d\n",omp_get_thread_num());
return 0;
}


text:
Q: GDB: How to convert enum value to string in GDB script I have the following enum in my code:
enum myenum {
  ready,
  waiting,
  stopping,
};

then I have a struct like so:
typedef struct {
  int a;
  int b;
  uint8 step;  // this is set using myenum.
} mystruct;

During GDB debugging session I am trying to declare an array of strings and then use its index to convert to string but running into couple of issues:

*

*It requires me to keep the array elements to be of the same size:

(gdb) set $step_str={"ready", "waiting", "stopping"}
array elements must all be the same size

*If I fix #1 by adding spaces and make all strings of same size then printf doesn't work with it:

(gdb) set $step_str={"ready   ", "waiting ", "stopping"}
(gdb) printf "step=%s", $step_str[0]
Attempt to take address of value not located in memory.

*The only way I could make it work is by using output command but the problem with output also is that if I end up adding a lot of spaces to a particular string then it is printed like this:

(gdb) set $step_str={"ready                     ", "this_is_a_long_enum_symbol"}
(gdb) output $step_str[0]
"ready", ' ' <repeats 21 times>

Having "' ' <repeats 21 times>" doesn't look nice and a bit confusing to the new readers of my output. I am trying to do this with a lot of enums and trying to gather debug info using GDB scripts on a core dump.
Another solution I thought of was to declare a helper command and make it set a variable but that becomes really long if I have several enums. For example:
define enum2str
  if $arg0 == 0
    set $retval="ready"
  end
  if $arg0 == 1
    set $retval="this_is_a_long_enum_symbol"
  end
  ... and so on but this will grow crazy if I have 20 enum values ...

Is there a better way to convert enum value to string? So I don't have to add those spaces to make array of same size elements and don't get that  in my output?
Thanks much in advance!

A: I believe the $_as_string convenience function is what you're after.
$_as_string(value)

    Return the string representation of value.

    This function is useful to obtain the textual label (enumerator) of an
    enumeration value. For example, assuming the variable node is of an
    enumerated type:

    (gdb) printf "Visiting node of type %s\n", $_as_string(node)
    Visiting node of type NODE_INTEGER


text:
Q: Payments and open source core developers I'm not sure if there's an established protocol for this (even if it's not an official one), but thought those most experienced with open source might want to share with us.
I'm aware that random patches submitted to open source projects are never paid. They may be indirectly funded by a client but they're never paid for by the open source project itself.
But how about core developers? I heard for example that drupal has some 800 core developers behind it. Core developers means that they work on drupal core itself and together they push the main releases, so they're very important to the project. Of course drupal is just an example, but in general, is there any established protocol in the open source world that defines whether the company behind the project is expected to pay them and do these core developers expect such payment?
Any facts or first hand experiences?

A: As a particular example, a few of the core Squeak developers work for Teleplace. They hack on Squeak as part of their day job, so Teleplace gets the stuff they need, and then release the changes to the base Squeak image and virtual machine back to the larger Squeak community.
There are quite a few other companies that pay their employees, in part at least, to hack on Squeak.

A: I covered this topic in detail in a blog post about donations to open-source projects.
The gist of it is this - once an open-source project reaches a certain size, one of several things can happen to allow it to continue existing (otherwise support and scope issues bring it down). There are 3 main ways to support an OS project at that stage:

*

*A big company (Google, Microsoft, etc) "sponsors" the project and has paid developers from its staff working on it full-time. Some projects come out directly from those companies and naturally have this option baked in.

*The project can transform into a real business, in the MySQL / Redhat mold. This means commercial licenses, paid support and customization / integration services. Otherwise some kind of bizdev opportunity that brings in a stream income (such as what Mozilla has with google by placing their search engine as the default one in Firefox).

*A community of maintainers forms around the project with the original maintainer ceding control to allow others to contribute.

1 is unlikely and not something you can plan for while 2 is very difficult for most developers and most projects fail at that point. This a problem very dear to my heart, which is why I started Binpress (the company whose blog I linked to at the beginning), to provide a platform for developers to build those sustainable businesses on top of their open-source projects. From our experience this is a very viable model, and we've seen a lot of success recently in that space.


text:
Q: Mass creation of invoice in magento 1.9 I am trying to add a mass action of creating the invoice, in my Magento store, which has been built with Magento - 1.9. The code files are as below.
But when I select the orders and click on the 'Invoice - Capture Online' option. It is getting redirected to the website instead of the admin end. And it is not creating the invoices either. Can anyone kindly let me know why this is happening?
app/etc/modules/MiscWS_MassActions.xml
<?xml version="1.0"?>
<config>
    <modules>
        <MiscWS_MassActions>
            <active>true</active>
            <codePool>local</codePool>
        </MiscWS_MassActions>
    </modules>
</config>

app/code/local/MiscWS/MassActions/etc/config.xml
<config>
    <modules>
        <MiscWS_MassActions>
            <version>0.1.0</version>
        </MiscWS_MassActions>
    </modules>
    <admin>
          <routers>
             <MiscWS_MassActions>
                <use>admin</use>
                <args>
                   <module>MiscWS_MassActions</module>
                   <frontName>miscwsmassactions</frontName>
                </args>
             </MiscWS_MassActions>
          </routers>
    </admin>
    <adminhtml>
        <events>
            <core_block_abstract_prepare_layout_before>
                <observers>
                    <MiscWS_MassActions_Model_Observer>
                        <type>singleton</type>
                        <class>MiscWS_MassActions_Model_Observer</class>
                        <method>addMassAction</method>
                    </MiscWS_MassActions_Model_Observer>
                </observers>
            </core_block_abstract_prepare_layout_before>
        </events>
    </adminhtml>
</config>

app/code/local/MiscWS/MassActions/Model/Observer.php
<?php
class MiscWS_MassActions_Model_Observer
{
    public function addMassAction($observer)
    {
        $block = $observer->getEvent()->getBlock();
        if(get_class($block) =='Mage_Adminhtml_Block_Widget_Grid_Massaction'
            && $block->getRequest()->getControllerName() == 'sales_order')
        {
            $block->addItem('miscwsmassactions', array(
                'label' => 'Invoice - Capture Online',
                'url' => Mage::app()->getStore()->getUrl('miscwsmassactions/adminhtml_massActions/massInvoiceCaptureOnline')
            ));
        }
    }
}

app/code/local/MiscWS/MassActions/Controllers/Adminhtml/MassActionsController.php
<?php

class MiscWS_MassActions_Adminhtml_MassActionsController extends Mage_Adminhtml_Controller_Action
{
  public function massInvoiceCaptureOnlineAction()
    {
        $orderIds = $this->getRequest()->getPost('order_ids', array());
        $countInvoicedOrder = 0;
        $countNonInvoicedOrder = 0;

        foreach ($orderIds as $orderId) {
            $order = Mage::getModel('sales/order')->load($orderId);
            if ($order->canInvoice()) {
                $invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice();
                if( $invoice->getTotalQty() ) {
                    $invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_ONLINE);
                    $invoice->register();
                    $transactionSave = Mage::getModel('core/resource_transaction')
                        ->addObject($invoice)
                        ->addObject($invoice->getOrder());
                    $transactionSave->save();
                    $countInvoicedOrder++;
                } else {
                    $countNonInvoicedOrder++;
                }

            } else {
                $countNonInvoicedOrder++;
            }
        }
        if ($countNonInvoicedOrder) {
            if ($countInvoicedOrder) {
                $this->_getSession()->addError($this->__('%s order(s) were not invoiced.', $countNonInvoicedOrder));
            } else {
                $this->_getSession()->addError($this->__('No order(s) were invoiced.'));
            }
        }
        if ($countInvoicedOrder) {
            $this->_getSession()->addSuccess($this->__('%s order(s) have been invoiced.', $countInvoicedOrder));
        }
        $this->_redirect('adminhtml/sales_order/');
    }
}

Reference: http://misc.ws/2014/12/27/adding-mass-actions-to-magento-orders/

A: The issue is with your controller file path. According to my knowledge you have put the MassActionsController.php under

/app/code/local/MiscWS/MassActions/controllers/

You need to put the file under below location:

/app/code/local/MiscWS/MassActions/controllers/Adminhtml/

Also for best practice dont use the below line in your observer:
'url' => Mage::app()->getStore()->getUrl('miscwsmassactions/adminhtml_massActions/massInvoiceCaptureOnline')

Replace it with the below code:
'url' => Mage::helper('adminhtml')->getUrl('miscwsmassactions/adminhtml_massActions/massInvoiceCaptureOnline', array('_secure' => true))


text:
Q: How can I properly fetch data using MagicalRecord for Swift 4? I am trying to fetch data from my User class:
@objc(User)
class User: NSManagedObject {

// Attributes
   @NSManaged var cAge: Int16
   @NSManaged var rAge: Int16
   @NSManaged var cIncome: Int64
   @NSManaged var rIncome: Int64
   @NSManaged var state: String
   @NSManaged var returnRate: Float

}

Here is my fetch call:
let user = User.mr_findAll()! as! [User]
print(user)

Here is the output from print(user):
[<User: 0x2812da300> (entity: User; id: 0x2831da740 <x-coredata:///User/t34A918DC-3B79-4ECC-91EF-16F658B20B8A2> ;
data: {
    cAge = 23;
    cIncome = 125086;
    rAge = 50;
    rIncome = 365048;
    returnRate = "0.78";
    state = In;
})]

How can I just retrieve the data, and not all the other information?

A: I needed to loop through the results to extract the attributes from the User class.
let users = User.mr_findAll()! as! [User]
for user in users{
     print(user.cAge)
}


text:
Q: How to remove a user from a channel via sync function How is a user removed from a channel when the user was granted access via sync function?
As I understand it adding a document to a channel operates on the document revision. It is therefore easy to remove a document from a channel (or remove a channel from a document? I suppose there is a single right way of phrasing this) as each update of a document sets the document's channel to nil and the sync function can decide further what to do.
Would granting a user access to a channel via access() do the same? I read the following here, which suggests it does:

When a document is updated and either the previous or the current
  revision grants channel access, all of the users and roles named in
  both revisions' access lists have their all_channels properties
  cleared to nil to invalidate them.

In which case it operates similar to document channel assignment.

A: So here is the answer from the documentation:
Sync Function API

The sync function is called every time a new revision/update is made
  to a document, and the changes to channels and access made by the
  sync function are tied to that revision. If the document is later
  updated, the sync function will be called again on the new revision,
  and the new channel assignments and user/channel access replace the
  ones from the first call.

Emphasis mine.


text:
Q: When to use MainWindow and when to use MainWindowController in MonoMac I have just started developing on MonoMac and MonoDevelop 3.0, and I'm really confused on where I am supposed to be routing up my IBOutlets and actions.  In all of the samples, MainWindowController is used to wire everything up. However, I just could not get anything to work except using MainWindow instead.
Also, I'm a little thrown off because in several of the samples MainWindowController shows up as a sub-folder to the nib.  But when I new up a solution, it shows up as its own file.
Any help appreciated
Edit: I uploaded the project to GitHub: https://github.com/ucsbmrf/MonoMacTest

A: Most of the issue probably stems from the fact that most tutorials you find on the web still reference older versions of MonoDevelop, XCode and IB. The new workflow for setting up a test project can be found in this post which takes into account the changes which incorporated Interface Builder into XCode in v4.2+.


text:
Q: Calling a abstract method from a static method I have defined an abstract class like so:
class Fruits(ABC):
   @abstractmethod
   def eat(self):
       dosomething
   @staticmethod
   def helper(apple: Fruits):
       apple.eat()
       dosomethingelse

However I am getting undefined name "Fruits" for the static method helper. I wonder what I am doing incorrectly here.


text:
Q: If it carries out, how can an iPhone terminal be locked using MDM? I am using "APNs" of Apple, and "MDM".
The list of applications is also acquirable from the iOS terminal using "MDM".
But, only the lock of a device cannot be performed.
An error message is not displayed.
The payload of a success.   PUT is carried out to the server.
However, an iPhone terminal can be used ordinarily, without being locked.
"DeviceLock" of MDM Protocol Reference is being used for the payload.
If it carries out, how can an iPhone terminal be locked using MDM?
Please let me know.
Please help me.

A: Check device logs when you are sending "DeviceLock" command.
When you are sending "DeviceLock" command from MDM server then what is the change in iPhone screen?
For me iPhone screen is locked when "DeviceLock" command is sent and I can again swipe the finger to unlock the device.


text:
Q: unable to add value to html textbox of type password hi all am trying to load values from cookies to the text box.My HTMLis as below
<fieldset class="boxBody">

    Username
    <input type="text" name="Username" id="txtUsername" runat="server" tabindex="1" placeholder="Username"  />
    Password
    <input type="password" name="password" id="txtpassword" runat="server" placeholder="Password"  tabindex="2" />
</fieldset>

and my code in pageload is
txtUsername.Value = Request.Cookies["SN"]["UserName"];
txtpassword.Value = Request.Cookies["SN"]["Password"];

what happens is instead of password only the placeholder is visible.when i change the type to text it works.Any way to add text when the page is loaded

A: Set the attribute, as a workaround:
txtPassword.Attributes.Add("value", Request.Cookies["SN"]["Password"])

Disclaimer: Pre-filling passwords may not be a good idea.

A: Do you really need to hide the password cause if its not you can change the text of txtPassword to asterisks

textmode="Password"


text:
Q: is there a way adding webex meeting to use google calendar api? I'm beginner looking for way to make schedule adding webex meeting..
i found google calendar API, but it seems only support hangout / meets..
is anybody know the way to add webex meeting in conference type?

A: If you have checked the GSuite Updates blog, the third-party conferencing is available in Google Calendar.

We're launching with five partners whose add-ons are available in the
  G Suite
  Marketplace,
  with more to come in the future:

*

*Cisco (Webex integration)

*Dialpad (UberConference integration)

*LogMeIn (GoToMeeting integration)

*RingCentral (RingCentral integration)

*Vonage (Vonage integration)

But if you read the current release notes in the Google Calendar API documentation, it was not yet stated that these partners are live. So I think we have to wait for the update in the documentation.


text:
Q: Detect Quicktime plugin withOUT using Javascript Is it possible to detect the existence of the Browser's Quicktime plugin withOUT using Javascript?
I know how to test for Quicktime using Javascript, but not without.
My logic says that Javascript can be enabled/disabled by the user and the existence of the Quicktime plugin is determined by the programmers for each Browser.  Therefore, each should an independent statistic ... even for Apple's iOS which has Quicktime built in.
Thanks,

A: I am really throwing away my question. However, I thought some of you might be curious why ...
I honestly do not know if it is possible to detect the existence of the Browser's Quicktime plugin withOUT using Javascript. I do know, for example, that Quicktime is built into Apple's current OS and probably many prior ones.
Nevertheless, I have come across the expression "Progressive Enhancement". As a direct result, I have discovered the works of others that result in my being okay with detection of Quicktime using Javascript.
The following illustrates what I mean:
The way-back-when driving force was to avoid document.write in the display of media players for .mp3, .m4a and the like.
The new approach places the media player, the no-js message, and the no-qt message in the html markup.
The default case is to show just the no-js message in the html markup. Using the "Progressive Enhancement" paradigm, if Javascript is enabled, then Javascript is used to first hide the no-js message. Depending on the presence of Quicktime, we then show the media player and hide the no-qt message, or vice versa. As a result, we progress from a "vanilla" text message about no Javascript to showing a media player if Quicktime is present.
For example, my html markup presents:

<audio name="aMedia" class="aMedia" controls preload="auto"
       src="audio/My Love Song Forever.mp3">

Turn on Javascript to hear an awesome Love Song

Install Quicktime

 to hear an awesome Love Song

In my  is this


text:
Q: What is strictness? In Haskell, I try to understand the notion of strictness. I understand that
const x y = x

is strict on the first argument but not on the second.
But is
 ifFun pred cons alt = if pred then cons else alt

strict? It is strict on the first argument. I understand that the fact that cons and alt are evaluated depending on the value of pred. Does that mean the function is not strict on those arguments?

A: "Strict" is one of those words that has a precise technical meaning that has been coopted by the community to mean something a bit less formal. Here's the technical definition.
Function f is strict if f ⊥ = ⊥.
Here ⊥ is the standard symbol for an undefined computation; generally in denotational semantics there is just one and all undefined computations are indistinguishable from each other, but in Haskell as a concession to practicality we have many different kinds that can be distinguished: exceptions, infinite loops, pattern match failures, and so on. For the purposes of this answer, we'll consider them all equal.
Let's ask if const is strict. We have
const = \x -> \y -> x

hence
const ⊥ = \y -> ⊥ ≠ ⊥

and therefore const is not strict. But, oh, we've lost some very important communication power here! There is a good sense in which, when applied to undefined behavior, const doesn't behave well. So many people will say "strict in the nth argument" and we'll pretty much understand what they mean. It isn't obvious how to define what they mean formally, but a half-decent first stab at it goes something like this:
If function f has m arguments, then it is strict in the nth argument for some n ≤ m when ∀ a1, ..., am. f a1 a2 ... a(n-1) ⊥ a(n+1) ... am = ⊥.
(Aside: why isn't this quite right? For many functions -- including const -- we can't statically know how many arguments it has. Although const looks like it might be a two-argument function, const id () () is perfectly well typed and applies const to three arguments.)
Now we can say something like "const is strict on its first argument" and have it mean what we want it to mean (provided, as above, that const actually is a two-argument function), because ∀y. const ⊥ y = ⊥ does indeed hold.
We now also have the tools to address your question about ifFun, namely: is ifFun strict on its second argument? That is, can we cook up pred and alt such that
ifFun pred ⊥ alt ≠ ⊥ -- ?

I think it's clear we can do so, since:
ifFun False ⊥ () = if False then ⊥ else () = () ≠ ⊥

A similar argument shows that ifFun is "not strict on its third argument" in the popular understanding of this phrase (again modulo the provisos discussed above), but is "strict on its first argument".


text:
Q: singly Linked List use setter & getter I was trying to run a singly linked list, but no output is given and without error. I don't know where is the problem. in the class node or the test class   Here is the implementation... Below is the node class...
public class ListNode {

private int data;
private ListNode next;

public ListNode(int data)
{
    this.data=data;

}

public int getData() {
    return data;
}

public void setData(int data) {
    this.data = data;
}

public ListNode getNext() {
    return next;
}

public void setNext(ListNode next) {
    this.next = next;
}
}

and here my code in list methods
public class Linkedklist {
ListNode head;
private int length ;

public Linkedklist()
{
length=0;
}
public synchronized ListNode getHead()
{
    return head;
}
public synchronized void insertAtBegin(ListNode node)
{
    node.setNext(head);
    head=node;
    length++;
}

public int ListLength(ListNode headNode)
{
    ListNode currentNode = headNode;
    while(currentNode != null)
    {
        length++;
        currentNode = currentNode.getNext();
    }
    return length;
}

finally the test class:
    Linkedklist t=new Linkedklist();
    Scanner s=new Scanner(System.in);
                  t.insertAtBegin(2);
                  t.insertAtBegin(3);
                  t.insertAtBegin(10);
                 System.out.println("the head of the list: ");
                 t.getHead();

                 System.out.println("Enter the Element: ");
                  int e1=s.nextInt();
                  t.insertAtEnd(e1);
                  t.getHead();
                 System.out.println("=====length of the list : =====");

                 t.length();

I'm looking at many programs to find the problem but I didn't get any results.
but I think the problem is in pass data to the method (ListNode node)
the proble is I don't know how to work with ListNode instance, I used to write code for the class Node Like this then pass data.
public Node(String a,double b)
{
    ename=a;
    salary=b;
    next=null;
}

public Node(String a,double b,Node n)
{
    ename=a;
    salary=b;
    next=n;
}

but I face difficulty with getter and setter and node instance.
thank you StackOverflow members.
error with printlist() output appears like this: WITH  -2147483648 not include in list element
 -2147483648
 60
 50
 40
 30
 20
 10
 -2147483648

A: Here's the solution
Hope this helps
ListNode.java
public class ListNode {
  private int data;
  private ListNode next;

  public ListNode(int data) {
    this.data = data;
    next = null;
  }

  public int getData() { return data; }

  public void setData(int data) { this.data = data; }

  public ListNode getNext() {
      return next;
  }

  public void setNext(ListNode next) {
      this.next = next;
  }
}

Linkedklist.java
public class Linkedklist {
  ListNode head;
  private int length;

  public Linkedklist() {
    head = null;
    length = 0;
  }
  public synchronized ListNode getHead() { return head; }
  public synchronized void insertAtBegin(ListNode node) {
    node.setNext(head);
    head = node;
    length++;
  }

  public int getLength() { return length; }
  public void insertAtEnd(ListNode node) {
    ListNode curr, prev;
    curr = head;
    prev = null;
    while (curr != null) {
      prev = curr;
      curr = curr.getNext();
    }
    if (prev == null) {
      head = node;
      head.setNext(null);
    } else {
      prev.setNext(node);
      node.setNext(null);
    }
    length++;
  }
  public int computeLength() {
    ListNode currNode = head;
    int len = 0;
    while (currNode != null) {
      len++;
      currNode = currNode.getNext();
    }
    return len;
  }
  public void printList() {
    ListNode curr = head;
    while (curr != null) {
      System.out.println(curr.getData());
      curr = curr.getNext();
    }
  }
}

Main.java

import java.util.Scanner;
public class Main {
  public static void main(String[] args) {
    Linkedklist t = new Linkedklist();
    Scanner s = new Scanner(System.in);
    t.insertAtBegin(new ListNode(2));
    t.insertAtBegin(new ListNode(3));
    t.insertAtBegin(new ListNode(10));
    t.insertAtEnd(new ListNode(4));
    System.out.print("Enter a number: ");
    int num = s.nextInt();
    t.insertAtEnd(new ListNode(num));
    System.out.println("List Entries: ");
    t.printList();
    System.out.println("Length of the list = " + t.getLength());
    System.out.println("Computed length of the list = " + t.computeLength());
  }
}


text:
Q: Prevent table updating I have more tables replicated using transactional replication with push subscription.
How can I prevent users/stored procedures updating those tables?

A: Create a user without rights to run that SP or write in that tables and use it as the user for  your needs (run app, etc).


text:
Q: Obtain nickname of telegram user Is it possible to obtain the telegram user nickname using the Telegram client API if I don't have the contact in my rubric?

A: Yes, you can get the User object. In the Message Bot API documentation, there is a from field, which returns a User object. In the User object, you will find all the user information that has sent the message to your bot.


text:
Q: How to specify the Z direction(depth) for a cube I would like to know how can I specify the z-direction for my cube. It needs to be translated to -5 along z-direction.
The whole problem statement is like this: Implement the transformation pipeline, by defining a cube in 3d space, setting up a camera in the origin of the coordinate system and a projection matrix that has a 90° FOV. The cube size should be 2 unites (2x2x2), laid down 5 unites along the negative z axis
    package transformations;
import java.util.*;

import java.awt.Frame;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;

public class Transformations {

        //declare list of polygons
        static ArrayList<Integer>p_left=new ArrayList<Integer>();
        static ArrayList<Integer>p_right=new ArrayList<Integer>();
        static ArrayList<Integer>p_down=new ArrayList<Integer>();
        static ArrayList<Integer>p_top=new ArrayList<Integer>();
        static ArrayList<Integer>p_near=new ArrayList<Integer>();
        static ArrayList<Integer>p_far=new ArrayList<Integer>();

        static int count=0;
        public static BufferedImage gradientSetRaster(BufferedImage img) {
            int width = img.getWidth();
            int height = img.getHeight();

            WritableRaster raster = img.getRaster();
            int[] pixel = new int[3]; //RGB

                for (int y = 0; y < height; y++) {
                    int val = (int) (y * 255f / height);
                    for (int shift = 1; shift < 3; shift++) {
                        pixel[shift] = val;
                    }

                    for (int x = 0; x < width; x++) {
                        raster.setPixel(x, y, pixel);
                    }
                }

            return img;
        }

        public static BufferedImage drawLine(BufferedImage img, int x0, int y0, int xn, int yn)
        {
            WritableRaster raster=img.getRaster();

            int[] pixel = new int[3]; //RGB
            for(int k=0; k<3; k++)
            {
                pixel[k]=255;
            }

            int dx=Math.abs(xn-x0);
            int dy=Math.abs(yn-y0);
            int m=dy/dx;
            int twoDy=2*dy;
            int twoDyMintwoDx=twoDy-2*dx;

            if(dx>dy)   //slope is positive and is less than or equal to 1
            {
                int p=twoDy-dx;

                for(int k=0; k<dx-1; k++)
                {
                    if(p<0)
                    {
                        x0=x0+1;
                        raster.setPixel(x0, y0, pixel);
                        p=p+twoDy;
                    }
                    else
                    {
                        x0=x0+1;
                        y0=y0+1;
                        raster.setPixel(x0, y0, pixel);
                        p=p+twoDy-2*dx;
                    }

                }
            }

            if(dy>dx)
            {
                int p=2*dx-dy;
                int temp1=x0;
                x0=y0;
                y0=temp1;

                int temp2=xn;
                xn=yn;
                yn=temp2;

                for(int k=0; k<dx-1; k++)
                {
                    x0=x0+1;
                    y0=y0+1;
                    raster.setPixel(x0, y0, pixel);
                }
            }

            if(dy==dx)
            {
                x0=x0+1;
                y0=y0+1;

                raster.setPixel(x0, y0, pixel);
            }

            return img;
        }

        public static BufferedImage drawUpPolygon(Graphics g, BufferedImage img, ArrayList<Integer>p_top)
        {
            g.drawLine(p_top.get(0), p_top.get(1), p_top.get(2), p_top.get(3));
            g.drawLine(p_top.get(0), p_top.get(1), p_top.get(4), p_top.get(5));
            g.drawLine(p_top.get(4), p_top.get(5), p_top.get(6), p_top.get(7));
            g.drawLine(p_top.get(6), p_top.get(7), p_top.get(2), p_top.get(3));

            return img;
        }

        public static BufferedImage drawDownPolygon(Graphics g, BufferedImage img, ArrayList<Integer>p_top)
        {
            g.drawLine(p_down.get(0), p_down.get(1), p_down.get(2), p_down.get(3));
            g.drawLine(p_down.get(0), p_down.get(1), p_down.get(4), p_down.get(5));
            g.drawLine(p_down.get(4), p_down.get(5), p_down.get(6), p_down.get(7));
            g.drawLine(p_down.get(6), p_down.get(7), p_down.get(2), p_down.get(3));

            return img;
        }

        public static BufferedImage drawBetween(Graphics g, BufferedImage img, ArrayList<Integer>p_top, ArrayList<Integer>p_down)
        {
            g.drawLine(p_top.get(0), p_top.get(1), p_down.get(0), p_down.get(1));
            g.drawLine(p_top.get(2), p_top.get(3), p_down.get(2), p_down.get(3));
            g.drawLine(p_top.get(4), p_top.get(5), p_down.get(4), p_down.get(5));
            g.drawLine(p_top.get(6), p_top.get(7), p_down.get(6), p_down.get(7));

            return img;
        }

        public static void main(String... args) {
            Frame w = new Frame("Raster");  //window
            final int imageWidth = 500;
            final int imageHeight = 500;

            w.setSize(imageWidth,imageHeight);
            w.setLocation(100,100);
            w.setVisible(true);

            Graphics g = w.getGraphics();

            BufferedImage img = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);
            gradientSetRaster(img);
            g.drawImage(img, 0, 0, (img1, infoflags, x, y, width, height) -> false);  //draw the image. You can think of this as the display method.

            w.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    //order will be(vertex->index)
                    //lowerLeft->0,1
                    //upperLeft->2,3
                    //lowerRight->4,5
                    //upperRight->6,7
                    count++;

                    int t_lowLeftX=e.getX();
                    int t_lowLeftY=e.getY();
                    //top polygon
                    int t_lowRightX;
                    int t_lowRightY;

                    int t_uppLeftX;
                    int t_uppLeftY;

                    int t_uppRightX;
                    int t_uppRightY;

                    //bottom polygon
                    int d_lowLeftX;
                    int d_lowLeftY;

                    int d_lowRightX;
                    int d_lowRightY;

                    int d_uppLeftX;
                    int d_uppLeftY;

                    int d_uppRightX;
                    int d_uppRightY;

                    if(count==1) {
                        //lowerLeft indexes
                        t_lowLeftX=e.getX();
                        t_lowLeftY=e.getY();

                        t_lowRightX=t_lowLeftX+100;
                        t_lowRightY=t_lowLeftY;

                        t_uppLeftX=t_lowLeftX+50;
                        t_uppLeftY=t_lowLeftY+50;

                        t_uppRightX=t_uppLeftX+100;
                        t_uppRightY=t_uppLeftY;

                        d_lowLeftX=t_lowLeftX;
                        d_lowLeftY=t_lowLeftY-70;

                        d_lowRightX=t_lowRightX;
                        d_lowRightY=t_lowRightY-70;

                        d_uppLeftX=t_uppLeftX;
                        d_uppLeftY=t_uppLeftY-70;

                        d_uppRightX=t_uppRightX;
                        d_uppRightY=t_uppRightY-70;

                        //connect(lowLeft->uppLeft, lowLeft->lowRight, uppLeft->uppRight,
                        //uppRight->lowRight ...)
                        p_top.add(t_lowLeftX);
                        p_top.add(t_lowLeftY);
                        p_top.add(t_lowRightX);
                        p_top.add(t_lowRightY);
                        p_top.add(t_uppLeftX);
                        p_top.add(t_uppLeftY);
                        p_top.add(t_uppRightX);
                        p_top.add(t_uppRightY);

                        p_down.add(d_lowLeftX);
                        p_down.add(d_lowLeftY);
                        p_down.add(d_lowRightX);
                        p_down.add(d_lowRightY);
                        p_down.add(d_uppLeftX);
                        p_down.add(d_uppLeftY);
                        p_down.add(d_uppRightX);
                        p_down.add(d_uppRightY);

//                      g.drawLine(lowLeftX, lowLeftY, uppLeftX, uppLeftY);
//                      g.drawLine(lowLeftX, lowLeftY, lowRightX, lowRightY);
//                      g.drawLine(uppLeftX, uppLeftY, uppRightX, uppRightY);
//                      g.drawLine(uppRightX, uppRightY, lowRightX, lowRightY);

                        drawUpPolygon(g, img, p_top);
                        drawDownPolygon(g, img, p_down);
                        drawBetween(g, img, p_top, p_down);

                        int[] pixel = {255,255,255};
                        img.getRaster().setPixel(t_lowLeftX,t_lowLeftY,pixel);
                        img.getRaster().setPixel(t_uppLeftX, t_uppLeftY,pixel);
                        img.getRaster().setPixel(t_lowLeftX, t_lowLeftY, pixel);
                        img.getRaster().setPixel(t_lowRightX, t_lowRightY, pixel);
                        img.getRaster().setPixel(t_uppRightX, t_uppRightY, pixel);

                        img.getRaster().setPixel(d_lowLeftX,d_lowLeftY,pixel);
                        img.getRaster().setPixel(d_uppLeftX, d_uppLeftY,pixel);
                        img.getRaster().setPixel(d_lowLeftX, d_lowLeftY, pixel);
                        img.getRaster().setPixel(d_lowRightX, d_lowRightY, pixel);
                        img.getRaster().setPixel(d_uppRightX, d_uppRightY, pixel);

                    };

                    //top polygon's lower left vertex

                }
            });

            w.addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent e) {
                    w.dispose();
                    g.dispose();
                    System.exit(0);
                }
            });
        }
    }


text:
Q: Searching By ID - ASP.NET MVC i have page where user can search also by ID and for that i tried to Convert int to string ,but when i run page i get this error.Can anyone help me or point me in the right direction!
Thanks in advance :)

LINQ to Entities does not recognize the method 'Int32 ToInt32(System.String)' method, and this method cannot be translated into a store expression.

Controller:
 public ActionResult Lukkedesager(string searchingLukkedesager, int? pageNumber)

   {
        IPagedList<RMAHistory> query = db.RMAStatus
       .Join(db.RMA_History, u => u.ID, y => y.StatusID, (u, y) => new { u, y })
       .Where(x => x.y.Kundenavn.Contains(searchingLukkedesager) || Convert.ToString(x.y.Id).Contains(searchingLukkedesager))
       .Select(t => new RMAHistory
            {
               Kundenavn = t.y.Kundenavn,
               Id = t.y.Id

            }).ToPagedList(pageNumber ?? 1, 10);

            return View(query);

   }

View:
using (Html.BeginForm("Lukkedesager", "User", FormMethod.Get))
   {

 @Html.TextBox("searchingLukkedesager", null, new { @placeholder = "VareNR, FakturaNR, Firmanavn", @class = "form-control", @id = "tx1" })

<button class="srhbtn" id="sh1" type="submit">SØG</button>

      }

A: Instead of Convert.ToString() use x.y.id.ToString().Contains...
  IPagedList<RMAHistory> query = db.RMAStatus
   .Join(db.RMA_History, u => u.ID, y => y.StatusID, (u, y) => new { u, y })
   .Where(x => x.y.Kundenavn.Contains(searchingLukkedesager) || x.y.Id.ToString().Contains(searchingLukkedesager))
   .Select(t => new RMAHistory
        {
           Kundenavn = t.y.Kundenavn,
           Id = t.y.Id

        }).ToPagedList(pageNumber ?? 1, 10);

        return View(query);


text:
Q: Keep logo position fixed on responsive navbar I am having problems styling a responsive navbar.
The expected behaviour is that all nav links are displayed on larger screens but are collapsed into a hidden mobile menu on smaller screen sizes.
In the following snippet on smaller screens, when the logo is clicked, the logo moves down to the middle of the dropdown.
How do I keep it(the logo) fixed to the top of the navbar and properly align the menu items?

document.querySelector('.topbar-brand').addEventListener('click', () => document.querySelector('.topbar-nav').classList.toggle('responsive'));
document.addEventListener('scroll', () => document.querySelector('.topbar-nav').classList.remove('responsive'));
.topbar {
  background-color: rgb(40, 58, 156);
  display: flex;
  flex-flow: row nowrap;
  top: 0;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding-left: 1rem;
  padding-right: 1rem;
  z-index: 1;
}

.topbar-brand {
  display: block;
  margin-right: 1rem;
  font-size: 1.25rem;
  font-family: cursive, Arial, Helvetica, sans-serif;
}

.topbar-brand img {
  object-fit: contain;
  height: 5rem;
  width: 5rem;
}

.topbar-brand:hover,
.topbar-brand:focus {
  text-decoration: none;
}

.topbar-nav {
  display: flex;
  flex-direction: row;
  justify-self: center;
  justify-content: space-between;
  list-style: none;
  margin: 0;
  padding: 0;
}

.sticky {
  position: fixed;
}

.nav-link {
  font-family: Roboto, Arial, Helvetica, sans-serif;
  font-style: italic;
  font-weight: 900;
  display: block;
  padding: 1.5rem;
  text-decoration: none;
  color: whitesmoke;
}

.nav-link:focus {
  background-color: rgba(41, 71, 240, 0.993);
  border-radius: 1rem;
}

@media screen and (max-width: 600px) {
  .topbar-nav li {
    display: none;
  }
  .topbar {
    align-content: space-around;
    justify-content: start;
  }
}

@media screen and (max-width: 600px) {
  .topbar-brand {
    margin-right: 5 rem;
    margin-top: 0;
  }
  .topbar-nav.responsive {
    display: flex;
    flex-direction: column;
    text-align: left;
    margin-top: 2rem;
  }
  .topbar-nav.responsive li {
    display: initial;
  }
  .topbar-nav.responsive li {
    border-bottom: 0.1rem solid black;
  }
}

      Home

      Top Picks

      Login

A: Simply add margin-bottom: auto; to .topbar-brand. Since it's a flex element this will force its alignment to the top.
Here is a good article with some more info regarding flexbox and auto margins: CSS-tricks: The peculiar magic of flexbox and auto margins

document.querySelector('.topbar-brand').addEventListener('click', () => document.querySelector('.topbar-nav').classList.toggle('responsive'));
document.addEventListener('scroll', () => document.querySelector('.topbar-nav').classList.remove('responsive'));
.topbar {
  background-color: rgb(40, 58, 156);
  display: flex;
  flex-flow: row nowrap;
  top: 0;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding-left: 1rem;
  padding-right: 1rem;
  z-index: 1;
}

.topbar-brand {
  display: block;
  margin-right: 1rem;
  font-size: 1.25rem;
  font-family: cursive, Arial, Helvetica, sans-serif;
}

.topbar-brand img {
  object-fit: contain;
  height: 5rem;
  width: 5rem;
}

.topbar-brand:hover,
.topbar-brand:focus {
  text-decoration: none;
}

.topbar-nav {
  display: flex;
  flex-direction: row;
  justify-self: center;
  justify-content: space-between;
  list-style: none;
  margin: 0;
  padding: 0;
}

.sticky {
  position: fixed;
}

.nav-link {
  font-family: Roboto, Arial, Helvetica, sans-serif;
  font-style: italic;
  font-weight: 900;
  display: block;
  padding: 1.5rem;
  text-decoration: none;
  color: whitesmoke;
}

.nav-link:focus {
  background-color: rgba(41, 71, 240, 0.993);
  border-radius: 1rem;
}

@media screen and (max-width: 600px) {
  .topbar-nav li {
    display: none;
  }
  .topbar {
    align-content: space-around;
    justify-content: start;
  }
}

@media screen and (max-width: 600px) {
  .topbar-brand {
    margin-right: 5 rem;
    margin-top: 0;
    margin-bottom: auto;
  }
  .topbar-nav.responsive {
    display: flex;
    flex-direction: column;
    text-align: left;
    margin-top: 2rem;
  }
  .topbar-nav.responsive li {
    display: initial;
  }
  .topbar-nav.responsive li {
    border-bottom: 0.1rem solid black;
  }
}

      Home

      Top Picks

      Login


text:
Q: "import serial" fails with Python 3.3.2, pyserial 2.5 I am having a problem with "import "serial".
I am running Python 3.3.2 on Windows (XP) and have installed pyserial 2.5 from the Windows installer pyserial-2.5.win32.exe. The traceback below shows what happens.
C:\hal\Python>python
Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 bit (Intel)]  on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import serial
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "c:\python33\lib\site-packages\serial\__init__.py", line 19, in <module>
    from serialwin32 import *
ImportError: No module named 'serialwin32'
>>>

The python interpreter finds and runs c:\python33\lib\site-packages\serial\ __init__.py, which checks the os name, finds that it is "nt" and executes "from serialwin32 import *". That fails.
The file serialwin32.py is in the \serial directory with __init__.py.
I tried this with Python 3.1.1 and 3.2.3 and got the same results.
I read that pyserial 2.5 is not dependent on pywin32 but I have it installed anyway; win32, build 18, for Python 3.3.
Has anyone seen this problem or know what I may be doing wrong?
Thanks


text:
Q: Dynamic select freeze on adding options in ie8 I have a <select> that I added with JQ ,
its loadded all options from a class (value + data) list return by $.ajax call, and load it to a div.
My code:
varTempDiv+= '<select class="selectFromList" width="200">';
$.each(data.d, function (index) {
    varTempDiv+= '<option value="' + this.value >+ '">' + this.txtName + '</option>';
});
varTempDiv+= '</select>';
$("#loadedDiv").html(varTempDiv);

It work fine at all in chrome ,
but in ie8 its froze to some second append to list length.
The length start with 100 to 1000+ items.
How can i fix that things?
Thanks!!

A: Try using native for loop instead of jQuery.each. It should give you significant performance improvement especially if you have so many items in your array. Take a look at this comparison http://jsperf.com/jquery-each-vs-for-loop/69.

A: What happens if you change
varTempDiv+= '<option value="' + this.value >+ '">' + this.txtName + '</option>';

to
varTempDiv+= '<option value="' + this.value + '">' + this.txtName + '</option>';

Thousand items in a select also seems unusable, maybe you should consider a different design.


text:
Q: VBA IF formula not working? I have some VBA code that is working between a few workbooks
I am running into a problem where I cannot get this IF formula to apply.
I am not sure how I am getting Subscript out of range error.
I have tried to use .Range("O"), .Range("O:O"), .Range("O", i) but all give the same 1004 error.
Am I using .Range() wrong? I was able to use range on a different formula so not sure why this wont work.
Sub if_after()

    Dim co_detail As Workbook
    Set co_detail = ThisWorkbook

        With co_detail.Sheets("Detail")

            For i = 2 To 100
                .Range("O2").Formula = "=IF(L" & i & "=N" & i & ",'good','update')"
            Next i

        End With

End Sub

A: That's a zero not an oh and full quotes are used for text. Quotes must also be doubled up within a quoted string.
.Range("o" & i).Formula = "=IF(L" & i & "=N" & i & ", ""good"", ""update"")"

A: You could simplify this entire code to the following - no need to loop at all, you can just Resize:
Sub If_after()
    ThisWorkbook.Sheets("Detail").Range("O2").Resize(99).Formula = "=IF(L2=N2,""good"",""update"")"
End Sub

A: Instead of using .Range("o" & i).Formula = … try using .Range("o" & i).FormulaR1C1 …. I always use FormulaR1C1 instead of Formula.


text:
Q: Java foreach method from second element in LinkedList I need help with foreach method to LinkedList in Java 8.
I need to start from second element. I don't know how to do this.

A: You can skip the first element: list.stream().skip(1).forEach(...). Note that the skipped elements will still be traversed by the stream, so for a random access list such as ArrayList it is much more efficient to use a loop starting from the relevant index if this index is very large. In your case it doesn't matter because your starting index is small and your list doesn't support random access.


text:
Q: My c++ program spend so much CPU? I have a project that I tried to run and it wasted more than 30% CPU. why?
The code is for a shortcut program and some reminders.
I am using visual studio 2017 c++ windows 10 Core Intel/i7
the command line:
/Yu"stdafx.h" /GS /analyze- /W3 /Zc:wchar_t /ZI /Gm /Od /sdl /Fd"Debug\vc141.pdb" /Zc:inline /fp:precise /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_UNICODE" /D "UNICODE" /errorReport:prompt /WX- /Zc:forScope /RTC1 /Gd /Oy- /MDd /Fa"Debug\" /EHsc /nologo /Fo"Debug\" /Fp"Debug\Clear.pch" /diagnostics:classic
the code:
#include "stdafx.h"
#include <Windows.h>
#include <shellapi.h>

bool pressed(int key) { return GetAsyncKeyState(key); }
namespace Main {
///to hide the console
void Main()
{
            SetWindowPos(GetConsoleWindow(), nullptr, 0, 0, 0, 0, SWP_HIDEWINDOW);
}
///the shortcuts
void Main1() {
    while (true) {
        ///Win-C = chrome
        if (pressed(VK_LWIN)&&pressed('C')) system("chrome http://www.google.com");
        ///Menu = battery message
        if (pressed(VK_APPS)) {
            SYSTEM_POWER_STATUS a;
            GetSystemPowerStatus(&a);
            char title[15]; sprintf(title, "%d%% battery%s", a.BatteryLifePercent, a.BatteryFlag & 8 ? ", charging" : "");
            char disp[100]; sprintf(disp, "You have %d hours and %d minutes left...", a.BatteryLifeTime / 3600 % 60, a.BatteryLifeTime / 60 % 60);
            MessageBoxA(nullptr, disp, title, 0);
        }
        if (pressed(VK_LWIN) && pressed(VK_DELETE)) SHEmptyRecycleBinA(nullptr, "", 0);
        if (pressed(VK_LWIN) && pressed('V')) system("C:\\Users\\steven\\source\\repos\\Clear\\Clear.sln");
        if (pressed(VK_LWIN) && pressed('Z')) system("start cmd");
        Sleep(GetDoubleClickTime());
    }
}
///time
void Main2() {
    while (true) {
        SYSTEMTIME t;
        GetSystemTime(&t);
        if (t.wDayOfWeek != 4 && t.wDayOfWeek != 5 && t.wHour == 0 && t.wMinute == 0 && t.wSecond == 0 && t.wMilliseconds == 0) MessageBoxA(nullptr, "Its 00:00", "Sleep", 0);
        if (t.wDayOfWeek == 0 && t.wHour == 15 && t.wMinute == 10 && t.wSecond == 0 && t.wMilliseconds == 0) MessageBoxA(nullptr, "Go to the Technion", "תירגול", 0);
        if ((t.wDayOfWeek == 1 || t.wDayOfWeek == 2) && t.wHour == 12 && t.wMinute == 25 && t.wSecond == 0 && t.wMilliseconds == 0) MessageBoxA(nullptr, "Go to the lab", "Math is over", 0);
        if (t.wDayOfWeek == 3 && t.wHour == 9 && t.wMinute == 35 && t.wSecond == 0 && t.wMilliseconds == 0) MessageBoxA(nullptr, "Go to the class", "Math is over", 0);
        if (t.wDayOfWeek == 4 && t.wHour == 10 && t.wMinute == 50 && t.wSecond == 0 && t.wMilliseconds == 0) MessageBoxA(nullptr, "Go to the class", "Math is over", 0);
    }
}
///the exit shortcut
void Main0() {
    while (true) {
        if (pressed(VK_LMENU) && pressed(VK_RMENU)) if (MessageBoxA(nullptr, "Do you want to exit?", "ShortCut", MB_YESNO|MB_ICONINFORMATION) == IDYES) exit(0);
        Sleep(GetDoubleClickTime());
        }
    }
}
#include <thread>
using namespace std;
int main(){
using namespace Main;
thread a[4]={thread(Main), thread(Main0), thread(Main1), thread(Main2)};
for(thread& b:a) b.join();
return 0;}

A: Main2() is very processor intensive, as it's a tight loop.
As a crude fix, consider a Sleep on that thread too.

A: The correct way to find out is with a profiller; visual studio has one built in which you should get some practice with; since it would not only highlight your high CPU; but also which thread.
Knowing which thread, in this example, would be enough information to answer your question.  If you plan to write threaded code you should get to grips with more of the tools in VS since threading gets very complex, very fast.


text:
Q: C# Automapper conditional mapping I am using nhibernate to map elements from one object to another. However, one of the elements in my complex objects, needs to have a condition set in order for the destination object element to have a value set accordingly.
To explain in detail
 Mapper.CreateMap<OneObject, AnotherObject>()
 .ForMember(
     destination => destination.complexelement,
       option => option.MapFrom(source=> source.value == enumValue.ToString()
        ? new object( {Id 123 })
        : new object ({ Id 567 }))

So, you can see that I want to set a nested object on the destination object based upon a value from the source object to create an object and save it to the destination element. The example code above I have tried, but it is throwing an error saying I can't use a string on a lambda expression.
Does anyone know how I can set an object based upon a condition?
Thanks

A: I think this will work for you. Unfortunately it is based on AutoMapper 6.1.1. Hope you can use this version. Because I didn't know your class structure, I created simple test classes, but you should be abled to transfer the sample to your scenario.
OneObject oo = new OneObject();
oo.value = "B";
Testenum enumValue = Testenum.A;

Mapper.Initialize(a => a.CreateMap<OneObject, AnotherObject>()
    .ForMember(
        destination => destination.complexelement,
        option => option.MapFrom(source => source.value == enumValue.ToString()
            ? 123
            : 567)));

AnotherObject ao = Mapper.Map<OneObject, AnotherObject>(oo);

Test classes and enum
class OneObject
{
    public string value { get; set; }
}

class AnotherObject
{
    public object complexelement { get; set; }
}

enum Testenum
{
    A,
    B,
    C
}


text:
Q: Linear programming with kernel Can anyone please help me with solving the constrained minimization problem below?
$$\mathbf{x}^* = \arg\min \sum_{i=1}^m q_i e^{-2x_i} $$
$$s.t.$$
$$\sum_{i=1}^m x_i = c$$
$$x_i\geq0, i = 1,\cdots,m$$
where $\mathbf{x}=[x_1,\cdots,x_m]^T$ is the unknown vector and $\mathbf{q}=[q_1,\cdots,q_m]^T$ and $c$ are given constants.
Do I need to consider the KKT conditions for this?
Or, can this problem be solved as a linear program by considering the exponential part as a sort of kernel?

A: Any reason not to solve directly as an NLP (nonlinear programming problem)? It seems convex and well-behaved. I had no problem with:


text:
Q: Find server details when connection lost with client I have a code to access multiple wcf server from one client with multiple instances. if any connection lost between this, having faulted/closed event trigger function to hande this.
((ICommunicationObject)notificationProviderClient).Faulted += new EventHandler(myHost_Faulted);
((ICommunicationObject)notificationProviderClient).Closed += new EventHandler(myHost_Closed);
void myHost_Faulted(object sender, EventArgs e)
{
}
void myHost_Closed(object sender, EventArgs e)
 {
}
The above function get called, if any connection get fault/closed.
 In this scenarion how to find which wcf server connection lost with the clent? is there any possible to find this or we have to go for another method to handle this?

A: to find remote address of server during connection lost, use this on client side
this.notificationProviderClient.InnerDuplexChannel.Faulted += new EventHandler(myHost_Faulted);
void myHost_Faulted(object sender, EventArgs e) {
    IContextChannel channel = sender as IContextChannel;

    if (channel  != null)
    {
      var remoteAddrs = a1.RemoteAddress;
    }

}


text:
Q: Get the asset url without fingerprint in Rails Using javascript_url we can get the url of the asset:
<script src="<%= javascript_url 'company_widget' %>"
  token="<%= current_user.token %>"
  class="ofri-company-widget"
></script>

However, the javascript_url returns the url with the fingerprint:
domain.com/assets/company_widget-<fingerprint>.js

It seems this get cached forever, and whenever we need to make changes in the script, the third-parties using this script will have to reload it.
I noticed that accessing the file without fingerprint works too:
domain.com/assets/company_widget.js

Is there a way to tell javascript_url to not add the fingerprint? Or is there another better solution in this context?

A: http://guides.rubyonrails.org/asset_pipeline.html#turning-digests-off
You can turn off digests by updating config/environments/development.rb to include:
config.assets.digest = false

A: What you really need to do is to return your javascript file in controller action, so have control over the cache for this particular file.
In your controller action you should do something like:
def company_widget
  response.headers["Expires"] = 1.day.from_now.httpdate
  expires_in 1.day, public: true, must_revalidate: true

  format.js do
    asset = open(ActionController::Base.helpers.asset_url('company_widget.js', host: host))
    send_data asset.read, :type => asset.content_type
  end
end

def host
  request.protocol + request.host_with_port
end

Then you can point to controller action and be sure that you have control over what is returned.
<script src="http://example.com/company_widget.js"></script>

Expires header is older way of setting cache, while expires_in Rails method will set Cache-Control header which is the best way to manage your cache. It takes precedence over Expires.
Additionally you can take a look on a great article about caching: https://www.mnot.net/cache_docs/