text:
Q: PreferenceManager.setDefaultValues throws exception; handwritten code to do same works fine. What's happening behind the scenes to cause the error? I have been bothered with this error message for 3 days:
FATAL EXCEPTION: main
Process: com.dslomer64.sqhell, PID: 20613
java.lang.RuntimeException: Unable to start activity
  ComponentInfo{com.dslomer64.sqhell/com.dslomer64.sqhell.MainActivity}:
  java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String

It occurs in this line:
  PreferenceManager.setDefaultValues(this, R.xml.preferences_no_table, true);

So I have no idea which variable caused it. A few days and a couple of rewrites ago, the same error occurred in trying to do this:
editor.putInt(PREF_ROWS, DEFAULT_ROWS);

No changes to xml. Of possible interest: PREF_ROWS was not in the original preferences file, with which I'd had no errors that I can recall.
Might it be that in trying to deal with PREF_ROWS ("pref_rows" in the xml file), PreferenceManager is running into whatever was causing that problem for me back then? But I'm having no such problem tonight.
Here's preferences_no_table.xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >

<ListPreference
    android:key         ="pref_rows"
    android:defaultValue="@integer/defaultrows_no_table"
    android:persistent   ="true"/>

<ListPreference
    android:key         ="pref_max_matches"
    android:defaultValue="@integer/defaultmaxmatches"
    android:entries     ="@array/matches_list"
    android:entryValues ="@array/matches_list"
    android:persistent  ="true"       />

<ListPreference
    android:key           ="pref_shortest_word"
    android:defaultValue="@integer/defaultshortestword"
    android:entries     ="@array/word_lengths"
    android:entryValues ="@array/word_lengths"
    android:persistent  ="true"/>

<ListPreference
    android:key="pref_longest_word"
    android:defaultValue="@integer/defaultlongestword"
    android:entries     ="@array/word_lengths"
    android:entryValues ="@array/word_lengths"
    android:persistent="true"/>

<CheckBoxPreference
    android:key="pref_scrabble"
    android:defaultValue="true"
    android:persistent="true"        />

<CheckBoxPreference
    android:key="pref_spell_check"
    android:persistent="true"
    android:enabled="false"/>

<CheckBoxPreference
    android:key="pref_dic_test"
    android:defaultValue="false"
    android:checked="false"
    android:enabled="true"
    android:persistent="true"  />

<CheckBoxPreference
    android:key         ="pref_db_ready"
    android:defaultValue="false"
    android:persistent  ="true"/>

<CheckBoxPreference
    android:key         ="pref_want_scoring"
    android:defaultValue="false"
    android:persistent  ="true"        />

Here's integerdefaults.xml:
    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <integer name="defaultmaxmatches">     100  </integer>
        <integer name="defaultshortestword">     2  </integer>
        <integer name="defaultlongestword">     14  </integer>
        <integer name="defaultrows_no_table">   -1  </integer>
        <integer name="defaultrows_empty_table"> 0  </integer>
    </resources>

I don't see how arrays.xml, which contains the values for 3 of the ListPreferences could cause the problem so it's omitted.
So I made my own method to set the defaults and called it like so:
myClearAndSetDefaultsAsInXml();

Here's the code:
  private void myClearAndSetDefaultsAsInXml(){ //SET PREFS TO ORIGINAL DEFAULTS
    SharedPreferences.Editor editor = sp.edit();
    spDump("in pref clear and set my def");
    editor.clear();
    spDump("after editor clear");
    editor.putBoolean(PREF_DB_READY,      false);
    editor.putBoolean(PREF_DIC_TEST,      false);
    editor.putBoolean(PREF_SCRABBLE,      true);
    editor.putBoolean(PREF_WANT_SCORING,  false);
    editor.putInt    (PREF_ROWS,          DEFAULT_ROWS);
    editor.putInt    (PREF_MAX_MATCHES,   DEFAULT_MATCHES);
    editor.putInt    (PREF_LONGEST_WORD,  DEFAULT_LONGEST_WORD);
    editor.putInt    (PREF_SHORTEST_WORD, DEFAULT_SHORTEST_WORD);

    setBooleanPref(KEY_HAS_SET_DEFAULT_VALUES, true);
    editor.commit();
    spDump("end of myPrefSetDefaults");
  }

The spDump lines were for debugging. Turns out I didn't need them because the above code ran with no problems. Then I removed the call to my line removed and replaced it by the original PreferenceManager.setDefaultValues. And got the same error. What is going on inside this method? Why do I have no problems but the preferred line of code does?
There is a database involved and it's not been opened at the particular point where the error occurs, but SQLiteDatabase and SharedPreferences don't talk to each other directly anyway. That's my job (e.g., to allow user to set different values for any of the prefs and keep those values until changed by user).
Something about the way I am handling preferences is obviously wrong. But what?
Here's the relevant part of onCreate in MainActivity:
@Override protected void        onCreate(Bundle savedInstanceState)
{
  super.onCreate(savedInstanceState);

  sp = getDefaultSharedPreferences(this);
  sp.registerOnSharedPreferenceChangeListener(preferenceChangeListener);

  PreferenceManager.setDefaultValues(this, R.xml.preferences_no_table, true);
  mDatabase = myGetDatabase();
}

(sp is defined like so:   static SharedPreferences sp;)
P.S. Same error with PreferenceManager.setDefaultValues(this, R.xml.preferences_no_table, false);


text:
Q: Populating Drop Menu from Array Using JavaScript I need to dynamically generate a drop-menu list from an array via JavaScript. I'm getting close, but while I can populate the array elements into the Bootstrap-enabled drop-menu that appears on my index.html page, I cannot select those individual elements that show up as drop menu items. I need to edit my code so I can click on one of those elements and run my second function, that populates the selection to an input field.
First, here's my script to iterate over the array:

And here's the second script I use:

And here's the drop-menu section in my HTML where I'm trying to use this:

    <button class="btn btn-default btn-primary dropdown-toggle" type="button" data-toggle="dropdown">
      Select Job Type to Schedule
      </button>

Notice I am adding the "id" to the
 element. Should it be going elsewhere? I did try putting the "id" on the
 element, but that makes all the array elements one clickable field, rather than each one being clickable.
Right now, when I click on the drop-menu button, the different jobs do appear. However, they are not individually clickable.
What do I need to edit in my code to make each element a clickable link?

A: To match what you have templated, you need to do the following:

  let select = document.getElementById("selectJob");
    let options = ["Job 1", "Job 2", "Job 3", "Job 4", "Job 5"];
    for (let i = 0; i < options.length; i++) {
      let opt = options[i];
      let a = document.createElement("a");
      a.textContent = opt;
      a.setAttribute('href', '#');
      a.setAttribute('onclick', 'populateJobVal(selectJob)');
      a.setAttribute('class', 'btn btn-link');
      let li = document.createElement("li");
      li.appendChild(a);
      select.appendChild(li);
    }

 function populateJobVal(val) {
      document.getElementById("selection").value = val;
    }

    <button class="btn btn-default btn-primary dropdown-toggle" type="button" data-toggle="dropdown">
      Select Job Type to Schedule
      </button>

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can particles undergo length contraction if they're 0 dimensional? Take idea of relativistic magnetism, for example. How can a magnetic field be generated due to the electrons undergoing length contraction relative to the positive charges if the electrons moving through the wire themselves have no length?

A: Their three-dimensional fields get squished.

A: I assume your talking about a positive ion lattice with free electrons moving at $\beta$. This is one of the most misunderstood SR problems on the internet.
In the wire lattice frame, the proton and electron densities are the same:
$$\rho_+=-\rho_-$$
(by definition…it is stipulated in the problem that the wire is neutral in its rest frame). Hence, there is just a magnetic field $B$.
Now in a primed frame moving at $\beta$, so that the current electrons are at rest, the positive lattice is Lorentz contracted, and the density increases:
$$ \rho_+' = \gamma\rho_+$$
Moreover, they are moving at $-\beta$, so they create a current:
$$ I_+=-\beta\rho_+'$$
Fine. It's the electrons that confuse everyone.
They are not in a lattice. They are not one physical object. They are many independent objects that, when the current is turned on, accelerate with identical profiles in the initial rest frame of the wire. Again, this is stipulated b/c the wire remains neutral.
At this point, you need to master Bell's spaceship paradox, where each electron is a spaceship accelerating uniformly in the wire frame.
If you do not understand Bell's spaceship paradox, you will not understand this problem. Period.
It means in any electron's rest frame, the other electrons spread out and the charge density decreases to:
$$ \rho_-' = \rho_-/\gamma $$
With zero current from electrons:
$$ I'_- = 0 $$
Now use those charge and current densities to compute $B'$ and $E'$. You will find they are the exact transforms of $B$ and $E=0$, by $\beta$.
Everything works out just fine,as it always does.
In thinking about the problem: in the wire rest frame, the moving electrons pass the ions all simultaneously, so that in the electron restframe: they don't. That might clear up apparent contradictions.


text:
Q: Gremlin Query Language: how to drop every vertex that is not edged to anything? As the title suggests. How do I drop every vertex that does not have any edges?

