text:
Q: how do I put a gnome-terminal icon on the desktop? How do I put a gnome-terminal icon on the desktop?  I already have one on the upper "panel" (ie: the strip across the top) but I need multiple ones on the desktop (so that I can customize with the --working-directory option).
I know this is possible because I already have some on the desktop.
Edit: Apparently, copying an existing one works.  However, I don't recommend this because after you copy it you will likely right click it and edit some properties to get it to do what you want it to do.  Then if you use the console to view the ~/Desktop folder, you will see that your property edits do not get reflected in the name of the executable file that implements the gnome-terminal.  The file system name will be an automatically generated name that is something like "original name (copy).desktop".  It's a little ugly that the name doesn't match your properties.

A: Right click -> Create launcher
Name:     Terminal
Command : gnome-terminal

A: I'm pretty sure you can just drag it feom the upper panel on to the desktop.  From there you can edit the properties and add your working-directory.


text:
Q: Using git as a backend storage system New to git here...
I want to commit my personal file share to a git repo (text, docs, images etc).
As I make modifications to various files over time, telling git about them along the way, how do go about things so I can:

*

*Get out of the business of traditional fulls/incrementals.

*Be able to do a point-in-time file or full clone restore.

Basically, I want something granular, such that, if I make an edit to a file 5 times on a particular day. I will have 5 versions of that file that I can refer back to- forever. Or even just derive the a full copy of everything the way it looked on that particular day.
I am currently using rsync for remote incremental syncs (no file versioning).

A: To initialize the process, you can simply:
git init .
git add -A
git commit -m "initiali state of my documents"

in the directory where all your documents are.
Then use one of Chris Jhonsen's suggestions to commit on each saves.
Once you want to save your all history and export it elsewhere, use git bundle.
(and copy only one file around, anywhere you want)
As for extracting from that big bundle the exact state of a repo at a certain date, you would use the Specifying Revisions section of git rev-parse

A ref followed by the suffix @ with a date specification enclosed in a brace pair
  (e.g. {yesterday}, {1 month 2 weeks 3 days 1 hour 1 second ago} or {1979-02-26 18:30:00}) to specify the value of the ref at a prior point in time.
  This suffix may only be used immediately following a ref name and the ref must have an existing log ($GIT_DIR/logs/<ref>).
  Note that this looks up the state of your local ref at a given time; e.g., what was in your local master branch last week.
  If you want to look at commits made during certain times, see --since and --until.

A: So to answer your question in full would take a tutorial.  In summary though, git should make a decent solution for this.
You'll want to set up a git server somewhere and create a repository there and create a local clone of it.  Then you can add all your files and push them to the server.
One nice things is you can do local commits without worrying about the server and then later, when it's time to backup, you do a push.
If I was going to do this, I would be worried about disk usage, but the git repository I use has a ton of history, so maybe I'm overly concerned about that for your usage.

redpajama_set_name: RedPajamaStackExchange


text:
Q: fullpage carousel with hammer.js I'm trying to adapt the example at https://rawgit.com/hammerjs/hammer.js/master/tests/manual/nested.html to allow for fullpage panning, however I am not sure how to account for browser resizing and dynamically adding/removing panes.
I've tried resetting the carousel on resize as well as on changes to the DOM.
However, in both cases, if I reinitialize the carousel, it gets reset back to index 0. Any suggestions?
$( window ).resize(function() {
  outer = new HammerCarousel(document.querySelector(".panes.wrapper"),      Hammer.DIRECTION_HORIZONTAL);
});

I have a fiddle at https://jsfiddle.net/afroz/0jq5ynq8/1/

A: I was able to get this working by setting an environment variable to the current index and then modifying the carousel function to read that instead of using the default index of 0.
I've modified the fiddle with the fixes.


text:
Q: How to show a list of information on the fly in a razor component I have a database and a lot of entries in a table. I want to show those entries on a webpage, using blazor.
I have tried loading the entries using context.tableName.Load() and context.tableName.Local and iterating through the entries using
@foreach(var entry in localList){
    <p>@entry.Name</p>
}

That works fine.. but it first loads all the data from the database and when it finally has finished, it starts rendering the page/results.
I want to show the results that have been loaded immediately, popping up responsive on the webpage as the loading continues. Any ideas how I would implement that?
Thanks!

A: What you describe matches what IAsyncEnumerable<> does.
Just for fun I adapted the standard starter app a little:
In WeatherForecastService :
public async IAsyncEnumerable<WeatherForecast> GetForecastAsync(DateTime startDate)
{
    var rng = new Random();

    for (int i = 0; i < 77; i++)
    {
        yield return new WeatherForecast
        {
            Date = startDate.AddDays(i),
            TemperatureC = rng.Next(-20, 55),
            Summary = Summaries[rng.Next(Summaries.Length)]
        };
        await Task.Delay(100);
    }
}

and in the FetchData.razor page:
List<WeatherForecast> forecasts = new List<WeatherForecast>();

protected override async Task OnInitializedAsync()
{
    await foreach (var forecast in ForecastService.GetForecastAsync(DateTime.Now))
    {
        forecasts.Add(forecast);
        StateHasChanged();
    }
}

be aware that this is not a very efficent way of moving data but it might work for some scenarios.


text:
Q: Using EventHandler with Entity Framework: A second operation started on this context before a previous asynchronous operation completed I am trying to update my database based on some events. Whenever A is generating an event, B will execute a DB update. I keep getting the following exception:
"A second operation started on this context before a previous asynchronous operation completed. Use await to ensure that any asynchronous operations have completed before calling another method on this context. Any instance members are not guaranteed to be thread safe."
I understand the exception but I don't know where is it coming from and if it's related to using EventHandler.
After long searches:

*

*I made sure everything has await to make sure there is no parallel calls with the dbcontext

*I made sure I only have ONE event subscribed (this was an advice from other stackoverflow questions)

*I subscribed the event with async/await

*I tried Task.WaitAll() in all possible combinations

class A {
    public event EventHandler<LogArgs> LogEvent;

    public void WorkInA() {
        .....
        this.SendLogEvent();
        .....
        this.SendLogEvent();
        .....
    }

    private void SendLogEvent() {
        this.LogEvent(this, args);
    }

}

class B {
    private A a;

    public async void Init() {
        //Before: a.LogEvent += LogEventToDB;
        a.LogEvent += async (s, e) => await LogEventToDB(s, e);

    }

    public void DoWork() {
        .....
        a.WorkInA();
        .....
    }

    private async Task LogEventToDB(object sender, LogMessageEventArgs e) {
        .....
        await this.unitOfWork.SaveAsync();
        .....
    }
}

//Inside unitOfWork
public async Task SaveAsync()
{
       await this.context.SaveChangesAsync();
}

I would like to know what causes this issue and if it's possible to fix it.

A: Yes, your problem is due to event handling. More specifically, it's due to async void. Both of the lines of code below fall into the async void trap:
//Before: a.LogEvent += LogEventToDB;
a.LogEvent += async (s, e) => await LogEventToDB(s, e);

One of the problems with async void is that the calling code cannot know when it has completed.
If you really want to use events for log messages (which seems a bit odd to me), then you must have the events just add the log message into a queue (synchronously), and have a separate "worker" pulling messages out of the queue and sending them to the database (asynchronously).


text:
Q: Oracle not use extra indexes when there's an ORDER BY I'm playing with Oracle 12 and indexes...
In a query like this:
SELECT a, b, c FROM table WHERE col1 = val1 AND col2 = val2 ORDER BY id DESC

(where id is the primary key of the table), Oracle always uses the index on the primary key.
So even if I create an index on the columns col1 and col2, since there's the ORDER BY statement, it doesn't use the index.
So can I infer that this is a general rule? Should I never put extra indexes in case all my queries contains "ORDER BY ID" ?
Here is my table structure:
ID                  NUMBER GENERATED ALWAYS AS IDENTITY NOCACHE ORDER,
USERNAME            VARCHAR2(30 CHAR)
TYPE_A              CHAR(1 BYTE)
TYPE_B              CHAR(1 BYTE)
CREATED             DATE
UPDATED             DATE

ALTER TABLE my_table
    ADD CONSTRAINT my_table_pk
    PRIMARY KEY (ID)
    USING INDEX TABLESPACE XXX;

On the table I perform only this query:
SELECT id, USERNAME, TYPE_A, TYPE_B, CREATED FROM table
where username = 'MYUSER'
AND created >= TO_DATE('2016-01-01','YYYY-MM-DD')
AND created <= TO_DATE('2016-06-30','YYYY-MM-DD')
AND TYPE_A = 1
order by ID desc;

One index: on pk (ID) (automatically created by oracle)
-------------------------------------------------------------------------------------------------------
| Id  | Operation                   | Name                    | Rows  | Bytes | Cost (%CPU)| Time     |
-------------------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT            |                         |     2 |   384 |     1   (0)| 00:00:01 |
|*  1 |  TABLE ACCESS BY INDEX ROWID| table                   |     2 |   384 |     1   (0)| 00:00:01 |
|   2 |   INDEX FULL SCAN DESCENDING| INDEX_PK                |    10 |       |     1   (0)| 00:00:01 |
-------------------------------------------------------------------------------------------------------

Two indexes: first on pk and second on (USERNAME, CREATED, TYPE_A)
-------------------------------------------------------------------------------------------------------
| Id  | Operation                   | Name                    | Rows  | Bytes | Cost (%CPU)| Time     |
-------------------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT            |                         |     2 |   384 |     1   (0)| 00:00:01 |
|*  1 |  TABLE ACCESS BY INDEX ROWID| table                   |     2 |   384 |     1   (0)| 00:00:01 |
|   2 |   INDEX FULL SCAN DESCENDING| INDEX_PK                |    10 |       |     1   (0)| 00:00:01 |
-------------------------------------------------------------------------------------------------------

So the second index seems to be useless.
By the way If i remove the ORDER BY statement, Oracle uses the second index on USERNAME, CREATED, TYPE_A.
Thanks all!

