text:
Q: lodash - is there a method to filter by array of single property? const buttons = [
  { id: 1, text: 'First' },
  { id: 2, text: 'Second' },
  { id: 3, text: 'Third' }
]

const activeButtonIds = [1, 3]

Using lodash, I want to filter out all buttons with ids not included within activeButtonIds = [1, 3].
The obvious way of doing that is:
_.filter(buttons, ({ id }) => _.includes(activeButtonIds, id))
But I was wondering, is there a simpler way of achieving the same thing? A built-in function for this within lodash?

A: You can use _.intersectionWith() to find items that are included in both arrays using a comperator function:

const buttons = [{"id":1,"text":"First"},{"id":2,"text":"Second"},{"id":3,"text":"Third"}]
const activeButtonIds = [1, 3]

const result = _.intersectionWith(buttons, activeButtonIds, (button, activeId) =>
  button.id === activeId
)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to log plugin errors to plugin error_log file How can errors, specific to a given plugin, be logged to an error_log file contained within the plugin root folder itself?
Examples:

*

*Syntax errors

*Database errors

*Compatibility errors

*PHP fatal errors

*Ajax request errors

Similar to the /wp-content/debug.log file enable when WP_DEBUG_LOG is defined as true in the wp-config.php file (albeit specifically for plugins with its concerns separated from any other general error unrelated to the plugin itself).
Research:
Debugging Plugins section in the official documentation of the Codex refers to using 3rd party plugins to debug 3rd party plugins.
Don't Develop Without Debuggingby Smashing Magazine refers to site-wide general debugging.
Plugin Handbook appears to layout no specific guidelines.

A: By setting the second argument to 3 for error_log:
$pluginlog = plugin_dir_path(__FILE__).'debug.log';
$message = 'SOME ERROR'.PHP_EOL;
error_log($message, 3, $pluginlog);

http://php.net/manual/en/function.error-log.php


text:
Q: Insert wrong date in MongoDB I am tring to save dates in my MongoDB table using C#.
Here is a JavaScript logic that send data using Ajax to C# controller
$(function ($, w, d) {
    var _user = {}
    //var time =    moment("2016-04-02", "YYYYMMDD").fromNow()
    //var bime =    moment().endOf('day').fromNow();
    //var crime =   moment("20120620", "YYYYMMDD").fromNow();
    //              document.getElementById('time').innerHTML = time;
    var obj = {};
    var holidaylist = ["Mar-31-2018", "Apr-01-2018","Apr-04-2018","Apr-07-2018","Apr-08-2018"];
    var  startdate = new Date("Apr-02-2018");

    obj.endDate = "Apr-06-2018";
    obj.holidaylist = holidaylist;
    obj.NumberOfCount = 9;
    CallAjax("POST", '/LeaveManagement/', 'checkleavelogic', obj, onsuccessaddemployee, '');

here is the C# logic that saves the data in MongoDB:
public JsonResult checkLeaveLogic(LeaveLogicModel leaveLogic)
{
    string strconnectiomstring = "mongodb://10.10.32.125:27017";
    MongoClient Client = new MongoClient(strconnectiomstring);
    var DB = Client.GetDatabase("TimeClock");

    List<DateTime> leavesDate = new List<DateTime>();
    var collection = DB.GetCollection<LeaveLogicModel>("leaves1");
    collection.InsertOne(leaveLogic);
}

Now this is the MongoDB table that saves as a previous date.

Here you can see that my StartDate is Apr-02-2018 but it saves as Apr-01-2018 and for all date it is the same.
Can someone tell me where I am wrong?

A: When you create new dates with just date or date and time, it usually creates them in the same timezone as the program is.
So if you dont specify the timezone, it becomes the timezone the server is in. When you save to Mongo, the Date is serialized to UTC -> zero timezone.
Create the dates with +00:00 timezone and you should have consistent data.

A: It's a good practice to set your datetimes to UTC, however if you want to convert it, you can use something like this.
       var date = DateTime.UtcNow;
       TimeZoneInfo.ConvertTime(date, TimeZoneInfo.Local);


text:
Q: How can I copy data from an external HDD that is about to fail? I have an external HDD that is about to fail. I want to copy as much as I can to a new external HDD before it completely dies. I've been able to start copying files for a few minutes before the drive starts turning off and on repeatedly and clicking.
Is there a (preferably free) Mac application that can copy files off an about-to-fail hard drive, handle the drive suddenly disappearing, and continue where it left off when the drive is reconnected?
Or do you have any other tips that might help? I've heard rumours about putting a drive in the freezer. Do you think that might help, or is it more likely to kill the drive?

A: I would try using rsync from the command line.
rsync -av --ignore-errors /Volumes/failingDrive/ /Volumes/brandNewDrive

should do the trick. Mind the trailing / at the end of the source. Rsync will not copy files it finds on the destination, so if you call it a second time it will continue where it left off.

A: And oddly enough a possible solution that involves no software at all, just your freezer.
Double or triple bag your HD (to keep ALL moisture out) and put it in the freezer for a couple of hours.
Then plug it into your Mac and see if you get a longer useful life (15 min instead of 5 or 10) out of it.
Often times HD issues are exacerbated by heat. Keeping the drive as cold as possible will SOMETIMES delay the heat related failures and allow you to get the necessary data off the drive.
Just be careful to keep the drive DRY as moisture will kill the drive faster than heat. And kill it permanently. So watch for condensation on the newly "frozen" HD.


text:
Q: When is power and bandwidth shared among USB ports? I'd like to know when power and bandwidth is shared among USB ports on a PC.
Let me give an example and please correct me where I may be wrong:
I have a PC with 5 USB ports: three are USB 3.0 and two are USB 2.0.
My understanding is that:
If you plug two USB Hard Drives to two of the USB 3.0 ports:
If they're plugged to USB 3.0 ports on the same internal Root Hub, they'll share power and bandwidth.
If they're plugged to USB 3.0 ports on different internal Root Hubs, they will each get the full speed and power.
If one is plugged to a USB 3.0 port and the other to a USB 2.0 port, they won't share the power and speed, as USB 3 ports and USB ports always hook to different root hubs, although the USB 2 port will deliver less power and speed.
…if this is true, then I should check device manager to learn which ports are hooked to which Root Hubs.
Any clarification much appreciated

A: As per the specifications (at Wikipedia)
Each USB 2.0 EXTERNAL port is supposed to provide upto 500 mA of current.
Each USB 3.0 EXTERNAL port is supposed to provide upto 900 mA of current.

If they're plugged to USB 3.0 ports on the same internal Root Hub, they'll share power and bandwidth.

Even if the are connected to USB3 ports on the SAME internal Root Hubs, each port should have 900 mA of current available separately.
Whether or not they will share bandwidth, will depend on the internal architecture of the system.
There is a discussion here:
More than 5Gbps bandwidth reported from a USB3.0 / USB3.1 Gen 1 Root Hub, how is it possible?
https://electronics.stackexchange.com/questions/403090/how-to-determine-bandwidth-available-at-usb-ports


text:
Q: Bootstrap Modal not working inside mdl-layout__content I have a project where I, have existing Bootstrap code and now we are migrating to material design lite. Everything work fine in bootstrap code as well as MDL. The main layout page has rendering class as

            Procument

                    search

                    <input class="mdl-textfield__input" type="text" name="sample"
                           id="fixed-header-drawer-exp">

                hello@example.com

                <button id="accbtn" class="mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--icon">

                    arrow_drop_down

                    Accounts

                </button>

hello@example.com

info@example.com

addAdd another account...

            homeDashboard

            inboxUpload

            deleteReport

            help_outlineHelp

        @RenderBody()

The modal doesnot work on mdl-layout__content as I, have tried with MDL modal also. The limitation of modal is that it need to be direct child of body. However I, am using bootstrap modal the modal appears in screen but it overlay on the screen.
Here is the code for the modal
@{
    ViewBag.Title = "Report";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
    <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
        Launch demo modal
    </button>

Modal title

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        ×
                    </button>

                    ...

                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary">Save changes</button>

I, have many page with each page their is the modal required. I, can't add all modal to the layout file.
The main cause of error is mdl-layout__content class. If I don't include this class my design is not looking good.
How can I solve this issue.
Here are the few issue raised by the people
https://github.com/google/material-design-lite/issues/4038
Here is the screen shot

CSS from MDL File
 .mdl-layout__drawer.is-visible {
    -webkit-transform: translateX(0);
            transform: translateX(0); }
    .mdl-layout__drawer.is-visible ~ .mdl-layout__content.mdl-layout__content {
      overflow: hidden; }
.mdl-layout__content {
  -ms-flex: 0 1 auto;
  position: relative;
  display: inline-block;
  overflow-y: auto;
  overflow-x: hidden;
  -webkit-flex-grow: 1;
      -ms-flex-positive: 1;
          flex-grow: 1;
  z-index: 1;
  -webkit-overflow-scrolling: touch; }
  .mdl-layout--fixed-drawer > .mdl-layout__content {
    margin-left: 240px; }
  .mdl-layout__container.has-scrolling-header .mdl-layout__content {
    overflow: visible; }
  @media screen and (max-width: 1024px) {
    .mdl-layout--fixed-drawer > .mdl-layout__content {
      margin-left: 0; }
    .mdl-layout__container.has-scrolling-header .mdl-layout__content {
      overflow-y: auto;
      overflow-x: hidden; } }

You can find the whole css file here


text:
Q: Inspect a given route to determine if it has a subdomain constraint I'm building a Rails app that has a merchant subdomain. I have these two routes:
get '/about', controller: :marketing, action: :about, as: :about
get '/about', controller: :merchant, action: :about, constraints: { subdomain: 'merchant' }, as: :merchant_about

But when I use their URL helpers both merchant_about_url and about_url result in http://example.com/about.
I know I can specify the subdomain argument on the helper to prefix the URL with the subdomain, but since these URLs are going to be frequently used in various cases I'd like to build a wrapper for this helper to make it smarter.
My question: Can I inspect a given route to see if it has a subdomain constraint?
If I can, I'd like to do something like the following:
def smart_url(route_name, opts={})
  if # route_name has subdomain constraint
    opts.merge!({ subdomain: 'merchant' })
  end

  send("#{route_name}_url", opts)
end

In doing this, I can effectively call:
smart_url('about')          # http://example.com/about
smart_url('merchant_about') # http://merchant.example.com/about

Is this possible?

A:
Can I inspect a given route to see if it has a subdomain constraint?

Yes, that is possible. You need to use Rails' routes API to get info about the route.
def smart_url(route_name, opts={})
  route = Rails.application.routes.routes.detect {|r| r.name == route_name }

  if opts.is_a? Hash && route&.constraints[:subdomain]
    opts.merge!({ subdomain: 'merchant' })
  end

  send("#{route_name}_url", opts)
end

The above searches a route by its name, and inspects its constraints if the route is found.

A: you can create class under lib folder like this
class Subdomain
    def self.matches?(request)
        case request.subdomain
        when SUB_DOMAIN_NAME
          true
        else
          false
        end
    end
end

and in your routes.rb file create routes like this
constraints(Subdomain) do
    get '/about', to: 'marketings#about', as: :about
end

get '/about', to: 'marketings#about', as: :merchant_about


text:
Q: Plone: Registry dict field with multiple fields values I have an interface:
class ISomething(Interface):
    something = schema.Dict(
        title=u"Something",
        description=u"Define something.",
        key_type=schema.TextLine(title=u"Some Title"),
        value_type=schema.Text(title=u"Some Text"))

used to create a form that saves values in registry (ControlPanelFormWrapper, RegistryEditForm).
In registry.xml:
<record name="something">
  <field type="plone.registry.field.Dict">
    <title>Something</title>
    <key_type type="plone.registry.field.TextLine" />
    <value_type type="plone.registry.field.Text" />
  </field>
</record>

It's working: I can add key-value items {'Some Title': 'Some Text'}.
I need to modify my form to have multiple fields instead of Some text, but keeping the Dict. Example:
{'Some Title': {
    'field_1': 'Value 1',
    'field_2': 'Value 2'
    }
 }
I expect this to work then:
registry = getUtility(IRegistry)
reg_something = registry.get("something")
print reg_something['Some Title']['field_1']

>>> Value 1

So, how to change my interface and registry record to have the form updated in this way?

A: This is described in an article from Mark van Lent:
https://www.vlent.nl/weblog/2011/09/07/dict-list-value-ploneappregistry/
Adjust the registry.xml accordingly, exchange the record-name with yours:
<record name="my.package.example">
 <field type="plone.registry.field.Dict">
   <title>Verification filesnames</title>
   <key_type type="plone.registry.field.TextLine">
     <title>Key</title>
   </key_type>
   <value_type type="plone.registry.field.List">
     <title>Value list</title>
     <value_type type="plone.registry.field.TextLine">
       <title>Values</title>
     </value_type>
   </value_type>
 </field>
 <value purge="false" />

See also this question where Luca Fabbri and Gil Forcada each provide alternative approaches, which might be true time-savers on the long term:
Plone- How can I create a control panel for a record in registry that is a dictionary type?

A: registry.xml in my default profile (imported with an upgrade step):
<registry>
  <records interface="my.package.something.ISomethingItems">

    <record name="mypackage_multiplesomething">
      <field type="plone.registry.field.List">
        <title>Something Items</title>
        <value_type type="collective.z3cform.datagridfield.DictRow">
          <schema>my.package.something.ISomething</schema>
        </value_type>
      </field>
    </record>
  </records>
</registry>

In something.py just define the interfaces:
from collective.z3cform.datagridfield import BlockDataGridFieldFactory
from collective.z3cform.datagridfield.registry import DictRow
from plone import api
from plone.app.registry.browser.controlpanel import ControlPanelFormWrapper
from plone.app.registry.browser.controlpanel import RegistryEditForm
from plone.autoform import directives
from zope import schema
from zope.interface import Interface
from zope.interface import implementer
from zope.schema.interfaces import IVocabularyFactory
from zope.schema.vocabulary import SimpleTerm
from zope.schema.vocabulary import SimpleVocabulary

class ISomething(Interface):
    id = schema.ASCIILine(
        title=u"Something ID",
        description=u"Some description."
    )

    text = schema.Text(
        title=u"A text field",
        description=u"Human readable text"
    )

    url = schema.URI(
        title=u"An URL",
        description=u"Don't forget http:// or https://"
    )

class ISomethingItems(Interface):
    # the field is the same used in registry.xml
    mypackage_multiplesomething = schema.List(
        title=u"Something Items",
        description=u"Define something items",
        value_type=DictRow(title=u"Something", schema=ISomething)
    )
    directives.widget(mypackage_multiplesomething=BlockDataGridFieldFactory)

Now we can have an edit form (in something.py):
class SomethingItemsEditForm(RegistryEditForm):

    schema = ISomethingItems
    label = u"Something items definition"

class SomethingItemsView(ControlPanelFormWrapper):
    """ Something items edit form """

    form = SomethingItemsEditForm

defined as browser page (configure.zcml):
  <browser:page
    name="something-items-settings"
    for="Products.CMFPlone.interfaces.IPloneSiteRoot"
    class=".something.SomethingItemsView"
    permission="cmf.ManagePortal"
    />

Easy to get the values from registry using api:
>>> from plone import api
>>> reg_something_items = api.portal.get_registry_record(
    'mypackage_somethingitems', interface=ISomethingItems)
[{'id': 'some id', 'text': 'some text', 'url': 'http://something.com'}, {'id': 'some id other', 'text': 'some text other', 'url': 'http://something-other.com'}]
>>> item = reg_something_items[0]
{'id': 'some id', 'text': 'some text', 'url': 'http://something.com'}
>>> item['id']
some id
>>> item['text']
some text
>>> item['url']
http://something.com

If you added an uninstall profile to your product it is a good idea to add registry.xml in it:
<registry>
  <record name="my.package.something.ISomethingItems.mypackage_somethingitems"
          delete="True" remove="True" />

</registry>

to be sure the registry will be clean after uninstall.
You can check anytime the values you have in registry in SITE/portal_registry (Site Setup -> Configuration Registry)


text:
Q: Java Swing GUI hour glass There is a JTabbedPane In my Swing program.
When user clicks on a tab, the program takes a while to get the data and process the results, then shows the results in the selected tab.
How can I display a hour glass, or something of that effect so that user knows it's processing data? Not to click on the tab again before it finishes it job.

A: A JProgressBar (possibly in indetermiante mode) sounds right - put that on the tab until the data has been fetched. A well-designed UI shouldn't force the user to wait for long-running tasks to complete and instead allow them to do something else inbetween.

A: setCursor(int) is deprecated. This is probably a bit cleaner:
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

A: The simplest way is to just call setCursor on the appropriate component (probably the top-level window) with the appropriate Cursor.
component.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

And then set it back when you are done.
component.setCursor(Cursor.getDefaultCursor());

A: As the other answers mention, you can set a wait cursor, but you also mention preventing additional mouse clicks. You can use a glass pane to prevent clicks on components until the long operation is finished. In addition to the Sun tutorials on the glass pane, there is a nice example at http://www.java2s.com/Code/Java/Swing-JFC/DemonstrateuseofGlassPane.htm

A: I would as other mentioned

*

*Change the cursor

*Use a SwingWorker

*Display the progressbar or an animated image in the glasspane

*Hide the glasspane when the task is completed

*Restore the default cursor


text:
Q: Want to Add View Controllers to Tabbar items Hi i am currently working on an project which requires two tab bars one at top and second at bottom i have added these tab bars but the problem is i am stuck with navigating between viewcontrollers using those tab bars item. using tabbar
let tabbar1 = UITabBar() //Note that tabbar height is fixed to 49
view.addSubview(tabbar1)

tabbar1.translatesAutoresizingMaskIntoConstraints = false
tabbar1.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0.0).isActive = true
tabbar1.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0.0).isActive = true
tabbar1.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 0.0).isActive = true

