text:
Q: git - handling many similar-yet-slightly-different applications? I'm currently working for a company that's using Rational/IBM ClearCase for a great many of its source control needs and have been looking (predominately in my free time, of course) at if/how we could migrate to git in the future.
For background: many of our projects in ClearCase are derived from a common "base" system which we then branch as needed. Most applications start out as strictly base, but client needs require that we branch the files within, resulting two versions: one base, one client-specific. Since the customer-specific version has its own label, each application can evolve independently of one another. Since the labels are affixed to a certain version of each changed file, we don't need to worry that a change in base will break things for a client (since they'll be at different revisions until someone goes in and moves the labels around). We also track the state of the code (sent to QA, awaiting customer feedback, in production) via labels as well.
As far as I can tell I'd create a new repo for the 'base' version and use tags to define the state, but handling the customer-specific versions is really confusing me. Would I need to create an entirely new repo for the client and manually move changes between the base and client versions or is there a better way? Is using tags the best way to handle delineating which revisions go w/ a particular client or am I missing something? I'd seen some mention of submodules, but from what I can tell that's predominately used to handle code related to the application and not essentially large swaths of identical code?
My questions might give it away but all of my git experience has been w/ git for personal projects. It's (relatively) easy to understand the behaviour when you're dealing with a greenfield project, not so much when you're trying to impose a new tool on an existing workflow.
I'd appreciate any insight you might have and thanks for taking your time to read my question!

A: From what you described, Git would be very well-suited to handle the use cases at your company.  You would create a new Git repo based on the existing "base" system.  This "base" system would correspond to the master branch in Git.  For each customer version, you could create a new Git branch.  Branching is an area where Git really beats out just about every other version control system, because it can create a new branch very quickly, while requiring very little storage space.  Note that you would not have to initialize a new Git repository for each customer branch.
If you need to move specific features between master ("base") and any customer branches, you can do so using git merge, git rebase or even git cherry-pick.  Git rebase allows you to maintain the entire history of a feature branch when bringing it back into the master branch.  This could be extremely valuable to your organization if you need to carefully preserve the details of every feature added for every customer.
This question has actually been thoroughly discussed on Stack Overflow already.


text:
Q: python - number of days in between I am pretty new to Python. I am trying to subtract datetime from today's day, but I am getting the following an error when I run the following code:
temp['datetime'] - date.today()

TypeError: unsupported operand type(s) for -: 'DatetimeArray' and
'datetime.date

Sample data and data types are provided below:
datetime     datetime64[ns]
machineID             int64
comp                 object
dtype: object

Table:
        datetime        |machineID  | errorID
0   03/01/2015 07:00:00 |    1      |  error1
1   03/01/2015 20:00:00 |    1      |  error3
2   04/01/2015 06:00:00 |    1      |  error5
3   10/01/2015 15:00:00 |    1      |  error4
4   22/01/2015 10:00:00 |    1      |  error4

I would really appreciate if anyone can answer me on how to solve this problem.

A: It is interesting. I am on pandas 1.0.1 and I has the same error as yours.
To overcome this error, you need to wrap date.today() in Timestamp
from datetime import date

df.datetime - pd.Timestamp(date.today())

Out[91]:
0   -2000 days +07:00:00
1   -2000 days +20:00:00
2   -1969 days +06:00:00
3   -1786 days +15:00:00
4   -2038 days +10:00:00
Name: datetime, dtype: timedelta64[ns]

A: i think you should use
pd.to_datetime('today') instead of date.today()

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why is the output 1 bigger than it should be? (assembly) My code:
.data
x: .word 1
y: .word 1
z: .word 1

.text
main:
lw $t0, x
lw $t1, y
lw $t2, z

add $t0, $t0, $t1   # t0= x+y
add $t0, $t0, $t2   # t0= x+y+z

add $a0, $a0, $t0

li $v0, 1
syscall

li $v0, 10
syscall

i am adding 1 to 1 to 1. The answer should be 3, but it is 4.
Even when im using big numbers, the answer is alwasys 1 bigger that it should be.
why is it so?

A: To do $a0 = $t0, use move $a0, $t0.
What you wrote adds your value to the old value of $a0 for no reason or benefit, like $a0 += $t0.  You wouldn't write that in a high-level language with an uninitialized variable; don't do it in asm.  Obviously $a0 was 1 for some reason at this point in your code, but in general could have had any value.
move is a pseudo-instruction that could assemble to addiu $a0, $t0, 0, or an add or or with $zero.  Either way, the destination register is only written, so the value you leave there won't depend on whatever was there before.
Or better, just add $a0, $t0, $t2 in the first place to do $a0 = $t0 + $t2.
MIPS is a 3-operand machine, don't limit yourself to always having dst and src1 be the same register.


text:
Q: How to draw a layer on stage by json in kineticjs There is a method in KineticJS to draw a stage (canvas) from json
Kinetic.Node.create(JSON, 'container');

There are many layers on stage. I have saved a layer in to JSON
How can I draw just one layer on existing stage?

A: Why don't you just use AJAX to execute the code?
 $.ajax(
   url:
   success: function(response){
      stage.add(new Kinetic.Layer());
   }
 );

You can make this dependent on what is stored in your JSON object.


text:
Q: How should I format output for reading into a list of vectors I have a program that outputs to file an unevenly spaced time series of vectors (one vector per interval) that vary in size . I'm wondering what would be the best way of formatting the output so that the file can be read into a list of vectors in R (Assuming that is the correct data structure), and what code in R i would use to read it.
For example, I imagine the output could look something like this:
1, 24, 5, 211
3, 5
59, 465, 3, 333, 9, 98

or
(1 24 5 211)
(3 5)
(59 465 3 333 9 98)

But what I'm saying is that I want to change the formatting to suite the R read function.

A: Keep fill = TRUE
data = read.table(file.choose(),sep=",",fill=TRUE)

data[is.na(data)] <- ""   # Replacing NA Values with nothing..


text:
Q: Using FPDF, can I chain PDF reports? I have PHP Code which works fine if I comment out one of the two lines below:
$pdf2->Output($filename2,'D'); This gives me report #1
$pdf->Output($output_filename,'D'); This gives me report #2

*

*I'd like to just have them run in succession.

Question: Is there a way to chain them so I'll get the download dialog box twice?
Thank you in advance.


text:
Q: printing only specific lines with sed I have following File (wishlist.txt):
Alligatoah Musik_ist_keine_lösung;https:///uhfhf
Alligatoah STRW;https:///uhfhf?i
Amewu Entwicklungshilfe;https:///uhfhf?i

and want to have the first word of line n.
so for n = 1:
Alligatoah

What i have so far is:
sed -e 's/\s.*//g' wishlist.txt

is there a elegant way to get rid of all lines except n?
Edit:
How to pass a bash variable "$i" to sed since
sed -n '$is/ .*//p' $wishlist

and
sed -n "\`${i}\`s/ .*//p" $wishlist

doesn't work

A: A couple of other techniques to get the first word of the 3rd line:
awk -v line=3 'NR == line {print $1; exit}' file

or
head -n 3 file | tail -n 1 | cut -d ' ' -f 1

A: Something like this. For the 1st word of the 3rd line.
sed -n '3s/\s.*//p' wishlist.txt

To use a variable: Note: Double quotes.
line=3; sed -n "${line}s/\s.*//p" wishlist.txt

A: sed supports "addresses", so you can tell it what lines to operate on. To print only the first line, you can use
sed -e '1!d; s/\s.*//'

where 1!d means: on lines other then 1, delete the line.


text:
Q: jquery unwrap a ul nested inside another with the same id hello this is what my html looks like (I didn't make any mistakes one ul is nested inside the next and they both have the same id)

1

2

3

4

5

6

7

8

I want to use jquery().unwrap(); to remove the second ul and the closing tag. but leave all the li elements

A: You have made two mistakes

*

*There can not be more then one element having same ID.

*UL can not be immediate child of another UL.

But if you really want to remove nested UL try following line.
$("#members-list ul li").unwrap()

Look at Jsfiddle


text:
Q: where I need to add "wait.ignoring" to "ExpectedConditions.visibilityOfElementLocated" I do not understand the concept of:
wait.ignoring(StaleElementReferenceException.class).until
 (ExpectedConditions.visibilityOfElementLocated(By.xpath("bla bla")));

I other words, why do I need to have this part:
ignoring(StaleElementReferenceException.class)

while
ExpectedConditions.visibilityOfElementLocated

waits till the element is visible so that it is not stale.

A: In simple words you can understand the above code like this.
ignoring(StaleElementReferenceException.class)

Above ignore is used to ignore an specific exception that may occur while wait is on executing. For example while waiting for an element if a StaleElementReferenceException occures it will ignore the exception and will not throw the exception to the outside.
A stale element reference exception is thrown in one of two cases, the first being more common than the second:

*

*The element has been deleted entirely.

*The element is no longer attached to the DOM.

Stale Element Reference Exception Documentation

A: The general effect of telling an instance of FluentWait (which is what WebDriverWait is based on) to ignore exceptions is that if such exception happens when it polls the DOM, it will continue polling rather than let the exception trickle up.
In the specific case of ExpectedConditions.visibilityOfElementLocated there is no benefit to explicitly ignoring StaleElementReferenceException because ExpectedConditions.visibilityOfElementLocated already ignores it. There is an explicit try... catch... block in it that will make it return null if the element is stale. I do not know whether older versions of Selenium did not have this try... catch... block. Maybe for some earlier versions of Selenium it was necessary to explicitly tell FluentWait to ignore this exception.

waits till the element is visible so that it is not stale.

It is possible for ExpectedConditions.visibilityOfElementLocated to have to deal with a stale element. It performs its test in two steps:

*

*Get a WebElement that corresponds to the locator the user passed.

*Call .isDisplayed() on this element.
Between these two steps, it is possible for the DOM to be changed so that the element acquired in the first step is already stale (== no longer in the document) by the time the 2nd step runs. It is a very small window of risk, but it exists, and so has to be handled.


text:
Q: How to manage multilingual content in express app I'm building an express app which have to manage translation for some fields of my models. (I'm using loopBackjs framework to be exact)
Example: a product needs to have its title and description directly editable in the backend form in multiple languages
Is there a module that does this kind of translation ?
If not, what is the best way to do this in mongoDB
Thank you for your help


text:
Q: dpkg fails on Ubuntu Server 22.04 LTS My Ubuntu 22.04 LTS seems to have problems with dpkg and I can't find anyone online that has the same issue as me. It makes me not able to install packages and I just don't know how to fix this.
Setting up dpkg (1.21.1ubuntu2.1) ...
head: error reading 'info_silent': Is a directory
dpkg: error processing package dpkg (--configure):
 installed dpkg package post-installation script subprocess returned error exit status 1
Errors were encountered while processing:
 dpkg
