Android manifest not updating app version from Gradle build

Question: Based on this Google document I'm expecting Gradle to update my manifest.xml file with a version number, notably this quoted section:
The defaultConfig element configures core settings and entries in the manifest file (AndroidManifest.xml) dynamically from the build system. The values in defaultConfig override those in the manifest file.

However when I change the version code or version name of my Gradle file, the values arent' changed in my manifest.

Is this normal behavior?
Which values, between the manifest and the gradle build, are stting version codes and names?
How can I make the connection between the manifest versions and the gradle build more visible?
Answer: Even I am facing the similar issue. It is the default behaviour of gradle system I guess. You need to update both AndroidManifest.xml and build.gradle seperately if there is any changes in sdk versions, version code, version name,etc. I am looking forward that these kinda issues must be fixed in upcoming releases.
Answer: I have versionCode(1.0.3) and versionName(8) in my build.gradle only and it had worked correctly for me in past.
Now I updated the versionCode to 1.0.4 and versionName to 1 but it kept on giving me error on Google play. I even tried adding the new versionCode and versionName to AndroidManifest.xml but it did not help. Only thing that worked was updating the versionName to a higher number (9). Something seems broken in the Google Play upload apk and verify mechanism. Hopefully my answer would save someone else's 1 hour for solving this silly bug.


Date Time Picker Validation

Question: In a form, the user is required to choose date and time in a picker, thereafter choose other fields and hit 'Done'.
I have a datetime picker that displays a date and time by default. Moreover, the user is allowed to type and erase the date and time. (by using keys and backspace).
In case a user doesn't fill an entire date as an entry.
I have to choose between either of the following two options:

Whether the date time picker should auto-fill the recent value on the user's behalf?
Or should the input field stay half-filled and then throw a 'Validation Error' like "Please Choose a Date and Time" ?
Answer: This depends on the context of the date picker.
If your users are likely to want to regularly use today's date then you automatically populate with todays date.
If, however, using today's is not possible (or is problematic for some other reason) then you need to throw an error.
I would recommend some simple testing with your target users to find out what they want to see.
(You will also need to test any error systems with them too so that you can be sure that they understand what is required from them when an error occurs.)
Answer: Depending on the context of the DateTime-picker I'd suggest considering adding a button next to it to populate the picker with a specified date (again, depending on context).
The button should be clearly defined so that the user knows what it does, use date.now(), a pre-selected date depending on the context or whatever.
This would allow the user a way to easily add the date to the picker or decide to add the date manually.
When it comes to Dates / Times it's always (in my opinion) important to use some sort of validation and formatting as regions etc have different formats etc.
Simply add an invisible label next to the picker that shows up in red forecolor to display what the error might be and what the user can do to fix it.
My biggest suggestion is to be clear with the requirements to the user, make it as easy as possible to fulfill those requirements - but don't dumb it down for him / her!

Date Time Picker Validation


How to retrieve data from mongoose and use it in every page

Question: I'm create a simple website where user have to register in it and subscribe to some challenge that is activated. I'm using passport to make the registration and the login form and save the user email and password into my DB. The problem is when I try to use the user email for example in another page.
Once a user have done the login my app redirect him to the profile page and there I can retrieve the data from the database, but when I try to use the data in another page I can't.
Someone know how to fix this?
my passport file
  passport.use('local-login', new LocalStrategy({
    // by default, local strategy uses username and password, we will         override with email
    usernameField : 'email',
    passwordField : 'password',
    passReqToCallback : true // allows us to pass back the entire request to the callback
},
    function(req, email, password, done) { // callback with email and password from our form

        // find a user whose email is the same as the forms email
        // we are checking to see if the user trying to login already exists
        User.findOne({ 'local.email' :  email }, function(err, user) {
            // if there are any errors, return the error before anything else
            if (err)
                return done(err);

            // if no user is found, return the message
            if (!user)
                return done(null, false, req.flash('loginMessage', 'No user found.')); // req.flash is the way to set flashdata using connect-flash

            // if the user is found but the password is wrong
            if (!user.validPassword(password))
                return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); // create the loginMessage and save it to session as flashdata

            // all is well, return successful user
            return done(null, user);
        });

    }));

here is my redirect page
  app.get('/login', function(req, res) {

    // render the page and pass in any flash data if it exists
    res.render('login.ejs', { message: req.flash('loginMessage') });
});

// process the login form
// app.post('/login', do all our passport stuff here);
app.post('/login', passport.authenticate('local-login', {
    successRedirect : '/partecipant', // redirect to the secure profile section
    failureRedirect : '/login', // redirect back to the signup page if there is an error
    failureFlash : true // allow flash messages
}));

my partecipant page, and here i can retrieve the data using this variable

id: <%= user.id %>

email:<%= user.local.email %>

password: <%= user.local.password %>

here is another page where i try to use the same variables as used in the partecipant page but It doesn't work

email:<%= user.local.email %>

Answer: After you authenticate a user with Passport, the user should be stored in req.user.
app.get('/particepant', function(req, res) {
    console.log(req.user);
});

What you can do is then create a local variable that is accessible to all views. You would set this variable in a middleware.
app.use(function(req, res, next) {
    res.locals.user = req.user;
    next();
});

app.get('/particepant', function(req, res) {
    console.log(req.user);
});

// and other routes


Mini Fridge thermostat turns on/off doesn't cool

Question: I have a Magic Chef Mini Fridge 2 door from Home Depot (HVDR430SE) that doesn't cool. It has no evaporator or condenser fan because it is a sealed unit. The thermostat clicks on, starting the compressor and turning it off also stops the compressor but nothing cools. Is the fridge worth fixing. It's new but I can't return it.
Comment: Why can't you return it?  Is it in warranty, and what would it cost to ship to MagicChef directly?
Comment: Is broken, is not made to be fixed - recycle and replace if you "can't return it" or otherwise get it solved (which will be replaced, not fixed) by the manufacturer.
Comment: I bought this from an auction for $25. I was hoping it would easily be repaired.   Guess not.
Answer: Throw it away and go buy another, they cost more to fix than to replace.
Comment: I'm not a big fan of buying another of something that breaks.  Maybe pick out a different minifridge.


MATLAB/Embedded Coder File Loading

Question: I generated code for loading a mat file as follows
data=coder.load('data.mat');
a=data.a;
b=data.b;

Because one of the variables, for example "a", is very big, it is defined as a big static const array in the main function with all values initialized there.
Is there any way I can make MATLAB Coder load data from a file in C Code instead of defining it as a variable in main function?
Answer: The MATLAB fread function is supported for code generation. So you can fwrite the data to a file in MATLAB and then fread it in the generated code. This will do a runtime read and avoid the giant constant in the generated code.
Comment: Try to specify the precision argument to `fread` and `fwrite`. Say you have `int32` values, then use `'int32'` to write and `'*int32'` to read them as 32-bit integers. Just change the type name for your example.
Answer: This is the exact code that we should use based on Ryan's answer:
load('Data.mat')
fileID = fopen('Data.bin', 'w');
fwrite(fileID, Matrix1,'uint64');
fclose(fileID);

fileID=fopen('Data.bin');
Matrix2=fread(fileID,[256,256],'uint64');
fclose(fileID);

Matrix 2 is now the same as Matrix 1. The trick for writing and reading is to use the same precision based on the data type.

MATLAB/Embedded Coder File Loading


Datatable edit delete and new buttons placement