A: Well, in short answer - no, but we can't give you a general rule, because every time will be different as to a lot of different variable. For more specific answer you should include an explain plan of this query, and we'll have a better picture on why it doesn't use the index.
Oracle will know to use this index as long as ID column will be specified first .
You shouldn't add unnecessary indexes for selects that will only occur once in a lot of time or those that are slow, but not too slow. You should only add indexes related to the most common selects/updates that occurs on this table.
If a select with filters on col1 and col2 is repeatedly , then most likely(again, I don't know what other processes you are doing on this table) an index on all 3 columns will be better :
(ID,Col1,Col2)

A: Let me just give you a counterexample which shows that there are cases where Oracle will use the second index.
SQL> create table tab (
  2  ID          NUMBER GENERATED ALWAYS AS IDENTITY NOCACHE ORDER,
  3  USERNAME        VARCHAR2(30 CHAR),
  4  TYPE_A      CHAR(1 BYTE),
  5  TYPE_B      CHAR(1 BYTE),
  6  CREATED         DATE,
  7  UPDATED         DATE
  8  )
  9  /

Table created.

SQL> alter table tab add constraint tab_pk primary key (id) using index
  2  /

Table altered.

SQL> create index SECOND_IDX on tab(username, created, type_a)
  2  /

Index created.

SQL> insert into tab(username, type_a, type_b, created)
  2  select 'OTHER_USER', '2', '2', date '2015-06-01'
  3  from all_objects, all_objects where rownum <= 1e5;

100000 rows created.

SQL>
SQL> update tab
  2  set username = 'MYUSER',
  3      created = DATE '2016-06-01',
  4      type_a = '1'
  5   where id = 50000;

1 row updated.

SQL> commit;

Commit complete.

SQL> begin
  2     dbms_stats.gather_table_stats(ownname => USER,
  3        tabname => 'TAB',
  4        estimate_percent => 100,
  5        method_opt => 'FOR ALL INDEXED COLUMNS'
  6     );
  7  end;
  8  /

PL/SQL procedure successfully completed.

SQL>
SQL> set autotrace traceonly exp
SQL>
SQL> SELECT id, USERNAME, TYPE_A, TYPE_B, CREATED FROM tab
  2  where username = 'MYUSER'
  3  AND created >= TO_DATE('2016-01-01','YYYY-MM-DD')
  4  AND created <= TO_DATE('2016-06-30','YYYY-MM-DD')
  5  AND TYPE_A = '1'
  6  order by ID desc;

Execution Plan
----------------------------------------------------------
Plan hash value: 3658386757

---------------------------------------------------------------------------------------------------
| Id  | Operation                            | Name       | Rows  | Bytes | Cost (%CPU)| Time     |
---------------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT                     |            |     1 |    29 |     5  (20)| 00:00:01 |
|   1 |  SORT ORDER BY                       |            |     1 |    29 |     5  (20)| 00:00:01 |
|   2 |   TABLE ACCESS BY INDEX ROWID BATCHED| TAB        |     1 |    29 |     4   (0)| 00:00:01 |
|*  3 |    INDEX RANGE SCAN                  | SECOND_IDX |     1 |       |     3   (0)| 00:00:01 |
---------------------------------------------------------------------------------------------------

In this case the reason to use the second index is the extremely high selectivity (one row out of 100000).


text:
Q: Issues reading file content from a directory within a Jar I found a lot of answers to this on SO but somehow am not able to integrate it with my code.
I have a jar which after opening a JarConnection and finding the Path for it looks like:
/Users/xyz/WTMS/target/WTMS.jar

I have a directory whose name is known to me as vega-config-templates with unknown files names under it like:
anonymous1.txt
anonymous2.txt
anonymous3.txt
.
.
.

Code:
URL url = getClass().getClassLoader().getResource(directoryPath);
List<String> arrayList = new ArrayList<>();
    final Enumeration<JarEntry> entries = jarFile.entries();
    while (entries.hasMoreElements()) {
        final JarEntry entry = entries.nextElement();
        final String entryName = entry.getName();

        System.out.println("Entry name "+entryName);
        if (entryName.startsWith("/vega-config-templates")) {
            arrayList.add(entryName.replace('/', File.separatorChar));
        }
    }
}

With this code I am able to access the top level directory as a Jar Entry with name "vega-config-templates" but over this i want to do something like :
FileUtils.listFiles(directory, null, true)

then I want to get the content of these Collection<Files> , files, on the go, which I am not able to do with JarEntry as it not drilling down the top level directories.
Neither can I apply traditional file traversals over these URIs to open this directory and then iterate over it as a simple File directory = new File(jarUri+"/vega-config-templates");
How do i dynamically iterate over the files and get file objects so i can extract the content over each one of them , all under a known directory within a jar.


text:
Q: Accepted answers count on top users page I like the top users feature. It brings out my competitive spirit.
The one thing that bugs me about it is that as far as I can see, it is not affected at all by the number of accepted answers. It would be nice if this was included in some way. Even if it was just another column by the number of questions answered and up votes.
Edit
It may help people judge someone's ability in a tag. If there are two people with similar numbers of questions and upvotes one may have written something on a popular question, and a load of tosh on numerous others. The other may have spent time answering in detail other non popular questions and being accepted. Especially with the CV thingy it may be important to note such differences

A: They could use it for a third parameter sort, so votes-answers-accepted.

A: I'd quite like to see this done too, both on a 30-day and all-time basis. It's all about ego-stoking! :-)
While yes, I know that there's always a possibility that someone could have a lot of accepted answers while the community disagrees that they are valuable, that actually seems to be pretty rare. (Anecdotally) it's uncommon that a question is accepted and not the most highly-scored answer, and rarer still that it isn't the next most highly scored when not "best". The cases where it happens seem to be where someone that many people rate very highly – a "rockstar programmer" – makes a point that is generally OK, but which isn't actually an answer to the question; there appears to be a few sub-communities of SO where this sometimes happens, but thankfully it's rare. Ultimately we should all be here to answer the questions that are asked, not to grandstand.

A: I fully agree on this one. For example, on node.js I have 21 accepted answers, but just 18 upvotes. Mainly because I am answering the obscure questions; which leads to a very low upvotes/questions percentage.

A: Coming at this from the "specialist" badge point of view:

*

*Counting an acceptance towards your in-tag vote count would give the question asker two effective votes. Now, askers are often the people least able to judge the quality of an answer, so it would not do to give them more leverage towards determining who the "experts" are.


text:
Q: Inconsistency with arrays #include <iostream>

using namespace std;

int grade(char [][5], int);

int main()
{
    int tests, i,j;
    cout << "How many tests?"; cin >> tests;
    char answers[tests][5];
    cout << "What were the answers for all the tests (T/F)?";
    for (i=0;i<tests;i++)
        for (j=0;j<5;j++) cin >> answers[i][j];;
    int g[tests] = {grade(answers, tests)};

    for (i=1;i<=tests;i++)
    {
        cout << "\n   Test " << i << ": ";
        cout << g[i-1] << " out of 25";
    }
    cout << endl;

    return 0;
}

int grade(char ans[][5], int test)
{
    int k, l;
    int gr[test]={0};
    char sheet[5] = {'T', 'T', 'F', 'F', 'T'}; cout << sheet[1];
    for (k=0;k<test;k++)
            for (l=0;l<5;l++)
                    if (ans[k][l]==sheet[l]) gr[k]+= 5;;;

    return *gr;
}

I can't figure out why my program is so inconsistent. If I input T T F F T for the first test, everything turns out fine, but if I have any "wrong answers" for the first test, the values of my g array seem to always be 0.
Any ideas? Thanks!

A: Here's the problem. The return value of the function returns a single number, and then assigns that single number to all values of the array. So, whatever the first test's grade was, all grades read the same.
The {} after an array sets the initial values for the array, and only having one value in that makes that value be assigned to all parts of the array.
My compiler doesn't like your syntax of int g[tests], as it expects tests to be a constant, so I had to convert those dynamic array size declarations. The following code worked as expected for me on Visual Studio 2017. Try this.
#include <iostream>

using namespace std;

int* grade(char** ans, int test);

int main()
{
    int tests, i, j;
    cout << "How many tests?"; cin >> tests;

    char** answers = new char*[tests];
    for (int i=0;i<tests;i++)
        answers[i] = new char[5];

    cout << "What were the answers for all the tests (T/F)?";
    for (i = 0; i<tests; i++)
        for (j = 0; j<5; j++) cin >> answers[i][j];

    int* g = grade(answers, tests);

    for (i = 1; i <= tests; i++)
    {
        cout << "\n   Test " << i << ": ";
        cout << g[i - 1] << " out of 25";
    }
    cout << endl;

    for (int i = 0; i < tests; i++)
        delete[] answers[i];
    delete[] answers;
    delete[] g;

    system("pause");

    return 0;
}

int* grade(char** ans, int test)
{
    int k, l;
    int* gr = new int [test] {0};
    char sheet[5] = { 'T', 'T', 'F', 'F', 'T' };
    cout << sheet[1];
    for (k = 0; k<test; k++)
        for (l = 0; l<5; l++)
            if (ans[k][l] == sheet[l]) gr[k] += 5;;;

    return gr;
}


text:
Q: History of Algebraic Geometry: Motivation behind definition of schemes I am trying to read an article by Jean Dieudonne which talks about development of Algebraic Geometry. The article was being published in the journal "Advances in Mathematics" Volume 3, Issue 3, Pages 233-413 (July 1969). One can find the article from the link http://www.sciencedirect.com/science/journal/00018708/3/3
I quote from the article:

Thus we are led to associate with every variety $V$ a ring of finite type $A = K[X_1, \dots, X_n]/\mathfrak a$, where, for the sake of simplicity, we assume that the field $K$ is algebraically closed. Our problem is to establish a one-to-one correspondence between algebraic and geometric objects. Given a point $z\in V$, we associate with it the set of all functions on $V$ which vanish at $z$; this set is a maximal ideal in $A$. A subvariety $W$ of $V$ is defined by an ideal $\mathfrak b$ which contains $\mathfrak a$: the set of all functions on $V$ which vanish on $W$ forms an ideal in $A$, and we associate this ideal with the subvariety $W$.
In the opposite direction, given an algebraically closed field $K$ and a ring of finite type $A = K[X_1, \dots, X_n]/\mathfrak a$, we want to associate with it a variety $V$. By what precedes, it is natural to consider as the points of $V$ the elements of the maximal spectrum $\operatorname{Specm}(A)$ of $A$, i.e., the maximal ideals of $A$. This, however, will certainly not give a one-to-one correspondence between algebraic and geometric objects, since to any field $K$ there would correspond the variety consisting of one point. A way to correct this situation is again suggested by Riemann's approach who considered the rings $A_z$ formed by the functions on $V$ which have no poles at $z$. Thus we should take as elements of the geometric object we want to associate with the ring $A$, the pairs $(\mathfrak m, A_{\mathfrak m})$, where $\mathfrak m$ is a maximal ideal of $A$ and $A_{\mathfrak m}$ is the local ring at $\mathfrak m$. In this way, for different fields we obtain different pairs $(z, K)$.

I don't understand "This, however, will certainly not give a one-to-once correspondence between algebraic and geometric objects,since to any field $K$ there would correspond the variety consisting of one point." and whatever he says after that about considering the local ring at a maximal ideal.
Can someone please clarify.

