text:
Q: Free resources for learning R I'm interested in learning R on the cheap. What's the best free resource/book/tutorial for learning R?

A: The official guides are pretty nice; check out http://cran.r-project.org/manuals.html . There is also a lot of contributed documentation there.

A: If you're an economist/econometrician then Grant Farnworth's paper on using R is indispensable and is available on CRAN at:
http://cran.r-project.org/doc/contrib/Farnsworth-EconometricsInR.pdf

A: If you have experience in other languages, these "R Rosetta Stone" videos may be useful:

*

*Python

*MATLAB

*SQL
These are all included in the video list added by Jeromy, so big +1 for his list.

A: One resource is 'Some hints for the R beginner' at
http://www.burns-stat.com/pages/Tutor/hints_R_begin.html

A: I have written a document that is freely available at my website and on CRAN. See the linked page:
icebreakeR
The datasets that are used in the document are also linked from that page.  Feedback is welcome and appreciated!
Andrew

A: After you learn the basics, I find the following sites very useful:

*

*R-bloggers.

*Subscribing to the Stack overflow R tag.

A: A large number of short videos that cover a lot of useful tasks with R (91 videos as of March 2013): http://www.twotorials.com/
Here's a nice new interactive online tutorial on the basics of R: http://tryr.codeschool.com/

A: Some useful R links (find out the link that suits you):
Intro:

*

*for R basics http://cran.r-project.org/doc/contrib/usingR.pdf

*for data manipulation http://had.co.nz/plyr/plyr-intro-090510.pdf

*http://portal.stats.ox.ac.uk/userdata/ruth/APTS2012/APTS.html

*Interactive intro to R programming language https://www.datacamp.com/courses/introduction-to-r

*Application focused R tutorial https://www.teamleada.com/tutorials/introduction-to-statistical-programming-in-r

*In-browser learning for R http://tryr.codeschool.com/
with a focus on economics:

*

*lecture notes with R code http://www.econ.uiuc.edu/~econ472/e-Tutorial.html

*A brief guide to R and Economics http://people.su.se/~ma/R_intro/R_intro.pdf
Graphics: plots, maps, etc.:

*

*tutorial with info on plots http://cran.r-project.org/doc/contrib/Rossiter-RIntro-ITC.pdf

*a graph gallery of R plots and charts with supporting code http://addictedtor.free.fr/graphiques/

*A tutorial for Lattice http://osiris.sunderland.ac.uk/~cs0her/Statistics/UsingLatticeGraphicsInR.htm

*Ggplot R graphics http://had.co.nz/ggplot2/

*Ggplot Vs Lattice @ http://had.co.nz/ggplot/vs-lattice.html

*Multiple tutorials for using ggplot2 and Lattice http://learnr.wordpress.com/tag/ggplot2/

*Google Charts with R http://www.iq.harvard.edu/blog/sss/archives/2008/04/google_charts_f_1.shtml

*Introduction to using RGoogleMaps @ http://cran.r-project.org/web/packages/RgoogleMaps/vignettes/RgoogleMaps-intro.pdf

*Thematic Maps with R https://stackoverflow.com/questions/1260965/developing-geographic-thematic-maps-with-r

*geographic maps in R http://smartdatacollective.com/Home/22052
GUIs:

*

*Poor Man GUI for R http://wiener.math.csi.cuny.edu/pmg/

*R Commander is a robust GUI for R http://socserv.mcmaster.ca/jfox/Misc/Rcmdr/installation-notes.html

*JGR is a Java-based GUI for R http://jgr.markushelbig.org/Screenshots.html
Time series & finance:

*

*a good beginner's tutorial for Time Series http://www.stat.pitt.edu/stoffer/tsa2/index.html

*Interesting time series packages in R http://robjhyndman.com/software

*advanced time series in R http://www.wise.xmu.edu.cn/2007summerworkshop/download/Advanced%20Topics%20in%20Time%20Series%20Econometrics%20Using%20R1_ZongwuCAI.pdf

*provides a great analysis and visualization framework for quantitative trading http://www.quantmod.com/

*Guide to Credit Scoring using R http://cran.r-project.org/doc/contrib/Sharma-CreditScoring.pdf

*an Open Source framework for Financial Analysis http://www.rmetrics.org/
Data / text mining:

*

*A Data Mining tool in R http://rattle.togaware.com/

*An online e-book for Data Mining with R http://www.liaad.up.pt/~ltorgo/DataMiningWithR/

*Introduction to the Text Mining package in R http://cran.r-project.org/web/packages/tm/vignettes/tm.pdf
Other statistical techniques:

*

*Quick-R http://www.statmethods.net/

*annotated guides for a variety of models http://www.ats.ucla.edu/stat/r/dae/default.htm

*Social Network Analysis http://www.r-project.org/conferences/useR-2008/slides/Bojanowski.pdf
Editors:

*

*Komodo Edit R editor http://www.sciviews.org/SciViews-K/index.html

*Tinn-R makes for a good R editor http://www.sciviews.org/Tinn-R/

*An Eclipse plugin for R @ http://www.walware.de/goto/statet

*Instructions to install StatET in Eclipse http://www.splusbook.com/Rintro/R_Eclipse_StatET.pdf

*RStudio http://rstudio.org/

*Emacs Speaks Statistics, a statistical language package for Emacs http://ess.r-project.org/
Interfacing w/ other languages / software:

*

*to embed R data frames in Excel via multiple approaches http://learnr.wordpress.com/2009/10/06/export-data-frames-to-multi-worksheet-excel-file/

*provides a tool to make R usable from Excel http://www.statconn.com/

*Connect to MySQL from R http://erikvold.com/blog/index.cfm/2008/8/20/how-to-connect-to-mysql-with-r-in-wndows-using-rmysql

*info about pulling data from SAS, STATA, SPSS, etc. http://www.statmethods.net/input/importingdata.html

*Latex http://www.stat.uni-muenchen.de/~leisch/Sweave/

*R2HTML http://www.feferraz.net/en/P/R2HTML
Blogs, newsletters, etc.:

*

*A very informative blog http://blog.revolutionanalytics.com/

*A blog aggregator for posts about R  http://www.r-bloggers.com/

*R mailing lists  http://www.r-project.org/mail.html

*R newsletter (old)  http://cran.r-project.org/doc/Rnews/

*R journal (current)  http://journal.r-project.org/
Other / uncategorized: (as of yet)

*

*Web Scraping in R http://www.programmingr.com/content/webscraping-using-readlines-and-rcurl

*a very interesting list of packages that is seriously worth a look http://www.omegahat.org/

*Commercial versions of R @ http://www.revolutionanalytics.com/

*Red R for R tasks http://code.google.com/p/r-orange/

*KNIME for R (worth a serious look) http://www.knime.org/introduction/screenshots

*R Tutorial for Titanic https://statsguys.wordpress.com/

A: The R project website has lots of manuals to start, and I suggest you the Nabble R forum and the R-bloggers site as well.

A: If you already know another programming language, these notes may help point out some of the ways R might surprise you.

A: I liked these lectures: Statistical Aspects of Data Mining. The lecturer is solving example problems using R.

A: If you are coming from a SAS or SPSS background, check out:
http://sites.google.com/site/r4statistics/
This is the companion site to the book, R for SAS and SPSS Users by Robert Muenchen and a free version of the book can be found here.

A: One more:  R bloggers has many posts with tutorials materials:
http://www.r-bloggers.com/?s=tutorial

A: If I had to choose one thing, make sure that you read "The R Inferno".
There are many good resources on the R homepage, but in particular, read "An Introduction to R" and "The R Language Definition".

A: There are some very good learning materials here: http://scc.stat.ucla.edu/mini-courses/materials-from-past-mini-courses/spring-2009-mini-course-materials/

A: Look for R Users Groups in your area.  They are growing around the world.
http://blog.revolutionanalytics.com/local-r-groups.html
If you don't have one then help get one started.  I'm sure you will be able to find like minded interested folks.
As for helpful links the Dallas R Users Group has a nice list.
http://www.meetup.com/Dallas-R-Users-Group/pages/R_Helpful_Links/

A: http://www.datamind.org offers interactive R tutorials, currently focused at real beginners

A: Quick-R can be a good place to start.
A little bit data mining oriented R and Data Mining resources: Examples and Case Studies and R Reference Card for Data Mining.

A: *

*If you like learning through videos, I collated a list of R training videos.

*I also prepared a general post on learning R with  suggestions on books, online manuals, blogs, videos, user interfaces, and more.

A: Try IPSUR, Introduction to Probability and Statistics Using R. It's a free book, free in the GNU sense of the word.
http://ipsur.r-forge.r-project.org/book/index.php
It's definitely open source - on the download page you can download the LaTeX source or the lyx source used to generate this.

A: If you'd like a beginners tutorial to R in the context of Econometrics this may be a good starting point as well: http://www.quandl.com/learn/working-with-quandl-and-r


text:
Q: anchor links doesen't link to url can anyone help me figure out what's wrong with the code? links   not working, if you click on it nothing happens. I thought I left some tags open but I checked with https://validator.w3.org and there are no such errors! What could be the problem?
I have seen the other questions and answers related to this topic but they did not help me.
note: navigate to "i miei lavori" page or "my work" page
link:
minimal reproducible example
html
<!DOCTYPE html>

    <meta charset="utf-8" />
    <link rel="stylesheet" href="style.css" />
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Poppins">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <meta name="viewport" content="width=device-width">
    <title>i miei lavori - Andrea</title>

        <button class="pulsanti-menu" name="btnchisono" onclick="chisonoPage()">chi sono</button>
        <button class="pulsanti-menu" style="color:blue;" name="btnlavori" onclick="lavoriPage()">i miei lavori</button>
        <button class="pulsanti-menu" name="btncuriosita" onclick="curiositaPage()">curiosità</button>

        <button class="btn-language" onclick="changeLanguage()"></button>

Lavori svolti per svago anni fà

"Firewall", un trojan per mIRC

Correva l'anno 2000, avevo da poco avuto accesso a internet, avevo una connessione 56k flat 12/24 con Libero@Sogno, ero affascinato da alcuni degli script di mIRC, il celebre programma di chat, molto gettonato in rete in quegli anni e ne provai alcuni, così per curiosità mi misi a leggere il codice sorgente degli script ".ini", fu così che iniziò il mio viaggio nel mondo della programmazione.

La mia prima creazione fù un trojan che chiamai "firewall", per ovvie ragioni di ingegneria sociale di cui parlerò più avanti. Il Trojan era composto da uno script che era caricato nel mio client, che inviava i comandi da eseguire sul client della vittima che avrebbe dovuto caricare lo script malevolo sul proprio mIRC ma le fondamenta del trojan era la direttiva "onNotice", un evento che veniva generato quando si riceveva un messaggio particolare, il notice appunto. Di default questi messaggi erano nascosti, il client li riceveva, li elaborava ma l'utente era ignaro di averlo ricevuto, per questo motivo lo scelsi. Lo script che era caricato nel mio client mIRC non faceva altro che inviare un "notice" criptato alla vittima, bastava aprire un canale privato con l'utente target per avere accesso alle funzioni.