Question: I am developing a web application which has a datatable in the user inteface. Datatable has got couple of common actions to do like the basic CRUD operations.
The questions is how & where should the buttons edit, delete and create be placed from the usability perspective.
Here is an example with table having edit and delete in each row. I feel it is duplication of buttons in each row, instead we can select one row and click on edit/delete button somewhere at the top as shown in this example
But, I am not sure that the later one is so clear to understand or usable for a naive user. Any thoughts would help.
Answer: I think the light color on hover in the first example is better and more fast and simple to use. The second one could really be confuse, and you should not have to click on each line (I didn't even noticed at first the I each line was clickable).
I suggest a simple solution, just show the edit/delete buttons (or icons) on the hover state. The table, in this case, remain with the same size (or smaller) since I deleted the last column and in that space the icons appear only on hover of each row.

The create button is probably better at the top left, and something more like the second example you gave (a more recognizable button) than the just text button on the first example is better too. Also, the filter "Show -number- entries" is too close of "Create new record", the create button should be more visible and elements too close like in this example could confuse and not give the right perception of the importance of it.


EhCache CacheManager with multiple EntityManagerFactory

Question: And one entityManagerFactory in spring-server.xml.
But i must generate one more entityManager, and i do it with
Persistence.createEntityManagerFactory("myotherpersistenceunitname");

but i get exception
Caused by: net.sf.ehcache.CacheException: Another unnamed CacheManager already exists in the same VM. Please provide unique names for each CacheManager in the config or do one of following:
1. Use one of the CacheManager.create() static factory methods to reuse same CacheManager with same name or create one if necessary
2. Shutdown the earlier cacheManager before creating new one with same name.
The source of the existing CacheManager is: DefaultConfigurationSource [ ehcache.xml or ehcache-failsafe.xml ]
    at net.sf.ehcache.CacheManager.assertNoCacheManagerExistsWithSameName(CacheManager.java:457)
    at net.sf.ehcache.CacheManager.init(CacheManager.java:354)
    at net.sf.ehcache.CacheManager.<init>(CacheManager.java:242)
    at net.sf.ehcache.hibernate.EhCacheRegionFactory.start(EhCacheRegionFactory.java:70)

spring.xml:
<context:property-placeholder location="classpath:application.properties"/>
    <context:component-scan base-package="merve.web.app" >
     <context:exclude-filter expression="org.springframework.stereotype.Controller" type="annotation" />
    </context:component-scan>
    <context:annotation-config/>
    <tx:annotation-driven transaction-manager="txManager" proxy-target-class="true"  />

    <cache:annotation-driven />

    <bean id="properties" class="merve.web.app.configuration.PropertyResourceConfiguration" />

    <bean id="entityManagerFactory"
          class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
         <property name="persistenceUnitName" value="myPU"/>
         <property name="dataSource" ref="dataSource" />
         <property name="jpaVendorAdapter">
             <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                 <property name="databasePlatform" value="${database.target}"/>
                 <property name="showSql" value="${database.showSql}" />
             </bean>
         </property>
    </bean>

    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${database.driver}"/>
        <property name="jdbcUrl" value="${database.url}"/>
        <property name="user" value="${database.username}"/>
        <property name="password" value="${database.password}"/>
        <property name="minPoolSize" value="2"/>
        <property name="maxPoolSize" value="10"/>
        <property name="breakAfterAcquireFailure" value="false"/>
        <property name="acquireRetryAttempts" value="3"/>
        <property name="idleConnectionTestPeriod" value="300" />
        <property name="testConnectionOnCheckout" value="true" />
    </bean>

    <bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>

    <bean id="jamesEntityManagerFactory"
          class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
         <property name="persistenceUnitName" value="jamesPU"/>
         <property name="dataSource" ref="dataSourceJames" />
         <property name="persistenceXmlLocation" value="classpath:META-INF/james-persistence.xml"/>
         <property name="jpaVendorAdapter">
             <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                 <property name="databasePlatform" value="org.hibernate.dialect.MySQL5InnoDBDialect"/>
                 <property name="showSql" value="true" />
             </bean>
         </property>
    </bean>

    <bean id="dataSourceJames" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="org.apache.derby.jdbc.EmbeddedDriver"/>
        <property name="jdbcUrl" value="jdbc:derby:../var/store/derby;create=true"/>
        <property name="user" value="app"/>
        <property name="password" value="app"/>
        <property name="minPoolSize" value="2"/>
        <property name="maxPoolSize" value="10"/>
        <property name="breakAfterAcquireFailure" value="false"/>
        <property name="acquireRetryAttempts" value="3"/>
        <property name="idleConnectionTestPeriod" value="300" />
        <property name="testConnectionOnCheckout" value="true" />
    </bean>

    <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

     <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basenames">
            <list>
                <value>messages</value>
            </list>
        </property>
    </bean>

    <bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" p:shared="true" p:config-location="classpath:ehcache.xml"/>

    <bean id="cacheManager"   class="org.springframework.cache.ehcache.EhCacheCacheManager" >
     <property name="cacheManager"><ref local="ehcache"></ref></property>
    </bean>

<dwr:configuration/>
    <dwr:annotation-scan base-package="tuxi.web.app.service.dwr" scanRemoteProxy="true" scanDataTransferObject="true"/>
    <dwr:url-mapping />

    <dwr:controller id="dwrController"/>

</beans>

Comment: Can you post your configuration files? I expect that you can make 2 cache managers with different names.
Comment: @mael i added spring.xml. how can i set names to cache maangers, i only can set ids for now. also should i tell entityManagerFactories to use which cache manager
Answer: The problem, described here, and fixed in the source is not using the EhCache singleton correctly.  The answer depends on which version of spring-context-support AND which version of EhCache you are using.  For both, you need to be using EhCache 2.6 or greater:
<dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache</artifactId>
    <version>2.6.0</version>
</dependency>

Next, determine what to do based on your spring-context-support version:
If using Spring 3.1/3.2
<bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
    p:shared="true"
    p:config-location="classpath:ehcache.xml"/>

If using Spring 4.x
<bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
    p:shared="false"
    P:acceptExisting="true"
    p:config-location="classpath:ehcache.xml"/>

Answer: Try naming both cacheManagers differently in ehcache.xml
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    name="ehCacheManager1">

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    name="ehCacheManager2">


Python finds a string in multiple files recursively and returns the file path

Question: I'm learning Python and would like to search for a keyword in multiple files recursively.
I have an example function which should find the *.doc extension in a directory.
Then, the function should open each file with that file extension and read it.
If a keyword is found while reading the file, the function should identify the file path and print it.
Else, if the keyword is not found, python should continue.
To do that, I have defined a function which takes two arguments:
def find_word(extension, word):
      # define the path for os.walk
      for dname, dirs, files in os.walk('/rootFolder'):
            #search for file name in files:
            for fname in files:
                  #define the path of each file
                  fpath = os.path.join(dname, fname)
                  #open each file and read it
                  with open(fpath) as f:
                        data=f.read()
                  # if data contains the word
                  if word in data:
                        #print the file path of that file
                        print (fpath)
                  else:
                        continue

Could you give me a hand to fix this code?
Thanks,
Comment: could you give us some input, and some output, what you expect and where the code fails?
Answer: .doc files are rich text files, i.e. they wont open with a simple text editor or python open method. In this case, you can use other python modules such as python-docx.
Update
For doc files (previous to Word 2007) you can also use other tools such as catdoc or antiword. Try the following.
import subprocess

def doc_to_text(filename):
    return subprocess.Popen(
        'catdoc -w "%s"' % filename,
        shell=True,
        stdout=subprocess.PIPE
    ).stdout.read()

print doc_to_text('fixtures/doc.doc')

Comment: Thanks for your reply. Python-docx works great with .docx files but I cannot make it work with .doc files. Any suggestion? Thanks!
Answer: def find_word(extension, word):
    for root, dirs, files in os.walk('/DOC'):
        # filter files for given extension:
        files = [fi for fi in files if fi.endswith(".{ext}".format(ext=extension))]
        for filename in files:
            path = os.path.join(root, filename)
            # open each file and read it
            with open(path) as f:
                # split() will create list of words and set will
                # create list of unique words
                words = set(f.read().split())
                if word in words:
                    print(path)

Answer: If you are trying to read .doc file in your code the this won't work. you will have to change the part where you are reading the file.
Here are some links for reading a .doc file in python.
extracting text from MS word files in python
Reading/Writing MS Word files in Python
Reading/Writing MS Word files in Python


How to search on a field that may be empty in zapier

Question: Trying to sync up a postgres record to airtable on create/update. The field has a couple of ids that I would like to check for in airtable to determine whether I should create a new record or update an existing one. The first id (optional_id) I need to search on can possibly be null. This causes the search to fail before it can get to the other id(required_id) that should always be populated. Is there any way I can skip the initial search for optional_id if it turns out to be null in postgres?
My current outline is as follows:
Answer: I would use a Formatter > Text > Default Value step in case the input value can be null and then make sure the fallback value is from a record that does not exist.
If further help is needed, feel free to reach out to us here:
https://zapier.com/app/get-help


Expected value of a random variable at a stopping time.

Question: Let $x_1,x_2 \dots$ be adapted to the filtration $\mathcal{F}_1, \mathcal{F}_2, \dots$.
Let $\tau$ be a stopping time that is also adapted to the filtration.
  Say that
$\mathbb{E}[x_i \mid \mathcal{F}_{i-1}] = 0$.
Is it true that
  $$\mathbb{E}[x_{\tau}] = 0?$$
One idea I had was to write $x_{n} = x_0 + (x_1 - x_0) + \dots + (x_{n}- x_{n-1}) = x_0 + \sum\limits_{i=1}^{n}z_i$ where $z_i = x_{i} - x_{i-1}$.
I thought perhaps the partial sums $S_n = \sum\limits_{i=1}^{n}z_i$ could be a martingale, and I could use the optional sampling theorem, but it doesn't seem to be the case.
Answer: Now I see this couldn't be the case: Suppose each $x_i$ is random variable that is $-1$ with probability $1/2$ and $+1$ with probability $1/2$. Then define $\tau = \inf\{ n \geq 1 \mid x_n =1\}$. Let $\mathcal{F}_n = \sigma(x_1,\dots, x_n)$. Then the assumptions hold but $\mathbb{E}[x_{\tau}] = 1$.
Comment: If the $x_i$'s are iid and have distribution Ind(p), then $\mathbb E[x_i| \mathcal F_{i-1}] = \mathbb E[x_i] =1-2p \ne 0$ if $p\neq 1/2$.
Comment: Yes, then the assumptions hold, and $x_\tau = 1$ with probability $1$.
Comment: True, thank you. Do you believe the counter example be valid if $p=1/2$?
Answer: Suppose $\tau$ is finite with probability one. Then $$ \mathbb E x_{\tau} = \mathbb E [ \mathbb E[x_\tau | \tau]] = \sum_n \mathbb E [x_\tau | \tau = n]P(\tau = n) $$
If $\tau$ is not finite, i.e. $P(\tau <\infty) <1$, then let $N$ be a positive integer and let $\tau_N := \min(\tau,N)$. Then $\tau_N$ is finite with probability 1, due to Fatou's lemma
$$ \mathbb E[x_\tau I(\tau<\infty)] = \mathbb E[\liminf_N x_{\tau_N} ]\le \liminf_N \mathbb E[x_{\tau_N}]. $$
Comment: $\tau$ finite a.s. is  not enough to get the desired conclusion. You should require $\tau \leq M$ a.s. for some constant $M$ (which happens rarely) or some less stringent conditions as the ones described in the corresponding wikipedia article https://en.wikipedia.org/wiki/Optional_stopping_theorem


Floor sinks 7 inches to the center over 25 feet

Question: I found out the floors in my condo sink 7 inches to the center over a 25 foot space.
I am wondering if maybe the floor joists are beyond repair ?
They want to put a pilar and beam under this to "stop" the sinking but I worry about everything above me.
We think a header or structural beam was removed 20 or more years ago and now it's just getting worse
For safety I wonder if there is anyway to repair a 7 inch drop ?
I feel like the only correct way and safe way is to guy rehab the whole tier but what are your thoughts.
The doors are all square so it looks like the sinking happened and they forgot to put a pilar underneath so it keeps sinking.
Wouldn't the joists be warped at 7 inch drop ?
Comment: What floor is your condo on? How may floors are above you? How many below? Can you access the structure below your unit? Is this a wood frame building? How old is the building?
Comment: Is it a dip(always there) of 7 inches or does the floor sink 7 inches when you are walking on it?  If it was me I would want out of there, hopefully with them giving me my money back.
Comment: Please edit your question to post photos
Comment: It's a condo...you must have neighbors...do they also have floors that are so out of level?
Answer: 7-in is a lot, but not unheard of. But whatever caused the sinking, you need to find out what it is.
Is this on a first floor, and you have access to the basement? Take a look.  It could be that a Lally column was removed and a girder splitting, or that the joists are undersized for the span, etc. etc. Why do you think that removing a header could cause this? As in a floor below, removing a header to a door frame? How could a "structural beam" be removed without the house collapsing? The beams I know have joists attached to them.
Yes, 7" drops can be repaired. For example, if this happened many years ago, say when the house was built 50 years ago, and then stopped, then you could just live with it. Or remove the floors and sister the joists and put new 3/4 subfloor and a new floor. Or, if the case is that a girder split, you might able to jack it up. Beware that if this happened over decades and the house is still moving, jacking the house will cause all sheetrock and plaster to crack. And the door frames were indeed redone, you'll have to redo them again.
Are the door frames plumb and square? That suggests that the house sank, they repaired, and it stopped sinking.
Answer: There is a 7 inch drop in a floor of a condo.
Any additional information is confusing and probably moot, because this is something that a structural engineer MUST be consulted about.
Any information or suggestions from those on this site would be a guess.


create and define properties and subproperties of a JS object

Question: I have a variable x which may have or not have some property propA, and I would like to affect some subproperty propA1, and creating propA along the way if needed, so a valid code would be
if ('propA' in x) {
    x.propA.propA1='0'
} else {
    x.propA={'propA1' : 0}
}

or I could do something with try..catch, but I have actually some long lists of nested properties and I would like some umbrella assumption such as
x.propA.propA1=0

which does not raise an error if x does not have a propA property, but instead creates it with {'propA1':0}
Or maybe in a nice JS code all this properties should be defined since the beginning? Alternatively I would like
x.propA.propA1

to return undefined and not raise an error if propA is not defined, but I imagine it's not how it is intented to be...
Comment: It's unclear what you're asking. Do you want to know which approach is considered "best practice"? Or are you looking for help on how to implement one of the approaches you mentioned?
Comment: what's the bad to use `if ('propA' in x)` ?
Comment: I al just looking for something more compact and as I'm here good practices are always nice to know
Answer: Sadly there's no equivalent of the new optional chaining operator for when you're setting a property, only when you're getting it.
What you're doing is already how you do this, though you can just test for the object rather than using in, which is might or might not be slightly more efficient but is definitely more idiomatic:
if (x.propA) { // *** Change is on this line
    x.propA.propA1='0'
} else {
    x.propA={'propA1' : 0}
}

That works because any object is truthy, and reading a non-existent property from an object results in the value undefined, which is falsy.
You can use a utility function for it if you like:
function setSub(obj, main, sub, value) {
    if (obj[main]) {
        obj[main][sub] = value;
    } else {
        obj[main] = {[sub]: value};
    }
    return obj;
}

Using it in your example:
setSub(x, "propA", "propA1", 0);

Another approach is to create a new object every time, which is frequently useful when following the guidelines of immutable programming, but does incur overhead:
x.propA = {...x.propA, propA1: 0};

Note that that even works when x.propA doesn't exist, because property spread notation explicitly allows spreading undefined and null — doing so adds no properties to the resulting object. So the above will copy the properties from x.propA if it's there, ignore it if it isn't, and include the propA: 0 property in the result:

const x1 = {};

x1.propA = {...x1.propA, propA1: 0};
console.log(x1);

const x2 = {propA: {}};

x2.propA = {...x2.propA, propA1: 0};
console.log(x2);

const x3 = {propA: {unrelated: "example"}};

x3.propA = {...x3.propA, propA1: 0};
console.log(x3);
.as-console-wrapper {
    max-height: 100% !important;
}
Comment: @MisterJojo - Since the OP's code would throw an error in that case (because the `in` test would be true and then they'd try to create a property on `null`), I think we can reasonably assume they don't do that.