E: Sub-process /usr/bin/dpkg returned an error code (1)

My Ubuntu Server version:
Distributor ID: Ubuntu
Description:    Ubuntu 22.04 LTS
Release:        22.04
Codename:       jammy

I've read that a reinstall is an option, but I also can't find a good way to reinstall LTS without losing my data.

A: I finally got this fixed, I found a YouTube video that fixed my issue.
These are the commands that fixed my problem:
sudo mv /var/lib/dpkg/info /var/lib/dpkg/info_silent
sudo mkdir /var/lib/dpkg/info
sudo apt-get update
sudo apt-get -f install
sudo mv /var/lib/dpkg/info/* /var/lib/dpkg/info_silent
sudo rm -rf /var/lib/dpkg/info
sudo mv /var/lib/dpkg/info_silent /var/lib/dpkg/info


text:
Q: How to populate User defined objects from list of lists in scala I am new to Scala.
Currently trying to write a program which fetches table metadata from a database as a list of lists in the below format, and convert it to Objects of user defined type TableFieldMetadata.
The getAllTableMetaDataAsVO function does this conversion.
Can you tell me if I can write this function much better in functional way.
| **Table Name** | **FieldName** | **Data type** |

| table xxxxxx  | field yyyyyy  | type zzzz |

| table xxxxxx  | field wwwww| type mmm|

| table qqqqqq| field nnnnnn| type zzzz |

Note: Here table name can repeat as it usually has multiple columns.
User defined classes:
1. TableFieldMetadata:
/**
 * Class to hold the meta data for a table
 */
class TableFieldMetadata (name: String){
  var tableName: String = name
  var fieldMetaDataList: List[FieldMetaData] = List()

 def add(fieldMetadata: FieldMetaData) {
    fieldMetaDataList = fieldMetadata :: fieldMetaDataList
 }
}

2. FieldMetaData :
/**
 * Class to hold the meta data for a field
 */
class FieldMetaData (fieldName: String, fieldsDataType: String) {
    var name:String = fieldName
    var dataType:String = fieldsDataType
}

Function:
/**
 * Function to convert list of lists to user defined objects
 */
def getAllTableMetaDataAsVO(allTableMetaData: List[List[String]]):List[TableFieldMetadata] = {
  var currentTableName:String = null
  var currentTable: TableFieldMetadata = null;
  var tableFieldMetadataList: List[TableFieldMetadata] = List()

  allTableMetaData.foreach { tableFieldMetadataItem =>
    var tableName = tableFieldMetadataItem.head
    if (currentTableName == null || !currentTableName.equals(tableName)) {
      currentTableName = tableName
      currentTable = new TableFieldMetadata(tableName)
      tableFieldMetadataList = currentTable :: tableFieldMetadataList
    }
    if (currentTableName.equals(tableName)) {
      var tableField = tableFieldMetadataItem.tail
      currentTable.add(new FieldMetaData(tableField(0), tableField(1)))
    }

  }
  return tableFieldMetadataList
}

A: Here is one solution. NOTE: I just used Table and Field for easy of typing into the REPL. You should use case classes.
scala> case class Field( name: String, dType : String)
defined class Field

scala> case class Table(name : String, fields : List[Field])
defined class Table

scala> val rawData = List( List("table1", "field1", "string"), List("table1", "field2", "int"), List("table2", "field1", "string") )
rawData: List[List[String]] = List(List(table1, field1, string), List(table1, field2, int), List(table2, field1, string))

scala> val grouped = rawData.groupBy(_.head)
grouped: scala.collection.immutable.Map[String,List[List[String]]] = Map(table1 -> List(List(table1, field1, string), List(table1, field2, int)), table2 -> List(List(table2, field1, string)))

scala> val result = grouped.map { case(k,v) => { val fields = for { r <- v } yield { Field( r(1), r(2) ) }; Table( k, fields ) } }
result: scala.collection.immutable.Iterable[Table] = List(Table(table1,List(Field(field1,string), Field(field2,int))), Table(table2,List(Field(field1,string))))


text:
Q: OrientDB: UPDATE query result in distributed mode I have a scheme-less class in my OrientDB, let's say it called 'testClass', it's pretty simple and contains 1 boolean property:
{
    lock : 'true'
}

When I execute update query via console or web ui:
update testClass set lock = true

i've got
Updated record(s) '1' in 0.033000 sec(s).

from console and similar result from web ui.
The same result i've got when I execute following Java code
ODatabaseDocumentTx db = ... // open db connection
Object result = db.command(new OCommandSQL("update testClass set lock = true")).execute()

The 'result' variable is of type Integer and contains number of updated record.
But everything changes when the OrientDB server is started in distributed mode (I have 3 nodes). The execution of the same query from console produceds:
Updated record(s) '[null]' in 0.010000 sec(s).

As you can see, now the result is an array and it's empty. The same I've got from Java - the 'result' variable is of type ArrayList and it's empty.
The most interesting result shows web ui - when I execute the same query, I've got '[1]' in 'value' column, which means, I guess, that result is array and it contain 1 integer value '1'.
Is it a feature or a bug? What am I doing wrong?

A: Looking at the guide http://orientdb.com/docs/last/SQL-Update.html
try this query
update testClass set lock = true return after @rid


text:
Q: Group comparison for extreme value data: which method is suitable? I have measured Gaussian curvature data of 3D objects from two different groups, A and B. I would like to find out whether the objects differ in curvature.
The distribution of data values for each subject looks like an extreme value distribution:

(This is expected since Gaussian curvature is computed as the product of the 2 principal curvature k1 and k2, which are the maximum and the minimum over all possible curvature lines.)
If the data were normally distributed, I would take the mean of the data for each subject and fit a linear model to the data, then look at the main effect of the group variable.
However, taking the mean of such a distribution does not seem to make much sense. What would be a suitable approach here?
Note that one could model positive and negative values separately, I guess. Would it be valid to apply a Box-Cox transformation (to the positive and negative parts separately) and then check for mean differences of the resulting distributions? (I somehow doubt it.) Or should I use a GAM?


text:
Q: How to identify similar images despite some being cropped? I have 100 images, all visually similar and I need to search for duplicates. I have an algorithm which can match same colour/pattern/editing etc. but it doesn't support cropping. Meaning if two similar image, one of which is cropped, the result will be different.
I need algorithm which can match two similar images despite of cropping, somehow like tineye works. I got some references but nothing worked.
Here's an example article for reference.

A: I think you are on the right track using hashing for identifying nearly-duplicates. I believe locality sensitive hashing can give you the extra mileage you need. It takes into account the locality of the image features from which it computes the hash key and thus achieves better performance for the task of near-duplicates detection.


text:
Q: How to detect roads from satellite images? OpenStreetMap has announced a Bing API to detect roads. I want to know what is the theory behind road detection and if there is any open source tool that do that.

A: The first is "Create Vector". The bitmap [Raster] is translated to vector notation as soon as possible. That is, each single bit is converted into four directional vectors, joined as a square.
The second is "Simplify Vector". The vector field is simplified by checking for duplicates and removing the vectors that are lying on top of each other (these would be adjacent bits in the bitmap). This is done by referring to the links to the identical vectors and merging these, much like one would remove an item from a linked list.
The third and last is "Lengthen Vector". The algorithm goes through the modified vector field looking for joined parallel vectors and turns these multiple vectors into a single vector.
http://cardhouse.com/computer/vector.htm
and see the IBM patents
http://www.ibm.com/search/csass/search?sn=mh&q=vectorization&lang=en&cc=us&en=utf


text:
Q: Opening popups from AS3 using ExternalInterface in Safari I'm using this code to open a popup
ExternalInterface.call("function () { window.open('" + url + "','" + title + "','" + options + "'); }");

for JavaScript people: calling ExternalInterface.call(string); from flash player lets the browser do eval(string)();
as this call is within a click handler, it even works perfectly with Firefox and IE, for Opera it lets you open the popup manually.
But in Safari, it is always blocked silently. Anyone have an idea how circumvent this?
thanks
back2dos

A: I've run into this, and as far as I could tell there was no real solution... the only workaround I could find was essentially checking if window.open works, and if it doesn't use navigateToURL instead... I just found this link that explains this much better:
http://www.asserttrue.com/articles/2007/08/22/workaround-for-safari-blocking-flash-initiated-pop-ups

A: You shouldn't be creating your function inside of AS3. That's probably one of the reasons you are getting bad behavior.
You should create your function in the HTML or JS files and call it with EI, and pass the arguments you need.