C'erano funzioni standard per cambiare nick alla vittima, scrivere messaggi al suo posto e disconnetterla dal server con messaggi particolari, di solito quando c'era una disconnessione del client appariva un messaggio di questo genere "connection reset by peer", al posto di "peer" erano disponibili vari nomi tra cui Babbo Natale(connection reset by Babbo Natale), divertente!. Potevo scrivere messaggi su canali e chat private al posto del malcapitato e potevo cambiarli nick ma la feature più potente era poter eseguire qualsiasi direttiva sulla macchina vittima. La cosa più difficile di questo sistema era convincere la vittima a caricare lo script sul proprio client, da qui il nome che ho scelto per il trojan, "Firewall", c'era molta ignoranza informatica in quegli anni ma molti degli internauti sapeva cosa era un firewall e lo avrebbe caricato più facilmente.

Detto questo ci fù solo una vittima di questo trojan, un mio amico di chat che si fidò ciecamente di me e lo convissi molto facilmente a installare "Firewall". Tuttavia il divertimento durò poco, li cambiai nick un paio di volte, scrissi qualche parolaccia, feci coming-out al posto suo su dei canali pubblici e lo disconnettei diverse volte ma ero così orgoglioso del mio lavoro che per vantarmi li dissi tutto e subito e così dandomi della merda disinstallò lo scrip. Rimane ad oggi l'unica vittima di Firewall. Condividerei il codice sorgente ma è andato perduto negli anni.

Windows 98, mIRC scripting

Convertitore da .wav a .mp3

Erano i primi anni 2000, avevo circa 16/17 anni ed era consuetudine rivoltare i CD musicali nel computer per poter creare le proprie playlist. Windows Media Player in quegli anni creava file wav quando si eseguivano queste operazioni e si sa che il formato wav è molto pesante rispetto agli mp3 e gli HD non erano molto capienti. Così sentii la necessità di un convertitore, cercai in internet e trovai una libreria per convertire, aprii il mio VB6 con cui smanettavo da poco tempo e scrissi qualche linea di codice. Il programma prevedeva una navigazione nelle cartelle di sistema per scegliere quali file convertire, una volta selezionati si avviava la conversione e venivano creati i files mp3 con gli stessi nomi degli originali. È stato veramente semplice utilizzare la libreria, bastava impostare alcune configurazioni e richiamare la funzione di conversione con i dovuti parametri.

Windows ME, Visual Basic 6

Sondaggio scolastico

Frequentavo il II anno del Liceo Scientifico del mio paese, il Preside aveva fatto distribuire dei fogli che avrebbero costituito un sondaggio ma non ricordo i temi trattati. Era complicato analizzare i dati delle risposte di tutti gli alunni a mano così mi chiese se potevo scrivere un programma che raccogliesse i dati e li elaborasse.

Allora non ero a conoscenza dell'esistenza di SQL ne sapevo a cosa servisse Access di Microsoft così mi venne in mente di immagazzinare i dati nelle celle dei fogli Excel, usai le librerie di Visual Basic 6 per accedere ai fogli di calcolo, MSDN era la mia fonte principale di informazione per sviluppare.

Mi divertii molto a creare questa applicazione, credevo che avrei ricevuto dei compensi scolastici, crediti formativi o un'incremento dei voti in matematica(in cui andavo già bene) ma l'unica cosa che ricevetti è stato l'incremento della mia esperienza(ben venga sempre) e un grazie dal Preside.

Windows XP, Visual Basic 6, Excel

Formattatore files .csv

È stato molto semplice sviluppare questa applicazione. Avevo bisogno di formattare dei files csv composti da tantissime righe, era impossibile farlo a mano così lessi qualche tutorial del C++ e da lì a poco mi misi a scrivere righe di codice. Leggendo i tutorial riuscii a capire anche i puntatori e feci qualche applicazione che li utilizzava ma era per solo scopo didattico. Ora per essere sincero non ricordo quasi nulla di questo fantastico linguaggio dal momento che è stata la prima e l'ultima volta che lo utilizzai.

GNU Linux Debian, C++

Indicatori su piattaforma di trading

Negli anni 2012/2013 circa mi accanii nel trading online e utilizzavo la piattaforma Metatrader4, ore e ore di studio di molta analisi tecnica. Una volta acquisite le conoscenze cercai di supplire alla mancanza di indicatori per il volume di scambi nel forex e non solo. Di indicatori ed oscillatori ce ne erano molti ma mi accorsi che mancava qualcosa e mi misi a lavoro. Sinceramente ora non ricordo bene cosa facessero questi indicatori, nel codice sorgente di alcuni di essi c'è una valore Delta che non ricordo proprio cosa sia. Comunque questi indicatori come già detto misuravano il volume di scambi e quindi un bilanciamento tra domanda e offerta e ce ne sono alcuni che mi servivano per gestire il money management. Di questi ho il codice sorgente, perdonatemi se qualche file risulta poco leggibile ma quando l'ho scritto dovevo programmare da un decennio circa.

VSA CumulativeDelta 0.1.mq4

VSA PriceDelta Correlation v.0.1.mq4

VSA PriceVolume Correlation v.0.4.mq4

VSA Volume Percentage v.1.5.mq4

    MM RiskControl v2.1.mq4

Windows XP, MetaTrader4 Language

Alla ricerca dell'olio essenziale

Avevo acquistato da poco una enciclopedia degli olii essenziali, ancora la possiedo, è ben fatta, ci sono descrizioni dettagliate di molti olii, nelle descrizioni ci sono le proprietà e gli antichi usi nella erboristeria popolare e molte altre informazioni, inoltre ci sono delle sezioni in cui puoi ricercare l'olio essenziale per proprietà, ad esempio se cerchi la voce antinfiammatorio puoi trovare nell'elenco l'olio di eucalipto. Perchè non portare in digitale questo sistema e magari migliorarlo anche?

Così mi misi a lavoro, scelsi Gambas per sviluppare l'applicazione, aveva tutte le caratteristiche di cui avevo bisogno, e come database mi sono appoggiato a mySQL. Oltre che un'interfaccia per inserire gli olii e le loro proprietà c'era la parte più importante dell applicazione che consisteva nell'inserire una o più proprietà nella barra di ricerca. Così venivano fuori per primi gli olii che possedevano tutte quelle proprietà, mentre secondariamente erano elencati gli olii che possedevano solo alcune delle proprietà cercate.

Tra le svariate reinstallazioni, backup incompleti e pc bruciati l'applicazione è andata perduta, mi sarebbe piaciuto poterla condividere in rete.

GNU Linux Debian, Gambas

Lavori svolti recentemente con Angular

NGRX Store Demo

Questa demo mostra il funzionamento basilare di ngrx, cioè mostra l'uso di actions, reducers e selector. Inserendo i dati nel form viene aggiornato l'utente nello store.

            github
            stackblitz

GNU Linux Debian 10, TypeScript, Angular, NGRX

NGRX Entity Demo

Questa demo è stata sviluppata per mostrare il funzionamento delle entity in ngrx, ovviamente usa anche actions, reducers e selectors. È possibile aggiungere gli utenti tramite il form che verranno presentati e ordinati secondo l'età.

            github
            stackblitz

GNU Linux Debian 10, TypeScript, Angular, NGRX

NGRX Effects and Entity Demo

In questa demo utilizzo per la prima volta gli Effects che vanno prima a modificare i dati mock per simulare un cambiamento nel database, se l' aggiornamento dei dati mock ha successo si andranno a modificare anche i dati nello store, in caso contrario viene lanciata l'action di errore di inserimento. Dall' interfaccia ui è possibile aggiungere gli utenti che saranno listati in ordine di età.

            github
            stackblitz

GNU Linux Debian 10, TypeScript, Angular, NGRX

NGRX Chain of Responsibility Demo

In questa demo viene affrontato il discorso del pattern della delegazione di responsabilità.Sostanzialmente il componente conteiner si occupa di quasi tutta la logica e il resto dei componenti sono solo di presentazione, ad eccezione del componente per dare il rating nel quale c'è una funzione per la visualizzazione delle stelle di rating e per l'emissione del nuovo rating che scalando la gerarchia dei componenti arriverà fino al componente conteiner che farà il dispatch dell' azione di inserimento rating. I dati da osservare hanno lo stesso funzionamento, al cambiare dei dati nello store, essi vengono passati tramite le proprietà di input ai componenti figli.

            github
            stackblitz

GNU Linux Debian 10, TypeScript, Angular, NGRX

rxjs combineLatest Demo

Non c' è molto da dire su questa demo, mostra l'uso dell' operatore rxjs combineLatest, combina due observable e restituisce un observable di array di oggetti.

            github
            stackblitz

GNU Linux Debian 10, TypeScript, Angular

Change Detection Strategy Default Demo

La CD di default praticamente viene sempre eseguita, qualsiasi pulsante viene cliccato, quindi si renderizzano i componenti ma individua i cambiamenti dell' oggetto solo nel caso si clicchi "Change Object Reference".

            github
            stackblitz

GNU Linux Debian 10, TypeScript, Angular

Change Detection Strategy OnPush Demo

Nel caso della CD OnPush, che si usa solo per i componenti children, le proprietà di @Input vengono renderizzate solo nel caso in cui l'oggetto cambi referenza, nel caso in cui viene modificata solo la proprietà dell' oggetto il dato non viene renderizzato perché la CD non individua cambiamenti.

            github
            stackblitz

GNU Linux Debian 10, TypeScript, Angular

Angular Security Sanitization Demo

Questa è una demo per provare una feature di sicurezza in Angular, il contenuto interpolato non è interpretato e viene renderizzato completamente mentre usando innerHTML il contenuto viene interpretato e sanificato.

            github
            stackblitz

GNU Linux Debian 10, TypeScript, Angular

Angular Animations Owl Carousel Demo

Questa è una demo di un owl carousel, tipo quelle che si vedono su ebay o amazon, per gli oggetti visti di recente oppure per gli oggetti correlati.

            github
            stackblitz

GNU Linux Debian 10, TypeScript, Angular

Cars Market Place

Questo è il primo progetto che ho realizzato con Angular, senza contare "helloworld" e altre ormai insignificanti demo. Non avrei voluto pubblicarlo su github perchè essendo la prima esperienza con Angular il codice non è il massimo, le best pratice non sono tutte rispettate e ci sono altre questioni, un refactor non è pensabile, insomma come prima esperienza va piu che bene ma non bisogna fare molto caso alla forma, non è neanche completato del tutto, inoltre voglio ribadire che non sono un designer quindi il design non è apprezzabile.

Con firefox sul mio pc il design è corretto ma con stackblitz su firefox è sballato, problema di stackblitz, usa Chrome per visualizzare la demo in stackblitz. Loggati con user e password "StanfRei"

