text:
Q: A hacker installed vnc & remote management programs on my Macbook A nasty guy I dated last year secretly installed a series of programs onto my MacBook Pro and I need help with allocating and removing them please. I haven't switched it on for 11 months so it's still running snow leopard.
Please note that I haven't opened my macbook for 11 months due to this problem. My questions are:
Here's what I know:

*

*He used a USB to install: remote management, Remote Desktop, remote installer

*He also put a file that looked like a PDF but it was a virus or malware that is an executable file

*He uses both mac and windows and also uses his Nokia as a device to access his victims remotely as well.

Ihad NO idea this guy was a fraud and had been jailed for fraud and extortion 6 years before I knew him and I only knew him for a couple of months. Please don't remind me how silly or stupid I am I just need help.
I began to realise something was up from the following:

*

*A little screen appeared when I logged onto my mac asking for the IP address I'd like to remotely connect to

*my mouse would move when I wasn't using it

*my wifi would be switched to 'on' when I'd have turned it off on a previous screen

*files and folders were recreating themselves and multiplying and wouldn't allow me to delete them

*activity monitor showed hundreds of thousands of files uploaded in the sent messages column

*I looked at the sharing settings and it had a connection under the 802.1 (not sure on the correct number) in the VPN or vnc settings

*when I tried to quickly back up my home folder to my external hard drive and any other USB I'd try it wouldn't allow me and would say "unable to transfer files as "flash is using the USB or ex hard drive"(or something similar to this I can't recall the exact words sorry). I also went and purchased a brand new ex hard drive and when I connected it and went to format it it said something like this "unable to perform this operation as the flash is using the ex hard drive"

Upon searching 'recent' in spotlight, the following appeared which I hadn't opened or used: (!!!!)

*

*terminal

