text:
Q: KSQL join returns null fields I am trying to join the following stream
 Field     | Type
---------------------------------------
 ROWTIME   | BIGINT           (system)
 ROWKEY    | VARCHAR(STRING)  (system)
 USER_ID   | VARCHAR(STRING)
 FIRSTNAME | VARCHAR(STRING)
---------------------------------------

with the following table:
 Field     | Type
---------------------------------------
 ROWTIME   | BIGINT           (system)
 ROWKEY    | VARCHAR(STRING)  (system)
 USER_ID   | VARCHAR(STRING)
 USERNAME  | VARCHAR(STRING)
---------------------------------------

using
SELECT M.USER_ID, \
       C.USERNAME \
FROM MY_STREAM M \
LEFT JOIN MY_TABLE C \
ON (M.USER_ID = C.USER_ID);

but USERNAME contains only null values.
1 | null
2 | null
3 | null
4 | null
5 | null
6 | null
7 | null
8 | null

I am sure that there are common user_ids and that no username is null in the table. Am I missing anything here?

A: See my answer to this post, in which I demonstrate how to troubleshoot joins like this.
In short, you need to key the messages in your table's topic on the column on which you join.
If you're going to join on USER_ID then :
SELECT ROWKEY, USER_ID FROM MY_TABLE

should return
1 | 1
2 | 2
3 | 3

etc


text:
Q: Difference between algorithm time - Classifying a table I need to make a program that classify a vector using 2 different algorithms: Quick (which is O(NlogN)) and Bubble (which is O(N²)). Furthermore, I need to calculate the "delay time" of each algorithm. Since the user can select the method, my program have the following code:
 switch(answer[1]){
                case 'L':
                 start_t = clock()/ (double)CLOCKS_PER_SEC;
                 Log(Tab, NReg-1, answer[0]);
                 end_t = clock()/ (double)CLOCKS_PER_SEC;
                 break;
                case 'Q':
                     start_t = clock()/ (double)CLOCKS_PER_SEC;
                 Quad(Tab, NReg-1, answer[0]);
                 end_t = clock()/ (double)CLOCKS_PER_SEC;
                 break;
                 }

    total_t = (double)(end_t - start_t) ;
   printf("Time: %f\n", total_t  );

Log is the function that call my quick sort algorithm and Quad, Bubble Sort.
But, when I run my program and choose the method that I want to apply, I am getting bigger time on log method than quadratic method. Here, an example of times, in second, for a table with 1000 elements:
Quadratic: 0.0059300
Logarithm: 0.0340000
A bigger different can be noted using a table with more elements.
Well, we could think that my logarithm method was not efficient. But lets see what happens when I eliminate the previous part of the code and do not give the option for the user to choose the method (that is, I will classify the table using both methods):
Logarithm: 0.5810000
Quadratic: 1,0680000
Well, I don't know what is happening and I have no idea what could be causing this.
Giving a little more information about my program: It reads an archieve with a list of elements and classify it according the method (and field) required by the user. The algorithms are working really well, nothing seems wrong with then for me.
If more information is needed, I will be happy to give it.
Thanks in advance for your help!

redpajama_set_name: RedPajamaStackExchange


text:
Q: duplicate entry in map in Java I'm reading a json object and to setting them as key value pair into a HashMap, things were fine till now. Now I come across a problem that I have a particular key which is duplicated in the json object but with different values.
eg:
"id": 31231
"id": 33445
I would require both these values now. Can anyone recommend me the best data structure to store these data.

A: You can use a MultiMap or make your own Map<String,List<Value>.

A: Yes, make the Map value a List and add both values to it.  It's called a multi-map.

A: Use multiMap  The multiMap available in Commons Collections 3.2.1 API
       MultiMap multiMap = new MultiValueMap();
       multiMap.put("key", 12334);
       multiMap.put("key", 31231);
       multiMap.put("key", 12312);
       multiMap.put("key", 12312);
       System.out.println(multiMap);

{key=[12334, 31231, 12312, 12312]}

A: You can define the Map<String,Set<Integer>>, if you don't want the duplicate values against the same json object. Otherwise you can define the set like this: Map<String,List<Integer>>. where json object is the key and the value is set/list of integer values against the json object.
This is how your code logic should be
Before inserting an entry in the hashmap, check whether the key already exists

*

*a. If key does not exist then create a new set/list, add the value to the
se/list and insert it  against the key

*b. If key exists, fetch the set/list against the key and add an element in
the set

Hope you should be able to code that.

A: Guava library also contains Multimap interface along with variety of implementations.

A: It would be better if you keep a JSON Array instead of a single value for the key id. This is how your JSON will look after implementing the above suggestion:
{"ids": [{"id": "a"}, {"id": "b"}], "x": "c", "y": "d", ...  }

While reading just take the value (JSON Array) for the ids key and iterate through it and get id from the JSON objects inside the JSON Array.
I thinks it should work fine for your problem.


text:
Q: Spring transaction management breaks hibernate cascade I'm having a problem where the addition of spring's transaction management to an application causes Hibernate to throw the following error:
org.hibernate.HibernateException: A collection with cascade="all-delete-orphan" was no longer referenced by the owning entity instance: org.fstrf.masterpk.domain.ReportCriteriaBean.treatmentArms
org.hibernate.engine.Collections.processDereferencedCollection(Collections.java:96)
org.hibernate.engine.Collections.processUnreachableCollection(Collections.java:39)
org.hibernate.event.def.AbstractFlushingEventListener.flushCollections(AbstractFlushingEventListener.java:218)
org.hibernate.event.def.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:77)
org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:26)
org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)
org.springframework.orm.hibernate3.SpringSessionSynchronization.beforeCommit(SpringSessionSynchronization.java:135)
org.springframework.transaction.support.TransactionSynchronizationUtils.triggerBeforeCommit(TransactionSynchronizationUtils.java:72)
org.springframework.transaction.support.AbstractPlatformTransactionManager.triggerBeforeCommit(AbstractPlatformTransactionManager.java:905)
org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:715)
org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:701)
org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:321)
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:116)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
$Proxy92.saveNewReportCriteria(Unknown Source)
org.fstrf.masterpk.domain.logic.MasterPkFacade.saveNewReportCriteria(MasterPkFacade.java:134)
org.fstrf.masterpk.controllers.ReportCriteriaController.setupReportType(ReportCriteriaController.java:302)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
java.lang.reflect.Method.invoke(Method.java:585)
org.springframework.web.bind.annotation.support.HandlerMethodInvoker.doInvokeMethod(HandlerMethodInvoker.java:413)
org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:134)
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:310)
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:297)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:875)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:809)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:571)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:511)
javax.servlet.http.HttpServlet.service(HttpServlet.java:710)
javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)

I'm using Spring 2.5 and annotations to implement this management. Here is the class containing the saveNewReportCriteria method (which, as can be seen by the stack trace, is causing the error)
@Transactional(
     propagation = Propagation.REQUIRED,
     isolation = Isolation.DEFAULT,
     readOnly = false)
public class HibernateReportCriteriaDao implements ReportCriteriaDao{

private HibernateTemplate hibernateTemplate;

public Integer saveNewReportCriteria(ReportCriteriaBean reportCriteria) {
    hibernateTemplate.save(reportCriteria);

    List<Integer> maxIdList = hibernateTemplate.find("SELECT max(id) from ReportCriteriaBean");
        logger.info("ID of newly saved list is: " + maxIdList.get(0));
        return maxIdList.get(0);
    }

    public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
        this.hibernateTemplate = hibernateTemplate;
    }
}

Then I added the following sections to my configuration files to tell spring that I am using annotation driven transaction management:
<bean id="actgDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName" value="jdbc/actg" />
    <property name="resourceRef" value="true" />
</bean>

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="actgDataSource" />
</bean>

<tx:annotation-driven/>

I'm pretty sure that the de-referencing error is being caused due to the proxy class that Spring AOP creates and uses in order to handle transaction management, but I have no idea how I'd go about fixing it.

A: the error might well NOT be in that function, if you look carefully at the stack trace you'll see that the error is being called from the PROXY's saveNewReportCriteria and not your class's. this is likely something earlier that did an update or delete and wasn't flushed immediately to the db by hibernate because it can optimise certain things that way.
one way to find out what's happening is to put a .flush() at the end of every delete/update query, which isn't always desirable, or alternatively just do a search for where you might be setting treatmentArms to null or a new List() - to clear a list on hibernate use list.clear(); which will keep the hibernate-proxied collection the correct type.

A: I got the same (all-delete-orphan) problem while saving the parent and child tables at a time.
Solution:

*

*Save only parent first

*get child from parent and remove all old child data in child table

*add parent information to new child data

*add new child data

A: Apparently my problem did lie with the saveNewReportCriteria method. Removal of the second query (the find() call for the maximum ID) caused the error to go away. I have no idea why this is the case. As I mentioned earlier, this method was fine prior to the addition of the transaction management annotations. If anyone knows what is going on here I'd love to find out.