È un e-commerce in "stile e-bay" l'utente può comprare e vendere auto ma la funzione di vendita è stata disattivata in questa demo. La gallery presenta le auto in vendita da vari utenti, con il prezzo pieno e scontato e il rating di altri compratori, c'è il pulsante per osservare l'auto o rimuovere l'interesse. Sul lato sinistro ci sono le auto viste di recente, solo in caso di login effettuato. Le altre sezioni disponibili sul menu, se effettuato l'accesso, sono 'Observed Cars' e 'UserProfile', in quest' ultima è possibile inserire lo sconto per le auto messe in vendita dall' utente loggato. Tramite le card delle auto nella Gallery è possibile raggiungere sezioni dove è possibile comprare l' auto e dare un rating, oppure vedere le auto simili a quella selezionata. Come puoi aver capito ci sono delle guardie che limitano gli accessi a delle sezioni dell' app. Usa i dati mock, se si usasse un backend reale e ci fossero degli errori, sarebbero visualizzati a schermo, vengono intercettati dall' error interceptor e passati a un servizio, iniettato e gestito dal componente navbar.

            github
            stackblitz

GNU Linux Debian 10, (NodeJS), TypeScript, Angular

andreadicioccio1983@gmail.com

css
    *{
    font-family: 'Poppins';
    z-index: -1;
}

body{
    background-color:white;
    text-align:center;
    margin: 0;
}

p {
    font-size:1em;
    text-align:justify;
}

.scrollTop{
    position: fixed;
    right: 50px;
    bottom: 50px;
    z-index: 0;

}

.scrollTop:hover{
    cursor: pointer;
}

.specchietto-menu{
    text-align:center;
}

.pulsanti-menu{
    background-color:white;
    border:solid 1px lightgrey;
    font-size:1em;
    height:2em;
    width:7em;
    margin-top: 10px;
}

.pulsanti-menu:hover{
    cursor: pointer;
}

div.contenitore{
    text-align:center;
}

.choose-language{
    position: absolute;
    right: 5px;
    top: 10px;
    z-index: 0;
}

.btn-language{
    background-color: white;
    border: 0;
}

.presentazione-lavori{
    font-size: 26px;
    text-align:center;
}

div.specchietto-articolo{
    text-align:left;
    width:465px;
    position: relative;
    display: inline-block;
}

p.titolo-articolo {
    font-size:24px;
    text-align:center;
}

p.articolo{
    padding: 5px;
}
.contenitore-email{
    text-align:right;
    background-color:white;
    width: 100%;
    /*position: static;*/
    /*right: 0px;
    left: 0px;*/
}

@media screen and (max-width: 450px) {

    .pulsanti-menu{
        font-size: small;
        width: 100px;
    }

    .choose-language{
        position: absolute;
        right: 5px;
        top: 50px;
    }

    .presentazione-lavori{
        font-size: 20px;
    }

    p.titolo-articolo{
        font-size: 18px;
    }

    .specchietto-articolo{
        width:100% !important;
    }

    p.articolo{
        font-size: small;
    }

}

A: It's because of the z-index in your css. Links with negative z-index are unclickable, its better to remove the z-index: -1 from your *-selector.
Or you can add an additional selector for the -Tags to your style:
a {
  z-index: 1;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: iOS function to be called once (when application is initialized) I have an iOS application. Application has 2 different views: Main and Settings. In fact, application needs to load and initialize some library and framework before it is used in Main View.
When I put this initialization in viewDidLoad method, it works OK. But when go to Settings and come back to Main View, initialization starts again, which is not what I want, and application results in a memory problem.
I need an method that is called once when application is started. Any idea?
EDIT: I switched to tabbed view. It loads views once. This is another solution.

A: Use this one:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

It should be in your appdelegate class.
Hope it helps

A: You state in one of your comments that you don't want to put this code in application:didFinishLaunching and you want to keep it in viewDidLoad. You can use this snippet to run your code only the first time is is invoked:
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
    // code here
});

The inner block will only be executed once. If the view is loaded again, the block is not called. Note that there is an Xcode code snippet for this which you can access by starting to type dispatch_once in the editor:

A: You can also use
+ [NSObject initialize]

Define a class method of that name, and it will be run once before any other messages are sent to that class:
+ (void)initialize {
  // Put one-time initialization code here.
}

https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/nsobject_Class/Reference/Reference.html#//apple_ref/occ/clm/NSObject/initialize

A: In your AppDelegate, one of the objects guaranteed to have only one instance (singleton) throughout the app, you can declare an instance variable/property:
BOOL initialized;
And then in viewDidLoad of your UIViewController, you check if it's the code has been initialized; if not, then run the code and set the variable to true:
 if (!initialized) {
    // Code goes here
    initialized = true;
 }


text:
Q: VBA-equivalent to pressing "tab" inside a textbox or shape? I have a PowerPoint presentation called from Excel and want to change the text in one of the shapes. It's a table of contents and when I do it manually, I can write the text on the left, press tab once and the cursor jumps to the far right where I can write "Page". How do I do this with VBA, the "tab" part? I know I can write into a shape like this:
myPresentation.Slides(2).Shapes("shp2").TextFrame.TextRange.Text = "Development of X in Year 2019"

My workaround is that replace the part I wanna change, which is the year:
myPresentation.Slides(2).Shapes("shp1").TextFrame.TextRange.Text = Replace(myPresentation.Slides(2).Shapes("shp1").TextFrame.TextRange.Text, "2019", yearVariable)

But if someone manually deletes or changes the year, it doesn't work anymore so I don't want to use this.

A: Do you mean just using vbTab?
myPresentation.Slides(2).Shapes("shp2").TextFrame.TextRange.Text = "Development of X in Year" & vbTab & "2019"


text:
Q: Unable to Connect to BigQuery from local App Engine instance in Eclipse I'm new to Google App Engine and I'm trying to run through some of the tutorials to see how this would work for my organization.  We are looking at putting some of our data into BigQuery and converting some of our Web applications to App Engine which would need to access BigQuery data.
I am using the java-docs-samples-master code, specifically bigquery/cloud-client/src/main/java/com/example/bigquery/SimpleApp.java
I can run this from the command line using

mvn exec:java -Dexec.mainClass=com.example.bigquery.SimpleAppMain

I incorporate the code into App Engine, which I'm running in Eclipse and created a wrapper so I could still run it from the command line.  It works when running from the command line but I get an error when I run it from App Engine in Eclipse.
Is there something I'm missing to configure my local App Engine to connect to Big Query?
Error:
com.google.cloud.bigquery.BigQueryException: Invalid project ID 'no_app_id'. Project IDs must contain 6-63 lowercase letters, digits, or dashes. IDs must start with a letter and may not end with a dash.
at com.google.cloud.bigquery.spi.v2.HttpBigQueryRpc.translate(HttpBigQueryRpc.java:86)
at com.google.cloud.bigquery.spi.v2.HttpBigQueryRpc.create(HttpBigQueryRpc.java:170)
at com.google.cloud.bigquery.BigQueryImpl$3.call(BigQueryImpl.java:208)
...
Caused by: com.google.api.client.googleapis.json.GoogleJsonResponseException: 400
{ "code" : 400,
  "errors" : [ {
    "domain" : "global",
    "message" : "Invalid project ID 'no_app_id'. Project IDs must contain 6-63 lowercase letters, digits, or dashes. IDs must start with a letter and may not end with a dash.",
    "reason" : "invalid"
  } ],
  "message" : "Invalid project ID 'no_app_id'. Project IDs must contain 6-63 lowercase letters, digits, or dashes. IDs must start with a letter and may not end with a dash."
}

Code:
package com.example.bigquery;

import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQueryOptions;
import com.google.cloud.bigquery.FieldValue;
import com.google.cloud.bigquery.Job;
import com.google.cloud.bigquery.JobId;
import com.google.cloud.bigquery.JobInfo;
import com.google.cloud.bigquery.QueryJobConfiguration;
import com.google.cloud.bigquery.QueryResponse;
import com.google.cloud.bigquery.QueryResult;

import java.util.List;
import java.util.UUID;

public class SimpleApp {
  public void runBQ() throws Exception {
    // [START create_client]
    BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
    // [END create_client]
    // [START run_query]
    QueryJobConfiguration queryConfig =
        QueryJobConfiguration.newBuilder(
                "SELECT "
                    + "APPROX_TOP_COUNT(corpus, 10) as title, "
                    + "COUNT(*) as unique_words "
                    + "FROM `publicdata.samples.shakespeare`;")
            // Use standard SQL syntax for queries.
            // See: https://cloud.google.com/bigquery/sql-reference/
            .setUseLegacySql(false)
            .build();

    // Create a job ID so that we can safely retry.
    JobId jobId = JobId.of(UUID.randomUUID().toString());
    Job queryJob = bigquery.create(JobInfo.newBuilder(queryConfig).setJobId(jobId).build());

    // Wait for the query to complete.
    queryJob = queryJob.waitFor();

    // Check for errors
    if (queryJob == null) {
      throw new RuntimeException("Job no longer exists");
    } else if (queryJob.getStatus().getError() != null) {
      // You can also look at queryJob.getStatus().getExecutionErrors() for all
      // errors, not just the latest one.
      throw new RuntimeException(queryJob.getStatus().getError().toString());
    }

    // Get the results.
    QueryResponse response = bigquery.getQueryResults(jobId);
    // [END run_query]

    // [START print_results]
    QueryResult result = response.getResult();

    // Print all pages of the results.
    while (result != null) {
      for (List<FieldValue> row : result.iterateAll()) {
        List<FieldValue> titles = row.get(0).getRepeatedValue();
        System.out.println("titles:");

        for (FieldValue titleValue : titles) {
          List<FieldValue> titleRecord = titleValue.getRecordValue();
          String title = titleRecord.get(0).getStringValue();
          long uniqueWords = titleRecord.get(1).getLongValue();
          System.out.printf("\t%s: %d\n", title, uniqueWords);
        }

        long uniqueWords = row.get(1).getLongValue();
        System.out.printf("total unique words: %d\n", uniqueWords);
      }

      result = result.getNextPage();
    }
    // [END print_results]
  }
}

A: From the looks of your error code, it's probably due to your project ID not being set: "no_app_id". Here is how to set your project ID for app engine: https://developers.google.com/eclipse/docs/appengine_appid_version.

A: Not sure if I am late, but I encountered such error while working with Firestore and it was due to no project being set on the 'Cloud Platform' tab in App Engine run configuration. When I logged into an account and selected a project ID, this error went away.


text:
Q: Unable to update the Cursor of Database when using BaseAdapter for ListView After going through many tutorials i successfully implemented the database in my android application and everything is working fine except for one thing. My application is built to receive the text message(SMS) and store them in database and also populate them on the ListView. When the application receives the message, the database is updated but the listview is not updated in that instance, but after restaring the app the listview will be populated with all the received data in the database. Please help me sort this problem.
here is my code snippet:
Main class
    import android.os.Bundle;
    import android.widget.ListView;
    import com.example.bhash.database.Adapter;
    import com.example.bhash.database.MessageData;
    import com.example.bhashsms.adapters.DrawerAdapter;
    import com.jeremyfeinstein.slidingmenu.lib.app.SlidingActivity;

    public class Main extends SlidingActivity {
        ListView dList, mList;
        DrawerAdapter dAdapter;
        static MessageData db;
        static Adapter adapter;

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            setBehindContentView(R.layout.drawer);
            init();
            db = new MessageData(Main.this);

            adapter = new Adapter(this);
            mList.setAdapter(adapter);

        }

        private void init() {
            getSlidingMenu().setBehindOffset(100);
            dList = (ListView) findViewById(R.id.drawerlist);
            mList = (ListView) findViewById(R.id.mainlist);
        }

        public static void update(String number, String body) {
            // adapter.list.add(new Person_Data(number, body));
            try {

                db.open();
                db.createEntry(number, body);
                db.close();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            adapter.notifyDataSetChanged();

        }

    }