What are the hidden combos in Oh! Edo Towns?

Question: I have been playing Oh! Edo Towns (the new Kairosoft game for iOS), and have created all the combos currently available to me. The game mentions needing to create "hidden" combos - what are these, and what buildings do they use?
Answer: Here is a translated document of the combo moves...
Oh Edo Combo Guide

Combo Name  Facility    Facility    Facility    Yield   Price   Total Cost

    Snack   Udon Shop   Soba Shop   Stew Cart   15%     10%     240G
    Flower  Dumpling S. Cherry Tree Pond        18%     5%      460G
    Sweets  Bun Shop    Bean Soup   Dumpling Sh 15%     10%     210G
    Plum    Pub         Rice Shop   Plum Tree   20%     10%     350G
   Kamakura Daibutsu    Bun Shop    Hydrangeas  24%     16%     890G
    Lunch   Rice Shop   Tempura Sh. Greengrocer 20%     8%      340G
    Noodle  Udon Shop   Soba Shop   Tempura Sh. 10%     5%      300G
    Refresh Public Bath Bucket Shop Nature*     10%     6%  210G+Nature
    Cart    Stew Cart   Merchant C. Nature*     10%     5%  160G+Nature
   Medicine School      Medicine S. Nature*     15%     10% 420G+Nature
    Jizo    Jizo Statue Straw Hat   Nature*     10%     10% 340G+Nature
    Rice    Rice Shop   Bun Shop    Nature*     5%      10% 170G+Nature
    Lucky   Kimono Shop Cat Statue  Nature*     10%     15% 700G+Nature
   Mountain Dumpling S. Jizo Statue Nature*     8%      8%  320G+Nature
   Hangover Stew Cart   Pub         Nature*     10%     5%  230G+Nature
    Study   School      Library     Nature*     10%     10% 450G+Nature
    Warrior Samurai Ho. 5-Rf Tower  Nature*     10%     5%  2600G+Nature
    Hairpin General St. Kimono Shop Nature*     10%     12% 400G+Nature
    Archive Jizo Statue Library     Nature*     15%     5%  410G+Nature
    Beauty  Public Bath Bucket Shop General St. 15%     10%     310G
    Sunny   Park        Jizo Statue Fire Alarm  12%     10%     470G
   Shipping General St. Greengrocer Medicine Sh 12%     10%     300G
    Fried   Tempura Sh. Bun Shop    Udon Shop   12%     10%     270G
    Fiery   Fire Stati. Fire Alarm  Well        25%     -        880G
    Fun     Zoo         Kabuki The. 5-Rf Tower  20%     5%      3400G
    Scholar School      Samurai Ho. Library     25%     5%      1650G
   Literary Library     Library     Ukiyoe Shop 15%     10%     900G
   Training Weapon Shop Dojo        Notice Boa. 20%     10%     1080G
    Edomae  Sushi Shop  Fireworks   Tempura Sh. 20%     12%     550G
    Steamy  Pine Tree   Hot Spring  Boulder     25%     10%     1930G
    Import  Elekiter    Camera Shop Zoo         25%     25%     2800G
    Fortune Cat Statue  Case Shop   Shrine      25%     10%     1300G
    Komon   Case Shop   Sandal Shop Straw Hat   20%     -        680G
    Kyoto   Samurai Ho. 5-Rf Tower  Kimono Shop 20%     15%     2950G
    Gambler Gambling S. Pawn Shop   Pub         5%      25%     550G
    Corrupt Magistrate  Fancy Rest. Bun Shop    10%     10%     2050G
    Ghost   Well        Willow Tree Wooden Path 15%      -       295G
    Healthy Greengrocer Merchant C. Medicine S. 15%     10%     280G
   Traveler Sandal Shop Straw Hat   Carriage S. 25%     15%     680G
    Battle  Turret      Cannon      Weapon Sh.  30%     10%     850G**
    Playboy Gambling S. Kimono Shop Kabuki The. 20%     20%     1400G
    Vehicle Stables     Handcart S. Carriage S. 20%     25%     1700G
    Clothes Kimono Shop Large Store Fancy Rest. 16%     15%     1550G
   Princess Carriage S. Kimono Sho  Fancy Rest. 21%     15%     1850G
    Samurai Magistrate  Castle      Samurai Ho. 25%     15%     5200G***
    Karosft Kairo Statu Banana Tree Scarecrow   35%     35%     4476G

*Like trees, boulders, the fire alarm, or scarecrow.
**Most cost-effective combo for high yield!
***Most expensive combo for its yield.

If you're looking for tips on combo stacking/chaining, check out http://kairospot.net/community/threads/10x-combo-on-castle.1414/ (The thread is entitled 10x Combo On Castle.)
Comment: Would you mind adding the list of combos to your answer? The link is great but if it goes dead for whatever reason, having te list here would be helpful.
Comment: @AshleyNunn - I've added the table to the answer, although I had to  do some rather ugly formatting to make it fit halfway nicely.


API: How can I remotely check if two data sets are identical, without sending all data across the API?

Question: I'm building an API to allow remote systems to synchronise millions of rows in a data table (one-way).  The systems run different databases at each end (my receiving system is SQL Server but the sending system is SAP/Hana) so they can only communicate via an API.
Using only methods on an API, how can I determine the differences in data rows between the two systems and ensure they are always in sync?
One idea I had is to provide a list of IDs (primary keys), followed by some kind of "check" value or LastUpdatedDate which the remote systems can then use to find out which records they need to add or update. However if there are 10 million rows+, is there any way to avoid sending all 10 million keys each time I want to synchronise the databases?
Are there any protocols I can copy ideas from which do a similar thing?  I know IMAP for example, uses an approach similar to that above, but is poor at handling "millions" of emails.
EDIT (additional info):

No records can be deleted on the source system - so I don't need to handle that.
There will be 20 million new rows each year, up to a max of circa 150 million.
Old records can occasionally be updated and need to trigger a re-sync.
Comment: Ouch. One idea to test would be add a computed column to the tables with the hashbytes of their concatenated values (of all columns). Then, just check the hash of the entire column against the same of the other table. You can use SHA2_512 and should avoid collisions. Just an idea... could suck for performance, I'd just test against the dataset. Not sure how sap/Hana handles this type of function so this is speaking from SQL Server.
Comment: If you use some sort of versioning, meaning where you aren't updating rows only inserting *new* rows with a "inserted time" columns, then you could check the max(ID) or max(timeColumn) against each other and only compare this one row. I'd use the ID in this case since it'd be the primary clustered key.
Comment: Alas, the old rows sometimes get updated without me being able to change the ID. That's a limitation of the source system.
Comment: Theoretically, LastModifiedDate should work just as well as a hash, as long as the source system *always* updates it.
Comment: Only thing i was thinking about that is what if they were updated at the same time, but different values were inserted/updated? Just depends on your granularity i supposes.
Comment: The sync is one way only... so that can't happen. Essentially I just need a 'backup' of the data from the remote system.
Comment: Ah, then last_updated timecolumn is where i'd probably go. I'm sure there are gaps in this though. Maybe move this to dba.stackexchange.com. They'd be better.
Comment: Have you looked at SQL Server Change Data Capture? This might help you avoid some work.
Comment: @DavidButtrick That looks like it would be useful, if the source server was SQL, but unfortunately the flow is from SAP to SQL Server.
Answer: There is a theorem that there is no perfect way to do this without sending the full data across the wire.
However you can cheat.  The rsync utility solves this problem by hashing entire ranges and comparing.  If there is a difference it breaks into chunks and repeats until it finds minimal diffs to send.  The reason why this is cheating is that hashes of different things are not guaranteed to be different - they are just likely to be different.
In your case I would suggest having hashes of each row, then hash the concatenation of those hashes over ranges based on the original ID.  If there is a block without differences, you can ignore it.  If it has differences and is large, then split into k blocks (you can experiment on k) and repeat.  If it has differences and is fewer than N rows (experiment on that as well) then send the list of hashes, and you know what rows to compare.
For efficiency I would precompute the hashes per row like @scsimon suggested, and have a combined index on (id, hashed).  That way all of the queries to pull back and hash blocks will JUST be range queries on the index data structure, and don't even visit the large table.  Trust me, this should make a very significant performance difference.