A: I will clarify the part "A way to correct to this suggestion is again suggested by Riemann....." which is the only part left, as you point out in the comments above. $A$ is the ring of functions (coordinate ring) on $V$, and $A_z$ the localization of $A$ at $z\in V$ (if you don't know about localization: Atiyah-Macdonald); thus one is led to consider local rings (as he also points in the parts in the article below your quote). The point is that for a field $k$ you have only one maximal ideal and the localization at this maximal ideals is the field itself, so as he says for different fields we obtain different pairs. By the way these things are discussed in another way in Grothendieck's introduction to EGA (GRUNDLEHREN DER MATH. WISS. edition)

A: Well, any field $K$ has a unique maximal ideal, the zero ideal. Hence, the maximal spectrum (as a topological space!) $\mathrm{Specm}(K)$ doesn't suffice to reconstruct $K$. One needs to introduce the sheaf of regular functions on a variety. A space together with a sheaf of rings on it is called a ringed space. We may reconstruct any finitely generated integral commutative $k$-algebra $A$ from the ringed space $\mathrm{Specm}(A)$ (and more generally, but this is already scheme-land, any commutative ring $A$ from the ringed space $\mathrm{Spec}(A)$.) What is suggested in the text is to keep track of the stalks of the sheaf of regular functions. For $\mathrm{Specm}(A)$ these are the localization of $A$ at maximal ideals of $A$. This also suffices to reconstruct a field $K$, but for general commutative rings we need more than just the stalks.


text:
Q: Multithreaded Mail server I need to create a multuthreaded mail server on ubuntu 14.04. So i opted for Postfix which is default smtp server on ubuntu. but now I am stuck with multithreading in postfix. how can i perform multithreading in postfix? i came to know about multiple instance management in postfix (http://www.postfix.org/postmulti.1.html) but I am confused on how to perform multithreading.

A: Multi-instance is not equal changing the number of threads. The term multi-instance is used to have multiple distinct instances running.
If you wanna change the number of threads allowed to spawn for different subsystems of postfix, maybe have a look at the performance tuning?
http://www.postfix.org/TUNING_README.html#proc_limit


text:
Q: Command not working with subprocess.run but does work with subprocess.call I am trying to use subprocess.run with a custom argument, that works both directly from windows cmd, and from subprocess.call, but not with subprocess.run, as suggested by Running shell command and capturing the output.
This works:
    retcode = subprocess.call(build_command_line, shell=True)

This fails:
    result = subprocess.run([build_command_line], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

and outputs
The filename, directory name, or volume label syntax is incorrect.
Traceback (most recent call last):
  File "C:\Program Files\Python37\lib\subprocess.py", line 800, in __init__
    restore_signals, start_new_session)
  File "C:\Program Files\Python37\lib\subprocess.py", line 1207, in _execute_child
    startupinfo)
  File "C:\Program Files\JetBrains\PyCharm 2020.1.1\plugins\python\helpers\pydev\_pydev_bundle\pydev_monkey.py", line 551, in new_CreateProcess
    return getattr(_subprocess, original_name)(app_name, patch_arg_str_win(cmd_line), *args)
PermissionError: [WinError 5] Access is denied

even though I run with administrator.
Not that it should matter, but for completeness:
build_command_line is:
'"C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319\\MSBuild.exe" "C:\\code\\EPMD\\Kodex\\Solutions\\Kodex.All.sln" /t:REBUILD /p:Configuration=RELEASE'

How do I get it to work with subprocess.run?

A: Problem was my understanding of subprocess.run
correct call:
result = subprocess.run(build_command_line, stdout=subprocess.PIPE, stderr=subprocess.PIPE)


text:
Q: How to setup IMAP backend in Rails 5? I have a rails 5 application and I have stored emails in mysql database.
What I want to do:

*

*I want to setup an IMAP backend in my Rails 5 application

*So that, users can use android and desktop email client to connect to my rails app

*And sync emails from my database to their email app (like gmail app)

*

*I want a very lightweight solution

*If no solution is available, may be, I will build it myself.

So, any suggestion / tips / documentation / tutorial is highly appriciated.
Thanks.


text:
Q: Jupyter/Ipython notebook autosave during execution Is it possible to autosave the notebook while e kernel is running and a cell is being executed?
Everytime I execute a cell for a long time it stops autosaving and it starts saving again after the cell execution is finished.
Is this the default behavior?
Is there a way to change it?

A: Autosaving is always running on a timer, regardless of execution. However, the autosave event only fires if there are changes to save (indicated via a so-called 'dirty' flag). Output arriving sets that flag, which might be why you see autosave resuming once execution completes (more precisely, it should be when output arrives).
If you are making changes and autosave isn't happening, then there might be a bug in how the notebook tracks its dirty state.


text:
Q: Overriding object value in loop in scala im trying to write some generic test scenario builders for gatling and my problem is that I have a list of objects, and I want to iterate over it and do something with every object.
So i do like this
var counter = 0
   val scn = scenario("scenario")
      .repeat(requestsList.requests.size) {
        var tmp = requestLists.requests(counter)
                 ....
counter += 1
}

but when I printing tmp object it always show the first object from list and dosen't get second one. What im missing?

A: the gatling DSL creates immutable builders that are only executed once - so your looping / array indexing approach won't work
you'll have to use gatling's feeder constructs


text:
Q: Another Uncaught ReferenceError: google is not defined It must say something about Google Maps API that similar questions come up so often. But I've read all the previous ones, and couldn't find anything to solve my problem.
I have a Google Map working successfully (after a lot of pain and experimentation) on one website. There the map opens in a floatbox. Now I am trying to transfer it to another website where it will open in a div in the parent page. I've copied the code across, but am completely bogged down by "Uncaught ReferenceError: google is not defined" errors.
More specifically the Chrome console reports:
Uncaught ReferenceError: google is not defined
at eval (eval at <anonymous> (eval at <anonymous> (jquery.min.js:2)), <anonymous>:1:959)
at eval (eval at <anonymous> (jquery.min.js:2), <anonymous>:1:1)
at eval (<anonymous>)
at jquery.min.js:2
at Function.globalEval (jquery.min.js:2)
at text script (jquery.min.js:4)
at Xb (jquery.min.js:4)
at y (jquery.min.js:4)
at c (jquery.min.js:4)
at Object.send (jquery.min.js:4)

There is no jquery call in the map file so it presumably refers back to the parent page which does use jquery for various stuff, including opening the map with
$("#mapsee").click(function(){
     $("#mapsee").hide();
     $("#maphide").show();
     $("#mapspace").slideDown(2000, function() {
        $("#mapspace").load("/includes/map_hotel_dev.php?hid=<?php echo $row_hotel['hid'] ?>");
    });
    $('html, body').animate({
        scrollTop: $("#mapspace").offset().top
    }, 2000);
});

My Google Maps script on map_hotel_dev.php is
<script>
function initMap() {
var map;

  var image = {
      url: '../images/hotel_grey_icon.gif',
      size: new google.maps.Size(32, 37),
      origin: new google.maps.Point(0,0),
      anchor: new google.maps.Point(16, 35)
  };
  var hotelimage = {
      url: '../images/hotel_bigicon.gif',
      size: new google.maps.Size(32, 37),
      origin: new google.maps.Point(0,0),
      anchor: new google.maps.Point(16, 37)
      };

function createMarker(point, html) {
var timer;
var html;
var contentString = html;
        var ibOptions = {
         content: contentString
        ,closeBoxMargin: "-8px"
        ,disableAutoPan: true
        ,enableEventPropagation: false
        ,alignBottom: true
        ,pixelOffset: new google.maps.Size(-120, -36)
};
var ib = new InfoBox(ibOptions);

if(point.equals(thisLatlng)){
    var thisicon = hotelimage;
    var zed = 9999;
}else{
    var thisicon = image;
    var zed = Math.round(point.lat()*-100000)<<5
}
var marker = new google.maps.Marker({
    map: map,
    position: point,
    icon: thisicon,
    zIndex: zed
});

marker.addListener('mouseover', function() {
    timer = setTimeout(function(){
    ib.open(map, marker);
    }, 500);
});marker.addListener('mouseout', function() {
    clearTimeout(timer);
});
marker.addListener('click', function() {
    ib.open(map, marker);
});
google.maps.event.addListener(map, 'click', function() {
    ib.close(map, marker);
});

}

var lat = <?php echo $row_hotel['latitude'] ?>;
var lng = <?php echo $row_hotel['longitude'] ?>;
var zoom = 10;
var thisLatlng = new google.maps.LatLng(lat, lng);
var mapOptions = {
center: thisLatlng,
zoom: zoom,
mapTypeId: google.maps.MapTypeId.ROADMAP,
   streetViewControl: true,
   scaleControl: true,
   zoomControl: true
   }

map = new google.maps.Map(document.getElementById('mapCanvas'), mapOptions);

var style_nopoi = [{"featureType": "poi.business", "stylers": [{"visibility": "off"}]}]; // Styles, removes business points-of-interest. Lots of other possibilities.
map.setOptions({styles: style_nopoi});  // Applies the style to the map

var loadcnt = 0;
      google.maps.event.addListener(map, 'tilesloaded', function() {
        if (loadcnt==0) {
        map.setCenter(thisLatlng); // Seems to fix random centring problem on mobiles
        loadcnt=loadcnt+1;
        }
        });

downloadUrl("/includes/php-to-xml.php?iso=<?php echo $row_hotel['countryisocode'] ?>", function(doc) {
var xmlDoc = xmlParse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
    var lat = parseFloat(markers[i].getAttribute("lat"));
    var lng = parseFloat(markers[i].getAttribute("lng"));
    var point = new google.maps.LatLng(lat,lng);
    var html=markers[i].getAttribute("html");
    createMarker(point, html);
}

});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?v=quarterly&key=MYKEY&callback=initMap"></script>
<script type="text/javascript" src="../js/infobox.js"></script>

I've tried all manner of possible solutions: async loading, defer, putting the API and infobox scripts at the top of the page, and even transferring the API script to the parent page. Now I've just about run out of ideas.
A similar script using infowindow instead of infobox works fine. While testing I tried the old (infowindow) script with the addition of the infobox call and I immediately get the Uncaught ReferenceError so I suspect that is where the problem is in some way.

A: API is not getting loaded hence google undefined, can you remove the v=quarterly?
Use URL from documentation please
https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap

A: Well, I finally found the solution so for anyone else who comes along later, this is how I resolved it.
My mistake was to try to load a separate file (map_hotel_dev.php) into the div in the parent page. I copied the code from map_hotel_dev.php into the parent page and then changed to jquery to open the map to this:
$("#mapsee").click(function(){
     $("#mapsee").hide();
     $("#maphide").show();
     $("#mapspace").slideDown(2000, function() {
        initMap();
    });
    $('html, body').animate({
        scrollTop: $("#mapspace").offset().top
    }, 2000);
});

Now it all works a treat!


text:
Q: How to do a tile plot of a specialised plotting function from package I want to plot 4 of the following plots as an par(mfrow=c(2,2)) type arrangement.
install.packages("wavelets")
require(wavelets)
dat <- rnorm(100)
plot.modwt(modwt(dat)) #4 of these in a 2x2 grid is desired

However, layout and mfrow based attempts have not succeeded.
I will be giving the correct answer a bounty.

A: As @plannapus commented, the function plot.modwt already calls layout. So you will need to alter the original function.

*

*If you type plot.modwt in you R console, you will get the complete definition.

*Copy this function and save it as a new function, say, my.plot.modwt.

*Comment out the layout line in this function

*Set up your new layout. This worked for me:
nf = layout(matrix(c(3, 1, 4, 2, 7, 5,8, 6), 4, 2, byrow = TRUE),
     c(2,2), c(2,1, 2, 1), TRUE)
layout.show(nf)

*Call your function (4 times )to create plots:
my.plot.modwt(modwt(dat1))
my.plot.modwt(modwt(dat2))
my.plot.modwt(modwt(dat3))
my.plot.modwt(modwt(dat4))

Note, some other alterations to the layout will probably be needed.

My code:
y.plot.modwt = function (x, levels = NULL, draw.boundary = FALSE, type = "stack",
          col.plot = "black", col.boundary = "red", X.xtick.at = NULL,
          X.ytick.at = NULL, Stack.xtick.at = NULL, Stack.ytick.at = NULL,
          X.xlab = "t", y.rlabs = TRUE, plot.X = TRUE, plot.W = TRUE,
          plot.V = TRUE, ...)
{
  stackplot.modwt <- function(x, w.range, v.range, col.plot,
                              col.boundary, draw.boundary, X.xtick.at, X.ytick.at,
                              Stack.xtick.at, Stack.ytick.at, X.xlab = "t", plot.X = TRUE) {
    innerplot <- function(x, y, type = "l", xtick.at, ytick.at) {
      if (is.null(xtick.at) == FALSE || is.null(ytick.at) ==
            FALSE) {
        plot(x, y, type = "l", axes = FALSE, frame.plot = TRUE)
        <snip>

if (plot.X) {
      #nf <- layout(matrix(c(2, 2, 1, 1), 2, 2, byrow = TRUE),
      #             c(1, 2), c(2, 1), TRUE)
      par(mai = c(0.6, 0.4, 0.1, 0.6))

<snip>
}


text:
Q: Pulling Ruby version from regular expression I am trying to return the version of Ruby (such as 2.1.0) from a regular expression.  Here's the string as it should be evaluated by a regular expression:
ruby 2.1.0p0 (2013-12-25 revision 44422) [x86_64-darwin12.0]\n

How would I go about extracting 2.1.0 from this?  It seems to me that the best way to do this would be to extract the numbers around two periods, but no spaces or characters around them.  So basically, it would pull just 2.1.0 instead of anything else.
Any ideas?

A: How about:
str = "ruby 2.1.0p0 (2013-12-25 revision 44422) [x86_64-darwin12.0]\n"
str[/[\d.]+/] # => "2.1.0"

[\d.]+ means "find a string of characters that are digits or '.'.
str[/[\d.]+/] will find the first such string that matches and return it. See String#[] for more information.
The question is, do all versions and Ruby interpreters return their version information consistently? If your code could end up running on something besides the stock Ruby you might have a problem if the -v output changes in a way that puts the version farther into the string and something else matches first.

TinMan, I think you need a more rigorous regex; e.g., "1..0"[/[\d.]+/] => "1..0", "2.0.0.1."[/[\d.]+/] => "2.0.0.1.", "2.0.0.0.1"[/[\d.]+/] => "2.0.0.0.1"

Ruby uses a similar style to Semantic Versioning, so the actual format of the string shouldn't vary, allowing a simple pattern. Where the version number occurs might not be defined though.
IF it went crazy, something like /[\d.]{3,5}/ should herd things back into some semblance of order, and normalize the returned value:
[
  'foo 1.0 bar',
  'foo 1.1.1 bar',
  'foo 1.1.1.1 bar'
].map{ |s| s[/[\d.]{3,5}/] }
# => ["1.0", "1.1.1", "1.1.1"]

If you're trying to do this with running code, why not use the predefined constant RUBY_VERSION:
RUBY_VERSION # => "2.1.2"

Version numbers are notoriously difficult to grab, because there are so many different ways that people use to format them. Over the last several years we've seen some attempts to create some order and commonality.

A: Edit: I misread the question. I assumed the given string might be embedded in other text, but on re-reading I see that evidently is not the case.  The regex given by @theTinMan is sufficient and preferred.tidE
This is one way:
str = "ruby 2.1.0p0 (2013-12-25 revision 44422) [x86_64-darwin12.0]\n"

str[/[Rr]uby\s+(\d\.\d\.\d)/,1]
 #=> "2.1.0"

This could instead be written:
str[/[Rr]uby\s+(\d(\.\d){2})/,1]

If matching "Ruby 2.1" or Ruby "2" were desired, one could use
str[/[Rr]uby\s+(\d(\.\d){,2})/,1] # match "2", "2.1" or "2.1.1"

or
str[/[Rr]uby\s+(\d(\.\d){1,2})/,1] # "2.1" or "2.1.1", but not "2"

A: Just Inspect RUBY_VERSION
Rather than parsing the output of whatever you're trying to parse, just inspect the RUBY_VERSION constant. On any recent Ruby, you should get output similar to the following in a REPL like irb or pry:
RUBY_VERSION
# => "2.1.0"

Or ask Ruby on the command line with:
$ ruby -e 'puts RUBY_VERSION'
2.1.0

A: Try this:
str = "ruby 2.1.0p0 (2013-12-25 revision 44422) [x86_64-darwin12.0]\n"

pieces = str.split(" ", 3)
version, patch_num = pieces[1].split('p')

puts version

--output:--
2.1.0


text:
Q: What is a rescue image? I am trying to learn how to make my own os from osdev's wiki, but somewhere there it says that I have to use the grub-mkrescue command. I was doing some research around internet to understand what does that command do and found in the grub official documentation this sentence:

The program grub-mkrescue generates a bootable GRUB rescue image

What is a rescue image?

A: A rescue image can be used to restore your computer to a previous point in time. grub-mkrescue generates one of these rescue images. They're useful to have so that you have different restore points that you can go back to, or as a backup in case your hard drive goes bad. See this article for more info.


text:
Q: Concatenating constants and strings in CakePHP public class variables How do I concatenate global constants and strings in model $actsAs arrays in CakePHP 2.6?
I've got a file upload plugin that needs directory paths fed to it via the $actsAs configuration, but while it lets me just use a global constant OR a string as an array key value, it doesn't let me concatenate two together. This is a problem because theoretically my app could be living in various environments where the path to the app is different, and I'd rather not have this hard-coded and instead use a path relative to the global constant ROOT.
It looks to me like I'm running up against a limitation of PHP. What good solutions are there to this? Cake-specific / Cake-friendly solutions are a plus.
What works:
// Import.php
public $actsAs = array(
    'Uploader.Attachment' => array(
        'filename' => array(
            // You can use a global constant by itself:
            'tempDir' => TMP,
            'uploadDir' =>
            // Using a full string works, too.
            '/var/www/vhosts/hostname/app/webroot/file/imports',
            //
            'finalPath' => '/file/imports/',
            'nameCallback' => 'nameCallback',
            'overwrite' => false,
        ),
    ),
);

What I'd like to work, but doesn't work. Instead of concatenating, I get an "unexpected '.'" error:
public $actsAs = array(
    'Uploader.Attachment' => array(
        'filename' => array(
            'tempDir' => TMP,
            // Concatenation of the two results in an "unexpected ." error:
            // ROOT being '/var/www/vhosts/hostname/'
            'uploadDir' => ROOT . '/app/webroot/file/imports',
            //
            'finalPath' => '/file/imports/',
            'nameCallback' => 'nameCallback',
            'overwrite' => false,
        ),
    ),
);

A: You can do that in the constructor:
public function __construct($id = false, $table = null, $ds = null) {
   $this->actAs = array(
    'Uploader.Attachment' => array(
        'filename' => array(
            'tempDir' => TMP,
            'uploadDir' => ROOT . '/app/webroot/file/imports',
            'finalPath' => '/file/imports/',
            'nameCallback' => 'nameCallback',
            'overwrite' => false,
        ),
    ),
   );
  parent::__construct($id, $table, $ds);
}


text:
Q: Guardar datos desde una API en mi base de datos En el proyecto que estoy realizando me veo en la necesidad de conectar cada 5 minutos a una API foránea, capturar los datos y guardarlos en una tabla de mi DB. ¿Alguna idea de como logar esto?
Estoy trabajando con Laravel 5.6


text:
Q: Restrict change in Jupyter Themes I have a jupyter notebook server up that multiple ppl share.
Someone is changing the theme from default and its impacting everyone. I can't find who and they haven't heeded my pleas to stop.
Is it possible to restrict the use of jupyter themes (jt -t theme-name) without uninstalling jupyter themes (using company distribution so i can't).
I can't uninstall


text:
Q: API for automating Azure DevOps Pipelines? I want to automate the queue-ing of Azure Pipelines with an API call, get information on the pipeline/build/job status,

*

*Azure Pipelines docs only mention "API" for the "Invoke HTTP Rest API" task: https://learn.microsoft.com/en-us/azure/devops/pipelines/tasks/utility/http-rest-api?view=vsts That might come in handy, but is not what I am looking for.

*There is a "Azure DevOps Services REST API":
https://learn.microsoft.com/en-us/rest/api/azure/devops/?view=azure-devops-rest-5.1
But I couldn't find any mention of "Pipeline" there, so this doesn't seem to be the right thing as well.
The StackOverflow tag azure-devops-rest-api also only mentions VSTS and TFS:

Visual Studio Team Services REST APIs is a set of APIs allowing management of a Visual Studio Team Services accounts as well as TFS 2015 and 2017 servers.

Besides these two results, I only find other versions or translations of various copies of these - and a lot of unrelated documents that are about Azure in general.
Am I just using the wrong words to search?

Is there an actual API for Azure DevOps Pipelines?
Does it have a usable API Explorer?
Does it have proper clients for languages like JavaScript, Ruby or PHP?

A: I too have been working on automating DevOps pipelines and keep winding up back here.  Some of this information appears to be outdated.  As of the time of my writing this, I believe this article in the Microsoft Docs is the most recent.  I did have to scratch my head a bit to make it work, but wound up with this code
public static async Task InitiatePipeline(CancellationToken cancellationToken = default)
{
    using(HttpClient client = new HttpClient())
    {
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        var token = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "", AppSettings.DevOpsPAT)));
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", token);

var repoGuid = "Put GUID Here"; // You can get GUID for repo from the URL when you select the rpo of interest under  Repos is Project Settings
var bodyJson = @"{
    ""parameters"": {
        ""parameterName"": ""parameterValue""
    },
    ""variables"": {},
    ""resources"": {
        ""repositories"": {
            ""self"": {
                ""repository"": {
                    ""id"": """ + repoGuid + @""",
                    ""type"": ""azureReposGit""
                },
                ""refName"": ""refs/heads/master""
            }
        }
    }
}";

        var bodyContent = new StringContent(bodyJson, Encoding.UTF8, "application/json");
        var pipeLineId = 61; // Can get this from URL when you open the pipeline of interest in Azure DevOps
        var response = await client.PostAsync($"https://dev.azure.com/ORG_NAME/PROJECT_NAME/_apis/pipelines/{pipeLineId}/runs?api-version=6.0-preview.1", bodyContent, cancellationToken);
        response.EnsureSuccessStatusCode();
    }
}

A: Seems I was bad at googling:
Trigger Azure Pipelines build via API and Start a build and passing variables through VSTS Rest API (found via the searching for [azure-pipelines] apihere on StackOverflow) point me to the Azure DevOps Services REST API that I had mentioned above.

A: I ran into these problems as well and wound up making a powershell wrapper of the API and then wrapping that into an Azure DevOps Pipeline Template. I've just published it for anyone to use. I hope that anyone who finds this thread can find this template useful.

A: With AzFunc4DevOps this can be done in an event-driven way. And in C#.
E.g. here is how to trigger a build when another build succeeds:
[FunctionName(nameof(TriggerBuildWhenAnotherBuildSucceeds))]
public static async Task Run(
    [BuildStatusChangedTrigger
    (
        Project = "%TEAM_PROJECT_NAME%",
        BuildDefinitionIds = "%BUILD_DEFINITION_ID%",
        ToValue = "Completed"
    )]
    BuildProxy build,

    [BuildClient]
    BuildHttpClient buildClient,

    [BuildDefinition(Project = "%TEAM_PROJECT_NAME%", Id = "%NEXT_BUILD_DEFINITION_ID%")]
    BuildDefinitionProxy nextbuildDefinition
)
{
    await buildClient.QueueBuildAsync(new Build
    {
        Definition = nextbuildDefinition,
        Project = nextbuildDefinition.Project
    });
}

Here are some more examples.


text:
Q: How to dynamically load data inside page in nodejs project? How can I dynamically load data inside a page using nodejs?
In my case, I actually fetch some information from other sites and load it using ejs and render it. Due to the slowness of other sites from where I fetch, it takes time like around 3-5 seconds. So it simply means if users want to visit it, they have to wait 5 seconds before information can be presented to them.
I want to fix this problem by dynamically loading content inside a page means if the user visits the page, it will load the page immediately with all static content and it will say "loading" inside the area where fetched information will be shown.
How can I achieve this? is there some sort of technology for nodejs to achieve this?
If yes, can you please provide me documentation link of it?


text:
Q: How does the dependency resolution works with pip when a package specify a range and another doesn't? I have a requirement.txt with only 2 dependencies:
sentry-sdk==0.7.11
requests==2.21.0

I've checked the setup.py of both packages and both depend on urllib3:

*

*request provides a range that does not accpet the 1.25

*sentry-sdk instead does not specify a specific version or range

recently a new version of urllib3 (1.25) has been released when I install the dependencies with pip I get the following error:
ERROR: requests 2.21.0 has requirement urllib3<1.25,>=1.21.1, but you'll have urllib3 1.25 which is incompatible.

Is this behavior expected or is a bug in pip?
What is the meaning of not specifying a version of a dependency in install_requires? "force the latest version"?

A: The reason you observe this behavior is because pip installs sentry-sdk first. Since this does not have the version contraint, you get the latest version (1.25). When requests is to be installed, this version is incompatible.
The only way to solve this is to solve all version constraints globally, which AFAIK pip cannot do.
The solution is to specify the version of urllib3 you want in your requirements.txt (since you know which versions of its dependencies you use). This is probably good pratice anyway for transient packages without constraints.
Actually, the way to have reproducible builds with pip is to always do
pip freeze > requirements.txt

and check in the result. This way a third party package update won't break your build, and you can always manually upgrade later (and check in the result).


text:
Q: C# список для хранения произвольных классов Добрый день.
Возникла следующая задача.
Имеется несколько произвольных классов, они могут наследовать от одного базового класса, а могут не наследовать. Задача завести некий список, в котором будет хранится последовательность создания этих классов с возможностью добавления в произвольное место новых классов. Хотелось бы узнать у более опытных товарищей, как это лучше реализовать в C#. Заранее благодарю.


text:
Q: Netcore 2.2 - Docker Container cannot sending mail i'm current deploy one application into docker container, this app have function sending mail
(base on c# netcore 2.2)
but i can not sending mail (while mean i can sending mail from localhost)
the message of exception in docker

System.ComponentModel.Win32Exception: GSSAPI operation failed with
  error - Unspecified GSS failure.  Minor code may provide more
  information (Cannot find KDC for realm "xxx.yyyy").    at
  System.Net.Security.NegotiateStreamPal.AcquireCredentialsHandle(String
  package, Boolean isServer, NetworkCredential credential)    at
  System.Net.NTAuthentication.Initialize(Boolean isServer, String
  package, NetworkCredential credential, String spn, ContextFlagsPal
  requestedContextFlags, ChannelBinding channelBinding)    at
  System.Net.Mail.SmtpNegotiateAuthenticationModule.Authenticate(String
  challenge, NetworkCredential credential, Object sessionCookie, String
  spn, ChannelBinding channelBindingToken)    at
  System.Net.Mail.SmtpConnection.SetContextAndTryAuthenticate(ISmtpAuthenticationModule
  module, NetworkCredential credential, ContextAwareResult context)
  at System.Net.Mail.SmtpConnection.GetConnection(String host, Int32
  port)    at System.Net.Mail.SmtpTransport.GetConnection(String host,
  Int32 port)    at System.Net.Mail.SmtpClient.GetConnection()    at
  System.Net.Mail.SmtpClient.Send(MailMessage message)    --- End of
  inner exception stack trace ---    at
  System.Net.Mail.SmtpClient.Send(MailMessage message)

i have try some help from google but can not, so please help me
thanks

A: It seems there is an issue in dotnet on linux, when you send mails with the GSSAPI authentication type:
https://github.com/dotnet/runtime/issues/2174, https://github.com/dotnet/runtime/issues/25885, https://github.com/dotnet/runtime/issues/27285
Try installing "gss-ntlmssp" in the container if you need to use GSSAPI.
Or, if your server accepts other authentication types, use another one, like NTLM:
var cred = new NetworkCredential(user, password, domain);
var cache = new CredentialCache();
cache.Add(host, 25, "NTLM", cred);
client.Credentials = cache;


text:
Q: Is it advisable to always include an empty group to avoid double superscript error for math accents? This very helpful answer
https://tex.stackexchange.com/a/582444/239563
describes a way to avoid a double superscript error by including an empty group:
${{}\dot{y}^a}^\top$

My question is: is there any danger in always including an empty group whenever some "accent" like \dot or \bar is used? Are there cases where this has undesirable consequences in a different situation?
(I'm asking because in my case, the LaTeX code is automatically generated, and either my code does it, or the user has to take care of it by using a special instruction of my program.)
Thanks a lot for your help!

A: The group is essentially forcing an extra math node wrapper which is acting like a box and will affect positioning in various ways, arguably not for the better. For example it avoids a double superscript error by moving the superscript to the outer node but it also does the same for a subscript which would have been placed (and kerned) on the inner character node.

\documentclass{article}

\begin{document}

${{}\dot{y}^a}_1$

${\dot{y}^a}_1$
\end{document}

Maintaining the tightly kerned subscript is presumably why TeX unwinds the mathaccent construct to expose the character node in the first place.
Although it depends slightly on where you are proposing to "always" add the {}  this form with {} does produce the close subscript.

\documentclass{article}

\begin{document}

${{}\dot{y}^a_1}$
\end{document}


text:
Q: how to show percent from random number generator in C I can't seem to figure out what to do. I'm trying to practice with rand() in C but I don't know how to do the other part.
I want the output to look like:
Coins:
  Flips: 10
    Heads: 40%
    Tails: 60%
right now I have this as my code:
#include <stdio.h>
   #include <stdlib.h>

   int main()
   {
       int i, value;

       for(i=0; i < 10; i++){
         value = rand()%2;
         printf("Coin:\n____\n  Flips: 10\n");
         }

       return 0;

   }

I want it to generate heads or tails and then show a percentage of what it had. Any help?

A: The issue is that you are printing during the trials when you should only be printing after they are complete. Try this:
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int i, value;
    int heads = 0;

    srand(time(NULL)); /* seed for rand */

    for(i=0; i < 10; i++){
        value = rand() % 2;
        if (value == 1) {
            heads++;
        }
    }

    printf("Coin:\n____\n  Flips: 10\n");
    printf("    Heads: %d%%\n", heads * 10);
    printf("    Tails: %d%%\n\n", (10 - heads) * 10);

    return 0;
}

A: There's a bit wrong with this. You're not keeping track of anything to get the percentages. Please note this is more "pseudocode". I haven't tested it so it might have a typo.
int main()
{
    int i, value;
    int headsCount = 0;
    int tailsCount = 0;

    for(i=0; i < 10; i++){
        value = rand()%2;
        if (value == 0) headsCount++;
        else tailsCount++;

        printf("Coin:\n____\n  Flips: %d\n", i+1);
        printf("    Heads: %d%%\n", (headsCount * 100) / (i+1)));
        printf("    Tails: %d%%\n\n", (tailsCount * 100) / (i+1)));
    }

    return 0;
}

A: value / value will either equal 1 or cause a division by zero.
value / 10 will give you a result that is less than or equal to 1, but any value less than 1 will be rounded down to zero because its an integer.
value * 100 / 10 will give you a result that is less than or equal to 100 (a percentage).
100 - value * 100 / 10 will give you an opposite percentage.


text:
Q: Tkinter - Returning from a class and calling a new one I was trying to create my own version of the game Go Fish (two players for now) in python 3.4. My game has two main stages. The first one is to determine who is going to make the first move. This is done by calling my class FirstStage (file2.py) which is basically the hand game Rock Paper Scissors - me against robot. After we have a winner, FirstStage returns an integer (0 or 1) which represents the winner of this stage. Then SecondStage class (file3.py) is called passing self.winner as an argument. The game script was split in many files because I use many classes. This is the basic idea but for some reason FistStage is not returning anything. Can some help me with this? Here my code:
file1.py
from file2 import *
from file3 import *
import tkinter as tk

class start_gui(tk.Frame):

    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self,parent, *args, **kwargs)
        # create canvas
        self.canvas = tk.Canvas(parent, width=800, height=800, background="green")
        self.canvas.pack()

        # here we call FirstStage class to determine who starts first
        self.c = FirstStage(parent)
        self.winner = self.c.getwinner()
        #here we call SecondStage call to start the real game
        self.d = SecondStage(self.winner)

