text:
Q: VO issue over object in flex fusioncharts when I use VO instead of Object in the fusionCharts loader function I get the "set"
()attribute empty.
MY CODE:
[Bindable]
private var chartColl:ArrayCollection;

private function chartDetails():void
{
   var chartColl:ArrayCollection=new ArrayCollection();
   for (var j:int =0;j<uniqueData.length;j++)
   {
      var obj:ChartVO=new ChartVO();
      obj.label=String(uniqueData.getItemAt(j));
      var count:int=0;

      for(var i:int=0;i<getPopulation.length;i++)
      {
         if(String(uniqueData.getItemAt(j))== getPopulation.getItemAt(i).country)
         {
                count=count+getPopulation.getItemAt(i).count;
         }
      }

      obj.value=count;
      chartColl.addItem(obj);
  }
  fc.FCData(chartColl);
  fc.FCRender();
}

A: You would need to set 'value' property too along with 'label' property.
Please check setting debug mode the resultant XML.
Also make sure you are building proper ArrayCollection format as per chart type.
The data format for each type/group of chart is listed in these links:
http://www.fusioncharts.com/flex/docs/charts/Contents/create_single_array.html
http://www.fusioncharts.com/flex/docs/charts/Contents/create_multi_array.html
http://www.fusioncharts.com/flex/docs/charts/Contents/create_stacked_array.html
http://www.fusioncharts.com/flex/docs/charts/Contents/create_combi_array.html
http://www.fusioncharts.com/flex/docs/charts/Contents/create_plot_array.html
List of chart types/groups are here:
http://www.fusioncharts.com/flex/docs/charts/Contents/introduction_chartTypes.html
For further information on mapping of data from FusionCharts native XML format to ArrayCollection read:
http://www.fusioncharts.com/flex/docs/charts/Contents/xml_mapping_singleSeries.html
http://www.fusioncharts.com/flex/docs/charts/Contents/xml_mapping_multiSeries.html
http://www.fusioncharts.com/flex/docs/charts/Contents/xml_mapping_plot.html


text:
Q: How to Select and Group By query which is already grouped with Over() ? - Oracle I'm trying to refine following query:
    SELECT TID, INSERTDATE, TNAME, TSURNAME, TDATE1, TDATE2, TDATE3 FROM
    (SELECT T1.TID,T2.INSERTDATE, T1.TNAME, T1.TSURNAME,  T2.TDATE1, T2.TDATE2, T2.TDATE3, ROW_NUMBER() OVER (PARTITION BY T1.TID ORDER BY T2.INSERTDATE DESC) AS RN
FROM MEMBER T1 INNER JOIN MEMBERPROMOTION T2 ON T1.TID=T2.TID WHERE SOME CLAUSES AND
(TDATE1 >= TO_TIMESTAMP('15/07/2014', 'DD/MM/YYYY HH24:MI:SS') AND TDATE1 <= TO_TIMESTAMP('14/08/2014', 'DD/MM/YYYY HH24:MI:SS')) OR
(TDATE2 >= TO_TIMESTAMP('15/07/2014', 'DD/MM/YYYY HH24:MI:SS') AND TDATE2 <= TO_TIMESTAMP('14/08/2014', 'DD/MM/YYYY HH24:MI:SS')) OR
(TDATE3 >= TO_TIMESTAMP('15/07/2014', 'DD/MM/YYYY HH24:MI:SS') AND TDATE3 <= TO_TIMESTAMP('14/08/2014', 'DD/MM/YYYY HH24:MI:SS')))
 ORDERED WHERE RN = 1;

MEMBER
  TID  TNAME   TSURNAME
-------------------------------
   1    BLA   BLABLA
   2    BL    BLBL

MEMBERPROMOTIONS
  MPID  TID  INSERTDATE     TDATE1       TDATE2       TDATE3
--------------------------------------------------------
   1     1   11/06/2012   19/07/2013    19/07/2013   19/07/2013
   2     1   05/08/2013   19/07/2014    19/07/2014   19/07/2014
   3     2   05/08/2013   02/08/2014    21/07/2014   02/08/2014

EXPECTED RESULT
  TID  INSERTDATE     TDATE1       TDATE2       TDATE3
--------------------------------------------------------
   1   05/08/2013   19/07/2014    19/07/2014   19/07/2014
   2   05/08/2013   02/08/2014    21/07/2014   02/08/2014
   2   05/08/2013   02/08/2014    21/07/2014   02/08/2014

MEMBER table has member information and it has relationship with MEMBERPROMOTIONS table on TID column.
As you see; I have date inputs and I'm selecting rows at least one of dates(date1,date2,date3) between input dates. I just want max(INSERTDATE) row so I used OVER().
Here is what I am trying to accomplish:
If TDATE1, TDATE2 and TDATE3 is same I want single row return, otherwise I expect multiple rows. The point is I want to group by according to TDATE1, TDATE2 and TDATE3.

A: I think you're looking for an unpivot to convert the three TDATEx columns into rows; then to compare each of those with your date range. You've tagged this as 10g so the 11g unpivot operator isn't available, so this needs to be done the old way:
SELECT MP.MPID, MP.TID, MP.INSERTDATE, T.RN AS TDATE_NUM,
  CASE T.RN
    WHEN 1 THEN MP.TDATE1
    WHEN 2 THEN MP.TDATE2
    WHEN 3 THEN MP.TDATE3
  END AS TDATE
FROM (SELECT LEVEL AS RN FROM DUAL CONNECT BY LEVEL <= 3) T
CROSS JOIN MEMBERPROMOTION MP
ORDER BY MP.MPID, RN;

Which gives you:
      MPID        TID INSERTDATE  TDATE_NUM TDATE
---------- ---------- ---------- ---------- ----------
         1          1 11/06/2012          1 19/07/2013
         1          1 11/06/2012          2 19/07/2013
         1          1 11/06/2012          3 19/07/2013
         2          1 05/08/2013          1 19/07/2014
         2          1 05/08/2013          2 19/07/2014
         2          1 05/08/2013          3 19/07/2014
         3          2 05/08/2013          1 02/08/2014
         3          2 05/08/2013          2 21/07/2014
         3          2 05/08/2013          3 02/08/2014

Using that instead of your original table:
SELECT TID, MAX(INSERTDATE), TNAME, TSURNAME, TDATE
FROM (
  SELECT M.TID, MP.INSERTDATE, M.TNAME, M.TSURNAME, MP.TDATE_NUM, MP.TDATE
  FROM MEMBER M
  INNER JOIN (
    SELECT MP.MPID, MP.TID, MP.INSERTDATE, T.RN AS TDATE_NUM,
      CASE T.RN
        WHEN 1 THEN MP.TDATE1
        WHEN 2 THEN MP.TDATE2
        WHEN 3 THEN MP.TDATE3
      END AS TDATE
    FROM (SELECT LEVEL AS RN FROM DUAL CONNECT BY LEVEL <= 3) T
    CROSS JOIN MEMBERPROMOTION MP
  ) MP
  ON MP.TID=M.TID
  WHERE -- SOME CLAUSES AND
    MP.TDATE >= TO_TIMESTAMP('15/07/2014', 'DD/MM/YYYY HH24:MI:SS')
  AND MP.TDATE <= TO_TIMESTAMP('14/08/2014', 'DD/MM/YYYY HH24:MI:SS')
)
GROUP BY TID, TNAME, TSURNAME, TDATE;

Gives:
       TID INSERTDATE TNAME      TSURNAME    TDATE_NUM TDATE
---------- ---------- ---------- ---------- ---------- ----------
         1 05/08/2013 BLA        BLABLA              1 19/07/2014
         1 05/08/2013 BLA        BLABLA              2 19/07/2014
         1 05/08/2013 BLA        BLABLA              3 19/07/2014
         2 05/08/2013 BL         BLBL                1 02/08/2014
         2 05/08/2013 BL         BLBL                2 21/07/2014
         2 05/08/2013 BL         BLBL                3 02/08/2014

And that can then be your inner query; and you can apply the group-by to that result set:
SELECT TID, MAX(INSERTDATE) AS INSERTDATE, TNAME, TSURNAME, TDATE
FROM (
  SELECT M.TID, MP.INSERTDATE, M.TNAME, M.TSURNAME, MP.TDATE_NUM, MP.TDATE
  FROM MEMBER M
  INNER JOIN (
    SELECT MP.MPID, MP.TID, MP.INSERTDATE, T.RN AS TDATE_NUM,
      CASE T.RN
        WHEN 1 THEN MP.TDATE1
        WHEN 2 THEN MP.TDATE2
        WHEN 3 THEN MP.TDATE3
      END AS TDATE
    FROM (SELECT LEVEL AS RN FROM DUAL CONNECT BY LEVEL <= 3) T
    CROSS JOIN MEMBERPROMOTION MP
  ) MP
  ON MP.TID=M.TID
  WHERE -- SOME CLAUSES AND
    MP.TDATE >= TO_TIMESTAMP('15/07/2014', 'DD/MM/YYYY HH24:MI:SS')
  AND MP.TDATE <= TO_TIMESTAMP('14/08/2014', 'DD/MM/YYYY HH24:MI:SS')
)
GROUP BY TID, TNAME, TSURNAME, TDATE
ORDER BY TID, INSERTDATE, TDATE;

Giving:
       TID INSERTDATE TNAME      TSURNAME   TDATE
---------- ---------- ---------- ---------- ----------
         1 05/08/2013 BLA        BLABLA     19/07/2014
         2 05/08/2013 BL         BLBL       21/07/2014
         2 05/08/2013 BL         BLBL       02/08/2014

SQL Fiddle.

redpajama_set_name: RedPajamaStackExchange


text:
Q: makedepend missing? OS X 10.8 is missing makedepend (Apple: OpenSSL and make depend). It looks like the last version of OS X that had makedepend was 10.7.4 (http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man1/makedepend.1.html).
I can't modify the makefile due to policy, so I tried placing an alias in my .bash_profile, but it did not work as expected.
Is anyone aware of an alternative? Does Apple put deprecate packages anywhere? I did not see it on opensource.apple.com.

A: Two seconds of googling found this, which says that gcc -M is equivalent to makedepend.

A: Did you try:
brew install makedepend
https://github.com/Homebrew/homebrew/wiki/Installation


text:
Q: Horizontal Scrolling in Panorama View I hava a panorama view with multiple panorama items. In one of these panorama items I have a grid within a ScrollViewer. The grid is too large in terms of width.
The problem is that if the user slides the panorama view gets triggered and changes the panorama item, althrough the the scroll viewer should actually scroll horizontally (until the end of the grid).
However, if the user slides very slowly, the panorama view does not get triggered and only the scrolling takes place. This is the intended behaviour.
Thank you very much

A: You can use isHitTestVisible property.
//Disable panorama scrolling
MyPanorama.IsHitTestVisible = false;

//Enable panorama scrolling
MyPanorama.IsHitTestVisible = true;