A: You could do:
g.V().where(bothE().limit(1).count().is(lt(1)).drop()

or perhaps:
g.V().where(__.not(bothE())).drop()


text:
Q: Accessing the API logger in Flask-Restful's resources I'm currently using flask-restful (http://flask-restful.readthedocs.io/en/0.3.5/index.html) to deploy resources as endpoints and I'm wondering if there's a way to access the API logger from within then resources classes. I've skimmed through the docs and couldn't find the appropriate answer.
Basically I want to do that :
from flask_restful import Resource

class SomeEndpoint(Resource):

    def get(self):

        try:

            ... something throws an exception

        except SomeException as se:

            ... send custom message to API logger         <----- Here!

        return response

What I though of doing was passing the logger from the API through the constructor of the Resource like that :
App = Flask(__name__)
api = Api(App)
api.add_resource(SomeEndpoint, '/', resource_class_kwargs={'logger': App.logger})

Is this the most appropriate way to access the logger inside flask-restful resource endpoints ?
Thanks a lot

A: You need to define constructor of Resource. Here an example:
import logging

class SomeEndpoint(Resource):

    def __init__(self, **kwargs):
        self.logger = kwargs.get('logger')

    def get(self):
        # self.logger - 'logger' from resource_class_kwargs
        return self.logger.name

api.add_resource(SomeEndpoint, '/', resource_class_kwargs={
    # any logger here...
    'logger': logging.getLogger('my_custom_logger')
})

Open your endpoint. You will see my_custom_logger.
Hope this helps.

A: I know the answer has been chosen already, but there is a slightly different approach that also works.
First, import
from flask import current_app as app
in the resource file, and when calling the logger, do:
app.logger.info("This is an info message")

A: Setting debug=False temporarily fixes the problem.
But I dont really know what is the issue when debug is set to True


text:
Q: The right way to test rxjs I brought the book "rxjs in action" and just finish the testing section.
Testing rxjs codes are different then usual testing, because everything are lazy loading.
In the book, they mention two test method, either passing done(I am using QUnit and done signals async code is finish) or marble diagrams.
My question is, which method should I choose, that I have mentioned above?

A: I have been getting this question a lot from my colleagues. I finally got around to document my ways of testing RxJs on my blog. Since your question seems to be related to RxJs5 i will only quote the relevant part of my post here.
Testing in RxJs5 the RxJs4 way
When you migrate your codebase from RxJs4 towards 5 you will find out that a lot of things have been moved, renamed and above all that the implementation of the TestScheduler is no longer available. RxJs contributor kwonoj has created a compatibility shim to help migration towards RxJs5. You can install it using npm npm install @kwonoj/rxjs-testscheduler-compat. Not all features of the TestScheduler are implemented but the most important .startScheduler is working.
const TestScheduler = require('@kwonoj/rxjs-testscheduler-compat').TestScheduler;
const next = require('@kwonoj/rxjs-testscheduler-compat').next;
const complete = require('@kwonoj/rxjs-testscheduler-compat').complete;

it('works in RxJs5 with the compat package', () => {
  const scheduler = new TestScheduler(); // Note; no longer the Rx.TestScheduler

  const results = scheduler.startScheduler(
    () => Rx.Observable.interval(100, scheduler).take(3),
    { created: 100, subscribed: 200, unsubscribed: 1000 } // NOTE: disposed is now renamed to unsubscribed
  );

  collectionAssert.assertEqual(res.messages, [
    next(200 + 100, 0),
    next(200 + 200, 1),
    next(200 + 300, 2),
    complete(200 + 300)
  ]);
});

Testing in RxJs5 using the new Marble testing syntax
The RxJs team has introduced marble testing syntax to more visually define how your operator or custom code should operate.
var e1 = hot('----a--^--b-------c--|');
var e2 = hot(  '---d-^--e---------f-----|');
var expected =      '---(be)----c-f-----|';

expectObservable(e1.merge(e2)).toBe(expected);

At the time of writing this post they have not yet made this approach really easy to use outside of the RxJs5 library itself. There are implementations available to see how to do it yourself. You can also look around in the codebase of RxJs5 to see how to setup your testing framework to do your own marble tests. There is an open issue about documenting testing with RxJs5. I have not yet succeeded to get my testing framework setup to do marble testing in this way.

A: Time has passed, and now it is definitely possible (even easy) to use these marble tests yourself using TestScheduler. They are a great way to comprehensively test emissions over time, errors, completions and subscriptions in an easy-to-understand format. Here is a sample from their docs:
import { TestScheduler } from 'rxjs/testing';

const testScheduler = new TestScheduler((actual, expected) => {
  // asserting the two objects are equal
  // e.g. using chai.
  expect(actual).deep.equal(expected);
});

// This test will actually run *synchronously*
it('generate the stream correctly', () => {
  testScheduler.run(helpers => {
    const { cold, expectObservable, expectSubscriptions } = helpers;
    const e1 =  cold('-a--b--c---|');
    const subs =     '^----------!';
    const expected = '-a-----c---|';

    expectObservable(e1.pipe(throttleTime(3, testScheduler))).toBe(expected);
    expectSubscriptions(e1.subscriptions).toBe(subs);
  });
});

If you use Jasmine, I wrote a little helper called marbleTest() to reduce boilerplate, available in @s-libs/ng-dev:
import { marbleTest } from "s-ng-dev-utils";

it("generate the stream correctly", marbleTest(helpers => {
  const { cold, expectObservable, expectSubscriptions, testScheduler } = helpers;
  const e1 = cold(" -a--b--c---|");
  const subs = "    ^----------!";
  const expected = "-a-----c---|";

  expectObservable(e1.pipe(throttleTime(3, testScheduler))).toBe(expected);
  expectSubscriptions(e1.subscriptions).toBe(subs);
}));


text:
Q: Positive word for Premonition I wanted to use the word "Premonition" in a sentence, but when I checked the meaning I got "A feeling of evil to come", which was far from what I wanted to convey.
So I checked synonyms like "boding", "foreboding", "forewarning", "Presentiment", and so on. All had ominous connotations or a negativity or a sense of evil attached to the meaning.
So here I am, asking if there is a positive word for premonition, without negative implications.

UPDATE: "Hunch" is the word I select as matching my requirements, from all the answers I got.

A: A simple "prediction" would probably work.  It more relates to a suspicion rather than a 'gut feeling', but it carries no negative connotations towards the suspicion.
"Premonition" itself doesn't carry too heavy a negative connotation either, so you'd probably be safe using it as-is.  Though I wouldn't use "boding", "foreboding" or "forewarning", since those carry a little more negative weight.

A: A vision would also achieve the same effect with no negative connotations.
Though a vision portrays a vivid premonition where the person receiving it is able to see things that will happen in future, and is far more descriptive than a gut-feeling or hunch.
If you intend to portray a gut-feeling, vision will not fit.

A: Divination
1.
the practice of attempting to foretell future events or discover hidden knowledge by occult or supernatural means.
2.
augury; prophecy: The divination of the high priest was fulfilled.
3.
perception by intuition; instinctive foresight.
A more informal word could be Hunch

A: Precognition. Carries a serious psychiatric stain in German though. Alike all precognitive people are automatically suffering schizophrenia or worse.
I would summarize "clear-minded estimation", but I don't know how to bring that down to one word. INTUITION could be used for it though.
Paradoxically (?) there are more "clear-minded estimations" by scientists than by fortune-tellers and esoteric-fans.

A: Just say "positive premonition". It's thought provoking and challenges the reader's definition of premosition.  There are adjectives for a reason.


text:
Q: Is it ok to define a prototype function on Object in Javascript? Object.prototype.doSomething = function(p) {
    this.innerHTML = "bar";
    this.style.color = "#f00";
    alert(p);
};

document.getElementById("foo").doSomething("Hello World");

foo

The code above works fine.
But I remember that I saw this somewhere: Do not mess with native Object. well, something like that.
So is it ok to define a prototype function on Object? Are there any reasons that I should not do this?

A: The only safe way to add to Object.prototype is to use the ES5 method Object.defineProperty to create a non-enumerable property:
Object.defineProperty(Object.prototype, 'doSomething', {
    value: function(p) { ... },
    enumerable: false,  // actually the default
});

This ensures that the new property doesn't appear if you do for (key in object).
Note that this function cannot be reliably shimmed because non-enumerable properties didn't exist in previous versions of ECMAScript / JavaScript.
In any event, if your method only applies to HTML page elements, you would be better adding this to Element.prototype instead of to Object.prototype, although older (IE) browsers may complain if you do this.

A: Generally not a good idea.  That function is now available on everything in your app that uses the Object prototype(which is a lot) and will show up in functions that enumerate the Object proto.
A better option is to define a separate prototype:
function MyObject {
    ...
}

MyObject.prototype.doSomething = function() {
    ...
}

var myObj = new MyObject();

A: If you add stuff to the object prototype, you lose the nice object iteration functionality using for p in obj, since enumerable properties you have added are iterated over as well on all objects.
For example:
Object.prototype.doSomething = function(p) {
    this.innerHTML = "bar";
    this.style.color = "#f00";
    alert(p);
};

for (p in {foo:"bar"}){
    console.log(p);
}

//foo
//doSomething

Unexpectedly, you will also get doSomething logged. To fix this, you will have to add a hasOwnproperty check when iterating over your object, but the risk here is that you could break other code that doesn't expect a plain object to have properties other than the ones specified in the literal.

A: Another option is to call a method, defined not as an object prototype method-
function doSomething(p) {
    this.innerHTML = ""+p+"";
    this.style.color = "#f00";
    alert(p);
};

//
doSomething.call(document.getElementById("foo"),"Hello World");


text:
Q: Is it grammatical to say of some potential meaning that it is "able to be said" or "trying to be said"? A recent commenter on a recent word-search question nominated a term as "an even better word for what is trying to be said." This seems to me to attribute intention to something—a meaning—that is incapable of intention. I have also encountered this same fallacy, as it seems to me, with words such as able and ability followed by passive infinitive, in such a way as seemingly and absurdly to locate the ability in question in the patient rather than the agent. For some reason, passive constructions like "capacity to be [past participle]," and "capability of being [past participle]," which respectively locate the capacity and the capability in the patient, do not likewise bother me in the least:

The 235U nucleus has the unique capacity to be split by a neutron into 89Kr, 144Ba, and three neutrons that can in turn split further 235U nuclei.

But I would never say or write that the nucleus is able or has the ability to be split.
To say that something "can be said" is unquestionably grammatical, and some instances of "able to be said" result from trying to put that into the future tense or conditional mood, as "will/would/could/should be able to be said." To say that something is sayable is also unexceptionable: adjectives in -able or -ible normally tend to modify or be predicated of the patient.
A Google Books ngram of "able to  be said," "trying to  be said," and  "try to  be said" shows very low but non-zero frequencies for the former two. A plain-vanilla Google search for "able to  be said" turns up (besides a few instances where a comma and right-hand quotation mark separate be from said) a surprisingly high proportion of results from Google books, and a surprisingly high proportion of results that are products of translation from other languages. (Also and less unexpectedly I found among the top results one that resulted from a transformation of "can be said" as discussed above.) Searching for "passive infinitive" in combination with "able" or "try" led me to some on-line grammatical resources, but the only one to discuss this particular problem was a page I had written for my students a few months back.

A: AHD has this to say about whether or not 'This is able to be said' is allowable:

Usage Note:
The construction able to takes an infinitive to show the subject's
  [referent's] ability to accomplish an action:
We were able to get a grant for the project.
The new submarine is able to dive twice as fast as the older model.
Some people think it should be avoided when the subject does not
  have an ability, as in sentences with passive constructions involving
  forms of the verb be:
The problem was able to be solved by using a new lab technique.
The reasoning here is that since the problem has no ability to
  accomplish an action, it is not able to do anything, and therefore
  able to should not be used.
Presumably this ban would apply to similar words like capable and to
  negative words like unable and incapable. In such cases one can
  usually avoid the problem by using can or could:
The problem could be solved....
Keep in mind, however, that passives with get ascribe a more active
  role to their subjects, and here one can use able to:
He was able to get accepted by a top law school.


text:
Q: How To: UiBinder + GWT MVP + multiple independent display areas I am using GWT MVP and UiBinder to create an app with a DockLayoutPanel.  I want the north and south docks to be static, containing buttons and links.  I want to have dynamic views in the center and two different areas of the east dock.  As these dynamic areas should be independent of each other, I am setting up different ActivityMapper and ActivityManager's for each dynamic display area; center, east-top, and east-bottom.
How can I independently initialize these 3 different display areas when the application is loaded?  How can I switch from one Activity to another in one display area without affecting the other areas?
When I use the the PlaceController's goTo to switch from one Place to another in one area, the other area's Activity is stopped.
Mayday, please help, mayday!
The following is some of my code:
AppViewImpl.ui.xml
<g:DockLayoutPanel styleName="{style.dockPanel}" unit="PX" width="975px" height="100%">

    <!-- DOCK PANEL EAST -->
    <g:east size="220">
        <g:LayoutPanel styleName="{style.eastPanel}">
            <g:layer left="0px" width="220px" top="0px" height="105px">
                <g:SimpleLayoutPanel ui:field="topRightPanel"/>
            </g:layer>

            <g:layer left="0px" width="220px" top="110px" height="340px">
                    <g:InlineLabel styleName="{style.label}" text="ANOTHER DISPLAY AREA"/>
            </g:layer>
        </g:LayoutPanel>
    </g:east>

    <!-- DOCK PANEL NORTH -->
    <g:north size="110">
        <g:LayoutPanel styleName="{style.northPanel}">
            <g:layer left="0px" width="755px" top="0px" height="105px">
                    <g:InlineLabel styleName="{style.label}" text="NORTH PANEL"/>
            </g:layer>
        </g:LayoutPanel>
    </g:north>

    <!-- DOCK PANEL SOUTH -->
    <g:south size="20">
        <g:LayoutPanel styleName="{style.southPanel}">
            <g:layer left="0px" width="755px" top="0px" height="20px">
                    <g:InlineLabel styleName="{style.label}" text="SOUTH PANEL"/>
            </g:layer>
        </g:LayoutPanel>
    </g:south>

    <!-- DOCK PANEL CENTER -->
    <g:center>
        <g:SimpleLayoutPanel ui:field="mainPanel" />
    </g:center>
</g:DockLayoutPanel>

MyModule.java
public class MyModule implements EntryPoint {
private Place defaultPlace = new DefaultPlace("");

public void onModuleLoad() {
    // Create ClientFactory using deferred binding so we can replace with
    // different impls in gwt.xml
    ClientFactory clientFactory = GWT.create(ClientFactory.class);
    EventBus eventBus = clientFactory.getEventBus();
    PlaceController placeController = clientFactory.getPlaceController();

    // Start ActivityManager for the main widget with our ActivityMapper
    ActivityMapper topRightActivityMapper = new TopRightActivityMapper(clientFactory);
    ActivityManager topRightActivityManager = new ActivityManager(topRightActivityMapper, eventBus);
    topRightActivityManager.setDisplay(clientFactory.getAppView().getTopRightPanel());

    // Start ActivityManager for the main widget with our ActivityMapper
    ActivityMapper mainActivityMapper = new AppActivityMapper(clientFactory);
    ActivityManager mainActivityManager = new ActivityManager(mainActivityMapper, eventBus);
    mainActivityManager.setDisplay(clientFactory.getAppView().getMainPanel());

    // Start PlaceHistoryHandler with our PlaceHistoryMapper
    AppPlaceHistoryMapper historyMapper = GWT .create(AppPlaceHistoryMapper.class);
    PlaceHistoryHandler historyHandler = new PlaceHistoryHandler(historyMapper);
    historyHandler.register(placeController, eventBus, defaultPlace);
    RootLayoutPanel.get().add(clientFactory.getAppView());

    // Goes to place represented on URL or default place
    historyHandler.handleCurrentHistory();

    new AppController(clientFactory);
}

}
AppController.java
public class AppController implements AppView.Presenter {

    private ClientFactory clientFactory;

    AppController(ClientFactory clientFactory){
        this.clientFactory = clientFactory;
        goTo(new TopRightAPlace(""));
    }

    @Override
    public void goTo(Place place) {
        clientFactory.getPlaceController().goTo(place);
    }

}

TopRightAViewImpl.java
public class TopRightAViewImpl extends Composite implements TopRightAView {

    interface Binder extends UiBinder<Widget, TopRightAViewImpl> {
    }

    private static final Binder binder = GWT.create(Binder.class);

    private Presenter listener;
    @UiField
    Button button;

    public TopRightAViewImpl() {
        initWidget(binder.createAndBindUi(this));
    }

    @Override
    public void setName(String name) {
        button.setHTML(name);
    }

    @Override
    public void setPresenter(Presenter listener) {
        this.listener = listener;
    }

    @UiHandler("button")
    void onButtonClick(ClickEvent event) {
        listener.goTo(some other place);
    }
}

A: GWT Places, PlaceController, and PlaceHistoryMapper enable you to create bookmarkable URLs within your application that allow the browser's back button and bookmarks to work as one would expect.  This is what GWT Places was designed for.  Therefore it does not make sense to have more than one Place activated in an application at any point in time since you have one URL for the entire application.
PlaceController's goTo() method does notify the registered ActivityManager, which stops the current Activity upon receiving a PlaceChangeEvent.
My suggestion for you is not to use Places and PlaceChangeEvents for the two areas on the east side of your DockLayoutPanel.  Use Places for your application's main screen, which is probably the center of your DockLayoutPanel.  Fire different GwtEvent types, either one of the generic event types (ie. ValueChangeEvent) or a custom event type, for the areas on the east side when you need to have them updated.  You could still use Activities for the east side, but you would need to create your own ActivityManager, which is actually not that hard.  All you have to do is to copy GWT's ActivityManager, rename it, and replace the names of methods that handle PlaceChangeEvents and PlaceChangeRequestEvents with those that handle your own events.

A: Are you sure you really want to use google's mvp implementation? It's failry easy to implement this mechanism using mvp4g. The main module would be responsible for initializing main view and providing logic to reload dynamic areas. I used this framework in two large projects and works like a charm.


text:
Q: Input validation by regexp in Safari Modern browsers, including Safari, support pattern validation on inputs, such as:
<input type="text" pattern="[a-z]+">
Is using Unicode Categories somehow special?
Pattern [\p{L}]{1,100} doesn't work in Safari, but works in Chrome:

<!DOCTYPE html>
<html lang="en">
<body>
  <form>
    <!--
    "hello" should be a valid input
    works in chrome 66
    doesn't work in safari 11.1
    -->
    <input type="text" pattern="[\p{L}]{1,100}" name="bar" value="">
    <input type="submit">
  </form>
</body>
</html>

A: ECMAScript TC39
This is similar to other issues involving Chrome's ability to process lookbehinds in regex, but other browsers being incapable of the same. At the moment, this is part of the Ecma TC39 proposals under ECMAScript proposal: Unicode property escapes in regular expressions. It is scheduled to be included in ES2018.
So far this has been implemented in Chrome 64, Safari Preview 42 and regexpu (transpiler) according to that link.
There are a couple of workarounds for Unicode properties in JavaScript at the moment (also described in the link). The workarounds do not work for the HTML5 pattern attribute.
XRegExp

Use a library such as XRegExp to create the regular expressions
  at run-time:
const regexGreekSymbol = XRegExp('\\p{Greek}', 'A');
regexGreekSymbol.test('π');
// → true

The downside of this approach is that the XRegExp library is a
  run-time dependency which may not be ideal for performance-sensitive
  applications. For usage on the web, there is an additional load-time
  performance penalty: xregexp-all-min.js.gz takes up over 35 KB of
  space after minifying and applying gzip compression. Whenever the
  Unicode Standard is updated, a new version of XRegExp must be
  published and end users need to update their XRegExp copy in order to
  use the latest available data.

Regenerate

Use a library such as Regenerate to generate the regular
  expression at build time:
const regenerate = require('regenerate');
const codePoints = require('unicode-9.0.0/Script/Greek/code-points.js');
const set = regenerate(codePoints);
set.toString();
// → '[\u0370-\u0373\u0375-\u0377\u037A-\u037D\u037F\u0384\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03E1\u03F0-\u03FF\u1D26-\u1D2A\u1D5D-\u1D61\u1D66-\u1D6A\u1DBF\u1F00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FC4\u1FC6-\u1FD3\u1FD6-\u1FDB\u1FDD-\u1FEF\u1FF2-\u1FF4\u1FF6-\u1FFE\u2126\uAB65]|\uD800[\uDD40-\uDD8E\uDDA0]|\uD834[\uDE00-\uDE45]'
// Imagine there's more code here to save this pattern to a file.

This approach results in optimal run-time performance, although the
  generated regular expressions tend to be fairly large in size (which
  could lead to load-time performance problems on the web). The biggest
  downside is that it requires a build script, which gets painful as the
  developer needs more Unicode-aware regular expressions. Whenever the
  Unicode Standard is updated, the build script must be updated and its
  results must be deployed in order to use the latest available data.

I should also add that you can actually drop the [] from your regex: \p{L}{1,1000}


text:
Q: How do I improve and isolate from mains ground my Tesla coil control circuit? I made this circuit for my tesla coil. It is a glorified slayer exciter. I based my circuit one the one shown here
Both the coil supply and the control circuit supply come from an appropriately modified microwave oven transformer. The transformer core is grounded, and I noticed some sparks going from the 12V secondary to the core. These sparks only happen when the control circuit is activated and the secondary is generating high voltages. I suspect the diodes used to clip the input for the MOSFET driver are transferring the high voltage to the supply rail and thus to the transformer winding. Is there any way to prevent the MOSFET driver from frying and at the same time prevent high voltages in the supply rail? Can you suggest any improvements to the control circuit?
From what I gather high voltages in the mains system are very dangerous for appliances connected to the same network, so the transformer arcing is very bad news. I'd prefer not to switch it on until this is fixed.

simulate this circuit – Schematic created using CircuitLab
Here is the transformer with a resistive ballast, the bridge rectifiers and the capacitors.

A: I would eliminate the feedback loop from the transformer secondary (HV) and use a simple oscillator  (e.g. 555) to drive the '151 FET driver. Then you can fully take advantage of the isolation provided by T3.
I would also consider adding a snubbing diode across the primary of the tranformer to knock down the transients into the supply.


text:
Q: Uncaught TypeError: Cannot read properties of undefined (reading 'id') - how to solve? I'm creating a form that is supposed to create a new restaurant, it worked last night but I accidentally changed something and had to undo a couple of times and now I can't fix this error that I received
NewRestoranForm.js:15 :
  Uncaught TypeError: Cannot read properties of undefined (reading 'id')

This is the code :
import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { useAddNewRestoranMutation } from "./restoraniApiSlice";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faSave } from "@fortawesome/free-solid-svg-icons";

const NewRestoranForm = ({ users }) => {
  const [addNewRestoran, { isLoading, isSuccess, isError, error }] =
    useAddNewRestoranMutation();

  const navigate = useNavigate();

  const [naziv, setNaziv] = useState("");
  const [adresa, setAdresa] = useState("");
  const [userId, setUserId] = useState(users[0].id);

  useEffect(() => {
    if (isSuccess) {
      setNaziv("");
      setAdresa("");
      setUserId("");
      navigate("/restorani");
    }
  }, [isSuccess, navigate]);

  const onNazivChanged = (e) => setNaziv(e.target.value);
  const onAdresaChanged = (e) => setAdresa(e.target.value);
  const onUserIdChanged = (e) => setUserId(e.target.value);

  const canSave = [naziv, adresa, userId].every(Boolean) && !isLoading;

  const onSaveRestoranClicked = async (e) => {
    e.preventDefault();
    if (canSave) {
      await addNewRestoran({ user: userId, naziv, adresa });
    }
  };

  const options = users.map((user) => {
    return (
      <option key={user.id} value={user.id}>
        {" "}
        {user.username}
      </option>
    );
  });

  const errClass = isError ? "errmsg" : "offscreen";
  const validNazivClass = !naziv ? "form__input--incomplete" : "";
  const validAdresaClass = !adresa ? "form__input--incomplete" : "";

  const content = (
    <>

{error?.data?.message}

      <form className="form" onSubmit={onSaveRestoranClicked}>

New Restoran

            <button className="icon-button" title="Save" disabled={!canSave}>
              <FontAwesomeIcon icon={faSave} />
            </button>

          Naziv:

        <input
          className={`form__input ${validNazivClass}`}
          id="naziv"
          name="naziv"
          type="text"
          autoComplete="off"
          value={naziv}
          onChange={onNazivChanged}
        />

          Adresa:

        <textarea
          className={`form__input form__input--text ${validAdresaClass}`}
          id="adresa"
          name="adresa"
          value={adresa}
          onChange={onAdresaChanged}
        />

          ASSIGNED TO:

        <select
          id="username"
          name="username"
          className="form__select"
          value={userId}
          onChange={onUserIdChanged}
        >
          {options}
        </select>
      </form>
    </>
  );

  return content;
};

export default NewRestoranForm;

And this is NewRestoran.js that its importing:
import { useSelector } from "react-redux";
import { selectAllUsers } from "../users/usersApiSlice";
import NewRestoranForm from "./NewRestoranForm";

const NewRestoran = () => {
  const users = useSelector(selectAllUsers);

  const content = users ? <NewRestoranForm users={users} /> :
Loading...
;

  return content;
};
export default NewRestoran

I've gone line thru line and I don't see any change from when the code worked, there is supposed to be a form for creating a new restoran but all I get is errors in console

A: In your NewRestoran you get the users from your Redux Store. By looking at your code it will return a array of users.
In the NewRestoranForm you try to set the state userId by assuming the users variable has a value on index 0.
const [userId, setUserId] = useState(users[0].id);

The users arrary has to be an empty array since you can't find any value on index 0. You could fix this like so
const [userId, setUserId] = useState(users[0]?.id || "");


text:
Q: € Symbol from commandline (Arguments) I have a simple euro_to_dm command line program written but the "€" symbol doesn't work. The example change every time "dm to euro" but not "€ to dm". Sorry for my English.
Ubuntu 19.4 ise-eiffel AND liberty-eiffel
class EURO

inherit ARGUMENTS_32

create {ANY}
   make

feature {ANY}

   make
      do
         works_not
      end

   works_not
      local ok: BOOLEAN
      do
         print ("%N%NAnzahl Argumente : " + argument_count.out + "%N")
         print ("%NArgument -> Programmname    : " + argument(0))
         print ("%NArgument -> Wert            : " + argument(1))
         print ("%NArgument -> Währung         : " + argument(2) + "%N")

         ok := argument(2).is_equal("€")
         print ("%NArgument(2) ist Euro ?  " + ok.out + "%N%N")

         print ("don't work")
         io.put_new_line

         if argument(2).is_equal("€") then
            euro_in_dm(argument(1).to_real)
         else
            dm_in_euro(argument(1).to_real)
         end
      end

feature {ANY}

   euro_in_dm (a: REAL)
      do
         io.put_string("%N Euro -> DM ")
         io.put_real(a * 1.95583)
         io.put_string("%N%N")
      end

   dm_in_euro (a: REAL)
      do
         io.put_string("%N DM -> Euro ")
         io.put_real(a / 1.95583)
         io.put_string("%N%N")
      end

end

A: To create manifest Unicode string, you should use {STRING_32} "€"
To compare strings, you'd better use same_string, i.e
    if s.same_string ({STRING_32} "€") then ...
Note the syntax for manifest Unicode character using the hexadecimal value is {CHARACTER_32} '%/0x20AC/'
To output Unicode in console/terminal, it is better to use the LOCALIZED_PRINTER from the encoding library.
see https://www.eiffel.org/blog/jocelyn_fiat/lets_talk_about_the_encoding_library#Write_unicode_into_the_console

A: Here the program that works (this is in spanish). You should include the library encoding to your project. You cannot show the symbol € with print, you should use localized_print.
class
    EURO

inherit
    ARGUMENTS_32
    LOCALIZED_PRINTER

create
    make

feature {ANY}

   make
      do
         works_not
      end

   works_not
      local ok: BOOLEAN
      do
         print ("%N%NArgumentos                 : " + argument_count.out + "%N")
         print ("%NArgument -> Programa         : " + argument(0) + "%N")
         print ("%NArgument -> Valor            : " + argument(1) + "%N")
         localized_print ({STRING_32} "%NArgument -> Moneda           : " + argument(2) + {STRING_32} "%N")

         ok := argument(2).item(argument(2).lower).is_equal ('%/0x000020AC/')
         print ("%NArgument(2) ist Euro ?  " + ok.out + "%N%N")

         if ok then
            euro_in_dm(argument(1).to_real)
         else
            dm_in_euro(argument(1).to_real)
         end
      end

feature {ANY}

   euro_in_dm (a: REAL)
      do
         io.put_string("%N Euro -> DM ")
         io.put_real(a * 1.95583)
         io.put_string("%N%N")
      end

   dm_in_euro (a: REAL)
      do
         io.put_string("%N DM -> Euro ")
         io.put_real(a / 1.95583)
         io.put_string("%N%N")
      end


text:
Q: Angular Material Virtual Scroller gets stuck sometimes on Mobile only unsure why HTML
<section fxLayout="column" fxLayoutAlign="center center" class="vwubble-section" fxFlex="auto">
        <ng-container *ngIf="(allBubbles$ | async)">

                <cdk-virtual-scroll-viewport #scroller itemSize="355" class="scrolling-container scrollbar-hidden" minBufferPx="1200" maxBufferPx="1200">
                    <vw-vwubbles-item *cdkVirtualFor="let bubble of allBubbles$"
                                      [bubble]="bubble">
                    </vw-vwubbles-item>
                </cdk-virtual-scroll-viewport>

        </ng-container>
</section>

CSS
.vwubble-section {
    padding: 0px;
    margin: 0px;
    padding-top: 20px;
    min-width: 100%;
    /* padding-top: 300px; */
    background-color: #000;
    /* margin-bottom: 60px; */
    /* height:  1400px;
    overflow:hidden; */
}

.mat-form-field-appearance-fill .mat-form-field-flex{
    background-color: white;
}

::ng-deep .mat-select-value {
    color: #673ab7;
}

.scrolling-container{
    /* display: flex; */
    min-height: 1600px;
    /* flex-grow: 1; */
    width: 100%;
    max-width:800px;
    overflow-y: scroll;
    padding: 0px;
    overflow-x: hidden;
}
.scrolling-container::-webkit-scrollbar {
    width: 0;  /* Remove scrollbar space */
    background: transparent;  /* Optional: just make scrollbar invisible */
}

So these vwubble-items are like tweets, and the scroll gets stuck when the user tries to scroll down on mobile, but the weird thing is that I am using this same scrolling method for the replies to these main threads, and these replies never get stuck ever.
Any help would be much appreciated.


text:
Q: Python: Break and rejoin a list Is it possible to break from a for loop of question and rejoin on the next question after running other code.
answer = raw_input("Did you eat in or take out: ")
answers1 = ""
if 'in' in answer:
    questions1 = ["What was the restaurant like ?  ","What was the food like ? ", "Was the waiter attentive ?"]
    for i in questions1:
        print i
        ans = raw_input("Type your answer: ")
        answers1 = answers1 +" "+ ans+"."
        call(answers1)
        if  not n_topics:
            print("No negative topic" + '\n' )
        else:
            print "negative topic" , n_topics
            break

So this code breaks from the for loop if there is a negative answer, but can I rejoin on the next question after dealing with the negative answer.

A: Use continue instead of break.


text:
Q: How to securely implement SQL queries in a Java desktop app I am creating a Java desktop application that generates and stores users passwords on a database.
My question is: what is the most secure way to implement SQL queries in the application?
Surely it is not secure to have the queries within the source code. My work around would be to store the db file locally, but I would prefer to store the data on an external server.
So how do I implement SQL queries in a swing application without having them embedded the source code.

A:
Surely it is not secure to have the queries within the source code.

I have never seen an SQL query that was sensitive. Typically you accept the sensitive data from the user (e.g. password input into Swing field) and use this to populate an existing parameterized query, e.g.
UPDATE users SET password=? WHERE username=?

A: I dont know how do you want to execute something in your application without implementing it. I just simply dont understand your approach. You are probably want to register new user or something, and you dont't want to reveal your database structure in any way, am I right? You can't do something like that to directly operate on DB (by sql) and not code it into app.
Solution:
Create dedicated REST API for your needs. All db operation handling would be on server side (hah, you need server - can be simple apache hosting for php) so no DB structure revelations etc. All you would need to do would be send command to server with appropriate data - username and password. For maximum security you should use SSL for comunicating with API.
Thank you.

A: There is no need to protect query text. You may have concerns regarding logging of the parameters used by query. If you store raw passwords in the database this is a problem. So I would recommend to not store raw passwords in the first place.
I would elaborate a bit about embedding SQL into Java code. If you application works with database you need to make calls to database and this means execution of SQL statements. The only way to avoid this is to delegate this work to another application so your application will use not SQL but some custom protocol/API and that application will execute SQL queries on its behalf.
You may what to store SQL separately from Java code but this not due to security concerns but mainly because of need to more properly structure you application. That is main driving forces to not embed SQL into Java code are code readability, performance, maintenance and code reuse.
It is a common practice to use ORM when accessing database. In this case it not uncommon that your application do not have SQL code at all but access database through ORM API. In hibernate for example the query may look like
User user = session.createCriteria(User.class)
    .add( Restrictions.eq("name", userName) )
    .uniqueResult();

And even if you need to execute some SQL query which is not directly supported by ORM of your choice the SQL text itself is usually stored in some accompanied xml file.
Please note that in the latter case though technically SQL is not embedded into Java code it is still reside in one of your application packages.


text:
Q: Localhost is working but heroku deploy is not working after adding searchbar for users (heroku run rake db:seed error) I've added autocompleted searchbar for users to my app ("gem searchkick" and "elasticsearch" were used)  then it is great working on localhost. I have also added "SearchBox Elasticsearch -- Starter" to my Heroku app.
After I can push my app to heroku without fail but I've an error with "heroku run db:seed". (The first user can be installed but the second user is not)
How can I fix the problem?
Error
 Running rake db:seed on bloggerpoint... up, run.7859
 ActiveRecord::SchemaMigration Load (1.9ms)  SELECT "schema_migrations".* FROM "schema_migrations"
  (12.7ms)  BEGIN
 User Exists (1.6ms)  SELECT  1 AS one FROM "users" WHERE LOWER("users"."email") = LOWER('example@railstutorial.org') LIMIT 1
 SQL (1.1ms)  INSERT INTO "users" ("name", "email", "password_digest", "admin", "activated", "activated_at", "created_at", "updated_at", "activation_digest") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING "id"  [["name", "Example User"], ["email", "example@railstutorial.org"], ["password_digest", "$2a$10$tU5lWI6OSivx.9gONACjI.EHDrPgdhyQ9w/5rp6MxitVRpaRilbZu"], ["admin", "t"], ["activated", "t"], ["activated_at", "2015-12-08 20:06:39.898039"], ["created_at", "2015-12-08 20:06:40.199321"], ["updated_at", "2015-12-08 20:06:40.199321"], ["activation_digest", "$2a$10$kI/gNShPNgjz387uCxKBW.XT5OpYOJvL0ayb0G9EXRt6TqxgXjzTm"]]
 (2.0ms)  COMMIT

  User Store (5.9ms)  {"id":1,"exception":["Faraday::ConnectionFailed","Connection refused - connect(2)"]}
 rake aborted!

production.rb
 Elasticsearch::Model.client = Elasticsearch::Client.new host: ENV['search_box_url']

I've made addition to my User model and Gemfile before heroku deploy. My searchbar is working without them on localhost.
user.rb
include Elasticsearch::Model
include Elasticsearch::Model::Callbacks

Gemfile
 group :production do
    gem 'pg',             '0.17.1'
    gem 'rails_12factor', '0.0.2'
    gem 'puma',           '2.11.1'
    gem 'elasticsearch-model'
    gem 'elasticsearch-rails'
 end


text:
Q: MYSQL ignores not null constraint, inserts null values into table and only displays a warning I am using MYSQL versoin 14.14 Distrib 5.7.40, for Linux (x86_64). I have created a table with 3 columns and the columns have NOT NULL constraints set. Then when I try to insert null values directly into the table, it gives me an error saying the column cannot be null. However if I try to insert null values using a select statement, then MYSQL inserts a new record and only displays a warning. In the inserted record I see that the MYSQL has substituted NULL with empty string.
DROP TABLE IF EXISTS table1;

DROP TABLE IF EXISTS table2;

CREATE  TABLE IF NOT EXISTS table1 (
     id INT UNSIGNED NOT NULL AUTO_INCREMENT ,
     col_1 VARCHAR(45) NOT NULL ,
     col_2 VARCHAR(45) NOT NULL ,
     PRIMARY KEY (id));

CREATE TABLE IF NOT EXISTS table2 LIKE table1;

-- gets inserted as expected
INSERT INTO table1(id, col_1, col_2) VALUES (1,'aaa', 'bbb');
INSERT INTO table2(id, col_1, col_2) VALUES (2,'ccc', 'ddd');

-- does not get inserted as expected
INSERT INTO table1(col_1, col_2) VALUES ('xxx', NULL); -- ERROR 1048 (23000): Column 'col_2' cannot be null

-- gets inserted which I didn't expect, it gives a warning but inserts
INSERT INTO table1(id, col_1, col_2) SELECT id, col_1, NULL FROM table2 where id=2; -- Query OK, 1 row affected, 1 warning (0.07 sec)

I tried displaying the warning after the query execution. And it said, "Warning | 1048 | Column 'col_2' cannot be". But still MYSQL didn't stop me from inserting values into the table, it substituted empty string.
mysql> show warnings;
+---------+------+-------------------------------+
| Level   | Code | Message                       |
+---------+------+-------------------------------+
| Warning | 1048 | Column 'col_2' cannot be null |
+---------+------+-------------------------------+
1 row in set (0.00 sec)

mysql> select * from table1;
+----+-------+-------+
| id | col_1 | col_2 |
+----+-------+-------+
|  1 | aaa   | bbb   |
|  2 | ccc   |       |
+----+-------+-------+
2 rows in set (0.01 sec)

A: Why am I answering my own question? I had this question and found similar questions. The answers briefly pointed me to SQL STRICT MODE. But none of the answers are comprehensive, so I had to do my own digging. I have learnt how MYSQL NOT NULL CONSTRAINT, and the SQL STRICT MODE work together, and I would like to detail my answer here.
First let us understand, what happens when we try to insert NULL values into a column that has a NOT NULL constraint.
table1 has three columns id, col_1, and col_2 which all have NOT NULL constraints
mysql> desc table1;
+-------+------------------+------+-----+---------+----------------+
| Field | Type             | Null | Key | Default | Extra          |
+-------+------------------+------+-----+---------+----------------+
| id    | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| col_1 | varchar(45)      | NO   |     | NULL    |                |
| col_2 | varchar(45)      | NO   |     | NULL    |                |
+-------+------------------+------+-----+---------+----------------+
3 rows in set (0.03 sec)

When we try to insert explicit NULL values into the column, MYSQL will throw an error.
mysql> insert into table1(col_1, col_2) values (NULL,'xxx');
ERROR 1048 (23000): Column 'col_1' cannot be null

However if we try to skip a column (not inserting values), MYSQL will not give an error. Instead it will insert the record and only give a warning.
mysql> insert into table1(col_2) values ('xxx');
Query OK, 1 row affected, 1 warning (0.10 sec)

mysql> show warnings;
+---------+------+--------------------------------------------+
| Level   | Code | Message                                    |
+---------+------+--------------------------------------------+
| Warning | 1364 | Field 'col_1' doesnt have a default value |
+---------+------+--------------------------------------------+
1 row in set (0.00 sec)

mysql> select * from table1;
+----+-------+-------+
| id | col_1 | col_2 |
+----+-------+-------+
|  4 |       | xxx   |
+----+-------+-------+
1 row in set (0.00 sec)

We could also use a select query to insert values into a table. And in this case again MYSQL only gives a warning and inserts the record.
mysql> insert into table1(col_1, col_2) select NULL, col_2 from table2;
Query OK, 1 row affected, 1 warning (0.07 sec)
Records: 1  Duplicates: 0  Warnings: 1

mysql> show warnings;
+---------+------+-------------------------------+
| Level   | Code | Message                       |
+---------+------+-------------------------------+
| Warning | 1048 | Column 'col_1' cannot be null |
+---------+------+-------------------------------+
1 row in set (0.00 sec)

mysql> select * from table1;
+----+-------+-------+
| id | col_1 | col_2 |
+----+-------+-------+
|  4 |       | xxx   |
|  5 |       | ddd   |
+----+-------+-------+
2 rows in set (0.00 sec)

Now let us understand the SQL Modes in MYSQL. Strict mode controls how MySQL handles invalid or missing values in data-change statements such as INSERT or UPDATE. Please refer the MYSQL documentation for the details.
To check the current SQL mode, try the following.
mysql> select @@sql_mode;
+----------------------------------------------------------------------------------------------------+
| @@sql_mode                                                                                |
+----------------------------------------------------------------------------------------------------+
| NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION |
+----------------------------------------------------------------------------------------------------+
1 row in set (0.04 sec)

To set MYSQL to strict mode, try the following.
mysql> set sql_mode='STRICT_ALL_TABLES';
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> select @@sql_mode;
+-------------------+
| @@sql_mode        |
+-------------------+
| STRICT_ALL_TABLES |
+-------------------+
1 row in set (0.00 sec)

After MYSQL is set to strict mode, if you tried the previous insert statements they would fail with errors.
mysql> insert into table1(col_2) values ('xxx');
ERROR 1364 (HY000): Field 'col_1' doesnt have a default value
mysql> insert into table1(col_1, col_2) select NULL, col_2 from table2;
ERROR 1048 (23000): Column 'col_1' cannot be null

One more thing is that SQL_MODE will be set only for the current MYSQL session. If you want to set it forever, then you have to either set it in the GLOBAL or the MYSQL config files.
Try the following to set strict mode as a global SQL mode.
mysql> set global sql_mode='STRICT_ALL_TABLES';
Query OK, 0 rows affected, 1 warning (0.01 sec)

mysql> select @@global.sql_mode;
+-------------------+
| @@global.sql_mode |
+-------------------+
| STRICT_ALL_TABLES |
+-------------------+
1 row in set (0.00 sec)

I hope this very long answer sheds some light on the SQL mode and inserts in MYSQL. Please vote up the question and answer if you find it helpful.


text:
Q: Why is the WebBeans (JSR-299) Conversation Context tied to JSF? I am reading through the Public Review Draft of the Web Beans specification (JSR-299) and I am wondering why it is so 'tightly coupled' to JSF?
Especially the Conversation Context seems only be specified for JSF.
I understand, that it is a goal of WebBeans to integrate JSF and EJB3. But would it not make sense to specify the concept of conversations on a more general level (maybe for Servlets in general and not for a specific web framework)?
Is there any technical reason for this? I think it can hardly be, because Seam (which is some Kind of WebBeans-Prototype) does also support Wicket and provides the concept of conversations.
I think it would be helpful to have a Conversation Scope on Servlet level (injecting of conversation-scoped beans into servlets). In my understanding, this is not the case with the ciurrent specification (see chapter 8.5.4). Or am I misinterpreting something here ...

A: I think it's soley down to Gavin King picking JSF as his view technology for Seam and him pushing through the JSR as spec lead.
Clearly conversations go wider - for instance, Spring custom scopes have a facility for providing conversations:
http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/beans/factory/config/Scope.html

A: Just found this today. The reason why the ConversationScope is JSF based is simply because JSF is the standard UI framework for Java EE!
Beside this, most of the JSR-299 containers can provide Conversations for other UI technologies like e.g. Wicket too.
Otoh you can easily create your own Scopes which are even portable.
LieGrue,
strub


text:
Q: when weakSelf will be nil in block ,when should add strongSelf By using weakSelf in the block ,you are avoiding retain cycle.But sometime you should hold weakSelf until block retain ,therefor you need use strongSelf just like
__weak __typeof__(self) weakSelf = self;
dispatch_group_async(_operationsGroup, _operationsQueue, ^
{
__typeof__(self) strongSelf = weakSelf;
[strongSelf doSomething];
[strongSelf doSomethingElse];
} );

I want know when weakSelf will be nil ,then we should add__strong typeof(self) strongSelf = weakSelf

A: Example: If your aunty asked you, "Please purchase the umbrella from the market before I leave for my flight". You went to the market and it was very hard to find an umbrella. Finally you found a nice umbrella after few hours and you reach home but you find out that your aunt has left and you feel bad. But that was the right thing for your aunt because the flight is more important than the umbrella.
But in your coding problem what you're trying to do is
You are visiting market and taking your aunt's passport with you so that she won't leave until you come back.
I guess that's rude, but if you still want to do that, use self instead of strongSelf
dispatch_group_async(_operationsGroup, _operationsQueue, ^
{
  [self doSomething];
  [self doSomethingElse];
} );

A: It all depends on your requirements.  There's no one, right answer.
Capturing self weakly allows the instance to be deallocated, even if the block is still retained somewhere.  If self is released before the block is executed, it will be nil within the block.
If the block should not do anything when self has already been deallocated, there is no reason to capture self strongly.  Simply test for nil and exit early.  Or do whatever work is needed in the block that doesn't act on self.
If self should not disappear until the block has executed, capture self strongly, but avoid retain cycles by ensuring that self does not have a strong reference to the block.
If it's OK for self to disappear before the block begins executing, but must stick around until the block finishes, the block should capture a strong reference to the weakly-captured self when it begins.

A: If question is: "when weakSelf will be nil".
The answer is: When no one own the instance of self
For example, you have a UIViewController instance named vc, vc have a dependency for query API named apiHandler, and api have a callback block named successCallback.
like this:
@interface ApiHandler: NSObject

@property (nonatomic, copy) void (^successCallback)();

@end

@interface vc : UIViewController

@property (nonatomic, strong) ApiHandler *apiHandler;

@end

@implementation vc

- (void)doQuery {
    self.apiHandler.successCallback = ^{
        [self doSomething];
    };
}

- (void)doSomething {

}

If vc be pop or dismiss, the vc instance WILL NOT BE dealloc. Because of retain cycle.
vc own apiHandler, apiHandler own successCallback and successCallback own vc.
So, using weak vc in block can avoid retain cycle.
like this:
- (void)doQuery {
    __weak __typeof__(self) weakSelf = self;

    self.apiHandler.successCallback = ^{
        [weakSelf doSomething];
    };
}

And now, if your vc be pop or dismiss, the vc instance will be dealloc, and weakSelf will be nil.
When apiHandler do query success in background thread and invoke successCallback, the message doSomething will send to nil object. (Zombie)
This is why you need to use strongSelf in block like you said.


text:
Q: One record from one table to show up on all records on another table I have two tables. Table A and B. Table A would have data like:
    +---+---+---+
    | a | b | c |
    +---+---+---+
    | 2 | 1 | 8 |
    | 3 | 6 | 7 |
    | 4 | 5 | 9 |
    +---+---+---+

And table B as:
    +----+----+
    | e  | f  |
    +----+----+
    | 11 | 14 |
    +----+----+

I want to create a SQL query that would provide me an output where I keep all the records from table A and only the one record from table B, but the values from that one record in each column from table B would show up in all the records in table A. The result of the data set would look kike this:
    +---+---+---+----+----+
    | a | b | c | e  | f  |
    +---+---+---+----+----+
    | 2 | 1 | 8 | 11 | 14 |
    | 3 | 6 | 7 | 11 | 14 |
    | 4 | 5 | 9 | 11 | 14 |
    +---+---+---+----+----+

I am not sure how SQL handles appending records like this on table result. I would assume that there is a way to call out those fields from table B and do some kind of union to table A? If there is another question that has the answer then please flag this question as answered. Thank you.

A: You coudl try using a cross join
select a, b, c, d, f
from A
cross join B

A: SQL tables are by definition unordered and there are no row identifiers.  You can create a row identifier using row_number() and then use that for a join:
select a.a, a.b, a.c, b.e, b.f
from (select a.*, row_number() over (order by a) as seqnum
      from a
     ) a join
     (select b.*, row_number() over (order by e) as seqnum
      from b
     ) b
     on a.seqnum = b.seqnum;

This assumes that the first column in each table defines the ordering, as in your example data.


text:
Q: WP_Query orderby meta_value_num ACF Date Picker NOT working I am trying to orderby ACF Date picker custom field, however it is not sorting. I build the query depending on what form inputs are used, but I have tried just hard coding the query as well with no luck. I am submitting this via ajax to display the results on page.
I change order form DESC to ASC and there is no change at all
When I use the similar query via search results the orderby works exactly as expected. I feel like this is a little forrest for the trees.
Here is the code I get when I do a print_r on my query, maybe a fresh set of eyes can help me see a clear solution
[query] => Array(
    [posts_per_page] => -1
    [s] =>
    [post_type] => 'teamsi-course-dates'
    [meta_query] => Array(
        [0] => Array(
            [meta_query] => Array(
                [relation] => AND
                [0] => Array(
                    [key] => course_date_start_date
                    [compare] => >=
                    [value] => 20190212
                    [type] => DATE
                )

                [1] => Array(
                    [key] => course_date_start_date
                    [compare] => <=
                    [value] => 20200228
                    [type] => DATE
                )

            )

        )

        [1] => Array(
            [0] => Array(
                [key] => course_date_start_date
                [value] => 20190212
                [compare] => >
            )

        )

        [relation] => AND
    )

    [tax_query] => Array(
        [0] => Array(
            [taxonomy] => 'teamsi-program-dept'
            [field] => name
            [terms] => PDMP
        )

    )

    [meta_key] => course_date_start_date,
    ['orderby'] => meta_value_num,
    [order] => ASC
)

I am wanting to display by date DESC

A: I found the solution, by adding 'suppress_filters' => true to my $args it allows WP_Query to work with the orderby, you can read more about it: https://wordpress.stackexchange.com/questions/82092/wp-query-orderby-breaks-when-using-ajax


text:
Q: How can I obtain instructions distribution from an executable binary file This may sound a little insane, but I want to know the instructions distribution of an executable binary file. Say I have an executable compiled for ARM 32bit. I want to get something like:
mov: xxx times
blx: xxx times
vadd: xxx times

Anybody know a tool that can do this? Thanks


text:
Q: Android Proguard issues Using proguard seems to be quite confusing.  I am interested in simply obfuscating a few packages within my app.   I have eclipse set up in windows with the latest Android API's.  I have added the default proguard.cfg which builds my app with no problem, but when I run the app, certain functionality of the app does not work anymore.  It just does weird stuff.
Also, whenever I create a new project, it never automatically creates the proguard.cfg, I have no idea why.  But I can find it in
android-sdk-windows\tools\lib

All I am really interested in doing is obfuscating certain packages or even a couple classes in my code.  If I could do that I'd be pretty content.  Is there any simple way to just say "obfuscate THIS".  Any basic configs you guys could share?

A: I finally added -dontshrink and -dontoptimize to the proguard.cfg because proguard was stipping out code even when I would specific -keep class xxxxx.  So now my code is obfuscated, but not optimized and shrunk, which is all I really wanted in the first place.


text:
Q: Cypress - How to Wait for an attribute value to be false in Cypress I have a website which has everything in an iFrame. My scripts are failing because cypress is not able to wait for loading bar as cypress does not support iframes as of now. I want to write a custom command which wait until attributes 'ng-reflect-loading' value is changed to false.
I have tried with below code but its not working and halts cypress runner. Reference Thread 136
cy.get('iframe').iframeLoaded().its('document').getInDocument('.main >ng-component > :nth-child(1)').then(function($loading) {
       while( $loading.attr('ng-reflect-loading')!='false')
       {
           cy.log('waiting')
       }
    })

Can anyone please help on this.

A: I don't have any insight of how iFrames work. But is 'ng-reflect-loading' eventually hidden?
In that case this check should work:
cy.get('.ng-reflect-loading')
  .should('not.exist')

If it remains existing but the value should change you could either check on the first value not existing:
cy.get('.ng-reflect-loading')
  .should('not.contain.attr', 'attr_name', 'first value')

Or if the value changes, you could check for the second value to be available:
cy.get('.ng-reflect-loading')
  .should('contain.attr', 'attr_name', 'second value')


text:
Q: Number guessing game that requires suggestions for completion how do I get the difficulty level to work? I have found other codes similar but the difficulty is based on the group of number that it will choose the number from i.e. easy(1,10), medium (1,50), hard (1,100). I need to know how to make it work for the number of guesses. It keeps telling me I don't have easy,medium, or hard defined. how do I define them in way to make this code work?
I can get through it asking for my name then it will ask for the difficulty level and when I type e,m,or,h this is what it gives me: Traceback (most recent call last): File "C:\Users\ajohn\OneDrive - Fairmont State University\BISM3800\Assign2.py", line 58, in  guesses = get_guesses(level) File "C:\Users\ajohn\OneDrive - Fairmont State University\BISM3800\Assign2.py", line 50, in get_guesses if diffuculty == hard: NameError: name 'diffuculty' is not defined
here is the objectives for the code:
You are to ask the user if they wish to play the game or continue playing the game after they have guessed the number
You are to ask the user if they want easy, medium or HARD (Easy = unlimited guesses, Medium = 10 guesses, HARD = 5 guesses)
Once the game begins play you are to tell the user that you have picked a number and they are to guess what that number is
your application is to accept the players guess and if their guess is larger than the number you had picked then tell them that, if their guess is smaller then tell them that as well.
The game continues to play until the player picks the number you had originally picked or they have ran out of guesses. I also need to have an exception.
Here is my code so far:
This is a guessing the number game.
import random
this statement will allow the options for playing and quiting the game.
play = True
while play:
difficulty = 0

guessesTaken = 0

print('Hello! What is your name?')

myName = input()

easy = random.randint (1,100)
easy = random.randint (1,100)
easy = random.randint (1,100)

prompts the user to select a difficulty to play on
def select_level():
    while True:
        level = str(input("Would you like to play on easy, medium, or hard? \n"
                      "Type 'e' for easy, 'm' for medium, or 'h' for hard!\n"))
        if level != "e" and level != "m" and level != "h":
            print("Invalid input!\n")
        if level == "e" or level == "m" or level == "h":
            break
    return level

function that prompts the user to guess depending on chosen difficulty
def guess_number(level):
    if level == "e":
        (easy == 500)
    if level == "m":
        (medium == 10)
    if level == "h":
        (hard == 5)
    return guesses

selects number of guesses depending on difficulty selected
def get_guesses(level):
        if difficulty == easy:
            print ("Okay, " + myName + ". You have unlimited guesses")
        if difficulty == medium:
            print ("Okay, " + myName + ". You have 10 guesses.")
        if diffuculty == hard:
            print ("Okay, " + myName + ". You have 5 guesses.")
        elif level != "e" and level != "m" and level != "h":
            print ("Invalid input!")
            get_guesses()
        return guesses

level = select_level()
guesses = get_guesses(level)

print('Well, ' + myName + ', I am thinking of a number can you guess it?')

while guessesTaken < level:
     print('Take a guess.')
     guess = input()
     guess = int(guess)

     guessesTaken = guessesTaken + 1

     if guess < number:
        print('Your guess is too low.')

     if guess > number:
         print('Your guess is too high.')

     if guess == number:
         break

if guess == number:
    guessesTaken = str(guessesTaken)
    print('Good job, ' + myName + '! You guessed the number in ' + guessesTaken + ' guesses!')

if guess != number:
    number = str(number)
    print('Nope. The number I was thinking of was ' + number)

count=1
again=str(input("Do you want to play again, type yes or no "))
if again == "no":
  play = False

A: Here's the object oriented approach :
from random import randint

class Guessing_Game () :
    def __init__ (self, users_name) :
        self.difficulty = 10
        self.name = users_name
        self.start_the_game ()

    def start_the_game (self) :
        my_secret_number = randint (1, self.difficulty)
        print ('Well, ' + self.name + ', I am thinking of a ', end = '')
        print ('between 1 and ' + str (self.difficulty) + '.')
        print ('Can you guess it?')
        self.guess_the_number (my_secret_number)

    def guess_the_number (self, the_secret_number) :
        still_playing = True
        while still_playing == True :
            answer = int (input ('Take a guess : '))
            if answer == the_secret_number :
                print ('That is exactly correct! You win!')
                still_playing = False
            else :
                if answer > the_secret_number :
                    print ('Sorry, you are too high.')
                if answer < the_secret_number :
                    print ('Sorry, you are too low.')
        if self.play_again () == True :
            self.start_the_game ()

    def play_again (self) :
        self.difficulty = self.difficulty * 2
        answer = input ('Would you like to play again? ')
        if answer [0].lower () == 'y' : return True
        return False

users_name = input ('Please enter your name : ')
my_game = Guessing_Game (users_name)


text:
Q: Filtering data using checkbox For default must show items that have prop "state: 'notarchived'" and "state: 'archived'" must be hided
When I have a Check I need hide elemets with "state: 'notarchived'" and show elements with  "state: 'archived'"
There my HTML
<input ng-model="archived.state"  type="checkbox"
      ng-true-value="'archived'" ng-false-value="undefined">Show archived

          {{paymentinfo.date}}
          {{paymentinfo.name}}

JS
 $scope.datas = [
            {date:'06-12-2016', name : 'Pinao Class', state: 'archived', remark : 'remarled', amount : 101, id : 21},
            {date:'15-04-2016', name : 'drivers Class', state: 'notarchived', remark : 'remarled', amount : 102, id : 22},
            {date:'24-03-2016', name : 'Airplane Class', state: 'archived', remark : 'remarled', amount : 103, id : 23}

    ];

$scope.paymentList = $scope.datas;

Now displayes all elements
How to change filter that it work right way?

A: Try this one:
Set the initial value for the checkbox:
<input ng-model="archived.state"  type="checkbox"
      ng-true-value="'archived'" ng-false-value="'notarchived'"
      ng-init="archived.state='notarchived'">Show archived

and change the filter:

I tried and it works.

A: This is untested for I don't have a proper environment setup
<input ng-model="archived.state"  type="checkbox" ng-true-value="'archived'" ng-false-value="'notarchived'">Show archived
filter:{state: archived.state ? 'archived' : 'notarchived'}
Please test and let me know.
Thanks!


text:
Q: Input type = Registration number How do I set the input type for registration number. For example my university has specific format for registration number i.e. CIIT/SP17-mcs-044/Atk. I want CIIT/ATK is written already and Sp17-mcs-044 as a hint.

A: You can't define a random types of input type. You can only have one of these types as inputType.
If you want any custom behaviour, you might use TextWatcher and validate it

A: As @Tim has stated, the input type would be text over here and when user types in that EditText then check if the input is correct by using RegEx, and then show any message when the input is correct, for that you will need to add an OnTextChangedListener, about which you can learn more on official documentation.
Now, CIIT/ATK can be a TextView placed right before the EditText so it will be written already and will be uneditable. And yes, add that in final string after getting the input, like this:
finalInput = "CIIT/ATK" + input;


text:
Q: Access a domain controller without a DNS server I have a Windows 7 workstation that is joined to an Active Directory domain controlled by a Windows 2012 R2 server.  The workstation was set up locally and joined to the domain locally.
I moved the workstation to a remote location controlled by someone else.  They required me to use their DNS and I was not allowed to enter my own DNS into the workstation (my domain controller is also a DNS server).  There is a VPN from this remote location to my domain controller, I can ping the domain controller and verified that ports are open.  EDIT:  This is a router/firewall based VPN that is always on, not a VPN client.
I tried editing the hosts file on the computer, but I am still not able to log in as users who do not have cached credentials.
AD/DNS server name:  DCPRIMARY
Domain name:  mydomain.local

In the hosts file, I have:
192.168.55.5     DCPRIMARY
192.168.55.5     DCPRIMARY.mydomain.local
192.168.55.5     mydomain.local
192.168.55.5     mydomain

When I try to logon, I get this error:
There are currently no logon servers available to service the logon request.

For testing, they allowed me to put in 192.168.55.5 as the primary DNS, and I was able to log as a domain user at that point (although it took 5 minutes to login).  I was told I need to come up with a different solution besides using my DNS as the primary DNS.  They will not allow any changes to their DNS server.
How can I point this workstation to a domain controller without using a DNS server?  It will always have that static IP and is the only domain controller this workstation will ever see.
Alternately, they will allow me to enter my DNS into the "Alternate DNS Server", but my understanding is the computer will only use that if the Primary DNS is offline.  Is there any way to have the computer use the Alternate DNS if the Primary DNS does not return a match?

A: Your problem is that the VPN is not up before the login. I would use a VPN client that support a prelogin login.
Install a client like OpenVPN as a service, and allow it to connect before the login.
I suggest Always On VPN if you can upgrade the workstation to a Windows 10 build 1709+, as the remote endpoint can be a cisco asa or such, no need to be RRAS server specifically.
For your alternate DNS's problem I would make the VPN route all traffic if you can, thus becoming the default route 0.0.0.0, any IP and DNS received by the VPN client will be the default's one, bypassing your local area network card configuration for all the traffic.

A: If you can establish a VPN to your domain, the best solution would almost certainly be to connect to the VPN via IP, or hard code the name/ip of your VPN into your hosts file.  Then set your client to use the IP of the Domain controller, via the VPN.  This would require that your VPN be always on, and configured to operate system wide though.
The more complex, but flexible option would be to use the name resolution policy table on your client.  This allows you to specify servers to use for a specific zone on the client.  It is a bit of a pain to manage though.
Here ix a rule for *.example.org that would some servers for resolution.  In your case, you would have to establish the VPN first, then provide the add a rule to your table for the IP of your DC via the VPN.
$Rule = @{
    'Namespace'   = '.example.org'
    'Comment'     = 'the domain'
    'NameServers' = ('2001:db8:a362:58::2', '2001:db8:a362:58::3')
}
Add-DnsClientNrptRule @Rule


text:
Q: Calculating the probability of a set of numbers appearing in a randomly-generated 3x3 grid A challenge within a PC game I play features a 3x3 grid which contains all numbers from $1$ to $9$ in a random order. For example, this may be what a randomly-generated 3x3 grid looks like:
   _ _ _ _ _ _ _ _ _
  |     |     |     |
  |  5  |  3  |  1  |
  |_ _ _|_ _ _|_ _ _|
  |     |     |     |
  |  9  |  7  |  6  |
  |_ _ _|_ _ _|_ _ _|
  |     |     |     |
  |  2  |  8  |  4  |
  |_ _ _|_ _ _|_ _ _|

The aim of the game is to select a single row, column or diagonal whose sum will reward a variety of goodies. Getting the a sum of $6$ (from the numbers $1$, $2$ and $3$) offers the best rewards. Unfortunately our example grid doesn't have any rows, columns or diagonals which add up to $6$:

  16     18    9    11     10
       _ _ _ _ _ _ _ _ _
      |     |     |     |
  18  |  7  |  3  |  8  |  18
      |_ _ _|_ _ _|_ _ _|
      |     |     |     |
  20  |  9  |  5  |  6  |  20
      |_ _ _|_ _ _|_ _ _|
      |     |     |     |
  7   |  2  |  1  |  4  |   7
      |_ _ _|_ _ _|_ _ _|

  10     18    9    11     16

The number order is completely randomised every time the game is played. What is the probability of a row, column or diagonal adding up to $6$?

A: There are eight rows/columns/diagonals where we can place 1,2,3.  Then there are $3!$ orders we may place $1,2,3$ on that line.  Then there are $6!$ orders to place the other numbers in the other squares.  Hence the answer is $$\frac{8\cdot 3!\cdot 6!}{9!}=\frac{34560}{362880}=\frac{2}{21}\approx 9.5\%$$


text:
Q: Element cannot be located in parent view: Why im getting that error? Hi I am trying to call a function from xml view using function tag. Im getting the next error and I dont get it: Element '<function model="website.track" name="reconoce">' cannot be located in parent view.
Any help would be apreciated.
XML code:
<odoo>
    <record id="vista_track" model="ir.ui.view">
        <field name="name">vista.Web</field>
        <field name="model">website.track</field>
        <field name="inherit_id" ref="website.website_visitor_track_view_tree"></field>
        <field name="arch" type="xml">

                <field name="page_id" position="after">
                    <field name="partner_id"/>
                </field>
                <function model="website.track" name="reconoce">
                </function>

        </field>
    </record>
</odoo>

PYTHON code:
class visita(models.Model):
    _inherit = 'website.track'

    #prueba = fields.Char()
    partner_id = fields.Many2one(comodel_name = 'mailing.contact',string='visitante')

    @api.model
    @api.depends("url")
    def reconoce(self):
        for a in self:
            var = a.url
            if "?" in var:
                try:
                    var2 = int(var[var.find('?')+1:var.find('%')])
                    a['partner_id'] = self.env['mailing.contact'].browse(var2)
                except:
                    a['partner_id'] = False

The thing is this code should call the function properly

A: You added the function tag inside an inherited view arch, Odoo will try to find it in the parent view which is not what you want.
The function tag can be used in data files. when evaluated Odoo will call the function on the corresponding model, we add it as a child odoo tag.
The function tag can't be used as a child of a tree view, you can check the tree view rng file used to validate tree views


text:
Q: Special modules over symmetric algebras Let $A$ be a symmetric connected finite dimensional algebra over a field $k$.
Call a tuple of two modules $(X,M)$ (having no projective direct summands) cute in case $Ext^l(X,M) \neq 0$ for some $l \geq 1$ but $Ext^{l+i}(X,M)=0$ for all $i \geq 1$. We can assume that $M$ is indecomposable always.
Questions:

*

*Is there an easy construction of cute tuples?

*Are there cute tuples when the field is finite (or any other field that constists only of roots of unity)?


text:
Q: How to ensure xlwings connection is closed if script fails I am trying to develop something with xlwings because I need to manipulate a xls file with macros etc. Although it is always good to close connections, Excel is notorious in that it blocks access if more than one instance is running. Therefore I need to make sure that the app closes even though my code fails somewhere upstream.
I am currently doing this with a try statement that spans the whole script and when it fails calls app.quit(). But this suppresses my error messages, which makes debugging hard. So I feel there must be something better.
In another context I have seen with being used. And I have the feeling it would apply here too, but I do not understand how it works, nor how it would work in this specific case.
import xlwings as xw

def myexcel():
    try:
        #connect to Excel app in the background
        excel = xw.App(visible=False)
        # open excel book
        wb = excel.books.open(str(file))
        # asign the active app so it can be closed later
        app = xw.apps.active

        # more code goes here

    except:
        app.quit()

How could one make sure that the excel connection gets always closed no-matter the most efficient way?
If with is the solution, I would also appreciate a pointer to a good source to learn more about that concept.

A: As you mentioned, you can use a with statement and build your own contextmanager.  Here's a converted example based on your code:
import xlwings as xw

class MyExcelApp:
    def __init__(self):
        self.excel = xw.App(visible=False)

    def __enter__(self):
        return self.excel

    def __exit__(self, exc, value, traceback):
        # Handle your app-specific exceptions (exc) here
        self.excel.quit()
        return True
        # ^ return True only if you intend to catch all errors in here.
        # Otherwise, leave as is and use try... except on the outside.

class MyExcelWorkbook:
    def __init__(self, xlapp, bookname):
        self.workbook = xlapp.books.open(bookname)

    def __enter__(self):
        return self.workbook

    def __exit__(self, exc, value, traceback):
        # Handle your workbook specific exceptions (exc) here
        # self.workbook.save()   # depends what you want to do here
        self.workbook.close()
        return True
        # ^ return True only if you intend to catch all errors in here.
        # Otherwise, leave as is and use try... except on the outside.

With this set up you can simply call it like this:
with MyExcelApp() as app:
    with MyExcelWorkbook(filename) as wb:
        # do something with wb

You can also implement it with a generator, which will be quite similar to the other answer.
 Here's a simplified version:
import xlwings as xw
from contextlib import contextmanager

@contextmanager
def my_excel_app():
    app = xw.App(visible=False)
    try:
        yield app

    except:  # <-- Add SPECIFIC app exceptions
        # Handle the errors

    finally:
        app.quit()

Usage:
with my_excel() as app:
    wb = app.books.open(some_file)
    # do something...

A: you do it right - using try block in this case is the way to go. With statement is good when you need to open file, but not for your use case when you use library which is opening excel file using its own way.
To show details of exception you can change your code as follows:
import xlwings as xw

def myexcel():
    try:
        #connect to Excel app in the background
        excel = xw.App(visible=False)
        # open excel book
        wb = excel.books.open(str(file))
        # asign the active app so it can be closed later
        app = xw.apps.active

        # more code goes here

    finally:
        app.quit()
    except Exception as e:
        print('exception catched: {}'.format(e))
        app.quit()

A: Preferred solution
xlwings added a solution in v0.24.3 to this problem:
xlwings.App() can now be used as context manager, making sure that there are no zombie processes left over on Windows, even if you use a hidden instance and your code fails. It is therefore recommended to use it whenever you can, like so:
import xlwings as xw
with xw.App(visible=False) as app:
    wb = xw.Book("test.xlsx")
    sheet = wb.sheets['sheet1']
    # To evoke an error, I try to call an non-exisiting sheet here.
    nonexistent_sheet["A1"]

Solution before v24.0.3
You can use the library traceback, which makes debugging easier, because the error is displayed in red color. See this example:
import xlwings as xw
import traceback

filename = "test.xlsx"

try:
    # Do what you want here in the try block. For example, the following lines.
    app = xw.App(visible=False)
    wb = xw.Book(filename)
    sheet = wb.sheets['sheet1']
    # To evoke an error, I try to call an nonexistent sheet here.
    nonexistent_sheet["A1"]

# Use BaseException because it catches all possible exceptions: https://stackoverflow.com/a/31609619/13968392
except BaseException:
    # This prints the actual error in a verbose way.
    print(traceback.print_exc())
    app.quit()

The error displays with print(traceback.print_exc()) as follows:


text:
Q: Upgrading Cassandra 2.0.8 to 2.1.0 I have 8 nodes in my cassandra cluster. Now I have upgraded cluster from cassandra 2.0.8 to release version of cassandra 2.1.0.
how can i upgrading cassandra to 2.1.0?

A: First check your upgrade compatibility:
Cassandra upgrade for 2.1 version can be upgrade from cassandra-2.0.7 or later version.
Procedure:

*

*Do nodetool drain on a single node

*Take backup of cassandra.yaml file

*Shutdown the node

*For rpm install first uninstall dsc and cassandra rpm

*Install new version of cassandra

*Do all the change in new cassandra.yaml file as in old yaml file

*If JMX security was enable earlier the do required changes in cassandra-env.sh file

*Start the node with new version

*Run nodetool upgradesstables on the node

*Follow the same procedure on all nodes one by one

Before doing all that for your safe side you can take snashots first.

A: Follow the documentation here:
http://www.datastax.com/documentation/upgrade/doc/upgrade/cassandra/upgradeCassandra_g.html


text:
Q: Printing from a structure pointer I have defined a structure using typedef struct and then created a pointer in a function. I pass this pointer into a second function to assign values to the structure elements.
typedef struct
{
    double velocity; // there are more variables than this but its the
                     // same for each variable so only showing it for one.
}Variables;

void information(Variables **constants);

int main()
{
double k;

Variables *Constants=NULL; // the structure variable

information(&Constants); // passed into the 'filling' function

k=Constants->velocity;
printf("Velocity %lf\n",k); //this displays correctly

printf("Velocity %lf\n",Constants->velocity); // this does not display correctly

return;
}

 void information(Variables **Constants)
{
 Variables *consts,constants; //creates the struct to be filled
consts=&constants;

 constants.velocity=30.2;

*Constants=consts;  //assigns the pointer to the pointer passed into the function
return;

}

here you can see I display the velocity twice. The first time I assign the value from the pointer to a variable and everything works perfectly. If I try and directly display using the line printf("Velocity %lf\n",Constants->velocity); the code gives a random number.
I have displayed numbers using the .dot format for structures before but never via a pointer so I do not understand what might be going wrong.

A: It's because of promotion. It has nothing to do with struct or with pointers.
Illustration:
double k;
int i;

i = 123456;
k = i;       // here i is promoted to double before the assignment
             // takes place, now k contains 123456.0000

printf("Velocity %lf\n", k);  // this displays correctly
                              // because k is a double and %lf is the format
                              // specifier for double

printf("Velocity %lf\n", i);  // this does not display correctly
                              // because i is an int and if you use the %lf
                              // format specifier with an int, then you will
                              // get undefined behaviour hence the garbage
                              // that is printed

printf("Velocity %lf\n", (double)i);
                              // this does not display correctly because the cast
                              // converts the int to a double


text:
Q: two questions about Diophantine Equation I am reading an article Modular Arithmetic by Richard Taylor.    I have 2 questions:

*

*For which $n$, $x^2+y^2=nz^2$ has nontravial solutions? What are the solutions?

*A beautiful theorem of Hermann Minkowski and Helmut Hasse  says that if $Q (X_1 , ..., X_d ) $ is any homogeneous quadratic polynomial in any number of variables with whole number coefficients, then
$$Q (X_1 , ..., X_d ) $$
has a non-zero solution in whole numbers if and only if it has a non-zero solution in all (real) numbers and a primitive solution modulo $m$ for all positive whole numbers $m$
How to prove the beautiful theorem? Could you recommend some books?
Many thanks in advance!

A: 1.) We have
$$
\left(\frac{x}{z}\right)^2+\left(\frac{y}{z}\right)^2=n,
$$
so the answer is given by Fermat's two square theorem for rationals:
Theorem (Fermat): A positive rational number is a sum of two rational squares if and only if in its prime factorization every prime of the form $4k + 3$ appears with an even exponent.
For proofs see https://mathoverflow.net/questions/88539/sums-of-rational-squares.
2.) See the references given here: Proof of Hasse-Minkowski over Number Field. I would say, "J.P. Serre: A course in arithmetic" is a good source.