if __name__ == "__main__":
    # create main window
    root = tk.Tk()
    root.geometry("800x800")
    start_gui(root)
    root.mainloop()

file2.py
import tkinter as tk
from functools import partial
from PIL import ImageTk
from PIL import Image

class FirstStage(tk.Frame):

    def __init__(self, canv):
        tk.Frame.__init__(self, parent, background="black", padx=10, pady=10)
        self.winner = 0
        #here new frame is created
        #buttons and images are place in a grid
        self.rock_paper_scissors()

    def rock_papper_scissors(self):
        #here goes some code
        #player against API
        #undefine number of times until there is a winner

    def close(self, w):
        self.grid_forget()
        self.destroy()
        # here buttons, images and frame are destroy
        # save winner
        self.winner = w

    def getwinner(self):
        #return int - 0 for player and 1 for robot(opponent)
        return self.winner

file3.py
class SecondStage:
    def __init__(self, winner)
        #here goes some scripts

A: This is long so I couldn't provide it as a comment.
I tested your code as it is (with minor changes) and FirstStage returned the correct winner, which at the moment is 0 or whatever value you give in self.winner = 0.

*

*In file2.py, you have canv in the __init__ method but passed
parent to tk.Frame.__init__. It gave me error since these
arguments do not match, hence I changed canv to parent.