databasehelper class:
    public class MessageData {

        public static final String KEY_ROWID = "_id";
        public static final String KEY_NUMBER = "phone_number";
        public static final String KEY_MESSGAE = "message";

        private static final String DATABASE_NAME = "Message";
        private static final String DATABASE_TABLE = "SMS";
        private static final int DATABASE_VERSION = 1;
        private Helper helper;
        private Context ourContext;
        private SQLiteDatabase ourDatabase;

        public MessageData(Context c) {
            // TODO Auto-generated constructor stub
            ourContext = c;

        }

        private static class Helper extends SQLiteOpenHelper {

            public Helper(Context context) {
                super(context, DATABASE_NAME, null, DATABASE_VERSION);
                // TODO Auto-generated constructor stub
            }

            @Override
            public void onCreate(SQLiteDatabase db) {
                // TODO Auto-generated method stub
                try {
                    db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" + KEY_ROWID
                            + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_NUMBER
                            + " TEXT NOT NULL, " + KEY_MESSGAE + " TEXT NOT NULL);");
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            @Override
            public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
                // TODO Auto-generated method stub
                try {
                    db.execSQL("DROP TABLE IF EXIST " + DATABASE_TABLE);
                    onCreate(db);
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

        }

        public MessageData open() {
            helper = new Helper(ourContext);
            ourDatabase = helper.getWritableDatabase();
            return this;
        }

        public void close() {
            helper.close();
        }

        public long createEntry(String number, String message) {
            ContentValues cv = new ContentValues();
            cv.put(KEY_NUMBER, number);
            cv.put(KEY_MESSGAE, message);
            return ourDatabase.insert(DATABASE_TABLE, null, cv);

        }

        public List<Person_Data> getData() {
            String[] columns = new String[] { KEY_ROWID, KEY_NUMBER, KEY_MESSGAE };
            Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null,
                    null, null);

            // int iRow = c.getColumnIndex(KEY_ROWID);
            int iNumber = c.getColumnIndex(KEY_NUMBER);
            int iMessage = c.getColumnIndex(KEY_MESSGAE);
            Log.i("coaunt value",c.getCount()+"");
            List<Person_Data> list = new ArrayList<Person_Data>();
            c.moveToFirst();

            for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {

                list.add(new Person_Data(c.getString(iNumber), c
                        .getString(iMessage)));

            }
            c.close();
            return list;

        }

    }

Adapterclass:
    public class Adapter extends BaseAdapter {
        Context c;
        LayoutInflater inflaterr;
        public List<Person_Data> list = new ArrayList<Person_Data>();

        public Adapter(Context c) {
            this.c = c;
            MessageData md = new MessageData(c.getApplicationContext());
            md.open();
            Person_Data datatData;
            list = md.getData();
            Log.i("dasdasdad", list.size()+"");
            md.close();
            inflaterr = LayoutInflater.from(this.c);
            // TODO Auto-generated constructor stub
        }
        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            ViewHolder holder = null;
            View singleview = convertView;
            if (convertView == null) {

                singleview = inflaterr.inflate(R.layout.main_list_view, parent,
                        false);
                holder = new ViewHolder(singleview);
                singleview.setTag(holder);
            }

            else {
                holder = (ViewHolder) singleview.getTag();

            }
            final Person_Data data = list.get(position);
            holder.Number.setText(data.Number);
            holder.callme.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    ExtractNumber(data.Message);

                }

                private void ExtractNumber(String src) {
                    StringBuilder builder = new StringBuilder();
                    int j = src.length();
                    for (int i = 0; i < j; i++) {
                        char c = src.charAt(i);
                        if (c == '+') {
                            builder.append(c);
                            for (int k = i; k < j; k++) {
                                char r = src.charAt(k);
                                if (!Character.isDigit(r)) {
                                    i = k;
                                    break;
                                }
                                builder.append(r);
                            }
                            if (builder.toString().length() > 8
                                    && builder.toString().length() < 14)
                                break;
                        }
                    }

                    Intent callIntent = new Intent(Intent.ACTION_CALL);
                    callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    callIntent.setData(Uri.parse("tel:" + builder.toString()));
                    c.startActivity(callIntent);
                }

            });
            return singleview;
        }

        class ViewHolder {
            TextView Number, time;
            ImageView callme;

            public ViewHolder(View v) {
                // TODO Auto-generated constructor stub
                Number = (TextView) v.findViewById(R.id.rNum);
                callme = (ImageView) v.findViewById(R.id.callbutton);

            }
        }
    }


text:
Q: Method 'Range' of object'_Worksheet' failed reason? 1 I am writing a code to populate my combobox (Question_Num) using a defined name. My defined name is stored in str3. I'm very new to VBA. When I run the program it gives run time error

method range of object _worksheet failed

I don't know what I am doing wrong
this is where the program hangs...Set rngPage = ws.Range(str3)
Private Sub loadPage()

   Dim rngPage As Range
   Dim ws As Worksheet
   Dim str1 As String, str2 As String, str3 As String

      Set ws = Worksheets(Year_Combine.Value)
      Sheets(Year_Combine.Value).Activate

      str1 = Left(Year_Combine.Value, 4)
      str2 = Right(Year_Combine.Value, 1)
      str3 = "PageNum_" & str1 & "_" & str2

      Set rngPage = ws.Range(str3)

       For Each rngPage In ws.Range(str3)
            Me.Question_Num.AddItem rngPage.Value
       Next rngPage

End Sub

A: That is because you are not giving a valid range.
The Range method receives a range of Cells as an argument, for example, "A1" if you are referring to the first cell in a worksheet, or "A1:B1" if you want to refer to the first 2 horizontal cells.
You can check the following link for more information on how to use the .Range method.
https://learn.microsoft.com/en-us/office/vba/api/excel.range(object)


text:
Q: How to find all the documents in my collection in Solr, for which the length of a certain field is within a certain limit? I have to find all the documents where the size of a certain field, is within a certain limit, in fact within a range. Is there a way to do this Solr.
I have tried a lot of permutations and combinations, so any help will be appreciated.
Thanks in advance.

A: Which API are you using to communicate with Solr? I think you have a better chance of going around this on client side (ie on Solrj as a java regex filter function, or if its a web application communicating with solr through a http request this can be done through javascript). I would add this as a comment but I dont have enough rep.


text:
Q: Curious sequences associated to continuous fractions Given a strictly positive initial rational number $x_0$ in $\mathbb Q_>$
we define a sequence $x_0,x_1,\ldots$ recursively by
setting $x_{n+1}=x_n+1/S(x_n)$
for $S(x)=a_0+a_1+\ldots+a_k$
where $[a_0;a_1,\ldots]$ is the rational fraction expansion of
$x=a_0+1/(a_1+1/\ldots)$. (A rational number has of course two such expansions with equal sums.)
The rational sequence $x_0,x_1,\ldots$ is clearly increasing and converges therefore to a limit $L(x_0)$ in $(0,\infty)\cup\lbrace +\infty\rbrace$.
Experimentally one gets a curious behaviour: For simple rational values of $x_0$, the limit $L(x_0)$ is either an integer (and convergency is extremely fast: at some stage, the number of digits of $S(x_i)$ essentiantly doubles at each iteration) or convergency is slow and $L(x_0)$ can not be guessed numerically.
A few preimages of $L$ for small integers are:
$$L^{-1}(1)\supset\lbrace 1/5,2/5,3/7,4/7\rbrace,$$
$$L^{-1}(2)\supset\lbrace 3/2,4/3,7/4,7/5\rbrace,$$
$$L^{-1}(3)\supset\lbrace 1,2,1/2,1/3,2/3,1/4,3/4,3/5,4/5,5/2,1/6,5/6,5/7,6/7\rbrace,$$
$$L^{-1}(4)\supset\lbrace 3,7/2\rbrace.$$
A few initial values with bad convergency are $4,5,7,8,9,1/7,2/7,7/3,7/6$.
Can one say something interesting
about the set of values $L(\mathbb Q_>)$?
Remark: For negative rational values $x_0$ one gets sometimes into trouble (division by $S(x_i)=0$ at some stage). In the remaining cases the sequence $x_0,x_1,\ldots$ is no longer
increasing and can be eventually periodic: $x_0=-3$ leads to
$$-3,-10/3,-13/3,-29/6,-23/6,-10/3,\ldots\ .$$


text:
Q: POST responses not compressed despite Accept-Encoding Header being present in a request I have encountered a strange case. I am working with a Spring Boot application which consists of a few different services.
For each service, in a application.properties file, those properties were added:
server.compression.enabled=true
server.compression.mime-types=application/json,application/xml,text/html,text/xml,text/plain,application/javascript,text/css
server.compression.min-response-size=1024

Now, it should work that every appropriate request contains "Accept-Encoding" header and response contains "Content-Encoding" header, and the response should be compressed.
It it almost works like that, but for one service POST responses do not contain "Content-Encoding", even though POST requests contain "Accept-Encoding". Such responses are not compressed, so it's not only about missing headers. GET responses/requests for this service work fine. Both GET/POST requests/responses for the rest of services work fine too.
This particular service's Spring Boot version is 1.5.16.RELEASE.
Where should I look for the cause? Can this setting be overwritten somehow for POST responses only?
Update: I also noticed that in POST responses for this service, "Vary: Accept-Encoding" header is missing. It's present in all other cases.

A: Try to change wiremock dependency configuration from compile to testCompile. In my case, wiremock in 2.22.0 version (with compile) caused this issue.


text:
Q: Nginx image_filter does not resize after proxy_pass to remote image I'm trying to resize remote image on the fly
location ~^/photo/thumb/   {
    rewrite ^/photo/thumb/(\d+)x(\d+)/(.+)$ /photo/original/$3 break;

    proxy_pass  http://remote.url:80;
    proxy_set_header Host      $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_buffer_size 512k;
    proxy_buffers 16 512k;

    image_filter resize $1 $2;
}

but the image returned is unchanged. I've tried to hardcode dimensions but image remained unchanged. What am I doing wrong?

A: I made it work - rewrite was the biggest problem and you need to proxy_pass to exact URL. I.e. this works for me:
location ~^/photo/thumb/(\d+)x(\d+)/(.+)$   {
    proxy_pass  http://remote.url:80/photo/original/$3;
    proxy_set_header Host      $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_buffer_size 512k;
    proxy_buffers 16 512k;

    image_filter resize $1 $2;
}