*dropbox(I don't and have NEVER downloaded Dropbox)

*system settings

*the PDF executable file

*remote management

*remote installer

*keychain app

*activity monitor

*Apple remote "something"(can't recall)

Please note that I haven't opened my macbook for 11 months due to this problem. My questions are:

*

*has the program he's obviously installed able to connect a VPN or vpc automatically to my public wifi if I turn my macbook on?

*has he uploaded my files and documents etc to a Dropbox that he can access to view all my private documents off my mac?

*it's been 11 months since this happened, can he still acces me now when I turn it on?

*what terminal commands do I use to remove any vnc or VPN he's installed?

*how can I seriously remove these program's I've installed? And can I do it in safe mode through the terminal?

*how do I check for malware/spyware I believe he's installed? And remove it through terminal?

*there are 3 accounts on my mac so how can I do this so cleans all of them at once?

*I already tried to back up my data but i couldn't even get passed the formatting (I believe that was the malware or spyware installing something to do with dodgy flash on that ex hard drive I tried)

*can I fix my mac in safe mode and do this by using certain commands in terminal? Please help? thank you!

A: Since doing a clean installation is not an option, I would follow below steps (Apologies for windows terminilogy, I don't use mac)

*

*Use an antivirus software and spyware removers to try to clean up at least the programs preventing back ups.If you are lucky , he would have used any 'standard' malware which could be detected by these.

*Take a backup of all important files. Make sure you do a virus scan later, before you connect the backup hdd/usb to any other computer.

*For preventing unauthorized programs from connecting to the internet and sending your data/remotely connecting, install a firewall program. You can choose only the trusted applications to send/receive data. (note: If there are resident viruses, there is a chance this could be compromised. At this stage you can't be 100% sure)

*Uninstall all programs that you are not familiar with

*Check what all programs get loaded automatically during start up, uninstall/delete the unfamiliar ones

*Do a clean installation at the earliest opportunity

A: *

*Change your wifi password use WPA or WPA2 with a long password with numbers and symbols.

*Go to MAC store and buy a new blank hard drive and ask them to install it for you.

*Take your original MAC OS cd/DVD and reload onto the new hard drive.

*Update everything Have the MAC store scan and

*clean the original hard drive. Copy back only the files you need and

*reformat the old hard drive and use that as a backup.

A: In a situation like this, it's vital to do reformat your disk and do a clean install, or better yet, as cybernard suggested, purchase a new physical hard drive. Anti-virus programs absolutely do not catch all types of malware, and you can never be sure you've discovered and cleaned everything that the fraudster may have done to the box. For your long term peace of mind, you want to be sure, and the only way to be sure is a clean install.
Before you begin, change your wifi password or turn off your wifi. You don't want to be on the network at the time you start the re-install.
Save any critical files on a USB drive.
Reformat and reinstall.
You might also want to consider reporting your credit cards stolen and opening up a new checking account, because it's entirely possible that information has been stolen.


text:
Q: List of lists of lists to a map of flatten map of lists I have a lists(states) of lists(cities) of lists(towns). How do I flatten the middle list(cities) and convert to a map(state's name) of map(town's name) of lists(towns)?
This question may look similar to the other question Java 3 level nested list to 3 level nested map, but they are not the same. This one, I need to flatten one of the lists.
import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Data
@AllArgsConstructor
class Country {
    private String name;
    private List<State> states;
}

@Data
@AllArgsConstructor
class State {
    private String name;
    private List<City> cities;
}

@Data
@AllArgsConstructor
class City {
    private String name;
    private List<Town> towns;
}

@Data
@AllArgsConstructor
class Town {
    private String name;
    private String address;
    private Integer population;
}

public static void main(String[]args) {
    List<Town> countryAStateACityATownsList = new ArrayList();
    countryAStateACityATownsList.add(new Town("CountryA-StateA-CityA-TownA", "addressOfCountryA-StateA-CityA-TownA", 100));
    countryAStateACityATownsList.add(new Town("CountryA-StateA-CityA-TownB", "addressOfCountryA-StateA-CityA-TownB", 100));
    countryAStateACityATownsList.add(new Town("CountryA-StateA-CityA-TownC", "addressOfCountryA-StateA-CityA-TownC", 100));

    List<Town> countryAStateACityBTownsList = new ArrayList();
    countryAStateACityBTownsList.add(new Town("CountryA-StateA-CityB-TownA", "addressOfCountryA-StateA-CityB-TownA", 100));
    countryAStateACityBTownsList.add(new Town("CountryA-StateA-CityB-TownB", "addressOfCountryA-StateA-CityB-TownB", 100));
    countryAStateACityBTownsList.add(new Town("CountryA-StateA-CityB-TownC", "addressOfCountryA-StateA-CityB-TownC", 100));

    List<Town> countryAStateACityCTownsList = new ArrayList();
    countryAStateACityCTownsList.add(new Town("CountryA-StateA-CityC-TownA", "addressOfCountryA-StateA-CityC-TownA", 100));
    countryAStateACityCTownsList.add(new Town("CountryA-StateA-CityC-TownB", "addressOfCountryA-StateA-CityC-TownB", 100));
    countryAStateACityCTownsList.add(new Town("CountryA-StateA-CityC-TownC", "addressOfCountryA-StateA-CityC-TownC", 100));

    City cityA = new City("cityA", countryAStateACityATownsList);
    City cityB = new City("cityB", countryAStateACityBTownsList);
    City cityC = new City("cityC", countryAStateACityCTownsList);

    List<City> countryAStateACitiesList = new ArrayList<>();
    countryAStateACitiesList.add(cityA);
    countryAStateACitiesList.add(cityB);
    countryAStateACitiesList.add(cityC);

        State stateA = new State("stateA",countryAStateACitiesList);

        Country countryA = new Country("countryA", Collections.singletonList(stateA));

    }

}

I want a map of states of towns. (so city list is flatten):
state.name -> town.name -> town.
I want to do something like destinationMap.get("stateA").get("CountryA-StateA-CityA-TownA") and that would give me the town instance that has the name "CountryA-StateA-CityA-TownA".
Please help, I have been trying to accomplish this by using stream, but not able to so far.
I have tried this:
        countryA.getStates()
               .stream()
               .collect(Collectors.toMap(State::getName,
                        st-> st.getCities()
                               .stream()
                               .collect(Collectors.toMap(City::getName,
                                                         City::getTowns))));

This creates a map of state.name to city.name to towns. But this is not what I want.

I want a map of state.name to town.name to the town that has the same name.

A: I love functional parts of Java, here's what I did, seems to work the way you wanted to retrieve towns.
Map<String, Map<String, Town>> map =
  countryA.getStates()
    .stream()
    .collect(Collectors.toMap(State::getName,
      st -> st.getCities()
        .stream()
        .map(City::getTowns)
        .flatMap(List::stream)
        .collect(Collectors.toMap(Town::getName, Function.identity()))));
System.out.println(map.get("stateA").get("CountryA-StateA-CityA-TownA"));

Gives output
Town{name='CountryA-StateA-CityA-TownA', address='addressOfCountryA-StateA-CityA-TownA', population=100}

And watch out, you have duplicates in your example, I assumed there should not be duplicates of towns in different cities. Let me know if this is what you wanted!

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to program factoranalysis iterations Currently i'm very busy with a new type of factor analysis. I created the following binary operators:

*

*%M%     calculates a square positive definite symmetric matrix from an R dataframe

*%E%     calculates communality estimates and places these on the main diagonal of the square matrix M

*%F%    extracts one factor at a time from the new square matrix

*%R%   reproduce a new square matrix from the factor loadings of %F% and subtracts it from the original matrix
This is one cycle. The steps 2 to 4 are duplicated for the residuals,%F% extracts a second factor,    %R%    reproduces a new matrix, etc.
In this fashion the complete procedure (steps 2 - 4 , 2 - 4) is successively applied to smaller and smaller matrices.
My question is: How can i program these iterations in R? Clearly, in each iteration Step 4 is input for a new cycle from step 2 to step 4 in the next iteration.
Some R - code I use:
iterations
res=  a%M%lg3
est=  res%E%5
F1=   est%F%1

res=  F1%R%est
est=  res%E%5
F2=   est%F%1
res=   F2%R%est

est=  res%E%5
F3=   est%F%1
res=  F3%R%est

a= is an R dataframe, lg3 is new bivariate log3 consensus coefficient.
I welcome this opportunity to ask for some help.
Regards,
Luc

A: You could just use a while loop, I think:
while(..some stopping criteria..) {
  est <- res %E% 5
  res <- est %F% 1 %R% est
}

If you wanted to run it just four times, just add a counter
for(i in 1:4) {
  est <- res %E% 5
  res <- est %F% 1 %R% est
}


text:
Q: Laravel - How to call a method once a day automatically I am using Laravel v. 4.1 on a website. Every once in a month, I need a specific method to be called automatically for a monthly payment with Moneris. I already tested my API and it's working pretty fine. But how to call this method once a day to check if users have to pay for their monthly payment? Is it possible to do that and to call it without having a HTTP Request?
Thank you!

A: You need to build an artisan command and then call it in your crontab:
* 0 * * * php /usr/share/nginx/html/example.com/artisan tns:delete-old-jobs --env=production >/dev/null 2>$1

Have the artisan command trigger your API method.


text:
Q: Efficient ways to duplicate array/list in Python Note: I'm a Ruby developer trying to find my way in Python.
When I wanted to figure out why some scripts use mylist[:] instead of list(mylist) to duplicate lists, I made a quick benchmark of the various methods to duplicate range(10) (see code below).
EDIT: I updated the tests to make use of Python's timeit as suggested below. This makes it impossible to directly compare it to Ruby, because timeit doesn't account for the looping while Ruby's Benchmark does, so Ruby code is for reference only.
Python 2.7.2
Array duplicating. Tests run 50000000 times
list(a)     18.7599430084
copy(a)     59.1787488461
a[:]         9.58828091621
a[0:len(a)] 14.9832749367

For reference, I wrote the same script in Ruby too:
Ruby 1.9.2p0
Array duplicating. Tests 50000000 times
                      user     system      total        real
Array.new(a)     14.590000   0.030000  14.620000 ( 14.693033)
Array[*a]        18.840000   0.060000  18.900000 ( 19.156352)
a.take(a.size)    8.780000   0.020000   8.800000 (  8.805700)
a.clone          16.310000   0.040000  16.350000 ( 16.384711)
a[0,a.size]       8.950000   0.020000   8.970000 (  8.990514)

Question 1: what is mylist[:] doing differently that it is 25 % faster than even mylist[0:len(mylist)]. Does it copy in memory directly or what?
Question 2: edit: updated benchmarks don't show huge differences in Python and Ruby anymore. was: Did I implement the tests in some obviously inefficient way, so that Ruby code is so much faster than Python?
Now the code listings:
Python:
import timeit

COUNT = 50000000

print "Array duplicating. Tests run", COUNT, "times"

setup = 'a = range(10); import copy'

print "list(a)\t\t", timeit.timeit(stmt='list(a)', setup=setup, number=COUNT)
print "copy(a)\t\t", timeit.timeit(stmt='copy.copy(a)', setup=setup, number=COUNT)
print "a[:]\t\t", timeit.timeit(stmt='a[:]', setup=setup, number=COUNT)
print "a[0:len(a)]\t", timeit.timeit(stmt='a[0:len(a)]', setup=setup, number=COUNT)

Ruby:
require 'benchmark'

a = (0...10).to_a

COUNT = 50_000_000

puts "Array duplicating. Tests #{COUNT} times"

Benchmark.bm(16) do |x|
  x.report("Array.new(a)")   {COUNT.times{ Array.new(a) }}
  x.report("Array[*a]")   {COUNT.times{ Array[*a] }}
  x.report("a.take(a.size)")   {COUNT.times{ a.take(a.size) }}
  x.report("a.clone")    {COUNT.times{ a.clone }}
  x.report("a[0,a.size]"){COUNT.times{ a[0,a.size] }}
end

A: Use the timeit module in python for testing timings.
from copy import *

a=range(1000)

def cop():
    b=copy(a)

def func1():
    b=list(a)

def slice():
    b=a[:]

def slice_len():
    b=a[0:len(a)]

if __name__=="__main__":
    import timeit
    print "copy(a)",timeit.timeit("cop()", setup="from __main__ import cop")
    print "list(a)",timeit.timeit("func1()", setup="from __main__ import func1")
    print "a[:]",timeit.timeit("slice()", setup="from __main__ import slice")
    print "a[0:len(a)]",timeit.timeit("slice_len()", setup="from __main__ import slice_len")

Results:
copy(a) 3.98940896988
list(a) 2.54542589188
a[:] 1.96630120277                   #winner
a[0:len(a)] 10.5431251526

It's surely the extra steps involved in a[0:len(a)] are the reason for it's slowness.
Here's the byte code comparison of the two:
In [19]: dis.dis(func1)
  2           0 LOAD_GLOBAL              0 (range)
              3 LOAD_CONST               1 (100000)
              6 CALL_FUNCTION            1
              9 STORE_FAST               0 (a)

  3          12 LOAD_FAST                0 (a)
             15 SLICE+0
             16 STORE_FAST               1 (b)
             19 LOAD_CONST               0 (None)
             22 RETURN_VALUE

In [20]: dis.dis(func2)
  2           0 LOAD_GLOBAL              0 (range)
              3 LOAD_CONST               1 (100000)
              6 CALL_FUNCTION            1
              9 STORE_FAST               0 (a)

  3          12 LOAD_FAST                0 (a)    #same up to here
             15 LOAD_CONST               2 (0)    #loads 0
             18 LOAD_GLOBAL              1 (len) # loads the builtin len(),
                                                 # so it might take some lookup time
             21 LOAD_FAST                0 (a)
             24 CALL_FUNCTION            1
             27 SLICE+3
             28 STORE_FAST               1 (b)
             31 LOAD_CONST               0 (None)
             34 RETURN_VALUE

A: I can't comment on the ruby timing vs. the python timing.  But I can comment on list vs. slice.  Here's a quick inspection of the bytecode:
>>> import dis
>>> a = range(10)
>>> def func(a):
...     return a[:]
...
>>> def func2(a):
...     return list(a)
...
>>> dis.dis(func)
  2           0 LOAD_FAST                0 (a)
              3 SLICE+0
              4 RETURN_VALUE
>>> dis.dis(func2)
  2           0 LOAD_GLOBAL              0 (list)
              3 LOAD_FAST                0 (a)
              6 CALL_FUNCTION            1
              9 RETURN_VALUE

Notice that list requires a LOAD_GLOBAL to find the function list.  Looking up globals (and calling functions) in python is relatively slow.  This would explain why a[0:len(a)] is also slower.  Also remember that list needs to be able to handle arbitrary iterators whereas slicing doesn't.  This means that list needs to allocate a new list, pack elements into that list as it iterates over the list and resize when necessary.  There are a few things in here which are expensive -- resizing if necessary and iterating (effectively in python, not C).  With the slicing method, you can calculate the size of the memory you'll need so can probably avoid resizing, and the iteration can be done completely in C (probably with a memcpy or something.
disclaimer : I'm not a python dev, so I don't know how the internals of list() are implemented for sure.  I'm just speculating based what I know of the specification.
EDIT  -- So I've looked at the source (with a little guidance from Martijn).  The relevant code is in listobject.c.  list calls list_init which then calls listextend at line 799.  That function has some checks to see if it can use a fast branch if the object is a list or a tuple (line 812).  Finally, the heavy lifting is done starting at line 834:
 src = PySequence_Fast_ITEMS(b);
 dest = self->ob_item + m;
 for (i = 0; i < n; i++) {
     PyObject *o = src[i];
     Py_INCREF(o);
     dest[i] = o;
 }

Compare that to the slice version which I think is defined in list_subscript (line 2544).  That calls list_slice (line 2570) where the heavy lifting is done by the following loop (line 486):
 src = a->ob_item + ilow;
 dest = np->ob_item;
 for (i = 0; i < len; i++) {
     PyObject *v = src[i];
     Py_INCREF(v);
     dest[i] = v;
 }

They're pretty much the same code, so it's not surprising that the performance is almost the same for large lists (where the overhead of the small stuff like unpacking slices, looking up global variables, etc becomes less important)

Here's how I would run the python tests (and the results for my Ubuntu system):
$ python -m timeit -s 'a=range(30)' 'list(a)'
1000000 loops, best of 3: 0.39 usec per loop
$ python -m timeit -s 'a=range(30)' 'a[:]'
10000000 loops, best of 3: 0.183 usec per loop
$ python -m timeit -s 'a=range(30)' 'a[0:len(a)]'
1000000 loops, best of 3: 0.254 usec per loop


text:
Q: How can i open SISX package? I recently downloaded a dictionary and a movie both in a compressed format carrying the name (SISX), but my ubuntu 13.10 could not open it, i searched the software center but it did not hep.

A: The SISX files are used by applications that are installed on the Nokia phones that operate on the Symbain operating system.   To try to open the file take a look at S60 Software Suite.
I don't have a Nokia phone to be able to test with, so I can't verify for sure that it will work.


text:
Q: Cloud functions for firebase - deleted or added data I want to distinguish between deleted and data that was first created.
I´m using the code from Firebase:
if (event.data.previous.exists()) {
    return;
  }
  // Exit when the data is deleted.
  if (!event.data.exists()) {
    return;
  }

However, it doesn't work. I´m listening to the database which is structured as following:

*

*in use

*

*fruitID

*id: fruitID

I want to use code when the data is deleted and another code when the data is created, so when a fruit is added.
Using the given code only the part in
if (event.data.previous.exists()){
}

is executed AND ALWAYS when the data is DELETED.
Any suggestions?
Thanks.

A: Cloud functions has new triggers that you can use for this particular workflow.

onWrite(), which triggers when data is created, destroyed, or changed in the Realtime Database.
onCreate(), which triggers when new data is created in the Realtime Database.
onUpdate(), which triggers when data is updated in the Realtime Database.
onDelete(), which triggers when data is deleted from the Realtime Database.

You could create two triggers, onDelete and onCreate.
Otherwise if you want to create it in one function you could setup a function using onWrite
export listener = functions.database.ref('/fruit/{fruitId}').onWrite(event => {
  if (!event.data.previous.exists()) {
    // Created Event - Previous data doesn't exist.
  } else if (!event.data.exists()) {
    // Deleted Event - Data doesn't exist.
  } else {
    // Update
  }
}


text:
Q: Why is there a left space on the left of linear layout?

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/myToolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="#019032"
                android:padding="20dp"
                android:gravity="center_horizontal">

                <ImageView
                    android:layout_width="25dp"
                    android:layout_height="25dp"
                    android:layout_marginLeft="0dp"
                    android:paddingLeft="0dp"
                    android:src="@drawable/menu" />

                <TextView
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_gravity="center"
                    android:textAlignment="center"
                    android:layout_weight="1"
                    android:textStyle="bold"
                    android:textSize="18dp"
                    android:text="Falesie in Italia" />

                <ImageView
                    android:layout_width="25dp"
                    android:layout_height="25dp"
                    android:src="@drawable/menu" />

            </LinearLayout>

        </androidx.appcompat.widget.Toolbar>

</androidx.constraintlayout.widget.ConstraintLayout>

I'm trying to add a Toolbar on my app and i have a little space on the left of linear layout.
This is the code of my main activity layout, i tried to change padding and margin of all the element but the situation doasn't change.
Does anyone know why?

A: Could you try
 app:contentInsetLeft="0dp"
 app:contentInsetStart="0dp"
 android:padding="0dp"

it will be like this
<androidx.appcompat.widget.Toolbar
    android:id="@+id/myToolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:contentInsetLeft="0dp"
    app:contentInsetStart="0dp"
    android:padding="0dp">

A:
Preview in my Android Studio
The problem is with caches
Try

*

*Copy the file content

*Delete the file

*File > Invalidate & Restart

*Gradle sync

*Create new file with different name

*Check the preview

*Run the app and check

*Rename to original name

If this doesnt work

*

*Close android studio completely
(Check task manager and end task if its still running)

*Enter %USERPROFILE%\.gradle\caches in explorer and delete the caches folder

*Go to your project root and delete .idea, .gradle and build folders

*Open android studio


text:
Q: Empty value in application.properties leads to "Could not resolve placeholder" exception We got a spring-boot application which reads it's configuration from a configuration-server.
I encountered a problem reading empty properties using the spring-cloud-configuration-server.
Setting is a KV-pair with no value in application.properties.
e.g.
MyKey=
Loading it "regular" using just a file no problem is raised.
But when the client uses a configuration-server, the empty value is leading to a:

"java.lang.IllegalArgumentException: Could not resolve placeholder 'MyKey'".

Looks for me there is something weird in the config-server.
So here is the application.yml of it:
info:
  version: '@project.version@'
  artifact: '@project.artifactId@'
server:
  port: 10805
spring:
  application:
    name: ${info.artifact}
  http:
    encoding:
      charset: UTF-8
  boot:
    admin:
      discovery:
        enabled:  true
      context-path: /admin
  jmx:
    enabled: false
endpoints:
  jmx:
    enabled: false
turbine:
  combineHostPort: true
  app-config: service.us
  clusterNameExpression: "'default'"

---
spring:
  profiles: win
eureka:
  server:
    disable-delta: true
    disable-delta-for-remote-regions: true
  instance:
    hostname: ${COMPUTERNAME}
  client:
    serviceUrl:
      defaultZone: http://localhost:10805/eureka/
archaius:
  deployment:
    datacenter: ${eureka.instance.hostname}
    environment: local

---
spring:
  profiles: default
eureka:
  instance:
    virtual-host-name: ${eureka.instance.appname}
    app-group-name: ces
    appname: admin.ces

---
spring:
  profiles:
    active: subversion
  cloud:
    config:
      server:
        svn:
          uri : https://myserver/svn/ces/trunk/config/
          username: conf
          password: ****

Any Ideas?

A: I finally found the problem.
The configuration-server drives an eureka-server aswell.
This combination leads to the behavior described above.
Removing the annotation AND the dependency
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-eureka-server</artifactId>
    </dependency>

solves the problem.
So our idea to run both services on the same instance is currently not realisable.
Used versions:
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.4.1.RELEASE</version>
</parent>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Brixton.RS4</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>


text:
Q: How to call setState properly? Hello tell me the best practice please!
I need two simple action, get data from API, and set data to state. I read I can do API request in componentDidMount, but in this function I can't set state.
Actually all work good if I do this way, but if I try reload page, I got this error:

Can't perform a React state update on an unmounted component. This is
  a no-op, but it indicates a memory leak in your application. To fix,
  cancel all subscriptions and asynchronous tasks in the
  componentWillUnmount method.

componentDidMount = () => {
  this.getData();
}

getData = async () => {
  try {
    // Get data from api
    const fund = await axios.get(
      APIEnpoint + "api/smartfund/" + this.props.match.params.address
    );
    this.setState({
      smartFundAddress: fund.data.result.address,
      name: fund.data.result.name,
      balance: JSON.parse(fund.data.result.balance)
    });
  } catch (error) {
    // Catch any errors for any of the above operations.
    alert(`can't get data`);
    console.error(error);
  }
}

A: The problem is that you are trying to set your state after your component has been unmounted. So to prevent it for happening try this one:
    _isMounted = false;

    componentDidMount(){
        this._isMounted = true;
    }

    componentWillUnmount(){
        this._isMounted = false;
    }

getData = async () => {
  try {
    // Get data from api
    const fund = await axios.get(
      APIEnpoint + "api/smartfund/" + this.props.match.params.address
    );
    if(this._isMounted)
    {
        this.setState({
            smartFundAddress: fund.data.result.address,
            name: fund.data.result.name,
            balance: JSON.parse(fund.data.result.balance)
          });
    }
  } catch (error) {
    // Catch any errors for any of the above operations.
    alert(`can't get data`);
    console.error(error);
  }
}

So if the component is unmounted that will not try to update the state


text:
Q: Want to space evenly inside column for flexible widget flutter I want space evenly for the flexible widgets inside column. But not same type, I mean two widgets are text form field and one is text. Two flexible text form field take extra space in bottom and I don't know how they take spacing. Even if I know I can use SizedBox() to alignment. How can I know or remove that extra spacing for alignment.
I describe my issue.

This is my two text field code.
Flexible(
              flex: 1,
              child: Container(
                decoration: BoxDecoration(
                  border: Border.all(color: Colors.blue),
                ),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.baseline,
                  textBaseline: TextBaseline.alphabetic,
                  children: <Widget>[
                    Flexible(
                      flex: 1,
                      fit: FlexFit.tight,
                      child: Text(
                        AppLocalizations.of(context).translate('Paynow'),
                        style: kLabelTextStyle(
                            color: Colors.black87,
                            size: 16,
                            weight: FontWeight.normal),
                      ),
                    ),
                    Flexible(
                      flex: 2,
                      child: TextFormField(
                        decoration: kTextFormFieldsDecoration(
                          hintText: 'Max $remainingAmount',
                          fontSize: 13,
                          kFontColor: Colors.grey,
                        ).copyWith(helperText: ''),
                        keyboardType: TextInputType.number,
                        validator: _validate,
                        textInputAction: TextInputAction.done,
                        onChanged: (value) {},
                        onSaved: (value) {},
                      ),
                    ),
                  ],
                ),
              ),
            ),

This is middle widget with text
Flexible(
              flex: 1,
              child: Container(
                decoration: BoxDecoration(
                  border: Border.all(color: Colors.blue),
                ),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.baseline,
                  textBaseline: TextBaseline.alphabetic,
                  children: <Widget>[
                    Flexible(
                      flex: 1,
                      fit: FlexFit.tight,
                      child: Text(
                        'Paynow',
                        style: kLabelTextStyle(
                            color: Colors.black87,
                            size: 16,
                            weight: FontWeight.normal),
                      ),
                    ),
                    Flexible(
                        flex: 2,
                        child: Text(
                          'H',
                        )),
                  ],
                ),
              ),
            ),

Wrap these three flexible widgets inside Column of Container
Flexible(
              flex: 2,
              fit: FlexFit.tight,
              child: Container(
                decoration:
                    BoxDecoration(border: Border.all(color: Colors.red)),
                height: 500,
                child: Column(
                  children: [],
                ),
              ),
            ),

A: You can use expanded instead of flexible to achieve an even size for each one.  Is there any specific reason you want to use flexible with this layout?


text:
Q: oracle - hashing method, excluding DBMS_CRYPTO BACKGROUND:
DBAs have hidden DBMS_CRYPTO package to any role, grantee, and I wonder why. I have to use wrapper instead :(

Is there any way to get the same hash for the text field with the same text? All below methods give different results for the same text as they seem depending on rowid, or something similar:
SELECT
 , utl_raw.cast_to_raw(sys_op_map_nonnull(log_msg))                                                  AS "RAW"
 , rawtohex(utl_raw.cast_to_raw(sys_op_map_nonnull(log_msg)))                                        AS raw_hex
 , rawtohex(standard_hash(sys_op_map_nonnull(log_msg), 'MD5'))                                       AS md5_hex
 , ora_hash(log_msg)
 , dbms_obfuscation_toolkit.md5(input => utl_raw.cast_to_raw(sys_op_map_nonnull(log_msg)))           AS md5
 , rawtohex(dbms_obfuscation_toolkit.md5(input => utl_raw.cast_to_raw(sys_op_map_nonnull(log_msg)))) AS hex

log_msg is CLOB

A: *

*DBMS_OBFUSCATION_TOOLKIT was deprecated and replaced by DBMS_CRYPTO.

*ORA_HASH does not produce a unique checksum, per se, and does not support LOB types.

*STANDARD_HASH uses DBMS_CRYPTO under the hood, but also does not support LOB types.

Having recently faced a similar problem myself, I was able to get execute privileges on DBMS_CRYPTO for the application schema by demonstrating the need. The DBAs didn't have any problem granting the access as long is it was required and documented. It's the only real option for what you're trying to do. My function to produce a SHA256 hash wound up looking like this:
function get_sha256sum (p_clob in clob) return raw
is
begin
    return dbms_crypto.hash (src => utl_raw.cast_to_raw(p_clob), typ => 4);
end get_sha256sum;

Note: don't try to cast the raw checksum to anything else - it's only accurate as a checksum in the original format.

A: DBMS_OBFUSCATION_TOOLKIT is no longer available on any currently supported versions of Oracle Database.
My recommendation is for you to upgrade your DB so that you can use DBMS_CRYPTO.


text:
Q: NSArray Tokenize on base of a key I have already fetched data from server and passing the data is also populated with NSMutableArray after NSJSONSerialization.
Output of array is as follow's:
NSArray *jsonArray = (NSArray *)json;
NSLog(@"Array - %@",jsonArray);

I want to create a new array which will contain all the data of newsletter.
Array - (
        {
        error = 0;
        newsletter =         (
                        {
                date = "2015-11-23";
                description = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry\\'s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop p";
                id = 42;
                image = "link/uploads/14482883361619729430.png";
                "post_count" = 1;
                "posted_by" = admin;
                title = Testing;
            },
                        {
                date = "2015-11-23";
                description = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry\\'s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop p";
                id = 43;
                image = "link/uploads/14483023241983843096.png";
                "post_count" = 0;
                "posted_by" = admin;
                title = "Lorem Ipsum";
            },

I have tried to use the function objectAtIndex but didn't worked, I am checking the count of jsonArray.
NSLog(@"count of array - %lu",jsonArray);

it show's 2 as counter.
My Code :
if (responseData != nil) {
  NSMutableArray *json = [NSJSONSerialization JSONObjectWithData:responseData //1
                                                         options:NSJSONReadingMutableContainers
                                                           error:&err];

  NSArray *jsonArray = (NSArray *)json;
  NSLog(@"Array - %@",jsonArray);
  NSLog(@"Count %lu",[jsonArray count]);

}

Question Updated:
I want to populate two arrays 1 will have error = 0; and the second should need to have all data in newsletter
= (
{
  date = "2015-11-23";
  description = "Lorem Ipsum is simply...";
  id = 42;
  image = "link/uploads/14482883361619729430.png";
  "post_count" = 1;
  "posted_by" = admin;
  title = Testing;
}

Hope now question is bit clear...
Thanks in advance for understanding the question.

A: The question should not be "i want to have two arrays - one with error and one with all the data", as both are not arrays.
The error is just a number, and the newsletter data is a dictionary with key-value pairs that you will access by the key's value, eg
NSString* newsletterDate = newsletterData[@"date"]

So just get the second object of your JSON array - it will be a dictionary, and you can access all of its data by the respective keys.


text:
Q: My computer force pushes on git without asking me Everything is in the  title. My computer force pushes and my collaborators can't push after me.
It's starting to be a big problem, does anyone know about this problem?

A: I wonder if what is happening is that you are pushing, and since they don't have your commit in their local branch, they can't push
Original -- Your Commit - Your other commit
         \- Your colleague's commit

You colleague should be able to do something like this
git fetch
git rebase origin/branchname
# and now they will have your commit in their branch because you pushed first
git push origin branchname # now they can push because their local branch has everything origin has and more

I find it really helpful to use gitk and look at it before and after every commit, fetch, and push, to see how all this fits together.  If there is another problem, and you post a picture of gitk, I am sure somebody can get to the bottom of it.


text:
Q: Why is .$el needed, and what does it point to? This is probably more of a javascript question, but I'm going through this backbone tutorial and was wondering why is there a .$el at the end of this line, and which element is it point to?
self.$el.append((new BlogView({ model: blog})).render().$el);

Here is the full code below.....
var BlogsView = Backbone.View.extend({
    model: blogs,
    el: $('.blogs-list'),
    initialize: function() {
        this.model.on('add', this.render, this);
    },
    render: function() {
        var self = this;
        this.$el.html('');
        _.each(this.model.toArray(), function(blog) {
            self.$el.append((new BlogView({ model: blog})).render().$el);
        });
        return this;
    }
});

A: $el is a reference for the DOM element for the view. Backbone views are not DOM elements themselves, they are generic javascript objects which have a property called $el which holds the DOM element which is what you actually see on the webpage. You can think of a backbone view as a controller of sorts for the DOM element, and when you add event listeners to your view, define render, etc, you are always acting on its DOM element stored in $el ($el is the same DOM element as el, the former just plays nicely with jQuery). In this case, your view is BlogView and if we break new BlogView({ model: blog})).render().$el up:

*

*new BlogView - creating an instance of your view, backbone will automatically create a DOM element for your view and store it in yourView.$el

*.render() - telling the view to render its HTML inside the $el element. In Backbone, our render function is where we generate HTML markup/format data and "draw" the view by shoving this markup into our view's $el.

*render().$el - render() returns this which is just our view itself, so calling render().$el is like saying "render my view and return my DOM element.

*self.$el.append(..) - this block of code is thus given our DOM element $el which then inserts it.
so putting it all together we get: new BlogView({ model: blog})).render().$el which first creates our view, renders our view and returns our view's DOM element which can be appended to the page, manipulated, etc.


text:
Q: Restrict the status in Oracle Apex I have started to learn Oracle Apex, and I follow this document - https://www.oracle.com/technetwork/developer-tools/apex/application-express/apex-spreadsheet-hol-5532109.pdf
I can't understand why on page 27 they use this query
select distinct status d, status r
from spreadsheet
order by 1

They use status twice on one table
Thanks in advance

A: It's generating values for a select list. The first column is what is displayed in the select list and the second the value returned when selected. In this case both columns are the same but that isn't required


text:
Q: How to display multiple images on user command? I need to be able to display a group of images after the user presses a menu on the Gui. I have been trying to use the following code.
 private void imagePalleteToolStripMenuItem_Click(object sender, EventArgs e)
    {
        List<string> Files = this.MyImageCollection.ConvertFileNamesToList();
        foreach (string currtFile in Files)
        {
            Image newImage = Image.FromFile(currtFile);

            // Create rectangle for displaying image.
            Rectangle destRect = new Rectangle(100, 100, 450, 150);

            // Draw image to screen.
            e.Graphics.DrawImage(newImage, destRect);
        }

I think this would work but I get the error:
'System.EventArgs' does not contain a definition for 'Graphics' and no extension method 'Graphics' accepting a first argument of type 'System.EventArgs' could be found (are you missing a using directive or an assembly reference?)
I tried replaceing EventHandler with PaintEventHandler, but then I get an error here:
this.imagePalleteToolStripMenuItem.Click += new System.EventHandler(this.imagePalleteToolStripMenuItem_Click);

Stating:
No overload for 'imagePalleteToolStripMenuItem_Click' matches delegate 'System.EventHandler'
I also tried changing that line to:
this.imagePalleteToolStripMenuItem.Click += new System.Windows.Forms.PaintEventHandler(this.imagePalleteToolStripMenuItem_Click);

But this too gives an error stating:
Cannot implicitly convert type 'System.Windows.Forms.PaintEventHandler' to 'System.EventHandler'r
*Note:*My over all goal is to  invoke a dialog that will display all the images in thumbnail form. So if this is not the correct way to do so, please redirect me

A: You're confusing the paint event with the click event. If you want something to happen when a user clicks a button, you put that in the click event.  What would you be painting to in a button click?
Instead, design a new form to show your images, on the button click event, gather your images, and give those images to your dialog. Let the dialog worry about displaying them.

A: It looks like you grabbed some sample code that was originally in an OnPaint event. You've added this to a totally different type of event, which does not pass you a Graphics object. You either need to put this code in the OnPaint event of whatever control you want this in, or try a completely different approach.
The correct solution depends on exactly how you want this to work (are you trying to updated something already on screen, show a new dialog, etc).


text:
Q: update table's column's year without changing the month and date for all rows My table is kanaja postmeta,i hav around more than 1000 rows.
meta_id  post_id     meta_key        meta_value
403723   131871   _EventStartDate  2017-01-23 00:00:00
404269   131881   _EventStartDate  2017-01-03 00:00:00
404485   131883   _EventStartDate  2017-01-03 00:00:00
405271   131885   _EventStartDate  2017-12-20 00:00:00
404695   131887   _EventStartDate  2017-01-04 00:00:00

Where i just need to change the year from 2017 to 2018 and the date and month should be the same as before for all rows in the meta_value column.
               I have executed the following mysql query:
   UPDATE kanaja_wp.kanaja_postmeta
   SET meta_value = DATE_ADD('2017-01-23 00:00:00', INTERVAL 1 YEAR),
   SET meta_value = DATE_ADD('2017-02-01 00:00:00', INTERVAL 1 YEAR),
   WHERE meta_id IN (404269,404485);

which changes the year from 2017 to 2018 for two rows,To change the year for all 1000 rows,I should specify the meta_id and date for all 1000 rows which makes the query too long.
so can u help out with a mysql query,so that i can change only the year of all the column and the date and time should be same as before for all rows,so that   query will be smaller.I just want a query  like
   UPDATE kanaja_wp.kanaja_postmeta
   SET meta_value = DATE_ADD('2017-**-** 00:00:00', INTERVAL 1 YEAR),
   WHERE meta_key='_EventStartDate'

** specifies that the date and month which should not be changed

A: Try this:
   UPDATE kanaja_wp.kanaja_postmeta
   SET meta_value = DATE_FORMAT(meta_value,'2018-%m-%d %T')
   WHERE meta_key='_EventStartDate';

A: All you need to do is use the column name in the DATE_ADD() function and remove the WHERE clause so it finds all rows.
UPDATE kanaja_wp.kanaja_postmeta
    SET meta_value = DATE_ADD(meta_value, INTERVAL 1 YEAR);

If you only want to change the dates where meta_key='_EventStartDate' then keep the where
UPDATE kanaja_wp.kanaja_postmeta
    SET meta_value = DATE_ADD(meta_value, INTERVAL 1 YEAR)
WHERE meta_key='_EventStartDate';

A: This query works fine and it fulfilled my requirement
UPDATE kanaja_wp.kanaja_postmeta
SET meta_value = DATE_ADD(meta_value, INTERVAL 1 YEAR)
WHERE meta_key="_EventStartDate";

It works for all row names both start and End date as well.
Thanks for the answers :)


text:
Q: Print output to separate text files The script below opens devices.csv and reads the rows, then prints 2 of the fields.  I want to create a separate .txt file for each row using 'Host Name' field, then print 'Configuration Text' to each file.
import csv
import sys
import os
path = 'C:/configs'
fh = "C:/configs/devices.csv"
with open(fh, mode='r') as infile:
    reader = csv.DictReader(infile)
    for row in reader:
        print(row['Host Name'], row['Configuration Text'])

Please assist.

A: import csv
import sys
import os
path = 'C:/configs'
fh = "C:/configs/devices.csv"
with open(fh, mode='r') as infile:
    reader = csv.DictReader(infile)
    for row in reader:
        with open(os.path.join(path, row['Host Name']), "w") as outfile:     #Create File with host name
            outfile.write(row['Configuration Text'])     #Write Content


text:
Q: Why can't tree fully list /sys/class/hwmon? And how could I do that? If I understand correctly, in Linux, everything is a path, right down to each piece of hardware. I am trying to get information about how my sensors are structured, so I thought I would just use tree to map out all the things in my hwmon directory. However, tree does not behave the same with this directory as I am accustomed to.
When I run tree on a normal directory, I get the subdirectory structure without using the -R or -L flags:
$ tree /home
/home
└── boss
    ├── clones
    ├── Desktop
    ├── Documents
    │   ├── modules.txt
    │   ├── old_docs
    │   │   └── assorted
    │   └── prepscript.txt
    ├── Downloads
    ├── Music
    ├── Pictures
    ├── Public
    ├── Templates
    └── Videos

12 directories, 2 files

but I try to do the same with HWmon, it only goes one level deep, even if I do use the -R flag and even though there is stuff deeper:
$ tree /sys/class/hwmon/
/sys/class/hwmon/
├── hwmon0 -> ../../devices/pci0000:40/0000:40:01.3/0000:43:00.0/hwmon/hwmon0
├── hwmon1 -> ../../devices/pci0000:00/0000:00:01.3/0000:09:00.0/hwmon/hwmon1
├── hwmon2 -> ../../devices/pci0000:40/0000:40:03.1/0000:44:00.0/hwmon/hwmon2
├── hwmon3 -> ../../devices/pci0000:00/0000:00:18.3/hwmon/hwmon3
├── hwmon4 -> ../../devices/pci0000:00/0000:00:19.3/hwmon/hwmon4
├── hwmon5 -> ../../devices/virtual/thermal/thermal_zone0/hwmon5
└── hwmon6 -> ../../devices/platform/nct6775.656/hwmon/hwmon6

7 directories, 0 files
$ tree /sys/class/hwmon/hwmon0
/sys/class/hwmon/hwmon0
├── device -> ../../../0000:43:00.0
├── fan1_input
├── name
├── power
│   ├── async
│   ├── autosuspend_delay_ms
│   ├── control
│   ├── runtime_active_kids
│   ├── runtime_active_time
│   ├── runtime_enabled
│   ├── runtime_status
│   ├── runtime_suspended_time
│   └── runtime_usage
├── pwm1
├── pwm1_enable
├── pwm1_max
├── pwm1_min
├── subsystem -> ../../../../../../class/hwmon
├── temp1_auto_point1_pwm
├── temp1_auto_point1_temp
├── temp1_auto_point1_temp_hyst
├── temp1_crit
├── temp1_crit_hyst
├── temp1_emergency
├── temp1_emergency_hyst
├── temp1_input
├── temp1_max
├── temp1_max_hyst
├── uevent
└── update_interval

3 directories, 27 files

What causes this difference in behavior, and can I just get a simple tree of all the devices?

A: tree behaves that way because it doesn't dereference symlinks by default. The -l option will change that:
tree -l /sys/class/hwmon/

but you'll have fun making sense of all the output.


text:
Q: NUL character in xml file (using dom4j) I am using dom4j to extract information in xml files(all in one folder).
Here's my code:
    File folder = new File("c:/folder directory");
    File[] listOfFiles = folder.listFiles();
    FileOutputStream foutstream = new FileOutputStream("c:/mozilla_expertlist.txt",true);
    PrintWriter writer = new PrintWriter(foutstream);

    for (File file: listOfFiles)
    {
        System.out.println(file.getName());
        File f = new File("c:/Users/dahuo2013/workspace/mozilla_xml/"+file.getName());
        SAXReader reader = new SAXReader();
        reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        reader.setEncoding("utf-8");
        Document doc = reader.read(f);
        Element root = doc.getRootElement();
        Element foo;

        for (Iterator i = root.elementIterator("bug"); i.hasNext();)
        {
            foo = (Element) i.next();
            writer.println(foo.elementText("assigned_to"));
        }

    }
    writer.close();

My code is working however it always have errors reporting. Then I found that when the xml file has NUL NUL NUL characters. It shows error. When I delete those NUL characters. It will definitely work.
But I have more than 4000 xml files in the folder.I cannot delete those NUL one by one by my hands. My xml is encoded by utf-8. Is there any easy way to avoid those NUL characters? Or what kind of easy solution can delete those NUL characters?
Thanks!
also:

This is the NUL character. I opened in notepad++


text:
Q: Create multiple instances of the same class with Guice Sorry if it's a trivial question, I am new to Guice.
Let's say I have the following class:
public class MyClass {
     @Inject
     public MyClass(final MyDependency myDependency) {
          this.name = myDependency.getName();
     }

     public String getName() {
          this.name;
     }
}

Then somewhere else I want to do:
public class SomeOtherClass {
    public void test() {
        MyClass instanceFoo = injector.getInstance(MyClass.class);
        MyClass instanceBar = injector.getInstance(MyClass.class);

        assertTrue("foo", instanceFoo.getName());
        assertTrue("bar", instanceBar.getName());
    }
}

I would like to have two instances of "MyClass", one which has a name of "foo" and one with a name of "bar" (i.e. each of them has a different instance of it's dependency as well). How can I add those 2 instances to my injector, and how can I retrieve each of them with "injector.getInstance"?
I don't want to create a subclass of "MyClass" for each possible dependency.
Thanks!

A: Your question, as in the title, has a simpler solution: If you want an arbitrary number of instances of MyClass or MyDependency, you can inject a Provider<MyClass> or Provider<MyDependency>. This is true whether or not you've actually bound a Provider in a Module; for any T available in the graph Guice can actually inject either T or Provider<T>. (These correspond to Injector.getInstance and Injector.getProvider respectively.)
As in the body of the question, there are two pieces: Making more than one injectable Key for the same Class, and setting up the instances the way you want with different names and injected dependencies.
Keys and Binding Annotations
Guice identifies bindings using a Key, which is a fully-qualified class (like MyClass or List<MyClass>) combined with an optional "binding annotation". This is an annotation that is itself annotated with BindingAnnotation or javax.inject.Qualifier; you can create your own, or use the built in one called @Named that takes a String (so @Named("foo") is different from @Named("bar")).
Most of the time, you can get by without using Key directly: Use annotatedWith in your bind calls or add the annotation onto @Provides methods, and request them by putting the annotation onto constructor parameters or @Inject-annotated fields. However, you can still use getInstance and getProvider by creating a Key manually, using the static methods on Key. (For complicated cases, use TypeLiteral or Names.named; see their docs for details.)
Setting up instances
Now that you know how to inject @Named("foo") MyClass or @Foo MyClass, how do you provide them? Depending on your needs, I'd choose one of three options: binding toInstance, using a @Provides method, or creating an "assisted injection" factory.

*

*If your MyClass instances don't need injection themselves, and you don't mutate or manipulate instance state, you could just prepare the instances named as needed and then bind them with toInstance.

*You could also write a @Provides @Named("foo") MyClass method that takes a MyClass parameter (which Guice supplies through the injector), sets the name, and returns the instance. This is a low-overhead alternative to writing a Provider class or instance, and will get you a fresh instance rather than the sharing that a toInstance binding would imply.

*If you really want the name to be a part of your class's constructor parameters, perhaps to keep the instance immutable, you can use "Assisted Injection" to tell Guice which parameters you supply yourself and which come from the Guice injector. This would allow you to inject a MyClass.Factory and call myClassFactory.create("foo"), which you could do directly in your consuming classes, or using the @Provides technique above. The details are a little beyond the scope of the question, but look up "Assisted Injection" for details on syntax and on adding the appropriate JAR.


text:
Q: Why is span with class not showing up in WYSIWYG mode When I use this HTML code:

test

And I go to WYSIWYG mode, it is invisible.
When I go into Inspect Element, is see this output:

Is this a configuration setting?
Let me know please.
Thanks in advance!
Edit 1:
At first I had

test

But then I figured out that it has nothing to do with the class itself, but just using the attribute "class" is enough to get it invisible.
Also, it is only happening with a span, the others are working...

A: That is because you don't have the correct syntax for HTML.
Try this instead:

test


text:
Q: How to make more than one operation to sum values from different datasets in R (including time format) I've got a tool that I run to make calculations about running times of certain programs, giving me many times the same 1 row table with the resulting numbers (6 columns, with a header with column names). I am doing this for three programs and I have to sum/combine the result as if it was one program, not three. (for example, if program 1 takes 1 hour to run, program 2 takes 1 hour and program 3 takes 3 hours, then the result is to sum up and have 5 hours total).
5 of the values from such output tables look like "304.34" (decimal numbers, usually in the order of the hundreds, and have to be summed), but one column has time with the following format: 01:04:56 . I would like to make an R script that takes in 3 tables (for the three programs mentioned), and sums that to produce one table. (with the same header)
The problem is, I am having trouble to think of a function that can do that and sum the time column properly as well as the others. Thank you!

**example:
df <- read.table(text = "col1 col2 col3 col4 col5 col6_time
300.45 201.4 100.11 100.35 101 01:10:05
300 202.1 105.20 101.10 100 01:00:01
250.10 200.4 101.21 102 100 00:45:23", header = T)

**desired output (sum values, keep header):**

    col1  col2   col3   col4 col5 col6_time
1 850.55 603.9 306.52 303.45  301  02:55:28

A: You can turn the character columns to a period object and sum it.
library(dplyr)
library(lubridate)

df %>%
  summarise(across(where(is.numeric), sum),
            across(where(is.character),
                   ~format(parse_date_time(seconds_to_period(sum(period_to_seconds(hms(.)))), "HMS"), '%T')))

#    col1  col2   col3   col4 col5 col6_time
#1 850.55 603.9 306.52 303.45  301  02:55:29


text:
Q: How to store and load data properly with CoreData? I am a beginner and never worked close with CoreData. I have a JSON response, which results need to be shown in a Table View. I want implement a CoreData to my project.
JSON parsing (in Separate Swift file)
 func parseJSON(with currencyData: Data){
    let decoder = JSONDecoder()

    do {
        let decodedData = try decoder.decode(CurrencyData.self, from: currencyData)

        for valute in decodedData.Valute.values {
            if valute.CharCode != "XDR" {
                 let currency = Currency(context: self.context)
                currency.shortName = valute.CharCode
                currency.currentValue = valute.Value
            }
        }

         do {
             try context.save()
         } catch {
             print("Error saving context, \(error)")
         }
    } catch {
        self.delegate?.didFailWithError(self, error: error)
        return
    }
}

And in my VC I want to load it in my tableView which takes data from currencyArray:
    func loadCurrency() {
    let request: NSFetchRequest<Currency> = Currency.fetchRequest()
    do {
        currencyArray = try context.fetch(request)
    } catch {
        print(error)
    }
    tableView.reloadData()
}

I start the parsing and load currency data in my VC:
 override func viewDidLoad() {
    super.viewDidLoad()
    currencyNetworking.performRequest()
    loadCurrency()
}

But as a result when app first launch my tableView is empty. Second launch - I have doubled data. Maybe this is because loadCurrency() starts before performRequest() able to receive data from JSON and save it to context.
I tried also to not save context in parseJSON() but first through delegate method send it to VC and perform save to context and load from context from here. Then tableView loads from the first launch. But then every time app starts in my CoreData database I see an increase of the same data (33, 66, 99 lines).
My goal is to save parsed data to CoreData once (either where I parseJSON or in VC) and change only currentValue attribute when user want to update it.
How to make it correct?

A: You need to first choose which is your source of truth where you are showing data from. In your case it seems to be your local database which is filled from some external source.
If you wish to use your local database with data provided from remote server then you need to have some information to keep track of "same" entries. This is most usually achieved by using an id, an identifier which is unique between entries and persistent over changes in entry. Any other property may be used that corresponds to those rules. For instance CharCode may be sufficient in your case if there will always be only one of them.
Next to that you may need a deleted flag which means that you also get deleted items from server and when you find entry with deleted flag set to true you need to delete this object.
Now your pseudo code when getting items from server you should do:
func processEntries(_ remoteEntries: [CurrencyEntry]) {
    remoteEntries.forEach { remoteEntry in
        if remoteEntry.isDeleted {
            if let existingLocalEntry = database.currencyWithID(remoteEntry.id) {
                existingLocalEntry.deleteFromDatabase()
            }
        } else {
            if let existingLocalEntry = database.currencyWithID(remoteEntry.id) {
                database.updateCurrency(existingLocalEntry, withRemoteEntry: remoteEntry)
            } else {
                database.createCurrency(fromRemoteEntry: remoteEntry)
            }
        }
    }
}

And this is just for synchronization approach.

Now going to your view controller. When it appears you call to reload data from server and at the same time display whatever is in your database. This is all fine but you are missing a re-display once new data is available.
What you optimally need is another hook where your view controller will be notified when database has changes. So best thing to do is add event when your database changes which is whenever you save your database. You probably looking at something like this:
extension Database {

    func save() {
        guard context.hasChanges else { return }
        try? context.save()
        self.notifyListenersOfChangesInDatabase()
    }

and this method would be called within your parseJSON and everywhere else that you save your database. Then you would add your view controller as a listener on your database as
override func viewDidLoad() {
    super.viewDidLoad()
    database.addListener(self)
    currencyNetworking.performRequest()
    loadCurrency()
}

How exactly will listener and database be connected is up to you. I would suggest using delegate approach but it would mean a bit more work. So another simpler approach is using NotificationCenter which should have a lot of examples online, including on StackOverflow. The result will be

*

*Instead of database.addListener(self) you have NotificationCenter.default.addObserver...

*Instead of notifyListenersOfChangesInDatabase you use NotificationCenter.default.post...
In any of the cases you get a method in your view controller which is triggered whenever your database is changed. And in that method you call loadCurrency. This is pretty amazing because now you don't care who updated the data in your database, why and when. Whenever the change occurs you reload your data and user sees changes. For instance you could have a timer that pools for new data every few minutes and everything would just work without you needing to change anything.

The other approach you can do is simply add a closure to your performRequest method which triggers as soon as your request is done. This way your code should be like
override func viewDidLoad() {
    super.viewDidLoad()

    loadCurrency()
    currencyNetworking.performRequest {
        self.loadCurrency()
    }
}

note that loadCurrency is called twice. It means that we first want to show whatever is stored in local database so that user sees his data more or less instantly. At the same time we send out a request to remote server which may take a while. And once server response finished processing a reload is done again and user can view updated data.
Your method performRequest could then look like something as the following:
func performRequest(_ completion: @escaping () -> Void) {
    getDataFromRemoteServer { rawData in
        parseJSON(with: rawData)
        completion()
    }
}


text:
Q: Support Vector Machine on Hadoop Is there is an implementation of Support Vector Machine on Hadoop ?
I am looking for a code that lets me train and then test the SVM Model on top of Hadoop.

A: Somebody is working on an implementation on top of Apache Hama with BSP, which is basically a port of the MPI version of this project:
http://code.google.com/p/psvm/
You can track his progress here:
https://github.com/truncs/hello-world
https://github.com/truncs/psvm
I guess it will take 1-2 months to finish it, the main part is actually running.


text:
Q: Obtener formato de fecha específico Angular2 Quiero obtener un formato de fecha determinada recibo : "15/03/2016" y quiero obtener este formato 2016-03-15T00:00:00+01:00
He probado con :
  dateStart = new Date(filterDateStart.split('/').reverse().join('/'));
  dateStart = new Date(filterDateEnd).toLocaleDateString();
  dateStart =  new Date(filterDateStart).toISOString();
  dateStart = new Date(filterDateStart.split('/').reverse().toISOString('/'));

No me funciona ninguno...

A: Creo que lo más sencillo para formatear sería usar la librería moment.js:

const FORMATO_ENTRADA = 'DD-MM-YYYY';
const FORMATO_SALIDA = 'YYYY-MM-DDTHH:mm:ss Z';
const fecha = moment('15/06/2018',FORMATO_ENTRADA);

console.log(fecha.format(FORMATO_SALIDA))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment-with-locales.min.js"></script>

En un proyecto Angular:

*

*Instalas la librería con npm i moment.

*En el fichero (componente o servicio) la importas así:
import * as moment from 'moment';


text:
Q: Godot: Node as child of Node2D stays visible when parent turns invisible turning a Node2D invisible does not apply to it's base-class-Node children – these stay visible. Changing their type to Node2D then makes them become invisible along with the parent.
I see that a base-Node cannot be turned invisibe, but having some buried deep within my scene-tree, I wonder if it wouldn't be practical to have them adopt the behaviour of their parent in such a case.
Is there a reason for this behaviour? And can I somehow make a Node get invisible in such a case as well?

A: The Inheritance chain for a Node2D looks like this:
Node2D < CanvasItem < Node < Object

The visibility property is on the CanvasItem. So, the Node2D has that property because it inherits from CanvasItem. A Node does not have a visibility property, and therefore, it's not possible to set such a property there.
Additionally, a Node item by itself is not visible in-game. That is, there's nothing rendered for it by default.

Sprite1
    Node2D
        Sprite2

If you turn off visibility of Sprite1, then Sprite2 is also made invisible.
However, with this structure:
Sprite1
    Node
        Sprite2

Turning off the visibility of Sprite1 does not impact the visibility of Sprite2.
(Thanks to Jgodfrey on godotengine.org!)


text:
Q: Passing a pointer of inaccessible private base type to the derived class method This code example would describe the language feature I find non-intuitive.
class A {
public:
  A() {}
};

class B: private A
{
public:
  B() {}
};

class C: public B
{
public:
  C() {}
  void ProcessA(A* a) {
  }
};

int main() {
  C c;
}

Compilation of this code with Apple LLVM version 4.2 on Mac produces an
test.cc:16: error: 'class A' is inaccessible
test.cc:16: error: within this context

Replacing void ProcessA(A* a) with void ProcessA(::A* a) would make it build but I don't understand why should I use absolute class name here.
Is it a language feature that is there to avoid certain kind of errors or is it just a dark C++ grammar corner like requirement to put space between angle brackets (> >) in templates parametrized with other templates.
Thanks!

A: Human talk
I 'll start by describing what happens here -- forgive me if you already know this, but it creates necessary context for the follow-up.
The compiler resolves the unqualified A to ::C::A (the result will be the same if you make the change at source level yourself). Since ::C::A is inaccessible an error message is emitted.
You are proposing that the compiler should detect that ::C::A is inaccessible and the reference to A should then be considered a reference to ::A as a fallback. However, ::C::A and ::A may easily be two entirely different things.
Automatically guessing what should be done here is not only prone to introducing bugs and/or hair-pulling¹, but also completely contrary to the spirit of C++.
Standardese
Confirmation that this behavior is conformant and by-design, directly from the C++11 standard.
§9/2 says:

A class-name is inserted into the scope in which it is declared
  immediately after the class-name is seen. The class-name is also
  inserted into the scope of the class itself; this is known as the
  injected-class-name.

This means that inside the scope of class C, A is an injected-class-name.
§3.4/3 states that the injected-class-name is a candidate for name lookups:

The injected-class-name of a class is also considered to be a member
  of that class for the purposes of name hiding and lookup.

§3.4/1 clarifies that the inaccessibility of the base A does not prevent the injected-class-name A from being considered:

The access rules are considered only once name lookup and function
  overload resolution (if applicable) have succeeded.

§11.1/5 gives a direct explanation of the exact situation under discussion:

[Note: In a derived class, the lookup of a base class name will find
  the injected-class-name instead of the name of the base class in the
  scope in which it was declared. The injected-class-name might be less
  accessible than the name of the base class in the scope in which it
  was declared. —end note ]

The standard also gives this example, which is equivalent to yours:
class A { };
class B : private A { };
class C : public B {
    A *p;   // error: injected-class-name A is inaccessible
    ::A *q; // OK
};

¹ Imagine what happens if A is initially a public base, then later becomes private during a refactoring. Also imagine that ::A and ::C::A are unrelated. You would expect that a call like a->foo() (which used to work) would fail because foo is no longer accessible, but instead of this the type of a has changed behind your back and you now get a "there is no method foo" error. Huh?!? And that's of course far from the worst that could happen.


text:
Q: How do I print the list of changeset hashes on a given branch, in Mercurial? If I issue this command in terminal in a git repository it gives me commit unique ids or what I know as revision list, like below:
$ git rev-list --reverse master

de1ea6c8a9cd195b348562f42c6cef5bd3555748
2da45a72621e5c611e0d9f47fa7799fc24476c3c

How can I achieve the same result in Mercurial repository?

A: Basically, it's an output customization on the hg log command:
$ hg log --template '{node}\n'
75f18c4e5caaa5dd1e82f8a1ef1af8f55659fe15
9f15509b1ec305e688f8d524dc902f82000f5526
3199dde60fae0d9b4f9b674a96297bf6c0eec1a6
b3fcf3e324426dc2b5035df18804e8e8044d4f07
11ea8be87677152e1041ee1437c8cc47f0d96115

You can supply -r to specify which revset you want to display, like -r 100:200 (changesets since #100 up to #200) or -r "ancestors(v1.1)" (what was included in version 1.1).
Note that you can specify other fields like {desc} or {rev}. See also the Mercurial book.


text:
Q: Scrollbar not restored on modal hide I have a modal and is opened by clicking on button.
When this modal is opened then i am getting 2 scroll bars,

*

*first for Modal

*second for html/body

I tried removing scrollbar as below:
if ($(".dialog-popup-open").length > 0) {
    $('html').css('overflow','hidden');
}
$(".closeButton").off("click").on("click", function () {
     $('html').css('overflow','scroll');
     //$('html').css('overflow','inherit');
}

Scroll bar is hiding perfectly but not restoring when modal is closed.
Any ideas please?
i tried both scroll and inherit

A: Can you please try this one:

$("#openModal").click(function(){
  //code to open the overlay
  //....
  //....

  //add modalActive class to html tag
  $("html").addClass("modalActive");
  });

$(".closeButton").off("click").on("click", function () {

  //code to close the modal overlay
  //...
  //...

  //remove modalActive class from html
  $('html').removeClass("modalActive");

});
.modalActive{
  overflow: hidden;
  }

A: You need to give that to body:
$('body').css('overflow','auto');


text:
Q: Integrar Facebook Login na aplicação. Erro no keytool Olá,
Estou tentando realizar integrar o login do Facebook na minha aplicação, para quando o usuário se cadastrar ele poder fazer isso com o Facebook.
Já vi vários tutoriais aqui - no site-  e pela internet de como se faz. Mas para pegar a chave hash estou com um problema.
O que estou fazendo:

*

*Entro no CMD

*Faço o comando para ir até o diretório cd C:/usuario/artur/.android

*Depois aqui dentro eu coloco os comandos que o próprio site do facebook ensina e outros tutoriais também:

*keytool -exportcert -alias androiddebugkey -keystore
%HOMEPATH%.android\debug.keystore | openssl sha1 -binary | openssl
base64
Mas aparece a mensagem mostrando que o windows não reconhece o comando keytool
Em outros tutoriais que vi, ao invés de apontar o caminho para user/artur/.android era para apontar no cmd para c:/programs/java/java7
Tentei fazer isto e aqui dentro reconhece o comando keytool, mas não reconhece o comando openssl.
Sério, devo ter visto no minimo umas 10 tutoriais diferente, desde quando a IDE principal era o Eclipse até tutoriais mais recentes com android 2.3
Alguém já passou por isso ? Se alguém puder me dar uma luz, porque já não sei mais o que faço ou o que estou fazendo de errado


text:
Q: Right way to compose an action as a sequence of multiple smaller actions? I have three actions defined like so:
public class A extends AbstractAction;
public class B extends AbstractAction;
public class C extends AbstractAction;

Now I want to define a jumbo action that does these three actions in order. I am sure there is a better way to do this than to do the following:
public class JumboAction extends AbstractAction {

  ...

  public void actionPerformed(ActionEvent e) {
    new A().actionPerformed(null);
    new B().actionPerformed(null);
    new C().actionPerformed(null);
  }
}

I just dont know what the better way is. Can someone please point me to that?

To add more context as suggested in answers, my application has some UI elements (like nodes and edges), and the user can select a bunch of nodes and perform A, B, C, or JumboAction on them.

A: This idea of one control calling others as you're doing doesn't smell right to me, as if you're confusing the control with the model (ignoring also your use of null for the ActionEvents). The control should change the state of the model by calling model methods. Why not have your jumbo control call three (or more) model methods or whatever else is required, in order to complete its needs.
Perhaps you can give us a better understanding of your problem by giving more information about the concrete specifics of your problem as they may be just as or more important than the abstract ideas.

A: The way you're doing it is just fine.
The only thing I would do differently is replace actionPerformed(null) with actionPerformed(e). This would allow for A, B, and C to access the ActionEvent in context.
edit: If actions A, B, and C were not intended to be used individually as well, I would recommend combining the actions into three methods within the JumboAction class.

A: It seem to me that you are going outside the purpose of the Action classes because you are passing null to the actionPerformed methods.
Consider encapsulating your execution logic (business or otherwise) in a separate set of classes class and call those from the actions.
It will remove the need to duplicate the code and give you cleaner Action classes that do what they are supposed to do.
You can if you wish to use the same order have another method calling the business logic classes in an pre defined order.
Also check out the Command pattern, particularly the macro command area. Perhaps you can benefit from some adaptation of that.


text:
Q: Fotorama Wordpress Plugin I have "WordPress 3.7.5" installed and i get the following errors on page load (via element explorer)
http://fotorama.s3.amazonaws.com/4.4.6/fotorama.css Failed to load resource: the server responded with a status of 403 (Forbidden)
http://fotorama.s3.amazonaws.com/4.4.6/fotorama.js Failed to load resource: the server responded with a status of 403 (Forbidden)
http://fotorama.s3.amazonaws.com/4.4.6/fotorama.css Failed to load resource: the server responded with a status of 403 (Forbidden)

Can anyone help?


text:
Q: Aqua Data studio not connected to remote Database using Db2 I am using Db2 and Aqua data studio 14.0.1, when trying to register a server I am getting error and unable to connect to remote Server.
Getting these two messages when click 'Test Connection':
1- Your server is accepting socket connections on HostName
and then
2-
com.ibm.db2.jcc.am.SqlException: DatabaseName
at com.ibm.db2.jcc.am.ed.a(ed.java:679)
at com.ibm.db2.jcc.am.ed.a(ed.java:60)
at com.ibm.db2.jcc.am.ed.a(ed.java:127)
at com.ibm.db2.jcc.am.jb.a(jb.java:4485)
at com.ibm.db2.jcc.t4.ab.q(ab.java:713)
at com.ibm.db2.jcc.t4.ab.p(ab.java:586)
at com.ibm.db2.jcc.t4.ab.l(ab.java:407)
at com.ibm.db2.jcc.t4.ab.d(ab.java:145)
at com.ibm.db2.jcc.t4.b.Uc(b.java:1266)
at com.ibm.db2.jcc.t4.b.b(b.java:1184)
at com.ibm.db2.jcc.t4.b.a(b.java:5516)
at com.ibm.db2.jcc.t4.b.c(b.java:739)
at com.ibm.db2.jcc.t4.b.b(b.java:682)
at com.ibm.db2.jcc.t4.b.a(b.java:365)
at com.ibm.db2.jcc.t4.b.<init>(b.java:305)
at com.ibm.db2.jcc.DB2SimpleDataSource.getConnection(DB2SimpleDataSource.java:214)
at com.ibm.db2.jcc.DB2Driver.connect(DB2Driver.java:460)
at \\...\\ .\\हिñçêČάй語简�?한\\.eꋺꀈᠵ⧸ 4 int.a(Unknown Source)
at \\...\\ .\\हिñçêČάй語简�?한\\.tꄢꑪ⢎ꑅ default.Eu(Unknown Source)
at \\...\\ .\\हिñçêČάй語简�?한\\.tꄢꑪ⢎ꑅ default.ai(Unknown Source)
at \\...\\ .\\हिñçêČάй語简�?한\\.tꄢꑪ⢎ꑅ default.getConnection(Unknown Source)
at \\...\\ .\\हिñçêČάй語简�?한\\.tꄢꑪ⢎ꑅ default.getConnection(Unknown Source)
at \\...\\ .\\हिñçêČάй語简�?한\\.uꅭꌡꄒꂛ 2.ct(Unknown Source)
at \\...\\ .\\हिñçêČάй語简�?한\\.uꅭꌡꄒꂛ 2.c(Unknown Source)
at \\...\\ .\\हिñçêČάй語简�?한\\.Jᢔꋩ⢱ꅒ static double.d(Unknown Source)
at \\...\\ .\\हिñçêČάй語简�?한\\.Jᢔꋩ⢱ꅒ static double.b(Unknown Source)
at \\...\\ .\\हिñçêČάй語简�?한\\.Iꏏ⡚ꁮꑯ.Os(Unknown Source)
at \\...\\ .\\हिñçêČάй語简�?한\\.zꂚꁮꊗᛝ continue private.run(Unknown Source)

While If I use same properties and remote Db with some other version of Aqua data Studio, it works fine.
Is there any bug in this version of Aqua Studio?

A: Aqua Studio contains db2 java driver that might does not work properly with your DB2. Please copy with replace db2java.jar or db2cc.jar files from your DB2 installation into Aqua Data Studio drivers folder and try to connect again.


text:
Q: How does ActiveRecord::Relation get added to Rails' models and why does each model have individual Relation class? Suppose I have a Rails model: class Project < ActiveRecord::Base
In the Rails console:
> Project.all
=> #<ActiveRecord::Relation []>

That seems reasonable. However,
> Project.all.class
=> Project::ActiveRecord_Relation

What is Project::ActiveRecord_Relation? Specifically,

*

*How did it get "added" (namespaced into) to my model class?

*How does it respond to is_a? correctly? Project.all.is_a?(ActiveRecord::Relation) returns true (which is expected), but is Project::ActiveRecord_Relation actually an instance of ActiveRecord::Relation, or is it something else?

*Why do this? Why doesn't Project.all return an ActiveRecord::Relation, rather than Project::ActiveRecord_Relation?

(This is in the context of Rails 5.1, in case it's changed in older or newer versions.)
(I'm open to title edits if someone else can come up with a better title for this question)

A: Check this line of code from ActiveRecord.
https://github.com/rails/rails/blob/f40860800c231ecd1daef6cf6b5a8a8eda76478d/activerecord/lib/active_record/relation/delegation.rb#L23
mangled_name = klass.name.gsub("::", "_")

So, for your questions:

*

*it get's added on activerecord's base when it extendes the delegation module https://github.com/rails/rails/blob/f40860800c231ecd1daef6cf6b5a8a8eda76478d/activerecord/lib/active_record/base.rb#L290

*it's actually the same class, just something like an alias (not actually an alias, it's a constant with the class as value)

*the class is actually an ActiveRecord::Relation, it's just that the name was changed

A: There are actually two questions you are asking:

*

*How does it work?

*Why is it like that? (What for?)

@arieljuod has already given you some explanations and a link.
However the second question is still unanswered.
There is another similar question exists which I hope will help you find all the answers:
How can an ActiveRecord::Relation object call class methods
It looks like the two questions (by the link and yours one) answer each other )
Take a look at @nikita-shilnikov's answer. Good luck in your investigation!


text:
Q: How to detect to much memory being used in browser I am writing client side applications, but regularly run into an issue whereby I am using to much memory on a lower end device and it stops processing javascript to compensate for this.  This appears to be a common 'solution' to this problem on lower end devices.
Is there any reasonable way to detect memory usage and/or limits or when the limit has been reached and scripts are failing, etc.
If I can detect this, I can implement solutions to handle it (like limit caching, more lazy loading, etc.)
Please do not mark my question as duplicate to a question whose only answers are about how to detect memory usage and not about estimating memory limitations!

A: This might help you:
http://www.monitis.com/blog/2011/05/15/30-tips-to-improve-javascript-performance/
As for page performance:

*

*Use 'Profiles' tab in chrome developer window(press F12 to fire it up)

*Firebug profiler in Firefox


text:
Q: store pivot table into csv - preserve all data While trying to store the result of pivot_table to csv, it doesn't preserve all the data (headers)
Here's the sample code :
data = [{'TestPriority': 3, 'AutomationStatus': 'Done'},
{'TestPriority': 4, 'AutomationStatus': 'Review'}, {'TestPriority': 2,
'AutomationStatus': 'Review for Automation'}, {'TestPriority': 2,
'AutomationStatus': 'Review for Automation'}]

df = pd.DataFrame(data)
df['AutomationStatus'] = np.where(
    df['AutomationStatus'] == 'Done', 'Automated', 'Manual')
res = df.pivot_table(
    index='AutomationStatus', columns=['TestPriority'],
    aggfunc=len, fill_value=0)
print(res)

res.to_csv('sample.csv', sep=',')

the result of print statement is like:
TestPriority      2  3  4
AutomationStatus
Automated         0  1  0
Manual            2  0  1

while generated csv does not show TestPriority header:
AutomationStatus,2,3,4
Automated,0,1,0
Manual,2,0,1

Any suggestions on how to properly store the result of pivot_table to csv without loosing data?


text: Q: Модуль Page (генерация страниц) в CMS на Python Всем привет. Я хочу изобрести велосипед, сделать свою CMS на питоне. У меня есть проблема с пониманием модуля Page. Как генирируются страницы, что для этого нужно? Помогите пожалуйста, искал много где информацию и не нашёл. Даже если вы на php, помогите, прошу, принцип же один и тот же, наверное...


text:
Q: Mysql statement to select distinct rows from two columns I'm trying to write a mysql statement that pulls only unique messages from my chat system.
There is a to_id and a from_id. I want to pull one row from every conversation.
The problem is if there is a row with
    to_id = 1
    from_id = 2
and another row with
    to_id = 2
    from_id = 1
I want both of these rows to be treated as the same.
The statement I came up with is "SELECT * FROM chat_messages GROUP BY to_id,from_id ". This works except for the situation I mentioned above.
Another attempt I made was using "SELECT DISTINCT least(to_id,from_id) as value1, greatest(to_id,from_id) as value2 from chat_messages ".
This returns what I need but I do not know how to get the rest of the information from the row like the message, timestamp etc. It only gives me value1 & value2 which are the to_id & from_id.

A: Just use the expressions in the second query for the GROUP BY of the first query:
SELECT * FROM chat_messages GROUP BY LEAST(to_id,from_id), GREATEST(to_id,from_id)

A: If second query returns what you expect, then below query returns rest information:
SELECT *
FROM chat_messages t1 INNER JOIN (
    SELECT DISTINCT LEAST(to_id, from_id) AS value1,
        GREATEST(to_id, from_id) AS value2
    FROM chat_messages
) t2 ON t1.to_id = value1 AND t1.from_id = value2;


text:
Q: Getting started with iPython notebook Please don't consider this a duplicate.  I have seen a similar post and the recommended solution has not solved my issue.  I need input for I can't find a solution elsewhere and iPython does not seem to have a support forum.
I am trying to use iPython notebook on Kubuntu 14.04 but can not get it to launch.  I found this post and tried the recommended solution of installing dependencies. The system states that python-pip and python-dev are already the newest version.  There is no response for build-essential.
If one uses pip to install a python package, does it make a difference which Python interpreter is launched?  Troubleshooting this issue I discovered Python 2.7.6 & 3.4.0 are installed on my system.  Would that make a difference?  From my reading of the requirements, iPython should work on either version of Python.
In research to find a solution I came across ipython notebook --notebook-dir='<path/to/notebooks>'. I set the variable to a path under my home directory.  That did not make a difference.  If it try to start by entering ipython notebook I get the following Tracebacks:
Traceback (most recent call last):
  File "/usr/local/bin/ipython", line 11, in <module>
    sys.exit(start_ipython())
  File "/usr/local/lib/python2.7/dist-packages/IPython/__init__.py", line 120, in start_ipython
    return launch_new_instance(argv=argv, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/IPython/config/application.py", line 573, in launch_instance
    app.initialize(argv)
  File "<string>", line 2, in initialize
  File "/usr/local/lib/python2.7/dist-packages/IPython/config/application.py", line 75, in catch_config_error
    return method(app, *args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/IPython/terminal/ipapp.py", line 321, in initialize
    super(TerminalIPythonApp, self).initialize(argv)
  File "<string>", line 2, in initialize
  File "/usr/local/lib/python2.7/dist-packages/IPython/config/application.py", line 75, in catch_config_error
    return method(app, *args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/IPython/core/application.py", line 369, in initialize
    self.parse_command_line(argv)
  File "/usr/local/lib/python2.7/dist-packages/IPython/terminal/ipapp.py", line 316, in parse_command_line
    return super(TerminalIPythonApp, self).parse_command_line(argv)
  File "<string>", line 2, in parse_command_line
  File "/usr/local/lib/python2.7/dist-packages/IPython/config/application.py", line 75, in catch_config_error
    return method(app, *args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/IPython/config/application.py", line 471, in parse_command_line
    return self.initialize_subcommand(subc, subargv)
  File "<string>", line 2, in initialize_subcommand
  File "/usr/local/lib/python2.7/dist-packages/IPython/config/application.py", line 75, in catch_config_error
    return method(app, *args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/IPython/config/application.py", line 402, in initialize_subcommand
    subapp = import_item(subapp)
  File "/usr/local/lib/python2.7/dist-packages/IPython/utils/importstring.py", line 42, in import_item
    module = __import__(package, fromlist=[obj])
  File "/usr/local/lib/python2.7/dist-packages/IPython/html/notebookapp.py", line 30, in <module>
    check_for_zmq('13', 'IPython.html')
  File "/usr/local/lib/python2.7/dist-packages/IPython/utils/zmqrelated.py", line 12, in check_for_zmq
    raise ImportError("%s requires pyzmq >= %s"%(required_by, minimum_version))
ImportError: IPython.html requires pyzmq >= 13

Additional questions
After Steve Barnes  advice I am not sure everything working as it should.  For iPython to work, I had to create the directory for notebooks under the root of all other websites on my machine.
Entering ipython notebook in a command prompt I get the following output:
16:33:11 Fri Jul 31 - ~/www/ipython_notebooks
$> ipython notebook
[I 16:33:15.571 NotebookApp] Using MathJax from CDN: https://cdn.mathjax.org/mathjax/latest/MathJax.js
[I 16:33:15.588 NotebookApp] Serving notebooks from local directory: /home/daniel/www/ipython_notebooks
[I 16:33:15.588 NotebookApp] 0 active kernels
[I 16:33:15.589 NotebookApp] The IPython Notebook is running at: http://localhost:8888/
[I 16:33:15.589 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
[W 16:33:16.801 NotebookApp] 405 HEAD /tree (127.0.0.1) 5.74ms referer=None

In my browser the url is unexpected.  It displays as
file:///var/tmp/kdecache-daniel/krun/6915_0_tree

and the content appears as HTML with no CSS. Any links or dropdowns don't work.
To get the web page to work as expected it is necessary to type the url http://localhost:8888/notebooks/ explicitly. The page rendered next is unexpected either for Jupyter and not iPython.
I would like to include screenshots but apparently I don't have sufficient reputation to do so.  I feel there is something I am missing.  Can someone offer if they have had a similar result and how to fix it?

A: The last line tells what your problem is:
ImportError: IPython.html requires pyzmq >= 13

Your system either has no pyzmq or an old version - try:
sudo pip install -U pyzmq

The -U is the same as --upgrade and will request the installation of the latest version of pyzmq that is compatible with your version of python.
You may have to install some other dependencies to get this to work such as the python-dev package that matches your current version of python, which will need to be installed with apt-get install.
There may well be additional unmet and optional dependencies of iPython and its notebook for you to meet, for the majority sudo pip install -U name_of_component will do the trick. I would also suggest reading up on python virtual-env
Some more notes
Once iPython is running in notebook mode you will need browse to localhost:8888http://tree or //localhost:8888/tree as is shown by the last line in the command window, note that /tree is a view type not an actual directory and any notebooks and sub-directories in directory that you started iPython from will be shown.
You may also be confused to see that the server is now called jupyter this is because the notebook functionality from iPython has grown into, and is now being maintained and developed as, a separate project that supports Python 2/3, Julia, R, Haskell, Ruby and many other languages.
One server can open kernels running any of them that you have installed on your machine as well as you being able to mix some of them in a single notebook by using the magic commands.


text:
Q: target is not a jdk root. system library was not found. in eclipse 4.8 photon + jdk-10.0.2 I've tried to add JRE10 in Eclipse 4.8 Photon (Windows -> Preferences -> Java -> Installed JREs -> Add...). Unfortunately I've received the following error message:
target is not a jdk root. system library was not found.
I've already read this question and the related answers but since it is about different versions of Eclipse and JRE I wonder if somebody encountered a problem like mine and if somebody knows a solution about it. Thank you in advance.


text:
Q: Showing ads only to 20% percent of visitors. Or different ads to another 80% visitors How can I showing ads to only to 20% percent of visitors in a PHP file? Or showing different ads to another 80% visitors?
Any way that can work, maybe using time intervals, like the visitors that visit the site at minute 0-12 only that show it, and visitors that visit the site at minute 13-59 is not or another method would work.
Please help or share if you have, this should be easy enough and many people should need it, already googling it but still can't find it

A: I would simply go with a random number:
if (rand(0, 100) <= 20)
{
  ShowAd(1);
} else {
  ShowAd(2);
}

A: Try searching SO?
$adPercent = 20;
if (rand(0, 100) < $adPercent) {
   echo '
Buy now!
';
}

Got this from here:
Display Ads To % of Users

A: One possible, simple solution using random number generator:
$randInteger = rand(1, 10); // Generate a random number in variable $randInteger.
if ($randInteger <= 2) // If the integer is 1 or 2, show the 20% ad.
{
    showTwentyPercentAd();
}
else if ($randInteger >= 3) // Otherwise, if the integer is 3-10, show the 80% ad.
{
    showEightyPercentAd();
}

Hopefully, this is clear how the code is structured.


text:
Q: Make filters appear above column ExtJs 4.1.3 I have filters activated on each column in this ExtJs panel grid that appear as drop downs for each column. Is there a way to make them appear automatically above each corresponding column?
Desired outcome
fiddle

A: Some ideas here: ExtJs - Filter a grid with a search field in the column header
Basically you can add a text field as a sub component in the items of a column config. In that linked example they use Ext.form.field.Trigger.
Then add a listener on that field for whatever event you want to trigger the filter. In your handler, get a reference to the store and manually filter it as needed based on the text field input.


text:
Q: How to calculate stats for one column against another column in a data frame? I have a data frame with the columns 'age' (int) and 'gender' which is a factor.
How would I calculate for each gender (male and female) separately, the median, mean, quantile (for probs=0.25) and quantile (for probs=0.75) for the age column?
Thanks!

A: You can use aggregate:
aggregate(Age ~ Gender, data, summary)
  Gender Age.Min. Age.1st Qu. Age.Median Age.Mean Age.3rd Qu. Age.Max.
1 Female 21.00000    32.00000   43.00000 50.55556    69.00000 97.00000
2   Male  3.00000    26.00000   70.00000 55.72727    78.50000 95.00000

If you don't like the summary function, there are many other options.
Sample Data:
data <- data.frame( Age = sample(1:100,20, replace = TRUE), Gender = sample(factor(c("Female","Male")),20, replace = TRUE))


text:
Q: Regex para hacer replace de caracteres específicos dentro de paréntesis (JS) Necesito hacer un replace con regex de caracteres especificos dentro de los parentesis el caso de ejemplo seria el siguiente string
color:rgba(218;7;7;056);font-size:25px;font-family:
solo seria cambiar los ";" (punto y coma) que estan dentro de los parentesis por comas ","
lo intente de la siguiente manera titleconfrecoma.replace(/(([\;]+))/, ",") y me devuelve como resultado color:rgba(218,7;7;056);font-size:25px;font-family: . pero si le agrego titleconfrecoma.replace(/(([\;]+))/g, ",") me altera todos los ";" no solo los que estan dentro del parentesis

A: listo para quien lo necesite lo hice de la siguiente manera
 var titleconfrecoma = "rgba(218;7;7;056);font-size:25px;font-family:";
var res = titleconfrecoma.substring(parseInt(titleconfrecoma.indexOf("(")), parseInt(titleconfrecoma.indexOf(")"))+1);
var resAux = res;
res = res.replace(/;/g, ",");
 res = titleconfrecoma.replace(resAux, res);