*The spelling of rock_paper_scissors during method definition and
method call in the __init__ method are different, check the
spellings.

*You tried to change self.winner in the close method of file2.py, but that method is not called anywhere in the code you provided, so self.winner stays the same (having a value of 0).

*If you put a print statement after self.winner = self.c.getwinner() in file1.py, you'll realize the winner is
indeed returned.

If you make these changes and still don't get the correct winner, then the problem might be how you implemeted FirstStage in file2.py; which is not provided in the question.
Here is the code I used for testing:
file1.py
from file2 import *
from file3 import *
import tkinter as tk

class start_gui(tk.Frame):

    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self,parent, *args, **kwargs)
        # create canvas
        self.canvas = tk.Canvas(parent, width=800, height=800, background="green")
        self.canvas.pack()

        # here we call FirstStage class to determine who starts first
        self.c = FirstStage(parent)
        self.winner = self.c.getwinner()
        print(self.winner)
        #here we call SecondStage call to start the real game
        self.d = SecondStage(self.winner)

if __name__ == "__main__":
    # create main window
    root = tk.Tk()
    root.geometry("800x800")
    start_gui(root)
    root.mainloop()

file2.py
import tkinter as tk
from functools import partial
from PIL import ImageTk
from PIL import Image

class FirstStage(tk.Frame):

    def __init__(self, parent):
        tk.Frame.__init__(self, parent, background="black", padx=10, pady=10)
        self.winner = 0
        #here new frame is created
        #buttons and images are place in a grid
        self.rock_paper_scissors()

    def rock_paper_scissors(self):
        pass
        #here goes some code
        #player against API
        #undefine number of times until there is a winner

    def close(self, w):
        self.grid_forget()
        self.destroy()
        # here buttons, images and frame are destroy
        # save winner
        self.winner = w

    def getwinner(self):
        #return int - 0 for player and 1 for robot(opponent)
        return self.winner