text:
Q: Is the squeal a manifestation of the Painleve Paradox? When a DJ does a rewind (suddenly reverses the direction of the vinyl's rotation under the needle), a sharp squeal is produced. This squeal is neither simply the music played backwards (as a film would be when viewed backwards) nor is it due to a higher pitch because of acceleration…it must be something else.
In mechanics there is something called a Painlevé Paradox and I think it might also produce the squeal. The P-Paradox arises, for example, when one pushes (not pulls) a chalk across the blackboard. It screeches and jumps a bit up and down instead of drawing a smooth line. The reason is that the angle between the chalk and the blackboard is 'oblique' (instead of perpendicular or 'acute').
I think the angle between the needle and the vinyl may also be a bit oblique when played backwards and that this may be why a Painlevé Paradox occurs during a rewind.
Any thoughts to the question:
Is the squeal a manifestation of the Painleve Paradox ?


text:
Q: Filtrar resultados MYSQL de acordo com o resultado de uma linha Estou tendo um problema para realizar um filtro especifico em uma consulta no MySQL.
Estou construindo um sistema de pesquisa onde tenho as seguintes tabelas:

*

*Questionários: com o nome do questionarios

*Perguntas: contendo as perguntas do questionário, com foreign key apontando para a tabela questionário

*Respostas: contendo as respostas de cada pergunta, com o foreign key apontando para perguntas

*Fichas: Informações sobre quem respondeu

*Respostas Dadas: Contém as respostas dadas por cada pessoa.

Tenho a seguinte estrutura:
[Tabela Fichas]
- ID
- created_at
- latitude
- longitude

[Tabela Respostas dadas]
- id
- ficha_id
- resposta_id
- pergunta_id

Eu preciso de uma consulta que me retorne a quantidade de respostas_id de acordo com uma pergunta especifica.
Por exemplo, preciso saber dos que responderam "23" no campo resposta_id quando pergunta_id = "81", respondeu nas outras perguntas.
Já estou batendo cabeça a dias nisso mas não estou conseguindo. Pensei até em criar uma view que me organizasse os dados de forma que cada pergunta fosse uma coluna e as respostas fossem as linhas, mas também não consegui.

A: [Tabela Respostas dadas]
- id
- ficha_id
- resposta_id
- pergunta_id

Por exemplo, preciso saber dos que responderam "23" no campo
  resposta_id quando pergunta_id = "81", respondeu nas outras perguntas.

responderam "23" no campo resposta_id quando pergunta_id = "81"
select id
from respostas
where pergunta_id = "81"
and resposta_id = "23"

respondeu nas outras perguntas.
select *
from respostas
where pergunta_id <> "81"
and id in (select id
           from respostas
           where pergunta_id = "81"
           and resposta_id = "23")

Creio ser isto. []s

A: Obrigado a todos que postaram.
Com a ajuda do Motta cheguei na seguinte consulta:
 select respostas.valor, count(*) from respostas_dadas join respostas on
   respostas.id = respostas_dadas.resposta_id
   where respostas_dadas.pergunta_id <> "26"
    and ficha_id in
        (select ficha_id from respostas_dadas
        where pergunta_id = "26"
        and resposta_id = "82") group by respostas_dadas.resposta_id

Esse é um sisteminha de estudo que estou fazendo, pensando em uma empresa de pesquisas que tem que montar vários questionários. Na tabela questionarios eu jogo os dados gerais de cada questionário, na tabela perguntas eu jogo as perguntas desse questionário, na tabela respostas eu jogo as respostas de cada pergunta, na tabela fichas eu salvo os dados gerais de cada ficha, quando foi feito, local, e por último as respostas de cada ficha eu jogo na tabela respostas_dadas.
Esse filtro que estou tentando fazer é para perguntas tipo

"Das pessoas com sexo masculino ( pergunta 26, resposta 23 ) quantos vão votar no prefeito X"?

Valeu gente.
E desculpem não conseguir formatar o código, primeira vez que estou postando aqui. Segui a orientação de dar os 4 espaços mas o trecho da consulta não está saindo formatado.


text:
Q: wondering why there is no space in front of the output(.join()) build in fnc the code is very simple
chrs = chr(int(ord('A')+random.random()*26))
filledline = ''.join(5 * [chrs])+'\n'

why there isnot any space in front of the chrs?
can you please how .join fnc really work.

A: "*".join(["a", "b", "c"])

Outputs
"a*b*c"

Accordingly
"".join(["a", "b", "c"])

Outputs
"abc"

In order to spaces in front of the string, you have to do some concatenation:
"   " + "".join(["a", "b", "c"])

Outputs
"   abc"

A: The join method joins the values of the passed list into a string with the join separator specified at the start. In case of empty '', join separator just the values of the list into a string without any separator.
Try the method with ','.join() and you will get a fair idea about it.
a = ["Hello","world!"]
print ', '.join(a)

output
Hello, world!

A: I get it, I tried several times, ' '.join()mains use whatever inside ' 'to split the list.
sry for  my stupid question.


text:
Q: Ler arquivo de texto e jogar o conteúdo em posições em um array! Estou em dúvida em poder ler um arquivo .txt e armazenar os seus dados em diferentes posições em um array.
Sendo que o arquivo é salvo da seguinte maneira:
city=A(100,80);
city=B(160,70);
city=C(110,50);
city=D(140,120);
city=F(155,40);
city=G(210,60);
city=H(190,10);
city=I(170,110);
route=A-C;140;
route=A-D;155;
route=C-F;125;
route=D-B;115;
route=D-I;152;
route=B-F;119;
route=B-G;136;
route=G-F;133;
route=F-H;163;
route=I-H;197;

E gostaria de ler ele e armazenar ele separadamente nas posições de um array.
<?php

$f = fopen("mapa.txt", "r");

while (!feof($f)) {
     $arrM = explode(";",fgets($f));
}

fclose($f);

?>

Nesse exemplo, ele está armazenando ele todo dentro de uma única posição!
E no caso gostaria que fosse armazenado assim:
$arrM[0] = city=A(100,80);
$arrM[1] = city=B(160,70);
$arrM[2] = city=C(110,50);
//.....

$arrM[] = route=A-C;140;

A: Se o arquivo não for muito grande, pode usar a função file() ela vai converter o seu arquivo em um array.
$f = file("mapa.txt");
foreach($f as $item){
   echo $item .'<br>';
}

A: Segue abaixo outra forma usando o explode e file_get_contents:
$linhas = explode("\n", file_get_contents('mapa.txt'));

echo $linhas[0] . "\n"; // city=A(100,80);
echo $linhas[1] . "\n"; // city=B(160,70);
echo $linhas[2] . "\n"; // city=C(110,50);
echo $linhas[9] . "\n"; // route=A-D;155;


text:
Q: PHP coding - A class for each view or one class to rule them all? I am starting my first "programming" project in PHP making some sort of web application that give the linux program, Motion, a decent web interface.
Anyways, I was curious as to how when real applications are programmed, do y'all go for a class for each view or one single class for the application altogether? I know this is more of a preference thing, I was just curious as to how it happens in real software.

A: I suggest using a framework like CodeIgniter or CakePHP. It separates your model (database), views (the HTML), and controllers (application logic). MVC is the way of future programming...

A: Views are generally not classes, but template files containing HTML with placeholders or echo statements. In that case, a single View class is required to parse the template file and display it.
Of course, each view can have its own instance (i.e.: an object) of the View rendering class and be called separately.

A: I would use a class for each view. You could watch codeigniter's screencasts to give you some guidance how to use MVC.

A: I'm not sure what's your understanding of a "view". If you think of the Model-View-Controller-Pattern, you definitely should create one class per view.
If you didn't had the MVC pattern in mind, I assume that "view" means the whole page which is displayed at a time. Then you should try to create components (aka widgets) instead of views. So that you can create pages by combining those components. It will make reuse and refactoring easier. But I know that PHP will make it difficult, because it is not component-based and you will have an hard time to seperate the life-cycles of the components.
Also notice that there is a front-controller pattern, which will route all requests through a single class, but it is only routing requests and not rendering the whole "view".


text:
Q: SharedPreferences into a ViewPager I need to load my preferences.xml file based on SharedPreferences into a ViewPager.
I am getting this error:
java.lang.IllegalStateException: Content view not yet created

I was searching for a solution but I can't found anything. What can I do?
MainActivity.java
public class MainActivity extends FragmentActivity {

    private CustomViewPager customViewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_layout);
        customViewPager = (CustomViewPager) findViewById(R.id.pager);
        customViewPager.setAdapter(new CustomPagerAdapter());
        customViewPager.setPageMargin(0);
        PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
    }

    private class CustomPagerAdapter extends PagerAdapter {

        @Override
        public Object instantiateItem(ViewGroup viewGroup, int position) {
            RelativeLayout viewLayout = null;
            LayoutInflater inflater = (LayoutInflater) viewGroup.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            switch (position) {

            case 0:
                viewLayout = (RelativeLayout) inflater.inflate(R.layout.list_meetings, null);
                viewGroup.addView(viewLayout, 0);
                break;

            case 1:
                viewLayout = (RelativeLayout) inflater.inflate(R.layout.settings, null);
                viewGroup.addView(viewLayout, 0);

                getFragmentManager().beginTransaction().replace(android.R.id.content, new FragmentPreferences()).commit();
                break;
            }
            customViewPager.setObjectForPosition(viewLayout, position);
            return viewLayout;
        }

        @Override
        public int getCount() {
            return 2;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }
    }

    public static class FragmentPreferences extends PreferenceFragment {

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.preferences);
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

            // View view = inflater.inflate(R.layout.settings, null);
            // return view;

            return null;
        }
    }
}

settings.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</RelativeLayout>

preferences.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

    <ListPreference
        android:key="speed_setting"
        android:title="@string/speed_setting_title"
        android:summary="@string/speed_setting_description"
        android:dialogTitle="@string/speed_setting_title"
        android:entries="@array/speed_setting_entry_labels"
        android:entryValues="@array/speed_setting_entry_labels"
        android:defaultValue="@string/speed_setting_default_value"
        android:icon="@drawable/ic_list_speed_setting" />
    <ListPreference
        android:key="permission_type_setting"
        android:title="@string/permission_type_setting_title"
        android:summary="@string/permission_type_setting_description"
        android:dialogTitle="@string/permission_type_setting_title"
        android:entries="@array/permission_type_setting_entry_labels"
        android:entryValues="@array/permission_type_setting_entry_labels"
        android:defaultValue="@string/permission_type_setting_default_value"
        android:icon="@drawable/ic_list_permission_type_setting" />
    <ListPreference
        android:key="sensibility_setting"
        android:title="@string/sensibility_setting_title"
        android:summary="@string/sensibility_setting_description"
        android:dialogTitle="@string/sensibility_setting_title"
        android:entries="@array/sensibility_setting_entry_labels"
        android:entryValues="@array/sensibility_setting_entry_labels"
        android:defaultValue="@string/sensibility_setting_default_value"
        android:icon="@drawable/ic_list_sensibility_setting" />
    <ListPreference
        android:key="time_format_setting"
        android:title="@string/time_format_setting_title"
        android:summary="@string/time_format_setting_description"
        android:dialogTitle="@string/time_format_setting_title"
        android:entries="@array/time_format_setting_entry_labels"
        android:entryValues="@array/time_format_setting_entry_labels"
        android:defaultValue="@string/time_format_setting_default_value"
        android:icon="@drawable/ic_list_time_format_setting" />
    <ListPreference
        android:key="maps_setting"
        android:title="@string/maps_setting_title"
        android:summary="@string/maps_setting_description"
        android:dialogTitle="@string/maps_setting_title"
        android:entries="@array/maps_setting_entry_labels"
        android:entryValues="@array/maps_setting_entry_labels"
        android:defaultValue="@string/maps_setting_default_value"
        android:icon="@drawable/ic_list_maps_setting" />
    <ListPreference
        android:key="resource_consumption_setting"
        android:title="@string/resource_consumption_setting_title"
        android:summary="@string/resource_consumption_setting_description"
        android:dialogTitle="@string/resource_consumption_setting_title"
        android:entries="@array/resource_consumption_setting_entry_labels"
        android:entryValues="@array/resource_consumption_setting_entry_labels"
        android:defaultValue="@string/resource_consumption_setting_default_value"
        android:icon="@drawable/ic_list_resource_consumption_setting" />
</PreferenceScreen>

A: use PreferenceFragment. But it is only available after api level 11. You can find the details with clear example in the link


text:
Q: Populate input datetime-local in Angular I need to put a default value in my input datetime-local but for some reason it is not populated in angular. Please tell me what I need to do to make this right. My code is below

    <input
      formControlName="completionDate"
      type="datetime-local"
      id="completionDate"
      placeholder="yyyy-MM-ddTHH:mm:ss"
      [min]="date"
      class="form-control"
      required
    />

populateDate(): string {
    this.dateObj = new Date();
    this.month = this.dateObj.getUTCMonth() + 1;
    this.day = this.dateObj.getUTCDate();
    this.year = this.dateObj.getUTCFullYear();

    return `${this.year}-${this.month}-${this.day}`;
}

