text:
Q: How to restrict a key and its value in a HashMap using generics? I have a class hierarchy, where, say, class ICommon is at the root. I have separate repositories implementations in order to manipulate objects belonging at each level in this hierarchy.
interface IRepository<T extends ICommon> {
   public void createOrUpdate(T toCreate);
}

Now, I want to maintain a Map of classes VS their repositories. Its this part which I can't figure out.
I tried this, which works, but I do not think it is the correct representation.
private Map<Class<? extends ICommon>, IRepository<? extends ICommon>> repoMap = new
   HashMap<Class<? extends ICommon>, IRepository<? extends ICommon>>();

Later on, clients call this method to get an appropriate repository instance.
public <T extends ICommon> IRepository<T> getRepository(Class<T> clazz) {
   return (IRepository<T>) repoMap.get(clazz);
}

A: I faced similar problem some time ago and generally there is not way to restrict key and value  in map, however it is possible to construct map in typesafe way. If you introduce one more  method for returning target class repository you'll get compile time checking(unfortunately you can't do this in runtime since generic type is raised). After you have this method you can  register all repositories. It could be either implicit way - when repository holder know about all repositories, or by exploring classpath for classes with IRepository interface implemented, or if you use IoC container (like spring) you can get those classes autowired. Anyway, plain java solution is below:
interface IRepository<T extends ICommon> {
    public void createOrUpdate(T toCreate);

    public Class<T> getTargetClass();
}

class Repository1 implements IRepository<Common1> {

    @Override
    public void createOrUpdate(Common1 toCreate) {
        //no-op
    }

    @Override
    public Class<Common1> getTargetClass() {
        return Common1.class;
    }
}

class Repository2 implements IRepository<Common2> {

    @Override
    public void createOrUpdate(Common2 toCreate) {
        //no-op
    }

    @Override
    public Class<Common2> getTargetClass() {
        return Common2.class;
    }
}

class RepositoryHolder<T extends ICommon> {

    private IRepository repository1 = new Repository1();
    private IRepository repository2 = new Repository2();
    //...

    private Map<Class<T>, IRepository> map = new HashMap<Class<T>, IRepository>() {{
        put(repository1.getTargetClass(), repository1);
        put(repository2.getTargetClass(), repository2);
        //...
    }};

    public IRepository<T> getRepository(Class<T> clazz) {
        return map.get(clazz);
    }
}


text:
Q: Refer to unknown at advance object key in TypeScript gereric First look, below function addPropertyIfValueIsNotUndefined works:
function addPropertyIfValueIsNotUndefined<Value>(key: string, value: Value): { key?: Value; } {
    return isNotUndefined(value) ? { [key]: value } : {};
}

function isNotUndefined<TargetValue>(targetValue: TargetValue | undefined): targetValue is TargetValue {
  return typeof targetValue !== "undefined";
}

type Test = {
    alpha: string;
    bravo?: string;
}

const test1: Test = {
    alpha: "ALPHA1" ,
    // bravo: "BRAVO1"
};

const test2: Test = {
    alpha: "ALPHA2",
    ...addPropertyIfValueIsNotUndefined("bravo", test1.bravo)
};

console.log(test2)

// Neither TypeScript compiler nor JavaScript VM errors until here

But what if try to add some property that does not declare on type Test?
I am expecting that TypeScript emit the error TS2322 Type { gibberish: string; bravo: string | undefined; alpha: string; }' is not assignable to type 'Test', but TypeScript will not emit error or warning!
const test2: Type = {
    alpha: "ALPHA2",
    ...addPropertyIfValueIsNotUndefined("gibberish", test1.bravo)
};

Seems like I understood why. But how to annotate the returning value of addPropertyIfValueIsNotUndefined? We don't know the key at advance but need refer to it.
 Fiddle

A: Here's a slightly modified approach which I think accomplishes your goal.  Instead of having a separate function to create the {key: value} object, we pass the existing object into the function.
function addPropertyIfValueIsNotUndefined<T extends {}, K extends keyof T>(
   object: T, key: K, value: Required<T>[K]
): T & Required<Pick<T, K>> {
    return propertyIsNotUndefined(object, key) ? object : { ...object, [key]: value } as T & Required<Pick<T, K>>
}

Note that we have to use as to return the correct type because of how typescript treats dynamic keys and because it is theoretically possibly for the generic K to be wider than just the single key, in which case our return type could be incorrect.
The boolean checker now looks at the property on the object:
function propertyIsNotUndefined<T extends {}, K extends keyof T>(object: T, key: K): object is T & Required<Pick<T, K>> {
  return object[key] !== undefined;
}

The usage looks like this:
const test2 = addPropertyIfValueIsNotUndefined(test1, "bravo", "value") // ok

const test3 = addPropertyIfValueIsNotUndefined(test1, "bravo", undefined)
// error: Argument of type 'undefined' is not assignable to parameter of type 'string'

const test4 = addPropertyIfValueIsNotUndefined(test1, "wrongKey", "value")
// error: Argument of type '"wrongKey"' is not assignable to parameter of type '"bravo" | "alpha"'

Typescript Playground Link

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to restric data to insert in mysql I have 4 groups in one table called GroupA,GroupB,GroupC,GroupD.The Column should accept only 5 values, not more . How can I achieve this in MySQL ?
    GroupA GroupB
    aaa     fff
    bbb     ggg
    ccc     iii
    ddd
    eee

Now the 6th person should not entered into GroupA

A: There are two approaches you can take in MySQL.  The first is to use a trigger to validate the values.
The second is to create a reference table that has the five legal values in it and use a foreign key constraint to ensure the value.  Something like this:
create table GroupA_value (
     GroupA varchar(255) not null primary key
);

create table t (
     . . .
     GroupA varchar(255) not null preferences GroupA_value(GroupA)
)

Personally, I would use identifiers rather than the actual value, but you don't give much information about the overall structure.
Most other databases support the check constraint which makes this much easier.  MySQL accepts the syntax, but doesn't do the check.


text:
Q: How to render multiple objects as a single object for fluid simulation? i'm try doing fluid simulation using particles in 2d game.but something i can't get it through. situation like this, i have larger particles, which interactive each other physically,and applying constraint on particles, cause it's more like water,then use those
particles to collide with environment(e.g wall,obstacles)
but draw things doesn't go well,because by using particles-based fluid simulation, it exsits gap,or hole between circle particles, anyway,i would prefer to do some graphics trick to get rid of it.as you know, maybe use blur shader,or something else to smooth particles, but it's definitely infeasible, it makes particle size,radius visualization such changed,undetermined that can't use original information of particle to collide with environment anymore.
please give some hint on fluid simulation in 2d games,thank you.
EDIT:

too bad, it's apparently that "water" fluid was composed of several cicrle sprites.....

better but still gaps,holes.
i uploaded the image to illustrate this visually.
as the above figures shows, green circle particle was positioned separetely.it dosn't looks like water fluid. blurring the particles it's not my choice.   how can i fixed this.

A: You can do it solving the Navier-Stokes equation.
Google a little deeper and then you can find some examples and implementations. This is equivalent to the Netwon's F = M x A, but for fluid dynamics.


text:
Q: Android: NullPointerException when trying to add tweet object to my model in an AsyncTask I have this problem when I try to add my tweet objects to an ArrayList in my model, but I'm getting back a NullPointerException. This happens in my SearchTweetsTask class.
It only happens when I search for tweets with the twitter api. Getting timelines and stuff works just great, no problems at all. But only when I search for tweets I got this exception.
I search for tweets via a searchview in my actionbar which is created in my MainActivity.
I hope you can help me.
Here is some code:
    protected String doInBackground(String... params)
    {
        meldingen = "";
        String result = "";
        String searchString = params[0];
        String decoded = "";
        try {
            decoded = URLEncoder.encode(searchString, "UTF-8");
        } catch (UnsupportedEncodingException e1) {
            Log.d("URL ENCODER", "De Search query is niet goed ingelezen");
        }
        String url = "https://api.twitter.com/1.1/search/tweets.json?q=";
        String searchURL = url + decoded + "&count=50";

        try{
            HttpGet get = new HttpGet(searchURL);
            Authenticate.authentication(get);
            ResponseHandler<String> handler = new BasicResponseHandler();
            result = httpClient.execute(get, handler);
            JSONObject json = new JSONObject(result);
            JSONArray jArray = json.getJSONArray("statuses");
            for (int i = 0; i < jArray.length(); i++)
            {
                JSONObject subObject = jArray.getJSONObject(i);
                Tweet tweet = new Tweet (subObject);
                publishProgress(tweet);
            }
        }
        catch(HttpResponseException e)
        {
           //all the catch exceptions
           ....
        }
    //GETTING NULLER POINTER HERE
    protected void onProgressUpdate(Tweet... tweets) {
        for (Tweet tweet : tweets) {
            model.addSearchTweets(tweet);
        }
    }

Model class:
   private ArrayList<Tweet> searchTweets = new ArrayList<Tweet>();

   public void addSearchTweets(Tweet tweet)
   {
       searchTweets.add(tweet);
   }

MainActivity:
   public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.actions, menu);
    MenuItem searchItem = menu.findItem(R.id.action_search);
    final SearchView searchView = (SearchView) searchItem.getActionView();

    SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    if(null != searchManager )
    {
        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
        searchView.setOnQueryTextListener(new OnQueryTextListener() {

            @Override
            public boolean onQueryTextSubmit(String search) {
                model.clearSearchTweets();

                InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(searchView.getWindowToken(), 0);

                Fragment newFragment = new UserSearchTweetsFragment();
                FragmentTransaction transaction = getFragmentManager().beginTransaction();
                transaction.replace(R.id.frame_container, newFragment);
                transaction.addToBackStack(null);

                SearchTweetsTask searchTweets = new SearchTweetsTask(MainActivity.this);
                searchTweets.execute(search);

                transaction.commit();
                return true;
            }

            @Override
            public boolean onQueryTextChange(String search) {
                return true;
            }
        });
    }
    searchView.setIconifiedByDefault(false);
    return true;