text:
Q: XCUITest Reading file from bundle form UITest target I am trying to read a plist file present in Xcode bundle,
Approach #1 (Didn't work):
I was using a static variable(Line #23 in below screenshot) which returns the path of file present in bundle, It didn't work

Approach #2 (Didn't work):
Using Bundle.main to read a file didn't work

Approach #3 (Working solution):
When I write a function (Line #30 in below screenshot) with same lines of code, It works!

Initially I was trying to read file using the static variable and wasted 2 days, until I figured out that using function instead of static variable would work.
Questions:

*

*I cant find any relevant documentation, Can anyone explain why this Approach #1 didn't work?

*Is the type(of:) specific for object type not class    type?

A: The correct way to read file from within UITest target is
Correct way to read file:
func getPath() -> String?  {
    let bundle = Bundle(for: type(of: self))
    let path = bundle.path(forResource: "MockMDM", ofType: "plist")
    return path
}

Also let me share the code which seem correct but wont work
Wrong way to read file:
static var mockMDMFile: [String: Any]? {

    if let path = Bundle.main.path(forResource: "MockMDM", ofType: "plist") {
        let mdmDict = NSDictionary(contentsOfFile: path) as! [String: Any]
        return mdmDict
    }
    return nil
}

Reason for failure of wrong way:

*

*App has multiple bundles, and the files present in the UITest target will be part of a different bundle NOT Main bundle (Bundle.main).


text:
Q: Assign specific string of a specific line of a text file to a variable I have a text file where I know that the 16th line of the file will begin with _____Dest : xxx, where the underscores (5) are all spaces and xxx is not a known character length and may contain spaces. I want to assign xxx to a variable in a batch file. I imagine the code would contain a for /f "skip=15 delims=" and a find "Dest : " in there, but I'm not exactly sure how to go about it.
If it helps, I know that xxx will be a path that begins with \\ and I want to include the \\ in the variable.
Here is an excerpt from the file:
*******************************************************************************
*                                                                             *
* This is the robocopy log section.                                           *
*                                                                             *
*******************************************************************************

-------------------------------------------------------------------------------
   ROBOCOPY     ::     Robust File Copy for Windows
-------------------------------------------------------------------------------

  Started : Fri Dec 09 20:28:08 2016

   Source : \\server\path...
     Dest : \\server\path...

    Files : *.*

  Options : *.* /TEE /S /E /COPY:DAT /MT:128 /R:1 /W:1

etc.
etc.

I want to assign everything on the 16th line after Dest : to a variable

A: Here's a quick example of how I'd do it:
This method means that there's no need to skip/count lines and only picks out the lines where the robocopy destination is a server path, (as per your specifications).
For /F "Tokens=1*Delims=\" %%A In ('Find "Dest : \\" ^<"file.ext"') Do Set "VAR=\\%%B"

Where file.ext is your robocopy output log.

A: for /f "skip=15tokens=1*delims=: " %%a in (filename) do set "var=%%b"&goto done
:done

Where you'd need to "quote" any filename that contains separators, and if you use a quoted filename then you'll also need to include the usebackq parsing option before the skip.


text:
Q: Mass link redirection script Good Day Everyone,
My website uses a datafeed to upload product listings on my website and the links point to different external websites. I have two options. Either I simply use the links to external websites. Or use some script so that my website link appears first followed by the external link like this:
http://www.mysite/redirect.php?id=http://extsite.com/bla=1&bla=2&bla=3

When clicked, the external link should be executed and the visitor should be transferred to: http://extsite.com/bla=1&bla=2&bla=3
I am playing with php code that will goto the redirect.php file:
<?PHP
  $id = $_GET['id'];
  header("Location: $id");
  exit();
?>

The above method works if there are no parameters after the ext link. But if there are parameters (bla=1&bla=2&bla=3), it doesn't work. I'm not sure what am I doing wrong.
Any help in this matter will be greatly appreciated. Thank you!

A:
http://www.mysite/redirect.php?id=http://extsite.com/bla=1&bla=2&bla=3

Well, that's wrong. Your script gets id=http://extsite.com/bla=1 and bla=2 and bla=3 as its three parameters. Whoever is generating the URL needs to URL-encode the extra & characters as %26.


text:
Q: setting new default properties for to_xml serializer in Rails In Rails, I'm coding a series of controllers to generate XML. Each time I'm passing a number of properties in to to_xml like:
to_xml(:skip_types => true, :dasherize => false)

Is there a way I can set these as new default properties that will apply whenever to_xml is called in my app so that I don't have to repeat myself?

A: Are you calling to_xml on a hash or an ActiveRecord model (or something else)?
I am not that you would want to, but you can easily monkey patch to_xml and redefine it to start with those parameters.  I would suggest that you make a new method to_default_xml that simply called to_xml with the parameters you wanted
def to_default_xml
  self.to_xml(:skip_types => true, :dasherize => false)
end

Update:
Since you want to add this to a couple of ActiveRecord models you could do two things, open up ActiveRecord::base (which is a bit hackish and fragile) or create a module and import it into every model you want to use with it. A little more typing, but much cleaner code.
I would put a class in lib/ that looks something like this:
module DefaultXml
  def to_default_xml
    self.to_xml(:skip_types => true, :dasherize => false)
  end
end

Then in your models:
class MyModel < ActiveRecord::Base
  include DefaultXml
end

A: I put together a plugin to handle default serialization options. Check it out at github.com/laserlemon/dry_serial/tree/master.
class MyModel < ActiveRecord::Base
  dry_serial :skip_types => true, :dasherize => false
end

It also has support for multiple serialization styles that can be called like:
@my_model.to_xml(:skinny)
@my_model.to_xml(:fat)

A: Assuming you're talking about AR's to_xml method and depending on your needs, you could get away with extending the AcitveRecord class by creating a file named: lib\class_extensions.rb
class ActiveRecord::Base
   def to_xml_default
      self.to_xml(:skip_types => true, :dasherize => false)
   end
end

Next, put this in an initializer, so that it's included when Rails starts up:
require 'class_extensions'

Now, you can use it as follows (w/o having to specifically include it in each model):
MyModel.to_xml_default


text:
Q: Which loop to use in error checking? I do not need the answer, but just advice or tips into where and what kind of loop to use. The loop is used if the user enters non-numeric values in numLegal/Letter or copyLegal/Letter. It will ask to re-enter value. Also this is my first post, so please forgive me if I'm doing something wrong.
I was thinking about putting a While loop after I convert the users input.
    Dim numLetter, numLegal, copyLetter, copyLegal As Integer
    Const legalRate As Decimal = 0.06D, letterRate As Decimal = 0.05D, colorcopyRate As  Decimal = 0.49D, bindingRate As Decimal = 1.25D
    Dim colorcopy, binding, bistotal, total As Decimal

    'convert
    numLegal = CInt(numPagesLegalText.Text)
    numLetter = CInt(numPagesLetterText.Text)
    copyLegal = CInt(numCopiesLegalText.Text)
    copyLetter = CInt(numCopiesLetterText.Text)

    'calculate color copy
    If colorRadiobutton.Checked Then
        colorcopy = (numLegal + numLetter) * colorcopyRate
        colorcopyLabel.Text = colorcopy.ToString("c2")
    Else
        colorcopyLabel.Text = "$0.00"
    End If
    'binding button
    If bindingRadiobutton.Checked Then
        Dim numbinding As Integer = CInt(InputBox("How many sets need to be bound?"))
        binding += bindingRate * numbinding
        bindingLabel.Text = (bindingRate * numbinding).ToString("c2")
    Else
        bindingLabel.Text = "$0.00"
    End If
    'buisness cards
    If buiscardsRadiobutton.Checked = True Then

        Const rate100 As Decimal = 65D
        Const rate150 As Decimal = 55D
        Const rate200 As Decimal = 45D

        Dim buisnesscards As Integer = CInt(InputBox("How many buisness cards are needed?"))

        If buisnesscards >= 100 AndAlso buisnesscards <= 149 Then
            buisnesscardLabel.Text = rate100.ToString("c2")
            bistotal = rate100 + total
        End If
        If buisnesscards >= 150 AndAlso buisnesscards <= 200 Then
            buisnesscardLabel.Text = rate150.ToString("c2")
            bistotal = rate150 + total
        End If
        If buisnesscards > 200 Then
            buisnesscardLabel.Text = rate200.ToString("c2")
            bistotal = rate200 + total
        End If
    Else
        buisnesscardLabel.Text = "$0.00"
    End If
    total = ((numLegal * copyLegal) * legalRate) + ((numLetter * copyLetter) * letterRate) + colorcopy + binding + bistotal

    'display

    totalpriceLabel.Text = total.ToString("c2")
    copyLabel.Text = ((numLegal * copyLegal) + (numLetter * copyLetter)).ToString


text:
Q: What is the best way to rehydrate aggregate roots and their associated entities in an event sourced environment I have seen information on rehydrating aggregate roots in SO, but I am posting this question because I did not find any information in SO about doing so with in the context of an event sourced framework.
Has a best practice been discovered or developed for how to rehydrate aggregate roots when operating on the command side of an application using the event sourcing and CQRS pattern
OR is this still more of a "preference" among architects?
I have read through a number of blogs and watched a number of conference presentations on you tube  and I seem to get different guidance depending on who I am attending to.
On the one hand, I have found information stating fairly clearly that developers should create aggregates to hydrate themselves using "apply" methods on events obtained directly from the event store..
On the other hand, I have also seen in several places where presenters and bloggers have recommended rehydrating aggregate roots by submitting a query to the read side of the application. Some have suggested creating specific validation "buckets" / projections on the read side to facilitate this.
Can anyone help point me in the right direction on discovering if there is a single best practice or if the answer primarily depends upon performance issues or some other issue I am not thinking about?

A: Hydrating Aggregates in an event sourced framework is a well-understood problem.

On the one hand, I have found information stating fairly clearly that
  developers should create aggregates to hydrate themselves using
  "apply" methods on events obtained directly from the event store..

This is the prescribed way of handling it. There are various ways of achieving this, but I would suggest keeping any persistence logic (reading or writing events) outside of your Aggregate. One simple way is to expose a constructor that accepts domain events and then applies those events.

On the other hand, I have also seen in several places where presenters
  and bloggers have recommended rehydrating aggregate roots by
  submitting a query to the read side of the application. Some have
  suggested creating specific validation "buckets" / projections on the
  read side to facilitate this.

You can use the concept of snapshots as a way of optimizing your reads. This will create a memoized version of your hydrated Aggregate. You can load this snapshot and then only apply events that were generated since the snapshot was created. In this case, your Aggregate can define a constructor that takes two parameters: an existing state (snapshot) and any remaining domain events that can then be applied to that snapshot.
Snapshots are just an optimization and should be considered as such. You can create a system that does not use snapshots and apply them once read performance becomes a bottleneck.

On the other hand, I have also seen in several places where presenters
  and bloggers have recommended rehydrating aggregate roots by
  submitting a query to the read side of the application

Snapshots are not really part of the read side of the application. Data on the read side exists to satisfy use cases within the application. Those can change based on requirements even if the underlying domain does not change. As such, you shouldn't use read side data in your domain at all.

A: Event sourcing has developed different styles over the years. I could divide all o those into two big categories:

*

*an event stream represents one entity (an aggregate in case of DDD)

*one (partitioned) event stream for a (sub)system

When you deal with one stream per (sub)system, you aren't able to rehydrate the write-side on the fly, it is physically impossible due to the number of events in that stream. Therefore, you would rely on the projected read-side to retrieve the current entity state. As a consequence, this read-side must be fully consistent.
When going with the DDD-flavoured event sourcing, there's a strong consensus in the community how it should be done. The state of the aggregate (not just the root, but the whole aggregate) is restored by the command side before calling the domain model. You always restore using events. When snapshotting is enabled, snapshots are also stored as events in the aggregate snapshot stream, so you read the last one and all events from the snapshot version.
Concerning the Apply thing. You need to clearly separate the function that adds new events to the changes list (what you're going to save) and functions what mutate the aggregate state when events are applied.
The first function is the one called Apply and the second one is often called When. So you call the Apply function in your aggregate code to build up the changelist. The When function is called when restoring the aggregate state from events when you read the stream, and also from the Apply function.
You can find a simplistic example of an event-sourced aggregate in my book repo: https://github.com/alexeyzimarev/ddd-book/blob/master/chapter13/src/Marketplace.Ads.Domain/ClassifiedAds/ClassifiedAd.cs
For example:
    public void Publish(UserId userId)
        => Apply(
            new V1.ClassifiedAdPublished
            {
                Id = Id,
                ApprovedBy = userId,
                OwnerId = OwnerId,
                PublishedAt = DateTimeOffset.Now
            }
        );

And for the When:
    protected override void When(object @event)
    {
        switch (@event)
        {
            // more code here

            case V1.ClassifiedAdPublished e:
                ApprovedBy = UserId.FromGuid(e.ApprovedBy);
                State = ClassifiedAdState.Active;
                break;

            // and more here
         }
     }


text:
Q: update python 2.7 in place? A linux system has /usr/local/bin/python2.7 installed with a time stamp from August 2014. "python2.7 --version" says just "Python 2.7".  There are many packages installed in /usr/local/lib/python2.7/site-packages.
Is there a way to update this in place to 2.7.14 that will not break the existing installed site-packages?  (Searched for the answer but if it was there it was well and truly buried under all the threads about migrating 2.7.x to 3.x.)
Thanks.

A: Try posting here https://serverfault.com/ there may be more relevant answers but I think that is the version that ships with Linux and I would not touch that. It is better to just run yum or apt-get install python. If you do yum update or apt-get update that should update Linux python version if it does need to be updated.


text:
Q: MySQL case makes a new column If I use a MySQL case statement, it creates a new column, it didn't replace the column.
Is it possible to replace the column instead of new column?
Example:
SELECT *,
       CASE WHEN housenumber_addition IS NULL THEN 'ABC'
       ELSE housenumber_addition END AS housenumber_addition
FROM customer

A: You select that column effectively twice, just like you can select any column a multiple times:
select housenumber_addition, housenumber_addition, housenumber_addition
from customer

In general, you should select each column separately and replace housenumber_addition by the code you provided. SELECT * is considered harmful anyways.

A: Just explicitly select the columns you want to appear in your result set, and, in your case, exclude the housenumber_addition column:
SELECT
    col1,     -- some column, not housenumber_addition
    col2,     -- some other column, also not housenumber_addition
    ...,
    CASE WHEN housenumber_addition IS NULL
         THEN 'ABC'
         ELSE housenumber_addition END AS housenumber_addition
FROM customer;

Note that your CASE expression doesn't serve much purpose, because you could have just used COALESCE:
COALESCE(housenumber_addition, 'ABC')


text:
Q: How to set my custom URL for product collection in Magento custom module? I have setup following page for product collection in custom module page which come from the following url as
http://localhost/magento/brand/htc

xml from frontend.xml file
<shop_index_pageview>
        <reference name="root">
            <action method="setTemplate"><template>page/2columns-left.phtml</template></action>
        </reference>
        <reference name="content">
            <block type="shop/shop" name="testattrproduct" template="shop/product.phtml" />
            <block type="shop/shop" name="shop" template="catalog/product/list.phtml">
              <block type="catalog/product_list_toolbar" name="product_list_toolbar" template="catalog/product/list/toolbar.phtml">
                  <block type="page/html_pager" name="product_list_toolbar_pager" />
              </block>
              <action method="setColumnCount"><column_count>6</column_count></action>
              <action method="setToolbarBlockName"><name>product_list_toolbar</name></action>
              <action method="addColumnCountLayoutDepend"><layout>empty</layout><count>6</count></action>
              <action method="addColumnCountLayoutDepend"><layout>one_column</layout><count>5</count></action>
              <action method="addColumnCountLayoutDepend"><layout>two_columns_left</layout><count>4</count></action>
              <action method="addColumnCountLayoutDepend"><layout>two_columns_right</layout><count>4</count></action>
              <action method="addColumnCountLayoutDepend"><layout>three_columns</layout><count>3</count></action>
              <action method="setToolbarBlockName"><name>product_list_toolbar</name></action>
            </block>
      </reference>
    </shop_index_pageview>

Using Routing i have set which module,controller,action to use.
<events>
        <controller_front_init_routers>
            <observers>
                <test_initRouter>
                    <type>singleton</type>
                    <class>Test_Shop_Controller_Router</class>
                    <method>initController</method>
                </test_initRouter>
            </observers>
        </shop_initRouter>
        </events>

File from Controller/Router.php
            ...
            ...
    public function match(Zend_Controller_Request_Http $request)
{

        $front = $this->getFront();
    $identifier = trim($request->getPathInfo(), '/');
    if ($identifier) {
        $p = explode('/', $identifier);
    } else {
        $p = explode('/', $this->_getDefaultPath());
    }
        ...
            ...
    if(substr('brand', 0, strlen('brand')) =='brand'){
        if($p[1] == '')
            {
                $action = "view";
                $param = $action;
            }
        else
            {
                $action = "pageview";
                $param = $p[1];
            }
        $request->setModuleName('shop')
            ->setControllerName('index')
            ->setActionName(trim($action, '/'));
        if($p[1] == '')
            $request->setParam('param', $param);
        else
            $request->setParam('identifier', $param);
        return true;
    }
}
            ...
            ...

From block file
...
    protected function _getProductCollection() {

        if (is_null($this->_productCollection)) {
            $_getCurrentAttrObj = $this->_selected_attribute;
            // d($_getCurrentAttrObj->getData());
            if($_getCurrentAttrObj){
                $_defConfigAttrId = Mage::getStoreConfig('shop_by_brand/all_brands_page_setup/attribute_list');
                $arg_attribute = Mage::helper("shop")->getAttributeNameById($_defConfigAttrId);
                $collection = Mage::getModel('catalog/product')
                    ->getCollection('*')
                    ->addAttributeToSelect('*');
                $collection->addAttributeToFilter('test',12);
                Mage::getModel('catalog/layer')->prepareProductCollection($collection);
                $this->_productCollection = $collection;
            }
        }
        return parent::_getProductCollection();
    }
....

This comes as expected.I can list the product collection from product.phtml Here i can see the url like as  follows
> http://localhost/magento/shop/index/pageview/identifier/htc/?mode=list

Instead I need url in product collection as
> http://localhost/magento/brand/htc/?mode=list

How can i set/acheive routing url  in product collection ?

A: I think setting the controller's "frontName" to "brand" would be the easiest way to achieve this without using a custom router.
<routers>
        <Example>
            <use>standard</use>
            <args>
                <module>Example</module>
                <frontName>Cool</frontName>
            </args>
        </Example>
 </routers>

But if the routing logic is more complex for your particular use case then you should define the router properly, not as an event observer.
<default>
    <web>
        <routers>
            <shop_router>
                <area>frontend</area>
                <class>Test_Shop_Controller_Router</class>
            </shop_router>
        </routers>
    </web>
</default>

A: Use overriding or rewriting in config.xml
 <global>
    <blocks>
      <shop>
        <class>Test_Shop_Block</class>
      </shop>
     <catalog>
        <rewrite>
          <product_list_toolbar>Test_Shop_Block_Product_List_Toolbar</product_list_toolbar>
        </rewrite>
      </catalog>
    </blocks>
  </global>

And From Toolbar.php
class Test_Shop_Block_Product_List_Toolbar extends Mage_Catalog_Block_Product_List_Toolbar
{

    public function getPagerUrl($params=array())
    {
        $getDefaultUrl = new Magecart_Shopbyattribute_Block_Shop();
        $getDefaultUrlKeyForAttr = $getDefaultUrl->getDefaultUrlKeyForAttr();
        $_params = $this->getRequest()->getParams();
        $identifier = $_params['identifier'];
        $urlParams = array();
        $urlParams['_current']  = false;
        $urlParams['_escape']   = true;
        $urlParams['_use_rewrite']   = true;
        $urlParams['_query']    = $params;

        return $this->getUrl($getDefaultUrlKeyForAttr.'/'.$identifier, $urlParams);
    }

}

That is it. Now the magento will use the url from getPagerUrl() function :)


text:
Q: Prove this inequality by using the mean value theorem I want to prove that $x<\frac{2x}{2-x}, \forall x \in (0,1)$, by using the mean value theorem.
So, consider $f(x)=\frac{2x}{2-x} -x$. $f(0)=0$.
$f´(x)=\frac{2x-2}{(2-x)^2} - 1$ and $f'(x)<0, \forall x \in (0,1)$. By the mean value theorem:
$$\exists c \in (0,1)~~~\text{such that}~~~f(x)-f(0) = f'(c)(x-0)~~~\rightarrow~~~f(x)<0 ~~~\rightarrow~~~x> \frac{2x}{2-x}$$
So, it doesn't work.

A: It turns out that
$$f'(x)=\frac{4}{(2-x)^2}-1.$$
This is safely positive on our interval, so the MVT argument goes through.
Remark: It seems you were asked to use MVT explicitly. The ordinary way is to use the theorem, derived using the MVT, that if the derivative of a function is positive on an interval, then the function is increasing on that interval.


text:
Q: Fable: The Lost Chapters Quests Stuck I am playing Fable: The Lost Chapters on the PC, and I have a couple of quests that will just not get out of my quest log. The book quest is one and the chicken kicking is the other. I have already gotten silver keys for both and a chicken hat from the chicken kicking. I have not gotten the emote but it will not give it to me regardless of the score I get. Am I missing something or are they just stuck in my quest log?

A: I found an independent source, namely an FAQ on gamefaqs that says the quests I am talking about never go away! Which is a bit annoying since I am a completionist, hopefully the other versions of fable are not like that, but is less annoying now that I know I am not missing something.

A: I know from my personal experience of playing on Xbox (I've beaten Fable TLC ~10 times over) that the book quest will go away after you've donated all 30 possible books. It's possible that there's a bug in the PC version that causes the quest to not go away. On Xbox, in particular, after you've donated all 30 books and you attempt to talk to the teacher again during class, he tells you something to the effect of "You've done an amazing job helping us restock our library, and we don't need any more books!" And the quest is no longer in the list of active quests.
The chicken kicking quest, on the other hand, does not go away, even after getting all of the possible prizes (i.e. the hat, the key and the emotion), probably since you can still go back to the chicken kicking game anytime afterwards and win money. Again, it's possible that there's a bug on the PC version that won't allow it to give you the emotion prize.
Man, I used to love this game...so much nostalgia


text:
Q: Java/Gradle error with versions or something So, I have several Gradle projects that I am working on at the moment and when I do any command in the correct folder starting with ./gradlew it returns this error:

FAILURE: Build failed with an exception.

* What went wrong:
Could not determine java version from '11.0.9.1'.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

What is even going on?
Here is some other stuff that might be useful:
Im on mac
my java version is OpenJDK 11.0.9.1
i don't have Gradle installed on my system, I have it in the project directory. (e.g. I use ./gradlew not gradlew)
Any help would be appreciated, So thanks in advance.
UPDATE: I do NOT have 2 gradle installations... I have already stated this but apparently some1 just came in and said it was the same question...
I still need this to be fixedddddddd


text:
Q: Change tab on button click event i would like to change to a different tab when i click a button.
my xaml is as follow:
<TabControl Name="Tabcontrol1" Margin=" 5" SelectedIndex="0">
            <TabItem Header="Properties" Opacity="1">
                <Grid Width="1185" Height="945" Background="Snow" >
</Grid>
</TabItem>
<TabItem Header="Others">
<Grid>
</Grid>
</TabItem>
</TabControl>

and my button click event:
    private void BuildButton_Click(object sender, RoutedEventArgs e)
{
    Tabcontrol1.SelectedIndex = "1";
}

is there something wrong? "Cannot implicitly convert type 'string' to 'int'" appears

A: Remove quotes:
Tabcontrol1.SelectedIndex = 1;


text:
Q: How to config WSO2 API to access rails REST json web service I have a rails app exposed an rest json interface like: http://foo.com/agency/:name.json
I have written a wso2 esb api config to access the api
   <api name="agency" context="/agency">
      <resource methods="GET" uri-template="/view/{name}">
         <inSequence>
            <property name="REST_URL_POSTFIX"
                      expression="fn:concat('/',get-property('uri.var.name'), '.json')"
                      scope="axis2"/>
            <send>
               <endpoint>
                  <address uri="http://foo.com/agency/" format="pox"/>
               </endpoint>
            </send>
         </inSequence>
         <outSequence>
            <send/>
         </outSequence>
      </resource>
   </api>

when I tested the wso2 esb api using curl, I get
\dev\curl-w32>curl http://192.168.181.132:8280/agency/view/blah-blah
curl: (52) Empty reply from server

And the ESB log write
[2013-11-14 16:17:49,047]  INFO - LogMediator To: /agency/view/blah-blah, MessageID: urn:uuid:d0a4c4ec-7600-430d-bb52-e580b
6ec2516, Direction: request, MESSAGE = Executing default 'fault' sequence, ERROR
_CODE = 101500, ERROR_MESSAGE = Error in Sender, Envelope: <?xml version='1.0' e
ncoding='utf-8'?><soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap
-envelope"><soapenv:Body/></soapenv:Envelope>
[2013-11-14 16:18:49,063]  WARN - SourceHandler Connection time out after reques
t is read: http-incoming-48

seems endpoint url translate is not work.
How to correct my API config to make it work? Thx

A: Try changing the scope="axis2" to scope="transport" and removing format="pox" from the address endpoint.


text:
Q: AWS S3 and Spring 3.1.0-Release in java 1.8 project getting the below error when i try to implement upload/download files to AWS S3 in a java and spring project - with old version of Spring which is 3.1.0-release and java is 1.8.
i dont want to ugrade the version of spring as it widely used in the application so is there any way to achieve this with out uprgrading spring version.
your help would be appreciated. - please see the error below.
Thanks.
ERROR [org.springframework.web.context.ContextLoader] -
org.springframework.beans.factory.BeanDefinitionStoreException: Failed to read candidate component class: file ....[C:\Workspace\se\seyaWEB\target\classes\com\add\web\helper\S3Config.class]; nested exception is java.lang.ArrayIndexOutOfBoundsException: 13568


text:
Q: Sequelize error: defineCall not defined in Index.js I've been receiving this sequelize error
/node_modules/sequelize/lib/sequelize.js:508
      this.importCache[path] = defineCall(this, DataTypes);
                           ^
    TypeError: defineCall is not a function
    at module.exports.Sequelize.import             (/node_modules/sequelize/lib/sequelize.js:508:32)
at   /models/Index.js:16:33
at Array.forEach (native)
at Object.<anonymous> (/Users/vincentporta/Desktop/RCB_Classwork/cesarcell/models/Index.js:15:4)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Module.require (module.js:353:17)
at require (internal/module.js:12:17)

I've narrowed it down to the commented code in my Index.js file below
"use strict";
var fs        = require("fs");
var path      = require("path");
var Sequelize = require("sequelize");
var config    = require(path.join(__dirname, '..', 'config',    'config.json'))[env];
var sequelize = new Sequelize(config.database, config.username,  config.password, config);
var db        = {};

fs
  .readdirSync(__dirname)
  .filter(function(file) {
    return (file.indexOf(".") !== 0) && (file !== "index.js");
  })

This commented code below breaks it

    //.forEach(function(file) {
    //   var model = sequelize.import(path.join(__dirname, file));
    //   db[model.name] = model;
    // });
Object.keys(db).forEach(function(modelName) {
  if ("associate" in db[modelName]) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;

Does anyone know why this error is occuring?

A: I saw a similar problem just now and the problem was a file that was in the models folder that was not actually a database model. Ensure that your models folder only contains models for your database. Hopefully this helps!

A: This usually means you're trying to import a non-sequelize object. If the name of your index file is Index.js then you need to change it in your filter function (first letter is capital)
return (file.indexOf(".") !== 0) && (file !== "Index.js");

As it is case sensitive. Also check that there aren't any other files in your import folder which don't define sequelize model. If there are just add them to your filter function.

A: This can happen if you have a circular import, also.

A: In my case, it was missing default.
This code caused the error:
@Table
export class User extends Model<User> {
  @Column
  userId!: number;

  @Column
  tenantId!: number;
}

default in the class defintion fixed it:
@Table
export default class User extends Model<User> {
  @Column
  userId!: number;

  @Column
  tenantId!: number;
}


text:
Q: Is it possible to hide the name of the desktop icons? I know it is possible to hide the name by renaming the file/folder to something else. The problem comes with my cloud showing in the desktop. I want it to show and I don't want to change the names of my folders.
I made a cool icon set for the few things I've got in my desktop and the names there just don't fit.

A: If you want to just hide one filename or folder, the answer is kludgey but it works:
Insert 58 spaces in the beginning of the filename: the filename "disappears" from the desktop.  It still exists (you can Cmd-I or Finder to see it/change it), but it's no longer visible on the Desktop.  In actuality, it's probably showing the first 58 characters of the filename (the invisible spaces) and cutting off the rest, so technically it's not hiding the name, just truncating it, but anyway...  (The 58 may not be an exact number, but that's how many it took to hide "foo.app" on my 10.11.6 Mac.)

A: Using just Finder to hide filenames on the Desktop is (to my knowledge) not possible, but I would be happy to be proven wrong about that.
I realise you don't want to rename files and folders, but the only workaround I know of to "hide" the filenames is to rename them to a space " ".

A: To Hide Desktop Icons, run the following commands in Terminal:
defaults write com.apple.finder CreateDesktop -bool false
killall Finder

To show them again, run:
defaults write com.apple.finder CreateDesktop -bool true
killall Finder

Source: Hide All Desktop Icons in Mac OS X.

A: You can use HiddenMe app to hide Desktop icons on demand with a single click. This is especially useful for some presentations.
Homepage: http://appersian.net/


text:
Q: Shell : How to print progressbar I am trying to print a progress bar in shell as follows
#!/bin/bash

sleep $1 & PID=$!
printf "["
counter=1
while kill -0 $PID 2> /dev/null; do
    percent_done=$(echo "${counter}*100/${1}" | bc -l )
    printf  "▓%.0f" $percent_done
    sleep 1
    counter=$counter+1
done
    printf "] done!"

and i call it as
myScript.sh 10
so the script will invoke a sleep of 1 sec for 10 seconds. On each iteration of the loop, i want to print
▓<the percentage of the loop completed>
for instance i expect
▓10▓20▓30▓40▓50▓60 and so on. but i get
▓10▓11▓12▓13▓14▓15 instead
what am i doing wrong? am i not updating the counter properly? also, if i do
percent_done=$(echo "${counter}/${1}" | bc -l )
then i get
▓0.1000000000000▓1.100000000000000000▓2.10000000000000000000▓3.10000000000000000000▓ and so on.
Since I dont want the long floating point value, i added the *100 in the expression.
What am i doing wrong?

A: $ function tt {
sleep $1 & PID=$!
printf "["
counter=10
while kill -0 $PID 2> /dev/null; do
percent_done=$(echo "${counter} |bc -l)
printf  "▓%.0f" $percent_done
sleep 1
counter=$counter+10
done
printf "] done!"
}
$ tt 10
[▓10▓20▓30▓40▓50▓60▓70▓80▓90▓100

You can further simplify your code by declaring an integer to bash:
$ function t {
  sleep $1 & PID=$!;
  printf "[";
  declare -i counter=10;
  while kill -0 $PID 2> /dev/null; do printf  "▓%.0f" $counter;
  sleep 1;
  counter=$counter+10; done;
  printf "] done!"; }
$ t 20
[1] 4227
[▓10▓20▓30▓40▓50▓60▓70▓80▓90▓100▓110▓120▓130▓140▓150▓160▓170▓180▓190▓200[1]+  Done

A: I guess counter=$counter+1 does not do what you expect. It just concatenates $counter and "+1". So after n iterations you'll have some sting like "1+1+...+1" (n+1-times). You have that in the expression you pipe to bc and operator precedence (* before +) then leads to the unexpected results.
Change counter=$counter+1 to also use bc as you've done above, thus counter=$(echo "${counter}+1" | bc).
Or change percent_done=$(echo "${counter}*100/${1}" | bc -l ) to percent_done=$(echo "(${counter})*100/${1}" | bc -l ) (note the parenthesis) to overrule operator precedence, if for some reason you really want such a "1+1..+1" string.


text:
Q: Raising a base (which is a decimal) to a power yields false results This is a calculator for the sum of geometric series and my problem is that if  the base (r) is a decimal and is raised to any power > 1, I would get an incorrect result 5.5^2 is 25 it's 30.25
(to you editors out there, I don't know how to highlight code and for future convenience I would like to know how so it would really help if I got instructions on how to do that)
I've tried assigning the function "float" to the variables assuming that if python sees the variable as a decimal, maybe what's after the decimal point would be raised to the power as well.
a1 = int(float(input("First Term in Sequence")))
r = int(float(input("Rate of Change")))
n = int(float(input("Number of Terms")))

def a(r,n):
    global rn
    r = float(r)
    n = float(n)
    rn = r**n
    return rn

I expect the output to be correct:
As in 5.5^2 = 30.25
Not:
5.5^2 = 25
It's almost as though the code does not bother with what comes after the decimal

A: a1 = int(float(input("First Term in Sequence")))
r = int(float(input("Rate of Change")))
n = int(float(input("Number of Terms")))

Why are you turning your inputs to int here?
If you had typed-in 5.5, it would become 5 here. After this even if you do float(5) you would still get 5.0 not 5.5
So you're actually calculating 5.0 ** 2.0 == 25


text:
Q: Linux Cooked Capture in Packets What is the use of a Linux cooked capture header? I get this header from a device when I do packet capture on a particular interface.

A: The Linux cooked capture header and the reason for it is probably best described on the Wireshark wiki SLL page, quoted here for convenience:
Linux cooked-mode capture (SLL)
This is the pseudo-protocol used by libpcap on Linux to capture from the "any" device and to capture on some devices where the native link layer header isn't available or can't be used. (For example, the Linux PPP code doesn't reliably supply a PPP header to libpcap - it's usually either absent, meaning that the packet type isn't available, or contains extra random gunk in some but not all packets, as happens on some PPP-over-ISDN interfaces - so the SLL pseudo-link-layer is used on PPP interfaces. It's used on the "any" device because not all interfaces on a machine necessarily have the same link-layer type, but, in order for capture filters to work, all packets on an interface must have the same type of link-layer header.)
When capturing from the "any" device, or from one of those other devices, in Linux, the libpcap doesn't supply the link-layer header for the real "hardware protocol" like Ethernet, but instead supplies a fake link-layer header for this pseudo-protocol.
(For those who are curious, "SLL" stands for "sockaddr_ll"; capturing in "cooked mode" is done by reading from a PF_PACKET/SOCK_DGRAM socket rather than the PF_PACKET/SOCK_RAW socket normally used for capturing. Using SOCK_DGRAM rather than SOCK_RAW means that the Linux socket code doesn't supply the packet's link-layer header. This means that information such as the link-layer protocol's packet type field, if any, isn't available, so libpcap constructs a synthetic link-layer header from the address supplied when it does a recvfrom() on the socket. On PF_PACKET sockets, that address is of type sockaddr_ll, where "ll" presumably stands for "link layer"; the fields in that structure begin with sll_. See the packet(7) man page on a Linux system for more details.)


text:
Q: Two split exact sequence implies another one is split? $$\begin{array}{ccccccccc}
&&0&&0&&0\\
&&\downarrow &&\downarrow && \downarrow\\
0 & \to & \mathbb{Z}_2\{a\} & \to & \mathbb{Z}_2\{a\} & \to & 0 & \to & 0\\
  &     &\downarrow &    & \downarrow  &&\downarrow\\
0&\to&\mathbb{Z}_2\{a\}\oplus\mathbb{Z}_2\{b\}  & \xrightarrow{f} & G & \xrightarrow{g} & \mathbb{Z}_2\{c\} & \to & 0\\
&&\downarrow & &\downarrow & & \downarrow\\
0 & \to & \mathbb{Z}_2\{b\} & \xrightarrow{h} & \mathbb{Z}_2\{y\}\oplus\mathbb{Z}_2\{z\} & \xrightarrow{i} & \mathbb{Z}_2\{c\} & \to  &0\\
&&\downarrow && \downarrow &&\downarrow\\
&&0 && 0 && 0
\end{array}$$
where $\mathbb{Z}_2\{a\}$ means that $a$ generates $\mathbb{Z}_2$ and $y=h(b)$ and $i(z)=c$.
In the diagram, first and third rows are split and first and third columns are split.
Then second row($0 \to \mathbb{Z}_2 \oplus \mathbb{Z}_2 \to G \to \mathbb{Z}_2 \to 0$) or second column($0 \to \mathbb{Z}_2 \to G\to \mathbb{Z}_2  \oplus \mathbb{Z}_2 \to 0$) is split? Or $G$ is isomorphic to $\mathbb{Z}_4 \oplus \mathbb{Z}_2$?

A: Although the problem has been answered in the comments, I thought I'd make an observation that makes things more obvious. It is possible to produce such diagrams as a direct sum of two subdiagrams:
$$
\begin{array}{ccccc}
    \mathbb{Z}_2 &\to& \mathbb{Z}_2 &\to& 0
\\  \downarrow & & \downarrow & & \downarrow
\\  \mathbb{Z}_2 &\to& H &\to& \mathbb{Z}_2
\\  \downarrow & & \downarrow & & \downarrow
\\  0 &\to& \mathbb{Z}_2 &\to& \mathbb{Z}_2
\end{array}
$$
and
$$
\begin{array}{ccccc}
    0 &\to& 0 &\to& 0
\\  \downarrow & & \downarrow & & \downarrow
\\  \mathbb{Z}_2 &\to& \mathbb{Z}_2 &\to& 0
\\  \downarrow & & \downarrow & & \downarrow
\\  \mathbb{Z}_2 &\to& \mathbb{Z}_2 &\to& 0
\end{array}
$$
Off the cuff, I believe every way to fill in your diagram has such a direct sum decomposition. This simplification makes it easier to see that there are two possibilities for $H$.


text:
Q: How to apply a reduce function with Java threads? If I have a simple program to parallelize counting the number of 1's from a random integer from 0 - 9 for a large number of iterations, how do I reduce the variable counting the 1's (numOnes) using the sum function so that I can be able to use the total sum later on in my program.
This is equivalent to the reduction directive in OpenMP.
public void run() {

  long work = total_iterations / threads;
  long numOnes = 0;

  for (long i = 0; i < work; i++) {
    int randomNum = rand.nextInt(9);

    if (randomNum == 1) {
      numOnes += 1;
    }
  }
}

Once each thread is done executing, I want to be able to use numOnes containing the aggregate result.

A: In Java, you would have to sit down and manage things manually. In other words: assuming that your data is partitioned, you just kick of those 10 threads, and let them do their work.
In the end, you want to join all those threads; as in: only when all threads "joined"; all of them are done; and you are ready to go forward and process their results.
Alternatively, you would look into more "abstract" things like ExecutorService and Futures; to get away from dealing with "bare metal" threads directly.
Of course that is pretty generic; but well, so is your question.

A: You could use streams for this.
public class ParallelInts
{
   public static void main(String[] args) {
      int count = new Random().ints( 1_000_000, 0, 10 ).parallel()
              .reduce( 0, (sum, i) -> sum + ((i==1)?1:0) );
      System.out.println( "count = " + count );
   }
}


text:
Q: How to navigate c++ template instantiations in vim? I know that vim has a convenient way to navigate to between matching opening and closing parentheses (), brackets[], and braces{}. I happen to write lots of C++ template code, and would like to have a similar ability to navigate between matching angle brackets <>.
// I want to jump from this '<'
//         v
enable_if_t<conditional_t<test_v<x>, y, z>::template w<x, y>::value > 42,
            typename a<b, c>::type>
// ... to this '>'                ^

Is there a vim command that does this correctly in a context sensitive manner? Specifically, it should understand when < is less than and when it opens a template argument list, when > is greater than and when it closes a template argument list, and when >> is right shift and when it closes two template argument lists.
Edit: Would be willing to switch to emacs if it can do this.

A: You can configure vim to navigate between matching angle brackets only in c++ files by adding the following to your vimrc
autocmd FileType cpp setlocal matchpairs+=<:>


text:
Q: How to improve the neural networks accuracy? Recently I have Implemented Backpropagation on the MNIST dataset using the following code and obtained the overall accuracy of approximately 95.7%.
My question is how can we further improve the accuracy of the code given below.
I have tried to increase/decrease the number of hidden nodes. Also changing the learning rate to different values but the accuracy isn't going beyond 96%.
import numpy as np
import matplotlib.pyplot as plt
import scipy.special
from sklearn.metrics import confusion_matrix

k = list()
k_ =list()

class NeuralNetworks:

    def __init__(self, inputnodes, hiddennodes, outputnodes, learningrate ):

        self.inodes = inputnodes

        self.hnodes = hiddennodes

        self.onodes = outputnodes

        self.lr = learningrate

        self.wih = np.random.normal(0.0 , pow(self.hnodes , -0.5),(self.hnodes, self.inodes))

        self.who = np.random.normal(0.0 , pow(self.onodes , -0.5),(self.onodes , self.hnodes))

        self.activation_function = lambda x: scipy.special.expit(x)
        pass

    def train(self, input_list, target_list):

        inputs = np.array(input_list , ndmin = 2).T
        targets = np.array(target_list , ndmin =2).T

        hidden_inputs = np.dot(self.wih , inputs)

        hidden_outputs = self.activation_function(hidden_inputs)

        final_inputs = np.dot(self.who , hidden_outputs)

        final_outputs = self.activation_function(final_inputs)

        output_errors = targets - final_outputs

        hidden_errors = np.dot(self.who.T, output_errors)

        self.who += self.lr*np.dot((output_errors * final_outputs * (1 - final_outputs)), np.transpose(hidden_outputs))

        self.wih += self.lr*np.dot((hidden_errors * hidden_outputs *(1 - hidden_outputs)), np.transpose(inputs))

        pass

    def query(self, input_list):

        inputs = np.array(input_list , ndmin = 2).T

        hidden_inputs = np.dot(self.wih , inputs)

        hidden_outputs = self.activation_function(hidden_inputs)

        final_inputs = np.dot(self.who , hidden_outputs)

        final_outputs = self.activation_function(final_inputs)

        return final_outputs

input_nodes = 784

hidden_nodes = 300

output_nodes = 10

learning_rate = 0.2

n = NeuralNetworks(input_nodes , hidden_nodes , output_nodes , learning_rate)

train_data_f = open("C:\Python27\mnist\mnist_train.csv" , 'r')

train_data_all = train_data_f.readlines()

train_data_f.close()

for rec in train_data_all:

    all_val = rec.split(',')

    inputs = (np.asfarray(all_val[1:])/255.0*.99) + 0.01

    targets = np.zeros(output_nodes) + 0.01

    targets[int(all_val[0])] = 0.99

    n.train(inputs , targets)

test_data_f = open("C:\Python27\mnist\mnist_test.csv" , 'r')

test_data_all = test_data_f.readlines()

test_data_f.close()

for rec in test_data_all:

    all_val = rec.split(',')

    p = (n.query((np.asfarray(all_val[1:])/255*.99)+0.01))

    k.append(list(p).index(max(list(p))))

    k_.append(int(all_val[0]))

print confusion_matrix(k_ , k)

print np.trace(np.asarray(confusion_matrix(k_ , k)))/10000.0

The output of the above code is (Confusion Matrix & Overall Accuracy):
 Confusion Matrix-
 [[ 965    0    1    0    0    1    9    0    3    1]
 [   0 1126    2    1    0    1    2    0    3    0]
 [   8    4  958   19    1    1    6   10   22    3]
 [   1    0    2  982    0    5    1    4    9    6]
 [   3    0    4    0  923    0    9    0    3   40]
 [   3    3    0   14    1  843   11    0   12    5]
 [   7    3    0    0    3    9  935    0    1    0]
 [   4   16    5    1    3    1    1  952    2   43]
 [   3    3    1   12    6    8    8    5  920    8]
 [   4    7    0    8    8    2    2    3    8  967]]

 Overall Accuracy is 0.9571

Here's the plot:

A: If the learning rate is too big means steps may be too large, and we might step over potential optimums or even bounce out of an optimum.

*

*You should dive deeper in Andrew Ng's Coursera Course
to fully understand the fundamental ML knowledges.

*Second, better use Convolutional Neural Networks to extract more features, that will increase you accuracy.
Once you learn CNN technique, you probably know some useful skills dropout, pooling, relu activation ...etc.

A: Increasing/Decreasing hidden layers, changing learning rate, trying with different activation functions or modifying the number of epochs to train your neural network won't work out in most of the cases. Rather, try to focus on reducing the error rate of your neural network. Train Your network with a possible number of input data may help you to achieve accuracy in a better way.
Also, Feature Extraction here plays a vital role. Before Classification of MNIST data, apply the best feature extraction technique to improve classification rate of your network.
For an instance, I attached an URL below this answer. In that paper, they achieved 99.67% of accuracy rate for MNIST dataset. They used MLP for classification and Multiple Feature Selection Technique. Have a look into this.
------------------->        Link is attached here


text:
Q: SMTP relay through GMail overrides "from:" address with "[me]@gmail.com" I've been trying to figure out if this is a new "feature" or if there is an issue with my configuration.  I'm using Ubuntu 10.04 Desktop with Postfix as MTA.  My smtp (as opposed to smtpd) configuration follows that outlined in Jeremy's excellent response here:
Configure Postfix to send/relay emails Gmail (smtp.gmail.com) via port 587
I am able to successfully relay mail through [smtp.gmail.com]:587; however, on the receiving end, the from: address shows: "[my_gmail_username]@gmail.com" instead of "[my_user]@[my_domain]".
Would greatly appreciate any hints or tips; in this instance, my Google skills have failed me!

A: I think they've always done this, even when you've configured your gmail to send from other domains. As far as I know, the only way around this is to switch to using Google Apps, which is free if you just use the standard edition. The problem with this is that it means you have to change your MX records so that google handles all of your incoming mail, and it is only free for up to 50 users.

A: Did you add your non gmail address on https://mail.google.com/mail/?shva=1#settings/accounts ? (in the Send mail as part)

A: They do that for security reasons. Your ISP probably uses gmail as they email system, I know mine does. If you want to run a mail server without this issue try smtp2go. It is a small annual cost but it works like a charm! My server has about 5 users and I pay I think about $24.95 a year.
All you need to do is log in to sptp2go and specify what email address are allowed to use the smtp2go smtp server (your email users on your mail server) by email address and then set up your MTA.
SMTP2GO even can runn on different ports. Especially useful if you ISP blocks certain ports.

A: I've experienced this as well, and I don't think there's a way around it aside from switching to GAFYD


text:
Q: MS Word - if value "red" appears after value "1" and before value "2" then 1 in an Excel cell I have filled in questionnaires from a study. Correct answers can usually be identified by one word such as "red" or "car".
An idea to automate going through the answers might not be possible but I am interested in asking. Could you create a forumla or macro which adds a 1 to an excel cell (1 for correct) if between 1 and 2 (i.e., 1 for the first question and 2 for the second question) there is a certain text such as "red".
I have 67 questionnaires and if I could automate whether their answers are correct this would be really useful. As I said in other posts recently, I discovered not long ago how efficient it is to learn programming for research work that I am doing or almost any work for that matter.

A: Without knowing what your survey output looks like, I took a stab at this. I set up a spreadsheet like below:
Response            1       2       3       End      Question   Answer
1red2car3catEnd     1.00    1.00    1.00    3.00        1         red
1blue2car3catEnd    0.00    1.00    1.00    2.00        2         car
1red2boat3catEnd    1.00    0.00    1.00    2.00        3         cat
1blue2boat3catEnd   0.00    0.00    1.00    1.00

Where Response is in A1 and Question in G1 and Answer in H1.
I used this formula in B2:
=IF(RIGHT(LEFT($A2,FIND(C$1,$A2)-1),(FIND(C$1,$A2)-1-FIND(B$1,$A2)))=$H$2,1,0)

It gets the value after the column header value but before the next column header value from the response column and compares it to the answer key on the right.


text:
Q: Reset Find and Replace dialogs to Current Document in Visual Studio Is there a way to force the Find and Replace dialog boxes, in visual studio, to auto select Current Document in the Look in drop down? It should do this only on reopening the dialog. I regularly forget to switch back from entire solution or project and end up wasting a lot of time waiting for VS to search everything including designer files! I'm hoping for a registry hack or something.
I'm sure this is a major annoyance for others too. Any tips on this would be greatly appreciated!

A: As an alternative, you can use the Find combo box to only search the current document. The shortcut is Ctrl+/ or maybe Ctrl+D. It moves the focus to the Find combo box and you can type and press Enter to search.

A: Visual Studio retains separate settings for dialogs shown using Ctrl+F and Ctrl+Shift+F shortcuts, though dialogs themselves are identical. So when I want to search in current document, I hit Ctrl+F. When I want to search in Project/Solution/directory, I hit Ctrl+Shift+F and then choose where I want to search.


text:
Q: Negative temperature thermodynamics I asked this question about thermodynamics.
I considered $$T=\frac{\partial U}{\partial S}$$ at constant $V$ and $N$ (number of particles), but now I can't figure out the change of $U$ with respect to $V$ if $T<0$. Can somebody help me?
I also thought that $T = \text{slope of the tangent line to the function } U(S)$, but I can't figure out what the curve $U(V)$ is when $T<0$, as required.
Note: I know the temperature can't be negative, but I want to know what would theoretically happen.


text:
Q: Full Calendar Styling not Correct after import I'm trying to use React Full Calendar inside my project and though the calendar gets rendered in the correct way, the styling is a bit off. Here's how it is looking currently:

As you can see, in the header toolbar, the month word isn't aligned in the middle which is the same for other words and icons. Maybe, the size of the button itself is looking small in height.
The functionality of the button is working correctly but the styling isn't how it is that they are showing in documentation.
Here's the link to how it should actually look: https://fullcalendar.io/docs/toolbar-demo
Here's how I've included the FullCalendar:
import React, { Component } from 'react'
import FullCalendar from '@fullcalendar/react'
import dayGridPlugin from '@fullcalendar/daygrid'
import interactionPlugin from "@fullcalendar/interaction";
import timeGridPlugin from "@fullcalendar/timegrid";

import "@fullcalendar/common/main.css";
import "@fullcalendar/daygrid/main.css";
import "@fullcalendar/timegrid/main.css";

class TimelineScheduler3 extends Component {

handleDateClick = (arg) => { // bind with an arrow function
 alert(arg.dateStr)
}

render() {

return (
  <FullCalendar
    plugins={[dayGridPlugin, interactionPlugin, timeGridPlugin]}
    initialView="dayGridMonth"
    weekends={true}
    dateClick={this.handleDateClick}
    headerToolbar={{
      left: 'dayGridMonth,timeGridWeek,timeGridDay',
      center: 'title',
      right: 'prevYear,prev,next,nextYear'
    }}
    events={
      [
        { title: 'event 1', date: '2021-05-05' },
        { title: 'event 2', date: '2021-05-07' }
      ]}
  />
)
}
}

  export default TimelineScheduler3;

Is some import missing from my end or is the styling of my application overriding styling of FullCalendar?


text:
Q: Running Python script on AWS EC2 Apologies if it is repeat but i couldn't find anything worthwhile to accomplish my task.
I have an instance and i have figured out starting and stopping it using boto3 and it works but the real problem is running the script when instance is up. I would like to wait for script to finish and then stop the instance.
python /home/ubuntu/MyProject/TechInd/EuropeRun.py &
python /home/ubuntu/FTDataCrawlerEU/EuropeRun.py &

Reading quite a few post leads to the direction of Lambda and AWS Beanstalk but those don't appear simple.
Any suggestion is greatly appreciated.
Regards
DC

A: You can use the following code.
import boto3
import botocore
import os
from termcolor import colored
import paramiko

def stop_instance(instance_id, region_name):
    client = boto3.client('ec2', region_name=region_name)
while True:
    try:
        client.stop_instances(
            InstanceIds=[
                instance_id,
            ],
            Force=False
        )

    except Exception, e:
        print e

    else:
        break

# Waiter to wait till instance is stopped
waiter = client.get_waiter('instance_stopped')
try:
    waiter.wait(
        InstanceIds=[
            instance_id,
        ]
    )
except Exception, e:
    print e

def ssh_connect(public_ip, cmd):

# Join the paths using directory name and file name, to avoid OS conflicts
key_path = os.path.join('path_to_aws_pem', 'file_name.pem')

key = paramiko.RSAKey.from_private_key_file(key_path)
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# Connect/ssh to an instance
while True:
    try:
        client.connect(hostname=public_ip, username="ubuntu", pkey=key)

        # Execute a command after connecting/ssh to an instance
        stdin, stdout, stderr = client.exec_command(cmd)
        print stdout.read()

        # close the client connection once the job is done
        client.close()
        break

    except Exception, e:
        print e

# Main/Other module where you're doing other jobs:

# Get the public IP address of EC2 instance, I assume you should have handle to the ec2 instance already
# You can use any alternate method to fetch/get public ip of your ec2 instance
public_ip = ec2_instance.public_ip_address

# Get the instance ID of EC2 instance, I assume you should have handle to the ec2 instance already
instance_id = ec2_instance.instance_id

# Command to Run/Execute python scripts
cmd = "nohup python /home/ubuntu/MyProject/TechInd/EuropeRun.py & python /home/ubuntu/FTDataCrawlerEU/EuropeRun.py &"
ssh_connect(public_ip, cmd)
print colored('Script execution finished !!!', 'green')

# Shut down/Stop the instance
stop_instance(instance_id, region_name)

A: You can execute your shutdown command through python code once your script is done.
An example of using ls
from subprocess import call
call(["ls", "-l"])

But for something that simple lambda is much easier and resource efficient. You only need to upload your script to s3 and the execute the lambda function through boto3.
Actually you can just copy paste your script code to the lambda console if you don't have any dependencies.

A: Some options for running the script automatically at system startup:

*

*Call the script via the EC2 User-Data

*Configure the AMI to start the script on boot via an init.d script, or an @reboot cron job.

To shutdown the instance after the script is complete, add some code at the end of the script to either initiate a OS shutdown, or call the AWS API (via Boto) to shutdown the instance.


text:
Q: Start an intent based on Handler handle message I have an application which logs in into a webservice. I start a new thread when the login button is clicked and show a progress dialog while the device is communicating with the server. Based on the success or failure of the attempt I send a message to the handler of 1 - success and -1 -failure. But how do I create and start a new intent based on this message? Or how should I handle this situation otherwise. Here is my code for the Login Activity:
public class Login extends Activity implements OnClickListener {

private static final int DIALOG = 0;
private static String TAG="LoginActivity";
private ProgressDialog progressDialog;

private final Handler handler =  new Handler() {
    public void handleMessage(Message msg) {

        int state = msg.arg1;
        if (state != 0)
        {
            Log.i(TAG, "dialog dismissed, message received "+state);
            dismissDialog(DIALOG);
        }

    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.login);

    View loginButton = findViewById(R.id.login_button);
    loginButton.setOnClickListener(this);

}

public void onClick(View v) {

    switch (v.getId()) {
    case R.id.login_button:
        Log.i(TAG,"login button");
        showDialog(DIALOG);

        Intent i = new Intent(this, PTVActivity.class);
        startActivity(i);
        break;

    }
}

protected Dialog onCreateDialog(int id)
{
    switch(id) {
    case DIALOG:
        progressDialog = new ProgressDialog(Login.this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage(getString(R.string.login_progress));
        return progressDialog;
    default:
        return null;
    }
}

@Override
protected void onPrepareDialog(int id, Dialog dialog) {
    switch(id) {
    case DIALOG:

        EditText nameText=(EditText)findViewById(R.id.login_name);
        EditText pwText=(EditText)findViewById(R.id.password);
        String name = nameText.getText().toString();
        String pw = pwText.getText().toString();

        CommunicateServer communicate= new CommunicateServer(name,pw,handler);
        communicate.run();
    }

}

}

and here is the run() method of my CommunicateServer class:
@Override
public void run() {

    Message msg = handler.obtainMessage();
    if (login()==true)msg.arg1 = 1;
    else msg.arg1 = -1;
    handler.sendMessage(msg);

}

A: To create a new Intent and start an activity you have to do following:
Intent intent = new Intent(Login.this, anotherActivity.class);
startActivity(intent);

The simplest way of handling this type of work is to use AsyncTask (example):
In your case you have to show a Progress dialog in onPreExecute() method of AsyncTask.
In the doInBackground(..) you will be making a server call for authentication. You have to return the status (1 or -1) from doInBackground(..) method.
Finally you will get the status value (1 or -1) in onPostExecute(..) method as a parameter. Here you will be taking decision based on the status. If it is 1 you will be creating a new intent to open an Activity. You should also dismiss the progress dialog in this method.


text:
Q: Where to store files for admin to download in Django? I have some example files that I want to serve in a download link to all admins. They are not model dependant or user dependant (other than requiring admin). They're txt files and the same files must be available to all admins. I cannot find anything about this in the docs, or maybe I don't know what to look for. As far as I understand only css, js and images are static files, so should txt files be in /media/?
Where can I put these files so only admins can download them? Right now I have a hard coded link in my custom admin template to /media/admin/examples/data_template.txt, but anyone can get to this link. I have these configs in settings.py:
STATIC_URL = '/static/'
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)
STATIC_ROOT = os.path.join(BASE_DIR, 'assets')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

Edit: I have also tried putting it in the admin static directory so I load it into the template with {% load static %} and href="{% static 'admin/example_files/data_template.txt' %}" - but I can still use the download link when logged out. I'm in development, obviously. Is it supposed to be like that?

A: so static files are those files that are usually part of your code, or part of your dependencies' code. They could be javascript and CSS files, images for your web pages, etc.
Media files however are usually files that are uploaded by users or generated by your application during the life of your Django project. They are typically not stored in source control (like static files are). Basically, anything which is going into a FileField, ImageField is classified as media storage.
In your case, you can create a model with a file field and then add all the text files to that model. That will store these files in the media root. Then you can create a view wherein you check if the user is an admin or not, if yes then they can view, download those files.


text:
Q: A normal divided by $\sqrt{\chi^2(s)/s}$ If $Z \sim N(0,1)$ and $X \sim \chi^2(s)$.  If $Z$ and $X$ are independently distributed then the variable $Y = \frac{Z}{\sqrt{X/s}}$ follows a $t$ distribution with degrees of freedom $s$.
What happens if $Z \sim N(a,b)$?
Does it simply become a location scale t distribution with mean = a,  s.d. = $\sqrt{b}$ still with s degrees of freedom?

A: Not quite.
If $Z \sim \mathcal N(a, b)$,
then note that $Z' = \frac{Z - a}{\sqrt b} \sim \mathcal N(0, 1)$.
Then $Y = \frac{Z'}{\sqrt{X / s}} \sim \mathcal T(s)$.
Now, your proposed location-scale t distribution is $\sqrt b Y + a$. But that is
$$\sqrt b Y + a = \frac{\sqrt b Z'}{\sqrt{X / s}} + a = \frac{\sqrt b Z' + a \sqrt{X / s}}{\sqrt{X / s}} \ne \frac{\sqrt b Z' + a}{\sqrt{X / s}} = \frac{Z}{\sqrt{X / s}}.$$
The variable that you care about is instead a scaled noncentral t-distribution, with $s$ degrees of freedom, noncentrality parameter $a / \sqrt b$, and then scaled by $\sqrt b$:
$$
\frac{Z}{\sqrt{X / s}}
= \frac{\sqrt b Z' + a}{\sqrt{X / s}}
= \sqrt{b} \left( \frac{Z' + a/\sqrt{b}}{\sqrt{X / s}} \right)
.$$


text:
Q: jQuery selectors and .each() Why are the objects returned by a selector (for example $("div")) different from the objects you get by looping through the result of the selector with the .each() function?  I do not think I understand the exact semantics of either function.  Could someone clarify why they are different?  In particular if I form an array manually, why can I not call the same methods on objects of that array?
For example printing the values in the array for the two cases yields different results
array = $("div")

and
array = [];
$.each($("div"), function(index, value) {
    array.push(value);
});

Note
Turns out that they are in fact the same.  The difference was being cause for some reason because of the browser cache.  Cleaning up the cache made this work

A: Within your function, you can call this to reference to the element that function applies to!
You can wrap $() around this ($(this)) if you feel more comfortable working with jQuery objects.
The index parameter of your function corresponds with the position of the element in the list of selected elements.
The value parameter of your function corresponds with the element, which basically means that this and value have the same value.

Demo

var data = [];
$.each($("div"), function(index, value) {
    data.push({
        'index' : index,
        'this' : $(this).attr("id"),
        'value' : $(value).attr("id")
    });
});

document.body.innerHTML = '
' + JSON.stringify(data, undefined, 2) + '
';

     Hello

     World


text:
Q: How to split and modify a string in NodeJS? I have a string :
var str = "123, 124, 234,252";

I want to parse each item after split and increment 1. So I will have:
var arr = [124, 125, 235, 253 ];

How can I do that in NodeJS?

A: var str = "123, 124, 234,252";
var arr = str.split(",");
for(var i=0;i<arr.length;i++) {
    arr[i] = ++arr[i];
}

A: Use split and map function:
var str = "123, 124, 234,252";
var arr = str.split(",");
arr = arr.map(function (val) { return +val + 1; });

Notice +val - string is casted to a number.
Or shorter:
var str = "123, 124, 234,252";
var arr = str.split(",").map(function (val) { return +val + 1; });

edit 2015.07.29
Today I'd advise against using + operator to cast variable to a number. Instead I'd go with a more explicit but also more readable Number call:

var str = "123, 124, 234,252";
var arr = str.split(",").map(function (val) {
  return Number(val) + 1;
});
console.log(arr);

edit 2017.03.09
ECMAScript 2015 introduced arrow function so it could be used instead to make the code more concise:

var str = "123, 124, 234,252";
var arr = str.split(",").map(val => Number(val) + 1);
console.log(arr);

A: If you're using lodash and in the mood for a too-cute-for-its-own-good one-liner:
_.map(_.words('123, 124, 234,252'), _.add.bind(1, 1));

It's surprisingly robust thanks to lodash's powerful parsing capabilities.
If you want one that will also clean non-digit characters out of the string (and is easier to follow...and not quite so cutesy):
_.chain('123, 124, 234,252, n301')
   .replace(/[^\d,]/g, '')
   .words()
   .map(_.partial(_.add, 1))
   .value();

2017 edit:
I no longer recommend my previous solution. Besides being overkill and already easy to do without a third-party library, it makes use of _.chain, which has a variety of issues. Here's the solution I would now recommend:
const str = '123, 124, 234,252';
const arr = str.split(',').map(n => parseInt(n, 10) + 1);

My old answer is still correct, so I'll leave it for the record, but there's no need to use it nowadays.


text:
Q: Docker Neo4j Container keeps stopping - how to debug? We have a neo4j container and it keeps stopping.
There are 3 other containers (node servers) running on the box as well. It's on a dev box so it is low spec - only 588MB RAM- so I suspect that it keeps running out of memory.
But how do I verify why it keeps stopping?  Its only ever the neo container that stops. We launch it with:
$NEO4J_HOME/bin/neo4j console

I suspect its the neo4j process itself that is exiting, thus closing the container.
Any tips on debugging this?

A: You can check the log files, which are by default in the data/log subdirectory of your neo4j installation directory.

A: If you start it with
docker run --name <container_name> ... neo4j`

as official man propose, you can check errors with docker logs <container_name>
Also you can start it with additional volume
--volume=/path/to/logs:/logs

and check them


text:
Q: Best way for Data storage I have a Tabel with Buttons, 9 rows and 5 columns -> 45 Buttons. Each Button sould have the properties:
row, week, time, day, name, description, colour, room.
What is the best way for the storage? Do I have to use the complicated SQLite, or is there a easier solution? I'm new in Android, therefore SQLite is not easy for me.

A: Personally I would take some time to implement a ContentProvider and use a SQLite db...
However, you can use a lot of different approaches, you can save all your information in a private file (so you can format them as you wish) or use the SharedPreferences mechanism.
You should have a look here to read about the different methods

A: Assuming that it is static set of 45 buttons and does not require permanent persistence. There are two days you can solve it

*

*Extend Button class and define the properties you need

*Use setTag to store carry in-memory data objects along with view objects. So in your case create a Bundle object for each button and store it in the button view with setTag.


text:
Q: Execute script with COM in the background using php Hello I want to run script using COM in the background.
Here is my code:
$WshShell = new COM("WScript.Shell");
$obj = $WshShell->Run("cscript C:/Users/Administrator/Desktop/PhotoshopImg/script.vbs", 0, true);

I want to run the script in the background.
Its possible?
Thanks you :)

A: Given how PHP scripts are often run using Apache/Ngnix server, and are used to server content, my answer is: no. It's not possible.
However, you might use queuing solutions like redis or rabbitMq to schedule/run some jobs, which might be thought of "in the background", even though they are just separate PHP processes.


text:
Q: Open GUI apps on a Ubuntu 16.04 machine via SSH from an Ubuntu 14.04 machine I'm trying to open GUI apps (gedit/nautilus/firefox) on a 16.04 machine via SSH from a 14.04 machine. The command I use is:
ssh -X username@ipaddress

and then, for example:
nautilus

However, it doesn't open the app and says
Segmentation fault (core dumped)

It doesn't say anything else, just that. Can someone help me resolve this?

A: The accepted answer works, however according to Launchpad Bugs, the real cause is libepoxy.  libepoxy has been fixed since early 2017, but as of June 2017, it is not available as an updated package for 16.04.  I followed the instructions by Raj Bhattacharjea to fix this issue. Specifically:

*

*Downloaded the Zesty (17.04) libepoxy for my architecture from
https://packages.ubuntu.com/zesty/libs/libepoxy0 (for me it was
amd64).

*sudo dpkg -i libepoxy0_1.3.1-1ubuntu1_amd64.deb (or your architecture version)

Problem solved. As much as I don't like using a package from another version, this seems like the cleaner solution, especially since I don't have to worry about my link breaking if I change NVidia versions.

A: I had the same problem. I ran strace with meld and gedit and it indicated that for some reason there was problem finding libGLX_indirect.so.0 library. I attempted a fix by placing relevant symbolic link inside /usr/lib/x86_64-linux-gnu folder:
sudo ln -s /usr/lib/nvidia-361/libGLX_indirect.so.0

and it works now. Would like to know what is the preferred way of fixing it.


text:
Q: Using twisted.internet.reactor inside a Protocol subclass I am new to twisted and I am trying to understand the design patterns for asynchronous programming in general and twisted in particular. From a design standpoint, is it a good idea to access the reactor from a Protocol subclass as follows:
class A(Protocol):
   def __init__(self):
      reactor.callLater(5, function_not_defined_here)

A: Yes, that's absolutely standard. You can call reactor methods from anywhere in your application (pre or post reactor.run()). The only exception being when using threads, in which case you'll want to wrap your reactor method calls in reactor.callFromThread(), eg:
reactor.callFromThread(reactor.callLater, 5, function_not_defined_here)

A: You might consider several adjustments to this:

*

*Accept the reactor as an argument.  This makes your code more easily testable, since it means you can pass in a fake reactor in your unit tests which is independent of real time and can be inspected to verify A behaves as intended.

*Don't discard the result of reactor.callLater.  Save it as an attribute on the A instance so that you can use it later if necessary.  For example, you may want to cancel it (consider the case where the A instance loses its connection before the delayed call runs).

*Don't call reactor.callLater in A.__init__.  Instead, call it in A.connectionMade.  This one depends a bit on why you're using a delayed call at all, but it's much more likely that you want to do something some time after the connection is established, rather than some time after the protocol is instantiated.  This also lets you have an A instance that isn't messing around with the reactor yet (which is another thing you might want to do in your unit tests).


text:
Q: Create list of object in python I have to create a list of Student which contain name and roll number of student
but when i am creating new object of class student ad appending it to my list every object in list are changed and getting same data for all student
what should i do??
Code:
class Student:
    name = 'abc'
    roll_no = 1

    def print_info (self):
        print(Student.name,"\t",Student.roll_no)

    def input_info (self):
        Student.roll_no = int(input("Enter Student roll number  "))
        Student.name = input("Enter Student name  ")

ch=1
students = []

while ch!=3:
    print("1.Create new Student\n2. Display students\n3.Exit")
    ch=int(input("Enter choice\t"))`enter code here`
    if ch==1 :
        tmp=Student()
        tmp.input_info()
        students.append(tmp)
    elif ch==2:
        print("---Students Details---")
        print("Name\tRoll No")
    for i in students:
        i.print_info()

Output:
Output of code

A: The syntax for the append method is as follow:
list.append(obj)

So you should replace students.append() by:
students.append(tmp)

Moreover, your print_info and input_info methods are not displaying the properties of a given student, but the properties of the class Student itself (which are always the same for every instance of the class). You should fix that.


text:
Q: Update/Insert into table I have to update table on SQL Server but first i have to check for existing data in table so if data is there update it, if not make a new insert:
cmd_sql.CommandText = " SELECT BrDok as id_dok " +
                      " FROM ordersstavke " +
                      " WHERE SifParFil = '" + rw_mat["sifskl_kor"] + "'" +
                      " AND DokumentTip = '" + rw_mat["vrst_dok"] + "'";

MySqlDataAdapter sql_adapter = new MySqlDataAdapter(cmd_sql);
DataSet dt_dok = new DataSet("DOK_MAT_EXCHANGE");
sql_adapter.Fill(dt_dok);

if (dt_dok.Tables["DOK_MAT_EXCHANGE"].Rows.Count == 0)
{
   myQuery = " INSERT INTO ordersstavke (BrDok, DocumentTip, SifParFil) " +
             " VALUES ('" + rw_mat["brdok"] + "', '" +
                            rw_mat["vrst_dok"] + "', '" +
                            rw_mat["sifskl_kor"] + "')";
}
else
{
    UPDATE DATA
}

But I have an error in the code, the error is here if (dt_dok.Tables["DOK_MAT_EXCHANGE"].Rows.Count == 0)

Object reference not set to an instance of an object.

The problem is in this if statement...

A: DOK_MAT_EXCHANGE is the name of the DataSet, not of the first table.
You should test with
if (dt_dok.Tables[0].Rows.Count == 0)

Also, I think is better to use a syntax like this to discover how many records are presents
cmd_sql.CommandText = "SELECT COUNT(BrDok) as id_dok " +
                      " FROM ordersstavke " +
                      " WHERE SifParFil = ?p1 " +
                      " AND DokumentTip = ?p2";
cmd_sql.Parameters.AddWithValue("?p1", rw_mat["sifskl_kor"] );
cmd_sql.Parameters.AddWithValue("?p2", rw_mat["vrst_dok"] );
int rowCount = (Int32)cmd_sql.ExecuteScalar();

A: change
DataSet dt_dok = new DataSet("DOK_MAT_EXCHANGE");

to
DataSet dt_dok = new DataSet("ordersstavke ");

and
if (dt_dok.Tables["DOK_MAT_EXCHANGE"].Rows.Count == 0)

to
if (dt_dok.Tables["ordersstavke "].Rows.Count == 0)

A: Accessing the first table via the dataset name is incorrect, that's for setting the XML.
Instead use
dt_dok.Tables[0].Rows.Count;

That being said, you're better off writing this as a single SQL statement instead of a separate select && insert.  This way you're not going to the DB multiple times.
var sql = @"if exists(select * from ordersstavke where SifParFil = ? and DokumentTip = ?)
then
 -- do insert statement
else
 -- do update
end if";

This might also be better done with a stored proc, so you don't have as much SQL code in C#.  It's easier to manage multiple operations that way.
And for crying out loud, use SqlParameters, not string concatenation! That's just asking for trouble!

A: Ok, thanks guys, I wrote it like this
if (ds_dok.Tables[0].Rows.Count <= 0)
                    {
                        myQuery = " INSERT INTO ordersstavke (BrDok, " +
                                  " SifParFil) " +
                                  " VALUES ('" + rw_mat["brdok"] + "', '" +
                                                 rw_mat["sifskl_kor"] + "')";
                    }
                    else if (ds_dok.Tables[0].Rows.Count >= 1)
                    {

                        myQuery = "UPDATE ordersstavke " +
                                  "SET BrDok = '" + rw_mat["brdok"] + "', " +
                                  "SifParFil = '" + rw_mat["sifskl_kor"] + "', " +
                                  "WHERE BrDok = " + ds_dok.Tables["ordersstavke"].Rows[0]["BrDok"].ToString() + "'";

                    }

But there is a small problem in the section update: s_dok.Tables["ordersstavke"].Rows[0]["BrDok"].ToString(), here it give me that loving error : Object reference not set to an instance of an object.
Maybe the update on MySQL goes on different way, I'm referencing on example on sql server and there update goes differently


text:
Q: How to run dbunit task in ant? It doesn't work in ant,
I'd like to run some classes that extend DatabaseTestCase
<path id="libs.dir">
                <fileset dir="lib" includes="**/*.jar" />
</path>
<taskdef name="dbunit"
         classname="org.dbunit.ant.DbUnitTask"/>

<!-- run all tests in the source tree -->
<junit printsummary="yes" haltonfailure="yes">
  <formatter type="xml"/>
  <batchtest fork="yes" todir="${reports.tests}">
    <fileset dir="${src.tests}">
      <include name="**/*Test*.java"/>
    </fileset>
  </batchtest>
</junit>

It says the following:
Buildfile: D:\kariakin\jdbc_task\build.xml

BUILD FAILED
D:\kariakin\jdbc_task\build.xml:15: taskdef class org.dbunit.ant.DbUnitTask cannot be found
 using the classloader AntClassLoader[]

A: I think the problem is your taskdef, it's missing the path containing the dbunit jar:
<taskdef name="dbunit" classname="org.dbunit.ant.DbUnitTask" classpathref="libs.dir"/>