createTroubleTicketForm() {
    this.troublTicketForm = this.fb.group({
      ttNum: [null, Validators.required],
      status: [null, Validators.required],
      completionDate: [null],
      incident: [null, Validators.required],
      rootCause: [null, Validators.required],
      resolution: [null],
      category: [null, Validators.required],
      plazaCode: [null, Validators.required],
      laneNum: [null, Validators.required],
      reportedBy: [null],
      helpDeskAgent: [null, Validators.required],
      assignedToTier: [null],
      ticketCreated: [this.populateDate(), Validators.required],
      remarks: [null]
    });
}

A: You'd need to convert date into ISO format before it could be assigned via [ngModel];
relevant TS:
  completeDate: Date;
  localCompleteDate: string;
  constructor() {
    this.completeDate = new Date();
    this.localCompleteDate = this.completeDate.toISOString();
    this.localCompleteDate = this.localCompleteDate.substring(0, this.localCompleteDate.length - 1);
  }

relevant HTML:
<input
  type="datetime-local"
  id="completionDate"
  [ngModel] = "localCompleteDate"
  placeholder="yyyy-MM-ddTHH:mm:ss"
  [min]="date"
  class="form-control"
  required
/>

Date: {{completeDate | date:'short'}}

ISO Date: {{ localCompleteDate }}

check complete working stackblitz here


text:
Q: Cannot resolve symbol 'Registration' My imports:
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;

import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.extensions.android.json.AndroidJsonFactory;
import com.google.api.client.googleapis.services.AbstractGoogleClientRequest;
import com.google.api.client.googleapis.services.GoogleClientRequestInitializer;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

Part of the code:
private static Registration regService = null;
private GoogleCloudMessaging gcm;
private Context context;

And they cannot resolve the symbol 'Registration'. I dont know and dont find, what I have to compile.


text:
Q: How to do incremental backup every hour in Postgres? Trying to do an hourly incremental backup of a single Postgres server (Win7 64).
I have the following setup in postgresql.conf:
max_wal_senders = 2
wal_level       = archive
archive_mode    = on
archive_command = 'copy "%p" "c:\\postgres\\foo\\%f"'

(restart)
I did a base backup with pg_basebackup -U postgres -D ..\foo -F t -x
Which made a big base.tar file in the foo folder and added some 16,384 KB files, which I assume are WALs.
What I don't understand is why the WALs in foo don't change. The WALs in data/pg_xlog change. Is pg not supposed to copy them over? How does it decide to do so?
Perhaps I need to set archive_timeout=3600 ?
I've seen several sites (pg's mailing lists, bacula's postgres page) that say you need to call pg_start_backup() and pg_stop_backup(), but I believe that those are not required. Is that true?
Secondary questions:

*

*How often do the WALs in data/pg_xlog get written? What triggers a write?
It seems to update a WAL if I do some DML then \q in psql. Or edit a table in pgAdmin then close the window. I figured it would write on commit.

*Best practices? pg_basebackup once a week? Archive WALs to same machine as PG or a remote machine?

A: There is an existing tool that'll help you a great deal, WAL-E. It provides an archive_command and restore_command for PITR to S3.
There are no commands to do incremental or differential logical backups. pg_dump can't take an incremental or differential. The only way to do that is via log archiving.
In theory you could take a new full backup, do a binary diff between it and the last backup, and upload the diff. This strikes me as a fragile and inefficient way to do things, though, and I really wouldn't recommend it.
Additionally, PgBarman supports integration with S3 via hook scripts, and will automate much of the backup rotation and management for you. Again, this may not be an option on Windows.

A: You want to do an incremental backup of the archive folder to remote storage.
Should you need to restore from the backup, the basic scenario is that you'd need your base backup as the starting point, and the entire contents of the archive folder to replay the transactional activity that happened between the starting point and the crash.
Also to avoid having the files in the archive folder piling up forever, you want to do a new base backup from time to time and delete the files that were archived before the new base backup.


text:
Q: Reactive 2d canvas I'm working on a tool that has an underlying 3d spacial representation, but renders views of itself in 2d. There may be as many as 1000 shapes on the screen at once. I'm having trouble keeping the view in sync with the models, so I want to start using a reactive solution (like Konva for React), but it is not particularly performant.
Are there any reactive webgl or otherwise more performant solutions that allow me to have a state and reliably render a canvas that reflects that state? Or maybe I am just approaching this problem from the wrong direction?

A: I do not know how performant you would like it to be.
I have build one 2d engine with canvas for my project with no lib. I have one main Component that renders the canvas itself. Then i use redux to draw. All the business logic is done on the reducers. For my, its pretty performant. Then i have one file to draw what the reducers derived.
So the flow is like.
Canvas.js -> actions -> reduxMiddlewares -> reducers -> Drawer.js


text:
Q: Виртуальная клавиатура Google сделал виртуальную клавиатуру. На каких языках программирования она сделана
и как называется способ перемещение объекта с помощью мышки в окне браузера, который применили при создании виртуальной клавиатуры (google.com)?
A: Это JavaScript: Google Virtual Keyboard Developer's Guide. Перемещать элемент можно по разному в зависимости от задачи: либо меняя координаты div'а в соответствии с движениями мыши, либо используя Drag'Drop.


text:
Q: Passing multiple parameter using '?' mark in web urls http://xyz.com/packagesearch?cadu1=2&drtn1=05/08/2012&qryt=8&sort=10&drid1=1639&dlvl&rdct=1&star=30&subm=1&subm=1&inttkn=Dul0p4RNrlTnd61R&dsct&cmbt=2?dnam&tdpt1=362&ffst=0&rtmx&trtn1=362&tair1=IST&dcty=PAR&mcicid=174390028&rtmn&ddpt1=02/08/2012?stop_mobi=yes
what exactly this '?' does? can i use it multiple times or '&' is the only option to pass multiple parameter when '?' is already used once?
note: occurrence marked as bold.

A: The ? character in a URL signifies the start of the "request parameters", or "query string".  Additional parameters after that have to start with &.  You can develop your own way of handling "query strings", but most programming/scripting languages I know of already have built in ways of dealing with them, so it is generally easier to use the existing tools.

A: From http://en.wikipedia.org/wiki/Query_string

When a server receives a request for such a page, it runs a program
  (if configured to do so), passing the query_string unchanged to the
  program. The question mark is used as a separator and is not part of
  the query string.

As a result, ? should only be used once.


text:
Q: SearchCursor is outside tuple range despite having multiple fields in the parameter In the below script, I get an error on line that starts with insertRow that says IndexError: tuple index out of range.
outputLocation = arcpy.GetParameterAsText(0)
nullPntFc = arcpy.GetParameterAsText(1)
outPolyPath = arcpy.GetParameterAsText(2)

arcpy.CreateFeatureclass_management(outputLocation, nullPntFc, "POINT")
arcpy.management.AddField(os.path.join(outputLocation, nullPntFc), "FC", "TEXT")
arcpy.management.AddField(os.path.join(outputLocation, nullPntFc), "FC_objectId", "LONG")
arcpy.management.AddField(os.path.join(outputLocation, nullPntFc), "AttributeMissing", "TEXT")

# Get the list of feature classes in the geodatabase
fcListLine = arcpy.ListFeatureClasses("*Section", feature_dataset = "ARCFM.ElectricDataSet")
fcListPoint = arcpy.ListFeatureClasses("*Transformer", feature_dataset = "ARCFM.ElectricDataSet") + arcpy.ListFeatureClasses("*Bank", feature_dataset = "ARCFM.ElectricDataSet") + arcpy.ListFeatureClasses("*Location", feature_dataset = "ARCFM.ElectricDataSet")
fcListSelection = fcListLine + fcListPoint

for fc in fcListSelection:
    # Describe feature class to get attributes used in nullPntFc, nullPolylineFc, and nullPolygonFc.
    desc = arcpy.Describe(fc)
    fcName = desc.name
    fcType = desc.shapeType # Point, Polyline, Polygon
    arcpy.AddMessage(fcName + ' - '+ fcType)
    # get the field names to be used in the search cursor
    fieldNames = [field.name for field in arcpy.ListFields(fc) if field.name.endswith("FEEDERID") or field.name.endswith("LOCATIONID") or field.name.endswith("PHASINGCODE")] + ['SHAPE@XY']
    arcpy.AddMessage(fieldNames)
    # Get the shape field index from the list of fields.  The index will be used in the search cursor to pull the shape value
    fields = arcpy.ListFields(fc)
    for field in fields:
        if field.type == 'Geometry':
            shapeFieldIndex = fields.index(field)

    # Dump point features with null attributes in the point feature classes into nullPntFc
        if fcType == 'Point':
            count = 0
            while count < len(fieldNames) - 1:
                with arcpy.da.SearchCursor(fc,fieldNames) as sc:
                    for row in sc:
                        if row[0] == None or row[1] == None or row[2] == None:
                            arcpy.AddMessage(fieldNames)
                            fieldName = fieldNames[count]
                            insertCursor = arcpy.da.InsertCursor(os.path.join(outputLocation, nullPntFc), ('SHAPE@XY', 'FC', 'FC_objectId', 'AttributeMissing'))
                            insertRow = [row[shapeFieldIndex], fcName, str(row[0]), fieldName]
                            print(insertRow)
                            insertCursor.insertRow(insertRow)
                            del insertCursor
                count += 1

I know that the error is caused by the row[shapeFieldIndex] being outside the range of the SearchCursor, which has the parameter fieldNames that contains the fields I want to pass the loop through. I am not sure why the searchCursor is going outside the range of fieldNames when I defined multiple fields in it.


text:
Q: How to get end of process time per processor using "pool" in Python? I use Multiprocessing library in Python to distribute a function over multiple cores. To do that I use "Pool" function, but I want to know when each processor has completed its work.
Here is the code :
def parallel(m,G):

   D=0
   for i in xrange(G):
        D+=random()

   return 1*(D<1)

pool=Pool()

TOTAL=0
for i in xrange(10):
    TOTAL += sum(pool.map(partial(parallel,G=2),xrange(100)))
print TOTAL

I know how to use time.time() in normal situation, but what I need is to know when each core has completed is part of the job. If I put a time stamp directly in the function I will get many time values without knowing on what core it is processed.
Any advice is welcome!

A: You may return the completion time along with the actual result from parallel and then pick the last timestamp for each worker.
import time
from random import random
from functools import partial
from multiprocessing import Pool, current_process

def parallel(m, G):
    D = 0
    for i in xrange(G):
        D += random()
    # uncomment to give the other workers more chances to run
    # time.sleep(.001)
    return (current_process().name, time.time()), 1 * (D < 1)