Logcat
07-14 17:18:25.048: E/AndroidRuntime(9135): FATAL EXCEPTION: main
07-14 17:18:25.048: E/AndroidRuntime(9135): Process: nl.timkatgert.tweettweet, PID: 9135
07-14 17:18:25.048: E/AndroidRuntime(9135): java.lang.NullPointerException
07-14 17:18:25.048: E/AndroidRuntime(9135):     at nl.timkatgert.tweettweet.tasks.SearchTweetsTask.onProgressUpdate(SearchTweetsTask.java:117)
07-14 17:18:25.048: E/AndroidRuntime(9135):     at nl.timkatgert.tweettweet.tasks.SearchTweetsTask.onProgressUpdate(SearchTweetsTask.java:1)
07-14 17:18:25.048: E/AndroidRuntime(9135):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:648)
07-14 17:18:25.048: E/AndroidRuntime(9135):     at android.os.Handler.dispatchMessage(Handler.java:102)
07-14 17:18:25.048: E/AndroidRuntime(9135):     at android.os.Looper.loop(Looper.java:157)
07-14 17:18:25.048: E/AndroidRuntime(9135):     at android.app.ActivityThread.main(ActivityThread.java:5356)
07-14 17:18:25.048: E/AndroidRuntime(9135):     at java.lang.reflect.Method.invokeNative(Native Method)
07-14 17:18:25.048: E/AndroidRuntime(9135):     at java.lang.reflect.Method.invoke(Method.java:515)
07-14 17:18:25.048: E/AndroidRuntime(9135):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
07-14 17:18:25.048: E/AndroidRuntime(9135):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
07-14 17:18:25.048: E/AndroidRuntime(9135):     at dalvik.system.NativeStart.main(Native Method)

A: Did you checked the result you get before you instantiated the JsonObject?

Add Log.d("Result String Is", result);
After the http request you make in the doInBackground and post the answer here.
My bet is the result is null and you are trying to create a tweet object with a null string.


text:
Q: Google Apps Script - Copy Paste values on same page and in same row based on cell criteria I have a table with data in columns A:Ak. Some of the data contains formulas and when a row of data is complete (i.e. the status in column W is "Y") I would like to copy that row in place and only past the values.
This is what I have tried:
function Optimize() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var rows = sheet.getDataRange();
  var numRows = rows.getNumRows();
  var values = rows.getValues();
  for (var i = 0; i <= numRows - 1; i++) {
    var row = values[i];
    // This searches all cells in columns W copies and pastes values in row if cell has value 'Y'
    if (row[22] == 'Y') {
    sheet.getDataRange(sheet.getCurrentCell().getRow() - 0, 1, 1, sheet.getMaxColumns()).activate();
    sheet.getActiveRange().copyTo(sheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
    rowsCopiedpasted++;
    }
  }
}

When I am in the sheet and click on the cell in column A of a row with a "Y" value this works, but I need it to go through the whole sheet and copy/paste values of all rows with "Y" in column W.

A: Try this:
function Optimize() {
  const sh = SpreadsheetApp.getActiveSheet();
  const rg = sh.getDataRange();
  const vs = rg.getValues();
  const lc = sh.getLastColumn();
  let o = vs.forEach((r,i) => {
    if(r[22] == "Y") {
      sh.getRange(i + 1, lc + 1,1,lc).setValues([r])
    }
  });
}


text:
Q: Inconsistency between packages adding appendices. Error: Missing number, treated as zero I'm using a .sty file provided by the university to write my thesis. If I try to add an appendix using a very simple case such as the file below (omiting nonrelevant data), I get the error Missing number, treated as zero
\documentclass[12pt]{book}
\usepackage[titletoc]{appendix}
\begin{document}

\maketitle

\tableofcontents

\chapter{1}
\chapter{2}
\begin{appendices}
\chapter{a1}
\end{appendices}

\end{document}

I'm sure that the problem comes from the following lines of the .sty file (if I comment them I don't get the error message, but I loose a good part of the formatting):
\makeatletter
\iffalse  % ancien template utilité par coralie
\definecolor{gris_chap}{gray}{0.85}
\def\@makechapterhead#1{%
 \vspace*{20\p@}%
 {\parindent \z@ \raggedright \normalfont
   \ifnum \c@secnumdepth >\m@ne
     \if@mainmatter
       \raggedleft\scalebox{7}{\huge\bfseries\textsf{\textcolor{gray}{\thechapter~}}}  %\textsc{}

       \par\nobreak
       \vskip 30\p@

       \vspace{-3cm}

     \fi
   \fi
   \interlinepenalty\@M
   \Huge \bfseries \textsf{ #1}\par\nobreak
   \vskip 40\p@
 }}
\makeatother

\makeatletter
\def\@makeschapterhead#1{%
 \vspace*{20\p@}%
 {\if@mainmatter
  \parindent \z@ \raggedleft
   \normalfont
   \interlinepenalty\@M
   \Huge \bfseries  #1\par\nobreak
   \vskip 30\p@
  \else
  \parindent \z@ \raggedright
   \normalfont
   \interlinepenalty\@M
   \Huge \bfseries  #1\par\nobreak
   \vskip 40\p@
  \fi
 }}
\makeatother
\fi
% fin Alex chapitres