file3.py
class SecondStage:
    def __init__(self, winner):
        pass
        #here goes some scripts


text:
Q: How can I set the size of this GUI? I have an applet (and this is an SSCCE):
package tutoringcalculator;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.*;

public class TutoringCalculator extends JApplet {
    private JPanel _root;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame("Tutoring Calculator");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                JApplet applet = new TutoringCalculator();
                applet.init();

                frame.setContentPane(applet.getContentPane());

                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);

                applet.start();
            }
        });
    }

    private JPanel swingContainer;

    @Override
    public void init() {
        swingContainer = new JPanel(new BorderLayout());
        add(swingContainer, BorderLayout.CENTER);
        createScene();
        setSize(600, 400);
    }

    private void createScene() {
        JLabel lbl;
        JTextField txt;

        _root = new JPanel(new FlowLayout());

        // build the session minutes
        lbl = new JLabel();
        lbl.setText("Session Minutes:");
        _root.add(lbl);

        txt = new JTextField();
        _root.add(txt);

        swingContainer.add(_root);
    }
}

and I'd like to set the size to 600x400 - but I've issued setSize(600, 400) on applet, frame, swingContainer, and _root and nothing changes. I get a screen that looks like this:

A: As mentioned, an applet typically gets a size (forced upon it) by the HTML.  A free floating JFrame is different.  Instead it has components inside which suggest a size, which is then calculated at time of pack().  E.G. after setting a size in the constructor of the JTextField, this is what we see:

Now, I expect you are going to be adding a whole lot more components to this before it's done, and they will make the size bigger as well, but there are also some other tips for making the content larger.  Borders & layout padding.  Here is what it looks like with some of that.

So, what it comes down to is either a) Add a whole bunch of components that will make a GUI bigger, and/or b) add white space as defined in the layout constructors & borders.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;

public class TutoringCalculator {

    private JPanel _root;
    private JPanel swingContainer;
    private JLabel lbl;
    private JTextField txt;

    TutoringCalculator() {
        swingContainer = new JPanel(new BorderLayout());
        // set an empty border to it
        swingContainer.setBorder(new EmptyBorder(20,20,20,20));

        // suggest a spacing of 20px between components
        _root = new JPanel(new FlowLayout( FlowLayout.CENTER, 20, 20));
        swingContainer.add(_root);

        // add a line border so we can see the bounds of this container
        _root.setBorder(new LineBorder(Color.BLACK, 1));

        // this has a size as needed by the content
        lbl = new JLabel("Session Minutes:");
        _root.add(lbl);

        // Suggest a size (in characters - 10) for the text field
        txt = new JTextField(10);
        _root.add(txt);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame("Tutoring Calculator");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                TutoringCalculator calc = new TutoringCalculator();

                frame.setContentPane(calc.swingContainer);

                frame.pack();
                // much better!
                frame.setLocationByPlatform(true);
                frame.setVisible(true);
            }
        });
    }
}


text:
Q: Method identifier [29] out of range Error I have a EJB that existed in Weblogic 10.3. We moved it to 12c and modified the build to use the maven-plugin to create the EJB client and EJB (2 separate builds).
There is a Java application that needs to call the EJB via a remote interface. In doing so, there are 2 methods that give the following error (the rest of the methods work fine):
java.rmi.UnmarshalException: Method identifier [29] out of range
    at weblogic.rjvm.BasicOutboundRequest.sendReceive(BasicOutboundRequest.java:108)
    at weblogic.rmi.cluster.ReplicaAwareRemoteRef.invoke(ReplicaAwareRemoteRef.java:290)
    at weblogic.rmi.cluster.ReplicaAwareRemoteRef.invoke(ReplicaAwareRemoteRef.java:248)
    at net.footware.shoeManager.ShoeManager_xwmvzk_EOImpl_1211_WLStub.updateShoeStatus(Unknown Source)

The other method gives the same error, but with a different number:
java.rmi.UnmarshalException: Method identifier [28] out of range

It's notable that the client jar and EJB jar is built in 2 different pom.xml files. The pom.xml that builds the client explicitly excludes some classes, while the pom.xml that builds the EJB jar does not.
It's not simply missing the method as that would send back a "Method Not Found" error. I also reduced the method to simply returning true (no other logic). It appears the call never reaches the code in the remote methods. There are other methods that take and return the same objects and don't throw errors.
When I created a new method that accepts a boolean value, I got this error:
Caused by: java.io.StreamCorruptedException: invalid type code: 04

Any idea what could cause these errors?


text:
Q: android enable 'settings' permissions I'm writing some automation testing for my app,
On my emulator is there a way to enable settings permissions (permissions that requires the user to go to device settings and enable them)
like usage state, accessibility services, notifications from ADB? (like 'adb shell pm grant')

A: You don't have any APIs that can to that, but if you're using UIAutomator it is pretty easy to achieve. If you're using Espresso, you need to add UIAutomator (Espresso is for single app testing, while UiAutomator is cross-app testing) and this will give you the possibility to access the Settings app.

A: Using adb the closest you could get is opening the Application settings.
adb shell am start -a android.settings.APPLICATION_SETTINGS

Otherwise UIAutomator would be the way to automate this.


text:
Q: Google Chrome loads the javascript first even I put the script tag before the end of the body tag
I have a problem with loading JavaScript in Google Chrome.
I've created the separate js file with a simple alert message and then linked it before the end of the body tag.
Google Chrome shows the alert box first then when I click 'ok' the content is loaded.
In other browsers it works fine, I mean the alert box shows at the same time as the content of the web page.
In short, Google Chrome loads the javascript first even when I put the script tag before the end of the body tag.

alert("Hello World!");
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Write Your First Program</title>

      <link href="css/bootstrap.min.css" rel="stylesheet">

     <link href="css/styles.css" rel="stylesheet">

Write Your First Program

JavaScript Essentials

Do you have any idea  how to fix this problem?
Thanks a lot

A: Your problem is that your script have the tag async, which let it execute whitout taking care of the web page loading state. Remove the async tag, or replace it with defer, which execute the script after the page loading.
In order to prevent any problem with script and html/css loading times conflict, you should encapsulate your Javascript's scripts with window.onload = function() { //code here }. This will guarantee that your whole page is loaded before executing your code.

A: That is a problem with Chrome. The developers of chrome for some reason have still not corrected that. If you have alert or a prompt pop-up, which is the first thing that user has to interact with in your website, chrome will not load HTML until after the pop-up has been closed.

A: Try including jquery cdn just above your script tag in body.

This will work fine!!

A: I also had this problem and realized that my Google chrome was just loading the cached version of page(the one before putting my script tag near bottom).
Closing the window and reopening the page worked fine.