Use this in a ManipulationStarted listener. That is, when the use starts scrolling horizontally, you can temporarily make IsHitTestVisible to be false.


text:
Q: Create a Dictionary by ignoring repeating keys Let's say I have this Dictionary:
var Dict = Dictionary<Obj, Value>
And I want to create a new one that is:
var Dict2 = Dictionary<Obj.ParentId, Value>
However, there might be objects that have the same ParentId, so that would be a problem when creating a new Dictionary. Any two entries with the same ParentId will have the same Value, so I only care to keep one of the entries. Is there a way to easily do this either through LINQ?

A: The easiest way to do this is probably imperatively using a loop. In this approach, the last one wins - but, as you say, this shouldn't matter in your case:
var dict2 = new Dictionary<Obj.ParentId, Value>();

foreach (var (key, value) in dict1)
{
    dict2[key.ParentId] = value;
}

You could also do this using LINQ, but it's probably less performant given it has to do the 'distinct' part first:
var dict2 = dict1
    .DistinctBy(x => x.Key.ParentId)
    .ToDictionary(x => x.Key.ParentId, x => x.Value);

A: You can use Linq: query Dict and materialize result as Dict2
var Dict2 = Dict
  .GroupBy(pair => pair.Key.ParentId, pair => pair.Value)
   // Or group.Last().Value or some other logic
  .ToDictionary(group => group.Key, group => group.First().Value);

Or you can try looping:
var Dict2 = Dictionary<Obj.ParentId, Value>();

foreach (var pair in Dict)
  Dict2.TryAdd(pair.Key.ParentId, pair.Value);


text:
Q: Oracle Apex: Display different links in cell of table I have using oracle apex to create an application.
Is there a way to make a table cell display different links based on what is inside the cell?
So I want to have an icon '+' that is linked to a 'create' page inside the cells that are empty.
This is an interactive report for apex.

but I already set the asset column as a link to a 'edit' page

Here is the code to generate the data:
select ID,
(SELECT distinct listagg(v.asset_id,', ') within group (order by s.id) from subnet_lookup l, infra_assets_master v where l.subnet_id = s.id AND l.link_id = v.id AND l.def_id = 3) as Assets,
(SELECT distinct listagg(v.hostname,', ') within group (order by s.id) from subnet_lookup l, infra_assets_master v where l.subnet_id = s.id AND l.link_id = v.id AND l.def_id = 3) as Hostname,
(SELECT distinct listagg(m.hostname,', ') within group (order by s.id) from subnet_lookup l, servers_master m where l.subnet_id = s.id AND l.link_id = m.id AND l.def_id = 1) as Servers,

from subnet s
where NETWORK_ID = :P55_NETWORK_ID
ORDER BY ID desc

Is there a way I can set a condition to display different information with different links based on the values inside the cell?


text:
Q: The impact of SharePoint 2016's Excel Services Deprecations I know you have to switch to Excel Online in Office Online Server Preview, but I've also read that these features are deprecated:

*

*Trusted data providers

*Trusted data connection libraries

*Unattended service account

Here is what I use Excel Services for:

*

*Connecting to a multidimensional/MDX Cube (NO TABULAR model is ever used)

*Connecting to different data sources

*Using the Excel workbooks themselves as data sources for SharePoint web parts AND dashboards (PerformancePoint Services)

*Excel Web Access Web Part; and again, the Excel sheet connects to a cube, accepts parameters, and it is itself a data source for other artifacts. Part or all of the workbooks are used in PerformancePoint, webparts and report parts.

Sources considered:

*

*http://whitepages.unlimitedviz.com/2016/03/connecting-excel-to-data-with-sharepoint-2016-and-office-online-server-2016/

*https://msdn.microsoft.com/en-us/library/dn141153.aspx#bkmk_excel

*https://www.linkedin.com/pulse/sharepoint-server-2016-whats-deprecated-removed-zeeshan-asad


text:
Q: Delay translate elements with Intersection Observer API I'm using Intersection Observer API to show the elements when user scrolls to the content. It works well, but I want to delay the div's to be showed, if there are 4 div's, I want the first to be showed, next 0.5 sec the next is shown... not all in the same time. In the example the effect only applies on the first class too, if there are more than 1 class like there are, it didn't apply to the next img classes, only the first. You can see the example in the bottom of this page.
HTML

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras nibh justo, tincidunt sed felis vitae, egestas scelerisque eros.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras nibh justo, tincidunt sed felis vitae, egestas scelerisque eros.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras nibh justo, tincidunt sed felis vitae, egestas scelerisque eros.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras nibh justo, tincidunt sed felis vitae, egestas scelerisque eros.

JS
// Instantiate a new Intersection Observer
let observer7 = new IntersectionObserver(onEntry7);
let staff = document.querySelector('.floating');

let element7 = document.querySelector("#staff p");
observer7.observe(element7);

function onEntry7(entry7) {
  if (entry7[0].isIntersecting) {
    staff.classList.add("show-bottom");
  }
}

CSS
.floating {opacity: 0; transition: 1s opacity;}
.floating.show-bottom {opacity: 1;
  animation: movefromtop 1s alternate infinite;
  animation-iteration-count: 1;
  animation-fill-mode:  forwards;}
@keyframes movefromtop {
  from {
    transform: translateY(-5em);
  }
  to {
    transform: translateY(0em);
  }
}

A: Use querySelectorAll() to get all inner div elements, then using forEach call your observer.observe() method for all elements. Then in the observer, use the target property to query the inner image and add the show-bottom class to it.
To add a delay between each animation you have to create an animation chain by returning a Promise and using setTimeout(). Also make sure to not chain the same element more than once in the animation if the intersection triggers many times for the same element. For this, use an array of animatedElements to keep track of the elements being animated.
If you only want to animate the elements once, after begin intersected, you can call unobserve on your observer to unregister from further intersection events.
Note: I edited your HTML/CSS to make the grid work in the snippet to demonstrate the sequential animation effect when multiple elements are on the same row. I also added a with-img class to the inner divs so we can query them and pass them to the observe method.

const onEntry7 = animateSequence('.floating', 'show-bottom');
const observer7 = new IntersectionObserver(onEntry7);
const allElements7 = document.querySelectorAll('#staff div.with-img');
allElements7.forEach(e => observer7.observe(e));

function animateSequence(targetSelector, classToAdd, delay = 500) {
  const animatedElements = [];
  let chain = Promise.resolve();

  function show(e) {
    return new Promise((res, rej) => {
      setTimeout(() => {
        e.classList.add(classToAdd);
        res();
      }, delay);
    });
  }
  return function(entries) {
    entries.forEach(entry => {
      if (entry.intersectionRatio > 0) {
        const elem = entry.target.querySelector(targetSelector);
        if (!animatedElements.includes(elem)) {
          animatedElements.push(elem);
          console.clear();
          console.log('chaining', ...animatedElements.map(e => e.getAttribute('data--name')));
          chain = chain.then(() => show(elem));
          observer7.unobserve(entry.target);
        }
      }
    })
  }
}
.floating {
  opacity: 0;
  transition: 1s opacity;
  width: 157px;
  height: 220px;
}
.floating.show-bottom {
  opacity: 1;
  animation: movefromtop 1s alternate infinite;
  animation-iteration-count: 1;
  animation-fill-mode:  forwards;
}
@keyframes movefromtop {
  from { transform: translateY(-5em); }
  to { transform: translateY(0em); }
}
section#staff {
  margin-top: 200px;
  margin-bottom: 200px;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
Scroll Down

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras nibh justo, tincidunt sed felis vitae, egestas scelerisque eros.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras nibh justo, tincidunt sed felis vitae, egestas scelerisque eros.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras nibh justo, tincidunt sed felis vitae, egestas scelerisque eros.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras nibh justo, tincidunt sed felis vitae, egestas scelerisque eros.


text:
Q: Setting focus on textbox after listbox additem I have a simple form on Excel, with a couple information fields that are currently dragged from another previous form. There's only one textbox (txtEtiqueta) on which i input data using a handheld scanner. This data from my textbox, is added to a listbox using txtEtiqueta_AfterUpdate() event. My problem is that i cant set the focus back on my txtEtiqueta textbox and i ought to get this, in order to keep scanning barcodes.
    Private Sub txtEtiqueta_AfterUpdate()

            Me.ListBox2.ColumnCount = 7
            Me.ListBox2.AddItem Me.txtEtiqueta.Value
            Me.ListBox2.List(ListBox2.ListCount - 1, 1) = Me.txtUsuario3.Value
            Me.ListBox2.List(ListBox2.ListCount - 1, 2) = Me.txtFecha2.Value
            Me.ListBox2.List(ListBox2.ListCount - 1, 3) = Me.txtConductor.Value
            Me.ListBox2.List(ListBox2.ListCount - 1, 4) = Me.txtPatente2.Value
            Me.ListBox2.List(ListBox2.ListCount - 1, 5) = Me.txtCelular2.Value
            Me.ListBox2.List(ListBox2.ListCount - 1, 6) = Me.txtEmpresa2.Value
            Me.TextBox1.Value = Me.ListBox2.ListCount

End Sub

Right after doing so, i set txtEtiqueta.value to null with another textbox_change event (which changes by counting listbox items)
Private Sub TextBox1_Change()
        Me.txtEtiqueta.Value = Null
End Sub

Finally, after cleaning txtEtiqueta values, i need to set focus back on it again, but i don't know how to achieve it. I have tried this, with no success:
Private Sub TextBox1_Change()
        Me.txtEtiqueta.Value = Null
        Me.txtEtiqueta.SetFocus

End Sub

Sadly, previous code line actually sets txtEtiqueta's value to null, but it does not sets focus on it.

A: Bear in mind that
Private Sub TextBox1_Change()
        Me.txtEtiqueta.Value = Null
End Sub

will trigger the txtEtiqueta_AfterUpdate event which is changing the value of TextBox1 and thereby triggering the TextBox1_Change event. This should be an endless loop which is broken somewhere. Perhaps VBA recognises that txtEtiqueta_AfterUpdate replaces the existing value in TextBox1 with the exact same value on the second round and determines that no change has occurred. And perhaps you have some code elsewhere which you mention in your question but don't show. It doesn't really matter.
The solution to your problem lies in making sure that no events occur after you have set the focus back to txtEtiqueta. Use the Application.EnableEvents property for this purpose, perhaps like this:-
Private Sub TextBox1_Change()
        Application.EnableEvents = False
        Me.txtEtiqueta.Value = Null
        Me.txtEtiqueta.SetFocus
        Application.EnableEvents = True
End Sub

With this code you would prevent the txtEtiqueta_AfterUpdate event from being triggered by setting its value to Null.