Add a column with the hourly difference of the Datetime Index

Question: I have a Dataframe with a datetimeindex and I need to create a column that contains the difference in time between the rows of the datetimeindex expressed in hours. This is what I have:
Datetime            Numbers
2020-11-27 08:30:00    1
2020-11-27 13:00:00    2
2020-11-27 15:15:00    3
2020-11-27 20:45:00    4
2020-11-28 08:45:00    5
2020-11-28 10:45:00    6
2020-12-01 04:00:00    7
2020-12-01 08:15:00    8
2020-12-01 12:45:00    9
2020-12-01 14:45:00   10
2020-12-01 17:15:00   11
         ...

This is what I need:
Datetime             Numbers   Delta
2020-11-27 08:30:00    1        Nan
2020-11-27 13:00:00    2       4.5
2020-11-27 15:15:00    3       2.25
2020-11-27 20:45:00    4       5.5
2020-11-28 08:45:00    5       12
2020-11-28 10:45:00    6       2
2020-12-01 04:00:00    7       65.25
2020-12-01 08:15:00    8       4.25
2020-12-01 12:45:00    9       4.5
2020-12-01 14:45:00   10       2
2020-12-01 17:15:00   11       2.5
                  ...

The Dataframe has thousands of rows so I can't use a "for" loop. Thanks in advance!
EDIT: I found a solution:
df = df.reset_index()
df['Time'] = df['Datetime'].astype(np.int64) // 10**9
df['Delta'] = df['Time'].diff()/3600
df.drop(columns=['Time'],inplace =True)
df.set_index('Datetime', inplace=True)

Answer: I assume that Datetime is set as index:
df.reset_index(inplace=True)
df['Delta'] = df['Datetime'].diff().dt.total_seconds()/3600
df.set_index('Datetime', inplace=True)

OUTPUT:
                     Numbers  Delta
Datetime
2020-11-27 08:30:00        1    NaN
2020-11-27 13:00:00        2   4.50
2020-11-27 15:15:00        3   2.25
2020-11-27 20:45:00        4   5.50
2020-11-28 08:45:00        5  12.00
2020-11-28 10:45:00        6   2.00
2020-12-01 04:00:00        7  65.25
2020-12-01 08:15:00        8   4.25
2020-12-01 12:45:00        9   4.50
2020-12-01 14:45:00       10   2.00
2020-12-01 17:15:00       11   2.50

Comment: Please avoid answering duplicate questions.
Comment: I was coming back to answer my own question to find out that Muhammad gave the same answer. Thanks, Muhammad you are the best.
By the way Mayank is not the same question since in my case the solution does not work since it's a Datetime index and not a datetime column.
Comment: @Gus Please check the question I linked properly. It also uses datetime index not column.
Comment: @Muhammad This gives me an error : df['Delta'] = df['Datetime'].diff().dt.total_seconds()/3600 TypeError: 'method' object is not subscriptable
Comment: Working fine for me, are you sure `df` is dataframe here?
Comment: @Muhammad You are right, it works. The problem I was having had to do with the fact that while in the example provided here I showed a Dataframe In my code it was actually a series so I convert it to a dataframe and it worked.
Comment: @Mayank Now that I converted it to a Dataframe this works:
df['delta'] = df.index.to_series().diff()
However it's not in the correct format, like I said it should be expressed in hours as a number. So again is still not the same issue.


How to replacing a ByteToMessageDeocder in a safe way?

Question: I designed the following protocol.

Header's Length
Header
Content
Delimiter(end flag)

0x00000101
HELLO
json
###end###

The Client sends a message which contains "Header's Length","Header","content"and "Delimiter". It should be noted that the client will not send a complete message at once, the "Contend"field will be sent multiple times.when the client finish sending the Content field it will attach "###end###" at the end.The Server's job is to get the "Header"field and the "Content" field.
The Business logic is to handle the "Header" and "Content". So I need to get these from the bytebuf. The first thing that comes to my mind is using a decoder extends LengthFieldBasedFrameDecoder to get "Header".When I get the first decoded frame ,namely the "Header", i will change the pineline by replacing the decoder to another.In the end,I'll use the new handler to deal with leftover message.
I tried to overwrite LengthFieldBasedFrameDecoder's decode() method according to this answer. But it seems to be an infeasible method. When the decoder is removed from the pipeline,client is still sending messages.so what happen to these message? Will these messages be dropped?
Answer:
Your protocol format is a bit more complicated than just a simple build in decoder. This means you have to write your own decoder.
Looking a your format, we can identity the following states:

Read header length: read exactly 4 bytes
Read header: Read for the X amount of from last value
Read message until you see delimiter

Implementing a state switch like this is not too difficulty when using a ReplayingDecoder.
For example:
enum FrameDecoderState {
    FRAME_HEADER_LENGTH,
    FRAME_HEADER,
    FRAME_BODY
}

public class FrameDecoder extends ReplayingDecoder<FrameDecoderState> {
    private int headerLength;
    private ByteBuf header;
    private int detectedMessageLength;
    private final ByteBuf delimiter;

    public FrameDecoder(ByteBuf delimiter) {
        super(FRAME_HEADER_LENGTH);
        this.delimiter = Objects.requireNonNull(delimiter, "delimiter");
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        super.channelUnregistered(ctx);
        if (header != null) {
            header.release();
        }
        delimiter.release();
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> out) throws Exception {
        switch(this.state()) {
            default:
                throw new AssertionError("Shouldn't reach here.");
            case FRAME_HEADER_LENGTH:
                headerLength = buf.readInt();
                checkpoint(FRAME_HEADER);
            case FRAME_HEADER:
                header = buf.readBytes(headerLength);
                detectedMessageLength = 0;
                checkpoint(FRAME_BODY);
            case FRAME_BODY:
                int bodyStart = buf.readerIndex();
                while(true) {
                    if (findDelimiter(bodyStart + detectedMessageLength, buf)) {
                        out.add(new FrameDecoderFrame(header, buf.readBytes(detectedMessageLength)));
                        buf.readerIndex(bodyStart + detectedMessageLength + delimiter.capacity());
                        checkpoint(FRAME_HEADER_LENGTH);
                        break;
                    }
                    detectedMessageLength++;
                }
        }
    }

    private boolean findDelimiter(int bufIndex, ByteBuf buf) {
        for (int delimiterIndex = 0; delimiterIndex < delimiter.capacity(); delimiterIndex++) {
            if (buf.getByte(bufIndex) != delimiter.getByte(delimiterIndex)) {
                return false;
            } else {
                bufIndex++;
            }
        }
        return true;
    }
}

class FrameDecoderFrame extends AbstractReferenceCounted {
    private final ByteBuf header;
    private final ByteBuf body;

    public FrameDecoderFrame(ByteBuf header, ByteBuf body) {
        this.header = header;
        this.body = body;
    }

    public ByteBuf getHeader() {
        return header;
    }

    public ByteBuf getBody() {
        return body;
    }

    @Override
    public int hashCode() {
        int hash = 3;
        hash = 41 * hash + Objects.hashCode(this.header);
        hash = 41 * hash + Objects.hashCode(this.body);
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final FrameDecoderFrame other = (FrameDecoderFrame) obj;
        if (!Objects.equals(this.header, other.header)) {
            return false;
        }
        if (!Objects.equals(this.body, other.body)) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "FrameDecoderFrame{" + "header=" + header + ", body=" + body + '}';
    }

    @Override
    protected void deallocate() {
        header.release();
        body.release();
    }

    @Override
    public FrameDecoderFrame touch(Object o) {
        header.touch(o);
        body.touch(o);
        return this;
    }
}

After writing such an encoding make sure to test it, including with the cases there is partial data, or when there are multiple frames in the same message, for example:
@org.junit.jupiter.api.Test
public void testBasic() {
    var channel = new EmbeddedChannel(new FrameDecoder(Unpooled.wrappedBuffer("###end###".getBytes(US_ASCII))));

    channel.writeInbound(Unpooled.buffer().writeInt(4));
    assertNull(channel.readInbound());
    channel.writeInbound(Unpooled.wrappedBuffer("te".getBytes(US_ASCII)));
    assertNull(channel.readInbound());
    channel.writeInbound(Unpooled.wrappedBuffer("st{\"test\":".getBytes(US_ASCII)));
    assertNull(channel.readInbound());
    channel.writeInbound(Unpooled.wrappedBuffer("true}".getBytes(US_ASCII)));
    assertNull(channel.readInbound());
    channel.writeInbound(Unpooled.wrappedBuffer("###".getBytes(US_ASCII)));
    assertNull(channel.readInbound());
    channel.writeInbound(Unpooled.wrappedBuffer("end".getBytes(US_ASCII)));
    assertNull(channel.readInbound());
    channel.writeInbound(Unpooled.buffer().writeBytes("###".getBytes(US_ASCII)).writeInt(0).writeBytes("[]###end###".getBytes(US_ASCII)));
    assertEquals(
        new FrameDecoderFrame(
            Unpooled.wrappedBuffer("test".getBytes(US_ASCII)),
            Unpooled.wrappedBuffer("{\"test\":true}".getBytes(US_ASCII))
        ),
        channel.readInbound()
    );
    assertEquals(
        new FrameDecoderFrame(
            Unpooled.EMPTY_BUFFER,
            Unpooled.wrappedBuffer("[]".getBytes(US_ASCII))
        ),
        channel.readInbound()
    );
    assertNull(channel.readInbound());
}