A: async and defer boolean attributes are only helpful when the script is inserted in the head portion of the page. They are useless if you put the script in the body footer like we saw above.
(Refer following article: https://flaviocopes.com/javascript-async-defer/).
I am also facing similar issue and using window.onload = funcRef; with cleared cache also does not work on my google chrome. I have tried all of this with disabling all my browser extensions but in vain.
I was finally able to, not solve, but agree upon a way around - which was - to include a

jQuery CDN

before my javascript script in the body. Hope this helps.


text:
Q: Get path of Framework in MSI custom actions I'm trying to execute custom commands on my DLL using .msi. I want to know that How to get x86 framework path(c:\Windows\Microsoft.NET\Framework\v2.0.50727) in x64 machine and x86 machine
MSI Error - Failure of regsvr32 custom action
To get system path use we use [SystemFolder] so is there any property to get location of c:\Windows\Microsoft.NET\Framework\v2.0.50727

related article
Getting the .NET Framework directory path

A: "Self registration" (Regsvr32, Regasm, GACUTIL, InstallUtil et al) is not considered a best practice in Windows Installer because it runs out of process, isn't declarative and isn't transactional.  It defeats Windows Installers knowledge of the changes being made to the target machine, is slower, often fragile and often breaks in repair, upgrade, downgrade, rollback et al scenarios.
The alternative is to "harvest" or "extract" the COM metadata associated with your assembly and author them natively into your MSI.  How you do this exactly depends on what tool you are using to author your MSI.   InstallShield has a setting called ".NET Com Visible" and WiX has a feature called "Heat".  A more raw approach is to run the command  regasm foo.dll /regfile:out.reg and then author the contents of the regfile into your installer by hand substituting the paths with MSI directory properties.
There is one catch with regasm /regfile as documented on the regasm topic in MSDN:

Note that the .reg file does not contain any registry updates that can
  be made by user-defined register functions.


text:
Q: Reconcile Angular.js and Bootstrap form validation styling I am using Angular with Bootstrap. Here is the code for reference:
<form name="newUserForm" ng-submit="add()" class="" novalidate>
    <input type="text" class="input" ng-model="newUser.uname" placeholder="Twitter" ng-pattern="/^@[A-Za-z0-9_]{1,15}$/" required>
    <button type="submit" ng-disabled="newUserForm.$invalid" class="btn btn-add btn-primary">Add</button>
</form>

Bootstrap has styles for invalid fields in the form of input:invalid {.... }; these kick in when the field is empty. Now I also have some pattern matching via Angular. This creates odd cases when ":invalid" is off, but ".ng-invalid" is on, which would require me to re-implement bootstrap CSS classes for the ".ng-invalid" class.
I see two options, but having trouble with both

*

*Make Angular use some custom classname instead of "ng-valid" (I don't know how to do this).

*Disable html5 validation (I thought that that's what "novalidate" attribute in the form tag should do, but couldn't get it work for some reason).

The Angular-Bootstrap directives out there don't cover styling.

A: Use Bootstrap's "error" class for styling. You can write less code.
<form name="myForm">

    Name
    <input type="text" name="name" ng-model="project.name" required>

        Required

</form>

EDIT:
As other answers and comments point out - in Bootstrap 3 the class is now  "has-error", not "error".

A: The classes have changed in Bootstrap 3:
<form class="form-horizontal" name="form" novalidate ng-submit="submit()" action="/login" method="post">

    email:

    <input type="email" id="email" placeholder="email" name="email" ng-model="email" required>

please enter your email

please enter a valid email

  ...

Note the quotes around 'has-error' and 'has-success': took a while to find that...

A: If styling is the issue, but you don't want to disable the native validation, why not override the styling with your own, more specific style?
input.ng-invalid, input.ng-invalid:invalid {
   background: red;
   /*override any styling giving you fits here*/
}

Cascade your problems away with CSS selector specificity!

A: Another solution: Create directive which toggles has-error class according to a child input.

app.directive('bsHasError', [function() {
  return {
      restrict: "A",
      link: function(scope, element, attrs, ctrl) {
          var input = element.find('input[ng-model]');
          if (input.length) {
              scope.$watch(function() {
                  return input.hasClass('ng-invalid');
              }, function(isInvalid) {
                  element.toggleClass('has-error', isInvalid);
              });
          }
      }
  };
}]);

and then simple use it in template

    <input class="form-control" ng-model="foo" ng-pattern="/.../"/>

A: Minor improvement to @farincz's answer. I agree that a directive is the best approach here but I didn't want to have to repeat it on every .form-group element so I updated the code to allow adding it to either the .form-group or to the parent <form> element (which will add it to all contained .form-group elements):
angular.module('directives', [])
  .directive('showValidation', [function() {
    return {
        restrict: "A",
        link: function(scope, element, attrs, ctrl) {

            if (element.get(0).nodeName.toLowerCase() === 'form') {
                element.find('.form-group').each(function(i, formGroup) {
                    showValidation(angular.element(formGroup));
                });
            } else {
                showValidation(element);
            }

            function showValidation(formGroupEl) {
                var input = formGroupEl.find('input[ng-model],textarea[ng-model]');
                if (input.length > 0) {
                    scope.$watch(function() {
                        return input.hasClass('ng-invalid');
                    }, function(isInvalid) {
                        formGroupEl.toggleClass('has-error', isInvalid);
                    });
                }
            }
        }
    };
}]);

A: My improvement to Jason Im's answer the following adds two new directives show-validation-errors and show-validation-error.
'use strict';
(function() {

    function getParentFormName(element,$log) {
        var parentForm = element.parents('form:first');
        var parentFormName = parentForm.attr('name');

        if(!parentFormName){
            $log.error("Form name not specified!");
            return;
        }

        return parentFormName;
    }

    angular.module('directives').directive('showValidation', function () {
        return {
            restrict: 'A',
            require: 'form',
            link: function ($scope, element) {
                element.find('.form-group').each(function () {
                    var formGroup = $(this);
                    var inputs = formGroup.find('input[ng-model],textarea[ng-model],select[ng-model]');

                    if (inputs.length > 0) {
                        inputs.each(function () {
                            var input = $(this);
                            $scope.$watch(function () {
                                return input.hasClass('ng-invalid') && !input.hasClass('ng-pristine');
                            }, function (isInvalid) {
                                formGroup.toggleClass('has-error', isInvalid);
                            });
                            $scope.$watch(function () {
                                return input.hasClass('ng-valid') && !input.hasClass('ng-pristine');
                            }, function (isInvalid) {
                                formGroup.toggleClass('has-success', isInvalid);
                            });
                        });
                    }
                });
            }
        };
    });

    angular.module('directives').directive('showValidationErrors', function ($log) {
        return {
            restrict: 'A',
            link: function ($scope, element, attrs) {
                var parentFormName = getParentFormName(element,$log);
                var inputName = attrs['showValidationErrors'];
                element.addClass('ng-hide');

                if(!inputName){
                    $log.error("input name not specified!")
                    return;
                }

                $scope.$watch(function () {
                    return !($scope[parentFormName][inputName].$dirty && $scope[parentFormName][inputName].$invalid);
                },function(noErrors){
                    element.toggleClass('ng-hide',noErrors);
                });

            }
        };
    });

    angular.module('friport').directive('showValidationError', function ($log) {
        return {
            restrict: 'A',
            link: function ($scope, element, attrs) {
                var parentFormName = getParentFormName(element,$log);
                var parentContainer = element.parents('*[show-validation-errors]:first');
                var inputName = parentContainer.attr('show-validation-errors');
                var type = attrs['showValidationError'];

                element.addClass('ng-hide');

                if(!inputName){
                    $log.error("Could not find parent show-validation-errors!");
                    return;
                }

                if(!type){
                    $log.error("Could not find validation error type!");
                    return;
                }

                $scope.$watch(function () {
                    return !$scope[parentFormName][inputName].$error[type];
                },function(noErrors){
                    element.toggleClass('ng-hide',noErrors);
                });

            }
        };
    });

})();

The show-validation-errors can be added to a container of errors so that it will show/hide the container based upon a form fields validity.
and the show-validation-error shows or hides an element based upon that form fields validity on a given type.
An example of intended use:
        <form role="form" name="organizationForm" novalidate show-validation>

                Organization number
                <input type="text" class="form-control" id="organizationNumber" name="organizationNumber" required ng-pattern="/^[0-9]{3}[ ]?[0-9]{3}[ ]?[0-9]{3}$/" ng-model="organizationNumber">

                        Organization number is required.

                        Organization number needs to have the following format "000 000 000" or "000000000".

       </form>

A: I think it's too late to reply but hope you are going to love it:
CSS you can add other type of controls like select, date, password etc
input[type="text"].ng-invalid{
    border-left: 5px solid #ff0000;
    background-color: #FFEBD6;
}
input[type="text"].ng-valid{
    background-color: #FFFFFF;
    border-left: 5px solid #088b0b;
}
input[type="text"]:disabled.ng-valid{
    background-color: #efefef;
    border: 1px solid #bbb;
}

HTML: no need to add anything in controls except ng-required if it is
<input type="text"
       class="form-control"
       ng-model="customer.ZipCode"
       ng-required="true">

Just try it and type some text in your control, I find it really handy and awesome.

A: Minor improvement to @Andrew Smith's answer.
I change input elements and using require keyword.
.directive('showValidation', [function() {
    return {
        restrict: "A",
        require:'form',
        link: function(scope, element, attrs, formCtrl) {
            element.find('.form-group').each(function() {
                var $formGroup=$(this);
                var $inputs = $formGroup.find('input[ng-model],textarea[ng-model],select[ng-model]');

                if ($inputs.length > 0) {
                    $inputs.each(function() {
                        var $input=$(this);
                        scope.$watch(function() {
                            return $input.hasClass('ng-invalid');
                        }, function(isInvalid) {
                            $formGroup.toggleClass('has-error', isInvalid);
                        });
                    });
                }
            });
        }
    };
}]);

A: Thank you to @farincz for a great answer. Here are some modifications I have made to fit with my use case.
This version provides three directives:

*

*bs-has-success

*bs-has-error

*bs-has (a convenience for when you want to use the other two together)

Modifications I have made:

*

*Added a check to only show the has states when the form field is dirty, i.e. they won't be shown until somebody interacts with them.

*Altered the string passed into element.find() for those not using jQuery, as  element.find() in Angular's jQLite only supports finding elements by tagname.

*Added support for select boxes and textareas.

*Wrapped the element.find() in a $timeout to support cases where the element may not yet have it's children rendered to the DOM (e.g. if a child of the element is marked with ng-if).

*Changed if expression to check for the length of the returned array (if(input) from  @farincz's answer always returns true, as the return from element.find() is a jQuery array).

I hope somebody finds this useful!
angular.module('bs-has', [])
  .factory('bsProcessValidator', function($timeout) {
    return function(scope, element, ngClass, bsClass) {
      $timeout(function() {
        var input = element.find('input');
        if(!input.length) { input = element.find('select'); }
        if(!input.length) { input = element.find('textarea'); }
        if (input.length) {
            scope.$watch(function() {
                return input.hasClass(ngClass) && input.hasClass('ng-dirty');
            }, function(isValid) {
                element.toggleClass(bsClass, isValid);
            });
        }
      });
    };
  })
  .directive('bsHasSuccess', function(bsProcessValidator) {
    return {
      restrict: 'A',
      link: function(scope, element) {
        bsProcessValidator(scope, element, 'ng-valid', 'has-success');
      }
    };
  })
  .directive('bsHasError', function(bsProcessValidator) {
    return {
      restrict: 'A',
      link: function(scope, element) {
        bsProcessValidator(scope, element, 'ng-invalid', 'has-error');
      }
    };
  })
  .directive('bsHas', function(bsProcessValidator) {
    return {
      restrict: 'A',
      link: function(scope, element) {
        bsProcessValidator(scope, element, 'ng-valid', 'has-success');
        bsProcessValidator(scope, element, 'ng-invalid', 'has-error');
      }
    };
  });

Usage:

  <input
   type="text"
   id="text"
   name="text"
   ng-model="data.text"
   required>

  <select
   id="select"
   name="select"
   ng-model="data.select"
   ng-options="option.name for option in data.selectOptions"
   required>
    <option value="">-- Make a Choice --</option>
  </select>

  <textarea
   id="textarea"
   name="textarea"
   ng-model="data.textarea"
   required></textarea>

You can also install Guilherme's bower package that bundles all this together.

A: It's hard to tell for sure without a fiddle but looking at the angular.js code it does not replace classes - it just adds and removes its own. So any bootstrap classes (added dynamically by bootstrap UI scripts) should be untouched by angular.
That said, it does not make sense to use Bootstrap's JS functionality for validation at the same time as Angular - only use Angular. I would suggest you employ the bootstrap styles and the angular JS i.e. add the bootstrap css classes to your elements using a custom validation directive.

A:

  Email

    <input type="email" class="form-control" ng-model="user.email" name="uemail" placeholder="Enter email" required>

A: I know this is a very old question answer thread when I haven't heard the name of AngularJS itself :-)
But for others who land to this page looking for Angular + Bootstrap form validation in a clean and automated way, I've written a pretty small module for achieving the same without altering the HTML or Javascript in any form.
Checkout Bootstrap Angular Validation.
Following are the three simple steps:

*

*Install via Bower bower install bootstrap-angular-validation --save

*Add the script file

*Add the dependency bootstrap.angular.validation to your application and that's it!!
This works with Bootstrap 3 and jQuery is not required.
This is based on the concept of jQuery validation. This module provides some additional validation and common generic messages for validation error.


text:
Q: Detect incomplete translation files in Qt I want to be able to detect if translations are missing for any language during my release build.
I'm using CMake to build the application and CMake is also running lupdate and lrelease. In this process I would like to display a warning if some translations are missing in the TS files. As far as I can see lupdate and lrelease does not allow detection of missing translations, I have checked the output when running the commands with -help option. According to the Qt docs:

Both lupdate and lrelease may be used with TS translation source files
  which are incomplete. Missing translations will be replaced with the
  native language phrases at runtime.

This is very fine, but I would really like some indication that the files are incomplete.
Any ideas?


text:
Q: Find $\{\bar{u}_{k}\}$ in $\mathbb{R}^{2}$ s.t. $\{\|\bar{u}_{k}\|\}$ is bounded increasing but $\{\bar{u}_{k}\}$ not convergent. I'm trying to figure out how a sequence's distance can be increasing and bounded? Would the sequence $\{(-1)^n)\}$ satisfy this?

Find a sequence $\{\bar{u}_{k}\}$ in $\mathbb{R}^{2}$ with the property that $\{\|\bar{u}_{k}\|\}$ is a bounded increasing sequence but with $\{\bar{u}_{k}\}$ not convergent.

A: Imagine a spiral from inside a unite disk which gets closed and closer to the unit circle from inside but never crosses it. Pick $u_{k}$ on this spiral.


text:
Q: High-stability oscillators (non-crystal) Are there any high-stability oscilators, which are not crystal based, given that temperature is stable down to 0.01 C and voltage down to 0.001V?
Will LC-based oscillator be able to show performance comparable to crystals in such conditions (probably in wierd variants like LC-opamp-LC-opamp-LC-opamp... so that any energy loss on each stage is recovered and we are getting narrower bandwidth)?
Price is not limited here, to a some degree (so brand new atomic clocks are above the budget, but 100$ for peltier/oven & parts is ok).
From my (naive) point it seems that it should be possible to achieve better short & long-term stability than with crystals...

A: For a budget of $100 you could easily put together a GPS based standard. For example A Simplified GPS-Derived Frequency Standard.
This particular project has a measured accuracy and the author states: "I have made observations over several months, and concluded that the 10-10 decade (from 10-10 to 10-9) is a reasonable expectation from this system."
This is a project put together in 2006 and not optimized for stability.
Another option is a cheap oscillator using a phased locked loop (PLL) tied to a received radio signal from WWV or other national authority. Their short term stability isn't that great but their long term stability is probably as good as it gets. This is how the cheap "atomic clocks" that you see in the store for $20-30 (the kind that hang on the wall and display the time) work.
As an aside, you state "so brand new atomic clocks are above the budget". That is true, but you could pickup a used one for about $50-60.

A: Superb mechanical construction of the inductor is a major factor. See Czech Tesla report cited below for specific advice.
If you can track down this 1941 [!!!] original and/or the many derivatives based on it using both "valves" and 'solid state" circuits you will probably find circuits with performance about as good as you can get.
"E. O. Seiler, "A Low-C Electron-Coupled Oscillator," QST, Nov 1941."
A circuit based on Seiler's work was published in QST with , I think, a title like "A synthetic rock" or "The synthetic rock. (Rock == crystal).
One reference noted that the oscillator output was designed to be plugged into a  crystal socket and when used at eg 12 MHz to provide the reference fquency for a 2 m,etre band (144-148 Mhz) transmitter, produced a signal which was zero beat stable for hours ata time when compared with a crystal controlled test unit. Zero beat stable means drift is within a few Hz at most as otherwise you hear "rumbling" as the two signals heterodyne.

I don't speak or read  Croatian and gargoyle was having a bad day but I believe the circuits below are based on Seiler's ideas. See pages 147-148 here. Translation to English (unless you read Croatian) looks worthwhile. Many other related circuits there too. These may come from US "hams' W8PK & W3EB.
Note that these two circuits do NOT look overly special. I think a significant part of the "trick" is in the relative  (lack of) loading of the tuned circuit.

This mentions the Synthetic Rock in passing, with approval.

Valuable albeit old !!!
Resources for Understanding Oscillators {2003} - with references to MUCH older material.
Look for Seiler references.
The following are from the above reference -
E. O. Seiler, "A Low-C Electron-Coupled Oscillator," QST, Nov 1941.

*

*Describes the circuit that D. Stockton, ARRL Handbook, 1995+, p. 14.14, mistakenly calls "the original Colpitts circuit ... now often referred to as the parallel-tuned Colpitts..."

W. B. Bernard, "Let's Increase V.F.O. Stability," QST, Oct 1957.

*

*Suggests using grounded-cathode triode with separate buffer instead of the electron-coupled pentode circuit. Also suggests using the Seiler or Colpitts circuit with the largest available value of tuning variable capacitor instead of the Clapp circuit with a low value of tuning capacitor.

J. Vackar, "LC Oscillators and their frequency stability," Tesla Tech. Reports, Czechoslovakia, Dec 1949.

*

*He discusses mechanical design of tuning circuits, presents general analysis of oscillator circuits and their sensitivity to changes of internal capacities of valves (vacuum tubes). He reviews existing circuits, including Gouriet-Clapp, Seiler, and Lampkin, comparing their amplitude dependence on frequency and hence useful tuning range. He describes in detail the design process for circuit we commonly refer to as the Vackar oscillator, which has greater tuning range. He then goes on to describe a slight variation with still greater tuning range. This last circuit, which I have never seen elsewhere, he describes as a compromise between the first-mentioned Vackar circuit and that due to Seiler.

1949 original of the above report in Czech. Superb][(http://www.scribd.com/doc/62276627/Vackar-wholepaper)
 Starts with a description of mechanical requirements for high stability.
J. K. Clapp, "Frequency Stable LC Oscillators," Proc. IRE, Aug 1954.

*

*Shows that Gouriet-Clapp, Seiler, and Vackar oscillators have equivalent frequency stability given equal resonator Q. They differ only in how much the amplitude of oscillation changes when they are tuned. The three circuits are useful over frequency ranges of 1.2, 1.8, and 2.5 to one, respectively.

The above suggests that the Vackar oscillator is potentially more useful.

See refs here Discrete Oscillator design- Rhea  on page 261.

A: There are MEMs oscillators, resistant to shock in the order of tens of thousands of G's.  For example, see http://www.abracon.com/Oscillators/ASEM.pdf


text:
Q: Point relaxation inside of Chromaticity Plot 3D I'm trying out the new ChromaticityPlot3D function in Mathematica and noticed I can extract the mesh of the output graph using //InputForm.
I'd like to find the most even/relaxed distribution of points inside a subset luminosity of a ChromacityPlot3D in the CMYK (or other device) gamut projected in LAB color space, since it's perceptually uniform. My ultimate goal is to find the x most different print colors inside a luminosity range.
Here's the subset mesh I'm trying to relax points inside:
ChromaticityPlot3D["CMYK", "LAB", PlotRange -> {{.65, .82}, {-1, 1}, {-1, 1}}]
Successive application VoronoiMesh seems like the best way to solve this. I see another question applying this function iteratively, but I'm having trouble applying VoronoiMesh to the InputForm of ChromacityPlot3D.

A: I admit this is not the most elegant solution, but here is a function that I wrote which finds a solution of relaxed points in a colourspace (i.e. a constrained 3D vector space).
The function takes an initial point, a ChromaticityPlot3D object, the number of desired points, and the min and max constraints in all three dimensions (including the luminosity). It populates the space with random points and the essentially treats the points as identically charged particles confined within the specific region. So the points iteratively push each other around until they are as spread out as they can be.The function then returns the coordinates of all the points in colourspace.
I do have a clause at the end of the main while loop which helps shake things up (in case the solution gets stuck in a local maximum). It's a Monte Carlo method, so it's designed to be fast(ish), so it won't necessarily give the optimal answer. If you don't like the first answer it gives, change the random seed and run it again.
 RelaxedPoints[givenpoint_, chrmaticityplot3d_, npts_, lims_] :=
 Module[{iters = 1000, set, inc, region, points = {}, pnt, dm,
   vectors, magnitude, move, olddm = Table[Infinity, npts, npts],
   n = 0, m = 2, res, err, tol = 0.075, mean, ids, plt},
  set = Flatten[InputForm[chrmaticityplot3d][[1, 1, 1, ;; , 1]], 1];
  set = Reap[Do[
      inc =
       set[[i, 1]] > lims[[1, 1]] && set[[i, 1]] < lims[[1, 2]] &&
        set[[i, 2]] > lims[[2, 1]] && set[[i, 2]] < lims[[2, 2]] &&
        set[[i, 3]] > lims[[3, 1]] && set[[i, 3]] < lims[[3, 2]];
      If[ inc, Sow[set[[i]]]];
      , {i, 1, Length[set]}]][[2, 1]];
  region = ConvexHullMesh[set];

  pnt = givenpoint;
  If[! RegionMember[region, givenpoint],
   pnt = RegionNearest[region, givenpoint]];
  AppendTo[points, pnt];

  Do[
   pnt = RandomReal[{-1, 1}, 3];
   If[! RegionMember[region, pnt], pnt = RegionNearest[region, pnt]];
   AppendTo[points, pnt];
   , {i, 2, npts}];

  dm = DistanceMatrix[points];
  err = Total[Abs[dm - olddm], 2];
  While[err > tol && n < iters,
   vectors =
    Table[Normalize[points[[i]] - points[[j]]], {i, 1, npts}, {j, 1,
      npts}];
   magnitude = (1.0/(dm^2 + IdentityMatrix[npts] + 0.0001))/500.;

   move = magnitude*vectors;
   ids = Drop[Take[Ordering[#], Round[Log2[npts]*2]], 1] & /@ dm;

   Do[
    points[[i]] = points[[i]] + Total[move[[i, ids[[i]]]]];
    If[! RegionMember[region, points[[i]]],
     points[[i]] = RegionNearest[region, points[[i]]]]
    , {i, 2, npts}];

   If[n == 100*Fibonacci[m],
    ids = Ordering[Flatten[Drop[Take[Sort[#], 2], 1] & /@ dm]];
    If[ids[[1]] == 1,
     points[[ids[[2]]]] = Mean[points];,
     points[[ids[[1]]]] = Mean[points];
     ];
    m = m + 1;
    ];

   olddm = dm;
   n = n + 1;
   dm = DistanceMatrix[points];
   err = Total[Abs[dm - olddm], 2];
   ];
  Return[points];
  ]

Here is an example:
chplt = ChromaticityPlot3D["RGB", "LAB", FillingStyle -> Opacity[0.5]];
pt = {0.7, 0.1, 0.1};
regionlims = {{0.5, 0.7}, {-10, 10}, {-10, 10}};
pts = RelaxedPoints[pt, chplt, 9, regionlims];
Show[{chplt,
  Graphics3D[{PointSize[0.07], LABColor[#[[1]], #[[2]], #[[3]]],
      Point[#]} & /@ pts], Graphics3D[Point[#] & /@ pts]}]

Techniques that I used in to solve this problem include extracting the data set from the Plot object (using InputForm) and creating a Region object to work with (using ConvexHullMesh). Finally, it's not fool-proof so if you use if for something it's not designed for it might break.