text:
Q: No graph is being displayed I am running this code and getting nothing in output. There is no error in the buildup but I am not able to find out the mistakes. Can anyone tell me what could be the issue?? Regards
  <!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />

    <script src="Dependencies/Angular/angular.js"></script>
    <script src="Dependencies/D3/d3.js"></script>
    <script src="Dependencies/nvd3/nv.d3.js"></script>
    <script src="Dependencies/Angularjs-nvd3-Directives/angularjs-nvd3-directives.js"></script>
    <link rel="stylesheet"href="Dependencies/nvd3/nv.d3.css">

    <script>
        var app = angular.module("nvd3TestApp", ['nvd3ChartDirectives']);

        function ExampleCtrl($scope){
            $scope.exampleData = [
                {
                    "key": "Series 1",
                    "values": [ [ 1025409600000 , 0]  , [ 1309406400000 , 121.92388706072] , [ 1312084800000 , 116.70036100870] , [ 1314763200000 , 88.367701837033] , [ 1317355200000 , 59.159665765725] , [ 1320033600000 , 79.793568139753] , [ 1322629200000 , 75.903834028417] , [ 1325307600000 , 72.704218209157] , [ 1327986000000 , 84.936990804097] , [ 1330491600000 , 93.388148670744]]
                }];

        }
    </script>

</head>
<body ng-app='nvd3TestApp'>

    <div ng-controller="ExampleCtrl">
        <nvd3-line-chart data="exampleData"
                         showXAxis="true"
                         showYAxis="true"
                         tooltips="true"
                         interactive="true">
        </nvd3-line-chart>

    </div>

</body>
</html>

A: Global functions as controllers haven't been supported in angular for quite a while ... since around 1.2xx
try
 var app = angular.module("nvd3TestApp", ['nvd3ChartDirectives']);

 app.controller('ExampleCtrl', function($scope) {
   $scope.exampleData = [{
     "key": "Series 1",
     "values": [
      ......
     ]
   }];

 });

A: I believe I have solved your issue with your code. I didn't load any css so you may have to add yours to make it look right. I would also move your script tags to right before the closing </body> tag. That way your code will not run before the dom loads.  This will prevent some headaches in the future.
Live Preview: http://codepen.io/larryjoelane/pen/OMQqMd
JavaScript/Angular Code:
var app = angular.module("nvd3TestApp", ['nvd3ChartDirectives']).controller("ExampleCtrl", function($scope) {

  $scope.exampleData = [{
    "key": "Series 1",
    "values": [
      [1025409600000, 0],
      [1309406400000, 121.92388706072],
      [1312084800000, 116.70036100870],
      [1314763200000, 88.367701837033],
      [1317355200000, 59.159665765725],
      [1320033600000, 79.793568139753],
      [1322629200000, 75.903834028417],
      [1325307600000, 72.704218209157],
      [1327986000000, 84.936990804097],
      [1330491600000, 93.388148670744]
    ]
  }];

})();


text:
Q: Нужно исключить повторный ввод "./*-+=, подскажите пожалуйста. from tkinter import *
from tkinter import ttk

root = Tk()
root.title("Calculator")

# логика

def _calc(bttn):
    if bttn == "=":
        result = eval(data_out.get())
        data_out.insert(END, "=" + str(result))

# Очистка полz

    elif bttn == "C":
        data_out.delete(0, END)
    else:
        if "=" in data_out.get():
            data_out.delete(0, END)
        data_out.insert(END, bttn)

# Список кнопок

buttons = [
    "7", "8", "9", "/",
    "4", "5", "6", "*",
    "1", "2", "3", "-",
    " ", "0", " ", "+",
    " ", ".", "=", "C"
]

a = 1
b = 0

data_out = Entry(root, width=50)
data_out.grid(columnspan=4)

for i in buttons:
    #rel = ""
    cmd = lambda x=i: _calc(x)
    ttk.Button(root, text=i, command=cmd).grid(row=a, column=b)
    b += 1
    if b > 3:
        b = 0
        a += 1

root.mainloop()

A:
Ограничение ввода
Как уже говорилось выше, мы можем проверить ввод пользователя после того, как получим его, но не лучше ли было бы просто не допустить ввод ошибочных символов?
Поля ввода с маской.
Это подразумевает использование графического интерфейса для взаимодействия с пользователем и инструментария, который в состоянии отфильтровать недопустимые символы. Как правило, этот инструментарий имеет встроенные валидаторы (функции проверки корректности ввода прим. перев. ) для чисел, строк символов и пр. и очень прост в использовании. В настоящий момент, для создания графического интерфейса, я чаще всего использую PyQT, однако и TKinter, и WxPython, и даже Kaptain также предоставляют такую возможность. Боюсь оказаться неправым, но кажется PyGTK подобной "фишки" еще не имеет.
Если вы не найдете валидатор под свои нужды, то PyQT, к примеру, позволит создать свой собственный.
Я не буду здесь углубляться в рассмотрение каждого инструментария, а в качестве примера продемонстрирую -- как "прицепить" валидатор числа к полю ввода в PyQT. Имя поля ввода в программе -- 'self.rate', Мы "прицепим" к этому полю ввода 'QDoubleValidator' и дополнительно укажем диапазон чисел от 0.0 до 999.0, а также ограничим число знаков после запятой -- двумя:
self.rate.setValidator(QDoubleValidator(0.0, 999.0, 2, self.rate) )
Здорово? Конечно здорово! Мы не только указали тип числа, но еще и ограничили диапазон вводимых чисел!
Другой способ наложения ограничений -- это выбор из списка допустимых значений, но вы наверняка уже знаете об этом.

Источник: http://www.linuxcenter.ru/lib/articles/programming/python_foolproof.phtml


text:
Q: Oracle's plain behavior on EXECUTE IMMEDIATE with REPLACE and variable bind I am trying to avoid oracle's plain to be calculated at every dynamic SQL use.
Using REPLACE and then a EXECUTE IMMEDIATE without USING leads to overhead, as the string is different at every use, Oracle always seems to search a new plain.
But reading about EXECUTE IMMEDIATE statement a found the following:
You can execute a dynamic SQL statement repeatedly using new values for the bind arguments. You still incur some overhead, because EXECUTE IMMEDIATE re-prepares the dynamic string before every execution.
Is that? Does USING bind forces Oracle to recalculate every dynamic string? If so, how to avoid it?
a) querytoselect = REPLACE( querytoselect, 'pattern', 'var' );
   EXECUTE IMMEDIATE querytoselect.

b) EXECUTE IMMEDIATE querytoselect USING var

Thanks.

A: EXECUTE IMMEDIATE always does a parse, but if the statement is identical to one already in memory, it can simply use the plan already determined (this is called a "soft parse") instead of having to fully parse the statement and determine a new plan (a "hard parse").
There is really more subtlety to it than that, and depends on your configuration as well.  For instance, even if a matching statement is found in memory, bind peeking and table statistics could result in a hard parse being performed to determine if there is a potentially better plan given the particular input.
But overall, a soft parse is less overhead than a hard parse, and using bind variables increases the chance of avoiding a hard parse.
To completely avoid re-parsing, you can use DBMS_SQL instead of EXECUTE IMMEDIATE and hold onto the cursor after parsing.  I wouldn't bother doing this unless you've identified a significant performance issue caused by soft parsing.