text:
Q: Unable to install Macbuntu I downloaded Macbuntu from http://sourceforge.net/projects/macbuntu/
I extracted it in Downloads folder, and then I dble-clicked "install.sh"(Macbuntu-10.10 folder). When prompted, I clicked RUN IN TERMINAL. Immediately the terminal window appeared on the screen for a second, and disappeared. Nothing happened after that.
I was trying to follow the instructions posted in this link:
http://www.howtogeek.com/45817/how-to-make-ubuntu-linux-look-like-mac-os-x/
(I am on ubuntu 12.04)
Can someone point me to the right direction?

A: Macbuntu is for 10.10 and 10.04, doesn't work in 12.04.
This is because 10.XX uses Gnome 2, from 11.10 onwards Gnome 3 is used which is incompatible with Gnome 2 theme.
There are Gnome 3 Mac Themes so you can still get the OSX look and feel, but Macbuntu itself won't work unless they update it.

A: Adding futher to Uri Herrera's answer, check this out. That is for gnome 3 which you could use in ubuntu 12.04.


text:
Q: Script won't execute on crontab I have a script which executes manually:
#!/bin/bash
mount -t cifs //192.168.138.18/Shared_Drive /mnt/share -o username=user,password=guest

But sudo crontab -e doesn't execute it. I tried:
@reboot /home/user/startup.sh
@reboot sh /home/user/startup.sh
@reboot bash -l /home/user/startup.sh
@reboot /bin/bash /home/user/startup.sh

Nothing works. Permits are:
-rwxr-x--x 1 user user

A: crontab -e doesn't execute scheduled command, it opens your crontab rules file in an editor
The command will then be executed by cron itself on the specified schedule.  (If the rule is written correctly.  If you want help checking that then include the cron rule.)
Also note that the crontab command man page says

Note that su(8) can confuse crontab and that if you are running inside of su(8) you should always use the -u option for safety's sake

So you should run sudo crontab -u root -e


text:
Q: How to remove "" from shiny selectInput? I want to directly use some selectInput in a boolean way. Is there a possibility to do so?
Have a look at my minimal example:
ui <- fluidPage(
  selectInput("in", "some input", choices = c("0"=F, "1"=T))
)

server <- function(input, output, session) {
 test_data <- read.csv("testfile",
                       header= input$in,
                       sep= ";")
}

Normal tricks to remove quotes (as desribed here) won't do the trick. I've also tried to force R to treat the input's output to be logical (via as.logical) and I've tried something simple as print(..., quote=F). Nothing worked...

A: in is a reserved word in R. You can still refer to the input name with backticks to avoid an error. Also, input[['in']] will work too. Finally we can use as.logical to convert the string into a boolean.
app:
note: replace 'PATHTOFILE' before running the app.
library(shiny)

ui <- fluidPage(
  selectInput("in", "some input", choices = c("0"=F, "1"=T))
)

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

  test_data <- reactive({
    read.csv("PATHTOFILE",
                        header= as.logical(input$`in`),
                        sep= ";")})

  observe({
    print(input$`in`)
    print(head(test_data()))
  })
}

shinyApp(ui, server)


text:
Q: Python Editable Install - specifying __version__ in pyproject.toml reflected on change so similar to question in link I want to specify version within pyproject.toml and use that within code (eg for package var _version__)
I wanted to use solution as specified like below to
import importlib.metadata

__version__ = importlib_metadata.version(__package__ or __name__)

one issue I seem to be running into though is that if editable install (ie pip install -e .) and update the pyproject.toml project.version this wont be automatically reflected in __version__. is there way to get such behavior?


text:
Q: remove content between a specific character and whitespace I have a string in python of floats that looks like this:
"a b c,d e"

And I would like to efficiently change it to this:
"a b c e"

The original string is a line in a text file and there may be more than one comma in the string. I.e. every time there is a comma I want to remove all characters between it and whitespace. I could do this with a for loop, make a list, and then join that list with a whitespace character, but I need to do this many times so speed is important. Hopefully using regular expressions.
Just to be clear a,b,c,d and e are not characters they usually look like 1.00e-03 or something.

A: You can use regex for this;
>>> import re
>>> s = "a b c,d e"
>>> re.sub(r',\S+', '', s)
'a b c e'

A: text = "a b c,d e"
re.sub(re.search(r'(,\w)', text).group(1), '', text)
>> "a b c e"

A: If you need more speed as a simplest way you can use split :
>>> s="a b c,d e r ,y g k"
>>> sp=s.split(',')
>>> sp
['a b c', 'd e r ', 'y g k']
>>> new=[i[1:].strip() for i in sp[1:]]
>>> new
['e r', 'g k']
>>> new_string=sp[0]+' '+' '.join(new)
>>> new_string
'a b c e r g k'


text:
Q: H must be the handle to a figure or figure descendent Matlab I'm calling GUI function in matlab's classdefbut it gives error of "H must be the handle to a figure or figure descendent." in  guihandles(GUI);
How can I call function of GUI in matlab's class?
The working of the class is perfect by the way, but it gives error then figure is closed.
My class code:
classdef GUIclass < handle

    properties (Access = private)
        gui_h;
    end
    methods

        function obj = GUIclass
            guihandles(GUI);
        end

    end

end

A: This function guihandles(h) expects a handle. If the handle specified by h (in your case, GUI) is closed then it is no longer valid. You can check to see if GUI is a valid handle before using it with ishandle(h) or ishandle(GUI).
See the following code:
close all;
h = 1;

% We just closed everything, so we expect handle h=1 to be bad:
if ishandle(h)
    disp('Is a valid handle');
else
    disp('Is not a valid handle');
end

