Q:

Printing the preparedStatement SQL after the bind for Oracle jdbc driver

I have tried several examples , but none of them seem to work. Here is the code I tried last
 import oracle.jdbc.driver.OracleDriver;
 PreparedStatement prs = null;
 ResultSet rrs = null;
Class stmt1 = null;
java.lang.reflect.Field mem = null;

  requestSQL = "Select FIPS_STATE_CD_TXT, FIPS_COUNTY_CD_TXT from MSTR_FIPS_COUNTY where STATE_ID = ? " + " and COUNTY_TXT = ?";

    prs.setString(1, vPropertyState);
    prs.setString(2, vPropertyCounty);
    System.out.println(prs.toString()); //JRN
             Class stmt1 = prs.getClass();
          java.lang.reflect.Field mem = stmt1.getField("sql");
          String value= (String)mem.get(prs);
          rrs = prs.executeQuery();

I get an error on this at :
   Exception trying to make a TAF call
   java.lang.NoSuchFieldException: sql
    at java.lang.Class.getField(Class.java:1520)

I even tried using this example from JavaWorld, but my compiler doesn't seem to recognize DebugLevel and StatementFactory. Is there a special package I should download for this?
http://www.javaworld.com/javaworld/jw-01-2002/jw-0125-overpower.html?page=3
I am using Java 1.6 and Oracle 11g. I am also looking for a quick fix, rather than installing log4jdbc or p6sy

A:

Different drivers use different names. In your case the sql field you are trying to access is not one of the available ones for that driver.
To get all the names of your JDBC driver use this code:
Class stmt1 = prepStmt.getClass();
try {
    java.lang.reflect.Field mem[] = stmt1.getDeclaredFields();
    for (Field x:mem){
        System.out.println("Field:"+x.getName());
    }
}  catch (SecurityException ex) {

}

Observe the field name, and then use your code above to print its value.

A:

The answer is, you can't. Atleast not for the Oracle jdbc driver.


Q:

How to end session in asp.net using html

I want to know how can I end or clear the session when the user clicks "Log Out" from the navbar? I am using  tag and I can't seem to think how to end the session.
Below is my code thats how I made my tag and I don't know where can I put the session end command. How will i do it? Thanks!

                 Yusen Logistics Philippines, Inc.

Admin controls

Maintenance

                <%--
Requests
--%>

My Requests

                    Requests <%--(<asp:Label ID="lblcount" runat="server" Text="#"></asp:Label>)--%>

Pending Requests <%--(<asp:Label ID="lblPending" runat="server" Text="#"></asp:Label>)--%>

Approved Requests <%--(<asp:Label ID="lblApprove" runat="server" Text="#"></asp:Label>)--%>

Noted Requests <%--(<asp:Label ID="lblApprove" runat="server" Text="#"></asp:Label>)--%>

History <%--(<asp:Label ID="lblApprove" runat="server" Text="#"></asp:Label>)--%>

                <%--
Accepted Requests (<asp:Label ID="lblAccept" runat="server" Text="#"></asp:Label>)
--%>

<asp:Label ID="lblName" runat="server" CssClass="control-label" Text="#" Visible="false"></asp:Label>

                            #

Manage Account

Log Out

                            <%--
Hello, <%: Context.User.Identity.GetUserName()  %> !

                                <asp:LoginStatus runat="server" LogoutAction="Redirect" LogoutText="Log off" LogoutPageUrl="~/" OnLoggingOut="Unnamed_LoggingOut" />

--%>

A:

Add A new aspx page and in page load function  add the following code and specify redirect
Session.Abandon()
Response.Redirect("default.aspx")

and in your html add some code like this

Logout


Q:

What's with Battlemind's Iron Fist being so powerful?

I'm a bit confused about this one.
Like, almost every melee class have an at-will power that is basically equivalent:

Main Stat VS AC
  1[W]+Stat modifier + Stat modifier Temp HP on hit.

Fighters have it, Avengers have it, barbarians, paladins, etcetc. They all have the power that does roughly the same thing, and is balanced and equivalent.
Then, Battlemind happens.
Not only is it a Resistance to all damage and therefore applies to every attack, but it's an effect and therefore applies even on a miss.
Is it just me or it's somewhat gamebreaking for an at-will power?
Basically, hit or miss, he gains that DR. So he can have it almost permanently.
I understand that this power might become weaker as the levels progresses, but so does every "equivalent" power with the temp HP... ?

A:

The Resist lasts one turn. THP last until taken away (when hit).
So, given the same value (e.g. 4, which is not game-breaking):

Resist for one turn is better if the character is hit twice.
THP is better if the character is not hit.
The two buffs are numerically identical if the character is hit just once before the next turn.

It is a more reasonable trade-off than it might seem at first sight.
Also, THP stack with resistances gained from other powers, whilst this relatively weak resist will not. That applies the other way around of course, but there are some nicer Resist-based Utility powers available to the Battlemind that will not stack with this power.
There is a Battlemind PC in my group, we have played from Level 1 to Level 11, and he did not rate the power enough compared to mobility- or mark-based ones to ever take it.


Q:

Twitter Sign in using Spring Boot

I am trying to sign in to my web application (developed using Spring Boot) using social logins. The logins for Google & facebook are okay. But the for some reason there is a token issue in the twitter login. I have created the project in the twitter developer site obtained all the credentials. Please refer to my code below.
My Property file values are mentioned below.
twitter.client.client-id=XXXXXXX
twitter.client.client-secret=XXXXXXXX
twitter.client.access-token-uri=https://api.twitter.com/oauth/access_token
twitter.client.user-authorization-uri=https://api.twitter.com/oauth/authorize
twitter.client.token-name=oauth_token
twitter.client.authentication-scheme=form
twitter.resource.user-info-uri=https://api.twitter.com/1.1/account/verify_credentials.json
The filter method
private Filter ssoTwitterFilter(String processingUrl, PrincipalExtractor principalExtractor) {
    OAuth2ClientAuthenticationProcessingFilter twitterFilter = new OAuth2ClientAuthenticationProcessingFilter(
            processingUrl);
    LOGGER.debug("processingUrl :{} ", processingUrl);

    twitterFilter.setAuthenticationSuccessHandler(authenticationSuccessHandlerAndRegistrationFilter());
    OAuth2RestTemplate twitterTemplate = new OAuth2RestTemplate(twitter(), oauth2ClientContext);
    twitterFilter.setRestTemplate(twitterTemplate);
    UserInfoTokenServices tokenServices = new UserInfoTokenServices(twitterResource().getUserInfoUri(),
            twitter().getClientId());
    tokenServices.setRestTemplate(twitterTemplate);
    tokenServices.setPrincipalExtractor(principalExtractor);
    return twitterFilter;
}

These are the bean configurations.
@Bean
@ConfigurationProperties("twitter.client")
public AuthorizationCodeResourceDetails twitter() {
    return new AuthorizationCodeResourceDetails();
}

@Bean
@ConfigurationProperties("twitter.resource")
public ResourceServerProperties twitterResource() {
    return new ResourceServerProperties();
}

This is the error that I get
enter image description here
Please can anyone shed some light on this. Because all the samples I found were related getting profile information from twitter where as i need a sample for sign in using spring Boot. Thanks in advance

A:

You can configure Twitter login like this:
 @Configuration
 @EnableSocial
public class SocialConfig implements SocialConfigurer {

@Autowired
private  UserAuthorizationService userAuthorizationService;
@Override
public void addConnectionFactories(ConnectionFactoryConfigurer cfConfig, Environment env) {

    cfConfig.addConnectionFactory(new TwitterConnectionFactory(
            env.getProperty("twitter.consumer-key"),
            env.getProperty("twitter.consumer-secret")
    ));

}

@Override
public UserIdSource getUserIdSource() {
    return new UserIdSource() {
        @Override
        public String getUserId() {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication == null) {
                throw new IllegalStateException("Unable to get a ConnectionRepository: no user signed in");
            }
            return authentication.getName();
        }
    };
}

@Override
public UsersConnectionRepository getUsersConnectionRepository(ConnectionFactoryLocator connectionFactoryLocator) {
    InMemoryUsersConnectionRepository usersConnectionRepository = new InMemoryUsersConnectionRepository(

            connectionFactoryLocator
    );
    return usersConnectionRepository;
}

@Autowired
private TwitterConnectionSignup twitterConnectionSignup;
@Autowired
private ConnectionFactoryLocator connectionFactoryLocator;

@Autowired
private UsersConnectionRepository usersConnectionRepository;
@Bean
public ProviderSignInController providerSignInController() {
    ((InMemoryUsersConnectionRepository) usersConnectionRepository)
            .setConnectionSignUp(twitterConnectionSignup);

    return new ProviderSignInController(
            connectionFactoryLocator,
            usersConnectionRepository,
            new TwitterSignInAdapter(userAuthorizationService));
}

}
Configure TwitterConnectionSignup:
@Service
public class TwitterConnectionSignup implements ConnectionSignUp {

@Autowired
private UserRepo userRepo;

@Override
public String execute(Connection<?> connection) {

   //add your logic to save user to your db
    return connection.getDisplayName();
}

}
Now configure TwitterSignInAdapter:
public class TwitterSignInAdapter implements SignInAdapter {
private UserAuthorizationService userAuthorizationService;

public TwitterSignInAdapter(UserAuthorizationService userAuthorizationService) {
    this.userAuthorizationService = userAuthorizationService;
}

@Override
public String signIn(String localUserId, Connection<?> connection, NativeWebRequest webRequest) {

    log.debug(" Email {}", localUserId);

    UserAuthDto userAuthDto = (UserAuthDto) userAuthorizationService.loadUserByUsername(localUserId);
    UsernamePasswordAuthenticationToken updatedAuth = new UsernamePasswordAuthenticationToken(userAuthDto, userAuthDto.getSocialId(),
            userAuthDto.getAuthorities());

    SecurityContextHolder.getContext().setAuthentication(updatedAuth);
    HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class);
    // add authentication to the session
    servletRequest.getSession().setAttribute(
            HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
            SecurityContextHolder.getContext());

    return "/";
}

}


Q:

4K video from Panasonic VC8xx broken?

I have recorded some 4K videos as MP4 file on Panasonic VX878 and 9xx. Both produce a video which, when played in VLC or other player on Linux, has 3 tiles: 2 next to each other horizontally at the top 20 % of the canvas, both displaying the actual video, and the rest displays the 1st second of the video, looping.
I wonder where is the issue: In the player on in the camera? When I played the video in the camcoder's playback, it looked fine.

A:

Yes, the videos are broken. They are created due to an overheat and some kind of built-in reduction of the recorded video to FullHD; but the resolution of the result is still 4K, and the last filled content of the 4K buffer is used to fill the bottom large part (hence the repeating).
Still, it's possible to get a FullHD video from the broken file:
FILTER='
[in] split [a][b];
[a] crop=1920:540:0:0 [ac];
[b] crop=1920:540:1920:0 [bc];
[ac][bc] vstack [stack];
[stack] il=luma_mode=interleave:chroma_mode=interleave'

if [ "$2" != "" ] ; then
  ffplay -i "$INPUT" -vf "$FILTER"
else
  set -x
  ffmpeg -i "$INPUT" -filter:v "$FILTER" $QUALITY_GOOD_H265 -c:a copy "$NEW_NAME" \
  && touch "$NEW_NAME" -r "$INPUT"
  set +x
fi


Q:

Illegal scale after migrate to UWP from Window 8.1 Store App

I've migrated my Window 8.1 Store app to UWP and now displayInfo.ResolutionScale = Scale125Percent on my tablet. In Win8.1 this factor was equal to Scale100Percent.
I have 2 questions:

Why is that?
How to return displayInfo.ResolutionScale to Scale100Percent under UWP?

A:

Windows 8 used three scale factors - - 100% for traditional desktop monitors at ~96 DPI, 140% for the original Surface Pro and other devices at ~135 DPI, and 180% for future expansion.
Fast forward through 8.1 and the convergence with Phone and the slew of new devices and compat requirements for Desktop Win32 as well as iOS and Android, and now Windows has a much broader set of scale factors (100, 125, 150, 175, 200,...) and the default scale factor for any given machine might have been updated.
The user can change the scale factor in Display Settings; Apps cannot change the scale factor at runtime. Your app will observe whatever the user has set as their scale factor.
For compat reasons, Windows will lie to legacy apps and report the closest legacy value (100, 140, 180) to the actual scale factor of the device.


Q:

Why wouldn't a prototype function be able to read a prototype property?

I have this code, that returns an Uncaught ReferenceError: year is not defined.
function Car(color, drivetrain) {
    this.color = color;
  this.drivetrain = drivetrain;
  this.stats = function(){
  console.log(color + " " + drivetrain);
  };
}

Car.prototype.year = 2012;
Car.prototype.funcyear = function () { console.log(year);}; //reference error

var toyota = new Car('red', 'fwd');
toyota.stats();
console.log(toyota.year);
toyota.funcyear();

Why wouldn't this be able to work, shouldn't the funcyear function be located in the prototype, so year should be accessible?

A:

Because only year would reference a variable (or a function), but not a property.
To reference a property you have to name the object, this property is attached to.
Car.prototype.funcyear = function() {
    console.log(this.year);
};

Note:
function Car(color, drivetrain) {
    this.color = color;
    this.drivetrain = drivetrain;
    this.stats = function(){
        //this part is "dangerous", because color and drivetrain reference the local variables
        //in this surrouunding function-call, NOT the properties of this instance
        //so you might change the properties, but you don't see any effect.
        console.log(color + " " + drivetrain);
    };
}


Q:

Cannot access the element using the "Contains" keyword (Selenium,Python)

I'm trying to access the following element using the contains keyword but I fail every time:

Bulgaria

<input id="country_255" class="save-checkbox jcf-hidden" data-allowlist="378,438,183" name="jform[country][]" value="255" data-currency="2" data-bond_count="19" checked="checked" type="checkbox"/>

I tried:
1. //*[contains(text(), 'Bulgaria')])
2. //*[@id='country']/div[15][@label='Bulgaria']

(it's a list of countries and Bulgaria is under div[15]
Can anyone help me to find out what the problem is?

A:

 //*[contains(text(), 'Bulgaria')])

To break this down,

* is a selector that matches any element (i.e. tag) -- it returns a node-set.
The [] are a conditional that operates on each individual node in that node set. It matches if any of the individual nodes it operates on match the conditions inside the brackets.
text() is a selector that matches all of the text nodes that are children of the context node -- it returns a node set.
contains is a function that operates on a string. If it is passed a node set, the node set is converted into a string by returning the string-value of the node in the node-set that is first in document order. Hence, it can match only the first text node in your  element -- namely BLAH BLAH BLAH. Since that doesn't match, you don't get a  in your results.

You need to change this to
 //*[text()[contains(.,'Bulgaria')]]

* is a selector that matches any element (i.e. tag) -- it returns a node-set.
The outer [] are a conditional that operates on each individual node in that node set -- here it operates on each element in the document.
text() is a selector that matches all of the text nodes that are children of the context node -- it returns a node set.
The inner [] are a conditional that operates on each node in that node set -- here each individual text node. Each individual text node is the starting point for any path in the brackets, and can also be referred to explicitly as . within the brackets. It matches if any of the individual nodes it operates on match the conditions inside the brackets.
contains is a function that operates on a string. Here it is passed an individual text node (.). Since it is passed the second text node in the <Comment> tag individually, it will see the 'Bulgaria' string and be able to match it.


Q:

Error iterating a std::vector of pointers

I need to copy a std::vector that containing pointers to a class. The function is:
Clone::Clone( const Clone &source )
{
    m_pDerivate.clear();

    std::vector<Derivate *>::const_iterator it;
    it = source.m_pDerivate.begin();
    for (it = source.m_pDerivate.begin(); it != source.m_pDerivate.end(); ++it) {
        m_pDerivate.push_back(new Derivate(it));
    }
}

And the Derivate constructor is:
Derivate::Derivate( const Derivate &source )
{
    _y = source._y;
    _m = _strdup(source._m);
}

But when I compile, I get the following error ...
 cannot convert parameter 1 from 'std::_Vector_const_iterator<_Myvec>' to 'const Derivate &'

... in the line:
m_pDerivate.push_back(new Derivate(it));

If I change the line by ...
m_pDerivate.push_back(new Derivate((const Derivate &)(*it)));

... compile fine but the Derivate constructor not receives the data correctly.
Can you help me?
Thanks in advance.

A:

You need to dereference the iterator and the pointer:

*it is of type Derivate*
**it is of type Derivate

Change:
m_pDerivate.push_back(new Derivate(it));

to:
m_pDerivate.push_back(new Derivate(**it));


Q:

Dump all databases to file

Possible Duplicate:
Out of resources for mysqldump

I'm trying to export all databases from my wamp installation (so I can do a reinstall), but I get this error when trying to generate a dump file:

C:\wamp\bin\mysql\mysql5.1.36\bin>mysqldump -u root --all-databases >
  dbs.sql mysqldump: Got error: 23: Out of resources when opening file
  '.\site\posts_rg_lea d_detail.MYD' (Errcode: 24) when using LOCK
  TABLES

the export stops after ~70 MB...

A:

Error 24 is : "Too many open files"
try this (add --single-transation):
mysqldump -u root --all-databases --single-transaction > dbs.sql


Q:

XSSFSheet: Sheet index is out of range

I am tring to write the contents of xlsx file with POI but got an IllegalArgumentException.
Following is my code:
public static void ConvertToCSVOrgtoOrg(String Scenario) throws Exception {

    String IntermediateXLSXPath=GetFileDetailsSIF(Scenario,"ExcelPath");
    String IntermediateCSVPath=GetFileDetailsSIF(Scenario,"CSVPathOrgtoOrg");

    File inputFile = new File(IntermediateXLSXPath);
    File outputFile = new File(IntermediateCSVPath);
    // For storing data into CSV files
    StringBuffer data = new StringBuffer();

    try {
        FileOutputStream fos = new FileOutputStream(outputFile);
        // Get the workbook object for XLSX file
        XSSFWorkbook wBook = new XSSFWorkbook(new FileInputStream(inputFile));
        XSSFFormulaEvaluator.evaluateAllFormulaCells(wBook);
        // Get first sheet from the workbook
        XSSFSheet sheet = wBook.getSheetAt(18);
        XSSFFormulaEvaluator.evaluateAllFormulaCells(wBook);

        Row row;
        Cell cell;
        // Iterate through each rows from first sheet
        Iterator<Row> rowIterator = sheet.iterator();

        while (rowIterator.hasNext()) {
            row = rowIterator.next();
            data.append("\n");

            // For each row, iterate through each columns
            Iterator<Cell> cellIterator = row.cellIterator();
            while (cellIterator.hasNext()) {
                cell = cellIterator.next();

                switch (cell.getCellType()) {
                    case Cell.CELL_TYPE_BOOLEAN:
                        data.append(cell.getBooleanCellValue());
                        break;

                    case Cell.CELL_TYPE_NUMERIC:
                        data.append(cell.getNumericCellValue());
                        break;

                    case Cell.CELL_TYPE_STRING:
                        data.append(cell.getStringCellValue());
                        break;

                    case Cell.CELL_TYPE_FORMULA:
                        data.append(cell.getStringCellValue());

                    case Cell.CELL_TYPE_BLANK:
                        break;
                    default:
                }
            }
        }

        fos.write(data.toString().getBytes());
        Thread.sleep(1000);
        fos.close();

    } catch (Exception ioe) {
        ioe.printStackTrace();
    }

}

The exception I am getting is:

java.lang.IllegalArgumentException: Sheet index (18) is out of range (0..17)
  at org.apache.poi.xssf.usermodel.XSSFWorkbook.validateSheetIndex(XSSFWorkbook.java:1205)
  at org.apache.poi.xssf.usermodel.XSSFWorkbook.getSheetAt(XSSFWorkbook.java:960)
  at BasicCoreFramework.ObjectUtilities.ConvertToCSVOrgtoOrg(ObjectUtilities.java:1625)
  at TestUtilities.FileManipulation.PostAggregationScenario1Functionality(FileManipulation.java:40)
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
  at java.lang.reflect.Method.invoke(Unknown Source)
  at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:85)
  at org.testng.internal.Invoker.invokeMethod(Invoker.java:639)
  at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:816)
  at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1124)
  at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
  at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:108)
  at org.testng.TestRunner.privateRun(TestRunner.java:774)
  at org.testng.TestRunner.run(TestRunner.java:624)
  at org.testng.SuiteRunner.runTest(SuiteRunner.java:359)
  at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:354)
  at org.testng.SuiteRunner.privateRun(SuiteRunner.java:312)
  at org.testng.SuiteRunner.run(SuiteRunner.java:261)
  at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
  at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
  at org.testng.TestNG.runSuitesSequentially(TestNG.java:1215)
  at org.testng.TestNG.runSuitesLocally(TestNG.java:1140)
  at org.testng.TestNG.run(TestNG.java:1048)
  at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:126)
  at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:137)
  at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:58)

I do have a 18th sheet. Any help would be greatly appreciated.

A:

...
// Get first sheet from the workbook
//XSSFSheet sheet = wBook.getSheetAt(18); Instead,
XSSFSheet sheet = wBook.getSheetAt(17);
...

As you said you have only 18 excel sheets in that file, if you are going to get the 18th sheet in the excel file, you have to minus 1 from 18. Specify 17.
Index is start from 0 instead of 1.


Q:

Why does this example from the Ember.js guides not work?

I cannot get the second code example of the Ember.js website's Guides section to work. Following the Simple Routes example does not seem to do what is intended in the resulting Web app.
I have followed all the steps from the start of the guide to the end of that example, copying the code exactly, with two exceptions. First, I made a small change to routes/favorites.js to get around my lack of server backend, as shown here:
// import ajax from 'ic-ajax';

export default Ember.Route.extend({
 model() {
    // // the model is an Array of all of the posts
    // // fetched from this url
    // return ajax('/a/service/url/where/posts/live');
    return [{ title: 'Test 1' }, { title: 'Test 2' }];
  }
});

Second, I added an {{outlet}} to templates/application.hbs to show the templates/favorites.hbs:

{{appName}}

{{model.title}}

{{outlet}}

Unfortunately, going to /favorites while running ember serve just shows the same thing as /: the content of application.hbs (without the content of favorites.hbs). I would expect this to show a list with items "Test 1" and "Test 2".
Why does this not work? Am I doing something wrong?
When I run ember -v on my command line, I get this:
version: 1.13.6
node: 0.12.7
npm: 2.13.2
os: darwin x64

Update: Here is templates/favorites.hbs:

{{#each controller as |item|}}

{{item.title}}

{{/each}}

Here is /router.js:
var Router = Ember.Router.extend();

Router.map(function(){
  this.route('favorites');
});

export default Router;

I get a deprecation warning from the server:
DEPRECATION: Using `{{controller}}` or any path based on it ('my-app/templates/favorites.hbs' @ L2:C0) has been deprecated.

I also get four JSHint errors like this:
'Ember' is not defined.

A:

To be able to navigate without a hash (http://localhost:4200/favorites instead of http://localhost:4200/#/favorites) make sure your router has its location type set:
import Ember from 'ember';
import config from './config/environment';

var Router = Ember.Router.extend({
  location: config.locationType  // typically 'auto'
});

Router.map(function() {
  this.route('favorites');
});

export default Router;


Q:

Does C++ Standard description of indirection operator guarantee memory writes are not optimized away?

This is basically a continuation of this question. So far it looks like that if I have a function like this:
void SecureZeroMemory( void* ptr, size_t cnt )
{
   volatile char *vptr = (volatile char *)ptr;
   while (cnt) {
       *vptr = 0;
       vptr++;
       cnt--;
   }
}

and call it like this:
{
    char buffer[size];
    SecureZeroMemory( buffer, size );
}

then since buffer is not declared volatile it doesn't matter that a pointer to volatile is used - the data itself is not volatile, so write to the variable do not constitute observable behavior (1.9/6) and the compiler is allowed to optimize them away.
However recently I've come across a statement that it's only the pointer declaration that matters. Specifically C++03 5.3.1/1 describes indirection (*) like this:

The unary * operator performs indirection [...] If the type of the expression is “pointer to T,” the type of the result is “T.”

So the claim is that because of using indirection on a volatile char* we get volatile char and writes to those do constitute observable behavior and it no longer matters how the actual data is declared.
Does the C++03 5.3.1/1 description of indirection really guarantee that overwriting memory using a volatile T* pointer as in the sample above constitute observable behavior and is disallowed to be optimized away?

A:

I'm pretty sure all that "new" quote adds is that *vptr is an lvalue expression with type volatile char.
The type of the lvalue doesn't affect the type of the object to which that lvalue expression refers, for the same reason that a pointer-to-const that points at a non-const object doesn't somehow make the object const. So the original analysis isn't affected  this quote -- the object still doesn't have volatile-qualified type.
In normal parlance we'd say that the type of *vptr is volatile char &, but 5/5 says, "If an expression initially has the type “reference to T” the type is adjusted to T prior to any further analysis". That's the reason why *vptr is said to have type volatile char, not volatile char & -- before analysing any expression you remove the reference from the type, even if it's an lvalue.
[Edit: my answer used to have some text about cv-qualifications being insignificant for non-object values of integer type. It was true (lvalue-to-rvalue conversions of non-class types discard cv-qualifiers, 4.1/1) but irrelevant (I mistakenly thought that because the text you quoted mentioned a non-reference type it was talking about the type after this conversion)]

A:

It's an interesting question.  I think the intent of the
standard was that this should work.  On reading the standard
(C++03, §1.9/6,7) however:

The observable behavior of the abstract machine is its sequence
  of reads and writes to volatile data and calls to library I/O
  functions.
Accessing an object designated by a volatile lvalue, modifying
  an object, calling a library I/O function, or calling
  a function that does any of those operations are all side
  effects, which are changes in the state of the execution
  environment.  Evaluation of an expression might produce side
  effects. At certain specified points in the execution sequence
  called sequence points, all side effects of previous
  evaluations shall be complete and no side effects of
  subsequent evaluations shall have taken place.

The difference in wording in the two paragraphs would seem to be
significant: the "observable behavior" is the sequence of reads
and writes volatile data.  In your case, buffer is not
volatile data, so the compiler is, presumably, free to optimize
the accesses away.  I don't think that this is the intent, but
that seems to be what it says.
In your case, the optimization would be particularly simple,
since the conversion to volatile occurs in the function itself.
The compiler can easily determine that vptr doesn't point to
data that is actually volatile.  If you change the parameter
type to void volatile*, then the compiler would have to see
both the call site and the function at the same time in order to
safely do the optimization.
And finally, regardless of what the standard says, compilers
have their own interpretations of volatile.  In practice,
most, if not all compilers, will assume that you are using
volatile for a reason, and will generate the machine
instructions to do the writes.  (In practice, that is all that
they will do, which means that the order that the writes become
visible outside of the thread the code in which the thread is
running remains undefined.  This isn't a problem for your use,
but it is for a lot of other uses.)


Q:

Custom metric alarm function Amazon Cloudwatch

I am playing around with boto and Amazon EC2 instances. I am able to create an alarm on a metric for cpu utilisation that sends an email via an SNS Topic. However what I would like to do is call a function in my code when the alarm is triggered to launch a new instance. I don't see a way of placing anything besides an ARN string on an alarm action? Does anyone have any ideas? Thanks

A:

An alarm can only publish to an SNS topic but there are a number of ways to subscribe to that topic.  You can get an SMS message, get email, or you can have your own program called via HTTP or HTTPS.  You would have to write a small web application that listens for the SNS messages and then perform whatever action you want.  Or you could subscribe an SQS queue to the SNS topic and then have your program poll the SQS queue waiting for messages.


Q:

Kafka having duplicate messages

I don't see any failure while producing or consuming the data however there are bunch of duplicate messages in production. For a small topic which gets around 100k messages, there are ~4k duplicates though like I said there is no failure and on top of that there is no retry logic implemented or config value is set.
I also check offset values for those duplicate messages and each has distinct values which tells me that the issue is in producer.
Any help would be highly appreciated

A:

Read more about message delivery in kafka:
https://kafka.apache.org/08/design.html#semantics

So effectively Kafka guarantees at-least-once delivery by default and
  allows the user to implement at most once delivery by disabling
  retries on the producer and committing its offset prior to processing
  a batch of messages. Exactly-once delivery requires co-operation with
  the destination storage system but Kafka provides the offset which
  makes implementing this straight-forward.

Probably you are looking for "exactly once delivery" like in jms
https://cwiki.apache.org/confluence/display/KAFKA/FAQ#FAQ-HowdoIgetexactly-oncemessagingfromKafka?

There are two approaches to getting exactly once semantics during data
  production: 1. Use a single-writer per partition and every time you get a
  network error check the last message in that partition to see if your
  last write succeeded 2. Include a primary key (UUID or something) in the
  message and deduplicate on the consumer.

We implemented second point in our systems.


Q:

Avoid warning: unreferenced find_rule label

In order To get more compatibility between flex and other version of lex , we should add -l option in flex command.
One of these incompatibilities is yylineno (global variable to store line number). Although there are two ways to activate this option :

using %option yylineno
or -l option

I have always this kind of warning :

warning C4102: 'find_rule' : unreferenced label

any help please to avoid this warning!

A:

Since you say that the code triggering the warning is auto-generated and can't be controlled by you, the only way to get rid of the warning is to suppress it for that code only. You have two options.
Option one is to alter the compiler settings for the specific file (not the best thing to maintain).
Option 2 is to #include the .c file into another file and wrap that into #pragma warning:
//WrapperGateFile.c
#pragma warning(push)
#pragma warning(disable: 4102)

#include "ProblematicFile.c"

#pragma warning(pop)

and (important!) either not include the problematic .c file into the project or exclude the original .c file from build ("Excluded from build" property) so that it is not compiled and linked twice.


Q:

How to end try- catch in andoid?

I wanna jump out of try block,
How do i do it?
try
{
//some code

if()
{
// I want to break/ jump out from try block here if condition is true
}
else
{
}

//but it continues here
 // More Code
}
catch()
{
}

How Do i jump out of it?
Any help would be appreciated.

A:

Method 1
Try something like this:
try {
    do {
        ...
        if (condition)
            break;
        ...
    } while(false);
} catch () {
    ...
}

So the try block is just a do-while loop consisting all of the code. If the condition is true, it breaks out of the loop, and hence the try block.
Otherwise, it continues to the end and, because the condition of the do-while is false, comes out of the try block.
Note: If the if-statement is within another loop(other than this do-while loop), label this do-while loop, and later break to this label if condition is true.
Method 2
Make a custom Exception class and throw it only when the condition is met. Later, make the first catch statement to catch that custom exception. Like this:
try {
    ...
    if (condition)
        throw new CustomException();
    ...
} catch (CustomException e) {
    // Condition was true
} catch () {
    ...
}


Q:

To "be" or "have" more of something? (meaning: to be like something)

In a song I know, there's the line:

Who's more of a beast?

The rest of the lyrics around this makes it clear that it should mean something like "Who is more like a beast?" or "Who as more characteristics of a beast?".
So the 's, does it refer to is or has in this context?
How would one say this?

Who is more of a beast? or Who has more of a beast?

I would think "is", but in German one would rather use the direct translation of "have"...

A:

It's fairly common in English to say that a person or a thing is "more of an X", meaning that it more closely resembles X than it resembles Y, or that it resembles X more than other things do. Likewise, we say that it is "a bit of an X" or "something of an X" or similar phrases, meaning that it has some characteristics of X.
Example: "A modern cell phone is more of a computer than a telephone." It is more like a computer than it is like a telephone.
"Jack is a bit of a trouble-maker." Jack may not fully qualify as a trouble-maker, but he has some of the characteristics of a trouble-maker.
Etc.


Q:

Cherry-picking all commit history of a particular file

Suppose I want to cherry-pick full commit history of a particular file of a repo but the repo has more than one file and the commits are not even i.e 1st commit is to the particular file I wanted to cherry-pick and 2nd and 3rd is to some other and 4th to the particular file and so..
In this case how can my cherry-pick all the commits in one shot of that particular file excluding the commits that are done to other files..
I know,
$ git cherry-pick abc^..xyz

the command above wont work as it would cherry-pick the other commits which i wanna exclude also..
So my question is, Is there any way to do my requirement in a single command??

A:

Do you need the commit history also ?
One option is
git show <treeish>:<file>

and then just commit the file, Though it effectively "squashes" the commit
You could use this too
How to cherry pick only changes for only one file, not the whole commit
git diff <branch>^..<branch> -- <filename> | git apply


Q:

angular.js ng-options with custom values

I have the json object that is returned from an ajax call:
0: Object
    id: "0-0-0"
    selected: "selected"
    text: "option name"
    value: 0
    __proto__: Object
1: Object
    id: "12-0-0"
    selected: ""
    text: "4C 1.75 16v Tbi ( TCT )"
    value: 59885

I want to populate the options of a select like so:
<option value="0" id="0-0-0" selected="selected">option name </option>

How is this possible with ng-options?

A:

ng-repeat makes more sense if you need the id attribute populated by the server response:
HTML:
<select>
    <option ng-repeat="obj in results" id="{{obj.id}}" value="{{obj.value}}"
    ng-selected="obj.selected === 'selected'">{{obj.text}}</option>
</select>

ng-repeat Demo
However, if it's just the data you're after (and don't need to set the id attribute for each option), ng-options would work like this instead:
<select ng-model="selection" ng-options="obj as obj.text for obj in results">
</select>

ng-options Demo


Q:

SharePoint 2007 - custom context menu for certain file types

I was wondering if someone could help me out with SharePoint 2007. What I want to do is to add a custom menu item to a context menu (the menu that opens when you click a document or another item).
Right now, the menu looks like this: picture
I want to add an item, "Do stuff" for example, to this menu. Major problems:

I wish this item to appear only in menus for a certain file type (e.g. only for .html but not for .doc);
When I click this item ("Do stuff"), I want to call custom external code (written in C#, either an exe or a DLL), which accepts the name of the clicked file as an input parameter.

I understand the way to achieve this is by using Custom Actions (no JavaScript editing required in 2007, right?). But since I'm quite new to MOSS, I'm a bit lost and not sure what exactly to do and where to start, so any help is greatly appreciated.

A:

Sounds like you want a feature that includes your custom action and some code to execute.
Here is a walk-through:  http://blogit.create.pt/blogs/andrevala/archive/2008/08/11/SharePoint-2007-Deployment_3A00_-Custom-Action-Features.aspx


Q:

Empty page in the attributes manager

Not for sure but may be this is a noob Question.
If i want to change anything to the attributes sets in the attributes manager I get an empty page.
I tried to search in the log file and there is an error.
2014-08-23T11:34:48+00:00 ERR (3): Warning: include(): Failed opening 'Mage/Eav/Block/Adminhtml/Attribute/Grid/Abstract.php'

And I do not know how to fix this!
Any tips or tricks for this one?
Thank you,

A:

Download the same version of Magento you are having right now from magento connect and find and upload the file
app/code/core/Mage/Eav/Block/Adminhtml/Attribute/Grid/Abstract.php

from it to your Magento install. It seems the file was either deleted or was not uploaded.


Q:

Como criar transições personalizadas no Android Studio?

Gostaria de saber como fazer transições personalizadas no Android. As transições entre as atividades são sempre as mesmas. Tem algum tutorial que ensine a melhorar as transições?

A:

Para criar animações customizadas entre transições de telas na aplicação, pode-se usar o método overridePendingTransition() da sua classe pública Activity. Sua sintaxe é:
public void overridePendingTransition(int animacaoEntrada, int animacaoSaida)

Tem algum tutorial que ensine a melhorar as transições?

Sim, existem vários tutoriais, mas vou lhe dar um pequeno resumo. Quanto a melhoria das transições, vai da criatividade da cada uma.
Veja bem, existem algumas transições padrões dentro do diretório android.R.anim como por exemplo fade_in e fade_out. Então aplicando essa animação seria desta forma:
Intent i = new Intent(this, EnterActivity.class);
startActivity(i);
overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out);

Isso  fará com que saia do layout suavemente usando a tag alpha, como por exemplo o fade_in. Veja:
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
        android:interpolator="@interpolator/decelerate_quad"
        android:fromAlpha="0.0" android:toAlpha="1.0"
        android:duration="@android:integer/config_longAnimTime" />

Para criar uma animação customizada, basta, de preferência, criar diretório com o nome anim no seu resource, e inserir o arquivo de animação como por exemplo botton_in e top_out que fará com que o layout que chamado virá de baixo para cima, diferente da transição padrão. Veja como seria:
botton_in.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/linear_interpolator">
    <translate
        android:fromYDelta="100%p"
        android:toYDelta="0"
        android:duration="150"/>
</set>

top_out.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/linear_interpolator">
    <translate
        android:fromYDelta="0"
        android:toYDelta="-100%p"
        android:duration="150"/>
</set>

Classe
Intent i = new Intent(this, EnterActivity.class);
startActivity(i);
overridePendingTransition(R.anim.botton_in, R.anim.top_out);

O tema do Material fornece algumas animações padrão para botões e transições de atividades e o Android 5.0 (API de nível 21) e posteriores permitem a personalização dessas animações e a criação de novas. Você pode ver em Como definir animações personalizadas.


Q:

error A2070: invalid instruction operands IN SSE MASM64

when compiling this in ml64.exe 64bit (masm64)
the SSE command give me an error
what do i need to do to include the SSE commands in 64 bit?
.code

foo PROC

  movlps [rdx], xmm7 ;;error A2070: invalid instruction operands
  movhlps xmm6, xmm7
  movss [rdx+8], xmm6 ;;rror A2070: invalid instruction operands
  ret

foo ENDP

end

i get the error:
1>Performing Custom Build Step
1> Assembling: extasm.asm
1>extasm.asm(6) : error A2070: invalid instruction operands
1>extasm.asm(10) : error A2070: invalid instruction operands
1>Microsoft (R) Macro Assembler (x64) Version 8.00.50727.215
1>Copyright (C) Microsoft Corporation.  All rights reserved.
1>Project : error PRJ0019: A tool returned an error code from "Performing Custom Build Step"

A:

So modify the two lines to:
movlps QWORD PTR[rdx], xmm7
movss dword ptr [rdx+8], xmm6
like here:
http://social.msdn.microsoft.com/Forums/en-US/vcgeneral/thread/4f473acb-7b14-4bf4-bed3-e5e87e1f81e7


Q:

Test own cmdlets

Is there any common practice for testing cmdlets written in C#?
I'm interested in something like this:
[Test]
public void Test1()
{
    var cmdlet = new MyCmdlet();
    cmdlet.Property1 = "something 1";
    cmdlet.Property2 = "something 2";

    var actualOutput = Execute(cmdlet);

    AssertCmdLetOut(expectedOutput, actualOutput);
}

A:

Not very elegant. But still more than nothing: here.


Q:

Rest API to get list of artifacts from Nexus OSS 3.x Repository

I have created a raw repository in Nexus 3.x and I'm able to upload artifacts to the same. Now I want get the list of all artifacts residing inside that repo using Rest API.
Any help is appreciated.

A:

in the current Nexus3.14.0-04 the REST API has become final (no longer "beta") and the curl you need is:
curl -X GET "http://localhost:8081/service/rest/v1/components?repository=central" -H "accept: application/json"
this will return each "component" (group, name, version) with all its assets = each individual file (pom, sha1, md5, jar) who constitue the component
The result is a JSON string.
If instead you want to perform a COMPONENTS search - based on a groupId, artifactId - you can use this curl:
curl -X GET "http://localhost:8081/service/rest/v1/search?repository=central&format=maven2&maven.groupId=com.fasterxml.jackson.core&maven.artifactId=jackson-core&maven.extension=jar" -H  "accept: application/json"
this returns COMPONENTS with child ASSETS.
The variant to retrieve only the ASSETS, without grouping them by COMPONENT, is GET /service/rest/v1/search/assets?repository=central&format=maven2&maven.groupId=com.fasterxml.jackson.core&maven.artifactId=jackson-core&maven.extension=jar


Q:

Pass variable from beforeDelete to afterDelete() in CakePHP

I want to delete a file after a record in database has been deleted.
Because I use some data from a related model to build a path to image I need to fetch this data in the beforeDelete().
function beforeDelete() {
    $info = $this->find('first', array(
        'conditions' => array('Media.id' => $this->id),
    ));
}

function afterDelete() {
   unlink(WWW_ROOT . 'img/photos/' . $info['News']['related_id'] . "/" . $info['Media']['file']);
}

How to properly access $info array in afterDelete()?

A:

You can simply declare this var outside method scope.
private  $info;
function beforeDelete() {
$this->info = $this->find('first', array(
    'conditions' => array('Media.id' => $this->id),
));
}

function afterDelete() {
   unlink(WWW_ROOT . 'img/photos/' . $this->info ['News']['related_id'] . "/" . $this->info ['Media']    ['file']);
}


Q:

Por que devemos usar "IS NOT NULL" ao invés de "<> NULL"?

Sempre me perguntei isso: Por que devemos usar IS NOT NULL ao invés de <> NULL?
Pois, quando faço como no segundo caso, nenhum resultado é encontrado.
Exemplo:
SELECT * FROM tabela WHERE campo IS NOT NULL

Exibe todas as linhas, exceto quando campo não é nulo.
Exemplo:
SELECT * FROM tabela WHERE campo <> NULL

Não exibe nada.
Observação: A primeira vez que tentei fazer essa comparação foi com != e também não deu certo. Pois a funcionalidade desses operadores são semelhantes.

A:

Você não pode utilizar operadores de comparação aritméticos para validar o
NULL pois eles sempre retornarão NULL. Para verificar um valor NULL utilize aos operadores IS NULL e IS NOT NULL.
Um exemplo:
mysql> SELECT 1 = NULL, 1 <> NULL, 1 < NULL, 1 > NULL;
+----------+-----------+----------+----------+
| 1 = NULL | 1 <> NULL | 1 < NULL | 1 > NULL |
+----------+-----------+----------+----------+
|     NULL |      NULL |     NULL |     NULL |
+----------+-----------+----------+----------+

No  MySQL o 0(zero) e NULL são considerados como FALSE, e todo o restante como TRUE. O valor default para TRUE é 1.
mysql> SELECT 1 IS NULL, 1 IS NOT NULL;
+-----------+---------------+
| 1 IS NULL | 1 IS NOT NULL |
+-----------+---------------+
|         0 |             1 |
+-----------+---------------+

Dica de leitura: https://dev.mysql.com/doc/refman/5.0/en/working-with-null.html


Q:

how to parse a date into clj-time by ignoring the time and secs

Given the following string, I would like to get a date-time with only the date -
String "2013-02-20T17:24:33Z", I would like to get a date while ignoring the time and secs.
The following would work - (parse (formatters :date-time-no-ms) "2013-02-2T17:24:33Z"). However the resulting date-time object also contains the secs, how do I trim it down to just year-month-day ?
One way is do a regex and extract the required details and then parse it into a date -
(clojure.core/re-find #"\d{4}-\d{2}-\d{1,2}" "2013-02-20T17:24:33Z")
(parse (formatters :date) "2013-02-20")
However there should be a better way to the above by just using clj-time ?

A:

clj-time is just a wrapper around Joda Time, so you can call methods on DateTime object directly, and fortunately there is a method DateTime#toDateMidnight():
user=> (parse (formatters :date-time-no-ms) "2013-02-2T17:24:33Z")
#<DateTime 2013-02-02T17:24:33.000Z>
user=> (.toDateMidnight (parse (formatters :date-time-no-ms) "2013-02-2T17:24:33Z"))
#<DateMidnight 2013-02-02T00:00:00.000Z>

A:

(defn floor [dt f]
  (apply date-time
    (map #(%1 dt)
      (take-while (partial not= f) [year month day hour minute sec milli]))))

(floor (parse (formatters :date-time-no-ms) "2013-02-2T17:24:33Z") hour)


Q:

Log of a negative number

Why is the log of $x$ equal to the log of the absolute value of $x$ plus $i$ times $\pi$?
$$\log(x)=\log(|x|)+i\pi\text{, for }x < 0$$
Where does the $\pi$ come from? Is it from a logarithmic identity?
I know it sounds silly, but I was not able to find an answer from existing solutions: here, here, and here.

A:

$e^{πi} + 1 = 0$.
$e^{πi} = -1$.
$πi = \log(-1)$.
$\log(-1) + \log(|a|) = \log(-|a|)$.
$\log(-|a|) = \log(|a|)+iπ$.

A:

The standard explanation would go like this:

Any complex number $z$ can be written in polar form:
  $$z = |z|e^{i\theta}.$$
  So, if we want to define the complex logarithm, we do so as follows:
  $$\log (z) = \log(|z|e^{i\theta}) = \log(|z|) + \log(e^{i\theta}) = \log(|z|) + i\theta.$$
  In particular, the logarithm of a negative real number $x$ can then be calculated as
  $$\log (x) = \log(|x|e^{i\pi}) = \log(|x|) + \log(e^{i\pi}) = \log(|x|) + i\pi.$$

However, this explanation is not sufficient and the logarithm as presented is NOT a well-defined function. The angle $\theta$ is, well, an angle, and hence only defined up to multiples of $2\pi$:
$$|z|e^{i\theta} = |z|e^{i(\theta+k2\pi)}$$
for all $k \in \mathbb{Z}$. Therefore, the complex logarithm is only defined up to multiples of $2\pi i$ !
For example:
$$\log (x) = \log(|x|e^{i\frac{3}{2}\pi}) = \log(|x|) + \log(e^{i\frac{3}{2}\pi}) = \log(|x|) + i\frac{3}{2}\pi,$$
or maybe
$$\log (x) = \log(|x|e^{-i\frac{177}{2}\pi}) = \log(|x|) + \log(e^{-i\frac{177}{2}\pi}) = \log(|x|) - i\frac{177}{2}\pi.$$
But clearly $\pi \neq \frac{3}{2}\pi \neq -\frac{177}{2}\pi$. The point is: the complex logarithm is not a function, but what we call a multivalued function. To turn it into a proper function, we must restrict what $\theta$ is allowed to be, for example $\theta \in (-\pi,\pi]$. This is called the principal complex logarithm and is usually denoted by $\operatorname{Log}$ (capital L).
Technically, it doesn't matter to what range you restrict $\theta$, as long as the resulting logarithm is a proper function (not a multivalued function) and you are consistent in your restriction of $\theta$. For example, the following "proof" can be obtained if you're sloppy:
\begin{align}
e^{\pi i} = -1 & \implies (e^{\pi i})^2 = (-1)^2 & \text{ (square both sides)}\\
& \implies e^{2\pi i} = 1 & \text{ (calculate the squares)}\\
& \implies \log (e^{2\pi i}) = \log(1) & \text{ (take the logarithm)}\\
& \implies 2\pi i  = 0 & \text{ (calculate the logarithms)}
\end{align}
Clearly this is wrong!

A:

Slightly tongue in cheek but partially seriously I'm going to say "magic".
What I mean is before we talk about $\ln -k$ for a negative number we have to define what on earth it could possibly mean to have $e^{m} = -k$. There is no "natural" meaning to that and mathematicians, in one sense, must contrive a meaning for it. If our universe is the real numbers then this is .... impossible. If $b > 0$ then $b^x > 1$ and $e^x$ being negative is simply impossible.
But what if our universe is the complex numbers.  Then if $z = a + bi$ ($i^2 = -1$) then what could $e^{a+bi}$ possibly mean?  After all we can't just "multiply $e$ by itself the square root of negative one times".
Well, we know for real numbers, $e^{x + y} = e^xe^y$ and $\frac {de^x}{dx} = e^x$.  For this to still be true for complex numbers as well as for real numbers the only way to define $e^{z}$ where $z$ is a complex number, so that $e^{z+w} = e^ze^w$ and so that $\frac {d^z}{dz}$ the only possible way for that to stay true we have to define $e^{a+bi} = e^a(\cos b + i \sin b)$.
Okay.  That was ... a lot of hand waving.  But it works and if you study complex analysis it will be derived in great detail.  BUT this means....
$e^{i\pi} = e^{0 + i\pi} =  e^0(\cos \pi + i \sin \pi) = 1*(-1 + i*0) = -1$.
This is Euler's Formula,  one of the most famous mathematical formula in history.
Suddenly $e^z$ being a negative number is not impossible.  But if $e^z$ is negative then we need to have $e^{z} = e^{a + bi} = e^a(\cos b + i \sin b)$ so $\cos b + i \sin b$ is a negative number.  That means $b = \pi$ . So $z = i \pi$.
So this means $\ln -1*x = \ln -1 + \ln x = i\pi + \ln x$.
And that's where $\pi$ comes from.  When we define $e^{a+bi} = e^a(\cos b + i \sin b)$, exponents become thoroughly linked with trigonometric functions.  As such, $\pi$ is an essential part of the inverse.
For the real numbers only and logs of positive real numbers only, we don't have to worry as $e^x = e^{x + 0*i} = e^x(\cos 0 + i \sin 0) = e^x(1 + i*0) = e^x= k$ and $\ln k = x$ and $\pi$ is not relevant.


Q:

For $1\leq a\leq p-1$ and $5\leq p$, show that $\sum_{(a/p)=1}^{} a \equiv 0 \pmod{p}$

For $1\leq a\leq p-1$ and $5\leq p$, show that $$\sum_{(a/p)=1} a \equiv 0 \pmod{p}$$ where $(a/p)$ is the Legende symbol.

I know that there are as many quadratic residues as quadratic nonresidues, but I have no idea of how they are distributed.
Hints or complete solutions would be appreciated.

A:

Note that, quadratic residues are precisely members of the set, $\{1^2,2^2,\dots,\left(\frac{p-1}{2}\right)^2\}$, where I assume the rest of the arithmetic to be done modulo $p$.
Now,
$$
\sum_{k=1}^{\frac{p-1}{2}}k^2 \equiv \frac{\frac{p-1}{2}\cdot \frac{p+1}{2}p}{6} \pmod{p}.
$$
Since $p\neq 2,3$, the result follows immediately.


Q:

educate continuity of a function $f(x)=0$

How can I educate the continuity of $f(x)$, as $f(x)=0\ \forall x \in \mathbb{Q}$ and $f(x)=x\ \forall x \notin  \mathbb{Q}$? Because there is real number between every rational number.

A:

Here's a non-$\epsilon-\delta$ answer to complement the other answer.

Lemma: If $f$ is a continuous function on a topological space $X$, and $g$ is another continuous function such that $f(x)=g(x)$ for all $x$ in a dense subset $D$ of $X$, then $f=g$ on all of $X$.

First notice that $g(x)=x$ and $h(x)=0$ are both continuous functions on $\mathbb{R}$. Then notice that $\mathbb{Q}$ and $\mathbb{R}\setminus\mathbb{Q}$ are both dense in $\mathbb{R}$.
Now if $f$ were continuous, it would have to be equal to both $g$ and $h$, but $g$ and $h$ are obviously not equal... contradiction!

A:

Let us proceed by the $\epsilon$-$\delta$ definition of continuity.
It is to be shown that
$$\forall \epsilon >0 \exists \delta >0: |x|<\delta \implies |f(x)-f(0)|<\epsilon$$
Since $f(0) = 0$, this comes down to $|f(x)|<\epsilon$. Now take $\delta = \epsilon$.
Suppose that $x \in \Bbb R$ has $|x| < \delta$.
Then if $x \in \Bbb Q, |f(x)| = 0 < \epsilon$. If $x \notin \Bbb Q, |f(x)| = |x| < \delta = \epsilon$.
Thence $f$ is continuous at $0$. At other points a similar case distinction can be used to show that $f$ is discontinuous.


Q:

How to parse webpage for S&P500 P/E ratio

I am trying to import the current P/E ratio for S&P 500 from this webpage:
http://www.multpl.com
Where, below the chart,it says "current:", providing the current value (today the value is 24.11).
Is there a way to parse this webpage to automate importing it into R?

A:

If you need only PE ration you can use this
library(XML)
library(stringr)
url<-htmlParse("http://www.multpl.com/")
PE<-xpathSApply(url,"//div[@id='current']",xmlValue)
str<-str_replace_all(PE," ","")
str<-str_replace_all(str,"\n","")
begin<-str_locate(str,":")[[1]]
end<-str_locate(str,"\\+")[[1]]
PE_ratio<-as.numeric(str_sub(str,begin+1,end-1))
PE_ratio


Q:

My jQuery code is working, but is it very crappy from a programmer's point of view?

I cobbled together this jQuery function. It's purpose is to calculate the margins of all img elements inside div.article in order to balance the image's height with the baseline grid of the document, wich is 20 px. In order to match my baseline grid, every image height should be a multiple of 20. If that's not the case, e.g. one image's height is 154 px, the function adds a 6 px margin to the img, so that the balance with the baseline grid is restored.
The function works correctly, so my actual question is: Since I'm not a programmer, I'm wondering if my code is very crappy although it's working, and if so, how could the code be improved?
The jQuery code:
$('div.article img').each(function() {

    // define line height of CSS baseline grid:
    var line_height = 20;

    // capture the height of the img:
    var img_height = $(this).attr('height');

    // divide img height by line height and round up to get the next integer:
    var img_multiply = Math.ceil(img_height / line_height);

    // calculate the img margin needed to balance the height with the baseline grid:
    var img_margin = (img_multiply * line_height) - img_height;

    // if calculated margin < 5 px:
    if (img_margin < 5) {

        // then add another 20 px to avoid too small whitespace:
        img_margin = img_margin + 20;
    }

    // if img has caption:
    if ($($(this)).next().length) {

        // then apply margin to caption instead of img:
        $($(this)).next().attr('style', "margin-bottom: " + img_margin + "px;");
    } else {

        // apply margin to img:
        $(this).attr('style', "margin-bottom: " + img_margin + "px;");
    }
});

HTML code example, img with caption:

        Image Caption Goes Here

HTML code example, img without caption:

Edit: refined code based on Russ Cam's suggestions:
var line_height = 20;
var min_margin = 5;
$('div.article img').each(function() {
    var $this = $(this); // prefixed variable name with $ to remind it's a jQuery object
    var img_height = $this.height();
    var img_margin = ((Math.ceil(img_height / line_height)) * line_height) - img_height;
    img_margin = (img_margin < min_margin)? img_margin + line_height : img_margin;
    if ($this.next().length) {
        $this.next().css({'margin-bottom' : img_margin + 'px'});
    } else {
        $this.css({'margin-bottom' : img_margin + 'px'});
    }
});

A:

Some improvements I can recommend
1.cache $(this) inside the each() in a local variable
$('div.article img').each(function() {

    var $this = $(this); // prefixed variable name with $
                         // to remind it's a jQuery object

    // ....

   if ($this.next().length) {

   // ....

   }

});

2.instead of setting attr('style'), use the css() command
3.No need to do this
$($(this))

whilst it won't break jQuery, it's an unneccessary to pass a jQuery object into another jQuery object.
4.Use $(this).height()  or $(this).outerHeight() to get the height of the element in the browser
5.Not jQuery specific, but could use the ternary conditional operator to assign this value
// if calculated margin < 5 px:
if (img_margin < 5) {

    // then add another 20 px to avoid too small whitespace:
    img_margin = img_margin + 20;
}

becomes
// if calculated margin < 5 px then add another 20 px
// to avoid too small whitespace
img_margin = (img_margin < 5)? img_margin + 20 : img_margin;

6.As Alex has noted in the comments, I'd also remove the superfluous comments that merely repeat what the code tells you. Even if this is the debug script, in my opinion, they reduce readability and comments should serve only to provide detail that is not inherent from reading the code.

A:

The code is fine. You could make some minor improvements:

Don't use $(this) all over the place. Assign it to something early and use that so you don't re-extend the element over and over.
$(this).attr('style', "margin-bottom: " + img_margin + "px;"); can be rewritten as someEl.css('margin-bottom', img_margin + 'px');


Q:

How to do a each inside a each in jquery?

I have this json object :
{
"msg_id":"134",
"message":"Dick",
"comment":[
    {
    "com_id":"9",
    "comment":"test",
    "msg_id":"134",
    },
    {
    "com_id":"10",
    "comment":"testtt",
    "msg_id":"134",
    },
    {
    "com_id":"11",
    "comment":"testtttt",
    "msg_id":"134",
    }]
},
{
"msg_id":"134",
"message":"Dick",
},
{
"msg_id":"134",
"message":"Dick",
}

And I'm trying to iterate through it twice. Once for the main json object and then for the comment one.
I tried this:
$.each(data, function(index, obj){
    msg += template.replace( /{{message}}/ig  , obj.message )
                   .replace( /{{msg_id}}/ig   , obj.msg_id );

    $.each(obj.comment, function(key, val){
            msg += template.replace( /{{comment}}/ig , val.comment )
                   .replace( /{{com_id}}/ig , val.com_id )
                   .replace( /{{msg_id}}/ig , val.msg_id );
    });
});

If I do this I get a is undefined jquery.js line 2. Maybe I need to create another function for the second loop.

A:

Probably just a obj.comment being undefined (note that you don't have any comments in the last two messages), add this:
if(obj.comment) {
}

around the inner .each call, i.e. make it something like this:
$.each(messages, function(i, msg) {
    if(msg.comment) {
        $.each(msg.comment, function(i, comment) {
            $('#log').append($('<div>').text(comment.comment));
        });
    }
});

Working example:

http://jsfiddle.net/T8BX7/


Q:

How to prove $(1-\frac1{36})^{25}\lt\frac12$?

How to prove the inequality?
$(1-\frac1{36})^{25}\lt\frac12$

I'm in trouble.
Thank you very much for your help

A:

Note that $\left(1-\frac1{36}\right)^{36}\approx e^{-1}$, but more specifically $\left(1-\frac1{36}\right)^{36}\lt e^{-1}$ (because the function $\left(1-\frac1x\right)^x$ is increasing for $x\gt 1$ and its limit as $x\to\infty$ is $e^{-1}$).  Thus, $\left(1-\frac1{36}\right)^{25} =\left(\left(1-\frac1{36}\right)^{36}\right)^{\frac{25}{36}}\lt e^{-\frac{25}{36}}$.  But we have $e^{-\frac{25}{36}}\lt\frac12$ because $e^{\frac{25}{36}}\gt 2$ because $\frac{25}{36}\gt\ln 2$.  This last equation can easily be checked with a small table of constants.

A:

The series
$$(1-x)^{-25}=1+25 x+325 x^2 + 2925 x^3+20\,475 x^4+\ldots$$
has all coefficients positive. It follows that
$$\left(1-{1\over36}\right)^{-25}> 1+{25\over 36}+{325\over 36^2}+{2916\over 36^3}=1+{25\over36}+{325+81\over 36^2}={1301\over648}>2\ .$$

A:

We have that $\displaystyle\left(1-\frac{1}{36}\right)^{25}=\sum_{r=0}^{25} \binom{25}{r}(-1)^{r}\frac{1}{36^r}=1-\frac{25}{36}+\frac{25\cdot24}{2\cdot36^2}-\frac{25\cdot24\cdot23}{6\cdot36^3}+\frac{25\cdot24\cdot23\cdot22}{24\cdot36^4}-\cdots$.
Since the sum is alternating and has terms that are decreasing in absolute value, its value is less than
$\displaystyle1-\frac{25}{36}+\frac{25\cdot24}{2\cdot36^2}-\frac{25\cdot24\cdot23}{6\cdot36^3}+\frac{25\cdot24\cdot23\cdot22}{24\cdot36^4}=\frac{29}{54}-\frac{25\cdot23\cdot122}{36^4}<\frac{1}{2}$ since
$27(25)(23)(122)>27(24)(23)(120)=9(12^{2})(3)(2)(23)(10)=36^{2}(1380)>36^2(1296)=36^{4}$
$\implies\displaystyle\frac{25\cdot23\cdot122}{36^{4}}>\frac{1}{27}.$


Q:

How to create MongoID in android code?

I am developing app with mongoDB support in android.
I want to create MongoID from java code and send it to my server.
Here is my code
I want to create this json
{
"_id" : ObjectId("59b7bcdf92e706382b00009f"),
"user_id" : "6bb82a99-bccd-4868-a799-55e7d28f969c",
"is_active" : false,
"_slugs" : [
    "aaa"
],
"facility_name" : "aaa",
"industry_id" : 1,
"old_industry_id" : 1,
"established_date" : "1994-06-01",
"summary" : "this is test",
"facility_website" : "www.xxx.com",
"contact" : {
    "_id" : ObjectId("4637gdff92jhsgd378364y"),
    "info_type" : "PROFILE_INFO",
    "name" : "xxxxxxxxxx",
    "mobileNumber" : "xxxxxxxxx",
    "email" : "xxxxxxx@gmail.com",
    "shown_on_profile" : true
}}

But I am getting this Json from my java code.
{
"_id" : ObjectId("59b7bcdf92e706382b00009f"),
"user_id" : "6bb82a99-bccd-4868-a799-55e7d28f969c",
"is_active" : false,
"_slugs" : [
    "aaa"
],
"facility_name" : "aaa",
"industry_id" : 1,
"old_industry_id" : 1,
"established_date" : "1994-06-01",
"summary" : "this is test",
"facility_website" : "www.xxx.com",
"contact" : {
    "_id" : "{}",
    "info_type" : "PROFILE_INFO",
    "name" : "xxxxxxxxxx",
    "mobileNumber" : "xxxxxxxxx",
    "email" : "xxxxxxx@gmail.com",
    "shown_on_profile" : true
}}

Problem is in "contact" object
Here is my java code
String _id = new JsonObject().toString(); // this is Gson.JsonObject() object
JSONObject contact = new JSONObject();
contact.put("_id", _id);
contact.put("info_type", "PROFILE_INFO");
contact.put("name", "User-1");
contact.put("mobileNumber", "xxxxxxxxxx");
contact.put("email", "xxxxx@gmail.com");
contact.put("shown_on_profile", true);

A:

As said by @fandro i have solved my issue.
Server gives me mongoDB data like this
{"_id":{"$id":"59b7bcdf92e706382b00009f"}}

I can access this data using this code,
Here is my android Code
ID = jsonData.getJSONObject("_id).getString("$id");

For generating new ID i have created empty JSONObject in android and passed to my server.
_id = new JSONObject().put("$id", "");

On my server, i check id and if it is empty then i generate new MongoID form this code,
<?php
$_id = $_POST['_id'];
if ($_id['$id'] == "")
 $_id = new MongoID();
?>


Q:

Merge two columns in R while replacing when value is not present in other column

i want to merge two columns of my data set, The nature of these two columns are either/or, i.e if a value is present in one column it wont be present in other column.
i tried these
temp<-list(a=1:3,b=10:14)
paste(temp$a,temp$b)

output
"1 10" "2 11" "3 12" "1 13" "2 14"

and this
 temp<-list(a=1:3,b=10:14,c=20:25)
 temp<-within(temp,a <- paste(a, b, sep=''))

output
temp$a
[1] "110" "211" "312" "113" "214"

but what i am looking for is to replace the values when they are not present . for example temp$a only have 1:3 and temp$b have 10:14 , i.e two extra values - so i want my answer to be
1_10 2_11 3_12 _13 _14

EDIT -please look that i do not want column c to be concatenated with a and $b

A:

Using stri_list2matrix, we can fill the list elements that have shorter length with '' and use paste.
library(stringi)
do.call(paste, c(as.data.frame(stri_list2matrix(temp, fill='')), sep='_'))
#[1] "1_10" "2_11" "3_12" "_13"  "_14"

stri_list2matrix(temp, fill='') converts the list to matrix after filling the list elements that are shorter in length with ''.  Convert it to data.frame (as.data.frame)  and use do.call(paste to paste the elements in each row separated  by _ (sep='_').
Update
Based on the edited 'temp', if you are interested only in the first two elements of 'temp'
 do.call(paste, c(as.data.frame(stri_list2matrix(temp[1:2], fill='')),
         sep='_'))
 #[1] "1_10" "2_11" "3_12" "_13"  "_14"

You can also subset by the names ie. temp[c('a', 'b')]


Q:

ComboBox в гриде

Сделал табличку, данные подгружаются, но все никак не могу понять, как вставить комбобокс в одну из колонок, в моем коде это последняя:
Кто поможет, награжу хорошим кол-вом очков своей репутации :)
Ext.onReady(function(){
  Ext.define('User', {
    extend: 'Ext.data.Model',
    fields: [
      {name: 'id', type: 'int'},
      {name: 'day', type: 'string'},
      {name: 'time', type: 'string'},
      {name: 'what', type: 'string'},
      {name: 'combo', type: 'string'}
    ]
  });

  var store = Ext.create('Ext.data.Store', {
    model: 'User',
    proxy: {
      type: 'ajax',
      url: 't.php',
      reader: {
        type: 'json'
      }
    }
  });

  var grid = Ext.create('Ext.grid.Panel', {
    store: store,
    columns: [
      {
        text: "День", flex: 1, dataIndex: 'day', sortable: true
      },
      {
        text: "Трапеза", width: 115, dataIndex: 'time', sortable: true
      },
      {
        text: "sourse", width: 100, dataIndex: 'what', sortable: true
      },
      {
        text: "Combo тут! как его сделать???", width: 100, dataIndex: '', sortable: true
      }
    ],
    height:700,

    renderTo: 'grid-example'
  });

  store.load();
});

A:

Все просто становится, когда посмотрите на документацию.
Надо в GridPanel добавить плагин, который будет позволять редактирование.

plugins: [
    Ext.create('Ext.grid.plugin.CellEditing', {
        ptype: 'cellediting',
        clicksToEdit: 1,
        pluginId: 'myId'
    })
 ]

Дальше вам необходимо определить ячейки для редактирования:

editor: {
    xtype: 'combobox',
    /* все настройки для комбобокса.
       Но это уже на ваше исследование потому что вопрос
       на другую тему.
     */
 }

Если следовать примеру:

columns: [
    {
        text: "Трапеза",
        /* ... ... ...*/
        editor: {
            xtype: 'combobox',
            /* все настройки для комбобокса.
               Но это уже на ваше исследование потому что вопрос
               на другую тему.
              */
         }
    }
]

Более подробно про комбобокс тут.
Большой совет научиться пользоваться именно этим ресурсом. 95% информации я черпаю именно от туда.
PS
Очки можете приберечь. Мне они ни к чему:)


Q:

inbuilt save button text

I want to change here title of button can i change   by default it is coming 'save' can it be changed
UIBarButtonItem *dowButton = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemSave
                                                                           target:self action:@selector(download)];

strong text

A:

Create an own UIBarButtonItem instead of using the UIBarButtonSystemItemSave:
UIBarButtonItem *dowButton = [[[UIBarButtonItem alloc] initWithTitle:@"Download" style:UIBarButtonItemStylePlain target:self action:@selector(download)] autorelease];

This will helps you :-)


Q:

Compensating for differences in Android devices? (video game programming)

Different Android devices have different screen sizes and screen densities.  When programming a video game, what is a good way to compensate for the differences?

A:

I recommend checking out all the answers here. This question is up for bounty, so a lot of people should be providing helpful answers.


Q:

Hard Drive health check

In a previous thread the answer # smartctl -a /dev/sda looks good. The problem by my side is the highly verbose output. Is possible to obtain something more human understadable, something like "hard drive good at 80%" or "grepping" the essentials from smarctl -a?

A:

That's what smartctl -H does: it gives you a pass (no failure predicted) or fail (failure predicted in next 24h). SMART unfortunately doesn't give any way to ask a drive its expected remaining lifespan, other than that. Other than SSDs with their limited write durability, it probably isn't even possible to do in general.
You can get less output from smartctl with some of the other flags. For example -A will give only the attribute table. -l selftest will give only the selftest logs, etc.


Q:

How can I find values that make a matrix Linearly Dependent?

Let $$A=\left(\begin{smallmatrix}2&-1&0&1\\0&0&a&3\\0&0&0&b\end{smallmatrix}\right)$$
For what choices (if any) of real numbers a and b are the
rows of A linearly dependent? Justify your response.
I figured out that the free variables in this matrix are x2 and x4. However, I got the matrixes [-1/2 , -1 , -3/a , 1] and [-2, 1 , 0 , 0 ]. I'm not sure what my next step would be.

A:

To make them linearly dependent, you must find nontrivial $\lambda_1, \lambda_2, \lambda_3$ such that
$$\lambda_1 \pmatrix{2\\-1\\0\\1} + \lambda_2 \pmatrix{0\\0\\a\\3} + \lambda_3 \pmatrix{0\\0\\0\\b} = \pmatrix{0\\0\\0\\0}$$
The first two equations enforce $\lambda_1 = 0$ and the third equation enforces $\lambda_2 a = 0$, the fourth $3\lambda_2 + b\lambda_3 = 0$. To get a solution with $\lambda_2 \ne 0$ or $\lambda_3 \ne 0$ there are two possibilities

$b\ne 0$ then $\lambda_2 = -\lambda_3$ but this implies for nonzero $\lambda_3$. that $a = 0$:
$a=0, b\ne 0$
$b=0$ then we can chose $\lambda_2 = 0$ and $\lambda_3$ as well as $a$ arbitrary

Summing up: $a$ is arbitrary. If $a\ne0$ we must chose $b=0$, else $b$ is arbitrary as well.


Q:

Problem with 2 static process which creates 2 dynamic process with open mpi

The program must create 2 static processes that we can call m0 and m1.
Each master process (m0 and m1) must create 2 child processes dynamically with mpi_spawn. The m0 master must make a bcast to all processes with a single call to bcast.
I have no idea how I could solve it.
The code below would be valid if for example each master makes a bcast to their own children, but cannot make them to the children of the other master.
I guess I should create an intracom but I don't know how to do it
#include "mpi.h"
#include "stdio.h"
#define PROCESOS 2

int main(int argc, char *argv[])
{

    int rank, size, n = 1234, size_intercom, size_remote;
    MPI_Comm intercom, iguales;
    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_size(MPI_COMM_WORLD, &size);

    MPI_Comm_get_parent(&intercom); // Para conocer si tiene padre o no

    if (intercom == MPI_COMM_NULL)
    {
        MPI_Comm_spawn(argv[0], MPI_ARGV_NULL, PROCESOS, MPI_INFO_NULL, 0, MPI_COMM_SELF, &intercom, MPI_ERRCODES_IGNORE);

        printf("soy maestro %d\n", rank);
        MPI_Comm_size(intercom, &size_intercom);
        MPI_Comm_remote_size(MPI_COMM_WORLD, &size_remote);
        printf("procesos en intercom %d, en remoto %d \n", size_intercom, size_remote);

        MPI_Bcast(&n, 1, MPI_INT, MPI_ROOT, intercom);
    }
    else
    {

        // MPI_Intercomm_merge(intercom, 1, &iguales);
        MPI_Bcast(&n, 1, MPI_INT, 0, intercom);
        printf("soy hijo %d, recibo %d\n", rank, n);
    }

    MPI_Finalize();
    return 0;
}

VERSION 2.0:
I wonder if this can be an aproach, but i can't get the expected result:
 if (intercom == MPI_COMM_NULL)
    {
        if (rank == 0)
        {
            n = 1234;
        }
        MPI_Comm_spawn(argv[0], MPI_ARGV_NULL, PROCESOS, MPI_INFO_NULL, 0, MPI_COMM_SELF, &intercom, MPI_ERRCODES_IGNORE);
        MPI_Intercomm_merge(intercom, 0, &iguales);
        MPI_Intercomm_create(MPI_COMM_SELF, 0, iguales, 1, 1, &todos);
        MPI_Bcast(&n, 1, MPI_INT, MPI_ROOT, todos);
        printf("I'M MASTER rank: %d, i get: %d\n", rank, n);
    }
    else
    {

        MPI_Intercomm_merge(intercom, 1, &iguales);
        MPI_Intercomm_create(MPI_COMM_WORLD, 0, iguales, 0, 1, &todos);

        MPI_Bcast(&n, 1, MPI_INT, 0, todos);
        printf("I'm a child %d, i get: %d\n", rank, n);
    }

With the previous modification i get the same result that if i do the bcast through de intercom comnunicator intercom. I don't understand why:
I'M MASTER rank: 1, i get: 0
I'm a child 0, i get: 0
I'm a child 1, i get: 0
I'M MASTER rank: 0, i get: 1234
I'm a child 1, i get: 1234
I'm a child 0, i get: 1234

A:

If you cannot revamp your app so the two masters spawn the four slaves together, or you cannot use a two steps broadcast, here is how you can achieve the desired outcome.
#include "mpi.h"
#include "stdio.h"
#define PROCESSES 2

int main(int argc, char *argv[])
{

    int rank, size, n = -1, remote_leader = -1;
    int master;
    MPI_Comm intercomm, mergedcomm, universe_inter, universe;
    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_size(MPI_COMM_WORLD, &size);

    MPI_Comm_get_parent(&intercomm);

    if (MPI_COMM_NULL == intercomm)
    {
        printf("I am master %d\n", rank);
        MPI_Comm_spawn(argv[0], MPI_ARGV_NULL, PROCESSES, MPI_INFO_NULL, 0, MPI_COMM_SELF, &intercomm, MPI_ERRCODES_IGNORE);
        MPI_Bcast(&rank, 1, MPI_INT, MPI_ROOT, intercomm);
        master = rank;
        remote_leader = master^1;
        if (0 == rank) {
            n = 1234;
        }
    }
    else
    {
        MPI_Bcast(&master, 1, MPI_INT, 0, intercomm);
        printf("I am slave %d from master %d\n", rank, master);
    }

    /* make sure the master rank has rank 0 in the merged communicator */
    MPI_Intercomm_merge(intercomm, (NULL==MPI_COMM_NULL)?0:1, &mergedcomm);
    MPI_Intercomm_create(mergedcomm, 0, MPI_COMM_WORLD, remote_leader, 0, &universe_inter);
    /* make sure master 0 has rank 0 in the universe */
    MPI_Intercomm_merge(universe_inter, master, &universe);
    MPI_Comm_free(&mergedcomm);

    MPI_Bcast(&n, 1, MPI_INT, 0, universe);
    printf ("n = %d\n", n);

    MPI_Comm_free(&universe);
    MPI_Comm_disconnect(&intercomm);
    MPI_Finalize();
    return 0;
}


Q:

Is possible to use finish() in to return in previous activities like C>B>A?

Technically I have a MainActivity "A" then then I'll go to next activity which is activity "B" then there is the other activity which is Activity "C"
But when I use finish, the activity B and C returns to each other instead backing to the main activity

A:

When you route from Activity A to B then c, and you pressing back from C to B and A. You don't need to use finish() anywhere. Because android maintain stack for back button. It automatically push all activities and pop activities when back.
Refer this : https://developer.android.com/guide/components/tasks-and-back-stack.html


Q:

strftime in sqlite convert to postgres

I came across a function in sqlite that I need to convert to postgres syntax. It's date(date, '-'||strftime('%w',date)||' days').
Can anyone help me convert this sqlite segment to postgres?

A:

This SQLite:
date(date, '-' || strftime('%w', date) || ' days')

Is, AFAIK, subtracting the day-in-the-week number days (i.e. 0 for Sunday, 1 for Monday, ...) from date and then converting the result back to a date; see the date function reference for details.
I think the equivalent for PostgreSQL would be:
d - extract(dow from d)::int

where d is your date; subtracting an integer from a date subtracts that number of days. If d is a timestamp, then you might need to add some casting. There is date_trunc('week', 'd') as well but that starts numbering the days from Monday so you'd be off by one with that.

Here's a quick breakdown of the SQLite with the date variable replaced by d to avoid confusion with the date() function:
date(d, '-' || strftime('%w', d) || ' days')

First of all, || is the standard SQL string concatenation operator. The strftime function is a general purpose date and time formatter that comes from POSIX; the %w format specifier means "day of the week as a number with Sunday being day zero"; so the strftime call gives you 0 for Sunday, 1 for Monday, and so on up to 6 for Saturday. If d is a Tuesday, then the strftime call will yield 2 and the whole thing ends up as:
date(d, '-2 days')

The modifiers for the SQLite date function have various forms but '-2 days' means just what you'd think: subtract two days from d. The overall result is that you get d truncated to the week (where Sunday is considered to be the first day of the week).
On the PostgreSQL side:
d - extract(dow from d)::int

we can start with extract; extract is used to extract specific parts of a date or time and dow means "day of the week as a number with Sunday being day zero". Sound familiar? Then the ::int casts the DOW number to an integer and is needed because the DOW actually comes out as a double precision value and there is no operator defined for subtracting a double from a date in PostgreSQL; the cast can also be written in the standard form as cast(x as int). When you subtract an integer from a date in PostgreSQL, you subtract that many days; you can be more explicit by saying things like - interval '3 days' but that would just add more noise in this case so I opted for simplicity. If it is Tuesday, then our PostgreSQL version looks like:
d - 2

and that's the same as:
d - interval '2 days'

And after the subtraction we'd be back on Sunday. There's also date_trunc in PostgreSQL but that would truncate to Monday not Sunday.


Q:

How get all numerical values from a list except numbers relating to certain Strings

I want to get all the numbers from my String except for the numbers that are related to the String pattern 'SPN'
 def layoutStr = '1 ABC, 2 DEF, 3 SPN, 4 GHI'

 def splitted = layoutStr.split(',')
   *.trim()                        // remove white space from all the entries (note *)
   *.dropWhile { it ==~ /[^0-9 ]/ } // drop until you hit a char that isn't a letter or a space in the list
   .findAll { it[0] != 'SPN' }     // if a group starts with SPN, drop it

assert splitted == [1, 2, 4]

This doesn't seem to do what I expect it to do, I think I am missing the re-collecting step

A:

You can use findResults which only collects elements that aren't null, so you can use it to filter AND transform at the same time:
def layoutStr = '1 ABC, 2 DEF, 3 SPN, 4 GHI'

def splitted = layoutStr.split(',')
    *.trim()        // remove white space from all the entries (note *)
    *.split(/\s+/)  // Split all the entries on whitespace
    .findResults { it[1] == 'SPN' ? null : it[0] as Integer }

assert splitted == [1, 2, 4]


Q:

php array merge with value of parent array

I need to merge an array with value of parent array.
$testArr=unserialize('a:6:{s:5:"queue";a:2:{i:6;s:1:"5";i:5;s:1:"2";}s:3:"sum";a:2:{i:6;s:3:"765";i:5;s:3:"2.1";}s:7:"sumAccD";a:2:{i:6;s:3:"543";i:5;s:3:"3.1";}s:7:"sumAccC";a:2:{i:6;s:2:"54";i:5;s:3:"3.3";}s:7:"comment";a:2:{i:6;s:12:"test comment";i:5;s:6:"111222";}s:3:"yt0";s:0:"";}');

$ret = array();
foreach ($testArr as $pkey => $pval) {
if (is_array($pval)) {
    foreach ($pval as $pvkey => $pvval) {
        $ret[$pvkey] = array($pkey => $pvval);
    }
}
}
echo '<pre>', print_r($ret), '</pre>';

In this case it prints out
Array
(
[6] => Array
    (
        [comment] => test comment
    )

[5] => Array
    (
        [comment] => 111222
    )

)
1

Unfortunally it print out only comment. I need to add other rows: queue,sum,sumAccD,sumAccC. Array must look like this:
Array
(
[6] => Array
    (
        [queue] => 5
        [sum] => ''
        ....
        [comment] => test comment
    )

[5] => Array
    (
        [queue] => 2
        [sum] => 2.1
        ....
        [comment] => 111222
    )

)
1

Please help merge them.
Thanks.

A:

Problem solved by replacing
$ret[$pvkey] = array($pkey => $pvval);

with
$ret[$pvkey][$pkey] = $pvval;


Q:

Button on ng-mouseover & ng-mouseleave won't get shown as expected - AngularJS

I've a problem that I wasn't able to solve for a while now, even looking to other Q/A on SO.
I would like to switch from a button to another one with an ng-show.

When ng-mouseovertriggers, I would like to hide the current button, button-db, and show a second one, button-shout
When ng-mouseleave triggers, I would like to do the opposite, hiding button-shout and showing button-db.

I'm already able to make this work with the following code:
HTML:

          200

JS:
$scope.hoverEdit = true;

$scope.hoverIn = function(){
    $scope.hoverEdit = false;
};

$scope.hoverOut = function(){
    $scope.hoverEdit = true;
};

With the code above I'm able to get the following starter situation:

button-db on the left and button-action on the right

And I would like that, when ng-mouseover triggers, button-db (The Purple Rectangle) gets hidden while button-shout (~Green Rectangle with another image) gets shown and vice-versa (this is actually working), like in the following image:

What I'm trying to achieve -> button-shout on the left at button-db's place

But, instead, I get the following result:

What I get instead, when I go over button-db I get this uknown blank div instead of button-shout

button-shout doesn't get shown and it is not present in the DOM and it does not have height and width even if I managed to build it like I did with the other buttons.
I'm using the following CSS classes:
half gives dimensions to the buttons and sets their position
.pod .footer .half {
  display: table-cell;
  padding-top: 1px;
  padding-left: 8px;
  padding-right: 8px;
  vertical-align: middle;
  height: 45px;
}

button-db has both :before and :after with a little images and shout-value to handle the int number between them
.pod .footer .button-db {
  background-color: #6ab5ac;
  text-align: center;
  color: #fff;
  background-color: #6455a0;
}
.pod .footer .button-db .shout-value {
  margin-top: 0px;
  padding: 2px;
  color: #fff;
  display: inline-block;
  position: relative;
  font-size: 18px;
  font-weight: 600;
  line-height: 22px;
}
.pod .footer .button-db .shout-value:before {
  content: "";
  display: inline-block;
  background-image: url("./assets/css/img/shout-megaphone-white.svg");
  background-size: contain;
  background-position: center;
  background-repeat: no-repeat;
  width: 30px;
  height: 23px;
  position: absolute;
  left: -17px;
  top: 0px;
}
.pod .footer .button-db .shout-value:after {
  content: "";
  background-image: url("./assets/css/img/shout-db-white.svg");
  background-size: contain;
  background-position: right center;
  background-repeat: no-repeat;
  width: 28px;
  height: 27px;
  position: absolute;
  right: -19px;
  top: -1px;
  vertical-align: super;
  font-size: 12px;
  display: inline-block;
  padding: 0;
  padding-top: 0px;
  font-weight: 500;
}
.pod .footer .button-db .shout-value .db {
  vertical-align: super;
  font-size: 10px;
  display: inline-block;
  padding: 0;
}
.pod .footer .button-db .db-value {
  margin-top: 0px;
  padding: 2px;
  color: #fff;
  display: inline-block;
  position: relative;
  font-size: 18px;
  font-weight: 600;
  line-height: 22px;
}
.pod .footer .button-db .db-value:after {
  content: "dB";
  background-image: none;
  width: 28px;
  height: 23px;
  position: absolute;
  right: -19px;
  top: 0px;
  vertical-align: super;
  font-size: 12px;
  display: inline-block;
  padding: 0;
  padding-top: 0px;
  font-weight: 500;
}

button-shout button to get shown when ng-mouseover triggers; It does not need any :before and :after, it only has 1 image and no values
.pod .footer .button-shout {
  background-color: #6AB6AC;
  text-align: center;
  font-size: 18px;
  font-weight: 500;
  color: #fff;
  line-height: 30px;
}

button-action cart button, button-shout would look pretty much like it but for the color and the image
.pod .footer .button-action {
  background-color: #ffae00;
  text-align: center;
  font-size: 18px;
  font-weight: 500;
  color: #fff;
  line-height: 30px;
}

The functionalities I implemented using both ng-mouseover and ng-mouseleave work perfectly as I want. I don't get why button-shout has no dimensions and does not get shown at button-db's place when doing ng-mouseover.
I already tried using ng-if, adding and removing classes, using z-index and display: none & display: block but I always get this problem.
I noticed that button-shout inherits nothing except for half's placement.
Here is a little Plunker I put up with only two buttons to let you understand how it should work. It works on the Plunker but not in my application.
When mouseover triggers, one button hides and the other one is shown and when mouseleave triggers, the old one is shown back.
1) Have you any idea on why it doesn't get shown properly?
2) How can I fix this?
I hope I've been as much clear as possible, Thanks in advance.

A:

To be honest i'm not really sure of what the problem is so i'll post here a snippet that try to reproduce what you currently have. Feel free to tell us if this snippet reproduces your problem and for answeres to use it as a base for an answer.
Note : in your HTML i removed the ng-mouseleave on 1st element and ng-mouseenter on 2nd because they were conflicting each other and throw duplicate events.

angular.module("app", []).controller("ctrl", ['$scope', function($scope){
    $scope.hoverEdit = true;

$scope.hoverIn = function(){
    console.log("HOVER IN");
    $scope.hoverEdit = false;
};

$scope.hoverOut = function(){
    $scope.hoverEdit = true;
      console.log("HOVER OUT");
};
}]);
.pod .footer .half {
  display: table-cell;
  padding-top: 1px;
  padding-left: 8px;
  padding-right: 8px;
  vertical-align: middle;
  height: 45px;
}

.pod .footer .button-db {
  background-color: #6ab5ac;
  text-align: center;
  color: #fff;
  background-color: #6455a0;
}
.pod .footer .button-db .shout-value {
  margin-top: 0px;
  padding: 2px;
  color: #fff;
  display: inline-block;
  position: relative;
  font-size: 18px;
  font-weight: 600;
  line-height: 22px;
}
.pod .footer .button-db .shout-value:before {
  content: "";
  display: inline-block;
  background-color: black;/*url("./assets/css/img/shout-megaphone-white.svg");*/
  background-size: contain;
  background-position: center;
  background-repeat: no-repeat;
  width: 30px;
  height: 23px;
  position: absolute;
  left: -17px;
  top: 0px;
}
.pod .footer .button-db .shout-value:after {
  content: "";
  background-image: white;/*url("./assets/css/img/shout-db-white.svg");*/
  background-size: contain;
  background-position: right center;
  background-repeat: no-repeat;
  width: 28px;
  height: 27px;
  position: absolute;
  right: -19px;
  top: -1px;
  vertical-align: super;
  font-size: 12px;
  display: inline-block;
  padding: 0;
  padding-top: 0px;
  font-weight: 500;
}
.pod .footer .button-db .shout-value .db {
  vertical-align: super;
  font-size: 10px;
  display: inline-block;
  padding: 0;
}
.pod .footer .button-db .db-value {
  margin-top: 0px;
  padding: 2px;
  color: #fff;
  display: inline-block;
  position: relative;
  font-size: 18px;
  font-weight: 600;
  line-height: 22px;
}
.pod .footer .button-db .db-value:after {
  content: "dB";
  background-image: none;
  width: 28px;
  height: 23px;
  position: absolute;
  right: -19px;
  top: 0px;
  vertical-align: super;
  font-size: 12px;
  display: inline-block;
  padding: 0;
  padding-top: 0px;
  font-weight: 500;
}

.pod .footer .button-shout {
  background-color: #6AB6AC;
  text-align: center;
  font-size: 18px;
  font-weight: 500;
  color: #fff;
  line-height: 30px;
}

.pod .footer .button-action {
  background-color: #ffae00;
  text-align: center;
  font-size: 18px;
  font-weight: 500;
  color: #fff;
  line-height: 30px;
}

          <button class="shout-value">100</button>

         <button class="shout-value">200</button>

     <button class="shout-value">300</button>

Of course since i don't have the images, i changed them to black and white background. What i can see is that i have a black crap that seems to not be in the right place, however this doesn't seems to be what your problem is.


Q:

How to keep the Shell configurable with PRISM 4.1 & Unity?

I am writing a WPF application using PRISM 4.1 & Unity. The application will have every UI component configurable, including the Shell itself!
E.g. I have an interface called IShell. Consumers of the app can have their own implementation of IShell if they are not satisfied with my default implementation which has Regions and Views defined in some fixed way.
Now from my Bootstrapper class (which inherits UnityBootstrapper), I want to know the type registered for IShell with the Unity container. The overriden CreateShell will return configured type of the IShell.
My App.config looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
  </configSections>
  <unity>
    <container>
        <register type="Interfaces.IShell, Interfaces" mapTo="PrismApp.Shell, PrismApp"/>
    </container>
  </unity>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
</configuration>

In Bootstrapper class, I have following code:
public class PrismAppBootstrapper : UnityBootstrapper
{
    protected override DependencyObject CreateShell()
    {
        var obj =  ServiceLocator.Current.GetInstance<IShell>() as DependencyObject;
        return obj;
    }
}

In the WPF application's App.xaml.cs, I am instantiating PrismAppBootstrapper:
 PrismAppBootstrapper prismAppBootstrapper = new PrismAppBootstrapper();
        prismAppBootstrapper.Run();

However, when I run this code, I get the Exception : "InvalidOperationException - The current type, Interfaces.IShell, is an interface and cannot be constructed. Are you missing a type mapping?"
How to solve this problem?
Why does application fail to know the registered type of IShell which is there in app.config file?

A:

Keeping the Shell configurable is possible with the Unity container.
The problem was that my Unity Container was not properly configured to read mapping/registrations from the app.config file. So it failed to know the mapping of IShell at run time.
I had to override other methods along with CreateShell in my PrismAppBootstrapper class.
E.g.
public class PrismAppBootstrapper : UnityBootstrapper
    {
        protected override IModuleCatalog CreateModuleCatalog()
        {
            ModuleCatalog catalog = new ConfigurationModuleCatalog();
            return catalog;
        }

        protected override void ConfigureContainer()
        {
            base.ConfigureContainer();
            UnityConfigurationSection configurationSection =
                (UnityConfigurationSection) ConfigurationManager.GetSection("unity");
            if (configurationSection != null)
            {
                configurationSection.Configure(this.Container);
            }
        }

        protected override DependencyObject CreateShell()
        {
            IShell shell = this.Container.TryResolve<IShell>();
            return shell as Window;
        }

        protected override void InitializeShell()
        {
            base.InitializeShell();

            Application.Current.MainWindow = (Window)this.Shell;
            Application.Current.MainWindow.Show();
        }
    }


Q:

AngularJS event listener inside directive link function firing on each route change

I have a route that has a custom directive. In it's link function, I listen for an event on the window object which calls a method on scope.
The problem is that if that each time the route that has this directive is redirected to, it will run the link function resulting in multiple event listeners being added to the window event.
How can I avoid this? I tried using the compile function, but it doesn't have access to scope so I can't call scope.myMethod() inside of it.
Thanks.

A:

I will suggest that you use the $destroy event (see $destroy in scope documentation) on your directive's scope and do the necessary cleanup there. Something like that :
angular.directive('MyDirective', ['$rootScope', function($rootScope) {
  return {
    restrict: 'EAC',
    link: function(scope, element, attrs) {
      .... //Code of your directive

      scope.$on('$destroy', function() {
        console.log("destroy");
       //clean up - removeListeners
      });
    }
  };
}]);

Should do the trick.


Q:

angular.module called from separate files, does not find Controller

I am trying to modularize my code and moved controller in a separate file that uses same module. But, it does not load, I made sure the load order is correct.
// app.js
angular.module("app", []);

// LoginCtrl.js
angular.module("app", []).controller("LoginCtrl", function()
{
  //doSomeThing
});

If I do var app = angular.module in first file and use the same variable in other files, it works.
// app.js
var app = angular.module("app", []);

// LoginCtrl.js
app.controller("LoginCtrl", function()
{
  //doSomeThing
});

If I move all code in one file and use angular.module separately for each component, it works.
// app.js
angular.module("app", []);

angular.module("app", []).controller("LoginCtrl", function()
{
  //doSomeThing
});

Am I missing something?

A:

To create a module in AngularJS:
angular.module('app', []);
To get a module in AngularJS:
angular.module('app');
You use the same signature in your code to create and get a module, you mustn't add the injection array as the second argument of the module function when getting a module in another file.


Q:

listing prime numbers from user input in java

in java what i am trying to do is have a user input a value greater than 0 and with that number they input list that amount of prime numbers starting from 2
so if the user inputs "3" the program will display 2,3,5
if the user inputs "5" the program will display 2,3,5,7,11
and so on
the problem is I cant figure out how to have the user input do this correctly, i either end up with the numbers repeating however many times or the list ending at the user input, any help would be apreciated
import java.util.Scanner;

public class Primes
{

    public static void main(String[] args)
    {
        Scanner console = new Scanner(System.in);

        int n = console.nextInt();

        if(n<=0)
        {
            return;
        }
        else
        {
            for(int i=2; i < 100; i++)
            {
                boolean isPrime = true;

                for(int j=2; j < i; j++)
                {
                    if(i%j == 0)
                    {
                        isPrime = false;
                        break;
                    }
                }
                if(isPrime)
                {
                    System.out.println(i);
                }
            }
        }

    }

}

A:

Keep a count of how many primes have been found by changing your for loop to stop when you've found enough primes and performing primesFound++ when a prime is found:

    for (int i = 2, primesFound = 0; primesFound < n; i++)
    {
        boolean isPrime = true;

        for (int j = 2; j < i; j++)
        {
            if (i % j == 0)
            {
                isPrime = false;
                break;
            }
       }
       if (isPrime)
       {
           System.out.println(i);
           primesFound++;
       }
    }