text:
Q: git push failing suddenly (git-remote-https: relocation error) I've pushed to my repo less than an hour before. Now I get this error:
$ git push origin master
git-remote-https: relocation error: /usr/lib/i386-linux-gnu/libldap_r-2.4.so.2: symbol pt(read_mutex_destroy, version GLIBC_2.0 not defined in file libpthread.so.0 with link time reference

I'm running Debian Wheezy, and didn't install anything or run any upgrade.

A: Try setting up your remote head again. The pointer might have got corrupted.
git remote set-head <name>

A: This work for me :
$ wget http://mirrors.kernel.org/ubuntu/pool/main/libi/libidn2/libidn2-0_2.0.4-1.1build2_amd64.deb
$ sudo dpkg -i libidn2-0_2.0.4-1.1build2_amd64.deb
$ sudo apt-mark hold libidn2-0


text:
Q: I am running a eloquent query, but i am stuck in a position I am new in Laravel.
$year 'all' is every possible year
all, 2022, 2021, 2020, 2019

if i pass params any of them except all its working fine.
but when i pass all  as condition. i have no idea what to do?
Please help me.
public function findResultServiceFeeDubai($address, $type, $year, $norows){

        $result = DB::table('service-charges')
        ->select('address', 'year', 'type', 'total_charge_sqft')
        ->orWhere('address', 'LIKE', "%".$address."%")
        ->where('type', $type)
        ->where('year', $year)
        ->limit($norows)
        ->get();
        $response = $result;
        return response()->json($response, 200);

    }

Route::get('/findResultServiceFeeDubai/{name}/{type}/{year}/{norows}',[UserController::class,'findResultServiceFeeDubai'])->name('findResultServiceFeeDubai');

A: You are calling methods on a Query Builder. It is an object so you can assign it to a variable and make calls to it as needed to build your query. The get call is what is actually executing the query and returning a result. If you want to conditionally add query conditions to that query you can just use if statements (if you prefer to not use the functional approach):
$query = DB::table('service-charges')
    ->select('address', 'year', 'type', 'total_charge_sqft')
    ->where('address', 'LIKE', '%'. $address .'%')
    ->limit($norows);

if ($year !== 'all') {
    $query->where('year', $year);
}

if ($type !== 'all') {
    $query->where('type', $type);
}

$result = $query->get();


text:
Q: Scope operator in Operator Overloading I'm not able to understand the scope operator in Operator overloading. There are examples when they are using it when they don't. When I'm supposed to write T::operator. Can I write just the operator still works fine or is it recommended to use::?
The example:

Prototype examples (for class T)
Inside class definition
T& T::operator +=(const T2& b){}

Can I write it like T& operator +=(const T2& b){}
Or should I always write it like T& T::operator +=(const T2& b){}

A: Inside the class, you don't use the scope resolution operator :::
class T {
public:
    // ...
    T operator+=(const T2& b)
    {
        // ...
    }
};

If you define the operator outside the class, then you use the scope resolution operator :: in the out of class definition.  You still omit it in the declaration:
class T {
public:
    // ...
    T operator+=(const T2& b);
};

// in the implementation
T T::operator+=(const T2& b)
{
    // ...
}

This has nothing to do with recommendation or good practice.  Everything stated here is the only way that can work, the other ways are just not correct C++ code.

A: The operator += may be declared as a member function or member template of a class or class template and defined either within the class or class template or outside them.
If it is defined outside the class then the scope operator is required.
The operator may be also declared and defined as a stand-alone non-class function
Consider the following demonstrative program
#include <iostream>

struct A
{
    int x = 0;

    A & operator +=( char c )
    {
        x += c;
        return *this;
    }
};

struct B
{
    int x = 0;

    B & operator +=( char c );
};

B & B::operator +=( char c )
{
    x += c;
    return *this;
}

struct C
{
    int x = 0;
};

C & operator +=( C & cls, char c )
{
    cls.x += c;

    return cls;
}

int main()
{
    A a;

    a += 'A';

    std::cout << "a.x = " << a.x << '\n';

    B b;

    b += 'B';

    std::cout << "b.x = " << b.x << '\n';

    C c;

    c += 'C';

    std::cout << "c.x = " << c.x << '\n';

    return 0;
}

Its output is
a.x = 65
b.x = 66
c.x = 67

The operator can be also declared as a template operator. For example
#include <iostream>

template <class T>
struct A
{
    T x = T();
};

template <class T1, class T2>
T1 & operator +=( T1 &a, const T2 &x ) /* C++ 17 only requires requires( T1 t ) { t.x; }*/
{
    a.x += x;
    return a;
}

int main()
{

    A<int> a;
    std::cout << ( a += 10u ).x << '\n';
}

Again if the operator is a member function template and is defined outside its class then the scope resolution operator is required.
#include <iostream>

template <class T1>
struct A
{
    T1 x = T1();
    template <class T2>
    A<T1> & operator +=( const T2 &x );
};

template <class T1>
template <class T2>
A<T1> & A<T1>::operator +=( const T2 &x )
{
    this->x += x;
    return *this;
}

int main()
{

    A<int> a;
    std::cout << ( a += 10u ).x << '\n';
}


text:
Q: Creating a new python dict from existing dicts with different keys but same ids I have a composite dictionary d that is built up from a set of component dictionaries, d1 and d2:
d1 = {'key1': 4}
d2 = {'key2': 5}
d = {}
d['altname_key1'] = d1['key1']
d['altname_key2'] = d2['key2']

The behavior I am trying to accomplish is for changes to the keys of d to automatically propagate to changes in d1 and d2. The above code does not behave this way, which can be verified by comparing the ids:
id(d['altname_key1']) == id(d1['key1'])
True
id(d['altname_key2']) == id(d2['key2'])
True
d['altname_key1'] = 17
id(d['altname_key1']) == id(d1['key1'])
False

The behavior I am looking for can be accomplished if my composite dictionary was only a composite of a single component and if I did not change keynames:
d = d1
d['key1'] = 45
id(d['key1']) == id(d1['key1'])
True

Does python have a feature that enables a composite dictionary d, including different keynames, such that the keys point to the same point in memory, even if the keys have different names?

A: I believe something else may have caused the id of the values to change, maybe you did some other assignment to d dictionary before testing id , numbers in python are immutable, so two different numbers would not have the same id.
When you do - d['altname_key1'] = d1['a'] - Python is pass by assignment, which means the reference of d1['a']'s reference is passed by value. Example -
>>> d = {'a':[1,2]}
>>> d2 = {'b':[3,4]}
>>> d3 = {}
>>> d3 ['aa'] = d['a']
>>> d3['bb'] = d2['b']
>>> d3
{'bb': [3, 4], 'aa': [1, 2]}

>>> id(d3['aa']) == id(d['a'])
True
>>> d3['aa'].append(5)

>>> d3
{'bb': [3, 4], 'aa': [1, 2, 5]}

>>> d
{'a': [1, 2, 5]}

So what you are trying to achieve does work.

But this given , I would like to advice against keeping multiple references to same mutable object, as this method can lead mysterious bugs, some code may wrongly update d dictionary, even though you did not want it to and it can cause the same changes to get reflected in d1. And it would be hard to debug the issues.
Also, this method would break if you do an assignment on d , in that case, d dictionary's value would change, but d1 or d2 would not change. Example -
>>> d3['aa'] = [1]
>>> d3
{'bb': [3, 4], 'aa': [1]}
>>> d
{'a': [1, 2, 5]}

You may want to reconsider what you are trying to design.

Regarding Why you get the desired behavior when you do the following -
d = d1
d['key1'] = 45
id(d['key1']) == id(d1['key1'])
True

It is because in the d is a reference to the d1 dictionary object, so they are basically pointing to the same dictionaries. And hence d['key1'] would always be d1['key1'] . You can do  the following to see that they are the same reference -
id(d) == id(d1)

And this again would not be recommended due to above said reasons.

A: This class will act like a ChainMap, except it'll respect your alternate key mapping where specified. It works in Python 2.7 and Python 3.3+.
from __future__ import print_function

try:
    from collections import ChainMap  # Python 3
except ImportError:
    from ConfigParser import _Chainmap as ChainMap  # Python 2

class ChainMapWithAltKeys(ChainMap):
    def __init__(self, *maps, **kwargs):
        try:
            super(ChainMapWithAltKeys, self).__init__(*maps)
        except TypeError:  # Python 2
            ChainMap.__init__(self, *maps)  # Python 2
        self.altkeymap = kwargs.get('altkeymap', {})

    def __getitem__(self, key):
        if key in self.altkeymap:
            key = self.altkeymap[key]
        try:
            return super(ChainMapWithAltKeys, self).__getitem__(key)
        except TypeError:  # Python 2
            return ChainMap.__getitem__(self, key)  # Python 2

dict_one = {'a': 1, 'b': 2, 'c': 3, 'samekey': 'diffval_one'}
dict_two = {'x': 24, 'y': 25, 'z': 26, 'samekey': 'diffval_two'}

altkeymap = {'alpha': 'a', 'zulu': 'z'}

cmwak = ChainMapWithAltKeys(dict_one, dict_two, altkeymap=altkeymap)

print(cmwak['a'])  # 1
print(cmwak['alpha'])  # 1
print(cmwak['b'])  # 2
print(cmwak['y'])  # 25
print(cmwak['z'])  # 26
print(cmwak['zulu'])  # 26
print(cmwak['samekey'])  # diffval_one

Note that when a key is in more than one dict, the value is taken from the dict that was passed in first; specifically, each mapping in cmwak.maps is checked in order until the key is found. Read up on ChainMap for the details; everything there applies to ChainMapWithAltKeys.


text:
Q: How to add add_meta_box to specific Page Template? I want to add add_meta_box to specific page  type like Page Template, Like Product Template.
I am using this article http://wp.smashingmagazine.com/2011/10/04/create-custom-post-meta-boxes-wordpress/ to try it.

A: If your custom page template filename is foobar.php, you can use get_post_meta():
global $post;
if ( 'foobar.php' == get_post_meta( $post->ID, '_wp_page_template', true ) ) {
    // The current page has the foobar template assigned
    // do something
}

Personally, I like calling this inside my add_meta_boxes_page callback, and wrapping it around the add_meta_box() call itself.
function wpse82477_add_meta_boxes_page() {
    global $post;
    if ( 'foobar.php' == get_post_meta( $post->ID, '_wp_page_template', true ) ) {
        add_meta_box( $args );
    }
}
add_action( 'add_meta_boxes_page', 'wpse82477_add_meta_boxes_page' );

You'll just need to instruct users to save the page after assigning the template, so that the meta box appears.

A: I found a few bugs with the answer above option above but I customized this option below and it helped - no bugs at all.
add_action('add_meta_boxes', 'add_product_meta');
function add_product_meta()
{
    global $post;

    if(!empty($post))
    {
        $pageTemplate = get_post_meta($post->ID, '_wp_page_template', true);

        if($pageTemplate == 'page-templates/product-page.php' )
        {
            add_meta_box(
                'product_meta', // $id
                'Product Information', // $title
                'display_product_information', // $callback
                'page', // $page
                'normal', // $context
                'high'); // $priority
        }
    }
}

function display_product_information()
{
    // Add the HTML for the post meta
}

https://paulund.co.uk/display-post-meta-box-specific-page-templates
It's clean

A: This is a solution with name of the page :
Accueil is the name of the page.
    $screens = ['Accueil'];
    foreach ($screens as $screen) {
     if ( get_the_title() == $screen ) {//condition
     add_meta_box(
      'accueil_données',
      'Informations sur Orchestre',
      'metabox_accueil_infos',
      'page',
      'normal',
      'high'
     );
   }
}

A: function mcf_add_custom_metabox() {
    global $post;
    if ( $_REQUEST['post'] == 30 ) {
        add_meta_box( 'shop_editor', ' ', 'mcf_callback', 'page' );
    }
}
add_action( 'add_meta_boxes_page', 'mcf_add_custom_metabox' );

I got a way to add metabox in specific page using page id.


text:
Q: Spring Java based configuration with static method can any one please advice why we need to declare PropertySourcesPlaceholderConfigurer bean using a static method ? I just found that if I use non-static for below then url will be set to null value instead of taking from property file -
@Value("${spring.datasource.url}")
private String url;

@Bean
public static PropertySourcesPlaceholderConfigurer propertyConfig(String profile) {
    String propertyFileName = "application_"+profile+".properties";
    System.out.println(propertyFileName);
    PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
    configurer.setLocation(new ClassPathResource(propertyFileName));
    return configurer;
}

@Bean
@Profile("local")
public static String localProfile(){
    return "local";
}

@Bean
@Profile("prod")
public static String prodProfile(){
    return "prod";
}

A: PropertySourcesPlaceholderConfigurer objects are responsible for resolving @Value annotations against the current Spring Environment and its set of PropertySources. PropertySourcesPlaceholderConfigurer class implements BeanFactoryPostProcessor. In the container lifecycle, a BeanFactoryPostProcessor object must be instantiated earlier than an object of @Configuration-annotated class.
If you have @Configuration-annotated class with instance method returning a PropertySourcesPlaceholderConfigurer object, then the container can not instantiate the PropertySourcesPlaceholderConfigurer object without instantiating the @Configuration-annotated class object itself. In this case, @Value can not be resolved, since the PropertySourcesPlaceholderConfigurer object does not exist at the moment of instantiation of the object of @Configuration-annotated class. Thus, @Value-annotated field takes the default value, which is null.
Please see the "Bootstrapping" part of @Bean javadoc for more information.


text:
Q: Adding to dictionary dynamically I 'm having an array of dictionary like so...
[
  {
    "id" : "3",
    "sellingPrice" : "520",
    "quantity" : "15"
  },
  {
    "id" : "5",
    "sellingPrice" : "499",
    "quantity" : "-1"
  },
  {
    "id" : "8",
    "sellingPrice" : "500",
    "quantity" : "79"
  }
]

Now I want to add to the dictionary another key called remaining_balance with a value of 420,499 & 500 respectively. How can I achieve this..? Hope somebody can help...

A: It seems like you want to add a value to your dictionary that is an array:
var arrDict = Array<Dictionary<String,Any>>()  //Your array
arrDict.append(["id":"3","sellingPrice":"520","quantity":"13"])
arrDict.append(["id":"5","sellingPrice":"43","quantity":"32"])
arrDict.append(["id":"8","sellingPrice":"43","quantity":"33"])

let arrValue = ["420","499","500"] //Your remaining value in array

print("Before ",arrDict)
for (index,dict) in arrDict.enumerated() {
    var dictCopy = dict //assign to var variable
    dictCopy["remaining_balance"] = arrValue[index]
    arrDict[index] = dictCopy //Replace at index with new dictionary
}
print("After ",arrDict)

EDIT
If you are able keep an index of an array it would be possible,
Assuming that you have the index of an array
var dictCopy = arrDict[index]
dictCopy["remaining_balance"] = "666" //Your calculated value
arrDict[index] = dictCopy //Replace at index with new dictionary

A: Let's assume you have an array of dictionaries like so:
var arrayOfDictionaries = [
    [
      "id": 3,
      "sellingPrice": 520,
      "quantity": 15
    ]
]

It is important that arrayOfDictionaries is not a let constant, otherwise it is considered immutable and you can not call append on it.
Now you init a new dictionary like:
let newDictionary = [
    "id": 10,
    "remaining_balance": 420,
    "quantity": 15
]

Now add the newDictionary like
arrayOfDictionaries.append(newDictionary)

If the order is important
If the order is important there are a couple of ways to go about that.
When calling append the new value (in this case the new dictionary) will always be inserted at the bottom of the array.
If for some reason you can not call append in the correct order you could use insert, which inserts your dictionary at a specific position.
Yet another way is to append the values wildly and after you are done, call sort on the array.
Improvement Tips
Notice that for the values I did not use strings, as you only have numbers like "id" : 30.
Also, if you want the second key to be called remaining_balance you should call the first key selling_price instead of sellingPrice. Because of conistency.
Alternative approach
As far as I have understood you are trying to implement some software that is responsibly for selling some products.
I think you are tackling this problem from a completely wrong side.
I think you should read about database relationships. Selling products actually is a very common problem.
Maybe this will help you. I would offer a possible solution myself, but I think this misses the point of your question.
If you decide to use the database approach, you won't necessarily have to use a database. You can take the approach and implement it using simple structs/classes/arrays.

A: var newKV = [["remaining_balance": "420"],["remaining_balance": "490"],["remaining_balance": "500"]]
let array = [["id":"3", "sellingPrice":"520", "quantity":"15"], ["id":"5", "sellingPrice":"520", "quantity":"15"], ["id":"8", "sellingPrice":"520", "quantity":"15"]]

let newArray = array.enumerated().map { (index : Int, value: [String: String]) -> [String: String] in
    var dic = value
    dic.merge(newKV[index]) { (_, new) -> String in
        new
    }
    return dic
}

A: You could achieve it by mapping your array:
var myArray = [["id": "3", "sellingPrice": "520", "quantity" : "15"], ["id": "5", "sellingPrice": "499", "quantity" : "-1"], ["id": "8", "sellingPrice": "500", "quantity" : "79"]]

print(myArray)
/*
 [["id": "3", "sellingPrice": "520", "quantity": "15"],
 ["id": "5", "sellingPrice": "499", "quantity": "-1"],
 ["id": "8", "sellingPrice": "500", "quantity": "79"]]
 */
print("___________________")

var remainingBalanceDesriedValue = 420
myArray = myArray.map { (dict: [String: String]) -> [String: String] in
    var copyDict = dict
    copyDict["remaining_balance"] = "\(remainingBalanceDesriedValue)"

    remainingBalanceDesriedValue = (remainingBalanceDesriedValue == 420) ? 499 : (remainingBalanceDesriedValue == 499) ? 500 : 420

    return copyDict
}

print(myArray)
/*
 [["sellingPrice": "520", "quantity": "15", "id": "3", "remaining_balance": "420"],
 ["sellingPrice": "499", "quantity": "-1", "id": "5", "remaining_balance": "499"],
 ["sellingPrice": "500", "quantity": "79", "id": "8", "remaining_balance": "500"]]
 */

A: I noticed this question lacks an extension answer, yes.. I'm gonna be that guy, so here it is. This could be made more generic by supporting other types of dictionaries, feel free to pitch in ;)
Inspiration from @eason's answer.
var newKV = [["remaining_balance": "420"],["remaining_balance": "490"],["remaining_balance": "500"]]
var array = [["id":"3", "sellingPrice":"520", "quantity":"15"], ["id":"5", "sellingPrice":"520", "quantity":"15"], ["id":"8", "sellingPrice":"520", "quantity":"15"]]

extension Array where Element == [String: String] {

    enum UniquingKeysStrategy {
        case old
        case new
    }

    mutating func merge(with target: Array<Element>, uniquingKeysWith: UniquingKeysStrategy = .new) {

        self = self.merged(with: target)
    }

    func merged(with target: Array<Element>, uniquingKeysWith strategy: UniquingKeysStrategy = .new) -> Array<Element> {

        let base = self.count > target.count ? self : target
        let data = self.count > target.count ? target : self

        return data.enumerated().reduce(into: base, {
            result, data in

            result[data.offset]
                .merge(data.element, uniquingKeysWith: {
                    old, new in

                    if strategy == .new { return new }

                    return old
                })
        })
    }
}

let mergedArrays = newKV.merged(with: array, uniquingKeysWith: .old)

array.merge(with: newKV)

Happy Coding :)