Using unsigned data types in C

Question: How to use unsigned int properly? My function unsigned int sub(int num1, int num2);doesn't work when user input a is less than b. If I simply use int, we can expect a negative answer and I need to determine which is larger before subtracting. I know that's easy but maybe there is a way to use unsigned int to avoid that?
For instance when a = 7 and b = 4, the answer is 3.000000. But when I flip them, the code gives me 4294967296.000000 which I think is a memory address.
#include <stdio.h>

unsigned int sub(int num1,int num2){
    unsigned int diff = 0;
    diff = num1 - num2;
    return diff;
}

int main(){
    printf("sub(7,4) = %u\n", sub(7,4));
    printf("sub(4,7) = %u\n", sub(4,7));
}

output:
sub(7,4) = 3
sub(4,7) = 4294967293

Comment: Yeah, `unsigned` means _without a sign_, which means it can't be negative. If you need to allow negative values, you can't use `unsigned`. Out of interest, what did you think it meant?
Comment: Converting from signed to unsigned doesn't result in taking the absolute value. It results in a [modular arithmetic](https://en.wikipedia.org/wiki/Modular_arithmetic) conversion.
Comment: What did you expect to get from the a=4, b=7 case?
Comment: Almost none of the posted code is at all relevant, and the bit that _is_ relevant depends on user input you didn't show. At least say what output you want.
Comment: @Cornstalks ahh you're right, absolute value must be the best way to do it
Comment: @M.M I expect -3 but since it is unsigned, maybe it will drop the negative sign? Now that I think about it, maybe I misunderstood unsigned data types
Comment: Good read: http://stackoverflow.com/questions/16056758/c-c-unsigned-integer-overflow
Comment: @Cornstalks: Only for 2's complement representation.
Comment: @useless im sorry, still figuring out the MCVE practice. I thought it would simply drop the negative sign, but after my quick research, it basically translates the whole int range into the right of 0.
Comment: You want [`abs()`](http://en.cppreference.com/w/c/numeric/math/abs) for that. Using unsigned gives you the underflow behaviour described in the linked question and some of the answers. And, no problem - have a worked example of writing an MCVE.
Comment: @Useless wow thanks for editing. From how you edited my code, I take it that I don't need to present my hard code but only the essence.
Comment: @Olaf: No, not just for 2's complement representation. The conversion from signed to unsigned is well defined, and is effectively a modular arithmetic conversion. For example, a signed `int` variable `n` converted to `unsigned int` results in a positive value that is equivalent to `n` modulo `UINT_MAX+1`. [Example](https://www.wolframalpha.com/input/?i=-12+mod+2%5E32)
Comment: @Cornstalks: Ok, my fault, it is just "for free" (i.e. without extra operations) on 2's complement architectures, but has the same semantics on all three encodings.
Comment: It's possible for `num1 - num2` to overflow (if `num1` and `num2` are of type `int`). For safety, you can use `if (num2 > num1) diff = (unsigned)num2 - (unsigned)num1; else diff = (unsigned)num1 - (unsigned)num2;` to get the absolute difference with no integer overflow.
Answer: Unsigned numbers are unsigned... This means that they cannot be negative.
Instead they wrap (underflow or overflow).
If you do an experiment with an 8-bit unsigned, then you can see the effect of subtracting 1 from 0:
#include <stdio.h>
#include <stdint.h>

int main(void) {
    uint8_t i;

    i = 1;

    printf("i: %hhu\n", i);

    i -= 1;

    printf("i: %hhu\n", i);

    i -= 1;

    printf("i: %hhu\n", i);

    return 0;
}

i: 1
i: 0
i: 255

255 is the largest value that an 8-bit unsigned can hold (2^8 - 1).

We can then do the same experiment with a 32-bit unsigned, using your 4 - 7:
#include <stdio.h>
#include <stdint.h>

int main(void) {
    uint32_t i;

    i = 4;

    printf("i: %u\n", i);

    i -= 7;

    printf("i: %u\n", i);

    return 0;
}

i: 4
i: 4294967293

4294967293 is effectively 0 - 3, which wraps to 2^32 - 3.

You also need to be careful of assigning an integer value (the return type of your sub() function) to a float... Generally this is something to avoid.
See below. x() returns 4294967293 as an unsigned int, but it is stored in a float... This float is then printed as 4294967296???
#include <stdio.h>
#include <stdint.h>

unsigned int x(void) {
    return 4294967293U;
}

int main(void) {
    float y;

    y = x();

    printf("y: %f\n", y);

    return 0;
}

y: 4294967296.000000

This is actually to do with the precision of float... it is impossible to store the absolute value 4294967293 in a float.
Comment: @reiallenramos `uint8_t` is an unsigned integer type exactly 8 bits wide defined by `#include `. It is optional if the implementation has no such type available.
Comment: thank you for that very detailed explanation. Can I ask what type of identifier `uint8_t` is?
Answer: unsigned int cannot be used to represent a negative variable.  I believe what you wanted is to find the absolute value of the difference between a and b.  If so, you can use the abs() function from stdlib.h.  The abs() function takes in an int variable i and returns the absolute value of i.
The reason why unsigned int returns a huge number in your case is due to the way integers are represented in the system.  You declared diff as an int type, which is capable of storing a negative value, but the same sequence of bits that represents -3 when interpreted as unsigned int represents 4294967296 instead.
Answer: What you see is called unsigned integer overflow. As you noted, unsigned integers can't hold negative numbers. So when you try to do something that would result in a negative number, seemingly weird things can occour.
If you work with 32-bit integers,

int (int32_t) can hold numbers between (-2^31) and (+2^31-1), INT_MIN and INT_MAX
unsigned int (uint32_t) can hold numbers between (0) and (2^32-1), UINT_MIN and UINT_MAX

When you try to add something to an int that would lead to a number greater than the type can hold, it will overflow.
Comment: this is good info but it didn't answer my question, so I can't choose this as _the_ answer
Comment: @reiallenramos What do you want? To print a `unsigned` value as -3?
Comment: @chux no, I wanted to drop the - sign, which has been solved already by using abs() from the other comments
Comment: @reiallenramos `abs()` has its [problems](http://stackoverflow.com/a/43476048/2410359) too.
Comment: @chux like what? For my purposes, I just sticked to the int declaration and then used abs() down in the function definition.
Comment: @reiallenramos Taking the `abs()` issues to this [answer](http://stackoverflow.com/a/43476048/2410359)
Answer: It becomes a negative number, unsigned data types dont hold negative number, so instead it becomes a large number
Answer: "absolute value of the difference between a and b" does not work for many combinations of a,b.  Any a-b that overflows is undefined behavior.  Obviously abs(INT_MAX - INT_MIN) will not generate the correct answer.
Also, using abs() invokes undefined behavior with a select value of int.  abs(INT_MIN) is undefined behavior when -INT_MIN is not representable as an int.
To calculate the absolute value difference of 2 int, subtract them as unsigned.
unsigned int abssub(int num1,int num2){
  return (num1 > num2) ? (unsigned) num1 - num2 : (unsigned) num2 - num1;
}

Using unsigned data types in C


Naming custom fields of built-in objects without collisions

Question: I want to know, is there some standard way to name custom fields of built-in objects in JavaScript to avoid any collisions with standard fields?
For example:
var xhr = new XMLHttpRequest();
xhr.thisFieldIsNotGoingToBeUsed = 'by XHR internals but is used by the app';

It can be useful, for instance, to reverse lookup object parent in events without using loops with comparison of this object to each member.
There are data- attributes in HTML, but I can't find any JavaScript equivalent.
Answer: The rule of thumb is to not modify what you don't own. Consider this approach for your example instead;
var myObj = {};
var xhr = new XMLHttpRequest();

myObj.xhr = xhr;
myObj.customProperty = 4;
myObj.customFunc = function () {
    // use this.xhr
}

// Now pass myObj around instead, you have a reference to xhr (myObj.xhr)
// and your customProperty (myObj.customProperty).

Because of how closures work in JavaScript, you should also have access to the variables which were in scope when you defined your onreadystatechange function, which again removes the need for a this context completely;
var xhr = new XMLHttpRequest();
var something = function () {
    // I have access to "xhr" because of closures.
};

xhr.onreadystatechange = function () {
    if (this.readyState === 4 && this.status === 200) {
        // I still have access to "something" here because of closures;
    }
}

// xhr.open && send.

... even if you don't have closures on your side (e.g. the onreadystatechange is defined in a different scope), you should be looking at modifying your code to allow you to pass the necessary variables you need in order to do your work.
Comment: But I'm making a callback, so `this` would be the `xhr` (or, in my case, `WebSocketConnection`), not `myObj`.
Comment: @SiPlus: In your callback, you should have access to the variables surrounding the request because of closures; let me update my post with an example.
Comment: Actually I meant event listeners, not callbacks. I confuse them often.


Terraria Engineer NPC won't respawn

Question: Multiplayer with 2-3 players.  There were 2 Engineer NPCs in the dungeon when we "saved" them, in adjacent rooms from each other.  They of course died rather quickly in the dungeon.  I didn't think much of it as I knew she should respawn eventually.
But hasn't, and I bet we've put in a good 10+ hours of gameplay since then.  Maybe even more.
We keep making houses, and duplicate NPC's keep moving in instead of the Engineer.  We have 2 goblin tinkerers, and 2 nurses.  I killed one of the nurses with lava to see if that would help the engineer spawn, but it has not.
Plus, there is 1 other "house" on the far side of the map by the dungeon we occasionally use as a spawn point w/ a bed.  As far as I can tell, that house has never been occupied.
If I bring up the NPC/social menu, I can see that the Engineer is not listed (and so not "living" somewhere on the map other than our home base).
Any idea how to get the Engineer back?  The server is running TDSM 1.1.2 on a Linux box using Mono.  This is the first multiplayer server I've run, and there is not much on TDSM on the web anymore (their site, tdsm.org, is no longer up).  I've restarted the server to no avail.
UPDATE: We are currently at 1 NPC per NPC type, except no Engineer, and we have 6 (yes, six) Goblin Tinkerers.
Answer: It appeared to be a bug in the server I was using (TDSM).  I switched to TShock and all of a sudden things started working.  The Engineer showed up in like the first 2 minutes of playing.  Some other things that were buggy for me in TDSM but worked in TShock:

The flying skulls in the dungeon started spawing.  I had completely forgotten these even existed, as we had cleared the entire dungeon without seeing one, and just happened to see them now that we started mining some of the dungeon bricks.
Mannequins started working.  Before, I placed armor on one, left, came back and it was gone.  Another occasion I watched as one of the other players attempted to place the armor on the mannequin - it simply dissapeared.  Wasn't in his inventory, wasn't on the mannequin.

Terraria Engineer NPC won't respawn


Show that H is normal subgroup of G.

Question: Let H be a proper subgroup of G and  a $\in$ G, a $\notin$ H. Suppose that for all b $\in$ G, either b $\in$ H, or Ha = Hb. Show that H is normal subgroup of G. How do I proceed on this?
Comment: I guess he meant "either $\;b\in H\;$ or $\;Ha=Hb\;$ , making $\;H\;$ a subgroup of index two and thus normal...?
Comment: What do you mean by b $\in$, or Ha = Hb ?
Comment: Yes, thats I what I meant.. Why will a subgroup of index 2 always be normal?
Comment: Question has been asked, and answered, several times on this site.
Answer: The index of $H$ in $G$ is two that is it has exactly two right/left cosets, specifically $$ \{H, Ha\}$$ $$ \{H , a'H\} $$
Since the right/left cosets define equivalence classes $$ Ha = G \setminus H = a'H$$
Hence every left coset of $H$ is a right coset of $H$ in $G$ whence $H \triangleleft G $.

Show that H is normal subgroup of G.


MASM link error: unresolved external symbol _DumpRegs@0

Question: Comrades, I'm quite a newbie to assembly programming, and I'm starting with masm32 assembler and later nasm assembler. So I've created a first assembly source file and I've tried assembling and linking it with the masm32 editor. And I keep getting a link error:
warning LNK4003 : invalid library format; library ignored
hello.obj : error LNK2001 : unresolved external symbol _DumpRegs @0
hello.exe : fatal error LNK1120 : 1 unresolved externals
_
Link error

The source file is hello.asm and its contents are:
.386
.model flat,stdcall
.stack 4096

includelib C:\masm32\include\Irvine32.inc

DumpRegs PROTO

.data

var1 WORD 120
var2 WORD 99

.code
start:

call DumpRegs

end start

PUBLIC start

end

I was attempting to output the contents of the registers for a start and I got stuck. I'm running on win7 Ultimate x64 operating system.
How I'm supposed to compile it or if, in any case there's a problem with the source code, what i'm I supposed to change? Any help is gratefully appreciated
Comment: What commands did you type in to assemble and link?
Comment: I used the masm32 editor-the IDE. I cliked on "assemble and link" button
Comment: I think your `.inc` file should be just `include`. The `includelib` should point to `Irvine32.lib`.
Comment: if I use include Irvine.inc, I get error: Could not open Irvine.inc, but includelib Irvine.inc doesn't give the error
Comment: but even if i includelib Irvine32.lib, i still get the same link error
Answer: I figured that different assemblers come with different linkers, even they all support the very same masm syntax. I'm not sure if the Irvine libraries require a little tweaking for each  of these because none of them came with the Irvine libraries. But since most if not all masm assemblers work only on windows platforms, I used the Visual C++ to assemble my masm programs. I got the Irvine libraries plus a visual studio project file to ease my setting up procedures from this web page. The website contains all info that you need about setting up your project just before you start the programming itself. The beauty of visual studio is that, all you need to do is just
include Irvine32.inc

or
include Irvine16.inc

etc, then write your source code. You don't need to think about the Irvine32.lib or Irvine16.lib.  Then you just click on run or start without debugging button and you're good to go. This saves you a lot of work and it doesn't take long to set up.
Cheers!


Undefined symbol using enum class

Question: This is probably a trivial question, but I am not able to overcome a problem with enum class data:
enum class enumTest
{
   VALUE0 = 0, VALUE1 = 1, VALUE2 = 2
};

void __fastcall TForm1::Button1Click (TObject* Sender)
{
int a = VALUE1;
}

I get: Error: Undefined symbol: 'VALUE1'
Changing enum class enum into:
enum //class enumTest

the compiler works normally.
Unfortunately I cannot do it because it is defined into the TLB/OCX include file, as many other declarations.
This happens with different types of OCX of different vendors.
Answer: An enum class is called a scoped enumeration.  You need to use its enumerators in the scope of the enumeration.  For example,
int a = enumTest::VALUE1;

Comment: I thought `enum class` means you can't cast to int and vice versa, either. So `a` must be of type `enumTest` for this to compile.

Undefined symbol using enum class


How to get Path for local mp3 file from www in Phonegap IOS?

Question: i am using phonegap audio plugin in my phonegap app.
I have some audio files stored in www/audio folder.
For android i used "file:///android_asset/www/audio" to read local file.
For IOS i need help.
Thanks
Comment: may be the [link1](http://stackoverflow.com/questions/10945375/phonegap-ios-how-to-get-app-documents-folder-full-path) support you
Comment: Does this answer your question? [Playing local sound in phonegap](https://stackoverflow.com/questions/4438822/playing-local-sound-in-phonegap)
Answer: Finally got it,
reference:link
To get path i used this function
<code>function getPhoneGapPath() {
   var path = window.location.pathname;
   path = path.substr( path, path.length - 10 );
   return path;
};
</code>
USAGE:
For IOS:
var snd = new Media( getPhoneGapPath() + 'test.mp3' );
For Android:prepend 'file://'
var snd = new Media( 'file://' + getPhoneGapPath() + 'test.mp3' );
Answer: You will have trouble if called from a file other than 'index.html' because the part to trim off might not be 10 chars.
Try this:
<code>// Get absolute file path on the device.
function getPhoneGapPath() {
    var path = window.location.pathname;
    var sizefilename = path.length - (path.lastIndexOf("/")+1);
    path = path.substr( path, path.length - sizefilename );
    return path;
};
</code>
Comment: This is great for dealing with unexpected path sizes. This is a better method to get the path than subtracting a fixed length of 10.
Comment: In case the app name contains unicode characters which are encoded into %NN in the window-location-pathname, you will have to turn it back into unicode using `path = decodeURIComponent(path)`


NullPointer exception while selection in android sqlite database

Question: I have written this code to select count,last id , data of a table which I am sending as a parameter in method.
I am getting NullPointer exception when i want to select lastcount, totalcount and getdata while passing table name as parameter.
What should I do?
This is my database helper code:
public String getaccounttable(int j) {
    // TODO Auto-generated method stub
    String col[]=new String[]{col_id,col_name,col_bankname,col_bal,col_accno,col_date};
    Cursor c=ourDB.query(dbtabelmain, col, col_id+"="+j, null, null, null, null);
    String result="";
    if(c!=null)
    {
    int iname=c.getColumnIndex(col_name);
    int i=c.getColumnIndex(col_accno);
    for(c.moveToFirst();!c.isAfterLast();c.moveToNext())
    {
        result=result+c.getString(iname)+c.getString(i);
    }

    }
    return result;
}

public void addtr(Long bal, String date, String account) {
    // TODO Auto-generated method stub
    ContentValues cvs=new ContentValues();
    cvs.put(col_bal_tb, bal);
    cvs.put(col_date_tb, date);
    ourDB.insert(account, null, cvs);

}

public int getidacccount(String account) {
    // TODO Auto-generated method stub
    String cl[]=new String[]{col_id_tb,col_bal_tb,col_date_tb};
    String acc=account;
    Cursor c=ourDB.query(acc, cl, null, null, null, null, null);
    if(c!=null)
    {
    int i=c.getCount();
    return i;
    }
    else
    {
        return 0;
    }

}

public int getacclastidcount(String account) {
    // TODO Auto-generated method stub
    String cl[]=new String[]{col_id_tb,col_bal_tb,col_date_tb};
    String acc=account;
    Cursor c=ourDB.query(acc, cl, null, null, null, null, null);
    String rs="";
    int i=c.getColumnIndex(col_id_tb);
    c.moveToLast();
    rs=c.getString(i);
    int j=Integer.parseInt(rs);
    return j;

}

public String getaccdata(int i, String account) {
    // TODO Auto-generated method stub
    String cl[]=new String[]{col_id_tb,col_bal_tb,col_date_tb};
    String acc=account;
    Cursor c=ourDB.query(acc, cl, col_id_tb+"="+i, null, null, null, null);
    String result="";
    if(c!=null)
    {
    int iname=c.getColumnIndex(col_bal_tb);
    int idate=c.getColumnIndex(col_date_tb);
    for(c.moveToFirst();!c.isAfterLast();c.moveToNext())
    {
        result=result+c.getString(iname)+"\n "+c.getString(idate);
    }

    }
    return result;

}

And this my class code which is passing account(tablename) as parameter into method
Intent it=getIntent();

    final String pos=it.getStringExtra("ids");
    int x=Integer.parseInt(pos);
    PassBookAcc m =new PassBookAcc(ViewTransaction.this);
    m.open();
    final String account=m.getaccounttable(x);
    m.close();

    PassBookAcc info=new PassBookAcc(ViewTransaction.this);
    k=0;
    int size=info.getidacccount(account);
    String[] ex=new String[size];
    if(size==0)
    {
        setTitle("No Passbooks");
        info.close();
        ex[0]="NO PASSBOOKS";
    }
    else
    {
    i=info.getacclastidcount(account);

    String[] id=new String[i];

    for(j=0;j<i;j++)
    {
    id[j]=info.getaccdata(j+1,account);

    if(id[j]!="")
    {

        ex[k]=id[j];
        k++;
    }
    }
    info.close();
    }
    setListAdapter(new ArrayAdapter<String>(ViewTransaction.this,android.R.layout.simple_list_item_1,ex));

Comment: post stack trace, and narrow the code to to where the npe is being generated from (double click on the error).
Answer: your code is proper, i think you should be use
Cursor c=ourDB.query(dbtabelmain, col, col_id+"='"+j+"'", null, null, null, null);

instead  of
Cursor c=ourDB.query(dbtabelmain, col, col_id+"="+j, null, null, null, null);

Comment: i am not having trouble at this method but in the last three methods


How can I redeem my free GTA San Andreas?

Question: According to this announcement, I downloaded the launcher and when I opened it, I found out that GTA San Andreas is not for free. What am I missing? and How can I redeem it? Thank you,
Update : I'm already over 18 years old. I don't have issues like a bug or an error. It's available but not for FREE as they claimed on their website.
Answer: The announcement (see image below) states:

Download Now and get a bonus FREE copy of Grand Theft Auto: San Andreas on PC for a limited time

This was posted September 17, 2019. In all probability the giveaway has expired.
Comment: @user2824371: It's under "Newswire" on their website. You don't take old news off your website just because it's out of date. Update it, maybe, but not remove the article.
Comment: Since the offer has expired, I think they should remove it from the website. Thanks for the answer. That was useful.
Comment: Yup.  They have offered a lot of freebie games--most of them you have to claim in the week they are offered, they did a 12 days of Christmas thing where they had to be claimed in a 24 hour window.
Answer: Another announcement states the offer ended on October 8th 2019.

For those yet to download the Rockstar Games Launcher, be sure to download by Tuesday October 8th to get Grand Theft Auto: San Andreas for free.


How to shift values of given array by moving first value to the last C++

Question: I was struggling on how to move the first value to the las in order like shown in the picture
enter image description here
What should I do?
<code>#include <iostream>
using namespace std;

void rotate(int A[], int n = 5)
{
    int x = A[n - 1], i;
    for (i = n - 1; i > 0; i--)
    {
        A[i] = A[i -1];
    }
    A[0] = x;
}

int main()
{
    int A[] = { 1, 2, 3, 4, 5 }, i;
    int n = sizeof(A) / sizeof(A[5]);

    cout << "Given array is \n";
    for (i = 0; i < n; i++)
        cout << A[i] << ' ';

    for (int j = 0; j < n; j++)
    {
        rotate(A, n);

        cout << "\nStep " << j << " --> ";
        for (i = 0; i < n; i++)
        {
            cout << A[i] << ' ';
        }
    }
    return 0;
}
</code>
Comment: Do you _have_ to do this shift in 5 separate steps, given that your `rotate` function already achieves the same purpose in just 1 step?
Answer: Your code is still quite "C" like. Here is an example that hopefully will teach you some C++ coding :
<code>#include <algorithm>
#include <iostream>
#include <vector>

// passing arrays is easier using std::vector/std::array (no need to pass size seperately)
void rotate(std::vector<int>& values)
{
    // using algorithm's std::swap you can better show WHAT you are doing
    // vector and array also have a size() method so you don't
    // have to use "C" style sizeof tricks.
    for (std::size_t n = 0; n < values.size() - 1; ++n)
    {
        std::swap(values[n], values[n + 1]);
    }
}

int main()
{
    // prefer std::vector (or std::array) in C++. Not "C" style arrays
    std::vector<int> values{ 1,2,3,4,5 };

    rotate(values);

    // use range based for loop if you can.
    for (const auto value : values)
    {
        std::cout << value << " ";
    }

    return 0;
}
</code>


What does AM in "AM Container" mean in Hadoop

Question: In Hadoop, what does AM in "AM Container" mean?
There are many posts about the MapReduce error, "failed 2 times due to AM Container" ... "Exception from container-launch: org.apache.hadoop.util.Shell$ExitCodeException" ... but none solve my problem (with my HBase job).
I'm a beginner and I'd like to start by knowing what AM stands for. I can't find anything on the web.
Comment: AM means Application Master, check http://stackoverflow.com/a/23396829/2759636
Answer: Here's another link from Hadoop which may help understanding the Application Master (as @nigge noted above).
http://hadoop.apache.org/docs/stable/hadoop-yarn/hadoop-yarn-site/WritingYarnApplications.html
Comment: Thanks so much. And for other newbies, here's an actual page tying the two together: ApplicationMaster (AM): http://hadoop.apache.org/docs/current/hadoop-yarn/hadoop-yarn-site/YARN.html


Calling functions once fom dynamic linked library and once from executable

Question: I wanted to test what happens if executable and library share different versions of a library,
i.e. different classes with the same name. Idea: make a test function which
is called once from the executable directly, and once with the code from the library:
MWE:
base.h
defines an abstract plugin class, which can generate a port object (of type base)
struct base
{
    virtual void accept(struct visitor& ) {}
    virtual void test() = 0;
    virtual ~base() {}
};

struct visitor
{
    virtual void visit(struct base& ) {}
};

struct plugin
{
    virtual ~plugin() {}
    virtual base& port() = 0;
    virtual void test() = 0;
};

typedef plugin* (*loader_t) (void);

plugin.cpp
defines a derived plugin class, which can return a derived port (mport)
#include <iostream>
#include "base.h"

struct mport : public base
{
    void accept(struct visitor& ) override {}
    void test() override { std::cout << "plugin:test" << std::endl; }
    virtual ~mport() = default;
};

struct port_failure_plugin : public plugin
{
    void test() override final { inp.test(); }
    virtual ~port_failure_plugin() {}
private:
    mport inp;
    base& port() override { return inp; }
};

extern "C" {
const plugin* get_plugin() { return new port_failure_plugin; }
}

host.cpp
defines a derived port class with the same name (mport)
#include <cassert>
#include <cstdlib>
#include <iostream>
#include <dlfcn.h>
#include "base.h"

struct mport : public base
{
#ifdef ACCEPT_EXTERN
    void accept(struct visitor& ) override;
#else
    void accept(struct visitor& ) override {}
#endif
    void test() override { std::cout << "host:test" << std::endl; }
};

#ifdef ACCEPT_EXTERN
void mport::accept(struct visitor& ) {}
#endif

int main(int argc, char** argv)
{
    assert(argc > 1);
    const char* library_name = argv[1];

    loader_t loader;
    void* lib = dlopen(library_name, RTLD_LAZY | RTLD_LOCAL);
    assert(lib);
    *(void **) (&loader) = dlsym(lib, "get_plugin");
    assert(loader);

    plugin* plugin = (*loader)();
    base& host_ref = plugin->port();
    host_ref.test(); // expected output: "host:test"
    plugin->test(); // expected output: "plugin:test"

    return EXIT_SUCCESS;
}

Compile e.g.:
g++ -std=c++11 -DACCEPT_EXTERN -shared -fPIC plugin.cpp -o libplugin.so
g++ -std=c++11 -DACCEPT_EXTERN -ldl -rdynamic host.cpp -o host

The complete code is on github (try make help)
In order to let the host run test "like the plugin does",
it calls a virtual function, which is implemented in the plugin. So I expect that test is called

once from the object code of the host executable (expectation: "host:test")
once from the object code of the plugin library (expectation: "plugin:test")

The reality looks different:

In all (of the following) cases, both outputs are equal (2x"host:test" or 2x"plugin:test")
Compile host.cpp with -rdynamic, and without -DACCEPT_EXTERN the test calls output "plugin:test"
Compile host.cpp with -rdynamic, and with -DACCEPT_EXTERN (see Makefile), and the test calls call "host:test"
Compile host.cpp without -rdynamic, and the test calls output plugin:test (both intern and extern)

Questions:

Is it even possible to call both versions of mport::test (e.g. executable and library)?
Why does  -rdynamic change the behavior?
Why does -DACCEPT_EXTERN affect the behavior?
Answer: The thing here is you are violating the one definition rule.
Your two versions of mport::test have the same declaration, yet they do not have the same definition.
But you are doing it a dynamic linking time. Now, the C++ standard does not concern itself with dynamic loading. We have to turn to the x86 ELF ABI for further detail.
Long story short, the ABI supports a technique known as symbol interposition, which allows substituting symbols dynamically and still see consistent behavior. This is what you are doing here, though inadvertently.
You can check it manually:
spectras@etherhop$ objdump -R libplugin.so |grep test
0000000000202cf0 R_X86_64_64       _ZN19port_failure_plugin4testEv@@Base
0000000000202d10 R_X86_64_64       _ZN5mport4testEv@@Base
0000000000203028 R_X86_64_JUMP_SLOT  _ZN5mport4testEv@@Base

Here you see that, in the shared object, all uses of mport::test have a relocation entry. All calls go through the PLT.
spectras@etherhop$ objdump -t host |grep test
0000000000001328  w    F .text  0000000000000037              _ZN5mport4testEv

Here you see that host does export the symbol (because of -rdynamic). So when dynamic linking libplugin.so, the dynamic linker will use the mport::test of your main program.
That's the basic mechanism. That's also why you don't see this without -rdynamic: the host no longer exports its own version, so the plugin uses its own.
How to fix?
You can avoid all this leakage by hiding symbols (a good practice in general, it makes for faster loading and avoids name clashes).

add -fvisibility=hidden when compiling.
manually export your get_plugin function by prepending __attribute__ ((visibility("default"))) to the line. Tip: that's compiler-specific stuff, it's a good idea to make it a macro somewhere.
#define EXPORT __attribute__((visibility("default")))
// Later:
EXPORT const plugin* get_plugin() { /* stuff here */ }

Thus:
spectras@etherhop$ g++ -std=c++11 -fvisibility=hidden -shared -fPIC plugin.cpp -o libplugin.so
spectras@etherhop$ g++ -std=c++11 -fvisibility=hidden -rdynamic host.cpp -ldl -o host
spectras@etherhop$ ./host ./libplugin.so
plugin:test
plugin:test

Another option would be to simply make the class static by enclosing it within an anonymous namespace. This will work in your simple case, but it is not good if your plugin is made of multiple translation units.
As for your expectations of having a different result on your two lines, you're getting a base-reference to a derived class, why would you expect anything other than the appropriate virtual override to be called?
Comment: It just doesn't know. Your program could do crazy things such as, say, loading other derived classes from dynamic libraries ;). So it cannot optimize away the virtual call resolution, and properly goes through the vtable.
Comment: To expand a bit on that comment: dynamic_cast and exceptions require a typeinfo lookup, which requires RTTI information to be exported and visible. So to make your example work, you *must* export your `mport` class. And as soon as it's globally visible, then by definition it is one class, and the linker will pick one of the implementations and declare it to be *the one and only*. Now as to why it has this odd behavior… check [this question](https://stackoverflow.com/questions/19496643/using-clang-fvisibility-hidden-and-typeinfo-and-type-erasure).
Comment: Actually it does: defining a method within the class declaration implicitly makes it `inline`. The class now having only inline methods, none of which are used from that translation unit, your compiler chooses not to emit the class at all. On the rationale that if any other translation unit uses it, it will come with its own copy of the definition.
Comment: Thanks, must read your answer more carefully tomorrow. For your last question, I indeed expect `plugin->test()` to call the plugin `test` function. However, I expected `host_ref.test()` to call the host.cpp function: When compiling `host`, the compiler only knows one virtual override: the one in host.cpp, so that's the only one it could call?
Comment: Oh, I see, using `host_ref.test()` need not leed to the output "host:test", as this depends on runtime decisions. Do you have any idea how I can still call that function that outputs "host:test"?
Comment: On the object returned by the plugin? No way without undefined behavior, as with the fix I suggest, the two `mport` classes are independent, incompatible types. But `host.cpp` is free to instantiate its own `mport` class. That one will now print `host:test` as expected.
Comment: Let's see if I got it. Being not conform to ODR is undefined in the C++ standard, but is defined in the ABI as an "LD_PRELOAD"-like overwrite.
`-fvisibility=hidden` prevents the "LD_PRELOAD"-like preloading (or the unwanted behavior from -rdynamic).
Comment: Yes. Hidden visibility does exactly what it says: symbols are invisible to other shared objects. It's exactly like they had a different name.
Comment: `-fvisibility=hidden` seems to have side-effects. I just added a `dynamic_cast(&plugin->port())` at the end of host.cpp. The cast worked, and the compiler/executable now thinks it has an `mport` like in host.cpp. This caused invalid writes when I added different variables to the two `mport` classes :-( There's probably no way to find out when the `dynamic_cast` goes wrong?
Comment: No dynamic cast across plugin boundaries. That usually extends to no exceptions as well.
Comment: Sorry, one last question. There is a difference in compiling with `ACCEPT_EXTERN` or without (`make extern` or `make intern`), see the 2nd and 3rd point of the 4 points above (it happens if visibility is not used, or if it's used and both versions of `mport::test` are exported). Is the difference just happening for "random" reasons, or is this defined behaviour? It's hard to believe that moving a function out of the class body would make any difference.


Easiest way to draw a full neo4j graph in networkx

Question: I have a neo4j graph and I want to draw the entire graph in an ipython notebook with network x. How do I go about doing that?
Something like this?
g1 = nx.neo4j_graph
nx.draw(g1)
plt.show()

Answer: Use ipython-cypher to write a Cypher query and then convert the results to a NetworkX graph. Install it with pip install ipython-cypher.
import networkx as nx
%load_ext cypher
%matplotlib inline

results = %cypher MATCH p = ()-[]-() RETURN p

g = results.get_graph()

nx.draw(g)

Drawing your entire graph is expensive if it is large. Consider only drawing the subgraphs you're interested in. You'll also have to tweak the query slightly if you want nodes with degree 0.


Extract Sentences from A String

Question: I am working on a machine learning chatbot project which uses google's speech recognition api.
Now my problem is, when I say 2 or more sentences in one command, speech recognition api returns all sentences in one string, without any fullstop or commas. As a result, it has become harder to seperate sentences. For example, if I say,
Take a photo. Tell me about today's weather. Open Google Chrome.
the speech recognition api returnes:
take a photo tell me about todays weather open Google Chrome
so, my chatbot takes this full string as one sentence.
Is there any way to extract sentences from a string like the one above?
(BTW, I am using Python)
Answer: If you are about to say multiple commands say words like "and" and split the command based on that word. Now loop through the list and pass each value to your execute function.
If the variable command stores your value split it using command.split(" and ")
I had previously answered a similar question take a look at it:
https://stackoverflow.com/a/65872940/12279129
Comment: thanks for your answer but, I had already implememted what you just said. But saying "and"  every time feels weired to me. That's why I am interested doing this using NLP. It would be helpful if you can tell me how I would do it using nlp.
Answer: I think you could try different approaches to solve the problem:

A Naive solution

I don't know how your system works for now but if you are just looking for some subsentences you could search in the full set of sentences if there is what you are looking for.
i.e.
input_str = "Take a photo turn on fan".lower()

if "take a photo" in input_str :
 print("Just took a photo!")
if "turn on fan" in input_str :
 print("Just turned the fan on!")

Ofc you could also select a separator word (like and, furthermore, ..) and use it as separator.

A more advanced solution

You could use a NLP library (i.e. spacy) and perform entity recognition so that you can isolate verbs from noun and so on.
After that you could evemtually make use of stemming and lemmatization to further generalize the recognition.
You could also perform many intermediate step with different NLP techniques like stopwords removal.

Try auto punctuation from API

Maybe you can try enabling automatic punctuation in the speech to text api and see if this works good enough for you.
Comment: Thank you very much! Your 2nd and 3rd solution was very helpful.
Answer: That's because the Google Cloud Speech doesn't provide Natural Language Understanding and you are stuck parsing text transcripts.
You can of course create the natural language understanding component yourself, either by using simple regular expressions or using something like Rasa, but there's a smarter way, too.
Speechly provides you with everything you need to create voice user interfaces on Android, iOS or web. It returns you not only the transcript, but also actionable intents and entities that makes it a lot easier to create something a bit more complex. The best part is that it's free for up to 20 hours a month.
You can see a very simple example on how it works for instance for creating search experiences here. However, the basic idea is always the same: create a model and test that it returns correct intents for your speech input. After you are done, you integrate it to your app by looping through the returned results and whenever you get the correct intent, react in your application as needed. It's actually very simple.
Answer: You can use split method
Let your string is A
X = A.split('.')

It will make X a list which will contain items as sentences
Comment: There are no dots in a string that google api returns so I think you should replace it with space: X = A.split(' ')

Extract Sentences from A String


Remove Gem from RVM Gemset?

Question: New to RVM and playing with Rails 3 & Ruby 1.9.2 betas...
I've got two copies of rspec in a gemset. Was using beta.19 but need to downgrade to beta.18. changed my gemfile and then bundle install. now i have a mess...
*** LOCAL GEMS ***
. . .
rspec (2.0.0.beta.19, 2.0.0.beta.18)
rspec-core (2.0.0.beta.19, 2.0.0.beta.18)
rspec-expectations (2.0.0.beta.19, 2.0.0.beta.18)
rspec-mocks (2.0.0.beta.19, 2.0.0.beta.18)
rspec-rails (2.0.0.beta.19, 2.0.0.beta.18)

and I would like to remove all traces of beta.19 but can't seem to find out how.
Though the Gemfile is requiring beta.18, beta.19 is still running interference...and rspec is barfing all over my log files...
Edit: Thanks to Nikita I was able to remove the beta.19 gems. now i'm getting a broken path or something:
thismac:rails_app meltemi$ spec -v
/Library/Ruby/Site/1.8/rubygems.rb:335:in `bin_path': can't find executable spec for rspec-2.0.0.beta.18 (Gem::Exception)
    from /usr/bin/spec:19
mymac:appname meltemi$

is there something i need to do to rebuild now that 19 is gone and i'm falling back to 18?
Answer: How about gem uninstall rspec -v=2.0.0.beta.19 ?  Check gem help uninstall for details.
Or you can just uninstall all versions and then install the one you need.
Comment: thanks. got the gems "removed" but that only leads to another problem. *see above*
Comment: @Meltemi Never worked with rspec myself, but there're loads of similar reports in google:  http://www.google.com/search?hl=en&safe=off&q=ruby+spec+`bin_path':+can't+find+executable+spec+for+rspec++(Gem::Exception)&aq=f&aqi=&aql=&oq=&gs_rfai=
Comment: thanks for your help. i was able to figure it out. my fault...probably...but not sure what i did...but it seems to be working now. confusing stuff...
Comment: http://www.basictrading.biz/2011/06/solved-rails-uninstall-gem-rake-0-9-2-from-rvm/ this might also help
Answer: I had some similar issues with RVM due to the global and default gemsets. In my case the offending gems were in the @global gemsets and i was only able to remove them by doing
rvm @global do gem uninstall the-gem-name

Other commands like rvm all-gemsets do... and rvm all do... did not work
See this thread
How do I use RVM and create globally available gems?
and the doc
http://rvm.io/set/do
Answer: I had the same error message but what I needed to do was add the rspec rails to my :development group as well as :test, YMMV

Remove Gem from RVM Gemset?


how to hide UipickerViewController in applicationWillResignActive?

Question: I my application i want to hide the UIPickerview controller when application enter's in a paused state?
for eg: in my viewcontroller i am using uipickerview,and is placed in a popovercontroller,but i have not dismiss the popovercontroller and the application goes in a paused state.
when user open the application the uipikcer view is displayed which i want to dismiss.
please help me out with this.
Comment: http://stackoverflow.com/questions/3105974/dismissing-uialertviews-when-entering-background-state/12976086#12976086
Comment: Write your dismiss code in - (void)viewWillDisappear:(BOOL)animated;
Answer: Use NSNotificationCenter for hide the UIPickerView when application go in background like bellow...
[[NSNotificationCenter defaultCenter] addObserver:alertView selector:@selector(HidePickerView) name:@"UIApplicationWillResignActiveNotification" object:nil];

and hide the UIPickerView in bellow method..
- (void) HidePickerView {
      [yourPickerView setHidden:YES];
}

Answer: You need to subscribe for the UIApplicationWillResignActiveNotification notification and when it's fired and your selector is called, you should [self.myPickerView dismissViewControllerAnimated:NO completion:nil];.
Note: -viewWillDisappear: method would not be called when the app is resigning active.


How do I get the keys to the sewer?

Question: There is a cutscene that indicates that the whale/ghost noise that constantly plays is coming from the sewer, and in order to enter I need to get the key from the museum curator.  However, when I go to visit him, nothing happens.
So how do I get the keys?  Do I need to get a certain number of artifacts?  Is it a random reward?
Answer: According to the Stardew Valley Wiki:

The Sewers are unlocked by obtaining the Rusty Key after donating 60
  Artifacts to the Museum. They can be entered either through the sewer
  cover in the South of Pelican Town or through the grates in the South
  of Cindersap Forest.
In the Sewers you can catch the Mutant Carp, which is one of the five
  legendary fish in the game.
Krobus is also located here and sells 'rare' items, including a
  Stardrop and Iridium Sprinklers.

How do I get the keys to the sewer?