text:
Q: Trying to add an Edit button to the navigation bar I had created a xcode project of single view application. I put a tableview and navigation item on my storyboard screen. Now, I bind the array data source to tableview and set the code as below to show edit button on the navigation button.
self.navigationItem.leftBarButtonItem = self.editButtonItem;

However, it seems can't working. I can't find any button on my navigation bar.
Someone can tell me how to make the edit button show?
Thanks!

A:
I put a tableview and navigation item on my storyboard screen.

It sounds like maybe that's the problem. The way to set this up is to start with a UINavigationController as your storyboard's initial controller, and put the UITableViewController in a relation segue from that (as the navigation controller's root view controller). Now if the table view controller says
 self.navigationItem.leftBarButtonItem = self.editButtonItem;

the edit button will appear in the navigation bar.
To see an example, start with the Master-Detail template (for iPhone). The Master view controller is structured in the way I'm describing.


text:
Q: limit the results of a query server side I would like to know how to limit a query (server side. My knowledge is Meteor). For example, the comments of a particular post instead of retrieving all the comments in database.
I want it to be limited server side to avoid malicious client to fetch all the data of the database.
Thanks.

A: You could use limit. For example:
    post.comments.limit(10)

A: I think we talked about this in gitter, but I'm planning to add a query_restrictions api where you can reject queries that you don't like.  I'll probably add a default globally configurable limit also.  (that you can override on a per model basis)


text:
Q: Impersonating a sharepoint site to open it with custom account How to create a sharepoint 2007 site by impersonating with custom account, so that it wont show login prompt box

A: Use SPSite constructor where you pass SPUserToken object
To get token of some user, use SPWeb.AllUsers["userLoginName"].UserToken

A: I think that to be able get a user token you should be running your code with elevated priviledges and that might be why is pompting for login (beacuse the anonimous user doesnt have permissions to get another users token)
Example
 SPSecurity.RunWithElevatedPrivileges(delegate()
            {
   //is important that you instantiate your SPSite object within you elevated code
              using (SPSite oSite = new SPSite("your site URL"))
                    {

                        using (SPWeb oWeb = "your web")
                        {
                          //your code to run elevated
                        }
                    }
            });