# don't deny the existence of Windows
if __name__ == '__main__':
    pool = Pool()
    TOTAL = 0
    proc_times = {}
    for i in xrange(5):

        # times is a list of proc_name:timestamp pairs
        times, results = zip(*pool.map(partial(parallel, G=2), xrange(100)))
        TOTAL += sum(results)

        # process_times_loc is guaranteed to hold the last timestamp
        # for each proc_name, see the doc on dict
        proc_times_loc = dict(times)
        print 'local completion times:', proc_times_loc

        proc_times.update(proc_times_loc)

    print TOTAL
    print 'total completion times:', proc_times

However when jobs are that simple you may find that calling time.time each time consumes too much of CPU time.)


text:
Q: Having issues in camera application
I am working on a application where I have to create a camera and save the captured images.
  the code I am writing is here:

package com.dev.camera;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {

    Button cambutton;
    ImageView photoImage = null;

    private static final String TAG = "CallCamera";
    private static final int CAPTURE_IMAGE_ACTIVITY_REQ = 0;

    Uri fileUri = null;
    //ImageView photoImage1 = null;

    private File getOutputPhotoFile() {

          File directory = new File(Environment.getExternalStoragePublicDirectory(
                        Environment.DIRECTORY_PICTURES), getPackageName());

          if (!directory.exists()) {
            if (!directory.mkdirs()) {
              Log.e(TAG, "Failed to create storage directory.");
              return null;
            }
          }

          String timeStamp = new SimpleDateFormat("yyyMMdd_HHmmss", Locale.US).format(new Date());

          return new File(directory.getPath() + File.separator + "IMG_"
                            + timeStamp + ".jpg");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button camButton = (Button)findViewById(R.id.btncam);
        ImageView photoImage = (ImageView)findViewById(R.id.iv);

        camButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                Intent i = new Intent (MediaStore.ACTION_IMAGE_CAPTURE);

                fileUri = Uri.fromFile(getOutputPhotoFile());
                i.putExtra(MediaStore.EXTRA_OUTPUT,fileUri);

                startActivityForResult(i, CAPTURE_IMAGE_ACTIVITY_REQ);

            }
        });

    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
          if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQ) {
            if (resultCode == RESULT_OK) {
              Uri photoUri = null;
              if (data == null) {
                // A known bug here! The image should have saved in fileUri
                Toast.makeText(this, "Image saved successfully",
                               Toast.LENGTH_LONG).show();
                photoUri = fileUri;
              } else {
                photoUri = data.getData();
                Toast.makeText(this, "Image saved successfully in: " + data.getData(),
                               Toast.LENGTH_LONG).show();
              }
              showPhoto(photoUri.getPath());
            } else if (resultCode == RESULT_CANCELED) {
              Toast.makeText(this, "Cancelled", Toast.LENGTH_SHORT).show();
            } else {
              Toast.makeText(this, "Callout for image capture failed!",
                             Toast.LENGTH_LONG).show();
            }
          }
    }

    private void showPhoto(String photoUri) {
          File imageFile = new File (photoUri);
          if (imageFile.exists()){
             Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
             BitmapDrawable drawable = new BitmapDrawable(this.getResources(), bitmap);
             photoImage.setScaleType(ImageView.ScaleType.FIT_CENTER);
             photoImage.setImageDrawable(drawable);
          }
    }

}

here is the xml file I am using for this application.
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    tools:context="${relativePackage}.${activityClass}"
    android:background="#858500">

    <Button
        android:id="@+id/btncam"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="take picture"
        android:gravity="center"/>
    <ImageView
        android:id="@+id/iv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button_callcamera"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="80dp"
        android:src="@drawable/ic_launcher"/>

</RelativeLayout>

when I am running this code, I am getting an error that failed to create storage directory.  It would be very thankful if someone can help me out.

A: Use this code..I have made some changes in your files..
package com.example.sampleapp;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {

Button cambutton;
ImageView photoImage = null;

private static final String TAG = "CallCamera";
private static final int CAPTURE_IMAGE_ACTIVITY_REQ = 0;

Uri fileUri = null;

private File getOutputPhotoFile() {
      File directory = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_PICTURES), getPackageName());
      if (!directory.exists()) {
        if (!directory.mkdirs()) {
          Log.e(TAG, "Failed to create storage directory.");
          return null;
        }
      }
      String timeStamp = new SimpleDateFormat("yyyMMdd_HHmmss", Locale.US).format(new    Date());
      return new File(directory.getPath() + File.separator + "IMG_"
                        + timeStamp + ".jpg");
    }

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Button camButton = (Button)findViewById(R.id.btncam);
    photoImage = (ImageView)findViewById(R.id.iv);

    camButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            Intent i = new Intent (MediaStore.ACTION_IMAGE_CAPTURE);

            fileUri = Uri.fromFile(getOutputPhotoFile());
            i.putExtra(MediaStore.EXTRA_OUTPUT,fileUri);

            startActivityForResult(i, CAPTURE_IMAGE_ACTIVITY_REQ);

        }
    });

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
      if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQ)
      {
        if (resultCode == RESULT_OK) {
          Uri photoUri = null;
          if (data == null) {
            // A known bug here! The image should have saved in fileUri
            Toast.makeText(this, "Image saved successfully",Toast.LENGTH_LONG).show();
            photoUri = fileUri;
            showPhoto(photoUri);
          } else {
            photoUri = data.getData();
            showPhoto(photoUri);
            Toast.makeText(this, "Image saved successfully in: " + data.getData(),
                           Toast.LENGTH_LONG).show();
          }

        } else if (resultCode == RESULT_CANCELED) {
          Toast.makeText(this, "Cancelled", Toast.LENGTH_SHORT).show();
        } else {
          Toast.makeText(this, "Callout for image capture failed!",
                         Toast.LENGTH_LONG).show();
        }
      }
}

private void showPhoto(Uri photoUri) {
      File imageFile = new File(photoUri.getPath());
      if (imageFile.exists()){
         Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
         BitmapDrawable drawable = new BitmapDrawable(this.getResources(), bitmap);
         photoImage.setScaleType(ImageView.ScaleType.FIT_CENTER);
         photoImage.setImageDrawable(drawable);
      }
    }
}

and here is your xml file :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context="${relativePackage}.${activityClass}"
android:background="#858500">

<Button
    android:id="@+id/btncam"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="take picture"
    android:gravity="center"/>

<ImageView
    android:id="@+id/iv"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/btncam"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="80dp"
    android:src="@drawable/ic_launcher"/>

</RelativeLayout>

add these permissions to manifest file :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />


text:
Q: Is there any way to insert csv file data using cassandra stress? I have explored bit on cassandra stress tool using yaml file and it is working fine. I just wanted to know is there anyway by which we can specify the location of any external csv file in yaml profile to insert data into Cassandra table using cassandra stress?
So instead of random data i wanted to see the cassandra stres test result on specific dataload on this data model?

A: Standard cassandra-stress doesn't have such functionality, but you can use the NoSQLBench tool that was recently open sourced by DataStax. It also uses YAML to describe workloads, but it's much more flexible, and has a number of functions for sampling data from CSV files.
P.S. there is also a separate Slack workspace for this project (to get invite, fill this form)


text:
Q: Spring @RequestBody validation issue using @Valid annotation I am trying to perform validation on Spring Boot @RequestBody JSON object using @Valid annotation.
This JSON object POJO class will contain another nested object.
I have added field-level annotation for the nested object classes.
Also, I have added the @Valid annotation when adding the nested class object in the main object class.
But still, the validation for the nested class objects is not getting triggered when we are not passing the correct object.
Please find the code below for reference.
ExceptionController.class
@RestController
@RequestMapping("/student")
public class ExceptionController {

  @PostMapping
  @ResponseStatus(HttpStatus.CREATED)
  public String createStudent(@Valid @RequestBody Student student, HttpStatus status) {
    Student student1 = student;
    return "student data created!!";
  }
}

Student.class
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student {
  @NotEmpty(message = "First Name field can not be null or empty")
  @NotBlank(message = "First Name field can not be blank")
  private String firstName;
  @NotEmpty(message = "Last Name field can not be null or empty")
  @NotBlank(message = "Last Name field can not be blank")
  private String lastName;
  @Valid
  private Subject subject;
}

Subject.class
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Subject {
  @NotEmpty(message = "Topic field can not be null or empty")
  @NotBlank(message = "Topic field can not be blank")
  private String topic;
}

When I am not sending any data for Subject in the request it is not giving any exception and returns HTTP 200 OK status.
Any help will be highly appreciated.

A: Try adding @NotNull annotation to Subject subject:
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student {
  @NotEmpty(message = "First Name field can not be null or empty")
  @NotBlank(message = "First Name field can not be blank")
  private String firstName;
  @NotEmpty(message = "Last Name field can not be null or empty")
  @NotBlank(message = "Last Name field can not be blank")
  private String lastName;
  @Valid
  @NotNull
  private Subject subject;
}

Your current validations would only work if you actually send Subject data but with an empty topic attribute.
On another topic, you might drop the @NotEmpty annotations because @NotBlank does not allow null or empty Strings.


text:
Q: Installing or building boost - Windows cannot access specified device, path, or file I am try to get working boost with version 1_75_0-msvc-14.2-32 from https://sourceforge.net/projects/boost/files/boost-binaries/1.75.0/ or build my own 1.75 boost version, but every time when I try to install it from link above, or try to open b2.exe to build my own version, I am getting error

Windows cannot access the specified device, path, or file. You may not have the appropriate permissions to access the item.

The main problem is that I can not find any log file from witch I can know what is causing this problem, so does anyone know what I should do?

I was also trying to run some other versions of installer and found that boost_1_75_0-msvc-14.1-64 version install without any problems, but this version is usless for me because I need 32x version
The remaining 1.75 versions of installer that I tried and give me same error as above was - 11.0-32, 11.0-64, 14.1-32, 14.2-32

A: I found the solution, my antivirus was blocking some msvc files


text:
Q: Contact permissions problem in android manifest I need to set the permission in the manifest to read, I manually edited the manifest after having problems trying to use the android manifest editor. My code is below and is currently proving to be erroneous. Any help appreciated. :)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="ac.uk.d"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".Quiz"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    <uses-sdk android:minSdkVersion="7" />
    <uses-permission android:name="android.permission.READ_CONTACTS"/>
</manifest>

A: The issue is that you have not cleaned the project. To clean the project, select 'Project' on the top menu bar then you'll find clean upon which you clean the selected project or clean all projects as per your needs..