text:
Q: hide/suppress parts of a (iframed) google form I'm using the iframe-html-element to show a Google Form within my app. Can anyone give me some tips on how to hide/suppress parts of that form? e.g. header, footer, etc. specifically I want to hide the

 and
 and
 and

ps my app is a combination of html, css & javascript, including jquery.

A: Unless the other site wants to co-operate and add some JS to listen for requests from postMessage, you cannot.
It is Goggle's page, you cannot change it.


text:
Q: Spring Roo Presentation and Model binding I am starting on Springsource using Spring Roo.
Q1. Am I correct to say that Spring Roo automates a lot of tedium out of Spring?
I am asking that because when I follow non-roo tutorials on Spring, I am reading that I have to perform a significant amount of configuration and stubs which would have been done by roo. I don't see why, prior to roo, would Spring help reduce my work load.
Q2. Is it necessary to define entities using the namespace ~.domain.whatever. Is it necessary to have "domain"? Can I do
entity --class ~.profile.PostalAddress

? Is Spring sensitive to the word "domain"?
Q3. I would like to define an entity
Employee { long id, string name, string project, date startdate}

I would like to bind Employee to a presentation panel where

*

*id is a hidden field,

*name is displayed non-editable field,

*project is displayed editable field populated with the current value in the db,

*startdate is not even sent to the browser.

How do I accomplish that in Roo? If I cannot do that in Roo, is there a way I could muck around with the Spring generated innards to accomplish it and how easy would it be?
Q4. Spring roo generates a standard template web interface. But I do not wish to use the interface. I just want roo to generate RESTful panels for me, which I could associate with a GWT menu item.
The reason is I need to use GWT/SmartGWT navigation widgets and when the appropriate data manipulation item is called thro gwt/smartgwt, I would like to call/enable that Spring generated data panel RESTfully.
How do I get roo, or subsequently Spring, to generate a RESTful data panel for each of my entity without using Spring or roo's generated (useless/unattractive) default navigation side panes? Would I have to manually modify those roo generated files? If so, how and what?
In short, I want to use the convenience of roo's help in generating lots of presentation-validation-model bound modules but use my own GWT/Smart GWT to navigate to them. I am NOT asking about roo+gwt.

A: Q1: It is true that prior to Roo you would have to write quite a few configuration files for a Spring application. However, without Spring you would have to write even more configuration and, worse, Java code to glue it all together.
Q2: Roo is agnostic of the word "domain". You can call your packages any way you want. Personally I prefer the sub-package "model" for domain classes.
Can't say anything about Q3 and Q4, sorry.

A: Caveat - I am not a ROO expert.. just getting started myself
Q3:
You can find out how to do all of that here :
http://static.springsource.org/spring-roo/reference/html/base-web.html#jsp-views
ID : you'll need to import the standard jstl tags to support <frm:hidden> (Roo doesn't have this by default)..
Name:   You can render the Name field as plain text, or as a disabled text box -- if the latter, you can add disabled=true to the tag, I believe.
Project : Roo will do what you need for Project out of the box (although, if "Project" is another entity in a Many-Many relationship, it will create a Select Box by default, with all the possible Projects, and the current one selected)
StartDate : set "render='false'" on the roo-generated tag and it will not even output the html for that field.
In all cases, Roo will re-write your input fields unless you change the tags Z field to z="user-managed".
I would probably keep the original ROO tag, change it to render="false" z="user-managed" and add your own beneath it to do what you really want.

Q4
Not familiar with GWT, but have you considered the roo web gwt


text:
Q: What is the difference between Bare metal, RTOS and SoC? Having just recently gotten into embedded programming using PIC microcontrollers, I am trying to understand the difference between Bare metal, RTOS and SoC.
Online searches reveal contradictory definitions and meanings.
For example, Semiengineering state that "An RTOS is code written on bare metal" and arduino.cc state that "If you programming controller without using any [RT]OS it's a bare metal approach".
The implication is that some code written on bare metal can be considered to be RTOS, whilst others may not be.
Therefore, my question is when can embedded programming of microntroollers be considered programming of bare metal and/or RTOS? And where does SoC fit into all of this, if at all?
Any insight that anyone can provide will be very much appreciated!

A: The statement "An RTOS is code written on bare metal" is very misleading; all operating systems are written at a level that would be considered bare metal, except we only use the term bare metal to describe software/firmware that is written to operate directly without the use of an operating system. Sometimes you may see the term EABI used to mean bare metal, EABI stands for Embedded Application Binary Interface, but it really means code that isn't an application and that has no Application Binary Interface.
Software OS (operating system) categories are roughly: RTOS where the task scheduler guarantees execution time for designated critical system tasks, EABI/"bare-metal" where there is no OS at all and resources are managed directly by the software; Hypervisor for lightweight "virtual machine" task swappers that sort of try to encapsulate several traditional OSs, and finally just plain OS for operating systems that didn't have the benefit of this kind of marketing buzzword generator. This is all independent of whether the hardware is based on a CPU, a microcontroller, or a SoC.
From the perspective of problem-solving:
Software: EABI/bare-metal is just a new name for how programming was always done since Von Neumann and storable-program digital computers. (Before that, programming was much closer to designing a whole new hardware configuration for each new problem.) The name emerged somewhat recently to describe the alternative to other approaches. For example the GCC compiler builds code that works with some type of target OS, so there is a target field that can be "windows" or "linux" or "EABI" if neither of those. Most code written on microcontroller systems like PIC and Arduino is actually bare-metal.
Software: OS solves the problem of many different pieces of application software each needing to support every new piece of hardware, and also supports sharing resoruces among multiple application programs. Introduced time-sharing, inter-process communication, device drivers, file systems, and even the distinction of application software which is focused on solving one particular problem, without getting bogged down in all of the details of managing every resource directly.
Software: RTOS solves the problem of guaranteed latency. Keeping an advanced fighter jet airplane flying is a difficult problem, because the airframes they use are unstable -- allowing quick, nimble flying, but not able to just glide without constant correction. When the operating system is in charge of controlling the flight surfaces, the system absolutely cannot tolerate a delayed response -- the RTOS must be able to guarantee that every critical process gets enough system resources to produce results according to a real-time schedule. This makes the task scheduler more complicated, and the trade-off is that the RTOS has to be able to reject launching a new process if it cannot absolutely guarantee that the new process won't impact critical scheduled tasks.
Hardware: CPU "Central Processing Unit" is the main part of a computer system, that reads instructions from the memory system (which is external), decodes those instructions, and performs those actions. The term is used both for big furniture-sized IBM System/360 cabinets as well as for single-chip CPUs such as 8080/8085/Z80, 6502/6500/6800, etc. The CPU by itself can't do anything without a bunch of supporting actors providing memory and peripheral interfacing.
Hardware: Microcontroller would have been called a "System on Chip" if anyone in marketing had thought to call it that back in the mid 1980s... it's basically a single-chip CPU with some internal memory and some on-chip peripherals. Usually it does not have any way to add more memory and peripherals, because the CPU bus is completely internal to the microcontroller. Pins are expensive, and the CPU's internal bus requires a lot of pins working together. Microcontrollers solve the problem of running a "bare-metal" program inside a single IC, with communication only through bit-banging GPIO or low-pin-count interfaces like SPI/I2C.
Hardware: SoC "System on Chip" is really a marketing term, I think it first came from Xilinx Zynq XC7000 series. As Xilinx uses the term, it is a combination of dual-core ARM CPU together with FPGA programmable logic. Supposed to solve the problem of systems that require lots of application programming but also having low-latency programmable logic.