let contacts = UITabBarItem(tabBarSystemItem: UITabBarItem.SystemItem.contacts, tag: 100)
let bookmarks = UITabBarItem(tabBarSystemItem: UITabBarItem.SystemItem.bookmarks, tag: 101)
tabbar1.setItems([contacts, bookmarks], animated: false)

let tabbar2 = UITabBar() //Note that tabbar height is fixed to 49
view.addSubview(tabbar2)

tabbar2.translatesAutoresizingMaskIntoConstraints = false
tabbar2.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0.0).isActive = true
tabbar2.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0.0).isActive = true
tabbar2.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: 0.0).isActive = true

let downloads = UITabBarItem(tabBarSystemItem: UITabBarItem.SystemItem.downloads, tag: 103)
let favorites = UITabBarItem(tabBarSystemItem: UITabBarItem.SystemItem.favorites, tag: 104)
tabbar2.setItems([downloads, favorites], animated: false)


text:
Q: Pulling from sqlite database in a First In First Out (FIFO) order Android Hello Stackoverflowers!
I created a simple sqlite DB like so.
//event table name
private static final String TABLE_EVENTS = "events";

//event table columns names
private static final String KEY_ID = "id";
private static final String KEY_EVENT = "event";

@Override
public void onCreate(SQLiteDatabase db)
{
//String to define our database
String CREATE_EVENT_TABLE = "CREATE TABLE " + TABLE_EVENTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_EVENT + " TEXT" + ")";

//create our database
db.execSQL(CREATE_EVENT_TABLE);
}

Which I understand to be a table with an id column and an event column.
in the event column I am storing a JSONObject converted to a string which I would like to retrieve from the table in FIFO(First in First Out) order, so that if my application crashes I can send the JSONObjects that I have stored next time the app is opened.
I can insert to the table without a problem using:
public void addEvent(JSONObject event)
{
    //get our database so we can add to it
    SQLiteDatabase db = this.getWritableDatabase();

    //define content values to store our values
    ContentValues values = new ContentValues();

    //add our event to the ContentValues
    values.put(KEY_EVENT, event.toString());

    //insert a row
    db.insert(TABLE_EVENTS, null, values);

    //close the database connection
    db.close();
}

I am having trouble querying for a specific row or event and getting the event from the database as well as a good method to keep track the order in which the events were inserted, so that I can pull them out in a FIFO order.
Sample code is especially helpful seeing as when I try to query I am getting syntax errors, and am not very familiar with SQLite.
Any help is much appreciated! Thank you for your time.

A: Hello VinC the best approach is to auto increment id, which is your primary key so you can do it by,
String CREATE_EVENT_TABLE = "CREATE TABLE " + TABLE_EVENTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_EVENT + " TEXT" + ")";

Now you can query database with orderby Id in Ascending order
database.query("TABLE_EVENTS", new String[]{"KEY_EVENT"},null,null, null, null,"KEY_ID ASC");

A: typically the first row inserted is at the top on the table so if you want to query the entire table with FIFO in your query you can set the sort order to be in ascending order by the row id, meaning the newest row will be at the bottom and the oldest at the top
getContentLoader().query(DATABASENAME,new String[] {ID,EVENT},null,null,ID+" COLLATE LOCALIZED ASC");

that way when you step through the cursor you will have the list in the order you want and you can do whatever you want with it
EDIT
in regards to the error you are getting you need to do this
if(cursor != null && cursor.moveToFirst()){
    do{
         String event = cursor.getString(0);
         //loops through all the elements in the cursor
    }while(cursor.moveTONext());
}
cursor.close();

this prevents force closes because it checks if the cursor is null (nothing in it) and the cursor gets moved to the first element

A: You could also have another field called "last_updated" which inserts a timestamp in milliseconds durring the insert. When you query for the cursor you could then sort by this field.