% nouveau templace chapitre
\def\thickhrule{\leavevmode \leaders \hrule height 1ex \hfill \kern \z@}
\def\position{\centering}
%% Note the difference between the commands the one is
%% make and the other one is makes
\renewcommand{\@makechapterhead}[1]{%
  \vspace*{10\p@}%
  {\parindent \z@ \position \reset@font
        {\HUGE  \scshape  \romannumeral \thechapter }
        \par\nobreak
        \vspace*{10\p@}%
        \interlinepenalty\@M
        \thickhrule
        \par\nobreak
        \vspace*{2\p@}%
        {\Huge \bfseries #1\par\nobreak}
        \par\nobreak
        \vspace*{2\p@}%
        \thickhrule
    \vskip 40\p@
    \vskip 40\p@
  }}

%% This uses makes

\iffalse
\def\@makeschapterhead#1{%
  \vspace*{10\p@}%
  {\parindent \z@ \position \reset@font
        {\Huge \scshape \vphantom{\thechapter}}
        \par\nobreak
        \vspace*{10\p@}%
        \interlinepenalty\@M
        \thickhrule
        \par\nobreak
        \vspace*{2\p@}%
        {\Huge \bfseries #1\par\nobreak}
        \par\nobreak
        \vspace*{2\p@}%
        \thickhrule
    \vskip 100\p@
  }}
\fi

% Pour avoir des pages réellement vides entre les chapitres
\makeatletter
\def\cleardoublepage{\clearpage\if@twoside \ifodd\c@page\else
\hbox{}
\vspace*{\fill}
\vspace{\fill}
\thispagestyle{empty}
\newpage
\if@twocolumn\hbox{}\newpage\fi\fi\fi}
\makeatother

% En-tête et pieds de page avec fancyhdr
\headheight=14.85pt
% pour récupérer les noms de section en minuscule
\renewcommand{\chaptermark}[1]{\Makelowercase \markboth{\thechapter.\ #1}{}}
\renewcommand{\sectionmark}[1]{\markright{\thesection\ #1}}
\fancyhf{}
\fancyhead[RO]{\bfseries\rightmark}
\fancyhead[LE]{\bfseries\leftmark}
\fancyfoot[LE,RO]{\bfseries\thepage}
\renewcommand{\headrulewidth}{0.5pt}
\addtolength{\headheight}{0.5pt}
\renewcommand{\footrulewidth}{0pt}
\fancypagestyle{plain}{\fancyhead{}\renewcommand{\headrulewidth}{0pt}}

%%% mode: latex
%%% TeX-master: "main"
%% End:

Does anyone know what is wrong within these lines? Thank you for any help!


text:
Q: MISSISSIPPI with 2 constraints This is a post with two questions:
The problem states:
How many arrangements of MISSISSIPPI are there in which the first I precedes the first S and the first S precedes the first P.
First answer and question:
For the $S$'s the basic construction is:
$$
I \wedge S \wedge P \wedge P \wedge,
$$
so there are 4 spaces where to put 3 $S$'s: $\binom{6}{3}$.
For each arrangement of the $S$'s there are $8$ spaces where to fit $3$ $I$'s: $\binom{10}{3}$.
Finally, for the $M$, there are 11 ways to put it. Answer: $\binom{6}{3}\binom{10}{3}\binom{11}{1}=26400$. Apparently this is wrong, is it?

Second answer and question
The basic construction is
$$
\wedge I \wedge S \wedge P \wedge P \wedge,
$$
but here, the S's can occupy places $2-5$, $I$'s and the M can occupy all the places.
(a) There's zero $I$'s in places $2-5$ and $M$ is also in place $1$:
$1 \binom{6}{3}\frac{4!}{3!}$. (The first one is arrange the $S$'s, the arrange them in the allowed places, and the last term is to arrange $I$'s and the $M$ in the first place.
(b) There's zero $I$'s in places $2-5$ and $M$ is also in places $2-5$:
$\frac{4!}{3!} \binom{7}{4} 1$. (Again, the first term is to arrange the $S$'s and the $M$, then place them in the places $2-5$, the last term is the arrangement of $3$ identical I's.
(c) $1$ $I$ in places $2-5$ and $M$ in place $1$: $\frac{4!}{3!}\binom{7}{4}\frac{3!}{2!}$
(d) $1$ $I$ in places $2-5$ and $M$ in places $2-5$: $\frac{5!}{3!}\binom{8}{5} 1$
(e) $2$ $I$'s in places $2-5$ and $M$ in place $1$: $\frac{5!}{3!2!}\binom{8}{5} 2!$
(f) $2$ $I$'s in places $2-5$ and $M$ in places $2-5$: $\frac{6!}{3!2!}\binom{9}{6}$
(g) $3$ $I$'s in places $2-5$ and $M$ in place $1$: $\frac{6!}{3!3!}\binom{9}{6}$
(h) $3$ $I$'s in places $2-5$ and $M$ in places $2-5$: $\frac{7!}{3!3!}\binom{10}{7}$
Summing up all the cases I obtain the same number as my answer 1: $\binom{6}{3}\binom{10}{3}\binom{11}{1}$.
Now, my second question is the following, is it wrong this last argument?
I don't know if I can save my answer because for example I think I have double counting in the following example (I placed in parenthesis the position of the letters that occupy an allowed space):
$$
(M) I (SISI) S \wedge P (IS) P \wedge = \\
(M) I \wedge S (ISIS) P (IS) P \wedge
$$
This is some special case of (g), and they count differently because of the position of the letters and the permutation in the arrangement, but both are
at the end the word $MISISISPISP$.

A: Answer for first question.  Your method is basically correct.  However, after you have
$$I\cdots S\cdots P\cdots P\cdots\ ,$$
there are three possible places for the remaining $S$s, not four, because the one you have already is the first $S$.  Similarly, when you have
$$I\cdots S\cdots S\cdots P\cdots P\cdots S\cdots S\cdots$$
or something similar, there are seven places, not eight, for the remaining $I$s.  So the number of arrangements is
$$\binom53\binom9311=9240\ .$$
Note that to count the arrangements correctly you must specify at the beginning which is the first $S$ (and $I$ and $P$).  Once you have done this, then obviously you cannot place another $S$ before the first $S$.  If you don't do it this way, then taking for example
$$I\cdots_1S\cdots_2$$
and putting the next $S$ in place $1$ or place $2$ will give you the same arrangement counted twice.

A: Here is an alternate solution:
Since there are $11$ letters in MISSISSIPPI, there are $11$ ways to place the M.  We must fill the remaining $10$ positions with four I's, four S's, and two P's.  Since the first I must appear before the first S and the first S must appear before the first P, we must fill the leftmost open position with an I.  We are left with nine spaces to fill.  We can fill three of them with an I in $\binom{9}{3}$ ways.  This leaves us with six spaces to fill with the four S's and two P's.  Since the first S must appear before the first P, we must fill the leftmost open position with an S.  This leaves us with five spaces to fill.  We can fill three of them with the remaining S's in $\binom{5}{3}$ ways.  We can place the two P's in the two remaining positions in one way.  Hence, the number of permutations of MISSISSIPPI in which the first I appears before the first S and the first S appears before the first P is $$11\binom{9}{3}\binom{5}{3}$$


text:
Q: 2-way binding in Vue 2.3 component I understand the .sync modifier returned in Vue 2.3, and am using it for a simple child component which implements a 'multiple-choice' question and answer. The parent component calls the child like this:
<question
  :stem="What is your favourite colour?"
  :options="['Blue', 'No, wait, aaaaargh!']
  :answer.sync="userChoice"
>

The parent has a string data element userChoice to store the result from the child component. The child presents the question and radio buttons for the options. The essential bits of the child look like this (I'm using Quasar, hence q-radio):
<template>

{{stem}}

        <q-radio v-model="option" :val="opt.val" @input="handleInput"></q-radio>
        {{opt.text}}

</template>

export default {
  props: {
    stem: String,
    options: Array,
    answer: String
  },
  data: () => ({
    option: null
  }),
  methods: {
    handleInput () {
      this.$emit('update:answer', this.option)
    }
  }
}

This is all working fine, apart from the fact that if the parent then changes the value of userChoice due to something else happening in the app, the child doesn't update the radio buttons. I had to include this watch in the child:
  watch: {
    answer () {
      this.option = this.answer
    }
  }

But it feels a little redundant, and I was worried that emitting the event to update the parent's data would in fact cause the child 'watch' event to also fire. In this case it would have no effect other than wasting a few cycles, but if it was logging or counting anything, that would be a false positive...
Maybe that is the correct solution for true 2-way binding (i.e. dynamic Parent → Child, as well as Child → Parent). Did I miss something about how to connect the 'in' and 'out' data on both sides?
In case you're wondering, the most common case of the parent wanting to change 'userChoice' would be in response to a 'Clear Answers' button which would set userChoice back to an empty string. That should have the effect of 'unsetting' all the radio buttons.

A: Your construction had some oddities that didn't work, but basically answer.sync works if you propagate it down to the q-radio component where the changing happens. Changing the answer in the parent is handled properly, but to clear values, it seems you need to set it to an object rather than null (I think this is because it needs to be assignable).
Update
Your setup of options is a notable thing that didn't work.
I use answer in the q-radio to control its checked state (v-model has special behavior in a radio, which is why I use value in conjunction with v-model). From your comment, it looks like q-radio wants to have a value it can set. You ought to be able to do that with a computed based on answer, which you would use instead of your option data item: the get returns answer, and the set does the emit. I have updated my snippet to use the val prop for q-radio plus the computed I describe. The proxyAnswer emits an update event, which is what the .sync modifier wants. I also implemented q-radio using a proxy computed, but that's just to get the behavior that should already be baked-into your q-radio.
(What I describe is effectively what you're doing with a data item and a watcher, but a computed is a nicer way to encapsulate that).

new Vue({
  el: '#app',
  data: {
    userChoice: null,
    options: ['Blue', 'No, wait, aaaaargh!'].map(v => ({
      value: v,
      text: v
    }))
  },
  components: {
    question: {
      props: {
        stem: String,
        options: Array,
        answer: String
      },
      computed: {
        proxyAnswer: {
          get() {
            return this.answer;
          },
          set(newValue) {
            this.$emit('update:answer', newValue);
          }
        }
      },
      components: {
        qRadio: {
          props: ['value', 'val'],
          computed: {
            proxyValue: {
              get() {
                return this.value;
              },
              set(newValue) {
                this.$emit('input', newValue);
              }
            }
          }
        }
      }
    }
  },
  methods: {
    clearSelection() {
      this.userChoice = {};
    }
  }
});

  <question stem="What is your favourite colour?" :options="options" :answer.sync="userChoice" inline-template>

{{stem}}

Answer={{answer && answer.text}}, option={{opt.text}}

        <q-radio :val="opt" v-model="proxyAnswer" inline-template>
          <input type="radio" :value="val" v-model="proxyValue">
        </q-radio>
        {{opt.text}}

  </question>
  <button @click="clearSelection">Clear</button>


text:
Q: TMainMenu - managing Help and Search menu items Running my Firemonkey app in OSX, a Search box automatically appears on my last menu item, which I have labeled "Help." So far so good, because a Help menu with a Search box is standard for OSX.
Next, I needed to add a help file. I purchased an impressive utility Help Crafter with which I very quickly and easily made an Apple HelpBook. I placed the HelpBook bundle into the Resources folder of my main app. I then used Project|Options|Version Info in the IDE to edit the Info.plist file. I added two keys CFBundleHelpBookFolder and CFBundleHelpBookName to Info.plist to point to my HelpBook.
Running my app, I now found I had two Help menu items -- the item I had programmed and another apparently automatically created by the Mac OS, complete with a submenu item that brings up my HelpBook. To my amazement, I now had working help without any coding whatsoever.
Next, I wanted to remove the Help menu item I had created in order to eliminate the duplication. But the Search box was still located under my Help menu item, not on the Help menu item created by the OS. And when I deleted my Help menu item, the Search box relocated to what was now the last menu item created by me.

*

*How can I specify that the Search box should be located on the OS-created
Help menu item?

*Alternatively, can I specify that the OS should not automatically
create a Help menu item (so that I can create it myself)? In that
case, I should also need to know how to program the loading of the
HelpBook.

*If I stick with the OS-created Help menu item, how can I add
additional submenu items to it?

It appears from Apple documentation that the Help and Search functions are provided by the OS when a HelpBook has been registered. But the two functions are supposed to be on the same menu item. I am wondering if this may be a Firemonkey bug that they are being split up.

A: There were three parts to my question above. I have had no luck with 1 and 3, but I have a partial solution to 2.
To prevent the OS automatically creating a Help menu, it was only necessary to delete the CFBundleHelpBookFolder and CFBundleHelpBookName keys in Info.plist. The registering of the HelpBook was then accomplished in FormCreate with:
var
{$IFDEF MACOS}
  HelpBundle: NSBundle;
  AppBundle: NSBundle;
  Path: string;
  HelpReg: Boolean;
{$ENDIF}
begin
{$IFDEF MACOS}
  HelpMgr := TNSHelpManager.Create; // HelpMgr declared as a global variable
  AppBundle := TNSBundle.Wrap(TNSBundle.OCClass.mainBundle);
  Path := AppBundle.bundlePath.UTF8String +
    '/Contents/Resources/MyAppHelp.help';
  HelpBundle := TNSBundle.Wrap(TNSBundle.OCClass.bundleWithPath(StrToNSSTR(Path)));
  HelpReg := HelpMgr.registerBooksInBundle(HelpBundle);
  if not(HelpReg) then
    ShowMessage('Failed to register Help Book');
{$ENDIF}

To open the HelpBook, I placed the following code in the OnClick event of the appropriate submenu item (i.e. Help| MyApp Help):
HelpMgr.openHelpAnchor(StrToNSSTR('Page0'),
        StrToNSSTR('com.mycompany.myapp.help'));

This approach resulted in the Spotlight for Help field being added automatically to the Help menu. Unfortunately, Spotlight for Help doesn't index my HelpBook anymore. With the approach I had first tried (using Info.plist as described in my original post), Spotlight for Help did index my HelpBook but, as I reported, the Spotlight field was created on my last menu item and Help was on a new menu item created automatically by the OS, which while functional is non-standard.


text:
Q: Do i need 'unsigned' keyword with uintXX_t? I just discovered fixed-size types which can be found in stdint.h / cstdint. Some of them are "normal" types, like int32_t and some are designed to be unsigned, like uint64_t.
Do i need to use the "unsigned" keyword when using types which are unsigned by design ?

A: You do not need to use unsigned and in fact, you can not use it.
Only the fundamental types may be modified with the signed and unsigned (also long and short) keywords.
Aliases of the standard types can not be modified using those keywords and that includes the fixed width aliases.
If you write unsigned int32_t, then the compiler will parse this as a variable with type unsigned (which is shorthand for unsigned int) and the name of the variable will be int32_t. unsigned int32_t variable_name would be a syntax error.


text:
Q: Intellij 13.1.3 import project from sbt not working I have followed the instructions , attempting to either import from build.sbt or open project from build.sbt.
The end result is that the scala libraries are not imported as shown in the screenshot.
I have also tried sbt gen-idea from the command line.
This is just a problem that keeps surfacing..

A: If you are using Intellij, why don't you create scala sbt project? Then just add the libraries in the build.sbt and refresh the project or re-run the sbt gen-idea. The libraries will appear. See this link:
http://confluence.jetbrains.com/display/IntelliJIDEA/Getting+Started+with+SBT

A: I STILL have not figured out what the "magic" sequence of actions to follow in order to have  a reliable sbt build.
This time around the following worked:
TWICE running
sbt gen-idea

*

*and then import'ing the build.sbt as a new scala project

What did not work

*

*Import project from build.sbt  (without sbt gen-idea)

*Open project from build.sbt   (ditto)

*Open build.sbt from Explorer (selecting IJ to open it)


text:
Q: Problemas con Task Scheduling Laravel 6 Buen día,
Estoy tratando de realizar una tarea programada en laravel y cpanel, en la cual me borra cada mes los registros temporales de unos folios en Mysql, pero no me esta funcionando eh visto muchas preguntas aquí y en la documentación oficial de larevel 6
¿Quizá alguien me pueda guiar en que estoy haciendo mal?
Mi Command
    <?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class TruncateTempFolios extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'truncate:TempFolios';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Borrar cada primero de mes la tabla temp_folios';
    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        \DB::statement("SET foreign_key_checks=0");
        \DB::table('temporal_folios')->truncate();
        \DB::statement("SET foreign_key_checks=1");
    }
}

Mi Console/Kernel
<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        Commands\TruncateTempFolios::class,
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        $schedule->command('truncate:TempFolios')
        ->timezone('America/Tijuana')
        ->monthlyOn(1, '00:00');
    }

    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__.'/Commands');

        require base_path('routes/console.php');
    }
}

Tarea Cron en cpanel
0   0   1   *   *   /usr/local/bin/php /home/domain/public_html/test/artisan schedule:run >> /dev/null 2>&1
Hice algunas pruebas en local y funcionan algunos test de cada minuto pero en el hosting compartido no funcionan!

A: Tal y como dice la documentación de Laravel, el cron debe ejecutarse cada minuto, lo cual se logra con la siguiente sintaxis:
* * * * * /usr/local/bin/php /home/domain/public_html/test/artisan schedule:run >> /dev/null 2>&1

Todo esto, asumiendo que la ruta de php y de artisan son correctas.
https://laravel.com/docs/5.8/scheduling#introduction


text:
Q: Installing Xcode 3.2.5 on Mac OS X 10.6 This is my systems software config.

*

*System Version:  Mac OS X 10.6 (10A432)

*Kernel Version:  Darwin 10.0.0

i am trying to install xcode 3.2.5 but it says that  need 10.6.4. What is the latest version that i can use with installation and i think 10.6 is snow leopard so this version should work. but i m a very very new as far as mac is concerned and know close to nothing. so please any pointers as to what i should do would be greatly appreciated.
regards,
khizar

A: You need 10.6.4 or later.  Upgrade from your 10.6.x to the latest version of 10.6, the upgrade is free, just select "Software Update..." from the Apple menu.


text:
Q: How to multicast FOTA with CoAP I use CoAP ( write by C) to FOTA multicast but It timeout. I use unicast it still work done.
p/s:Sorry I use English don't well.
link source lib-coap: https://github.com/obgm/libcoap
image error:
enter image description here
How to fix it. Thanks.
I tried unicast and I want to use for multicast. But it don't work.

A: Using CON messages, CoAP adds "reliability" on the top of UDP.
But for multicast UDP, this doesn't work. Otherwise, you would need to know, how many devices are used.  RFC 7252 doesn't specify that use-case.
Multicast is also mostly limited to local-networks, it's very useful to discover the devices there, but not for FOTA.
That kind of optimizations usually don't pay off.


text:
Q: CLR User Defined Aggregate Function in order to get the first element of a sequence I need a FIRST aggregate function which returns the first element of a sequence and I will use that with HAVING clause.
this is a question which can be viewed as a continuation of my previous question: FIRST aggregate function which I can use with HAVING clause.
It turns out that only an aggregate function can solve my problem so I tried to create one:
[Serializable]
[SqlUserDefinedAggregate(
    Format.UserDefined, //use clr serialization to serialize the intermediate result
    IsInvariantToNulls = true, //optimizer property
    IsInvariantToDuplicates = false, //optimizer property
    IsInvariantToOrder = false, //optimizer property
    MaxByteSize = 8000) //maximum size in bytes of persisted value
]
public struct GetFirst : IBinarySerialize {

    private string allValues;

    public void Init() {
        allValues = string.Empty;
    }

    private void incrementAndAdd(SqlInt32 value) {

        allValues += (value.Value.ToString() + ",");
    }

    public void Accumulate(SqlInt32 Value) {

        incrementAndAdd(Value);
    }

    public void Merge(GetFirst Group) {

    }

    public SqlInt32 Terminate() {
        // Put your code here
        return new SqlInt32(int.Parse(allValues.Split(',')[0]));
    }

    // This is a place-holder member field
    private SqlInt32 var1;

    public void Read(System.IO.BinaryReader r) {

        allValues = r.ReadString();
    }

    public void Write(System.IO.BinaryWriter w) {

        w.Write(this.allValues);
    }
}

And this is how I used it:
DECLARE @fooTable AS TABLE(
    ID INT,
    CategoryName NVARCHAR(100),
    Name NVARCHAR(100),
    MinAllow INT,
    Price DECIMAL(18,2)
);

INSERT INTO @fooTable  VALUES(1, 'Cat1', 'Product1', 3, 112.2);
INSERT INTO @fooTable  VALUES(2, 'Cat2', 'Product2', 4, 12.34);
INSERT INTO @fooTable  VALUES(3, 'Cat1', 'Product3', 5, 233.32);
INSERT INTO @fooTable  VALUES(4, 'Cat3', 'Product4', 4, 12.43);
INSERT INTO @fooTable  VALUES(5, 'Cat3', 'Product5', 1, 13.00);
INSERT INTO @fooTable  VALUES(7, 'Cat4', 'Product7', 1, 15.00);
INSERT INTO @fooTable  VALUES(6, 'Cat4', 'Product6', 3, 13.00);

DECLARE @minAllowParam AS INT = 3;

SELECT ft.CategoryName, SUM(ft.Price), dbo.GetFirst(ft.MinAllow) FROM @fooTable ft
GROUP BY ft.CategoryName
HAVING dbo.GetFirst(ft.MinAllow) >= @minAllowParam;

It sometimes returns the proper result, sometimes not and I am quite not sure if I implemented it right. Any thoughts if I got this right in view of my requirements?

A: I think your problem is that IsInvariantToOrder is not yet implemented.

Reserved for future use. This property is not currently used by the
  query processor: order is currently not guaranteed.

So there is no guarantee that your function will be called in the correct order or even the same order between runs.
I don't know that much C# but I think it is possible to have two parameters to your function where the second is the field you want to order by. Save the pairs in a list and sort on the second field before you return the first value.
Update:
I don't do C# so there might be any number of errors bad practices in here that I don't see. But it looks like it works just fine in the tests I have made.
using System;
using System.Data;
using Microsoft.SqlServer.Server;
using System.Data.SqlTypes;
using System.IO;
using System.Text;

[Serializable]
[SqlUserDefinedAggregate(
    Format.UserDefined, //use clr serialization to serialize the intermediate result
    IsInvariantToNulls = true, //optimizer property
    IsInvariantToDuplicates = false, //optimizer property
    IsInvariantToOrder = false, //optimizer property
    MaxByteSize = 8000) //maximum size in bytes of persisted value
]

public class GetFirst : IBinarySerialize
{
    private int Value;
    private int OrderBy;

[SqlFunctionAttribute(IsDeterministic = true)]
    public void Init()
    {
      Value = 0;
      OrderBy = int.MaxValue;
    }

[SqlFunctionAttribute(IsDeterministic = true)]
    public void Accumulate(SqlInt32 SValue, SqlInt32 SOrderBy)
    {
        if (SValue.IsNull)
        {
            return;
        }

        if (SOrderBy.IsNull)
        {
            return;
        }

        if (SOrderBy.Value < OrderBy)
        {
            Value = SValue.Value;
            OrderBy = SOrderBy.Value;
        }
    }

[SqlFunctionAttribute(IsDeterministic = true)]
    public void Merge(GetFirst other)
    {
        if (other.OrderBy < OrderBy)
        {
            Value = other.Value;
            OrderBy = other.OrderBy;
        }
    }

[SqlFunctionAttribute(IsDeterministic = true)]
    public SqlInt32 Terminate()
    {
      return new SqlInt32(Value);
    }

[SqlFunctionAttribute(IsDeterministic = true)]
    public void Read(BinaryReader r)
    {
        Value = r.ReadInt32();
        OrderBy = r.ReadInt32();
    }

[SqlFunctionAttribute(IsDeterministic = true)]
    public void Write(BinaryWriter w)
    {
        w.Write(Value);
        w.Write(OrderBy);
    }
}

Install:
CREATE ASSEMBLY GetFirstAsm FROM 'First.dll'
GO
CREATE AGGREGATE GetFirst (@Value int, @OrderBy int) RETURNS int
EXTERNAL NAME GetFirstAsm.GetFirst

Use like this:
declare @T table
(
  ID1 int,
  ID2 int,
  Val int,
  Grp int
)

insert into @T values
(1, 5, '1', 1),
(2, 4, '2', 1),
(3, 3, '3', 1),
(4, 2, '4', 2),
(5, 1, '5', 2)

select Grp, dbo.GetFirst(Val, ID1) as Val
from @T
group by Grp

select Grp, dbo.GetFirst(Val, ID2) as Val
from @T
group by Grp

Result:
(5 row(s) affected)
Grp         Val
----------- -----------
1           1
2           4

(2 row(s) affected)

Grp         Val
----------- -----------
1           3
2           5

(2 row(s) affected)


text:
Q: Django Blog Add Comment Text Field Not Showing I have used django's models and forms to add a comment section to a blog app, however the form's text field will not show when loaded in the in the browser when i try to add a comment to a post. Only the submit button and the title is visible with no textfield to submit with.
models.py
from django.db import models
from django.utils import timezone

# Create your models here.
class Post(models.Model):
    author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
    title = models.CharField(max_length=200)
    text = models.TextField()
    created_date = models.DateTimeField(default=timezone.now)
    published_date = models.DateTimeField(blank=True, null=True)

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self):
        return self.title

class Comment(models.Model):
    post = models.ForeignKey('blog.Post', on_delete=models.CASCADE, related_name='comments')
    author = models.CharField(max_length=200)
    created_date = models.DateTimeField(default=timezone.now)
    text = models.TextField()

    def __str__(self):
        return self.text

forms.py
from django import forms
from .models import Post, Comment

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ('title', 'text')

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ('author', 'text',)

views.py
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, get_list_or_404, get_object_or_404, redirect
from django.utils import timezone

from blog.forms import PostForm
from .models import Post, Comment
from .forms import PostForm, CommentForm

# Create your views here.
def post_list(request):
    posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')
    stuff_for_frontend = {'posts': posts}
    return render(request, 'blog/post_list.html', stuff_for_frontend)

def post_detail(request, pk):
    post = get_object_or_404(Post, pk=pk)
    stuff_for_frontend = {'post': post}
    return render(request, 'blog/post_detail.html', stuff_for_frontend)

@login_required
def post_new(request):
    if request.method == "POST":
        form = PostForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user
            post.save()
            return redirect('post_detail', pk=post.pk)

    else:

        form = PostForm()
        stuff_for_frontend = {'form': form}
    return render(request, 'blog/post_edit.html', stuff_for_frontend)

def post_edit(request, pk):
    post = get_list_or_404(Post, pk=pk)
    if request.method == 'POST':

        # updating existing form
        form = PostForm(request.POST, instance=post)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user
            post.save()
            return redirect('post_detail', pk=post.pk)
        else:
            form = PostForm(instance=post)
            stuff_for_frontend = {'form': form, 'post': post}
        return render(request, 'blog/post_edit.html', stuff_for_frontend)

@login_required
def post_draft_list(request):
    posts = Post.objects.filter(published_date__isnull=True).order_by('-created_date')
    stuff_for_frontend = {'posts': posts}
    return render(request, 'blog/post_drafts_list.html', stuff_for_frontend)

@login_required
def post_publish(request, pk):
    post = get_object_or_404(Post, pk=pk)
    post.publish()
    return redirect('post_detail', pk=pk)

def add_comment_to_post(request, pk):
    post = get_object_or_404(Post, pk=pk)
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.author = request.user
            comment.post = post
            comment.save()
            return redirect('post_detail', pk=post.pk)
    else:
        form = CommentForm()
    return render(request, 'blog/add_comment_to_post.html', {form: 'form'})

def comment_remove(request, pk):
    comment = get_object_or_404(Comment, pk=pk)
    comment.delete()
    return redirect('post_detail', pk=comment.post.pk)

Add Comment HTML
{% extends 'blog/base.html' %}
{% block title %} Add Comment {% endblock %}
{% block content %}

New Comment

<form method="POST" class="post-form-blog">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit" class="save btn btn-default">Post</button>
</form>
{% endblock %}

enter image description here

A: I think you just mixed up two items in this line:
return render(request, 'blog/add_comment_to_post.html', {form: 'form'})

It should be
return render(request, 'blog/add_comment_to_post.html', {'form': form})


text:
Q: How can I fix configuration errors in ext.net? I'm new at ext.net. I create a new project and I change the web.config code but i always take configuration error. What am I supposed to do to fix this? here is my web.config code.
 <?xml version="1.0"?>
 <configuration>
  <configSections>
    <section name="extnet" type="Ext.Net.GlobalConfig" requirePermission="false"/>
 </configSections>
 <extnet scriptMode="Release"/>
 <!-- See Property Options in README.txt -->
 <!--
    The following system.web section is only requited for running ASP.NET AJAX under Internet
    Information Services 6.0 (or earlier).  This section is not necessary for IIS 7.0 or later.
  -->
 <system.web>
    <httpHandlers>
        <add path="*/ext.axd" verb="*" type="Ext.Net.ResourceHandler" validate="false"/>
    </httpHandlers>
    <httpModules>
        <add name="DirectRequestModule" type="Ext.Net.DirectRequestModule, Ext.Net"/>
    </httpModules>
    <compilation debug="true">
        <assemblies>
            <add assembly="System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
            <add assembly="System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
            <add assembly="System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
            <add assembly="System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
            <add assembly="System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
            <add assembly="System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
            <add assembly="System.Xml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
            <add assembly="System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
            <add assembly="Microsoft.CSharp, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
            <add assembly="System.ComponentModel.DataAnnotations, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/></assemblies></compilation></system.web>
<!--
    The system.webServer section is required for running ASP.NET AJAX under Internet Information Services 7.0.
    It is not necessary for previous version of IIS.
-->
<system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>
    <modules>
        <add name="DirectRequestModule" preCondition="managedHandler" type="Ext.Net.DirectRequestModule, Ext.Net"/>
    </modules>
    <handlers>
        <add name="DirectRequestHandler" verb="*" path="*/ext.axd" preCondition="integratedMode" type="Ext.Net.ResourceHandler"/>
    </handlers>
</system.webServer>

A: Add </ configuration> at end of file

A: A sample Web.config for Ext.NET is located in the Examples Explorer.

A: You can add a Schema to Visual Studio. I made a schema that you can add manually.
http://forums.ext.net/showthread.php?27683-XML-Extnet-Schema-to-avoid-Information-Error-in-web-config
Add this code before  tag into DotNetConfig.xsd schema.
I create the element based on 2.4.0 README File. http://examples.ext.net/#/Getting_St...uments/README/
  <?xml version="1.0" encoding="us-ascii"?>
  <xs:element name="extnet" vs:help="configuration/extnet">
    <xs:complexType>
      <xs:attribute name="ajaxViewStateMode" use="optional">
        <xs:simpleType>
          <xs:restriction base="xs:string">
            <xs:enumeration value="Default" />
            <xs:enumeration value="Exclude" />
            <xs:enumeration value="Include" />
          </xs:restriction>
        </xs:simpleType>
      </xs:attribute>
      <xs:attribute name="cleanResourceUrl" type="small_boolean_Type" use="optional" />
      <xs:attribute name="dateTimeZoneHandling" type="xs:string" use="optional" />
      <xs:attribute name="disableViewState" type="small_boolean_Type" use="optional" />
      <xs:attribute name="directEventUrl" type="xs:string" use="optional" />
      <xs:attribute name="directMethodProxy" use="optional">
        <xs:simpleType>
          <xs:restriction base="xs:string">
            <xs:enumeration value="Default" />
            <xs:enumeration value="Include" />
            <xs:enumeration value="Ignore" />
          </xs:restriction>
        </xs:simpleType>
      </xs:attribute>
      <xs:attribute name="directMethodNamespace" type="xs:string" use="optional" />
      <xs:attribute name="glyphFontFamily" type="xs:string" use="optional" />
      <xs:attribute name="gzip" type="small_boolean_Type" use="optional" />
      <xs:attribute name="idMode" use="optional">
        <xs:simpleType>
          <xs:restriction base="xs:string">
            <xs:enumeration value="Client" />
            <xs:enumeration value="Explicit" />
            <xs:enumeration value="Ignore" />
            <xs:enumeration value="Inherit" />
            <xs:enumeration value="Legacy" />
            <xs:enumeration value="Parent" />
            <xs:enumeration value="Predictable" />
            <xs:enumeration value="Static" />
          </xs:restriction>
        </xs:simpleType>
      </xs:attribute>
      <xs:attribute name="initScriptMode" use="optional">
        <xs:simpleType>
          <xs:restriction base="xs:string">
            <xs:enumeration value="Inline" />
            <xs:enumeration value="Linked" />
          </xs:restriction>
        </xs:simpleType>
      </xs:attribute>
      <xs:attribute name="licenseKey" type="xs:string" use="optional" />
      <xs:attribute name="locale" type="xs:string" use="optional" />
      <xs:attribute name="namespace" type="xs:string" use="optional" />
      <xs:attribute name="renderScripts" use="optional">
        <xs:simpleType>
          <xs:restriction base="xs:string">
            <xs:enumeration value="Embedded" />
            <xs:enumeration value="File" />
            <xs:enumeration value="CDN" />
            <xs:enumeration value="None" />
          </xs:restriction>
        </xs:simpleType>
      </xs:attribute>
      <xs:attribute name="renderStyles" use="optional">
        <xs:simpleType>
          <xs:restriction base="xs:string">
            <xs:enumeration value="Embedded" />
            <xs:enumeration value="File" />
            <xs:enumeration value="CDN" />
            <xs:enumeration value="None" />
          </xs:restriction>
        </xs:simpleType>
      </xs:attribute>
      <xs:attribute name="resourcePath" type="xs:string" use="optional" />
      <xs:attribute name="resourcesStrategyType" type="xs:string" use="optional" />
      <xs:attribute name="resetStyles" type="small_boolean_Type" use="optional" />
      <xs:attribute name="rethrowAjaxExceptions" type="small_boolean_Type" use="optional" />
      <xs:attribute name="rtl" type="small_boolean_Type" use="optional" />
      <xs:attribute name="scriptMode" use="optional">
        <xs:simpleType>
          <xs:restriction base="xs:string">
            <xs:enumeration value="Release" />
            <xs:enumeration value="Debug" />
            <xs:enumeration value="Development" />
          </xs:restriction>
        </xs:simpleType>
      </xs:attribute>
      <xs:attribute name="showWarningOnAjaxFailure" type="small_boolean_Type" use="optional" />
      <xs:attribute name="sourceFormatting" type="small_boolean_Type" use="optional" />
      <xs:attribute name="stateProvider" use="optional">
        <xs:simpleType>
          <xs:restriction base="xs:string">
            <xs:enumeration value="PostBack" />
            <xs:enumeration value="Cookie" />
            <xs:enumeration value="None" />
          </xs:restriction>
        </xs:simpleType>
      </xs:attribute>
      <xs:attribute name="submitDisabled" type="small_boolean_Type" use="optional" />
      <xs:attribute name="theme" use="optional">
        <xs:simpleType>
          <xs:restriction base="xs:string">
            <xs:enumeration value="Default" />
            <xs:enumeration value="Access" />
            <xs:enumeration value="Gray" />
            <xs:enumeration value="Neptune" />
          </xs:restriction>
        </xs:simpleType>
      </xs:attribute>
      <xs:attribute name="themePath" type="xs:string" use="optional" />
      <xs:attribute name="quickTips" type="small_boolean_Type" use="optional" />
      <xs:anyAttribute namespace="http://schemas.microsoft.com/XML-Document-Transform" processContents="strict"/>
    </xs:complexType>
  </xs:element>

Then you can debug what is wrong on your ext.net configuration. And additionally you can use and have Ext.net Intellisense on web.config :D


text:
Q: Combining autoResizeRows and setting empty rows to a size of 1 My goal is to set empty rows to a hight of 1 and filled ones to a fitting size (autosized) but I cant find a way to combine those two.
This is, what I'm currently using but it sets empty rows to 21 instead of 1:
function Higth() {
var s = SpreadsheetApp.getActive().getActiveSheet();

s.autoResizeRows(5, 31);
// 5 is the row in which the resizing starts and 31 is the amount of rows this is done
}

I hope someone knows a way to do this.
Jonah

A: I suggest you use the implementation in this SO post, given the active range:

function changeRowHeight()
{
  var ss=SpreadsheetApp.getActiveSpreadsheet();
  var sht=ss.getActiveSheet()
  var rng=sht.getActiveRange();
  var row=rng.getRow();
  var numrows=rng.getNumRows();
  var resp=SpreadsheetApp.getUi().prompt('Get Row Height', 'Enter Row Height in Pixels', SpreadsheetApp.getUi().ButtonSet.OK);
  var height = Number(resp.getResponseText());
  for(var i=0;i<numrows;i++)
  {
    sht.setRowHeight(row + i, height)
  }
}

Then you can insert some if() statement to check if the given row is filled with text using the autoResizeRowsfunction given in the Apps Script documentation. It should be something like this:

Sets the height of all rows starting at the given row position to fit
  their contents.
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

// Sets the first 15 rows to a height that fits their text.
sheet.autoResizeRows(1, 15);


text:
Q: ASP.NET MVC - After HTML append with Jquery the DropDownList value comes as undefined I have two dropdownlist and when I change the value of the first one with refreshes the value of the second one with the following code:
 function FillBooks(val) {
            $("#ddl_dep").attr("class", "form-group");
            $("#Help1").css("visibility", "hidden");
            var CategoryId = val;
            //console.log(CategoryId);
            console.log(CategoryId)
            $("#DDL_TIPO").empty();
            $.ajax({
                url: '@Url.Action("UpdateTipo", "Tickets")',
                type: "POST",
                dataType: "JSON",
                data: { value: CategoryId },
                success: function (data) {
                    var markup = "<option value='0'>Selecione um Tipo</option>";
                    for (var x = 0; x < data.length; x++) {
                        markup += "<option value=" + data[x].value + ">" + data[x].Text + "</option>";
                    }
                    $("#DDL_TIPO").html(markup).show();

                }
            });

        }

P.S - The data comes from the controller which is not relevant for the exemple that I am showing.
After this when I try to get the value of the Second dropdownlist it comes as undefined.
I tested before this jquery code and it gives me the value of the dropdownlist, it just doesn't give when I get this function to work on it.

A: Try this:
<script>
        function FillBooks(val)
    {

                $("#ddl_dep").attr("class", "form-group");
                $("#Help1").css("visibility", "hidden");
                var CategoryId = val;
                //console.log(CategoryId);
                console.log(CategoryId)
            $.ajax
            ({
                url: '@Url.Action("UpdateTipo", "Tickets")',
                type: 'POST',
                datatype: 'application/json',
                contentType: 'application/json',
                data: { value: CategoryId },
                success: function(result)
              {
                    $("#DDL_TIPO").html("");
                    $.each($.parseJSON(result), function(i, tipo)
                    {
                        $("#DDL_TIPO").append($('<option</option>').val(tipo.Value).html(tipo.Text))
                    })

                },
                error: function()
                {
                    alert("Whooaaa! Something went wrong..")
                },
            });
        }
    </script>


text:
Q: For what real values of $k$ does the series $\sum\frac{k^n}{\sqrt{n}}$ converge? I think it's $|k| < 1$, but I don't know how to prove it. It's either that or it never converges. $\sum\frac{1}{\sqrt{n}}$ obviously diverges, but can't an exponential beat it and make the sum finite?

A: If you do D'alembert's test you will have
$$ \lim_{n \to \infty}{\left|\frac{\frac{k^{n+1}}{\sqrt{n+1}}}{\frac{k^n}{\sqrt{n}}}\right|}
= \lim_{n \to \infty}{\left|\frac{k^{n+1}\sqrt{n}}{k^n\sqrt{n+1}}\right|}
= \lim_{n \to \infty}{|k|\sqrt{\frac{n}{n+1}}} = |k|
$$
So this tells you that the series converges for $|k| < 1$ and diverges for $|k| > 1$, for $k = 1$ it diverges like you said, and for $k = -1$ it is easy to see using Dirichlet's test that the series converges.

A: You are correct. I would recommend using a comparison test to the geometric series $\sum k^n$ to show convergence and comparison to the series $\sum \frac{1}{\sqrt{n}} $ to show divergence.


text:
Q: \usebeamerfont introduces extra space I have a (probably trivial) question about \usebeamerfont.
I want to use this command inside a \mbox and it somehow produces extra space compared to the manual change of font. Here comes my MWE:
\documentclass{beamer}

\setbeamerfont*{A}{size=\Large}
\begin{document}
    \begin{frame}
        \fbox{\Large a}
        \fbox{\usebeamerfont{A} a}
    \end{frame}
\end{document}

I would really appreciate an explanation of this behaviour.

A: It's because there is an extra space in there ¯_(ツ)_/¯. I thought, this command was non-space-sensitive...


text:
Q: ¿Cómo restar 2 columnas de fecha y mostrar en resultado en horas? Mi duda es como restar dos columnas pertenecientes a un dataframe y el resultado mostrarlo en horas (con los decimales incluidos).
Las dos columnas de fechas están transformadas a datetime:
fecha1 2018-09-11 11:31:09
fecha2 2018-09-10 10:30:38
resultado 25.008611  horas

A: Este código de puede servir u orientar para lo que quieres. La precisión de los decimales está dada en segundos.
import datetime

def restar_fechas(fecha1, fecha2):
    start_date = datetime.datetime.strptime(fecha1, '%Y-%m-%d %H:%M:%S')
    end_date = datetime.datetime.strptime(fecha2, '%Y-%m-%d %H:%M:%S')
    diff = end_date - start_date
    return diff.days*24 + diff.seconds/3600

# valores de prueba
print(restar_fechas('2018-09-10 10:30:38', '2018-09-10 11:31:09'))
print(restar_fechas('2018-09-10 10:30:38', '2018-09-11 11:31:09'))

Salida
1.0086111111111111
25.00861111111111

A: Si tus columnas son de tipo numpy.datetime64 como debería ser dado que el tipo nativo que usa Pandas (habría que ver como parseas esas columnas de no ser así), puedes restarlas directamente, con lo que obtienes una columna (Serie) con la diferencia con tipo  TimeDelta. Para pasarlo a horas basta con dividir entre el Timedelta que representa una hora:
import pandas as pd

data = {
        "a": ("2018-09-11 11:31:09", "2018-09-14 13:25:14"),
        "b": ("2018-09-10 10:30:38", "2018-09-14 11:05:38")
        }

df = pd.DataFrame(data, dtype="datetime64[ns]")
df["c"] = (df.a - df.b) / pd.Timedelta('1 hour')

>>> df
                    a                   b          c
0 2018-09-11 11:31:09 2018-09-10 10:30:38  25.008611
1 2018-09-14 13:25:14 2018-09-14 11:05:38   2.326667


text:
Q: What does vertexId mean in flink? I saw the rest api of flink uses vertexid a lot of places. What does it mean and how can I get it?

A: Vertices mean in this case basically the subtasks of the given task. You can get them from WebUI if you click on Task Metrics You will be asked to select the subtask, if You click on the subtask you will basically see its name and ID. VertexId is marked in red on the picture:


text:
Q: How to check if a device is under Connecting state when connecting to wifi or mobile data? I am developing the android app which runs my web service at app startup. My app is basically the home app of the device. So that's mean that When user will reboot the device, My app will come in front of him.
So far that is great. But I have noticed it that on app start the device takes 5 to 10 seconds to get the internet connected. whereas my web service gets run before the internet is established thus throwing an error of "An error occurred please try again later."
What I Want: Though I am showing that message I am really not satisfied as I really do want to show the user a Message. That message should be "Device is connecting to the internet"
but unfortunately, I am unable to do so. I am using the following code
    public static boolean isNetworkAvailable(Context context) {
    ConnectivityManager connectivityManager
            = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting();
}

but it really indicates me if the net is connected or not.
So is not there the case where I can show a message like "Please wait device is connecting to the internet"
Or how can I get that device is restarted not the only app. ... Please help

A: Register a local (or Manifest-declared if you want) broadcast receiver in your activity (documentation here https://developer.android.com/guide/components/broadcasts), listening to connectivity changes, using this intent filter: IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION).
Then check if is the device has internet connection with the code you posted.
Remember to register your broadcast receiver inside onResume() method and to unregister it inside onPause() method

*

*From api 24 and above:

you can use registerDefaultNetworkCallback https://developer.android.com/reference/android/net/ConnectivityManager.html#registerDefaultNetworkCallback(android.net.ConnectivityManager.NetworkCallback)
The callback has a public method called "onAvailable" https://developer.android.com/reference/android/net/ConnectivityManager.NetworkCallback.html#onAvailable(android.net.Network) that is called when a new network is ready to be used.


text:
Q: Bootstrap navbar not opening or collapsing I'm looking for a collapsible navbar. I attempted it with the code below without any success.
The following is my code:
<!DOCTYPE html>

<title> Portfolio</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">

Portfolio Site
<button type="button" class="navbar-toggle" data-        toggle="collapse" data-target=".navigation"></button>

Home

About

Contact

A: You have missed ,
Toggle navigation

within your button tag. Also make sure to add correct bootstrap and Jquery CDNs

<title> Portfolio</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">

Portfolio Site
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navigation"></button>
        Toggle navigation

      </button>

Home

About

Contact


text:
Q: Why my app is not connected to the localhost server? currently I am working on login and register tutorial. I have followed the tutorial completely but it failed. My Php scripts are fine, they are connected to my localhost server. However, when I am running on my app, it does not work and not respond at all, please help me to check and see if there is any error. My manifest.xml has already written the code permission internet. My app just couldn't link up and show no respond.
this is my linking class, BackgroundTask.class
package com.example.lam.loginregistertest2;

import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;

import org.apache.http.HttpConnection;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

/**
 * Created by LAM on 3/8/2015.
 */
public class BackgroundTask extends AsyncTask<String,Void,String> {
Context ctx;

BackgroundTask(Context ctx) {
    this.ctx = ctx;

}

@Override
protected void onPreExecute() {
    super.onPreExecute();
}

@Override
protected String doInBackground(String... params) {
    String reg_url = "http://192.168.43.225/webapp/register.php";
    String login_url = "http://10.0.2.2/webapp.login.php";

    String method = params[0];
    if (method.equals("register"))
    {
String name = params[1];
        String age = params[2];
        String username = params[3];
        String password = params[4];

        try {
            URL url = new URL(reg_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            OutputStream OS = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS,"UTF-8"));
            String data = URLEncoder.encode("name","UTF-8") +"="+URLEncoder.encode(name,"UTF-8")+"&"+
                    URLEncoder.encode("age","UTF-8") +"="+URLEncoder.encode(age,"UTF-8")+"&"+
                    URLEncoder.encode("username","UTF-8") +"="+URLEncoder.encode(username,"UTF-8")+"&"+
                    URLEncoder.encode("password","UTF-8") +"="+URLEncoder.encode(password,"UTF-8");
            bufferedWriter.write(data);
            bufferedWriter.flush();
            bufferedWriter.close();
            OS.close();
            InputStream IS = httpURLConnection.getInputStream();
            IS.close();
            return "Registration Success...";
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
         catch (IOException e) {
            e.printStackTrace();
        }

    }

        return null;
}

@Override
protected void onProgressUpdate(Void... values) {

    super.onProgressUpdate(values);
}

@Override
protected void onPostExecute(String result) {
    Toast.makeText(ctx,result,Toast.LENGTH_LONG).show();
}

}

register.php
<?php

require "init.php";
$name = isset ($_POST["name"]) ? $_POST["name"] : "";
$age = isset ($_POST["age"]) ? $_POST["age"] : "";
$username = isset ($_POST["username"]) ? $_POST["username"] : "";
$password = isset ($_POST["password"]) ? $_POST["password"] : "";

$sql_query = "insert into user values('$name','$age','$username','$password');";

if (mysqli_query($con,$sql_query)){
//echo "
Data Insertion Success...
";
}else{
//echo "Data insertion error..".mysqli_error($con);
}
?>

init.php
<?php
$db_name = "test";
$mysql_user = "root";
$mysql_pass = "cheehong";
$server_name = "localhost";

$con = mysqli_connect($server_name,$mysql_user,$mysql_pass,$db_name);
if(!$con){
//echo "Connection Error...".mysql_connect_error();

}else{
//echo "
Database Connection Successful...
";
}
?>

login.php
<?php
require "init.php";
$username = "ivan";
$password = "12";

$sql_query = "select name from user where username like '$username' and   password like '$password';";
$result = mysqli_query ($con,$sql_query);
if(mysqli_num_rows($result)>0){
$row = mysqli_fetch_assoc($result);
$name = $row["name"];
echo "
Hello welcome".$name."
";
}else{
echo "No info is available.";
}
?>

Register.class
package com.example.lam.loginregistertest2;

import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;

public class Register extends Activity {
EditText ET_NAME, ET_USER_NAME,ET_USER_PASS,ET_AGE;
String name,age, username,password;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register);
    ET_NAME = (EditText)findViewById(R.id.name);
    ET_AGE = (EditText)findViewById(R.id.age);
    ET_USER_NAME = (EditText)findViewById(R.id.new_user_name);
    ET_USER_PASS = (EditText)findViewById(R.id.new_user_pass);

  }

public void userReg(View view)
{
name = ET_NAME.getText().toString();
age = ET_AGE.getText().toString();
username = ET_USER_NAME.getText().toString();
password = ET_USER_PASS.getText().toString();
String method = "register";
BackgroundTask backgroundTask = new BackgroundTask(this);
backgroundTask.execute(method,name,age,username,password);
finish();
}
}

A: Check the urls that you are using
String reg_url = "http://192.168.43.225/webapp/register.php";
String login_url = "http://10.0.2.2/webapp.login.php";

both are different

A: Are you sure if your server and  device is within the same network? If not make it sure the server is reachable by device.


text:
Q: Select only one item from owned collection (EF core) Imagine that we have entity with owned collection and we want to select only one item from there by some condition. Is there any way to do it or I must load all collection?
Example:
class A {
    public ICollection<B> Bs {get; set;}
}

class B {
    public int SomeValue {get; set;}
}

And we want to get object with SomeValue == 2

A: You have to use the entire collection because you want to check a particular condition. Any one item from the collection can match the condition that why we have to traverse the entire collection.
By the way, you can use LINQ to perform a conditional operation to make code more readable.
B.Where(condition)

A: Bs.Where(t=>t.SomeValue == 2).First()


text:
Q: Do I need the package plasma-workspace on 18.04 with GNOME? I have Ubuntu 18.04 with GNOME. Do I need the package plasma-workspace or can I remove it?

A: You don't need the package plasma-workspace in Ubuntu 18.04 and you can safely remove it with sudo apt remove plasma-workspace if you haven't installed any packages that have plasma-workspace as a dependency.
Here are the reverse dependencies of plasma-workspace  in Ubuntu 18.04.
$ apt-cache rdepends plasma-workspace
plasma-workspace
Reverse Depends:
  plasma-workspace-dev
  sddm-theme-breeze
  plasma-workspace-wayland
  plasma-widgets-addons
  plasma-desktop-data
  plasma-desktop
  libkscreenlocker5
  kinfocenter
  kde-config-screenlocker
  drkonqi
  libkf5xmlrpcclient-data
  plasma-mediacenter
  openbox-kde-session
  libkf5globalaccel-data
  libkf5globalaccel-bin
  latte-dock
  kde-plasma-desktop
  kubuntu-web-shortcuts
  kubuntu-full
  kubuntu-desktop
The following command will show if any of these packages are currently installed.
apt policy plasma-workspace-dev sddm-theme-breeze plasma-workspace-wayland plasma-widgets-addons plasma-desktop-data plasma-desktop libkscreenlocker5 kinfocenter kde-config-screenlocker drkonqi libkf5xmlrpcclient-data plasma-mediacenter openbox-kde-session libkf5globalaccel-data libkf5globalaccel-bin latte-dock kde-plasma-desktop kubuntu-web-shortcuts kubuntu-full kubuntu-desktop


text:
Q: bazel build wildcards with suffix I have some bazel rules like so:
//a/b/c:foo_x
//a/b/c:foo_y
//a/b/d:bar_x
//a/b/d:bar_y
//a/b/e/f/g:qux_x
//a/b/e/f/g:qux_y

Is there a way to say I want to build all rules with the "_x" suffix? I know that Bazel supports wildcards such as //a/... but I would like greater control over what exactly I am building.

A: Use a combination of query and grep.
$ bazel build $(bazel query //a/b/... | grep -E ":.+_x")


text:
Q: Plotly world Choropleth Map offline in python? I'm trying to recreate the world Choropleth map given in plotlys example page here:  https://plot.ly/python/choropleth-maps/ with the intention of reusing some of the code, but changing the column which informs the shadings and the labelling.
However when I run the exact code given in the example I receive the following error.

plotly.exceptions.PlotlyError: Because you didn't supply a 'file_id' in the call, we're assuming you're trying to snag a figure from a url. You supplied the url, '', we expected it to start with 'https://plot.ly'.
  Run help on this function for more information.

I have no idea where this error arises from and my question really is how do I adapt the code so that it produces the said figure offline? Secondly is there a simple method for saving the figure directly to a png? Apologies if this is trivial I'm completely new to the package.
Here is the code:
import plotly.plotly as py
import pandas as pd

df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_world_gdp_with_codes.csv')
data = [dict(
    type='choropleth',
    locations=df['CODE'],
    z=df['GDP (BILLIONS)'],
    text=df['COUNTRY'],
    colorscale=[[0, "rgb(5, 10, 172)"], [0.35, "rgb(40, 60, 190)"], [0.5, "rgb(70, 100, 245)"],\
                [0.6, "rgb(90, 120, 245)"], [0.7, "rgb(106, 137, 247)"], [1, "rgb(220, 220, 220)"]],
    autocolorscale=False,
    reversescale=True,
    marker=dict(
        line=dict(
            color='rgb(180,180,180)',
            width=0.5
        )),
    colorbar=dict(
        autotick=False,
        tickprefix='$',
        title='GDP
Billions US$'),
)]

layout = dict(
    title='2014 Global GDP
Source:\
            \
            CIA World Factbook',
    geo=dict(
        showframe=False,
        showcoastlines=False,
        projection=dict(
            type='Mercator'
        )
    )
)

fig = dict(data=data, layout=layout)
py.iplot(fig,validate=False, filename='d3-world-map')

A: You need to import the offline specific functions, which allow you to plot inline in a jupyter notebook:
import plotly.figure_factory as ff
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
init_notebook_mode(connected=True)

# All of your code
# ....

# Just change the last line from py.iplot to iplot
iplot(fig,validate=False, filename='d3-world-map')

This renders the image inline in a jupyter notebook, and there's a button that allows you to Download plot as a png in the upper right, along with other functionality.

If you need to save the image as a png, you can try changing the last line to:
plot(fig, validate=False, filename='d3-world-map.html', image='png')

This actually creates an .html file and will open a browser. You can then manually save this as a .png. The last step can be automated with other libraries like selenium, but not sure there is a simple way around it given their documentation:

Note that you must generate the graph and open the file to save the
  image.


text:
Q: Sequence generating in for loop php I'm not able to solve issue with the for loop in php.
Numbers that I should output are:
10, 8, 11, 3, 9, 7, 10, 2, 8
$n = 10;
for ($i = 0; $i < 10; $i++) {
     if ($i == 0){
       $n = $n - 2;
     } else if ($i == 1) {
       $n = $n + 3;
     } else if ($i == 2) {
       $n = $n - 8;
     } else if ($i == 3) {
       $n = $n + 6;
     }
}

That is wrong way and I know that, but I'm not sure how to do proceed here, so when the $i = 4 it calculation should be the same as for $i = 0 and so on...
Any ideas?
EDIT:
first number in the sequence is 10
second: 10 - 2 = 8
third: 8 + 3 = 11
forth: 11 - 8 = 3
fifth: 3 + 6 = 9

then repeat -2, +3, -8, +6 and so on...

A: The modulus operator (%) is the best approach for this - each run through the loop will increase the modulus by 1 until it loops back round to zero again for as many iterations as required.
<?php
$number = 10;
$iterations = 10;

for ($i=0; $i<$iterations; $i++) {
  echo $number, PHP_EOL;
  switch ($i % 4) {
    case 0:
      $number -= 2;
      break;
    case 1:
      $number += 3;
      break;
    case 2:
      $number -= 8;
      break;
    case 3:
      $number += 6;
      break;
  }
}

=
10
8
11
3
9
7
10
2
8
6

See: https://eval.in/620557


text:
Q: deprecated notification.setLatestEventInfo I have problem with setLatestEventInfo i can't change it to new version .
please help me to rewrite new code.
    private void showNotification(int moodId, int textId) {
    CharSequence text = getText(textId);
    Notification notification = new Notification(R.drawable.icon,  getText(R.string.notify_message_started), System.currentTimeMillis());
    notification.setLatestEventInfo(this, getText(R.string.notify_message_running_headline), getText(R.string.notify_message_running_text),
            PendingIntent.getActivity(this, 0, new Intent(this, AudioMonitor.class).setFlags(603979776), 0));

    notification.flags |= 2;
   this.mNM.notify(MOOD_NOTIFICATIONS, notification);

}

I want can use flag for this line " notification.flags |= 2" in new level api.
I am new beginner android

A: You can perform a check for API level and then use the latest version
final int sdkVersion = Integer.parseInt(Build.VERSION.SDK);

if (sdkVersion < Build.VERSION_CODES.HONEYCOMB)
 {
   // Deprecated in API level 11
     CharSequence text = getText(textId);
     Notification notification = new Notification(R.drawable.icon,
     getText(R.string.notify_message_started), System.currentTimeMillis());
     notification.setLatestEventInfo(this, getText(R.string.notify_message_running_headline), getText(R.string.notify_message_running_text),
        PendingIntent.getActivity(this, 0, new Intent(this, AudioMonitor.class).setFlags(603979776), 0));

     notification.flags |= 2;
     this.mNM.notify(MOOD_NOTIFICATIONS, notification);

 }
 else
 {
 // available from API level 11 and onwards
 final Intent notificationIntent = new Intent(this, AudioMonitor.class);
 notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
 Intent.FLAG_ACTIVITY_SINGLE_TOP);
 PendingIntent contentIntent = PendingIntent.getActivity(myContext, 0, notificationIntent, 0);

 Notification notification = new Notification.Builder(mContext)
     .setContentTitle(getText(R.string.notify_message_running_headline))
     .setContentText(getText(R.string.notify_message_running_text))
     .setContentIntent(contentIntent);
     .setWhen(System.currentTimeMillis())
     .setOngoing(true)
     .setSmallIcon(R.drawable.icon)
     .setLargeIcon(R.drawable.icon)
     .build();
  NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    notificationManager.notify(MOOD_NOTIFICATIONS, notification);
 }


text:
Q: Viewport fit screen width and big images I'm trying to use a WebView for displaying a big image with the built-in multitouch and trying to avoid memory crashes.
I set the webView this way:
    setInitialScale(20);
    WebSettings settings = getSettings();
    settings.setJavaScriptEnabled(true);
    settings.setUseWideViewPort(true);
    settings.setLoadWithOverviewMode(true);
    settings.setSupportZoom(true);
    settings.setBuiltInZoomControls(true);

And then load the following code:

<meta
    name="viewport"
    content="width=device-width, user-scalable=yes"
/>

The problem is that if it loads a medium image (1600x1200 for example) it works nice and the image fits the screen width.

But if the image is bigger 7300x5200 in my example, it appears like zoomed in and with the zoom out disabled.

If you want to test the images urls are:
img1 &
img2
NOTE: I'm not the owner of that images and I'm only using it for testing

A: I think your images still end up larger than the viewport by default. Try this

<meta
    name="viewport"
    content="width=device-width, user-scalable=yes"
/>

A: Don't know the correct answer but a possible walkarround could be set the img max-width to a "non-very high value" for example 2*screen.width when the page is loaded

A: I've actually got this working on ICS by doing something a little counter-intuitive. While others are suggesting adding style="width:100%" to the img tag, my solution is to actually add style="height:100%" instead.
This works for me on my Android 4.0+ devices, but unfortunately it starts partially zoomed in (so the image height fills the view) on my older devices.

*

*It avoids the white space problem on all devices I tested.

*

*ICS shows space on initial fully-zoomed out view, but as you zoom in, it disappears exactly as you want.

*On older devices, there is never white space below, due to the initial zoom level.

*The zoom is not perfect, but much better.

*

*On ICS, you get exactly what you want (match the width).

*On older devices, the zoom is significantly more manageable than what you're getting in your second example in the question.

In short, I've met your requirements on ICS and gotten you much closer to them on older devices.  I'll edit my answer if I come up with anything else, but this seems worth sharing at this point, even if imperfect.

A: How about this: (retracted - still doesn't work right)

<meta
    name="viewport"
    content="width=device-width, user-scalable=yes"
/>

A: I'm more off a web developper, here is the code that works on android ics browser, this should work the same in a webview :
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="user-scalable=yes, initial-scale=1.0, width=device-width">

I tried it as well which a much biger image (http://macjacart.ca/admin/Product_Images/8UhBphVEae.jpg) and it worked smoothly.
Hope it helps!
[EDIT]
Since I have not enough room to post it in the comments, I'll put it there :
What you want is basically to cut off the bottom of the viewport as soon as your image height takes the full screen. You need some javascript to do that, and since the javascript does not have a zoom event, it's not going to require some hacks. Since android support flash, you could try this solution to get a zoom event. As soon as the zoom reach a certain level, which depends on image ratio, you update the css of your image with a height:100%, and set width to auto.
You can basically constrain width or height depending on which one is 100%.
You might also want to set the height progressivelly to 100% as the user is zooming, either way you are going to see a "jump" at some point.
Take a look at this post as well, this might help you.


text:
Q: Where does the magic column "name" come from? I got this by accident:
db=> select name from site;
ERROR:  column "name" does not exist
LINE 1: select name from site;
               ^
db=> select site.name from site;
     name
---------------
 (1,mysitename)
(1 row)

The second query return a tuple containing a whole row. Using postgres 9.0.1.
Edit: the definition of site by request. I doesn't really matter, this quirk works for any table.
db=> \d site
                         Table "public.site"
 Column |  Type   |                     Modifiers
--------+---------+---------------------------------------------------
 id     | integer | not null default nextval('site_id_seq'::regclass)
 title  | text    | not null

A: Also note that the implicit cast to name was removed in PostgreSQL 8.3, which means this behavior no longer works.  It is virtually impossible to accidently get this behavior in PostgreSQL 8.3 and higher because tuples don't automatically convert to text.
So in 9.1:
or_examples=# select c.name from comp_table_test c;
ERROR:  column c.name does not exist
LINE 1: select c.name from comp_table_test c;

but to get that behavior we have to:
or_examples=# select name(c::text) from comp_table_test c;

Or we could define our own name function taking in type comp_table_test and returning whatever we'd like.

A: NAME is actually a function. It's a quirk of Postgres that a function with one argument e.g. function(arg) can also be called as arg.function. From the docs:

The equivalence between functional
  notation and attribute notation makes
  it possible to use functions on
  composite types to emulate "computed
  fields".

NAME is an internal type for object names, and this function is casting its argument to that type and returning it.

A: "name" is a reserved key word. So you should "quote" the keyword to use it:
SELECT "name" FROM site;

This has resolved some of these issues for me in the past, altough the code you posted should also work without quoting. On the other hand
select site.name from site;

word because you are explicitly using the schema to resolve the name of the column