text:
Q: JS get data from django template tag I am currently using custom django middleware to check whether the user is authenticated or not. And then use custom templatetag in a template in order to show username/login form
A some point I came across a problem, where I need that authentication info in my js. The only thing I could think of is:

*

*create hidden element with the auth/not auth flag in it

*get value of that element in js and do whatever I want.

Is there any better way to do such thing?

A: Make 2 copy of JS files, then use template tag to render different one based on the authentication
Then you can keep the authentication decision on the server side.
{% if bool %}
    <script src = ....
{% else %}
    <script src = ....
{% endif %}

OR:
You can use AJAX in the JS file to GET the information you want. Then the server responses data based on the authentication.

A: As for the user auth this can reduce the effort

{% if user.is_authenticated %}

then add script you need
regards


text:
Q: jquery scrolltop stay position after response I wrote a code to view the chat history. Everything works fine, but I realized that. When you scroll up the div to view the history, old posts are displayed at a time. I've added this code $("#messages").scrollTop(200); to be able to continue scrolling, but this should not be. When you want to view old messages in apps like whatsapp or facebook, you can continue to scroll up for viewing old messages.
What am I supposed to do to stay position after response?
Here is DEMO page.
$(document).ready(function() {
  var logDown = $(".chatContainer");
  logDown.animate({ scrollTop: logDown.prop("scrollHeight") }, 0);
  var messages = ''; // New Posts are in demo
  var scrollLoading = true;
  $("#messages").scrollTop($("#messages")[0].scrollHeight);
  $("#messages").on("scroll", function() {
    if (scrollLoading && $("#messages").scrollTop() == 0) {
      $("#messages").prepend(messages);
      $("#messages").scrollTop(200);
    }
  });
});

A: now I understood, i solved it by subtracting the old-height from the new height and set this "old-position" as scrolltop
var old_height,new_height;
$("#messages").on("scroll", function() {
    if (scrollLoading && $("#messages").scrollTop() == 0) {
      old_height = $("#messages")[0].scrollHeight;
      $("#messages").prepend(messages);
      new_height = $("#messages")[0].scrollHeight;
      $("#messages").scrollTop(new_height - old_height);
    }
  });

works optimal for me

A: If I understood your problem you don't want to scroll to the top of the messages at every batch of prepends.
I managed to pull a version without jQuery and using window.requestAnimationFrame for good scroll performance.
Just my $0.02 on the problem.

var container = document.querySelector("#messages");
container.scrollTop = container.scrollHeight;
container.addEventListener("scroll", function(e) {
  last_known_scroll_position = e.target.scrollTop;
  var ticking;

  if (!ticking) {
    window.requestAnimationFrame(function() {
      if (last_known_scroll_position == 0) {
        var delta = e.target.scrollHeight;
        for (var i = 1; i <= 5; i++) {
          var message = document.createElement("DIV");
          message.textContent = "Message Here";
          message.classList.add("message", "red");
          e.target.prepend(message);
        }
        delta = e.target.scrollHeight - delta;
        e.target.scrollTop = delta;
        ticking = false;
      }
    });

    ticking = true;
  }
});
DIV.chatContainer {
  height: 200px;
  overflow: auto;
}

.message {
  margin-bottom:10px;
}

.red {
  background-color:red;
}

Message HERE

Message HERE

Message HERE

Message HERE

Message HERE

Message HERE

Message HERE

Message HERE

Message HERE

Message HERE

Message HERE

Message HERE

Message HERE

Message HERE last


text:
Q: layout_weight giving unpredictable results on device I'm currently trying to put together a layout consisting of a few input controls and a listview, and using layout_weight I've gotten it to look the way I want it in the Android Studio preview. However, on an actual device, the layout looks completely different.
I'm fairly new to Android and have been having a few problems with their layouts before, so I'm probably missing something. However, I've been reading up on different kinds of layouts and layout_weight in particular, and everything I've found so far makes me think the result would look like in Android Studio's preview. I could easily settle for another layout in this case, but I would prefer to actually learn what's wrong, as I may face the same issue again in the future.
Below is my layout code and comparison images.
Any ideas or hints are much appreciated.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical">

    <EditText
        android:id="@+id/input_title"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:hint="@string/title"/>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

        <Button
            android:id="@+id/input_submit"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_alignParentRight="true"
            android:text="@string/input_submit"/>

        <Button
            android:id="@+id/input_date"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_toLeftOf="@id/input_submit"
            android:text="@string/input_date"/>

        <EditText
            android:id="@+id/input_amount"
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:layout_alignBottom="@id/input_date"
            android:layout_toLeftOf="@id/input_date"
            android:hint="@string/amount"
            android:inputType="numberDecimal"/>

    </RelativeLayout>

    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="6"/>

</LinearLayout>

Android Studio preview: http://i.stack.imgur.com/4bWM6.png
Actual layout on device: http://i.stack.imgur.com/MJbOX.png

A: this happens because you didn't declare a standard WeightSum to the parent Layout, So add android:weightSum="8" to your main LinearLayout :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical"
              android:weightSum="8">

<!--  your code -->

</LinearLayout>

and the weight must be 8 as you gave your Views and layouts the weights (1 , 1 , 6), So the whole weight_sum of their parent layout must be 8

A: layout_weight is need for ListView and input_amount EditText rest are wrap_content :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <EditText
        android:id="@+id/input_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/title"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <EditText
            android:id="@+id/input_amount"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:hint="@string/amount"
            android:inputType="numberDecimal"/>
        <Button
            android:id="@+id/input_date"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/input_date"/>

        <Button
            android:id="@+id/input_submit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/input_submit"/>

    </LinearLayout>

    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"/>

</LinearLayout>


text:
Q: MDI form in monodevelop gtk-sharp Want to create MDIform applucation in monodevelop gtk-sharp, but not able to find MDI Parent child form options.
Requesting help

A: MDI (Multiple Document Interface) is not something that GTK# supports natively. The design principle behind GTK# is to abstract the window management away to the windowing engine and the configuration the user has specified on their OS. MDI tends to be Windows-centric, there are parallels in other OS but not generally exactly the same. My advice having been down this path before is to avoid MDI and design your application to be agnostic of the windowing engine.


text:
Q: Prolog check element in grid grid([
[w, w, w, b, w],
[b ,b, w, w, w],
[w, w, w, b, w],
[w, b, b, b, b],
[w, w, w, w, w] ]).

When I have a grid like this I want to check if a cell is white. When you enter the query:
white(X/Y).

it should say true if the cell is indeed white. I made this:
white(X/Y) :- grid([[w]]).

but it doesn't work and I don't know why. (I just started learning prolog)

A: Thank you, I figured it out.
 white(X/Y) :-
        grid(G),
        nth1(Y, G, YAxisGrid),
        nth1(X, YAxisGrid, w).

A: Try this using the folklore predicate nth1:
white(X/Y,G) :-
   nth1(Y, G, R),
   nth1(X, R, w).

I get:
?- grid(G), white(3/2,G).
G = ....

?- grid(G), white(2/2,G).
false.


text:
Q: Rails Controller Modify JSON Response I have this method in my controller:
# GET /bios/1
# GET /bios/1.json

def show
 if member_session?
   @member = MemberPresenter.new(@bio.member)
   # I need something here to add a flag to the json response to signal this is a member session.
 else
  @member = MemberPresenter.new(@bio.member)
 end
end

I need to modify the json response to return something like:
{ member: @member, member_session: true }
Thanks in advance!

A: You can use json param for render functions:
render json: { member: @member, member_session: true }

But it's not the best way to render JSON in rails. I'd recommend you try to use https://github.com/rails-api/active_model_serializers

A: I'm not sure if you specifically want to return json all the time but here's an alternative to rendering other formats as well:
respond_to do |format|
  format.html
  format.json { render json: { member: @member, flag: @member.status } }
end

For small and simple objects, doing this is fine, but if you had to drag the associations along, you have the choice of using a serializer, or you could override the to_json method to something like this.
# member.rb

def as_json(options = {})
  options = options.merge(
    except: [
     :updated_at,
     :created_at,
    ],
    include: {         # Getting associations here
      address: {
        only: [:street, :zip_code],
        include: {
          neighbors: { only: :name }
          }
        }
      }
   )
  super.as_json(options)
end

And finally within the controller, render json: @member.to_json and it will pull all the associations you want with it. This is the lazy man's way of serializing aka what I do :)


text:
Q: Google Chrome: How can I watch the state of the DOM while holding the mouse button in my DOM i have many SVG rectangles (each one in a separate ), that increase in size as long as the user clicks on (using the d3.js on-drag event). The size increases from 2px to 20px. It works, and all is fine - but:
I have a QUnit test that tests if the size is correct, and it currently runs red, telling me the size remained at 2px.
I tried to check the actual size in the DOM-Inspector, but as soon as I click onto the rectangle to fire the event, its group collapses in the DOM-Inspector and I cant look into. If I release the mouse, the group expands again, but its the original state again, which I dont want to inspect.
I want to look at the state of the DOM at the time when my mouse is clicked.
Is there any way to stop execution immediately?
I already tried using Event-Listener-Breakpoints and the element states :active/:focus etc, but without success.
Thanks in advance!
Kev

A: Attach one more mousedown event handler to your element. During this event handler you can proceed with your tests. Just make sure this handler is executed after the one that applies the changes to the element.
For QUnit you may use var done = assert.async() to get a function that you will call when your test is complete. At the end of the callback, just call done.
For example (using jQuery):
$('#element')
   .on('mousedown', function () { $(this).css({color:'red'}); })
   .on('mouseup', function () { $(this).css({color:'blue'}); })
   .on('mousedown', function () {

          // this is the second callback I am talking about

          // make your tests...
          console.log($(this).css('color'))

          // now it is done, call "done()"

   })

The color red will be logged.