% Now make the figure (we specify '1' so that will make h okay
figure(1);

% check to see if h is valid:
if ishandle(h)
    disp('Is a valid handle');
else
    disp('Is not a valid handle');
end


text:
Q: Java - using streams to get list elements with a certain property I have two classes named School and Student, a set of Schools, a list of Students and two maps that hold the School's preferences in terms of students and vice versa:
Set<School> schoolSet = new TreeSet<>();
Collections.addAll(schoolSet, schools);

List<Student> studentList = new LinkedList<>(Arrays.asList(students));

Map<School, List<Student>> schoolPrefMap = new TreeMap<>();
Map<Student, List<School>> stdPrefMap = new HashMap<>();

I'm using different implementations because that's one of the tasks that I have to fulfill.
I'm trying to create a query using java streams that returns the Schools from the set that have a certain student as their top priority, so the index of that student should be 0 in the list of values for that specific school key.
I have an example of trying something similar, only getting the students who have at least a certain school(s) in his preferences
List<School> target = Arrays.asList(schools[0], schools[2]);

List<Student> result = studentList.stream()
        .filter(std -> stdPrefMap.get(std).containsAll(target))
        .collect(Collectors.toList());

How can I use streams to get the schools that have a given student as their top preference?

A: This should accomplish what you specified:
Student target = ...
schoolSet.stream()
        .filter(school -> {
            List<Student> preferredStudents = schoolPrefMap.get(school);
            return !preferredStudents.isEmpty() && preferredStudents.get(0).equals(target);
        }).collect(Collectors.toList());

May I ask why you're not using a Map<School, PriorityQueue<Student>> and Map<Student, PriorityQueue<School>> (as it is perfectly suited for a case like this with rated preferences and using contains() / containsAll() on a list is not very efficient)?
In that case your code would look like this:
schoolSet.stream()
        .filter(school -> {
            Queue<Student> preferredStudents = schoolPrefMap.get(school);
            return !preferredStudents.isEmpty() && preferredStudents.peek().equals(target);
        }).collect(Collectors.toList());

A: I hope you will find it helpful:
        List<School> schoolsWithTargetedStudentAsTopPref = schoolSet.stream()
            .filter(school -> schoolPrefMap.get(school).stream()
                    .findFirst()
                    .filter(student-> student.equals(target))
                    .map(optionalSchool -> !optionalSchool.isEmpty())
                    .get())
            .collect(Collectors.toList());


text:
Q: Visual Studio 2022 Unauthorized Operation when opening .cs files Does anyone know how to fix a "Attempted to perform an unauthorized operation" error in Visual Studio 2022 when opening a .cs file?
I worked on a VS Solution yesterday. Opened the laptop today, rebooted, opened the solution, and open a cs file via Solution Explorer, I get an error and a blank tab:

Also noticed that opening a Solution from the Windows 10 Jump List will cause the VS 2022 logo to be displayed and then the process will silently crash.

What I've tried so far:

*

*Upgraded Visual Studio to v17.1.5

*Upgraded all Extensions

*Confirmed plenty of diskspace, memory.

Environment
Windows 10: 21H1
Visual Studio 2022 v17.1.5
3rd Party Extensions:   AWS Toolkit, ReSharper, T4Editor, Git Diff Margin, ReSharper

A: According to this forum entry
https://developercommunity.visualstudio.com/t/Visual-Studio-Editor-is-blank-without-an/1568780
A reboot should fix it.

A: Rebooting fixed the problem.
Looks like Microsoft is aware of the issue but doesn't expect it to be fixed until version 17.2.

Workaround - Oleg Tkachenko [MSFT]
Unfortunately until 17.2 you might still experience this issue every time Windows Terminal is autoupdated, too many code paths to handle exceptions on… The proven workaround is to restart Windows though.
- https://developercommunity.visualstudio.com/t/Visual-Studio-Editor-is-blank-without-an/1568780

Thanks to pm100 for the original link!!


text:
Q: Json Request from Node js to Django I have code in node js
const request = require('request-json');
var dataSend = {'data': "TESTS"}
var client = request.createClient('http://127.0.0.1:8000/');
client.post('report/', dataSend, function(err, res, body) {
    return console.log(body['status'])
});

and code in python in django 1.11.
def report(request):
    print(request.POST.get('data'))

    return JsonResponse({'status': True})

When i send request Django receive it and return JsonResponse({'status': True})  and request code is 200.
The problem is I can't receive and get {'data': "TESTS"} in python /django. When i use request.POST i receive <QueryDict: {}>Thx for help

A: request.POST will not contain the JSON request data - it only contains application/x-www-form-urlencoded form data.
To access the JSON request you need to read request.body directly:
data = request.body

Or in Python 3:
data = request.body.decode('utf-8')


text:
Q: 401 (Unauthorized): Exchange 2010 SP1 cannot see Exchange 2010 SP3 free/busy data under Federation I have followed the procedures to set up federation trust between 2 forest sites. Site A (Exchange 2010 SP1) and Site B (Exchange 2010 SP3).  They are not connected by any network.
The link to MFG seems to work by running Test-FederationTrust from both sites and we have established org relationship between the 2 sites.
However, Site B (EX2010 SP3) can see Site A (EX2010 SP1)'s free/busy data but Site A (EX2010 SP1) cannot see Site B (EX2010 SP1)'s free/busy data.
Below is the error when running Test-OrganisationRelationship from Site A (EX2010 SP1)
Site A error is "HTTP status 401: Unauthorised"
VERBOSE: [07:09:06.136 GMT] Test-OrganizationRelationship : The Microsoft Exchange Autodiscover service failed to be called at 'https://autodiscover.siteB.com.au/autodiscover/autodiscover.svc/WSSecurity' because the
following error occurred: WebException.Response =
Exception:
System.Net.WebException: The request failed with HTTP status 401: Unauthorized.
Has anyone encountered this problem before?

A: To configure free/busy sharing between two federated Exchange 2010 organizations, Check you have performed the steps in Configure Federated Delegation for both organizations.
Here're similar thread for your reference:
enter link description here
enter link description here


text:
Q: An inheritance example in Python I'm not clear how to pose this question.  If I did, I'd probably be a lot closer to a solution..  I need some insight into inheritance.
I want to make a custom subtype of float.  But I want the instance of this subtype to re-evaluate its value before performing any of the normal float methods (__add__,__mul__, etc..).  In this example it should multiply its value by the global FACTOR:
class FactorFloat(float):
    # I don't think I want to do this:
    ##    def __new__(self, value):
    ##        return float.__new__(self, value)
    def __init__(self, value):
        float.__init__(self, value)
    # Something important is missing..
    # I want to do something with global FACTOR
    # when any float method is called.

f = FactorFloat(3.)
FACTOR = 10.
print f   # 30.0
print f-1 # 29.0
FACTOR = 2.
print f   # 6.0
print f-1 # 5.0

This is a just a sanitized example that I think gets my point across.  I'll post a more complex "real" problem if necessary.

A: class FactorFloat(float):
    def _factor_scale(f):
        def wrapper(self, *args, **kwargs):
            scaled = float.__mul__(self, FACTOR)
            result = f(scaled, *args, **kwargs)
            # if you want to return FactorFloats when possible:
            if isinstance(result, float):
                result = type(self)(result/FACTOR)
            return result
        return wrapper

    def __repr__(self):
        return '%s(%s)' % (type(self).__name__, float.__repr__(self))

    __str__ = _factor_scale(float.__str__)
    __mul__ = _factor_scale(float.__mul__)
    __div__ = _factor_scale(float.__div__)
    __add__ = _factor_scale(float.__add__)
    __sub__ = _factor_scale(float.__sub__)

f = FactorFloat(3.)
FACTOR = 10.
print f   # 30.0
print f-1 # 29.0
FACTOR = 2.
print f   # 6.0
print f-1 # 5.0
print repr(f)

for:
30.0
29.0
6.0
5.0
FactorFloat(3.0)

EDIT:
In response to the question in the comment; making things slightly more general and automated, using a class decorator. I would not loop over dir(baseclass), but instead would explicitly list the methods I wished to wrap. In the example below, I list them in the class variable _scale_methods.
def wrap_scale_methods(cls):
    Base = cls.__base__
    def factor_scale(f):
        def wrapper(self, *args, **kwargs):
            scaled = Base.__mul__(self, FACTOR)
            result = f(scaled, *args, **kwargs)
            if isinstance(result, Base):
                result = type(self)(result/FACTOR)
            return result
        return wrapper
    for methodname in cls._scale_methods:
        setattr(cls, methodname, factor_scale(getattr(Base, methodname)))
    return cls

@wrap_scale_methods
class FactorComplex(complex):
    _scale_methods = '__str__ __mul__ __div__ __add__ __sub__'.split()
    def __repr__(self):
        return '%s(%s)' % (type(self).__name__, complex.__repr__(self)[1:-1])

A: What you're wanting to do is actually very hard. I do not know of any python software that subclasses a type such as float or int and then does mathematics with it. I think that perhaps there is a better way to accomplish what you're trying to achieve without using a subclass of float. You should investigate alternatives.

A: Here are a couple of methods to get your testcases passing
def __str__(self):
    return str(FACTOR*self)
def __sub__(self, other):
    return self*FACTOR-other

obviously you have to also implement __add__, __mul__, etc...
Having said that - what is your use case? This seems like a weird thing to want to do


text:
Q: How to debug an event of new line (enter) in HTML I'm a newbie to web programming.
I've downloaded a free template of html responsive website & there is a funny behavior I'm trying to debug and find the source/cause
the site has a textbox and a button in a form -- every time I press enter in the textbox the website "reloads"/scrolls to the top.
Textbox has a listener on onkeyup event like this
<form action="#" method="post" class="site-block-subscribe">

        <input id="name" type="text" onkeyup="enableBtn()" class="form-control border-secondary text-white bg-transparent" aria-describedby="searchBtn">

            <button class="btn btn-primary" type="button" id="goBtn" disabled>Go</button>

</form>

event.preventDefault(); if the event.keyCode == 13 but it did nothing
function enableBtn(){
    name =  document.getElementById("name").value;

    if(name.trim().length > 0) {
        document.getElementById("goBtn").disabled = false;
        if(event.keyCode == 13) {
            event.preventDefault();
            document.getElementById("goBtn").click(); // perform the operation as if the GO button was clicked
        }
    }
    else {
        document.getElementById("goBtn").disabled = true;
    }
}

How can I debug and understand the flow within the files and different functions of the site once an enter is clicked. I don't think the problem I'm facing is in the code shared above - and don't have a clue which file/function creates the problem.
Desired result: on enter or button click, the user will "remain in the same exact page place" and see the returned result in a message.
Important Note: I don't have an IDE and am working with a text editor and Opera browser.

A: this article helped me solve the problem, hope it will do the same for you all
https://javascript.info/forms-submit
<form onsubmit="return false" action="#" method="post" class="site-block-subscribe">


text:
Q: Using setEditing does not get the tableview to go into edit mode I have used the following code (extract) in one tableview and works well however I can't get the same code to work in a second tableview: What I need to do is be able to move rows in the table.
@IBOutlet weak var reOrgApps: UIBarButtonItem!

override func viewDidLoad() {
    super.viewDidLoad()
    self.reOrgApps.action = #selector(self.reOrgApps(_:))
    self.reOrgApps.title = "ReOrg"
    self.setEditing(isEditingMode, animated: true)}

@IBAction func reOrgApps(_ sender: UIBarButtonItem) {
    if isEditingMode
    {
        isEditingMode = false
        self.reOrgApps.title = "ReOrg"
        self.tableView.isEditing = false
    }
    else
    {
        isEditingMode = true
        self.reOrgApps.title = "Done"
        self.tableView.isEditing = true
    }
    self.setEditing(isEditingMode, animated: true)
}

The button work as expected but the tableview does not go into edit mode
I have used the exact code in a different tableview and it work fine.
So I am missing something that I can't work out. Any help gratefully accepted
I know there have been similar questions and I have tried the various answers with no success.

A: I found the problem, I tried to pass a variable to :
  func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath, another: IndexPath)

Which was wrong and swift then simply ignored everything to do with Editing. Removing the , another: IndexPath.resolved the issue.
Fundamental mistake overlooked in the rush to get the class done.


text:
Q: Versioning with gulp I'm little confused in versioning process and I'm not sure if it's possible.
I have gulp task that bundles and minifies the js files but each time I have to change the folder path in .dest and hit gulp command to generate file (Like 1.0.0, 1.0.1, 1.1.0, 2.0.0 etc). I'mm using semantic versioning approach.
Now I want files like:
https://{url}/1.0.0/file.js
https://{url}/1.0.1/file.js
https://{url}/1.1.0/file.js
https://{url}/2.0.0/file.js
.....

So is there any way to automate this process? Like we have in npmjs or what is the best way for versioning?


text:
Q: How to setup a git repository on local network? How do I setup git on a machine on my LAN so that other developers can commit to my machine?

A: *

*Create a repo with git init on machine A

*Clone it from another machine B with
git clone username@machineB.ip.address.here:path/to/git/repo/here.git

this may prompt you for login credentials for machine B.
That's all. If you do git remote -v on machine B now, you will see that the remote repo is located at machine A

A: From a terminal on the machine to act as the "git server", assumed to be "your machine":
cd ~
mkdir git && cd git
mkdir my-project && cd my-project
git init --bare --shared
exit

On the developer machines:
git clone <USERNAME>@<IP_ADDRESS>:git/my-project

Notes: I would suggest creating a new user on your machine called "git", you can also clone from your usual username, like the other developers, too.


text:
Q: Android: Shared preferences not saving the state of the buttons I have a tab-host with three activities and in each activity I have  buttons.
On each button press I am changing the background drawable resource
So now How can I save the pressed state of each button in all three child activities so that when I move from one activity to the other, the button pressed state will be reflected on moving back. first activity -> all 2 buttons pressed -> go to 2nd activity -> come back to first activity -> all buttons in first activity should be in pressed state with the drawable resource changed
I have two background Images.
button press -> highlited background image -> second time press same button  ->changes to normal background Image
For the first time when I run the application and If I press the button the background image is getting changed. If I go to 2nd child activity and coming back so the button is in pressed state with changed drawable resource. so Its fine
for the second time If I press the same button and coming back to the same activity from second activity. here its not working
First child activity -> press button ->high lighted background image changes ->go to second tabhost child activity -> come back to first child activity -> button is  showing the same background image after pressing(this is fine)
the problem is
now you press the same button in first child activity ->  background image changes to normal ->go to second tabhost child activity -> come back to first child activity -> but the button background resource is in highlighted instead of normal
and even If I run the application once again the button is showing the highligted background image
the below code I am using in my first child activity
EDITED
public void onResume() {
    super.onResume();
    SharedPreferences sharedPreferences = this.getSharedPreferences(
            "sharedPreferences", MODE_PRIVATE);

    int which = sharedPreferences.getInt("sharedPreferences", 1);
    switch (which)
    {
        case 1:
            seatdirnbtn.setBackgroundResource(R.drawable.icon4); break;
        case 2:
            seatdirnbtn.setBackgroundResource(R.drawable.icon4hlt); break;
        default:
            seatdirnbtn.setBackgroundResource(R.drawable.icon4); break;
    }
}