text:
Q: How to set authSource in MongoDB ODBC driver? I'm trying to set up a System DSN with MongoDB ODBC driver (v1.4.2) on Windows 10 but connection always fails.
I'm guessing it's because I need to set up the authSource but I don't know how.
In their documentation (https://docs.mongodb.com/bi-connector/master/tutorial/create-system-dsn/), it says to pass it on with the username like this:
grace?source=admin

But I tried that and it didn't work either.
Here's how I'm doing it
the error = "Lost connection to MySQL server at reading initial communication packet"


text:
Q: Ruby google_drive gem oAuth2 saving So before the update there was a simple way to log into google drive and manipulate your google docs - with ruby.
Before you were able to log into your google drive with this.
require 'google_drive'
$session = GoogleDrive.login("email@gmail.com", "password")

But now you get the warning message:
WARNING: GoogleDrive.login is deprecated and will be removed in the next version. Use GoogleDrive.login_with_oauth instead.

So I went to the git hub page to see how google wants us to use their services with high level languages, and found out they want us to use oAuth2. Like so.
require 'google/api_client'
require 'google_drive'

client = Google::APIClient.new(
  :application_name => 'Example Ruby application',
  :application_version => '1.0.0'
)
auth = client.authorization
auth.client_id = "YOUR CLIENT ID"
auth.client_secret = "YOUR CLIENT SECRET"
auth.scope =
    "https://www.googleapis.com/auth/drive " +
    "https://spreadsheets.google.com/feeds/"
auth.redirect_uri = "urn:ietf:wg:oauth:2.0:oob"
print("1. Open this page:\n%s\n\n" % auth.authorization_uri)
print("2. Enter the authorization code shown in the page: ")
auth.code = $stdin.gets.chomp
auth.fetch_access_token!
access_token = auth.access_token

$session = GoogleDrive.login_with_oauth(access_token)

This is fine and all but I can't save the auth variable.
I would like to hard code this in the script so I don't have to keep going to google to get a new access_token.
So I've tried to get the access_token and adding it to the script like so.
require 'google/api_client'
require 'google_drive'

client = Google::APIClient.new
access_token = "TokenFromGoogleHardCoded"

$session = GoogleDrive.login_with_oauth(access_token)

# $session doesn't connect

I'm not sure I'm attacking this problem in the correct manor. I would like to save the complete auth variable and hard code it in my scripts.

A: I figured out this mess.
auth.scope =
    "https://www.googleapis.com/auth/drive " +
    "https://spreadsheets.google.com/feeds/"

The auth.scope is missing a url. REFERENCE from github
auth.scope =
    "https://docs.google.com/feeds/" +
    "https://www.googleapis.com/auth/drive " +
    "https://spreadsheets.google.com/feeds/"

You can reuse your access_token, but first you need to get it. WARNING: The auth.access_token is only good for an hour. If you need another one you need to call auth.refresh! This will issue you another access_token.
require 'google/api_client'
require 'google_drive'

client = Google::APIClient.new(
  :application_name => 'Example Ruby application',
  :application_version => '1.0.0'
)
auth = client.authorization
auth.client_id = "YOUR CLIENT ID"
auth.client_secret = "YOUR CLIENT SECRET"
auth.scope =
    "https://www.googleapis.com/auth/drive " +
    "https://spreadsheets.google.com/feeds/"
auth.redirect_uri = "urn:ietf:wg:oauth:2.0:oob"
print("1. Open this page:\n%s\n\n" % auth.authorization_uri)
print("2. Enter the authorization code shown in the page: ")
auth.code = $stdin.gets.chomp
auth.fetch_access_token!
access_token = auth.access_token

system'clear'
print "Save your access token\n\n"
print access_token
print "\nSave your refresh token\n\n"
print auth.refresh_token

This chunk of code should print out your access_token/refresh_token in your console. Now you can hard code your application.
require "google/api_client"
require "google_driver"
client = Google::APIClient.new(
  :application_name => 'Example Ruby application',
  :application_version => '1.0.0'
)
auth = client.authorization
auth.client_id = "Your Client ID"
auth.client_secret = "Your client secret"

access_token = "token you saved from the terminal"

session = GoogleDrive.login_with_oauth(access_token)

for file in session.files
   p file.title
end

And eventually your "access_token" will expire. At this point you need to "refresh" it. You can call to see if your access_token is expired by calling
auth.expires_at

You can get a new access token with this example.
require 'google/api_client'
require 'google_drive'

$client_id = "YOUR CLIENT ID"
$client_secret = "YOUR CLIENT SECRET"
$refresh_token = "SAVED REFRESH TOKEN"

 client = Google::APIClient.new(:application_name => 'Example Ruby application', :application_version => '1.0.0')
    auth = client.authorization
    auth.client_id = $client_id
    auth.client_secret = $client_secret
    auth.scope = "https://docs.google.com/feeds/" + "https://www.googleapis.com/auth/drive " + "https://spreadsheets.google.com/feeds/"
    auth.redirect_uri = "urn:ietf:wg:oauth:2.0:oob"
    auth.refresh_token = $refresh_token

    #here's the magic sauce
    auth.refresh!

    #as you can see above auth.access_token wasn't passed a value
    # but if you call it now you'll see you have a new access_token

    auth.access_token
    => new token from server

A: You might find it easier to use service accounts, as outlined here:
https://github.com/gimite/google-drive-ruby/issues/126#issuecomment-73542381

A: Although Duck1337's answer will work, you don't actually need to call auth.refresh! with google_drive 1.0.*.
All you need to do is save the refresh_token from when you provided the authorization code in the first instance and then always pass that before calling auth.fetch_access_token! and the tokens will automatically get refreshed.
Below is what I use to login.  I use Environment variables rather that code constants, so I can add them to Heroku Config Vars and also to keep sensitive data out of the code.
client = Google::APIClient.new
    auth = client.authorization
    auth.client_id = ENV['GOOGLE_CLIENT_ID']
    auth.client_secret = ENV['GOOGLE_CLIENT_SECRET']
    auth.scope = [
        "https://www.googleapis.com/auth/drive",
        "https://spreadsheets.google.com/feeds/"
    ]
    auth.redirect_uri = "urn:ietf:wg:oauth:2.0:oob"

    if ENV['GOOGLE_REFRESH_TOKEN'] == "0" # Always start with 0 in your .env file, e.g. GOOGLE_REFRESH_TOKEN = 0
      puts("1. Open this page:\n%s\n\n" % auth.authorization_uri)
      puts("2. Enter the authorization code shown in the page: ")
      auth.code = $stdin.gets.chomp
    end if

    auth.refresh_token = ENV['GOOGLE_REFRESH_TOKEN'] #this will be 0 the first time around, but that's OK
    auth.fetch_access_token!

    if ENV['GOOGLE_REFRESH_TOKEN'] == "0"
      puts("3. Save this refresh token:\n%s\n\n" % auth.refresh_token) # you can now replace the 0 in your .env file with this token, so it'll be used permanently.  You can also add this to the Heroku Config Vars.
      ENV['GOOGLE_REFRESH_TOKEN'] = auth.refresh_token #we'll set it here, so it works without having to alter the .env file for this call
    end if

    GoogleDrive.login_with_oauth(auth.access_token)

A: Use capybara and navigate to the token page.  Grab it from the page source and save to a variable.  Plug the variable when needed.  The token string expires so I grab a new one each time I need to access the spreadsheet.


text:
Q: How did Einstein relate energy and the curvature of spacetime? My understanding of the mathematics of General Relativity is quite limited. So I am not expecting any mathematically rigorous answers, but what I do understand is that energy curves spacetime, which in turn dictates the motion of energy and mass. I've seen a lot of videos which explain why einstein thought of the universe as 4D space but non of them seem to explain how he related energy, pressure and stress to the curvature of spacetime

*

*I understand why einstein proposed that energy curves spacetime, but how did he know how much mass curves how much spacetime? I could randomly say that the curvature is linear with radius for a spherical mass which is not true. Where did einstein get his constraint from? that relates energy and curvature?

Is this the conservation of some quantity?

A: Ultimately the justification for Einstein's equation was experimental.
The assumption that the equivalence principle holds strongly suggests that gravity has to be described by a metric theory, that is the theory relates the curvature of spacetime to some property of the matter and energy present. The first such theory was Nordström's theory of gravity proposed in 1913, in which the field equation is simply:
$$ R = 24\pi T $$
where $R$ is the Ricci scalar and $T$ is the trace of the stress-energy tensor. This is a perfectly good theory of gravity with all the features we expect. It respects the equivalence principle and is derivable from an action principle. But it was unable to account for the perihelion shift of Mercury and predicted that gravitational lensing did not occur, while Einstein's equation:
$$ R_{\mu\nu} - \frac{1}{2} R\,g_{\mu\nu} =
  8 \pi T_{\mu\nu} $$
does correctly describe Mercury's orbit and gravitational lensing.
Einstein's equation is not the unique theory relating curvature and mass/energy but it is the simplest one that works. That's why Einstein chose it.

A: There is a gravitational constant $\mathbf{G}$ in Einstein field equations:
$$
R_{\mu\nu} - \frac{1}{2} R g_{\mu\nu} + \Lambda g_{\mu\nu} =
  \frac{8 \pi \mathbf{G}}{c^4} T_{\mu\nu}
$$
For non-relativistic setting the predictions must match existing observations, i.e. Newton's gravitation law. This is why Newton's gravitational constant is there.

A: So as somebody above pointed out, Einstein's field equations are;
$$
G^{\mu \nu} = \frac{8 \pi G}{c^{4}} T^{\mu \nu}
$$
Where $G^{\mu\nu}$ is a mathematical object that describes the curvature of the $4D$ spacetime. The object $T^{\mu\nu}$ is called the stress-energy tensor, and describes the energy, pressure, matter content of the spacetime. So essentially we have:
$$
\left(\mathrm{Curvature} \right) \ = \ \frac{8 \pi G}{c^{4}}  \times \left(\mathrm{Energy\ and\ Stuff}\right)
$$
The story I have heard is the following:

*

*We know that energy and momentum and so on must all be conserved: this condition can be very compactly written as $\nabla_{\nu} T^{\mu\nu} = 0$ (in simple terms it's basically saying that the derivative of $T$ is zero, and so it's overall energy/momentum content stays constant).

*The mathematics involved with the development of this $G^{\mu\nu}$ object requires that $\nabla_{\nu} G^{\mu\nu} = 0$
I suppose because of his thoughts on the equivalence principle (??) Einstein suspected that energy and curvature are related to each other. Since $\nabla_{\nu} T^{\mu\nu} = 0 = \nabla_{\nu} G^{\mu\nu}$, he said that $T^{\mu\nu} \propto G^{\mu\nu}$ and came up with the above equation (after putting in some constants to make the units work).
Interesting side note: $G^{\mu\nu}$ is the simplest curvature object which obeys $\nabla_{\nu}G^{\mu\nu}=0$, but there are other more complicated ones that could have been used.


text:
Q: javascript vbcript seek eof I am writing a destop script on windows 2003 and I need to open a file and seek to the end of it and read the last line.
I looked for a "seek" but couldn't find. I saw the openTextFile for option but didn't have.
I implement it by openning the file with the red flag and then reading line after line.
With big file it takes a time,
Do any one know how to do this quickly (either in vb script or javascript)

A: I can't think of a straightforward way to do it except for maybe reading the whole file, splitting into an array and popping the last line off:
var fso   = new ActiveXObject("Scripting.FileSystemObject");
var tf    = fso.OpenTextFile("c:\\testfile.txt", 1 /*for reading*/, false);

// Split all lines into an array
var lines = tf.ReadAll().split("\r\n");

// Get the last line from the file:
var lastLine = lines.pop();

I've done this on a number of occasions and it should be faster than a loop.


text:
Q: Connect backend with database in docker I have simple phpmyadmin, mysql containers.
I create new folder with backend in nodejs. At now, I just can't connect to database through backend.
All three containers (phpmyadmin, mysql, api) works and launch. But container api don't connect with database.
This is my main db.js file for connection, which is always throw error.
const mysql = require("mysql");

const db = mysql.createConnection({
    host: "localhost",
    user: "db_user",
    password: "db_user_pass",
    database: "any-game",
    port: 8899,
});

db.connect((err) => {
    if (err) {
        throw new Error("Something went wrong!"); //  Get error always in this line because can't connect to db
    }
});

module.exports = db;

Url for phpmyadmin is localhost:8899. Phpmyadmin work as I expect. Without any error. I can log in to db through login and password in docker-compose. But can't connect with backend.
And docker-compose.yml file
version: "3"

services:
  phpmyadmin:
    image: phpmyadmin/phpmyadmin
    container_name: phpmyadmin1
    environment:
      - PMA_ARBITRARY=1
      - PMA_HOST=db
      - PMA_PORT=3306
    restart: always
    links:
      - db
    ports:
      - 8899:80
    depends_on:
      - db

  api:
    build: ./api
    container_name: api1
    command: npm run start
    restart: unless-stopped
    ports:
      - "3005:3005"
    environment:
      - PORT=3005
    depends_on:
      - phpmyadmin

  db:
    image: mysql
    container_name: db
    environment:
      - MYSQL_ROOT_PASSWORD=my_secret_password
      - MYSQL_DATABASE=guess-game
      - MYSQL_USER=db_user
      - MYSQL_PASSWORD=db_user_pass
    restart: always
    ports:
      - 6033:3306

I tried to write like this:
const db = mysql.createConnection({
    host: "localhost",
    user: "db_user",
    password: "db_user_pass",
    database: "any-game",
});

Like this
const db = mysql.createConnection({
    host: "localhost",
    user: "db_user",
    password: "db_user_pass",
    database: "any-game",
    port: 80,
});

Or
const db = mysql.createConnection({
    host: "localhost",
    user: "db_user",
    password: "db_user_pass",
    database: "any-game",
    port: 6033, // DB port
});

Even
const db = mysql.createConnection({
    host: "127.0.0.1",
    user: "db_user",
    password: "db_user_pass",
    database: "any-game",
});

Please help

A: When working with docker containers, to communicate with different containers, you can do in following ways

*

*Establish connection using hostname

*Establish connection using proxy and sidecar to make use of localhost.

In your case try following snippet,
const db = mysql.createConnection({
    host: "db",
    user: "db_user",
    password: "db_user_pass",
    database: "any-game",
    port: 3306,
});


text:
Q: UILabel in UICollectionViewCell I designed UICollectionViewCell in storyboard .Consists 2 elements UILabel, UIImageView.
for UILabel i given constrains leading=0, trailing=0, bottom=0, height=100
My collectionViewCell

But when i run in simulator:

Edit: when i observed in interface inspector, label is not attached to view on collectionView:

A: I solved issue by adding these lines in cellForItemAtIndexPath
[cell setNeedsLayout];
[cell layoutIfNeeded];


text:
Q: Open Settings application on Unity iOS I am in need of a way to make the user is taken to the Settings application to disable the multitasking gestures. I know that in iOS 8 you can launch the Settings application programmatically through the URL in Objective-C:
NSURL * url = [NSURL URLWithString: UIApplicationOpenSettingsURLString];

But I do not know how to get this URL in Unity to use with Application.OpenURL()

A: Using idea of JeanLuc, I create a empty XCode project and print the string constant UIApplicationOpenSettingsURLString and used in Unity with Application.OpenURL() to not have to use a plugin. Works very nice.
The value for constant UIApplicationOpenSettingsURLString is: "app-settings:" (without quotas).
Use: Application.OpenURL("app-settings:") to open directly from unity
WARNING: The use of hardcoded strings is dangerous and can break your code if Apple change the value of constant UIApplicationOpenSettingsURLString. Its just a workaround while Unity does not add a constant for reference in C# code.

A: You need to write a tiny iOS plugin for that, here is more information about it: http://docs.unity3d.com/Manual/PluginsForIOS.html
And here is your solution, ask if something should be unclear.
Script/Example.cs
using UnityEngine;

public class Example
{
    public void OpenSettings()
    {
        #if UNITY_IPHONE
            string url = MyNativeBindings.GetSettingsURL();
            Debug.Log("the settings url is:" + url);
            Application.OpenURL(url);
        #endif
    }
}

Plugins/MyNativeBindings.cs
public class MyNativeBindings
{
    #if UNITY_IPHONE
        [DllImport ("__Internal")]
        public static extern string GetSettingsURL();

        [DllImport ("__Internal")]
        public static extern void OpenSettings();
    #endif
}

Plugins/iOS/MyNativeBindings.mm
extern "C" {
    // Helper method to create C string copy
    char* MakeStringCopy (NSString* nsstring)
    {
        if (nsstring == NULL) {
            return NULL;
        }
        // convert from NSString to char with utf8 encoding
        const char* string = [nsstring cStringUsingEncoding:NSUTF8StringEncoding];
        if (string == NULL) {
            return NULL;
        }

        // create char copy with malloc and strcpy
        char* res = (char*)malloc(strlen(string) + 1);
        strcpy(res, string);
        return res;
    }

    const char* GetSettingsURL () {
         NSURL * url = [NSURL URLWithString: UIApplicationOpenSettingsURLString];
         return MakeStringCopy(url.absoluteString);
    }

    void OpenSettings () {
        NSURL * url = [NSURL URLWithString: UIApplicationOpenSettingsURLString];
        [[UIApplication sharedApplication] openURL: url];
    }
}


text:
Q: Sklearn NN regression Attendance prediction I asked a question about the same problem earlier, but because my approach has changed I now have different questions.
My current code:
from sklearn import preprocessing
from openpyxl import load_workbook
import numpy as np
from numpy import exp, array, random, dot
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPRegressor
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import classification_report,confusion_matrix
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
#Set sizes
rowSize = 200
numColumns = 4

# read  from excel file
wb = load_workbook('python_excel_read.xlsx')
sheet_1 = wb["Sheet1"]

date = np.zeros(rowSize)
day = np.zeros(rowSize)
rain = np.zeros(rowSize)
temp = np.zeros(rowSize)
out = np.zeros(rowSize)

for i in range(0, rowSize):
    date[i] = sheet_1.cell(row=i + 1, column=1).value
    day[i] = sheet_1.cell(row=i + 1, column=2).value
    rain[i] = sheet_1.cell(row=i + 1, column=3).value
    temp[i] = sheet_1.cell(row=i + 1, column=4).value
    out[i] = sheet_1.cell(row=i + 1, column=5).value

train = np.zeros(shape=(rowSize,numColumns))
t_o = np.zeros(shape=(rowSize,1))

for i in range(0, rowSize):
    train[i] = [date[i], day[i], rain[i], temp[i]]
    t_o[i] = [out[i]]

X = train
# Output
y = t_o

X_train, X_test, y_train, y_test = train_test_split(X, y)

####Neural Net
nn = MLPRegressor(
    hidden_layer_sizes=(3,),  activation='relu', solver='adam', alpha=0.001, batch_size='auto',
    learning_rate='constant', learning_rate_init=0.01, power_t=0.5, max_iter=10000, shuffle=True,
    random_state=9, tol=0.0001, verbose=False, warm_start=False, momentum=0.9, nesterovs_momentum=True,
    early_stopping=False, validation_fraction=0.1, beta_1=0.9, beta_2=0.999, epsilon=1e-08)
nn.fit(X_train, y_train.ravel())

y_pred = nn.predict(X_test)

###Linear Regression
# lm = LinearRegression()
# lm.fit(X_train,y_train)
# y_pred = lm.predict(X_test)

fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.scatter(X_test[:,0], y_pred, s=1, c='b', marker="s", label='real')
ax1.scatter(X_test[:,0], y_test, s=10, c='r', marker="o", label='NN Prediction')
plt.show()

#Calc MSE
mse = np.square(y_test-y_pred).mean()

print(mse)

The results from this show a pretty bad prediction of the test data. Because I am new to this, I am not sure if it is my data, the model, or my coding. Based on the plot, I believe the model is wrong for the data (the model seems to predict something near linear or squared, while the actual data seems much more spread out)
Here are some of the data points:
formatted as Day of year(2 is jan 2nd), weekday(1)/weekend(0), rain(1)/no rain(0), Temp in F, attendance (this is output)
2   0   0   51  1366
4   0   0   62  538
5   1   0   71  317
6   1   0   76  174
7   1   0   78  176
8   1   0   68  220
12  1   1   64  256
13  1   1   60  379
14  1   0   64  316
18  0   0   72  758
19  1   0   72  1038
20  1   0   72  405
21  1   0   71  326
24  0   0   74  867
26  1   1   68  521
27  1   0   71  381
28  1   0   72  343
29  1   1   68  266
30  0   1   57  479
31  0   1   57  717
33  1   0   70  542
34  1   0   73  220
35  1   0   74  360
36  1   0   79  444
42  1   0   78  534
45  0   0   80  1572
52  0   0   76  1236
55  1   1   64  689
56  1   0   69  726
59  0   0   67  1188
60  0   0   74  1140
61  1   1   63  979
62  1   1   62  657
63  1   0   67  687
64  1   0   72  615
67  0   0   80  1074
68  1   0   81  1261
71  1   0   83  1332
73  0   0   85  1259
74  0   0   86  1142
76  1   0   88  1207
77  1   1   78  1438
82  1   0   85  1251
83  1   0   83  1019
85  1   0   86  1178
86  0   0   92  1306
87  0   0   92  1273
89  1   0   93  1101
90  1   0   92  1274
93  0   0   83  1548
94  0   0   86  1318
96  1   0   83  1395
97  1   0   81  1338
98  1   0   75  1240
100 0   0   84  1335
102 0   0   83  931
103 1   0   87  746
104 1   0   91  746
105 1   0   81  600
106 1   0   72  852
108 0   1   87  1204
109 0   0   89  1191
110 1   0   90  769
111 1   0   88  642
112 1   0   86  743
114 0   1   75  1085
115 0   1   78  1109
117 1   0   84  871
120 1   0   96  599
123 0   0   93  651
129 0   0   74  1325
133 1   0   88  637
134 1   0   84  470
135 0   1   73  980
136 0   0   72  1096
137 0   0   83  792
138 1   0   87  565
139 1   0   84  501
141 1   0   88  615
142 0   0   79  722
143 0   0   80  1363
144 0   0   82  1506
146 1   0   93  626
147 1   0   94  415
148 1   0   95  596
149 0   0   100 532
150 0   0   102 784
154 1   0   99  514
155 1   0   94  495
156 0   1   87  689
157 0   1   94  931
158 0   0   97  618
161 1   0   92  451
162 1   0   97  574
164 0   0   102 898
165 0   0   104 746
166 1   0   109 587
167 1   0   109 465
174 1   0   108 514
175 1   0   109 572
179 0   0   107 811
181 1   0   104 423
182 1   0   103 526
184 0   1   97  849
185 0   0   103 852
189 1   0   106 728
191 0   0   101 577
194 1   0   105 511
198 0   1   101 616
199 0   1   97  1056
200 0   0   94  740
202 1   0   103 498
205 0   0   101 610
206 0   0   106 944
207 0   0   105 769
208 1   0   103 551
209 1   0   103 624
210 1   0   97  513
212 0   1   107 561
213 0   0   100 905
214 0   0   105 767
215 1   0   107 510
216 1   0   108 406
217 1   0   109 439
218 1   0   103 427
219 0   1   104 460
224 1   0   105 213
227 0   0   112 834
228 0   0   109 615
229 1   0   105 216
230 1   0   104 213
231 1   0   104 256
232 1   0   104 282
235 0   0   104 569
238 1   0   103 165
239 1   1   105 176
241 0   1   108 727
242 0   1   105 652
243 1   1   103 231
244 1   0   96  117
245 1   1   98  168
246 1   1   97  113
247 0   0   95  227
248 0   0   92  1050
249 0   0   101 1274
250 1   1   95  1148
254 0   0   99  180
255 0   0   104 557
258 1   0   94  228
260 1   0   95  133
263 0   0   100 511
264 1   1   89  249
265 1   1   90  245
267 1   0   101 390
272 1   0   100 223
273 1   0   103 194
274 1   0   103 150
275 0   0   95  224
276 0   0   92  705
277 0   1   92  504
279 1   1   77  331
281 1   0   89  268
284 0   0   95  566
285 1   0   94  579
286 1   0   95  420
288 1   0   93  392
289 0   1   94  525
290 0   1   86  670
291 0   1   89  488
294 1   1   74  295
296 0   0   81  314
299 1   0   88  211
301 1   0   84  246
303 0   1   76  433
304 0   0   80  216
307 1   1   80  275
308 1   1   66  319
312 0   0   80  413
313 1   0   78  278
316 1   0   74  305
320 1   1   57  323
324 0   0   76  220
326 0   0   77  461
327 1   0   78  510
331 0   0   60  1701
334 1   0   58  237
335 1   0   62  355
336 1   0   68  266
338 0   0   70  246
342 1   0   72  109
343 1   0   70  103
347 0   0   58  486
349 1   0   52  144
350 1   0   53  209
351 1   0   55  289
354 0   0   62  707
355 1   0   59  903
359 0   0   58  481
360 0   0   53  1342
364 1   0   57  1624

I have over a thousand data points in total, but Im not using them all for training/testing. One thought is I need more, another is that I need more factors because temp/rain/day of week does not affect attendance enough.
Here is the plot:

What can I do to make my model more accurate and give better predictions?
Thanks
EDIT: I added more data points and another factor. I cant seem to upload the excel file so I put the data on here with a better explanation of how it is formatted
EDIT:
Here is the most recent code:
from sklearn import preprocessing
from openpyxl import load_workbook
import numpy as np
from numpy import exp, array, random, dot
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPRegressor
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import classification_report,confusion_matrix
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import KFold
from sklearn.model_selection import cross_val_predict
from sklearn import svm
from sklearn.model_selection import cross_val_score
from sklearn.metrics import confusion_matrix
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.model_selection import LeaveOneOut
#Set sizes
rowSize = 500
numColumns = 254

# read  from excel file
wb = load_workbook('python_excel_read.xlsx')
sheet_1 = wb["Sheet1"]

input = np.zeros(shape=(rowSize,numColumns))
out = np.zeros(rowSize)
for i in range(0, rowSize):
    for j in range(0,numColumns):
        input[i,j] = sheet_1.cell(row=i + 1, column=j+1).value
    out[i] = sheet_1.cell(row=i + 1, column=numColumns+1).value

output = np.zeros(shape=(rowSize,1))

for i in range(0, rowSize):
    output[i] = [out[i]]

X = input
# Output
y = output

print(X)
print(y)
y[y < 500] = 0
y[np.logical_and(y >= 500, y <= 1000)] = 1
y[np.logical_and(y > 1000, y <= 1200)] = 2
y[y > 1200] = 3

# Use cross-validation
#kf = KFold(n_splits = 10, random_state=0)
loo = LeaveOneOut()
# Try different models
clf = svm.SVC()
scaler = StandardScaler()
pipe = Pipeline([('scaler', scaler), ('svc', clf)])

accuracy = cross_val_score(pipe, X, y.ravel(), cv = loo, scoring = "accuracy")
print(accuracy.mean())

#y_pred = cross_val_predict(clf, X, y.ravel(), cv = kf)
#cm = confusion_matrix(y, y_pred)

and here is the up to date data with as many features as I could add. note this is a random sample from the full data:
Link to sample data
Current output:
0.6230954290296712
My ultimate goal is to achieve 90% or higher accuracy... I dont believe I can find more features, but will continue to gather as many as possible if helpful

A: Your question is really general, however I have some suggestions. You could use cross-validation and try different models. Personnaly, I would try SVR,RandomForests and as last choice I would use a MLPR.
I modified a bit your code to show a simple example:
import numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import classification_report,confusion_matrix
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import KFold
from sklearn.model_selection import cross_val_predict
from sklearn import svm
from sklearn.model_selection import cross_val_score
from sklearn.metrics import confusion_matrix
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.model_selection import LeaveOneOut
import pandas as pd
from sklearn.decomposition import PCA

# read the data
df = pd.read_excel('python_excel_read.xlsx', header = None)
rows, cols = df.shape

X = df.iloc[: , 0:(cols - 1)]
y = df.iloc[: , cols - 1 ]
print(X.shape)
print(y.shape)

y[y < 500] = 0
y[np.logical_and(y >= 500, y <= 1000)] = 1
y[np.logical_and(y > 1000, y <= 1200)] = 2
y[y > 1200] = 3
print(np.unique(y))

# We can apply PCA to reduce the dimensions of the data
# pca = PCA(n_components=2)
# pca.fit(X)
# X = pca.fit_transform(X)

# Use cross-validation
#kf = KFold(n_splits = 10, random_state=0)
loo = LeaveOneOut()
# Try different models
clf = svm.SVC(kernel = 'linear')
scaler = StandardScaler()
pipe = Pipeline([('scaler', scaler), ('svc', clf)])

accuracy = cross_val_score(pipe, X, y.ravel(), cv = loo, scoring = "accuracy")
print(accuracy.mean())

#y_pred = cross_val_predict(clf, X, y.ravel(), cv = kf)
#cm = confusion_matrix(y, y_pred)


text:
Q: Find view in dynamically added layouts So I have a layout with an Add button, which when clicked adds a custom layout to the LinearLayout.
In this custom layout, I have an image, that when clicked should increase a counter (displayed in a textView next to the image).
The problem I am currently having is, that when I have more than one custom layout added, and I click the image it always increases the count of the textView right on top and not the textView next to the image clicked.
How would I find the correct textView to change?
I am fairly new to the android dev world, so if I am doing anything wrong please add that too.
Regards

A: Set OnClickListener to each ImageView when you're inflating your custom layout. In this listener refer to a final TextView variable which repesents a TextView exactly from the currently created layout. Something like this:
    private void addView() {
        View customView = getLayoutInflater.inflate(resId, null);
        final TextView textView = (TextView) customView.findViewById(R.id.textview);
        customView.findViewById(R.id.imageview).setOnClickListener(new OnClickLitener(View v) {
            textView.setText("value");
        });
        container.addView(customView);
    }


text:
Q: Was JK Rowling inspired by The Legend of Zelda? There are some similarities, such as the sword of Gryffindor and the Master Sword, and the Deathly Hallows symbol, which looks similar to the Triforce.
So, is it possible for JKR to have been influenced by the videogame Legend of Zelda?

A: Human beings have used symbols to communicate since, at least, the beginning of recorded history. Scientists can't explain how it is that we learn and understand language, except to say what parts of the brain do these things. The fact that these two symbols look similar is only in the triangle. I would not hazard a guess as to whether or not J. K. Rowling has ever played any of the Legend of Zelda games, however, I would say that it is highly unlikely that she used the Tri-force as her inspiration for the Deathly Hallows. Each of these symbols means something different in symbology and in canon.
The Deathly Hallows
Canon: The Deathly Hallows is made up of a triangle, which represents the invisibility cloak, a circle which represents that resurrection stone, and the line through the center which represents the elder wand. When all three of them are held, it gives one mastery over death.
Symbology: Triangles represent balance and stability, but in this case, when coupled with a circle like this could represent unity for strength. The line splits both down the middle, symbolizing balance or duality, which gives way to the possibility of choice. Taking into account each element and what it means, it would probably support canon best by saying that the three make one whole that together are stronger than they would be alone. That is why they are drawn together, instead of separate.
The Tri-Force
Canon: The Tri-Force is made up of one large triangle to represent the whole and the other triangles, one piece for power, wisdom, and courage each.
Symbology: This symbol is actually very much older than the Legend of Zelda series. Triangles, as I mentioned before, represent stability and balance. Symbolically, there are not just three triangles here, there are actually five. Multiple triangles like this represent unity through stability. The bringing of three together breeds balance. The concepts of trinities are nothing new, exempli gratia, the Holy Trinity, human beings being of mind, body and spirit, et cetera. Canon is probably supported best by saying that bringing the three triangles together makes a stronger triangle.
In closing, I would like to say that these two are obviously not the same. The triangle is not synonymous with Nintendo or with The Legend of Zelda and can be used by anyone for anything. Human beings are predisposed to interpreting symbols as more than just what they are. It's part of how we reason and part of how we communicate and form relationships between one instance of something and another. While the Tri-force and The Deathly Hallows are slightly similar, they are two completely different vehicles for two separate pieces of two completely different stories.