text:
Q: (Solr) more like this cause this error RSolr::Error::Http (RSolr::Error::Http - 404 Not Found I want to search my articles using more_like_this, my controller code looks is below. Also looked at this post, and tried ry /solr/select with mlt=on parameter, it doesn't work as well:
            article = Article.find(params[:id])
            @search = Sunspot.more_like_this(article) do
                fields :title
                minimum_term_frequency 1
                adjust_solr_params do |params|
                    params["mlt.match.include"] = true
                    params["mlt"] = 'on' # doesn't work
                    params["mlt"] = true # doesn't work
                end
            end

Request handler also set in my solrconfg.xml
    <requestHandler class="solr.MoreLikeThisHandler" name="/mlt">
           <lst name="defaults">
            <str name="mlt.mintf">1</str>
            <str name="mlt.mindf">2</str>
         </lst>
       </requestHandler>

Log:
RSolr::Error::Http (RSolr::Error::Http - 404 Not Found
Error: <title>Apache Tomcat/6.0.39 - Error report</title>
HTTP Status 404 - /solr/mlt

type Status report

message /solr/mlt

description The requested resource is not available.

Apache Tomcat/6.0.39

URI: http://localhost:8888/solr/mlt?wt=ruby
Request Headers: {"Content-Type"=>"application/x-www-form-urlencoded; charset=UTF-8"}
Request Data: "fq=type%3AArticle&mlt.mintf=1&q=id%3AArticle%5C+2144&mlt.fl=title_textv&start=0&rows=30&mlt.match.include=true"

Backtrace: /home/chuhai/shared/bundle/ruby/2.2.0/gems/rsolr-1.0.12/lib/rsolr/client.rb:284:in `adapt_response'
/home/chuhai/shared/bundle/ruby/2.2.0/gems/rsolr-1.0.12/lib/rsolr/client.rb:190:in `execute'
/home/chuhai/shared/bundle/ruby/2.2.0/gems/rsolr-1.0.12/lib/rsolr/client.rb:176:in `send_and_receive'
/home/chuhai/shared/bundle/ruby/2.2.0/gems/sunspot_rails-2.2.0/lib/sunspot/rails/solr_instrumentation.rb:16:in `block in send_and_receive_with_as_instrumentation'
/home/chuhai/shared/bundle/ruby/2.2.0/gems/activesupport-4.2.1/lib/active_support/notifications.rb:164:in `block in instrument'
/home/chuhai/shared/bundle/ruby/2.2.0/gems/activesupport-4.2.1/lib/active_support/notifications/instrumenter.rb:20:in `instrument'
/home/chuhai/shared/bundle/ruby/2.2.0/gems/activesupport-4.2.1/lib/active_support/notifications.rb:164:in `instrument'
/home/chuhai/shared/bundle/ruby/2.2.0/gems/sunspot_rails-2.2.0/lib/sunspot/rails/solr_instrumentation.rb:15:in `send_and_receive_with_as_instrumentation'
(eval):2:in `post'
/home/chuhai/shared/bundle/ruby/2.2.0/gems/sunspot-2.2.0/lib/sunspot/search/abstract_search.rb:49:in `execute'
/home/chuhai/shared/bundle/ruby/2.2.0/gems/sunspot-2.2.0/lib/sunspot/search/more_like_this_search.rb:16:in `execute'):
  app/controllers/api/v1/articles_controller.rb:9:in `search'
  lib/cors.rb:7:in `call'
  lib/cors.rb:7:in `call'


text:
Q: exim4 - email clients unable to retrieve emails I have configured exim4 on my Debian system and I am able to send emails from the server as a user and receive emails to this user. I am also able to connect mail client such as thunderbird/bluemail and I can use these to send emails but what I am unable to do is read them.
When I use i.e my Gmail account and send email to my @example email account it reaches the server, and the mail is saved in /home/user/new directory but I do not know why but either programs can not read those emails.

A: Exim is a mail transport agent.  It doesn't support POP, IMAP or other protocols commonly used for retrieval.  You probably need to look into installing something like Dovecot or some other IMAP daemon.
Some links that may be helpful.

*

*https://wiki.debian.org/Dovecot

*https://www.dovecot.org/

*https://blog.dskwrk.com/2015/12/09/Exim4-with-Dovecot-in-SSL-on-Debian-Jessie/


text:
Q: Why do I get a "not well-formed" error? This is my code:
$(document).ready(function(){
    /*========*\
    | RSS feed |
    \*========*/

    //Feed address
    var feed = "http://www.kelvinshadewing.net/feed.xml";

    $.ajax(feed, {
        accepts:{ xml: "application/rss+xml"},
        datatype: "xml",
        success: function(data){
            $(data).find("item").each(function(){
                var el = $(this);

                console.log("----------------");
                console.log("Title: " + el.find("title").text());
                console.log("Link: " + el.find("link").text());
                console.log("Description: " + el.find("description").text());
            });
        }
    });
});

For some reason, it keeps giving me an error that just says "not well-formed" and in the section that says where the error is, it says <unknown>:1:116, basically pointing to a position on a line that doesn't exist. Does anyone know what this is? As far as I can tell, everything else in the code is correct; in fact, apart from my own feed address, this code is copy-pasted from this tutorial.
Does anyone have any idea what this error means? I'm using Firefox, and my feed format is XML.

A: For some reason, removing the domain and changing the feed variable to just feed.xml, it's working properly now. That might have been the cross-domain issue that was mentioned, but it's all on the same domain, so I don't really know. Either way, it works now, so anyone else reading this should try changing their feed URL to a local one.


text:
Q: Checkbox not in same range in linear layout with programmatically in Android I have problem in creating programmatically layout in Android. Where I want to display in list with name with check box but check box little down and not in same horizontal range. Here is the my code:
mDialog.setContentView(R.layout.exmple);
    mDialog.setCancelable(true);
    mDialog.setTitle("Hobbies");
    mDialog.show();

    final LinearLayout mLinearLayout = (LinearLayout) mDialog
            .findViewById(R.id.linear);

    mLinearLayout.setOrientation(LinearLayout.VERTICAL);

    final Button okButton = new Button(this);

    final int size = hobbyList.size();

    LinearLayout[] mLinearLayout2 = new LinearLayout[size];
    LinearLayout[] mLinearLayout3 = new LinearLayout[size];

    Check = new CheckBox[size];
    Text = new TextView[size];

    for (int i = 0; i < size; i++) {

        Check[i] = new CheckBox(this);
        Text[i] = new TextView(this);
        mLinearLayout2[i] = new LinearLayout(this);
        mLinearLayout3[i] = new LinearLayout(this);

        Check[i].setId(i);

        Text[i].setText(hobbyList.get(i));

        Text[i].setTypeface(font_regular);
        Text[i].setTextColor(color.black);

        mLinearLayout2[i].addView(Text[i]);
        mLinearLayout3[i].addView(Check[i]);
        mLinearLayout2[i].setGravity(Gravity.LEFT);
        mLinearLayout3[i].setGravity(Gravity.RIGHT);

        mLinearLayout.addView(mLinearLayout2[i]);
        mLinearLayout.addView(mLinearLayout3[i]);
                }

    okButton.setText("OK");
    mLinearLayout.addView(okButton);

Here is the output pictures:

A: The problem is with the layout
mLinearLayout.setOrientation(LinearLayout.VERTICAL);
so the layouts are coming one after another so the checkbox is not in line
you can try having a one relative layout and placing the text and checkbox right and left it's far more easier than your current approach


text:
Q: Delete temp files on startup My program requires a temp folder to put data in while running. This data is not needed after exit of the program and should be deleted. Each running instance of the program needs one folder on its own.
If I use file.deleteOnExit(), this does not make sure the file gets deleted on crash of whatever kind. My idea thus is to check for old temp files on startup that didn't got deleted and remove them. But when starting another instance of the program it shouldn't delete the temp files of still running programs. How can I achieve this?
To be more specific: The temp files should be in the System's temp directory and should be deleted if the program exits normally. This question is only for the few times the program crashed. The program has to be OS-independent. A solution using the Path instead of the File classes is preferred.

A: Well, I suggest to create at start for each application a private directory where store temporary files say /var/run/myapp/tmp.
And at start delete the directory content:
void purgeDirectory(File dir) {
    for (File file: dir.listFiles()) {
        if (file.isDirectory()) purgeDirectory(file);
        file.delete();
    }
}

You remain free to delete the directory content at app exit, but in this way, even if at the exit cleanup were not done correctly you're sure to have an empty dir at startup.

A: Usually it is a bad idea to let your application to have multiple instances if you need to rely on other common resources, like temp file. For example, if you already have two instances of apps, the third one just opened will be hard to tell whether it is the third one and whether other instance is still alive.
As you have said, deleteOnExit() will not clean temp file if JVM crash and Java doesn't provide a reliable way to clean temp file automatically.
So I have following suggestions:

*

*If you can choose to make only one instance of application with multiple windows:

*

*You can have a fixed location and clean it when startup. But, in this way, you may give up some portability of Java.

*If your application is GUI application, you can create temp file through Java API and register some clean action on closing the main frame, etc. -- still fail to handle some crash situations

*you may add shutdownHook -- still fail to handle some crash situations

*If you insist on having multiple instances and your application is GUI application: have to use Java API to create temp file and may add listener or shutdownHook.


text:
Q: update-database: "A network-related or instance-specific error occurred while establishing a connection to SQL Server" I have a simple C# project. This is my connection string in my web.config for the database:
<connectionStrings>
   <add name="DefaultConnection"
        connectionString="Data Source=172.17.0.47;Initial Catalog=DevSystemListe;User ID=web_access;Password=123456"
        providerName="System.Data.SqlClient" />
</connectionStrings>

I already made sure that this connection is working. I can connect to my database from the Visual Studio with this connection and I can also see the tables and data.
When I want to update my database with update-database, this error occurs:

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

I uninstalled Entity Framework and then installed it again. Nothing changed.

A: I finally found out. I have a website project and my API in my solution. The problem was that the website was set as startup project. So that entity framework searched the connection string in the website's web.config and not in the api's web.config. Changing the startup project to my API solved the problem.
If you want to have the website project as startup project. Just copy the connection string into the websides web.config.
Nevertheless thanks for everyones help.

A: Also for migrations you can use OnConfiguring EntityFramework will check it by default.
Add this code to your DbContext.
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder.UseSqlServer(@"connection_string_here");
}

A: You say you can use this connection string to see data & tables... can you also use this connection to insert new records ?
For each user, SQL Server lets you define if they have read access and/or write access.  Perhaps your user is just missing the db_datawriter permission...?

A: If the application is being run under full IIS, then there is some configuration for IIS needed to ensure that the localDB instance can be used in the application. See https://blogs.msdn.microsoft.com/sqlexpress/2011/12/08/using-localdb-with-full-iis-part-1-user-profile/

A: This is a late response, but I determined that the cause of this error for me was that I had tried to eliminate an extra web.config connection string without making a necessary change to my DbContext class.
I had one connection string for my DefaultConnection and another generated by EF Migrations.
<connectionStrings>
    <!-- PRODUCTION-->
    <add name="DefaultConnection" connectionString="…" providerName="System.Data.SqlClient"/>
    <add name="Clients.Link.Models.ClientsLinkDB" connectionString="…" providerName="System.Data.SqlClient"/>
</connectionStrings>

I decided to eliminate the second connection string thinking that EF would fall back or was already using my DefaultConnection.
<connectionStrings>
    <!-- PRODUCTION-->
    <add name="DefaultConnection" connectionString="…" providerName="System.Data.SqlClient"/>
</connectionStrings>

When I attempted to run update-database, I got the error message reported above:

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

The fix turned out to be extremely simple. I simply needed to instruct EF to use my DefaultConnection connection string instead of the one generated by migrations.
To do that, you just need to create or edit the constructor of your DbContext and pass the name of the DefaultConnection as a string to the base class constructor:
public class ClientsLinkDB : DbContext
{
    public ClientsLinkDB() : base("DefaultConnection")
    {

    }

    // The rest of your implementation follows
}


text:
Q: Get numbers that have only 2,3 and 5 as prime factors I am given an integer N. I have to find first N elements that are divisible by 2,3 or 5, but not by any other prime number.
N = 3
Results: 2,3,5
N = 5
Results: 2,3,5,6,8

Mistake number = 55.. 55/5 = 11.. 11 is prime number.. so means that it divides by any other prime number and doesn't counts in..
I guess there is need of recursive function,but I cant imagine what would algorithm look like
I was sent here from stackoverflow.
They gave me advice.. 2^i*3^j*5^k , for i,j,k = 0,1,2... , but it won't give an ordered array, because 2*2 < 2*3 .. and so on
I am trying to get this work in C++

A: Hint $\ $ There is a very simple recursive algorithm, e.g. the final $\color{#C00}\to$ below is calculated as follows.
$\ \ 1_{2,3,5}\to 1_{3,5} 2_2\to 1_5 2_{2,3} 3\to 1_5 2_{3} 3_2 4\to 1\, 2_{3,5} 3_2 4\, 5\to 1 2_{5} 3_3 4_2 5\,6\color{#C00}\to 1 2_{5} 3_3 4\, 5_2 6\,8\to\, \cdots$
The term $\:1 2_{5} 3_3 4_2 5\,6\:$ on the left of the $\color{#C00}\to$ means that we have computed the initial sequence $\:1\,2\,3\,4\,5\,6,\:$ where the subscript $5$ on $2$ means that $2\cdot 5$ is the next multiple of $5$ to insert, similarly $3\cdot 3$ and $4\cdot 2$ are the next multiples of $3$ and $2$ to be inserted. Therefore the next term must be $\rm\:min(2\cdot 5, 3\cdot 3, 4\cdot 2) = 8.\:$ Since  $8$ is not already at the end, we append it, then we bump the subscript $2$ from $4$ to the next term $5$, indicating that $2\cdot 5$ is the next multiple of $5$. Then recurse.
This can be implemented elegantly in a functional programming language using (lazy) streams for the multiples of $2,3,5$.

A: The algorithm in this answer, in the end, is the same as the one in Bill Dubuque's answer, but I hope to be more elaborate and describe how one could arrive at the algorithm. Let's frame the problem as that of building the list of all such numbers in ascending order, i.e., each time adding to the list the smallest number that is not already in it.
First, note that all the numbers you want are of the form $2^i3^j5^k$, where $i, j, k$ are nonnegative integers. This means that after the first number $1$ (corresponding to $i = j = k = 0$), each "next" number can be obtained by multiplying some number already generated in the list, by either $2$, or $3$ or $5$.
So you start the list with the first number, $1$. To find the next number, you have three choices: multiply the number $1$ by either $2$, or $3$, or $5$. Since you want the smallest result, you pick $2$, and your list becomes $[1, 2]$.
Now you can no longer multiply $1$ by $2$ to get a new number, it is "used up". Your three choices now are: multiplying $1$ by $3$, multiplying $1$ by $5$, or multiplying $\color{red}{2}$ by $2$. The smallest result is from multiplying $1$ by $3$, so you add the result to the list, which becomes $[1, 2, 3]$.
Now you can no longer multiply $1$ by $3$, it is "used up" for multiplication by $3$. The smallest number you can multiply by $3$ is the next number, $2$. Your three choices now are: multiplying $\color{red}{2}$ by $2$, multiplying $\color{red}2$ by $3$, and multiplying $1$ by $5$. You pick the smallest result, which corresponds to multiplying $2$ by $2$ and gives you $4$ which you add to the list, and now $2$ is also used up for multiplication by $2$ and for multiplication by $2$ you have to go to the next number in the list, namely $3$.
In general, you always have three choices: one number that you can multiply by $2$, another that you can multiply by $3$, and another that you can multiply by $5$. You pick whichever of these three choices gives the smallest result, and update the choice ("advance the pointer") for 2 or 3 or 5, whichever you chose.

The first few steps worked out explicitly:
List is $[1]$. Choice for 2 is $1$, choice for 3 is $1$, choice for 5 is $1$. (Choose multiplication by 2.)
List is $[1, 2]$. Choice for 2 is $2$, choice for 3 is $1$, choice for 5 is $1$. (Choose multiplication by 3.)
List is $[1, 2, 3]$. Choice for 2 is $2$, choice for 3 is $2$, choice for 5 is $1$. (Choose multiplication by 2.)
List $[1, 2, 3, 4]$. Choice for 2 is $3$, for 3 is $2$, choice for 5 is $1$. (Choose multiplication by 5.)
List is $[1, 2, 3, 4, 5]$. Choice for 2 is $3$, for 3 is $2$, for 5 is $2$. (Choose multiplication by 2.)
List is $[1, 2, 3, 4, 5, 6]$. Choice for 2 is $4$, for 3 is $3$ (note that we updated this also), for 5 is $2$. (Choose multiplication by 2.)
List is $[1, 2, 3, 4, 5, 6, 8]$. Choice for 2 is $5$, for 3 is $3$, for 5 is $2$. (Choose multiplication by $3$.)
List is $[1, 2, 3, 4, 5, 6, 8, 9]$. Choice for 2 is $5$, for 3 is $4$, for 5 is $2$.
List is $[1, 2, 3, 4, 5, 6, 8, 9, 10]$. Choice for 2 is $6$, for 3 is $4$, for 5 is $3$.
List is $[1, 2, 3, 4, 5, 6, 8, 9, 10, 12]$. Choice for 2 is $8$, for 3 is $5$, for $5$ is $3$.
List is $[1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15]$. Choice for 2 is $8$, for 3 is $6$, for $5$ is $4$.

In code, you could implement it as a growing array, with three array indices pointing to the choices for 2, 3, and 5. Here is a complete working Python program (time.sleep is to keep it slow enough to see the output):
import time
num = [1]
c2 = c3 = c5 = 0

while True:
  next = min(2*num[c2], 3*num[c3], 5*num[c5])
  num.append(next)
  print num
  if next == 2*num[c2]: c2 += 1
  if next == 3*num[c3]: c3 += 1
  if next == 5*num[c5]: c5 += 1
  time.sleep(0.5)

A: I'd build it up from the prime factorization. You're looking for numbers with a prime factorization of the form $2^a3^b5^c$. Thus, you can simply start with an a, b, and c of zero, and work along the following pseudocode algorithm:
do
{
   if(2^(a+1) > 3^(b+1))
      if(3^(b+1) > 5^(c+1))
      {
         increment c
         b = 0
         a = 0
      }
      else
      {
         increment b
         a = 0
      }
   else
      increment a

   results.add(2^a*3^b*5^c)
}
while(results.count < N) //should loop exactly N times

A: I solve this kind of situation with this:

function getIdealNums($l, $r) {
    $numbers = [];
for ($x=0; $x <= 2*pow(10, 5); $x++) {
        for ($y=0; $y <= 2*pow(10, 5); $y++) {
        $number = pow(3, $x)*pow(5, $y);
        if ($l <= $number) {
            if ($number <= $r) {
                array_push($numbers, $number);
            } else {
                break;
            }
        }
    }
}
return count($numbers);
}

A: I get similar type of question on competitive programming, although I'm beginner, my code is not much optimized but I think it will help.
// 1 2 3 4 5 6 8 9 10 12 14 15 16 18 20 21......etc//
// 1 2 3 4 5 6 7 8 9  10 11 12 13 14 15 16......etc//

#include<iostream>
using namespace std;

int main()
{
  int n;
  int size = 1000;
  int arr[size];
  int count = 1;
  int str = 1;
  int temp = 0;

  cin>>n;
  temp = n;

  while(count <= temp)
  {
    //cout<<"looping count : "<<count<<endl;

    if(temp == 1)
    {
      arr[count] = str;
    }
    if(count == 1)
    {
      arr[count] = str;
    }
    else if(count > 1)
    {
      str += 1;

      if(str % 2 == 0 || str % 3 == 0 || str % 5 == 0)
      {
        arr[count] = str;
      }
      else
      {
        str += 1;
        arr[count] = str;
      }

    }

    count += 1;
  }

  for(count = 1; count <= temp; count++)
    cout<<"Array at "<<count<<" "<<arr[count]<<endl;

  cout<<"End str : "<<str<<endl;

  return 0;
}

A: Make a loop over numbers i.  Check the numbers one at a time, it doesn't need to be recursive.
Added:
If you want, you can use a nice recursive algorithm f(i) which is true or false depending on whether the number i should be allowed into the list.
f(i):
if i == 1: return true
else if i % 2 == 0: return f(i/2)
else if i % 3 == 0: return f(i/3)
else if i % 5 == 0: return f(i/5)
else: return false
Added:
Start the loop at 2, otherwise this function will wrongly allow 1 into the list.


text:
Q: Error parsing JSON data from Facebook using FQL I am trying to parse a result (JSON) fetched from the Facebook API using FQL in an Android Application.
I have been able to parse all of the result set except this part:
[10151392619250579,10151392618640579,10151392618590579,10151392618785579,10151392618835579,10151392618885579,10151392619010579,10151392619155579]

The FQL query I am making is:
SELECT app_data FROM stream WHERE filter_key in (SELECT filter_key FROM stream_filter WHERE uid = me() AND type = 'newsfeed') AND is_hidden = 0 LIMIT 200

Which returns a result like this:
{
    "app_data": {
        "attachment_data": "[]",
        "images": "[10151392619250579,10151392618640579,10151392618590579,10151392618785579,10151392618835579,10151392618885579,10151392619010579,10151392619155579]",
        "photo_ids": [
          "10151392619250579",
          "10151392618640579",
          "10151392618590579",
          "10151392618785579",
          "10151392618835579",
          "10151392618885579",
          "10151392619010579",
          "10151392619155579"
        ]
    }
}

And this is the code I have used to fetch the data:
// GET THE APP DATA
if (JOFeeds.has("app_data"))    {
    String strAppData = JOFeeds.getString("app_data");

    if (strAppData.equals("[]"))    {
        // DO NOTHING
    } else {

        JSONObject JOAppData = new JSONObject(strAppData);

        if (JOAppData.has("photo_ids")) {
            String strPhotoIDS = JOAppData.getString("photo_ids");

            JSONArray JAPhotoIDS = new JSONArray(strPhotoIDS);
            Log.e("JAPhotoIDS", JAPhotoIDS.toString());

            for (int j = 0; j < JAPhotoIDS.length(); j++) {
                JSONObject JOPhotoIDS = JAPhotoIDS.getJSONObject(j);
                Log.e("PHOTO IDS", JOPhotoIDS.toString());
            }
        }

    }
}

The logcat however, always shows this error:
12-13 15:54:36.390: W/System.err(5841): org.json.JSONException: Value 10151392619250579 at 0 of type java.lang.Long cannot be converted to JSONObject

Clearly I am wrong in the coding. Can anyone provide any suggestions on what the proper approach / code should be?

A: the part where you are parsing the photo_ids is wrong, it should be like:
if (JOAppData.has("photo_ids")) {
        JSONArray JAPhotoIDS = JOAppData.getJSONArray("photo_ids");
        Log.e("JAPhotoIDS", JAPhotoIDS.toString());

        for (int j = 0; j < JAPhotoIDS.length(); j++) {
            String id = JAPhotoIDS.getString(j);
            Log.e("PHOTO IDS", id);
        }
    }

A: Your JSONArray JAPhotoIDS includes an array of Long (not JSONObject).
So instead using
JSONObject JOPhotoIDS = JAPhotoIDS.getJSONObject(j);

use
Long lPhotoIDS = JAPhotoIDS.getLong(j);


text:
Q: Iptables doesn't open port 53 I have been trying different ways of opening the port but for some reason doesn't work.
The last set of lines that I have used is as follows:
iptables -I OUTPUT -p udp --dport 53 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -I INPUT  -p udp --sport 53 -m state --state ESTABLISHED     -j ACCEPT
iptables -I OUTPUT -p tcp --dport 53 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -I INPUT  -p tcp --sport 53 -m state --state ESTABLISHED     -j ACCEPT

What am I doing wrong?
I have a plesk installed on my server, so it should handled dns for me. I have accessed the components page within Plesk and I can see BIND Support switched on. But, for some reason after I had a memory problem on the server DNS stopped functioning. So I gave server provider a call and all they could tell me is that port 53 is blocked and I have to unblock it, so i had to disable iptables. however for some reason after another restart DNS is back running, port 53 is open.

A: Assuming you're running a dns server (this is serverfault after all and 'opening the port' suggests that's what you're trying to do) then your dport and sport are round the wrong way. You want --dport 53 on the INPUT chain.
You've also got the connection state tracking wrong in that case. If you only allow ESTABLISHED on input, how can anyone reach your dns server ?
Finally, if you're not running a dns server, but instead are attempting to allow yourself to use a dns server, these rules are totally wrong :-)


text:
Q: Http status code from a global @ExceptionHandler with the @ControllerAdvice annotation I'm implementing a global exception handler inside a Spring Boot App, with the @ControllerAdvice annotation, and I'd like to know, how could I get the http status code for showing a different message when it's 404 and to persist a log with the error, in other cases.
This is a simplified version of the code:
@ControllerAdvice
public class GlobalExceptionHandler {

@ExceptionHandler(RuntimeException.class)
public ModelAndView handleException(Exception ex, HttpServletRequest request, HttpServletResponse response) {

    ...

    ModelAndView model = new ModelAndView();
    model.addObject("message", ex.getMessage());
    model.addObject("trace", trace);
    model.addObject("path",  path);
    //model.addObject("status", response.getStatus());

    model.setViewName("error");

    return model;
}

I've tried this approach, without success:
Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
Integer statusCode = Integer.valueOf(status.toString());

To get the request attribute, this other name; javax.servlet.error.status_code doesn't work either.

A: You have to set your own status code corresponding every exception that you are handling. If any exception missed, default will be 5.x.x server error.

A: I remember doing this by extracting the expected exception to a separate class that extends Exception.
By doing this, you can add @ResponseStatus to set your required status code.
This custom exception can be thrown in your controller needed.
@ResponseStatus(value=HttpStatus.NOT_FOUND, reason="Person Not Found")
public class PersonNotFoundException extends Exception {

    public PersonNotFoundException (int id){
        super("PersonNotFoundException with id="+id);
    }
}

Instead of specifying the generic RunTime exception, handle the PersonNotFoundException in your @ExceptionHandler and add the exception object to your ModelAndView.


text:
Q: Drag and drop using Raphael.js has laggy performance with more than 10 draggable elements I'm making a simple HTML5 app, that will be wrapped to be used on Android, iOS and web browsers. In my app I need a set of points to be dragged and sorted in a certain way, I'm using raphael.js for the animations and movememts and it works fine with 3 or 4 circles, but when I use more the laggy performance appears (mobile browser). I also need the app to be able to draw lines on freehand, like a marker, and the code i'm using refers to drag to, so the performance is awful. The interesting part is that the first moves work great, as i move more elements the performance drops down drastically. It works fine in the pc browser, but works fine for 3 or 4 movements on the mobie browser.
Is there any way to make drag and drop run fast and smooth with large quantity of elements?
Here's the code:
<!DOCTYPE html>

        <meta charset="utf-8">
        <title>Raphaël · Drag-n-drop</title>
        <link rel="stylesheet" href="demo.css" type="text/css" media="screen">
        <meta name="apple-mobile-web-app-capable" content="yes">
        <link rel="apple-touch-icon-precomposed" href="/Raphael.png">
        <link rel="stylesheet" href="demo-print.css" type="text/css" media="print">

Any ideas??
Thanks


text:
Q: How to break a sentence into different parts in css I want to break a sentence in 3 parts using css, e.g., United States ("US") - Tax reforms
Here I want to name 3 parts from the sentence.

*

*name: United States

*symbol: US

*subject: Tax reforms
I know I can use (" to yield name, (" and ") to yield symbol, and ") - to yield subject. But I don't know how to.
I looked up on "word-break" but it doesn't seem to achieve what I want.

A: You cannot use CSS for splitting a string into parts. You simply cannot target single letters with CSS (except for the first letter with the :first-letter pseudo class). See also this question for more information on this subject.
You could use JavaScript combined with e.g. a regular expression. A simple example would be the following (just as a reminder: do not parse user-content directly as HTML for security reasons):

const input = 'United States ("US") - Tax reforms';
const regex = /^([\w\s]+)\s\("(\w+)"\)\s-\s([\w ]+)/;
const result = regex.exec(input);

if (result !== null) {
  const resultingObject = {
    name: result[1],
    symbol: result[2],
    subject: result[3]
  };
  console.log(resultingObject);
  document.body.innerHTML = `
${resultingObject.name}

${resultingObject.symbol}

${resultingObject.subject}
`;
}
.name {
  font-weight: bold;
}
.symbol {
  font-style: italic;
}
.subject {
  text-decoration: underline;
}


text:
Q: Why does this C programm crash? I have written the following code, however I get a crash (without warnings or errors) and do not know the cause:
const int N = 1000;

int main(){
    int *pI = calloc(N,sizeof(int));
    for (int i=0;i<N;i++) {
        *(pI++) = (i+1);
    }
    free(pI);

    return EXIT_SUCCESS;
}

I am thankful for any advice!

A: You are not releasing the original pointer received from calloc():
 free(pI);

You have been modifying the value contained in this pointer:
*(pI++) = (i+1);

Do instead:
int *p = calloc(N,sizeof(int));
int *pI = p;
// ...
free(p);

That is, save the value returned from calloc() and then pass it to free() when you don't need the allocated memory anymore.


text:
Q: Applications with 3d accelerated guis? Basically all games have this, since a game just creates a window and draws to it with opengl. The gui runs at the same fps as the game, usually 60 fps or more.
I'm wondering if gui libraries like gtk and qt have the ability to use 3d acceleration for widgets? I would imagine this working the same way as a game. Or if not gtk or qt, another toolkit?


text:
Q: JAX-WS MTOM streaming: server reads entire stream before sending I have a JAX-WS RI server that does MTOM streaming. From the client, everything is fine. The server receives a StreamingDataHandler, and neither side uses much memory sending 1 GB. Retrieving the file, however, the server is reading the entire contents before sending it. The client is OK. I'm using DataHandler on both ends, so that aspect of things is fine. I just don't want the server to read all the data from the InputStream before it starts sending. I have the following annotations on the impl:
@MTOM
@StreamingAttachment(parseEagerly = false, memoryThreshold = 1L)
@WebService(...)

I've tried parseEagerly true and false. I set the memory threshold low because I'm not concerned about small performance hits for small files.
Is this a bug with JAX-WS RI?

A: This is what I did.  Worked like a charm.
Interface (think it's a lot like what you did)
@WebService
@SOAPBinding(style = Style.RPC)
public interface ResultsServer {
    @WebMethod
    @XmlMimeType("application/octet-stream")
    public DataHandler getResultDataAsXML(@WebParam Integer raceId) throws Exception;
}

Implementation
@MTOM
@WebService(endpointInterface = "ca.sportstats.wtc.ResultsServer")
@StreamingAttachment(parseEagerly=true, memoryThreshold=4000000L)
public class ResultsServerImpl implements ResultsServer {

    @Override
    public DataHandler getResultDataAsXML(@WebParam Integer raceId) throws Exception {
        File xmlFile = new File("c:/tmp/xml/response.xml");
        //... write my xml file using an XMLStreamWriter
        return new DataHandler(new FileDataSource(xmlFile));
    }
}

Testing
public class Test {
    public static void main(String[] args) throws Exception {

       URL url = new URL("http://url/to/ipmlementation/ResultsServerImplService?wsdl");
       QName qname = new QName("http://test.test.com/", "ResultsServer");

       Service service = Service.create(url, qname);
       ResultsServerImpl resultServer = service.getPort(ResultsServerImpl.class);

       /************  test download  ***************/
       DataHandler handler = resultServer.getResultDataAsXML(4);
       StreamingDataHandler dh = (StreamingDataHandler) handler;
       File file = File.createTempFile("test-received.xml", "");
       dh.moveTo(file);
       dh.close();

    }
}

This worked for me to stream (from the server) a large XML file without reading it all in memory.
See also

*

*https://metro.java.net/guide/ch06.html

*http://docs.oracle.com/cd/E15523_01/web.1111/e13734/mtom.htm#i279618

*http://www.mkyong.com/webservices/jax-ws/jax-ws-attachment-with-mtom/


text:
Q: How do I separate solr cores so their results don't mix? I'm trying to set up multiple solr cores (the data for each core is indexed using norconex, crawling entirely separate sites). The schema and solrconfig files are the same for all cores but there is a copy in each of their respective conf folders.
When I run a query in the admin UI for core 1, I'm getting a mix of results from info indexed to cores 2 and 3 as well. How do I keep them entirely separate? It was my understanding that having separate cores would do this by default?
I've tried clearing all documents from cores 2 and 3, but core 1 still pulls up their docs. Thanks for any help anyone can provide.

A: This should not be happening. So, something has gone wrong. Possible options, from most likely and down:

*

*You are - accidentally - indexing into single core (as mentioned in comments). This is most likely. Perhaps you got URL wrong or the software is using some old convention of naming the core through URL parameters. Try to intercept the URL actually used for indexing and see how they are different when software thinks it indexes into different cores. The core name should be in the URL itself (e.g. http://server:8983/solr/core1).

*You have created a SolrCloud collection but are trying to index into individual cores of that collection. You should be able to check that in Admin UI and usually the core names are quite noticeably specific.

*You have created an alias that spans multiple cores and are querying that instead of individual cores.

*You have accidentally pointed several of your cores to the same data directory.

You did not say what happens when you query core2. If it does not have any documents, then first outcome is most likely. If it does, there may be other issues in play.

A: The issue you're describing above sounds like it could be that you have cores 1 through 3 on the same shard.  That means that they would be replicas of each other and have the same data.  If core1 were to be killed and replaced with another core, then data from the other cores would be replicated to the new core when the new core was added to the collection.
If you want subsets of documents in three separate cores (the physical locations), then those cores need to live in three separate shards (the logical locations).  This can be accomplished using routing.
The compositeId router will let you send documents or queries to specific shards. The documentation shows an example of using data from a company field as part of the routing key value like this: "IBM!12345"
The exclamation point is a separator to break the key into the various parts used for creating the shard hash value. This allows sending "IBM" data to one shard, and "YOYODYNE" can be sent to another shard.
If "YOYODYNE" had way more documents than "IBM", then you might want to spread documents for "YOYODYNE" across multiple shards. The documentation says to use something like this:

Another use case could be if the customer "IBM" has a lot of documents
  and you want to spread it across multiple shards. The syntax for such
  a use case would be: shard_key/num!document_id where the /num is the
  number of bits from the shard key to use in the composite hash.
So IBM/3!12345 will take 3 bits from the shard key and 29 bits from the unique doc id, spreading the tenant over 1/8th of the shards
  in the collection. Likewise if the num value was 2 it would spread the
  documents across 1/4th the number of shards. At query time, you
  include the prefix(es) along with the number of bits into your query
  with the route parameter (i.e., q=solr&route=IBM/3!) to direct
  queries to specific shards.


text:
Q: ¿Cuál es la diferencia entre wait() y sleep() en Java? En mi aplicación estoy manejando distintos hilos, los cuales deben "dormir" X segundos. He notado que usando ambos métodos el hilo duerme.
¿La diferencia es que con Thread.sleep(5000); duermo el hilo principal y con hilo.wait() puedo hacer dormir cualquier otro hilo creado? ¿Estoy en lo correcto? Si no es así agradeceré mucho sus explicaciones.

A: Un wait puede ser "despertado" por otro proceso llamando notify en el monitor que está siendo atendido, mientras que un sleep no. También wait (y notify) debe suceder en un bloque synchronized sobre el objeto de monitor mientras que sleep no.
Object mon = ...;
synchronized (mon) {
    mon.wait();
}

En este punto, el hilo que se está ejecutando actualmente espera y libera el monitor. Otro hilo puede hacer:
synchronized (mon) {
     mon.notify();
}

(En el mismo objeto mon ) y el primer hilo (suponiendo que es el único hilo en espera en el monitor) puede despertar.
Existe una pregunta con una gran cantidad de respuestas en inglés:
https://stackoverflow.com/questions/1036754/difference-between-wait-and-sleep
respuesta realizada por el usuario oxbow-lakes (esto para respetar la licencia de SO)

A: wait() no es un método para esperar un tiempo, es parte de una primitiva de sincronización.
La primitiva de sincronización en cuestión, son los monitores. Un monitor, básicamente es un mútex más una variable de condición.
En Java, cada objeto tiene un monitor. Se adquiere el mútex del monitor con synchronized(objeto) {, y el mútex se libera cuando termina el bloque de código, con el correspondiente  }.
Mientras está adquirido el mútex, se pueden hacer operaciones con la variable de condición adecuada:

*

*Se puede esperar a que se produzca una condición:
while (!condicion) { objeto.wait(); }
Antes de poner el hilo en espera, se libera el mútex, para que otros hilos puedan realizar operaciones con la variable de condición. Cuando se despierta intenta readquirir el mútex.

*Se puede notificar que se ha producido la condición, pidiendo que se despierte uno de los hilos en espera:
objeto.notify();

*Se puede notificar que se ha producido la condición, pidiendo que se despierte todos los hilos en espera:
objeto.notifyAll();
Un ejemplo sería una cola con un hilo productor, y un hilo consumidor. La cola se protegería con el monitor. El consumidor iría desencolando elementos, si la cola esta vacía, se pondría a esperar con un wait(). El productor añadiría elementos a la cola, notificando a posibles consumidores que la cola ya no está vacía.
Cuando se espera a que se produzca una condición, es importante comprobar la condición en un bucle.

A: En el caso de Thread.sleep() no es el hilo principal el que se suspende sino el actual, es decir aquel que está ejecutando justamente esa línea de código.
En el caso de wait() no es a un hilo al que se hace el wait sino a un objeto que sirva para la sincronización.
La sobrecarga que mencionas del método wait() está definido en la clase Object así
public final void wait() throws InterruptedException

Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. In other words, this method behaves exactly as if it simply performs the call wait(0).

Traducción:

Hace que el hilo actual espere hasta que otro hilo invoque el método notify() o notifyAll() en este objeto. En otras palabras se comporta exactamente como si se hubiera llamado a wait(0).

Por lo tanto la única manera de resumir la ejecución del hilo (con esta sobrecarga ya que hay otra a la que le pasas un timeout) es utilizar Object.notify o  Object.notifyAll.
Si necesitas suspender un hilo hasta que otro lo despierte puedes usar object.wait() , si en cambio quieres suspender el hilo por un tiempo específico utiliza Thread.sleep(), cabe mencionar que un Thread.sleep no puede ser notificado para reaunudar, por lo que siempre deberás esperar al que el timout finalice.

A: Éstas son las diferencias entre sleep(int milis) y wait(int milis)

wait() sin parámetro de milis se comporta exáctamente como si simplemente llamase a wait(0)
No es una diferencia el uso que hacen del hilo o el procesador. Como demuestra el código que pongo al final. Ambos hacen una espera no ocupada sin consumir recursos (en una buena máquina virtual, cualquiera de los dos podría hacer una espera ocupada en una máquina virtual no optimizada).
Una diferencia muy importante son los despertares espúreos. Los cuales afectan a wait pero no a sleep. Un wait puede terminar en cualquier momento, sin motivo ni justificación, y es responsabilidad del programador tener esto en cuenta.
En lo que son iguales es en que ambos duermen al hilo en que se ha ejecutado la llamada a wait o sleep. Ninguno sirve para dormir al hilo principal (excepto si se ejecutan en el hilo principal).
Conclusión :
Usa sleep para esperar tiempo.
Los wait son para otra cosa (sincronización) y sufren de despertares espúreos.
Código demostración uso CPU
En mi máquina se ejecuta en 10-13 segundos tanto con USAR_SLEEP a true como a false.
class Test extends Thread {

    static final boolean USAR_SLEEP = false;
    static final int NUM_THREADS = 20000;

    public static void main(String[] args) throws InterruptedException {
            Test[] thread = new Test[NUM_THREADS];
            for (int n = 0; n < NUM_THREADS; ++n) {
                thread[n] = new Test();
                thread[n].start();
            }
            int m = 0;
            for (int n = 0; n < 100000000; ++n) {
                m = m * 23 + n;
            }
            if ( !USAR_SLEEP )
            {
                for ( Test t : thread )
                {
                    synchronized( t.cerrojoImplicito )
                    {
                        t.cerrojoImplicito.notify();
                    }
                }
            }
            for (Test t : thread) {
                t.join();
            }
    }

    public Object cerrojoImplicito = new Object();
    public void run() {
        try {
            if (USAR_SLEEP) {
                sleep(5000);
            } else {
                synchronized (cerrojoImplicito) {
                    cerrojoImplicito.wait(5000);
                }
            }
        } catch (InterruptedException ex) {
            System.out.println("Interrumpido");
        }
    }
}


text:
Q: Swap Key and Value in Concurrent Dictionary in C# Is there any way to swap key and value in Concurrent Dictionary in C# ? I know for Dictionary type, it can be something like
dictionary = dictionary.ToDictionary(x => x.Value, x => x.Key);

Anything similar in ConcurrentDictionary?

A: You cannot cast or convert Dictionary to ConcurrentDictionary directly.
Buy you can create a ConcurrentDictionary with a Dictionary, check this constructor
public ConcurrentDictionary(IEnumerable<KeyValuePair<TKey, TValue>> collection);

And look the extension method of LINQ that you say
  public static Dictionary<TKey, TElement> ToDictionary<TSource, TKey, TElement>(
        this IEnumerable<TSource> source,
        Func<TSource, TKey> keySelector,
        Func<TSource, TElement> elementSelector);

So if Dictionary has compatibility wiht IEnumerable<KeyValuePair<TKey, TValue>>
Solution 1
Just use ToDictionary extension method of LINQ
var concurrentDict = new ConcurrentDictionary<string, string>();
/* Add some items */
bool firstItem = concurrentDict.TryAdd("1", "First");  //returns true
bool secondItem = concurrentDict.TryAdd("2", "Second");  //returns  true

/* Swaping Value <-> Key to new Dictionary */
Dictionary<string,string> normalDict = concurrentDict.ToDictionary(x => x.Value, x => x.Key);

/* creating ConcurrentDictionary */
var newConcurrentDict = new ConcurrentDictionary<string, string>(normalDict);

Solution 2
What about thread safe?
You can use a custom extension method (like LINQ)
var concurrentDict = new ConcurrentDictionary<string, string>();
/* Add some items */
bool firstItem = concurrentDict.TryAdd("1", "First");  //returns true
bool secondItem = concurrentDict.TryAdd("2", "Second");  //returns  true

/* Swaping Value <-> Key to new Dictionary */
Dictionary<string,string> normalDict = concurrentDict.ToDictionary(x => x.Value, x => x.Key);

/* creating ConcurrentDictionary */
var newConcurrentDict = normalDict.ToConcurrentDictionary();

Extension method
Ref https://stackoverflow.com/a/27064366/1669574
public static class ConcurrentDictionaryExtensions
{
    public static ConcurrentDictionary<TKey, TElement> ToConcurrentDictionary<TSource, TKey, TElement>(
        this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector,
        IEqualityComparer<TKey> comparer)
    {
        if (source == null) throw new ArgumentNullException("source");
        if (keySelector == null) throw new ArgumentNullException("keySelector");
        if (elementSelector == null) throw new ArgumentNullException("elementSelector");

        ConcurrentDictionary<TKey, TElement> d = new ConcurrentDictionary<TKey, TElement>(comparer);
        foreach (TSource element in source)
            d.TryAdd(keySelector(element), elementSelector(element));

        return d;
    }

    public static ConcurrentDictionary<TKey, TSource> ToConcurrentDictionary<TSource, TKey>(
        this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
    {
        return ToConcurrentDictionary<TSource, TKey, TSource>(source, keySelector, IdentityFunction<TSource>.Instance,
            null);
    }

    public static ConcurrentDictionary<TKey, TSource> ToConcurrentDictionary<TSource, TKey>(
        this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer)
    {
        return ToConcurrentDictionary<TSource, TKey, TSource>(source, keySelector, IdentityFunction<TSource>.Instance,
            comparer);
    }

    public static ConcurrentDictionary<TKey, TElement> ToConcurrentDictionary<TSource, TKey, TElement>(
        this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector)
    {
        return ToConcurrentDictionary<TSource, TKey, TElement>(source, keySelector, elementSelector, null);
    }

    internal class IdentityFunction<TElement>
    {
        public static Func<TElement, TElement> Instance
        {
            get { return x => x; }
        }
    }
}


text:
Q: Evaluate LaTeX parts conditionally depending on Lua state In LuaLaTeX, I want to evaluate parts of the document conditionally, depending on Lua state.
A way to evaluate parts conditionally in LaTeX is a \if \else \fi construct.
A simple approach to connect this to Lua would be:
\documentclass{article}

\newcommand{\luaif}[1]{\ifnum1=\directlua{if #1 then tex.sprint(1) else tex.sprint(0) end} }

\directlua{a = 1}

\begin{document}
\luaif{a == 1} true \else false \fi % -> true
\luaif{a == 2} true \else false \fi % -> false
\end{document}

This feels quite hacky, though.
Are there any alternative (better) approaches, maybe already built-in?


text:
Q: Zeros of $e^{z}-z$, Stein-Shakarchi Complex Analysis Chapter 5, Exercise 13 This is an exercise form Stein-Shakarchi's Complex Analysis (page 155) Chapter 5, Exercise 13:

Prove that $f(z) = e^{z}-z$ has infinite many zeros in $\mathbb{C}$.

Attempt:
If not, by Hadamard's theorem we obtain $$e^{z}-z = e^{az+b}\prod_{1}^{n}(1-\frac{z}{z_{i}})$$ where $\{z_{i}\}$ are the zeros of $f$. How can we conclude ?

A: Note that $a=1$. Then rewrite your equation as
$$z=e^z P(z)$$
where $P(z)$ is a polynomial of degree $n$. For $|z|$ large enough, $P$ grows of order $|z|^n$. Therefore this equation implies upon taking absolut values that $e^{\mathrm{Re} z}$ decreases like $|z|^{1-n}$ as $|z|\rightarrow\infty$. This is clearly a contradiction.
Therefore you cannot apply Hadamard's theorem, i.e. $f$ has infinitely many zeros.

A: It is easy to see that $e^z-z$ has order of growth 1. So we can use Hadamard's theorem.
Assume that $f(z)=e^z-z$  has only finitely many zeroes, $a_1,a_2,\ldots, a_n$. Then by Hadamard's factorization theorem, for some $a\in \mathbb{C}$ we have $$e^z-z=e^{az}\prod_{i=1}^{n}\Big(1-\frac{z}{a_i}\Big).$$ Then by using the identity $$\frac{(f_1f_2\ldots f_n)'}{f_1f_2\ldots f_n}=\frac{f_1'}{f_1}+\cdots+\frac{f_n'}{f_n}.$$ We have for $z\notin \{a_1,a_2,\ldots,a_n\}$ $$\frac{e^z-1}{e^z-z}=a+\sum_{i=1}^{n}\frac{1}{z-a_i}.$$
The L.H.S has infinitely many zeroes $2\pi ni$ for $n \in \mathbb{Z}$, but the R.H.S is a quotient of two polynomial functions therefore has only has finitely many zeroes.
Therefore $f$ must have infinitely many zeores.

A: Are you allowed to use Picard's Theorem?
If yes here is a relative question:
Use Picard's Theorem to prove infinite zeros for $\exp(z)+Q(z)$


text:
Q: Quaternion: composition of rotations. Change of refence frame I have a world reference frame, let'denote it with {R}, and a reference frame attached to a sensor, let's denote it with {C}.
The sensor detect another reference frame {M}, located on a marker.
q represents the quaternion related to the orientation of {C} with respect to {R}.
qq represents the quaternion related to the orientation of {M} with respect to {C}.
I'd like to express the orientation of {M} with respect to {R}.
I'm struggling, because q and qq are not related to the same reference frame, and I can't find an easy way to go on. Matlab and python tf.transformations use different conventions, and I'm doing a mess mixing RPY, rotation matrices and stuff like this... Thanks for your help.

A: Rotate qq back from M to R frame
qq_R = q^-1 * qq * q


text:
Q: Web Configuration, Security in Oracle APEX I want to build an web application in Oracle APEX, where i want users to enter into the database server through the application server, thus i can ensure more security in my application. IF this is hard, then is there any other way where i can ensure more security in a web application in Oracle APEX?

A: Oracle APEX is a very stable and secure environement.
As is,

*

*you can encrypt and enforce high level passwords for the users

*you can lock account to avoid brute force attacks

*Devs and admins have accounts locked after a few attempts by default to avoid this issue

*The service can be easily configured with any SSL

*Webservices, like most of them, can be programmed to use access_tokens and other validations.

To my knowledge any additions security could be configured on the server and firewall. So I would say that you can do I lot, but it is up to you to perform good practices when defining your system's security.
Hope ity helps and good luck! :)


text:
Q: Riemann hypothesis and Robin's Inequality Implications Is the following statement true:
Let $\Bbb{A}$ be the set of all Natural numbers n, greater than or equal to 5041, for which the inequality $\displaystyle \sigma(n)<e^{\gamma}n\log\log n$ is not true (does not hold).
$\Bbb{A}$ = $\{\}$  $\Longleftrightarrow
$  For all $\displaystyle s ≠ -2n:\zeta(s)=0∧0<Re[s]<1=1/2$
Consequently, is the following wikipedia article making the same explicit statement?
Why or why not?
Referencing
https://en.wikipedia.org/wiki/Colossally_abundant_number#Relation_to_the_Riemann_hypothesis

A: I put a copy of Nicolas 1983 here
I put a copy of Robin 1984  here.


text:
Q: How to properly unittest in Python I have a method which does the following. Question is how do I unit test this method. I am pretty new to this Python unit testing module.
The question and solution are as follows:
Given a string containing of '0', '1' and '?' wildcard characters, generate all binary strings that can be formed by replacing each wildcard character by '0' or '1'.
Example :
Input str = "1??0?101"
Output:
        10000101
        10001101
        10100101
        10101101
        11000101
        11001101
        11100101
        11101101

Solution:
def _print(string, index):
    if index == len(string):
        print(''.join(string))
        return

    if string[index] == "?":

        # replace '?' by '0' and recurse
        string[index] = '0'
        _print(string, index + 1)

        # replace '?' by '1' and recurse
        string[index] = '1'
        _print(string, index + 1)

        # NOTE: Need to backtrack as string
        # is passed by reference to the
        # function
        string[index] = '?'
    else:
        _print(string, index + 1)

# Driver code
if __name__ == "__main__":

    string = "1??0?101"
    string = list(string) #don't forget to convert to string
    _print(string, 0)

Output:
        10000101
        10001101
        10100101
        10101101
        11000101
        11001101
        11100101
        11101101

Questions:
1. Also, is there a way of returning a list as output instead of printing them out?
2. Which assert test cases are appropriate in this scenario?
3. What would be the best end to end test cases to cover in this case?
4. What could be a better approach of solving this in terms of time and space complexity?
I have tried this which doesn't seem to work:
import unittest
from wildcard import _print
class TestWildCard(unittest.TestCase):

    def test_0_print(self):
        print("Start wildCard _print test: \n")
        result = 111
        self.assertEquals(_print("1?1",0),result,"Results match")

A: Answers:
1: sure, instead of printing something, append the result to a list result.append('some value') and don't forget to initialise the list at the start of your code result = [] and return it once the function is done return result - and probably don't call the function _print, but something like bit_strings.
ad 1: since your function is recursive, you now also need to capture the return value and add it to the result when calling the function recursively, so result += _print(string, index + 1)
2: you should typically think of edge cases and test them separately, or group those together that really test a single aspect of your function. There is no one way to state what the test should look like - if there were, the test framework would just generate it for you.
3: same answer as 2.
Your code becomes:
def bit_strings(s, index):
    result = []

    if index == len(s):
        result.append(''.join(s))
        return result

    if s[index] == "?":
        # replace '?' by '0' and recurse
        s[index] = '0'
        result += bit_strings(s, index + 1)

        # replace '?' by '1' and recurse
        s[index] = '1'
        result += bit_strings(s, index + 1)

        # NOTE: Need to backtrack as string
        # is passed by reference to the
        # function
        s[index] = '?'
    else:
        result += bit_strings(s, index + 1)

    return result

# Driver code
if __name__ == "__main__":
    x = "1??0?101"
    xl = list(x)  #don't forget to convert to string
    print(bit_strings(xl, 0))

There's more efficient ways of doing this, but I just modified your code in line with the questions and answers.
I've renamed string to s, since string is a bit confusing, reminding others of the type or shadowing the (built-in) module.
As for the unit test:
import unittest
from wildcard import bit_strings

class TestWildCard(unittest.TestCase):
    def test_0_print(self):
        print("Start wildCard _print test: \n")
        # you only had one case here and it's a list now
        result = ['101', '111']
        # user assertEqual, not Equals
        # you were passing in a string, but your code assumed a list, so list() added
        self.assertEqual(bit_strings(list("1?1"), 0), result, "Results match")

When using an environment like PyCharm, it helps to call the file test<something>.py (i.e. have test in the name), so that it helps you run the unit tests more easily.
Two alternate solutions as requested in comment (one still recursive, just a lot more concise, the other not recursive but arguably a bit wasteful with result lists - just two quickies):
from timeit import timeit

def unblank_bits(bits):
    if not bits:
        yield ''
    else:
        for ch in '01' if bits[0] == '?' else bits[0]:
            for continuation in unblank_bits(bits[1:]):
                yield ch + continuation

print(list(unblank_bits('0??100?1')))

def unblank_bits_non_recursive(bits):
    result = ['']
    for ch in bits:
        if ch == '?':
            result = [s+'0' for s in result] + [s+'1' for s in result]
        else:
            result = [s+ch for s in result]
    return result

print(list(unblank_bits_non_recursive('0??100?1')))

print(timeit(lambda: list(unblank_bits('0??100?1'))))
print(timeit(lambda: list(unblank_bits_non_recursive('0??100?1'))))

This solution doesn't move between lists and strings, as there is no need and doesn't manipulate the input values. As you can tell the recursive one is a bit slower, but I prefer it for readability. The output:
['00010001', '00010011', '00110001', '00110011', '01010001', '01010011', '01110001', '01110011']
['00010001', '01010001', '00110001', '01110001', '00010011', '01010011', '00110011', '01110011']
13.073874
3.9742709000000005

Note that your own solution ran in about 8 seconds using the same setup, so the "improved version" I suggested is simpler, but not faster, so you may prefer the latter solution.


text:
Q: Ajax function as part of a javascript comparison I'm running into an issue with a jquery ajax function not properly returning its results back to a javascript if statement.
Here is the issue, we have a database function that is generating a long string of if/then statements, an excerpt of which is below
if(1==1 && (GenericAjaxValidation("System.Yes")=="Y")) {do stuff}

The 1==1 is the result of something that happened in the database, so just ignore that bit. The GenericAjaxValidation call is the piece that is giving us issues The javascript function that it calls is below.
function GenericAjaxValidation(token) {

    $.ajax({
        type: "Post",
        url: '../FormAjax/GetAjaxValResult',
        data: {TOKEN:token,FormId:formDisplay.FormID,FormLayoutId:formDisplay.FormLayoutID},
        dataType: "json",
        timeout: 30000,
        async:false,
        success: function(obj) {
            result=obj.Object.ReturnValue;
        },
        error: function(obj) {

            return false;
        },
        complete: function(){
        return result;
        }
    });

}

The whole process is set up to fire off as part of an onchange event, and we reach the if statement with no issues. If I drop a break point into the jquery ajax function, it processes properly, and returns the "Y" that it is supposed to. However, when I step back out to the if statement, it fails. I looked at it a bit more and realized that it was always treating the result of GenericAjaxValidation as undefined. In fact, to test it, I changed the if statement to test for equality with undefined, and it succeeded.
My suspicion is that while the asynch: false is causing the rest of that single function to wait for the return, it doesn't appear that the if statement is waiting on it, and evaluates without waiting for the actual value. I searched the net for about a half hour on this one trying to find anything that said for sure one way or the other, but my Google-Fu failed me today.
So, my question is this: is there a way to make this work? or does javascript simply not play nice with this process.

A: The return statements are inside the "$.ajax()" callback functions. The values won't be returned as the result of your overall function, because it doesn't have a return at all.
You could have the callbacks instead set a local variable and then return that, but really you shouldn't do synchronous ajax in the first place.

A: Try (untested code):
function GenericAjaxValidation(token) {
    var result
    $.ajax({
        type: "Post",
        url: '../FormAjax/GetAjaxValResult',
        data: {TOKEN:token,FormId:formDisplay.FormID,FormLayoutId:formDisplay.FormLayoutID},
        dataType: "json",
        timeout: 30000,
        async:false,
        success: function(obj) {
            result=obj.Object.ReturnValue;
        },
        error: function(obj) {

            result = false;
        }
    });
    return result;
}

(edit: as @toby pointed out, the complete handler is unnecessary and doesn't do anything)
The problem is that GenericAjaxValidation wasn't returning anything.  It's the complete function that returns.  A return only returns from the immediate function, not the enclosing function, so GenericAjaxValidation was just completing without a return
To make it more clear, your original code could be written to be functionally equivilent like this (note in this sample and your original code, result is a global variable)_:
function GenericAjaxValidation(token) {
    $.ajax({
        type: "Post",
        url: '../FormAjax/GetAjaxValResult',
        data: {TOKEN:token,FormId:formDisplay.FormID,FormLayoutId:formDisplay.FormLayoutID},
        dataType: "json",
        timeout: 30000,
        async:false,
        success: onSuccess,
        error: onError,
        complete: onComplete
    });
    //No return statement
}
function onSuccess(obj) {
    result=obj.Object.ReturnValue;
}
function onError(obj) {
    return false;
}
function onComplete(){
    return result;
}

As you can see, GenericAjaxValidation never returns anything.

A: My suspicion is that jQuery is screwing you over.
I suggest you try removing the jQuery ajax call, and instead put in a regular XMLHttpRequest object. I can guarantee you that it'll work.
jQuery - simplifying things by complicating them! I write my own code and I know exactly what it does.


text:
Q: Template Parse Error in Angular 2 and Visual Studio update 3 I am following ASP.NET Core and Angular 2 from Packt Publishing. In Chapter 3 the Author Creates an ItemListComponent and ItemDetailComponent. When I use ItemDetailComponent i am getting template parse errors. Below is the error
Template parse errors:
Can't bind to 'item' since it isn't a known property of 'item-detail'.
1. If 'item-detail' is an Angular component and it has 'item' input, then  verify that it is part of this module.
2. If 'item-detail' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schema' of this component to suppress this message.
("

    <item-detail *ngIf="selectedItem" [ERROR ->][item]="selectedItem"></item-detail>

below is the Code i have written :
ItemDetailComponent:
import {Component, Input} from "@angular/core";
import {Item} from "./item";
@Component({
selector: "item-detail",
template: `

{{item.Title}} - Detail View

Title:
<input [(ngModel)]="item.Title" placeholder="Insert the
title..."/>

Description:
<textarea [(ngModel)]="item.Description"
placeholder="Insert a suitable description..."></textarea>

`,
styles: [`
.item-details {
margin: 5px;
padding: 5px 10px;
border: 1px solid black;
background-color: #dddddd;
width: 300px;
}
.item-details * {
vertical-align: middle;
}
.item-details ul li {
padding: 5px 0;
}
`]
})
export class ItemDetailComponent {
@Input("item") item: Item;
}

ItemListComponent:
import { Component, OnInit, Input } from '@angular/core';
import { Item } from './item';
import { ItemService } from './item.service';
@Component({
selector: `item-list`,
template: `

{{title}}:

            {{item.Title}}

    <item-detail *ngIf="selectedItem" [item]="selectedItem"></item-detail>

`,
styles: [`
    ul.items li {
        cursor: pointer;
    }
    ul.items li.selected {
        background-color: #cccccc;
    }
`]
})
export class ItemListComponent implements OnInit
{
@Input() class_name: string;
title: string;
selectedItem: Item;
items: Item[];
errorMessage: string;

constructor(private itemService: ItemService) {

}

ngOnInit() {
    console.log("ItemListComponent instantiated with the following type: " + this.class_name);
    var s = null;
    switch (this.class_name) {
        case "latest":
        default:
            this.title = "Latest Items";
            s = this.itemService.getLatest();
            break;
        case "most-viewed":
            this.title = "Most Viewed Items";
            s = this.itemService.getMostViewed();
            break;
        case "random":
            this.title = "Random Items";
            s = this.itemService.getRandom();
            break;
    }
    s.subscribe(
        items => this.items = items,
        error => this.errorMessage = <any>error
    );
    //this.getLatest();
}

getLatest() {
    this.itemService.getLatest()
        .subscribe(
        latestItems => this.items = latestItems,
        error => this.errorMessage = <any>error
        );
}

onSelect(item: Item) {
    this.selectedItem = item;
    console.log("item with Id " + this.selectedItem.Id + " has been selected.");
}
}

I created another simple component Called DemoInput :
import { Component, Input } from '@angular/core';
@Component({
selector: "demo-input",
template: `<h1>{{title_name}}</h1>`
})
export class DemoInput
{
@Input("in_name") title_name: string;
}

Here also the same error saying that in_name isn't a known property of demo-input.
app.component.ts
import { Component } from '@angular/core';

@Component({
selector: 'opengamelist',
template: `
{{title}}

           <item-list class_name="latest" class="latest"></item-list>

           `,
styles: [`
        item-list {
            min-width: 332px;
            border: 1px solid #aaaaaa;
            display: inline-block;
            margin: 0 10px;
            padding: 10px;
        }
        item-list.latest {
            background-color: #f9f9f9;
        }
        item-list.most-viewed {
            background-color: #f0f0f0;
        }
        item-list.random {
            background-color: #e9e9e9;
        }
    `]
})
export class AppComponent {
title:string = "Open Game List"
}

app.module.ts
///<reference path="../../typings/index.d.ts"/>
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpModule } from '@angular/http';
import { FormsModule } from "@angular/forms";
import { RouterModule } from "@angular/router";
import "rxjs/Rx";

import { AppComponent } from './app.component';
import { ItemListComponent } from './item-list.component';
import { ItemService } from './item.service';
import { ItemDetailComponent } from './item-detail.component';
import { DemoInput } from './DemoInput';

@NgModule({
declarations: [AppComponent, ItemListComponent, ItemDetailComponent,     DemoInput],
imports: [BrowserModule, HttpModule, FormsModule, RouterModule],
providers: [ItemService],
bootstrap: [AppComponent]
})
export class AppModule
{

}

I am using Visual Studio 2015 Update 3 on Virtual Machine Running on Mac. I tried creating the same DemoInput component on a Mac by installing Angular 2. It works fine in my Mac.
Is this a problem of Visual Studio 2015. What wrong am I doing. If I remove the item-detail tag from ItemListComponent template everything works fine.
Can anybody give me a solution.
Thanks in Advance :)

A: Are you using the exact same Angular2 version/build specified in the book? If not, please tell me what you've been using: I'm not getting this error with the RC5.
I also suggest to try to get the book source code from the official GitHub repository:
https://github.com/PacktPublishing/ASPdotNET-Core-and-Angular-2
Each chapter/book section has its own solution file: yours is Chapter 3 - Part 1.
As a side note: considering that ItemDetailComponent implementation is replaced later in Chapter 3 (Chapter 3 - Part 2): if you don't figure out a suitable fix for your issue you could probably just skip that sample implementation and go straight to the updated ItemDetailComponent.


text:
Q: Why can't I configure the perspective camera to have the actual sizes in three js? I am using Three Js for visualizing a car, but I am having a problem with my perspective camera

I would like it to look more real: I want to see only the front, not the back. I'm clear? haha
I have tried to change a lot of properties, but I am not being able to do it.
Here is the github repository.

A: I can see in your code you are changing the FOV with the mouse wheel...
Is this what you want to do?
I would expect you would change the camera z position to zoom in and out, not the FOV.
I suggest you do like what jscastro says in the comments and make yout camera fov 45 and move your camera closer and make your scroll event change the camera position, not the fov.
Here is a demo where you can change the camera fov and z position to see how they interact.

var camera, scene, renderer, mesh, material, stats;
init();
animate();

function init() {
    // Renderer.
    renderer = new THREE.WebGLRenderer();
    //renderer.setPixelRatio(window.devicePixelRatio);
    renderer.setSize(window.innerWidth, window.innerHeight);
    // Add renderer to page
    document.body.appendChild(renderer.domElement);

    // Create camera.
    camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 1, 10000);
    camera.position.z = 400;

    // Create scene.
    scene = new THREE.Scene();

    // Create material
    material = new THREE.MeshPhongMaterial();

    // Create cube and add to scene.
    var geometry = new THREE.BoxGeometry(200, 200, 200);
    mesh = new THREE.Mesh(geometry, material);
    scene.add(mesh);

    // Create ambient light and add to scene.
    var light = new THREE.AmbientLight(0x404040); // soft white light
    scene.add(light);

    // Create directional light and add to scene.
    var directionalLight = new THREE.DirectionalLight(0xffffff);
    directionalLight.position.set(1, 1, 1);
    scene.add(directionalLight);

    // Add listener for window resize.
    window.addEventListener('resize', onWindowResize, false);

    // Add dat.gui.
    var gui = new dat.GUI();
    var fovgui = gui.add(camera, "fov").onChange(function(newvalue){
      camera.updateProjectionMatrix();
    }).name('camera.fov');
    var posgui = gui.add(camera.position, "z").name('camera.position.z');

    gui.add({click: function(){
      camera.fov = 5;
      camera.position.z = 5000;
      camera.updateProjectionMatrix();
      fovgui.updateDisplay();
      posgui.updateDisplay();
    }}, 'click').name('FOV:5 Z:5000');

    gui.add({click: function(){
      camera.fov = 70;
      camera.position.z = 400;
      camera.updateProjectionMatrix();
      fovgui.updateDisplay();
      posgui.updateDisplay();
    }}, 'click').name('FOV:70 Z:400');

    gui.add({click: function(){
      camera.fov = 130;
      camera.position.z = 190;
      camera.updateProjectionMatrix();
      fovgui.updateDisplay();
      posgui.updateDisplay();
    }}, 'click').name('FOV:130 Z:190');

}

function animate() {
    requestAnimationFrame(animate);
    mesh.rotation.x += 0.005;
    mesh.rotation.y += 0.01;
    renderer.render(scene, camera);
}

function onWindowResize() {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth, window.innerHeight);
}
body {
    padding: 0;
    margin: 0;
}
canvas {
  display: block;
}
<script src="https://cdn.rawgit.com/dataarts/dat.gui/master/build/dat.gui.min.js"></script>
<link href="https://cdn.rawgit.com/dataarts/dat.gui/master/build/dat.gui.css" rel="stylesheet"/>
<script src="https://cdn.rawgit.com/mrdoob/three.js/master/build/three.min.js"></script>