public void onPause() {
    super.onPause();
     boolean isclick = false;
    SharedPreferences sharedPreferences = this.getSharedPreferences(
            "sharedPreferences", MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();

    if (isclick) {
        seatdirnbtn.setBackgroundResource(R.drawable.icon4hlt);

        editor.putInt("sharedPreferences", 2).commit();
    }
}

EDIT2
     public static boolean isclick = false;
private View.OnClickListener listner1 = new View.OnClickListener() {

    public void onClick(View v) {

    if (isclick) {
            seatdirnbtn.setBackgroundResource(R.drawable.icon4hlt);

        } else {
            seatdirnbtn.setBackgroundResource(R.drawable.icon4);
        }

        isclick = !isclick;
    }

};

A: Try this change:
if (isclick) {
        seatdirnbtn.setBackgroundResource(R.drawable.icon4hlt);
        editor.clear();
        editor.putInt("sharedPreferences", 2).commit();
    }
else {
        seatdirnbtn.setBackgroundResource(R.drawable.icon4);
        editor.clear();
        editor.putInt("sharedPreferences", 1).commit();
}

A: Here's what i meant:
boolean[] btnBool = new boolean[2]; // number of buttons

private View.OnClickListener listner1 = new View.OnClickListener() {
    public void onClick(View v) {
        toggleBtn(0); //zero refers to which index of the array for button button
        setDrawables();
    }

};

public void onResume() {
    super.onResume();
    toggleAllBtns();
    setDrawables();
}

private void toggleBtn(int index) {
    if(btnBool[index]) {
        btnBool[index] = false;
    } else {
        btnBool[index] = true;
    }
}

private void toggleAllBtns() {
    // first switch the values of the array
    for (int i = 0; i < btnBool.length; i++) {
        if(btnBool[i]) {
            btnBool[i] = false;
        } else {
            btnBool[i] = true;
        }
    }
}

private void setDrawables() {
    // then set drawables based on values
    if (btnBool[0]) {
        seatdirnbtn.setBackgroundResource(R.drawable.icon4);
    } else {
        seatdirnbtn.setBackgroundResource(R.drawable.icon4hlt);
    }
}


text:
Q: How do you win the zombies mode in Call of Duty Black ops The zombies game in Black ops (FPS one, not the top one) seems to have one obvious goal at the beginning: Restore the power. I've looked around the net and not seen any explanation of whether this is all you need to win or whether it then gets worse from there or what... Can anybody explain the progression of the game? are there limited rooms? Is there a win condition? Or do you just see how far you can go before being taken down?

A: The goal is to see how long you can last. Turning the power on just gives you access to fun toys around the map like traps and guns and whatever.

A: Zombie mode is a strange game. The only winning move is not to play
Ultimately, you will lose to the horde. The point is simply to see how long you will last. TUrning on the power activates the power up

A: Winning is not always achieved at finishing something; winning usually in the form of enjoyment. For this game, to be able to achieve that, you must play cooperatively. Don't do something stupid that would make you overrun by the zombies or piss-off your team-mates just like what those think they were already "Pros" on this game.
Always try to communicate with others and observe from those who already know this game.
Try to come-up with a good strategy and don't get in the way of other players. ^_^


text:
Q: GLMM with time-series covariance and binary response variable? I have a binary response variable that was measured at irregular time intervals for a number of individuals. I want to fit a GLMM that accounts for the time-series covariance within individuals.
I know that this is possible for Gaussian response variables by using the corCAR1 autocorrelation structure in the nlme package, but it seems that nlme does not fit logistic GLMMs. On the other hand, I can fit a logistic GLMM in the other popular R package for multilevel models, lme4, but that package doesn't seem to allow for specifying a time-series covariance structure.
Does anyone know of a way to fit this model in R? I know this model would be useful for many researchers, because I have encountered several researchers working on various problems who also wanted to fit such a model, but couldn't find a way to do it in R, so they resorted to less than ideal models (e.g., simply fitting a logistic GLMM without accounting for the time series).
I would greatly appreciate any advice!!!


text:
Q: Swift UI animated closure If I have a SwiftUI view declaration like:
ProfileView(userData, onDoneEdit: {
withAnimation {
        isEditingViewPresented.toggle()
    }
...
}, onCancel: { ... })

does anyone know if it can be implemented a custom annotation that let me have:
ProfileView(userData, onDoneEdit: { @withAnimation
    isEditingViewPresented.toggle()
    ...
    }, onCancel: { ... })

This question is more for learning purpose as I'm experimenting with SwiftUI.


text:
Q: Is there a way to directly read data from s3 for model training in tensorflow I have tfrecords in s3 and I want to directly read those files and feed them into tensorflow training.
    filename = "s3location"
    filename_queue = tf.train.string_input_producer([filename])
    with tf.Session() as sess:
      _, value = tf.TFRecordReader().read(filename_queue)

      feature = {'train/image': tf.FixedLenFeature([], tf.string),
            'train/label': tf.FixedLenFeature([], tf.int64)}

      features = tf.parse_single_example(value, features=feature)

      image = tf.decode_raw(features['train/image'], tf.float32)

      label = tf.cast(features['train/label'], tf.int32)

      image = tf.reshape(image, [32, 32, 1])

      images, labels = tf.train.shuffle_batch([image, label], batch_size=50, capacity=100, num_threads=1, min_after_dequeue=10)

But when I am trying to feed this sess.run(train, feed_dict={x:images, y: labels, hold_prob: 0.5})
I get the following error -
TypeError: The value of a feed cannot be a tf.Tensor object. Acceptable feed values include Python scalars, strings, lists, numpy ndarrays, or TensorHandles.
I have 2 questions -

*

*Is there a way to read data directly from s3 in tensorflow. looks like the support was added but I can't find any examples.

*If it is supported, is my approach correct?


text:
Q: How to refactoring legacy simgle web page/app to MVC with a modern js framework like backbone.js or angular.js I'd to know examples, recommendations and frameworks to start in a right way to refractory a single page web app with html, css and js files (jquery) in a MVC/MVP js application that needs to  works in a ie 7 at least (this is mandatory), but if its possible I'd like that this  app could works well in others browsers too.
The code is a lot of ifs and else and each one use the document.write() js method to write page elements. To 90's style yet, like bellow:
if ($auth$ == 19) {
   document.write("
");
   document.write("");
   document.write("$username$ you cannot access your account.
Please contact your Security Administrator or Help Desk.");
        document.write("    	");
        document.write("
");
}

80% percent of this web app is written in this way depends of the external variable values
What are the js modern frameworks or a modern approach that let me able to prototype this in a MVC/MVP js way?
Some references? tutorials?
I'm glad for your help, thanks!

A: I spent quite a bit of time researching whats available.  KnockoutJS has a great tutorial site.  Then I found AngularJS which is much more complex because it does so much more.  Angular is a full framework to do your routing, databinding (without observables), as well as letting you build your app domain centric by using directives.
Another thing I love about the Angular team is that they are all about testing.  They released the Testacular test runner which watches your file system and when any file changes, it runs your unit tests in a browser of your choosing.  Automated browser based unit testing, I became hooked pretty quickly.
I have read many people not preferring AngularJS because the there are so many other bits out there that are constantly evolving that are focused on specific aspects of SPA, such as historyJS, backboneJS, sammyJS...Each of these have their own focus and may do the job better.  I personally trust AngularJS as its backed by google, and its community is really growing.
John Lindquest has a great set of tutorials he just started recently at egghead.io.
There is a modules community at ngmodules.org which demonstrates the ease of building expansion modules into an angular app.
The youtube page for AngularJS has been very helpful for me to keep up with the suggested structures for your angular app.
I would suggest checking them out.  Once you wrap your head around doing it the angular way, you really change your way of thinking.


text:
Q: What is Theta Protocol? We're hearing Theta Protocol in Marvel's Agents of S.H.I.E.L.D. TV series for some time (Coulson was hiding it from the team). In the last episode S02E19 of the TV series, this conversation happened regarding Theta Protocol:

 Maria Hill: Last Thing. Theta Protocol. Is it ready?
Coulson: Yes, it is. Time to bring in the Avengers.

What exactly is Theta Protocol? This clearly sets up the events of Avengers: Age of Ultron movie (which I have already watched), but I am unable to find a picture of Theta Protocol in the movie.

A: Based on last night's Agents of SHIELD, it appears that Theta Protocol had to do with the Helicarrier that was being stored in an unknown SHIELD base. One of the Koenig brothers was running the base for Coulson and Fury.
So I would assume by saying that Theta was ready, Coulson was informing Fury that the carrier was ready to be put into play if necessary.

A: After the episode Scars (S02E20), we can definitively say that Theta Protocol was the restoration of the Helicarrier. It was kept a secret in case any other HYDRA agents were still active within SHIELD.


text:
Q: Image management: When to recycle bitmaps? I've read When should I recycle a bitmap using LRU Cache and several other questions here, and am still struggling with OutOfMemoryExceptions. But I'm getting ahead of myself.
I'm taking over an app that displays a tremendous amount of images. Primarily this is done in an grid view, using a subclassed ArrayAdapter. Images are loaded off the web, using an Asynchronous task, and stored in a cache (which I'll eventually switch to an LRU Cache).
Each picture in the grid view can lead to a detailed view of the image (with more details/UI components), which can lead to another grid view. Eventually there are so many views on the stack that we run out of memory. The cache is being completely flushed of images through the Application.onLowMemory() function, yet despite that, we're running out of memory.
The adapters never check to see if anything is in the cache when recycling views, and I'm sure that could buy me a little bit of breathing room, but it feels like the big gain would be in recycling images in Activities that are 4+ layers back in the stack. The problem is, I'm not sure how to accomplish this. In the onPause routine?
It seems like when the onPause routine is run (switching to the next Activity layer), that the images it was showing will still be in the cache, so they'll not get recycled then. Do I need to pull up the Activity stack and call some custom routine on the older activities at that point to tell them to recycle images?
Additionally, I'm trying to support API levels 9-19. The LRU Cache is provided via the support library for the lower APIs, the full featured one was added in API 12, but apparently if I use the support version, any device running API 12+ won't use the newer version - should I be writing custom code to detect the API version and then use some sort of LRUCache factory to create the version I need? Do I need to write custom code to only do the bitmap recycling on APIs lower than 11?

A: The solution I eventually went with was this:
I added the support LRU Cache, and then also added Jake Wharton's DiskLRU Cache. Before images were downloaded from the web, first I checked the memory LRUCache, and then the DiskLRUCache. Any image downloaded was stored in both. Next, every Fragment and Activity that owned any images was registered as a listener to the LRU Cache. If the LRU Cache was going to evict an image to make room for another image, it sent a notification to all the listening Fragments and Activities. These listeners then marked their image as 'dirty', meaning they needed to be re-downloaded, and also then called recycle() on the bitmap.
This approach seems to work pretty well overall. The app can still get bogged down with garbage collection and eventually after a long time it's still possible to run out of memory on older phones, but it's hard to see where I could improve it any further.


text:
Q: API to solve the CORS problem ('Access-Control-Allow-Origin) I am currently on an API where I am trying to retrieve data with the "GET" method.
I used the AXIOS library to retrieve my data.
But the problem I'm having is that when I want to retrieve it I get this error message in my console that blocks me with CORS: "Access to XMLHttpRequest at 'http://localhost:8080/champions' from origin 'http://localhost:8081' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource."
My function to retrieve my data :
function Champions() {
    const token = "...."

    useEffect(() => {
      const headers = {
        Authorization: `Bearer ${token}`,
        "Access-Control-Allow-Origin" :"http://localhost:8080/champions"
      };
      axios
        .get("http://localhost:8080/champions", { headers })
        .then((response) => console.log(response));
    }, []);

    return (

Coucou

    )
  }

export default Champions;

proxy attempt (non-functional) :
const { createProxyMiddleware } = require("http-proxy-middleware")

module.exports = app =>  {
    app.use(
        '/api',
        createProxyMiddleware('/champions',
        {
            target: "http://localhost:8080",
            ChangeOrigin: true,
        })
    )
}

Should I make a proxy? (I tried different tutorials without success...)
Or should I add something in my Headers function that refers to 'Access-Control-Allow-Origin'?

A: I think CORS issue is common in Chrome. Came across an article, which might help you for atleast in the development phase(Not tried it though).


text:
Q: Image Reveal Animation On Swiper Slider Using Gsap I am trying Image Reveal animation on swiper slider I achieve to get the animation its working fine in the first slide I am stuck in when the change to other slides the animations are not working I have used  event for changing other slides I am trying to get when clicking on next arrow the animation start. when there is slide change. I am stuck in these please someone point me in the right direction.  Thanks in advance.
Achieve Code: codepen

$(document).ready(function() {
     var mainslider = new Swiper('.slider-main', {
       pagination: {
         el: '.swiper-pagination',
         type: 'progressbar',
       },
       navigation: {
         nextEl: '.swiper-button-next',
         prevEl: '.swiper-button-prev',
       },
     });

  // click next arrow for another slide animation
  mainslider.on('slideChange', function () {
   var controller2 = new ScrollMagic.Controller();
   $(".ansa-landing-wrap").each(function() {
    var tl = new TimelineMax();
    var cov = $(this).find(".cover");
    var img = $(this).find(".ansa-slider");
     tl.from(cov, 1, { scaleX: 0, transformOrigin: "left" });
     tl.to(cov, 1, { scaleX: 0, transformOrigin: "right" }, "reveal");
     tl.from(img, 1, { opacity: 0 }, "reveal");
    var scene = new ScrollMagic.Scene({
     triggerElement: this,
     triggerHook: 0.7,
    })
    .setTween(tl)
    .addIndicators()
    .addTo(controller2);
   });
   alert('testing');
  });

  //Slider Animationon first slide
   var controller1 = new ScrollMagic.Controller();
 $(".slider-main").each(function() {
    var tl = new TimelineMax();
    var cov = $(this).find(".cover");
    var img = $(this).find(".img-slider");
    tl.from(cov, 1, { scaleX: 0, transformOrigin: "left" });
    tl.to(cov, 1, { scaleX: 0, transformOrigin: "right" }, "reveal");
    tl.from(img, 1, { opacity: 0 }, "reveal");
    var scene = new ScrollMagic.Scene({
      triggerElement: this,
      triggerHook: 0.7
    })
     .setTween(tl)
     .addIndicators()
     .addTo(controller1);
 });

  });
.swiper-slide {
    text-align: center;
    font-size: 18px;
    background: #fff;
    display: flex;
    justify-content: center;
    align-items: flex-end;
}
.swiper-pagination-progressbar {
 bottom: 0;
}

.swiper-container-horizontal>.swiper-pagination-progressbar {
    top: auto;
   bottom: 48px;
}
.swiper-container-horizontal>.swiper-pagination-progressbar {
    width: 20%;
    height: 4px;
 left: 48%;
 top: 95%;
    background-color: rgba(232, 227, 227, 0.2);
}
.swiper-pagination-progressbar .swiper-pagination-progressbar-fill {
    width: 100%;
    background-color: #f06a44;
 }
h2 {
    font-family: sans-serif;
    font-size: 50px;
    font-weight: bold;
    color: #ffffff;
    text-align: left;
}
.swiper-slide:nth-Child(even){
    background: #cccccc;
}

.swiper-slide:nth-Child(odd){
    background: #666666;
}

.caption {
    text-align: center;
    padding-top: 20px;
}
.counter, .counter span {
    position:relative;
}
.counter .next, .counter .count {
    position:absolute;
}
.counter .next {
    transform:translateY(-12px);
    left:0;
}
.sl {
    position: relative;
    width: 100%;
    height: calc(100vh - 100px);
    z-index: 1;
}
 img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}
.cover {
    position: absolute;
    width: 100%;
    height: 100%;
    background: #000000;
}

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.5.0/css/swiper.min.css">


text:
Q: Number Sense Math I'm third grade. Shay.
I need help explaining how to get this answer.
Question: Kyle is thinking of a four digit number in which all the digits are different and ¾ of the digits are odd. What could Kyle number be.

A: When you have a question like this, the first thing to do is find out what the question is asking.
Ask yourself:

*

*Do I know what a four-digit number is?  Can I think of an example?

*Do I know what an odd digit is?  Can I think of an example?

*Do I know what "All the digits are different" means? Can I think of an example?

*Do I know what "¾ of the digits" means?

*Do I know what "¾ of the digits are odd" means?  Can I think of an example?

If you discover that you don't know one of those things, then the next thing to do is to find out what it means.  Nobody can answer a question if they don't understand what the question is asking for!
Then if you still don't know how to solve the problem, try solving a simpler problem.  Maybe you can't find Kyle's number,  but can you find a four-digit number where all the digits are different?  Can you find a number where ¾ of the digits are odd?  Can you find one where ¾ of the digits are odd, and  the digits aren't all different?
As you add more conditions, perhaps the problem becomes more difficult, but at the same time you have more practice solving problems of the same kind, and you get better at doing it.  After solving some simpler problems of the same kind, you might be able to solve the original problem when you come back to it.


text:
Q: Windows 7 Hiberate Returns to Ubuntu I recently dual booted my laptop with Ubuntu and Windows 7. Whenever I close the top of my laptop while in Windows it goes to hibernate, however it returns back to the Ubuntu log in screen. Grub doesn't even show up to allow me to choose which system to boot back to.
How can I fix this problem? Thanks.

A: *

*If you reboot from the ubuntu screen and select windows in grub, you will (probably) get the pre-hibernation state.

*If you make windows your default OS in grub, you will probably replace the "hibernate in windows -> wake up in ubuntu" problem with "hibernate in ubuntu -> wake up in windows" one.


text:
Q: website acceleration, loading other web pages resource? I am wondering if such technology exists. In PageA, when the loading is completed, PageA began to load resouces in PageB, which is very likely to be accessed after some time(predict).
If the loading is succeeded, then most of the resource in PageB will be already in cache.
The resource including swf, js, images, etc.
Thanks.

A: Yes, it exists, some browsers do this, it's called prefetching. However it's often not done by default in normal browsing (though DNS prefetching often is)...it's mainly used for offline viewing support.

A: I always preload images when I'm pretty sure about the next page. You can use this code at the end of your page:
<script type="text/javascript">
preload=new Image();
preload.src="future_image.jpg";
</script>

A: Yes, some web sites use techniques of prefetching to enhance the loading time of certain web pages. Just think of an photo gallery, slide show, or a series of web pages in general where it is very likely that the next photo/slide/page is viewed as well.
In that case you could prefetch the resources of the next page on the current page to lower the remaining loading time of the next page.
Common techniques are

*

*the prefetch link relation that was introduced by Mozilla (I'm not sure what browsers support this)

*using JavaScript to load images (see Habax has already mentioned) or even whole web pages (e.g. hidden frames).

But besides the benefits of lower loading times of subsequent pages you should also be aware that using prefetching can also prefetch resources that are not used (i.e. the assumption that the user does visit the next page is wrong).


text:
Q: Docker ERROR: Error processing tar file(exit status 1): unexpected EOF I needed space and executed: docker rmi $(docker images -f "dangling=true" -q)
Since then I can't with docker-compose: docker-compose build, I get the error: ERROR: Error processing tar file(exit status 1): unexpected EOF.
I tried to remove all images, reinstall docker, but nothing will do: always the same error, after quite some time.
I built on another system and it worked, which suggests that this is a wrong-state issue.
Any idea what I should clean?
Using:
▶ docker version
Client:
 Version:      17.03.0-ce
 API version:  1.24 (downgraded from 1.26)
 Go version:   go1.7.5
 Git commit:   3a232c8
 Built:        Tue Feb 28 08:01:32 2017
 OS/Arch:      linux/amd64

Server:
 Version:      1.12.6
 API version:  1.24 (minimum version )
 Go version:   go1.6.2
 Git commit:   78d1802
 Built:        Tue Jan 31 23:35:14 2017
 OS/Arch:      linux/amd64
 Experimental: false

▶ docker-compose version
docker-compose version 1.11.2, build dfed245
docker-py version: 2.1.0
CPython version: 2.7.13
OpenSSL version: OpenSSL 1.0.1t  3 May 2016

A: I had the same issue and the approved answer didn't work for me.
Turns out I had a file with permissions which didn't allow the user running docker-compose to read it. After removing the file everything was OK

A: For me it was a permission error.
I walked against the same exact issue as PR,
ERROR: Error processing tar file(exit status 1): unexpected EOF
My solution is dirty but worked for me
chown -R 777 /foo/bar/project
You almost always want to avoid to set permissions on 777, 655 is more reasonable.
0 = ---
1 = --x
2 = -w-
3 = -wx
4 = r-
5 = r-x
6 = rw-
7 = rwx

A more detailed explanation can be found here:
https://www.pluralsight.com/blog/it-ops/linux-file-permissions

A: Solving this error for good
docker build needs read access to every file in the context directory tree. To avoid permission issues, add all your mounted directories to .dockerignore file except those required for the build. For example, for this docker-compose file:
version: '3'
services:
    myservice:
        build: .
    volumes:
        - './etc:/etc/myservice'
        - './log:/var/log/myservice'

Add a .dockerignore file with this content:
/etc
/log

The problem will go away no matter the permissions of the files in your mounted directories.
How to get a more informative error
The docker-compose error is not very informative so you can try to run docker on each build just to get detailed information:
$ docker build .

You will get an error like this:
error checking context: 'no permission to read from '/home/david/docker/myservice/log/2020161.log'.

A: There is an built in command to remove unused images (Version 1.13+):
docker image prune

Now to handle the situation:

*

*Stop Docker Service
systemctl stop docker

*Backup /var/lib/docker then:

*Remove /var/lib/docker
Caution: This will remove images, containers, volumes, ... make sure you back it up first.
rm -rf /var/lib/docker

*Start Docker service
systemctl start docker

Update:
As noted in the other answer, In somecases it might be file permissions issue. Please review permissions.

A: For me the issue turned out that a Docker Pull was hung, so I CTRL+C'd out of it and tried again. Same error message.
In the end I found some files owned by root in this directory. Giving the files proper permissions fixed the issue.
chown -R <username>:<group> /var/lib/docker/tmp

*

*MAC Docker version 17.12.0-ce, build c97c6d6

A: there could be several different problems. You can find out the problem by checking the issue that docker build is throwing.
The problem is that docker-compose build will suppress the information of the issue. To find out what the issue is
do not use:
docker-compose build XXX

instead, open your docker-compose.yml, find the build: tag of the service is giving you an issue, e.g.
services:
   yourservice:
       build: yourservice-directory/

and then run:
docker build yourservice-directory

after this you will see what is the issue.

A: Reference:
https://medium.com/the-code-review/clean-out-your-docker-images-containers-and-volumes-with-single-commands-b8e38253c271
1. Clean up containers, images, volumes and networks on your system:
docker system prune --all --force --volumes
2. docker-compose up

A: If you have tried looking through permissions, docker reset, docker system prune, deleting all containers, deleting all images (dangling or otherwise), reading about everything that there is surrounding this issue and have had no success. Try uninstalling docker and re-installing the stable version.
Although, the error I was struggling with was : Error processing tar file(exit status 1): mkdir /some/path/name: no such file or directory

A: In my case, the problem was a .dump file created by one of my project's scripts.
docker-compose passes the context to the engine as a tar file, therefore, the build command was packing a tar (the .dump file) inside another tar file (the docker context) hence throwing an unexpected EOF on the context.
Since I don't need the .dump file in the container, I added it to my .dockerignore file.

A: I was having the same issue when i changed the Dockerfile location in a python project. I tried the accepted answer and didn't work for me.
I resolved the problem by running :
find . | grep -E "(__pycache__|\.pyc|\.pyo$)" | xargs sudo rm -r

On the project root.
The problem was that docker-compose build  was trying to read files inside pycache folders.
Maybe this also can be fixed with a proper use of .dockerignore but i dind't try it
Hope this helps.
Saludos.

A: Try increasing the memory for Docker, it fixed the issue for me.
Docker memory setting in Preferences was set to 2GB, so when pulling the ~3GB image, I was getting exactly this error:
$ docker pull skymindops/skil-ce
latest: Pulling from skymindops/skil-ce
118c5f2883d6: Pull complete
3d199b2e6224: Extracting [==================================================>]  2.902GB/2.902GB
failed to register layer: Error processing tar file(exit status 1): unexpected EOF

Increasing the memory limit fixed it (I also increased the swap, but unsure was it required or not).

A: I tried everything from rebooting, reinstalling Docker, and purging /var/lib/docker.
My cause was  something corrupting the build context in my project. After I ran git clean to reset the project directory back to its original state, I was able to docker-compose.
Run git clean -iXd in your project's root to interactively git clean.
Edit: after a while, it happened again. This time, git clean didn't fix it. I'm pretty sure it only happens on Ubuntu. My arch coworkers have never encountered it.

A: I found a temporary solution:

*

*Ensure specify the image name on docker-compose.yml
for example, specify the image name and container_name as django_practice_db/django_practice_web
services:
  django_practice_db:
    image: postgres
    container_name: django_practice_db
  django_practice_web:
    container_name: django_practice_web
    build: .
    command: pipenv run python manage.py runserver 0.0.0.0:8000

*Copy the project file to another place

*Go inside the copied project directory

*Execute docker-compose build

*Go back to the original project directory

*Execute docker-compose up
Not sure why I can build images when I change the folder path.

A: Another potential cause of this, especially if you're seeing an error like
Error processing tar file(exit status 1): write /code/node_modules/xxx: no space left on device

You might want to check the "disk image size" in the Docker application. You might need to increase the disk size.

A: I had the same error in Ubuntu: Ran below command and it worked (just make sure to start again once you are done):
/opt/McAfee/ens/tp/init/mfetpd-control.sh stop

A: Solve for me. You need have your user in docker group (usermod -aG docker $USER):
sudo chmod -R 775 .
sudo chown -R : .

A: This question is a little bit old now, but I had this problem today and what I figured out was next. When I was exporting my image as a tar file with next command:
docker save -o exportedfile.tar myimage/version:latest

I exported this in Linux shell instead of CMD. When I do it in CMD everything works fine. I guess there is some difference in -o flag between Windows and Linux.

A: For me, I replaced the .tar file and tried to build again and it worked.

A: I had the same issue as OP, but neither the approved answer nor the top voted answer did it for me.
What pointed me in the right direction was a comment under the approved answer by JGlass saying that after closing Notepad++ everything worked properly.
I wasn't using Notepad++, but I did have Visual Studio open. I didn't have any files open either, but I did have the project open in the solution explorer. After closing Visual Studio, the issue was resolved.
In my case it wasn't a permission issue, but Docker was unable to access the file because another application was using it.
Hopes this helps someone.


text:
Q: Two dataframes broadcast together in multiple subplots I want to plot 5 different subplots, one for each year of data.  For each year, I want to show the DEMs and REPs for each county.  I have written the following code so far:
fig = plt.figure(figsize=(13,10))

plt.subplot(3, 2, 1)
plt.bar(data=districts_2018[['DEM', 'REP']],
        x=districts_2018.index,
        height=(districts_2018[['DEM', 'REP']]))

plt.subplot(3, 2, 2)
plt.bar(data=districts_2017[['DEM', 'REP']],
        x=districts_2017.index,
        height=districts_2017['DEM'])

plt.subplot(3, 2, 3)
plt.bar(data=districts_2016[['DEM', 'REP']],
        x=districts_2016.index,
        height=districts_2016['DEM'])

plt.subplot(3, 2, 4)
plt.bar(data=districts_2015[['DEM', 'REP']],
        x=districts_2015.index,
        height=districts_2015['DEM'])

plt.subplot(3, 2, 5)
plt.bar(data=districts_2014[['DEM', 'REP']],
        x=districts_2014.index,
        height=districts_2014['DEM'])

plt.tight_layout();

However, as in the case of the first subplot (3,2,1) I get the error:
ValueError: shape mismatch: objects cannot be broadcast to a single shape.  This code works if I only set the height to districts_2018['DEM'] but then that only shows the DEMs and not the REPs.

A: You may directly use the pandas wrapper to plot grouped bar plots. Set the ax to the respective subplot you want the plot to appear in.
fig, axes = plt.subplots(3,2,figsize=(13,10))
for ax, df in zip(axes.flat, [districts_2018, districts_2017, ....])
    df[['DEM', 'REP']].plot.bar(ax=ax)


text:
Q: Add values from pandas dataframe to a list I have a dataframe where one column in that dataframe has the GPA of first-year students. I want to loop through this column and append to a list of lists all values that fall within 0.4 units of each other. For example, if I have the values (0.4, 0.6, 0.8, 3, 3.4), then I want my list to be [[0.4,0.6,0.8], [3, 3.4]].
This is the code I have tried.
averages = [[] for w in range(len(df['GPA_year1'])//4)]

small = min(df['GPA_year1']) + 0.4

for i in range(len(averages)):

    for y in range(len(df['GPA_year1'])):

        if small - 0.4 <= df['GPA_year1'][y] <= (small + 0.4):

            averages[i].append(df['GPA_year1'][y])

    small = small + 0.4

However, when I run this code in Jupyter Notebook, it seems to run forever, which makes me think that there may be an infinite loop somewhere (?) but I'm not sure where the infinite loop might be.
Here is the dataframe

A: From your expected result I see that:

*

*The first bin contains elements in the range [0.4 - 0.8].

*The next bin starts from 3.0.

So you:

*

*Don't want one-side-open bins (the first bin is closed at both sides).

*Want neither "ëmpty bins" nor "adjacent ranges" (e.g. [0.4 - 0.8), then [0.8 - 1.2)
and so on.

You want rather something like this:

*

*Set the üpper limit to the lowest element in the source list + 0.4.

*Put in the first "bin" elements <= limit (append this list to averages).

*Drop these elements from the list.

*Repeat the above procedure while the list is not empty.

I also assume that the result should be a plain Python list of lists.
To get this result, try the following code:
averages = []
src = df['GPA_year1'].sort_values()
while not src.empty:
    limit = src.min() + 0.4
    currBin = src[src <= limit]
    averages.append(currBin.to_list())
    src.drop(currBin.index, inplace=True)

This code should run quicker, beacause:

*

*Due to sort_values() there is no need for the inner loop.

*All values for the current bin are selected in a single instruction.

*Dropping of "used" values is performed also in a single instruction.

For GPA_year1 column from your DataFrame this code generates:
[[0.74], [1.95, 2.18, 2.34], [3.23, 3.23, 3.44, 3.49], [3.64, 3.78, 3.82]]

One more remark concerning your code:
averages = [[] for w in range(len(df['GPA_year1'])//4)]

looks strange.
How do you know that the output list will contain just 4 lists?
Accidentally this is the case for your sample data, but consider such
case that:

*

*One part of values will be "very bad" (all around some lower limit).

*The second part of values will be "very good" (all around some upper
limit).

Then the number of "bins" will be just 2 (not 4).

A: This is my way: assuming df is your Dataframe:
GPA_year1 = df['GPA_year1'].tolist()
GPA_year1 = [3.82, 3.64, 1.95, 3.44, 2.18, 3.49, 3.78, 3.23, 0.74, 3.23, 0.74, 3.23, 2.34]

Sort the list:
GPA_year1.sort()

initialize the averages list with the first element
averages = [[GPA_year1[0]]]

loop trough your list:
for x, y in zip(GPA_year1, GPA_year1[1:]):
    if y - x <= 0.4:
        averages[-1].append(y)
    else:
        averages.append([y]) #if not create a new sublist
print(averages)
# [[0.74, 0.74], [1.95, 2.18, 2.34], [3.23, 3.23, 3.23, 3.44, 3.49, 3.64, 3.78, 3.82]]


text:
Q: Post запрос для регистрации. Андроид Прошу совета в следующем вопросе.
Нужно реализовать регистрацию пользователя. Решил попробовать библиотеку Retrofit, но приложение упало.
P.S: строго не судите, я новичек)
Вот код
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
    private static final String TAG = "this";
    private final String baseUrl = "http://u1938.blue.elastictech.org/api/users";

    private Gson gson = new GsonBuilder().create();
    private Retrofit retrofit = new Retrofit.Builder()
            .addConverterFactory(GsonConverterFactory.create(gson))
            .baseUrl(baseUrl)
            .build();

    private Link parse = (Link) retrofit.create(List.class);

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

        Intent intent = getIntent();
        intent.getExtras();

        buttonRegistration2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (editPassword != editPassword2) {
                    Toast.makeText(RegistrationActivity.this, "Пароли не совпадают. Повторите попытку", Toast.LENGTH_SHORT).show();
                }
                else {
                    Map<String, String> mapJson = new HashMap<String, String>();
                    mapJson.put("email", editEmail.getText().toString());
                    mapJson.put("name", editUserName.getText().toString());
                    mapJson.put("password", editPassword.getText().toString());
                    mapJson.put("contact_number", editNumber.getText().toString());

                    Call<Object> call = parse.parseMethod(mapJson);

                    try {
                        Response<Object> response = call.execute();
                        Map<String, String> map = gson.fromJson(response.body().toString(), Map.class);

                        for (Map.Entry e : map.entrySet())
                        {
                            System.out.println(e.getKey() + "" + e.getValue());
                            Log.e(TAG, "Object");
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

            }
        });
    }

Интерфейс
interface Link {
    @FormUrlEncoded
    @POST("/users")
    Call<Object> parseMethod(@FieldMap Map<String, String> map);
}

Ошибка
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.idrisov.mypost/com.example.idrisov.mypost.RegistrationActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
                                                                              at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2849)

A: Вы забыли в onCreate проинициализировать переменную buttonRegistration2 после setContentView(R.layout.registration_activity);
Добавьте buttonRegistration2 = findViewById(R.id.your_buttton_id);, где your_buttton_id - id, указанный для кнопки в registration_activity.xml


text:
Q: Advices on how to structure a database I have to add tables in my database in order to stock information like this :
user 1
2015:
- 3 times at bowling
- 10 times at cinema
2014:
- 2 times at bowling
- 3 times at the restaurant
- 5 times at cinema
user 2
2015:
- 1 time at the restaurant
- 3 times at the cinema
2014:
- 2 times at bowling
2013:
- 3 times at the restaurant
- 1 time at bowling

user 1
2015:
- 1 time doctor
- 1 time dentist
2014:
- 2 times doctor
user 2
2015:
- 2 times doctor
- 1 time ophthalmologist

The number of years differ according to the users, the number of hobbies, doctor and so on.
There is also global data on the user which differ from one year to another (for instance the number of vaacation days).
I thought to this structure :
Global table :
userId - year - nbHolidays -

Hobbies table :
userId - year - activityId - numberOfTimes

medical table :
userId - year - kindDoctorId - numberOfTimes

I have not a lot of experience with database conception, do you think this is a good structure ?


text:
Q: How to sort a subset of a dataframe Please find attached my sample data set.
What I really want to achieve with this is to create a data frame that first sorts the data based on period on ascending order and within each period that data is sorted again by the descending order of count of case (grouped by period,region,manager,employee)
So far, I have done up to this but it does not give me what I want.
I am planning to plot this values, so that's why I need to sort it on ascending order first and within each of that I want the data to be sorted in descending order.
SampleRADN <- read_excel("C:/Users/xxx/Documents/Exercises/PBIR/SampleRADN.xlsx")
df1<-unique(data.frame(SampleRADN))
library(dplyr)
df2<-df1%>%count(period,region,manager,employee)
df3<-df2[order(df2$period, -df2$n)

Any help is greatly appreciated.

A: @NelsonGon thank you very much for pointing out that the users need to provide the data in a better way so that the whoever is looking for a solution can always both access the data and answer. I honestly did not think of that. However, my sample data has more than 600+ rows and I don't know how to replicate the sample data of this size other than providing it through a link.
However, I solved this problem by doing following
library(openxlsx)
library(dplyr)
library(tidyverse)
df <- read.xlsx("C:/Users/smpao1/Documents/Exercises/PBIR/SampleRADN.xlsx")
df1<-data.frame(df)
df2<-df1%>%count(period,region)
df3<-df2[order(df2$period, -df2$n),]
df4<-df1%>%count(period,region,manager,employee)
df5<-df4[order(df4$period, -df4$n),]
df6<-left_join(df3,df5,by=c("period"="period","region"="region"))
df7<-df6%>% select(period, region, manager, employee,n.y)

A: If I understand correctly, the OP wants to sort the data by ascending period and within each period by the descending order of count of case (grouped by period, region, manager, employee).
The solution in OP's own answer is way too complicated. My suggestion is to add the group counts to the data frame and sort by period and count.
dplyr
library(dplyr)
df2 <- readxl::read_xlsx("SampleRADN.xlsx") %>%
  add_count(period, region, manager, employee, name = "count") %>%
  arrange(period, -count)
df2

# A tibble: 369 x 6
   region  period manager employee case      count
   <chr>    <dbl> <chr>   <chr>    <chr>     <int>
 1 Eastern      1 RP      DL       2019-467     12
 2 Eastern      1 RP      DL       2019-591     12
 3 Eastern      1 RP      DL       2019-1009    12
 4 Eastern      1 RP      DL       2019-1747    12
 5 Eastern      1 RP      DL       2019-2536    12
 6 Eastern      1 RP      DL       2019-2579    12
 7 Eastern      1 RP      DL       2019-683     12
 8 Eastern      1 RP      DL       2019-1127    12
 9 Eastern      1 RP      DL       2019-1748    12
10 Eastern      1 RP      DL       2019-1749    12
# ... with 359 more rows

data.table
library(data.table)
df <- readxl::read_xlsx("SampleRADN.xlsx")
setDT(df)[, count := .N, by = .(period, region, manager, employee)]
setorder(df, period, -count)
df

      region period manager employee       case count
  1: Eastern      1      RP       DL   2019-467    12
  2: Eastern      1      RP       DL   2019-591    12
  3: Eastern      1      RP       DL  2019-1009    12
  4: Eastern      1      RP       DL  2019-1747    12
  5: Eastern      1      RP       DL  2019-2536    12
 ---
365: Central      6      TG       RK 2019-28005     1
366: Central      6      EL       MP 2019-28363     1
367: Central      6      SS       DC 2019-29488     1
368: Central      6      JT       LV 2019-30283     1
369: Central      6      KJ       SL 2019-27948     1


text:
Q: How to restrict output of a neural net to a specific range? I'm using Keras for a regression task and want to restrict my output to a range (say between 1 and 10)
Is there a way to ensure this?

A: Normalize your outputs so they are in the range 0, 1. Make sure your normalization function lets you transform them back later.
The sigmoid activation function always outputs between 0, 1. Just make sure your last layer has sigmoid activation to restrict your output into that range. Now you can take your outputs and transform them back into the range you wanted.
You could also look into writing your own activation function to transform your data.

A: Write a custom activation function like this
# a simple custom activation
from keras import backend as BK
def mapping_to_target_range( x, target_min=1, target_max=10 ) :
    x02 = BK.tanh(x) + 1 # x in range(0,2)
    scale = ( target_max-target_min )/2.
    return  x02 * scale + target_min

# create a simple model
from keras.layers import Input, Dense
from keras.models import Model
x = Input(shape=(1000,))
y = Dense(4, activation=mapping_to_target_range )(x)
model = Model(inputs=x, outputs=y)

# testing
import numpy as np
a = np.random.randn(10,1000)
b = model.predict(a)
print b.min(), b.max()

And you are expected to see the min and max values of b are very close to 1 and 10, respectively.


text:
Q: Converting dataframe to dictionary I have a dataframe which includes two columns, one with state names and the other with state abbreviation, as below:

I'm trying to convert this into a dictionary that looks like this:
{AL: Alabama, AK: Alaska, AZ: Arizona, AR: Arkansas, CA: California, CO: Colorado, CT: Connecticut}
I ran the following code:
x = dic.set_index('Abbreviation').T.to_dict('records')

But it converts my dataframe to a list of dictionary, like so:
[{AL: Alabama, AK: Alaska, AZ: Arizona, AR: Arkansas, CA: California, CO: Colorado, CT: Connecticut}]
Is there a way I can convert it to just a dictionary? All the other orientation in the to_dict() function includes the index, which I do not need.
I'm sure this is a very simple problem, but I've been having some trouble so any help would be appreciated. Many thanks in advance!

A: Another solution:
d = dict(zip(df["Abbreviation"], df["State"]))
print(d)

Prints:
{
    "AL": "Alabama",
    "AK": "Alaska",
    "AZ": "Arizona",
    "AR": "Arkansas",
    "CA": "California",
    "CO": "Colorado",
    "CT": "Connecticut",
}

A: Use a Series:
x = dic.set_index('Abbreviation')['State'].to_dict()

output:
{'AL': 'Alabama',
 'AK': 'Alaska',
 'AZ': 'Arizona',
 'AR': 'Arkansas',
 'CA': 'California',
 'CO': 'Colorado',
 'CT': 'Connecticut'}


text:
Q: Redirecting from Sub Directory to Root Directory I have 2 directories in my public_html directory as MainSite & OtherSite.
Now I want the following:
1 If  a user enters my domain on it's root address, for instance www.example.com he must be redirected to my MainSite directory as I have all of the contents there.
2- But if user enters a subaddress, i.e. www.example.com/othersite, then he must be redirected to the OtherSite directory.
I know 1 can be done easily by pointing this folder for my main domain then in this case where to put my htaccess file and what do I write in that?
I don't want any other directory or sub directory contents to be disturbed.
So, what is a better approach?


text: Q: How could the T-1000 use time travel technology? It is established in The Terminator that anything travelling through time needs to be encased in living tissue. However, the T-1000 just seems to be made of liquid metal. Does the movie ever address this, or is it just a giant plot hole?


text:
Q: PHP Config.ini file parsing with multi-level arrays I have a config.ini file that has a number of these types of variables:
site.social.twitter = "URL"
site.social.facebook = "URL"
site.social.google-plus = "URL"

I use PHP's built-in function to parse the INI.
$config = parse_ini_file(__DIR__ ."/../config.ini");

The next step is to get this (site.social.twitter)
to become an array.
$config['site']['social']['twitter']

You could just 'explode()', but it doesn't quite get there. Is there any simpler solutions to something like this?

A: OK, so you can look at using sections and the array syntax for INI files such as:
[site]
social[twitter] = URL
social[facebook] = URL
social[google-plus] = URL

Then pass true as the second argument:
$config = parse_ini_file(__DIR__ ."/../config.ini", true);

Or to build using your existing INI structure (adapted from How to access and manipulate multi-dimensional array by key names / path?):
$array = array();

foreach($config as $path => $value) {
    $temp = &$array;
    foreach(explode('.', $path) as $key) {
        $temp =& $temp[$key];
    }
    $temp = $value;
}
$config = $array;
print_r($config);

A: Does simply referencing $config['site']['social'] get you the array you want? According to the documentation this should yield:
Array
    (
        [twitter] => "URL"
        [facebook] => "URL"
        [google-plus] => "URL"
    )


text:
Q: Where can I find the Preferred install location? Hello my issue starts like that, I'm trying to install the facebook.apk. my error is "Failed to create secure container" and I got to this page: http://forum.xda-developers.com/showpost.php?p=58409922&postcount=4845 which told me to get to  Settings > Apps > Open the menu > Preferred install location > set it to "Internal device storage"! but I don't know where is it.. which setting should I click? in the emulator I can't find this options.. and no ethier in the eclipse! help

A: In order to install an apk that doesn't come from the store, you need to enable the "unknown sources" options, it will allow you to install apps manually, and then you can install you apk using adb with the following command: adb install {your APK name}

A: Open an blank activity and from the terminal of the project run the install line. Have the following line in manifest file before installing apk file and try:
android:installLocation="auto"

If your aim is only to use Facebook sdks you need not install apk file I feel check the following link and follow the steps to setup Facebook ask in android:
https://developers.facebook.com/docs/android/getting-started
hope it helps.