text:
Q: Write CSV To File Without Enclosures In PHP Is there a native function or solid class/library for writing an array as a line in a CSV file without enclosures? fputcsv will default to " if nothing is passed in for the enclosure param. Google is failing me (returning results for a whole bunch of pages about fputcsv), and PEAR's libraries do more or less the same things as fputcsv.
Something that works exactly like fputcsv, but will allow the fields to remain unquoted.
currently: "field 1","field 2",field3hasNoSpaces
desired: field 1,field 2,field3hasNoSpaces

A: The warnings about foregoing enclosures are valid, but you've said they don't apply to your use-case.
I'm wondering why you can't just use something like this?
<?php
$fields = array(
    "field 1","field 2","field3hasNoSpaces"
);
fputs(STDOUT, implode(',', $fields)."\n");

A: fputcsv($file, $data, ';', chr(127));

A: Well car(0) didn't work out as the NULL value will most likely choke most csv parsers.
I ended using fputcsv() to build the initial file, then went through and removed all quotes. Elegant? Maybe not, but it got the job done :).

A: <?php

$filename = "sample.csv";
$handle = fopen($filename, 'w+');
fputcsv($handle, ['column 1','column 2']);
$data = ['sample','data'];

fputs($handle, implode(',', $data)."\n");

// or

fwrite($handle, implode(',', $data)."\n");

fclose($handle);
$headers = array(
    'Content-Type' => 'text/csv',
);

A: works with chr() function:
fputcsv($f,$array,',',chr(0));

A: Doesn't this work?
fputcsv($fp, split(',', $line),',',' ');

A: This is what I use to put standard CSV into an array...
function csv_explode($delim=',', $str, $enclose='"', $preserve=false){
        $resArr = array();
        $n = 0;
        $expEncArr = explode($enclose, $str);
        foreach($expEncArr as $EncItem){
                if($n++%2){
                        array_push($resArr, array_pop($resArr) . ($preserve?$enclose:'') . $EncItem.($preserve?$enclose:''));
                }else{
                        $expDelArr = explode($delim, $EncItem);
                        array_push($resArr, array_pop($resArr) . array_shift($expDelArr));
                        $resArr = array_merge($resArr, $expDelArr);
                }
        }
        return $resArr;
}

You can then output whatever you want in a foreach loop.

A: The downside with a CSV file with no enclosures means an errant comma in user input will munge the row. So you'll need to remove commas before writing a CSV row.
The tricky part with handling CSV is parsing enclosures, which makes the PHP & PEAR CSV functions valuable. Essentially you're looking for a file that is comma-delimited for columns and newline-delimited for rows. Here's a simple starting point:
<?php
$col_separator= ',';
$row_separator= "\n";

$a= array(
 array('my', 'values', 'are', 'awes,breakit,ome'),
 array('these', 'values', 'also', "rock\nAND\nROLL")
);

function encodeRow(array $a) {
 global $col_separator;
 global $row_separator;
 // Can't have the separators in the column data!
 $a2= array();
 foreach ($a as $v) {
  $a2[]= str_replace(array($col_separator, $row_separator), '', $v);
 }
 return implode($col_separator, $a2);
}

$output= array();
foreach ($a as $row) {
 $output[]= encodeRow($row);
}

echo(implode($row_separator, $output));

?>

A: I use tricky way to remove double quote, but only in Linux
....
fputcsv($fp, $product_data,"\t");
....
shell_exec('sed -i \'s/"//g\' /path/to/your-file.txt ');

A: Whats wrong with good old fwrite()?
function encloseString($field){
    return ($field) ? '"' . $field . '"' : null;
}

$delimiter = ';';
$data = ["data_field_1", "data_field_2", "data_field_3"];

$fp = fopen("some-file.csv", 'w');

for($i = 0;$i<100000;$i++) {
    fwrite($fp, implode($delimiter, array_map('encloseString', $data) . "\n");
}

fclose($fp);

(Obviously you need to make sure the data in $data is escaped first)

A: Chose the solution depends on your application. For some case own code for csv is needed. In case 1 (See result chr0), case 2 (chr127) and case 3 (chr127) the data will be modified(bad thing). Instead use something like this, thanks @oops:
<?php
$fields = array("field 1","field 2","field3hasNoSpaces");
fputs(STDOUT, implode(',', $fields)."\n");

*

*case 1. fputcsv($f, $array, $delimiter, car(0)) See result chr0

*case 2. fputcsv($f, $array, $delimiter, car(127))
chr127

*case 3. fputcsv($f, $array, $delimiter, ' ')
onespace

*case 4. Own code (s.above inspired by
oops  or
Ansyori  or
zeros-and-ones ) produces
better results.

A: This is an old question but as I was struggling with this as well, I thought it would be good to let anyone who is looking for something like this know than you can just pass empty string in the enclosure param of fputcsv and it will not use any enclosure at all.
i.e.

fputcsv($file, $array, ',', '');

A: Figured it out. By passing in the ascii code for Null to the car() function it seems to work just fine.
fputcsv($f, $array, $delimiter, car(0))
Thanks for the answers everyone!!!

A: chr(0) also worked for me:
 fputcsv($fp, $aLine, $sDelimiter, chr(0));


text:
Q: Do I still need an Entitlements.plist file for an ad-hoc build? The instructions given in the Distribution page on the iOS Provisioning portal clearly still describe the process of creating, and including the Entitlements.plist file in a build for an ad-hoc distribution.  The iOS Development Guide's Distributing Applications page, on the other hand, makes no mention of the Entitlements.plist file.
When I tried to "Build and Archive" our latest app following the instructions from the iOS Development Guide, the resulting ad-hoc app.ipa wouldn't install on my development device, due to a problem with the entitlements.  When I rebuilt with the Entitlements.plist file, the new app.ipa installed fine.
Unfortunately, including the Entitlements.plist in the app.ipa means that the resulting build can't simply be re-signed and submitted to the app store - Right?  Instead, I have to rebuild without the Entitlements.plist and submit the result to the app store.
I guess that I really have a few related questions:

*

*Would the app.ipa produced as directed in the iOS Development Guide (no Entitlements.plist, just sign with the ad-hoc distribution provisioning profile) install OK on a non-dev device that was properly identified in the test distribution provisioning profile?

*Is there any way for me to test the exact results of a "Build and Archive" on my dev machine, so that I can just re-sign it and submit it to the App Store from Xcode?

*Will an app.ipa that explicitly includes an Entitlements.plist file be rejected if I did submit it?

Thanks!

A:
As of Xcode 4.2 you no longer have to create an Entitlements.plist file when creating applications that do not require any special permissions to run. The get-task-allow entitlement is automatically set to true or false, depending on what kind of provisioning profile you sign your application with (Developer, Ad Hoc, or App Store).

ref:http://help.testflightapp.com/customer/portal/articles/535398-invalid-profile-distribution-build-entitlements-must-have-get-task-allow-set-to-false-

A: i just tried , no need entitlements for simply ad-hoc , simply using ad-hoc profile to archive and share , then fine .

A: From the iOS Developer library:

If you're doing an Ad Hoc distribution, you must properly configure your project to include an Entitlements.plist file and uncheck the get-task-allow checkbox (which sets it to False).
  http://developer.apple.com/library/ios/#technotes/tn2242/_index.html

There's no issue with leaving the Entitlements.plist file in the Distribution build, I've had several apps submitted with it.
Actually, Entitlements.plist is also for other iOS features that your app may use:

Entitlements. These files define
  properties that provide your
  application access to iOS features
  (such as push notifications) and
  secure data (such as the user's
  keychain).
http://developer.apple.com/library/ios/#documentation/Xcode/Conceptual/iphone_development/115-Configuring_Applications/configuring_applications.html

Also check this answer:
The executable was signed with invalid entitlements

A: Get-task-allow is now called "Can be debugged" in Xcode 4.1 if you've used the modernization tool

A: I don't have answers to all your questions, but I needed to add an Entitlements.plist when I recently used ad hoc distribution for some testing. I think the documentation still talks about the 'get-task-allow' setting in the .plist, but when I followed the instructions exactly I had problems signing the app. Instead, I created an Entitlements.plist using Xcode's template. It has two or three settings, none of which are get-task-allow. I left it exactly as it was when created, and the build succeeded.
My experience in the past has been that apps submitted to the app store with an Entitlements.plist included failed the verification step.

redpajama_set_name: RedPajamaStackExchange


text:
Q: GLM for count data I ran an experiment with an eye tracker and my data frame has this look:
               Condition   DWellsAOI1 DwellsAOI2  TotalDwells
Participant1       1             12         13            25
Participant2       2            100         11           111
Participant3       1             50         50           100

and so on. DWellsAOI1 counts the number of dwells on AOI1. Each participant belongs to one condition only, and the duration of the experiment is not fixed, so different TotalDwells.
I was trying to check if there is a significant difference among the between conditions in terms of DwellsAOI1, and my first approach was to compute the percentages (DwellsAOI1/TotalDwells) and run anova. However, data violates both the assumptions.
I searched on Google and I found that I can use a generalized linear model (GLM) with binomial family.
Currently I'm running it like this:
mod <- glm(cbind(DwellsAOI1,TotalDwells-DwellsAOI1) ~ Condition,
               data=df, family=binomial("logit"))
summary(aov(mod))

Is it the correct way?
Thanks!

A: You're making a strong assumption with this model: that the probability of dwelling on AOI1 in each trial depends only on the Condition factor & is not affected by variability between participants or between sessions.† So the danger is a misleadingly precise estimate of the effect of Condition. Examine the model diagnostics carefully, & note that the residual deviance should be approximately equal to the residual degrees of freedom; much greater is a tell-tale sign of over-dispersion. If the assumption seems untenable, alternatives include fitting a beta-binomial model, using a quasi-likelihood approach with an estimated dispersion parameter, & fitting a generalized linear mixed model with a random intercept term representing the participant-session effect.
† To see this: the fitted model will be the same as if you'd summed up dwell counts across each condition before the analysis, leaving you with a two-way contingency table.


text:
Q: Draw function in matlab I need to transform my raw input, into function
dt = 0.01;
t1 = 0:dt:1;
t2 = 1+dt:dt:2.5;
t3 = 2.5+dt:dt:3.5;
t4 = 3.5+dt:dt:4;
t5 = 4+dt:dt:4.5;

y1 = ones(size(t1))*-1;
y2 = 2*(t2-2.5);
y3 = 1*sin(2*pi*(t3-1));
y4 = ones(size(t4))*0;
y5 = rand( size(t5) )-0.5;;

plot(t1, y1, t2, y2, t3, y3, t4, y4, t5 ,y5)

"This one works fine ^^^^."
Here i have done it, but something is wrong in the script.
Where did i made mistake?
How its looks now
function [t1, y1, t2, y2, t3, y3, t4, y4, t5 ,y5]=funct(t)
t = 0.01; % Its every step (0<=t) = (0<=0.01)

t1 =t((0<=t)&(t<1));
y1 = ones(size(t1))*-1;

t2 =t((1<=t)&(t<2.5));
y2 = 2*(t2-2.5);

t3 = t((2.5<=t)&(t<3.5));
y3 = 1*sin(2*pi*(t3-1)); %you wrote sn here

t4 =t((3.5<=t)&(t<4));
y4 = ones(size(t4))*0;

t5=t((4<=t)&(t<4.5));
y5 = rand( size(t5) )-0.5;

plot(t1, y1, t2, y2, t3, y3, t4, y4, t5 ,y5)

A: I obtain the same result.
First I run your code:
dt = 0.01;
t1 = 0:dt:1;
t2 = 1+dt:dt:2.5;
t3 = 2.5+dt:dt:3.5;
t4 = 3.5+dt:dt:4;
t5 = 4+dt:dt:4.5;

y1 = ones(size(t1))*-1;
y2 = 2*(t2-2.5);
y3 = 1*sin(2*pi*(t3-1));
y4 = ones(size(t4))*0;
y5 = rand( size(t5) )-0.5;;

plot(t1, y1, t2, y2, t3, y3, t4, y4, t5 ,y5)

and obtained this:

After I tried to run your function:
t = 0:dt:5;
funct(t)

where
function y=funct(t)
%dt = 0.01; %this is not necessary I think

%t1 = 0:dt:1;
t1 =t((0<=t)&(t<1));
y1 = ones(size(t1))*-1;

%t2 = 1+dt:dt:2.5;
t2 =t((1<=t)&(t<2.5));
y2 = 2*(t2-2.5);

%t3 = 2.5+dt:dt:3.5;
t3 = t((2.5<=t)&(t<3.5));
y3 = 1*sin(2*pi*(t3-1)); %you wrote sn here

%t4 = 3.5+dt:dt:4;
t4 =t((3.5<=t)&(t<4));
y4 = ones(size(t4))*0;

%t5 = 4+dt:dt:4.5;
t5=t((4<=t)&(t<4.5));
y5 = rand( size(t5) )-0.5;

y=[y1 y2 y3 y4 y5];

figure
plot(t1, y1, t2, y2, t3, y3, t4, y4, t5 ,y5)

I just corrected sn->sin in your code.
Also not that if you tried to execute plot(t1, y1, t2, y2, t3, y3, t4, y4, t5 ,y5) outside the function it cannot work because the function as it is doesn't have enough outputs.
You should modify the first line in the following way:
function [t1, y1, t2, y2, t3, y3, t4, y4, t5 ,y5]=funct(t)

Hope this helps. Were the errors different?


text:
Q: Swift: how to always get different value from shuffled array I created an array of words basically inside of a button, and each time I press my button I get a random item from the array. Now sometimes I get identical items. What if I don't want my items to repeat themselves and I always want to get new items? (Obviously I even want them to repeat their cycle after they all have ben showed once).
@IBOutlet weak var shoppingLabel : UILabel!
@IBAction func shoppingListButton(_ sender: Any) {
         var shoppingList = ["Oranges","Apples","Broccoli"].shuffled()
        print(shoppingList)
        resultLabel.text = shoppingList.first ?? ""
    }

this is not a duplicate as the similar question has an array outside of the button and is a var array, mine is a let. With my array I'm unable to remove items from it because it can't be changed, and no, I can't make it a var array...

A: To cycle through a random array:

*

*Create the array

*Shuffle it once

*Pick values by cycling through the array from the beginning to the end

To achieve 1) and 2) simply define the array as a constant and shuffle it outside the method in which you want to use it.
To achieve 3) create an additional variable to keep track of which index of the array you are currently at, and increment it after picking a value.
To make sure you don't go beyond the bounds of the array and to achieve the "cycling" through of the array, reset the index to 0 when the index becomes greater than the last index of the array. A simple way to do this, is to use the remainder operator % in Swift.
E.g.
let shoppingList = ["Oranges", "Apples", "Broccoli"].shuffled()
var currentIndex = 0

@IBAction func shoppingListButton(_ sender: Any) {

    // pick an item
    let nextItem = shoppingList[currentIndex]

    // update the label
    resultLabel.text = nextItem

    // increment the index to cycle through items
    currentIndex = (currentIndex + 1) % shoppingList.count
}

To pick random non-repeating values from an array:

*

*Create the array

*Pick a random value from the array

*If the picked value equals the last value, pick a new one

To achieve 2) use the randomElement() function to pick a random element. This is less computationally expensive than shuffling the entire array and picking the first element each time.
To achieve 3) use a while loop or similar to keep picking random elements until a new one is generated.
E.g.
let shoppingList = ["Oranges", "Apples", "Broccoli"]

@IBAction func shoppingListButton(_ sender: Any) {

    // pick a random element that is not equal to the last one
    var nextItem: String?
    repeat {
        nextItem = shoppingList.randomElement()
    } while nextItem == resultLabel.text

    // update the label
    resultLabel.text = nextItem
}


text:
Q: mysql query - can't wrap my head around it i have this little PHP script that tracks downloads of files and currently i am fetching the results with this query:
SELECT file, COUNT(file) AS downloads
FROM downloads
WHERE file LIKE 'pfx_%'
GROUP BY file
ORDER BY downloads DESC

For every new download i create a new row where i keep the filename in one column.
This brings back something like

Filename01 | 1200
Filename02 | 100
Filename03 | 256
...
Filename0x | 932

The problem i have now is that some files have versions like Filename01_1.0 and Filename01_1.1, Filename01_1.2 etc
Is it possible to fetch these versions and count them as one Filename?
I hope it makes sense :)

A: You could do like:
GROUB BY SUBSTRING_INDEX(file, '.', 1)

A: The SUBSTRING_INDEX() function is your friend:
SELECT SUBSTRING_INDEX(file, '_', 1) as file, COUNT(*) AS downloads
FROM downloads
WHERE file LIKE 'pfx_%'
GROUP BY file
ORDER BY downloads DESC


text:
Q: Как спозиционировать блоки с помощью float? Подскажите как спозиционировать блоки main и sub с помощью флоата, имя вот такой код:

.clearfix:after{
content:"";
display: table;
clear:both;
}

.main{
  background-color:red;
  width:100px;
  position:relative;
float:left;
}

.main div{
    position:absolute;
}

.sub{
  background-color:green;
  float:left;
}

12312321321

12312321321

12312321321

asd

asd

asd

A: Float устаревшее решение для позиционирования.
Его используют для обтекания какого-то изображения.
Лучше использовать flexbox, grid или другие методы для позиционирования.
Вот пример на flexbox:

.main {
  font-family: 'Montserrat', sans-serif;
  font-size: 14px;
  font-weight: 600;
  height: 100px;
  display: flex;
}

.list {
  padding: 10px;
  background: green;
}

.sublist {
  padding: 10px;
  background: red;
}

.item {
  color: #272727;
}

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet

A: Это можно сделать на стандартных инлайн блоках:

* {
  margin: 0;
  padding: 0;
}

.sub {
  background: red;
}

.main {
  background: green;
}

main {
  font-size: 0;
}

main>div {
  font-size: 16px;
}

main>div {
  display: inline-block;
}

Hello, world

Hello, world

Hello, world

Hello, world

Hello, world

Hello, world

A: Или на grid можно так. В перспективе лучше выбрать grid, но не забывайте, что grid не так давно получил поддержку браузерами. Хотя "не так давно" - понятие растяжимое)

.main {
  font-family: 'Montserrat', sans-serif;
  font-size: 14px;
  font-weight: 600;
  height: 100px;
  display: grid; /* GRID */
  grid-template-columns: repeat(2, 1fr); /* две колонки */
}

.list {
  padding: 10px;
  background: green;
}

.sublist {
  padding: 10px;
  background: red;
}

.item {
  color: #272727;
}

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet


text:
Q: Inconsistent Selenium Grid Errors I am running tests on Selenium grid - usually 5 machines running tests in parallel. I am getting some odd errors that aren't consistent. For example, one of my tests with about 600 iterations will finish with 0-50 of the 3 errors below. The number is different every time I run it. For each exception, the line it fails on is always the same.

*

*org.openqa.selenium.UnsupportedCommandException:
Command duration or timeout: 65.91 seconds
com.web.test.library.BaseTest.openUrl(BaseTest.java:45)
Line #45 in BaseTest: remoteDriver.get(url);

*org.openqa.selenium.WebDriverException: Error forwarding the new session Error forwarding the request Read timed out
Command duration or timeout: 134.11 seconds
com.web.test.utility.DriverFactory.generateDriver(DriverFactory.java:46)
Line #46 in DriverFactory: WebDriver driver = new RemoteWebDriver("my hub url here", capabilities);

*org.openqa.selenium.WebDriverException: Unable to bind to locking port 7054 within 45000 ms
com.web.test.utility.DriverFactory.generateDriver(DriverFactory.java:46)
Line #46 in DriverFactory: WebDriver driver = new RemoteWebDriver("my hub url here", capabilities);
When I search for these errors online the fixes only help when this error is stopping every test. I can't find anything when it happens inconsistently like this. For example, the fix I found for #1 requires editing the host file. I don't think that is the problem in my case since it works ~95% of the time.

A: I'm guessing you are doing parallel testing using multiple threads.
If that is the case, I would recommend looking at ThreadGuard.  It's a lightweight solution to make Webdriver thread safe.
If that doesn't work, then I imagine you are running into a networking overload problem (you are trying to do too many outgoing connections).  How to fix such a problem, I don't know.


text:
Q: Calculate if $ \lim_{(x,y) \to (0,0)} \frac{|x^2y^2|}{|x^3|+|y^3|}$ exists I have to calculate if this limit exist:
$$ \lim_{(x,y) \to (0,0)} \frac{\vert x^2y^2\vert}{\vert x^3\vert +\vert y^3\vert}$$
Could anyone give me a hand?

A: by $AM-GM$ we get $$|x|^3+|y|^3\geq 2|xy|^{3/2}$$ from here we obtain
$$\frac{x^2y^2}{|x|^3+|y|^3}\le \frac{1}{2}\frac{x^2y^2}{|xy|^{3/2}}=\frac{1}{2}|xy|^{1/2}\to0$$


text:
Q: Erro definir getElementById? Eu tenho um elemento onde o atributo id é um inteiro. Estou tentando definir, mas não estou conseguindo.
Estou fazendo assim:
var 1 = document.getElementById(1).value

Esta correto?

A: Os problemas são:

*

*Variáveis não podem ser compostas apenas de numeros var 1; var 2;

*O parâmetro no getElementById deve ser string
Extras:

*

*HTML4.01: O atributo ID nunca pode se repetir e deve começar com letras e não deve conter espaços

*HTML5: É mais permissivo, todavia ainda sim não aceita espaços.

*IDs nunca devem se repetir em uma mesma página HTML
O problema é por onde começar a aprender
O problema da pergunta não é o seu erro, mas é um problema comum de quem está começando a aprender, pois costumam inventar da própria cabeça ou sair usando aleatoriamente uma função ou código. Para todas tecnologias populares sempre existe uma documentação ao menos (oficial ou não oficial), o mesmo vale para JavaScript que é usada amplamente, então não tente usar sem seguir ao menos um exemplo que esteja na documentação, se tiver dificuldades leia os detalhes da própria documentação sobre a função que esta tentando usar no momento, então aprenda o básico primeiro, pois não adianta pular etapas.
Em JavaScript comece por algo como: https://developer.mozilla.org/pt-BR/docs/Web/JavaScript
Para aprender a usar e declarar variáveis leia na DOC:

*

*Declarando variáveis
Para aprender sobre o uso do getElementById:

*

*getElementById
Outros links dentro da doc úteis para começar:

*

*https://developer.mozilla.org/pt-BR/docs/Web/API

*https://developer.mozilla.org/pt-BR/docs/Web/API/Document

*https://developer.mozilla.org/pt-BR/docs/Web/API/Window

*https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Guide/Numeros_e_datas

*https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Guide/Formatando_texto

*https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Guide/Expressions_and_Operators

*https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Guide/Funções

*https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Guide/Lacos_e_iteracoes

A maior parte das "docs" de javascript tem algum problema, principalmente em português, mas ainda sim para aprender o básico o link da Mozilla atende bem

Para resolver
Para resolver pode fazer algo como:
document.getElementById("item_1").value;

E mudar o HTML para algo como (apesar do HTML5 ser mais permissivo quanto ao ID):

Claro que pode usar números no ID sendo HTML5, como já disse, mas no caso não sei quais os navegadores que pretende rodar e mesmo que funcione no HTML4, ainda você pdoe se atrapalhar.
Um exemplo:

window.onload = function() {
    var item1 = document.getElementById("item_1");
    var button = document.getElementById("enviar");

    button.onclick = function() {
        console.log(item1.value);
    };
};
<input type="text" value="Olá mundo" id="item_1">

<button id="enviar">Enviar</button>

A: O problema é que o nome da tua variável é um inteiro, nunca deves fazer isso, até porque se desse (ainda bem que não dá) iria trazer imensos problemas, assim como o id deve ser passado como string dentro do metodo getElementById(), faz o seguinte:

var val_1 = document.getElementById("1").value;
alert(val_1);
<input id="1" value="heya">

E assim como é mencionado na resposta do Virgilio, também deves evitar usar somente um número como id, nem deves colocar o número no inicio do nome do id, porque se quiseres estilizar (CSS) usando o id como selector não vais conseguir, ex:

#1 {
  background-color: red;
}
<input id="1" value="heya">

Exemplo que funciona:

#a1 {
  background-color: red;
}
<input id="a1" value="heya">

A: O teu problema está no nome da variável. Variáveis com numeros no inicio do nome são inválidas.

*

*div1 funciona como nome de variável

*1div ou 1 não funciona como nome de variável

O erro que isso dá diz isso, "apareceu um numero inesperado":

(index):45 Uncaught SyntaxError: Unexpected number

O .getElementById aceita uma variável ou string como argumento. Podes usar um numero, que é aceite em HTML5, mas o correto é usar uma string.
Exemplo:

var um = document.getElementById(1);
um.style.color = 'red';

1

2

A: Não é uma boa prática colocar a id (leia) de qualquer tag html somente com um número coloque sempre a inicial uma letra (exemplo: a1, b1, etc.), no código tem o problema de colocar um número como variável (isso não pode em qualquer linguagem, segue um padrão um letra e depois pode ter números, logo abaixo tem a explicação de criação de variaveis com php e javascript) e por fim o paramento dentro do getElementById é um texto (getElementById("t1"));
Para funcionar basicamente sem muitas mudanças:

var numero = document.getElementById("1").value;
console.log(numero);
<input type="text" value="100" id="1" name="t1" />

Uma maneira correta: O id foi adicionado um letra t e após um número (t1):

var numero = document.getElementById("t1").value;
console.log(numero);
<input type="text" value="100" id="t1" name="t1" />

Como definir uma variável?
Javascript
A linguagem JavaScript faz distinção entre maiúsculas e minúsculas.  Isso significa que um nome de variável, como myCounter, é diferente do nome de variável MYCounter.  Nomes de variáveis podem ser de qualquer comprimento.  As regras para a criação de nomes de variável legais são as seguintes:

*

*O primeiro caractere deve ser uma letra ASCII (em maiúscula ou minúscula) ou um caractere de sublinhado (_).  Observe que um número não pode ser usado como o primeiro caractere.

*Os caracteres subsequentes devem ser letras, números ou sublinhados (_).

*O nome da variável não deve ser uma palavra reservada.
Referencia e Direitos autorais - MSDN Microsoft
PHP
Nomes de variável seguem as mesmas regras como outros rótulos no PHP. Um nome de variável válido inicia-se com uma letra ou sublinhado, seguido de qualquer número de letras, números ou sublinhados. Em uma expressão regular, poderia ser representado assim: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]**
Referencia e direitos autoriais - Site PHP.
Mesmo sendo uma definição para PHP segue a nomenclatura básica para criação de nomes de variáveis em programação.
Esses dois textos que explicam como criar nomes para variáveis vai permitir a compreensão melhor de como definir nomes inclusive de elementos de html, porque, também são nomes de variáveis de tela, cuidado com repetição de nomes que pode ser um grande transtorno no desenvolvimento e use essas nomenclaturas que defini a criação de nomes de variaveis.
Referencias:

*

*Variável (programação)

*HTML DOM getElementById() Method

*HTML DOM id Property

*www.w3.org - 6 Basic HTML data types


text:
Q: Open Google Earth and load specific KML file when user clicks link on web page I'm currently working on a site which displays map data in Google Maps, but also has a link to display it in Google Earth.
To get view this data in Google Earth, a user clicks the link, downloads the file, then opens the file with Google Earth. Is there a method to automate this, so that a user can click the link and the file is automatically opened in Google Earth, similar to the iTunes web store?
I've searched through the documentation to little avail.

A: No, you can't force the users machine to launch an application like that. However, a user can set this up themselves if they wish in certain operating systems with certain browsers.
For example, in Windows I have Google Earth associated with the kml and kmz file extensions. I browse using Google Chrome. When I click a link to a kml/kmz file it is downloaded as per normal. In the download bar I can then choose to "Always open files of this type". Thus, when ever I click a link to a kml/kmz file it is automatically opened in Google Earth.
If a site could 'force' this behaviour not only would it be immensely annoying it would also be a massive security risk.
Also, why not just use the web based version of Google Earth? It is pretty simple to intergate it directly using the Google Maps Api.
i.e:
http://earth-api-samples.googlecode.com/svn/trunk/demos/mapsapi/index.html
http://earth-api-samples.googlecode.com/svn/trunk/demos/mapsapi/beefy.html


text:
Q: Using sass variables in a VueJS component I got a rather simple problem with a VueJS component that needs to use a variable. The problem comes with getting sass to register variables inside a component.
I tried importing the _variables.scss file containing my variables but to no luck. At this point any guidance is very much appreciated, or if there is another way for a component to inherit styling.
MyComponent.vue
<template>

</template>

Gulpfile.js
var elixir = require('laravel-elixir');
require('laravel-elixir-vueify');

elixir(function(mix) {
    mix.browserify('main.js');
    mix.sass('app.scss');
});

app.scss
@import "node_modules/bootstrap-sass/assets/stylesheets/bootstrap";
@import "modules/variables";

variables.scss
$primary-color: #BA2731; //Red

A: I'm using the latest version (v9.0.2) of sass-loader, and prependData doesn't seem like an option now. You might want to try this configuration in vue-config.js. Notice the additionalData option is being used as there's no longer a prependData option.
module.exports = {
  css: {
    loaderOptions: {
      sass: {
        additionalData: '@import "@/pathto/variables.scss";'
      }
    }
  }
}

A: Importing the _variables.scss in every component seems to be the only solution I've found so far (it should work, according to this issue).
<template>

</template>

As you are only going to include variables, this shouldn't be a problem.
But as mentioned in the issue, a word of caution: You should only include abstract entities (variables, extends, mixins) into every component, no concrete CSS rules.

A: Assuming you are using vue-cli, try this.
If you don't already have the sass loader installed:
npm install -D sass-loader node-sass

Then in vue.config.js:
const path = require('path');

module.exports = {
  css: {
    loaderOptions: {
      sass: {
        data: `@import "@/pathto/variables.scss";`
      }
    }
  }
};

In your component:

Source:

*

*Passing options to pre-processor loaders

*How to import a sass file into every vue component
Edit:
As of sass-loader 8, data needs to be prependData (Thanks to @ben-y for pointing this out):
const path = require('path');

module.exports = {
  css: {
    loaderOptions: {
      sass: {
        prependData: `@import "@/pathto/variables.scss";`
      }
    }
  }
};

A: For me none of the solutions above worked (sass-loader 9.0.3) but this did:
module.exports = {
  css: {
    loaderOptions: {
      sass: {
        sassOptions: {
          prependData: `@import "@/scss/variables.scss";`
        }
      },
    },
  },
};

A: For Nuxt 3
Inside of nuxt.config.ts
export default defineNuxtConfig({
  css: ["@/assets/styles/main.scss"],
  vite: {
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: '@import "@/assets/styles/_variables.scss";'
        }
      }
    }
  }
})

A: For my project I used Vue CLI webpack and here's a solution that worked for me.
I manage all of my SCSS in the App.vue file. In each of my Component.vue I stopped using  and started creating a separate component.scss.

So my src folder looks like:
 /src
     /assets
     /components
         /compA
             CompA.vue
             compA.scss
         /compB
             CompB.vue
             compB.scss
    App.vue
    main.js

And my App.vue looks like
<template> ... </template>

The advantage of this setup is getting to manage all your styles in one location, and also being able to use all your bootstrap variables and mixins.
Note:
This is just another option of using SASS variables in Vue.
I went this route since when I import the Boostrap SCSS in all of my components, the size of my app kept growing. The increase is negligible if I'm only importing the variables, but when I import the whole Boostrap SCSS the increase becomes significant. I do this so I can use the mixins and extend some existing styles.


text:
Q: What is a head in Coq head normal form? I am having trouble understanding Coq/CIC head normal form. More specifically, I don't understand what is a head. The reference manual (8.5p1) says that

Any term can be written as:

But the above definition is in the negative sense: it requires t0 not to be an application, but didn't say what can t0 be. In fact, as far as I can remember, the only thing that can be written as t0 t1 t2 ... is an application of a function or constructor t0.
Can someone help spell out what  exactly can be the head here?

A: Yes, t0 t1 ... tn is an application, but the manual is talking about the form of t0 standing by itself.
In the manual, t or ti for some i usually denotes a term, so t0 can be any term, that is not an application, e.g. a λ-abstraction, etc. -- see the list in sect. 4.1.2 of the manual and the sect. 1.2.1 on syntax.
Also, this Wikipedia page might be of some help.


text:
Q: The subset of $L_p$ space has empty interior Let $f\in L_1([0,1], \lambda)$ and suppose $\int_0^1 |f|^2 dx \leq M$.
Does there exist function $g \in L_1([0,1], \lambda)$ which is close to $f$ (i.e. $\|f-g\|_{L_1} < \epsilon$) but which is not square-integrable, or at least satisfies $\int_0^1 |g|^2 dx > M$?

A: Take your favorite function $h \in L^1(0,1) \setminus L^2(0,1)$. Then set $g_t:=f+th$, for $t\searrow 0$, $\|f-g\|_{L^1} \searrow0$, but $g_t\not\in L^2(0,1)$.
(One valid choice of $h$ would be $h(x) =x^{-1/2}$.)


text:
Q: How to find the node handle of a child component in react-native? I had setup a ViewPager component in my react-native application which goes like this:
render(){
  return(
    <View>
       <ViewPager
         ref="main"
         dataSource={this.state.dataSource}
         renderPage={this.renderView}
       />
       <TouchableHighlight onPress={this._onPressButton}>
           <Text>Something</Text>
       </TouchableHighlight>
    </View>
  );
}

renderView(){
    return(
      <View ref="main1">
          <Text>Something else</Text>
      </View>
    );
}

_onPressButton(){
    //Do something with {this.refs.main} and {this.refs.main1}
}

Now I want to access the node handle of View with main1 reference. I can find the node handle of ViewPager using findNodeHandle(this.refs.main) but this.refs.main1 returns null. How can find this child View's node handle?

A: I read somewhere that views which only contain one child are collapsed. It is entirely possible that that is what is happening in your case. I was able to force the view to not be collapsed by attaching a border to it. Obviously this isn't a solution, but it would at least tell you if that is what is happening.


text:
Q: Scikit-learn cross val score: too many indices for array I have the following code
 from sklearn.ensemble import ExtraTreesClassifier
 from sklearn.cross_validation import cross_val_score
 #split the dataset for train and test
 combnum['is_train'] = np.random.uniform(0, 1, len(combnum)) <= .75
 train, test = combnum[combnum['is_train']==True], combnum[combnum['is_train']==False]

 et = ExtraTreesClassifier(n_estimators=200, max_depth=None, min_samples_split=10, random_state=0)
 min_samples_split=10, random_state=0  )

 labels = train[list(label_columns)].values
 tlabels = test[list(label_columns)].values

 features = train[list(columns)].values
 tfeatures = test[list(columns)].values

 et_score = cross_val_score(et, features, labels, n_jobs=-1)
 print("{0} -> ET: {1})".format(label_columns, et_score))

Checking the shape of the arrays:
 features.shape
 Out[19]:(43069, 34)

And
labels.shape
Out[20]:(43069, 1)

and I'm getting:
IndexError: too many indices for array

and this relevant part of the traceback:
---> 22 et_score = cross_val_score(et, features, labels, n_jobs=-1)

I'm creating the data from Pandas dataframes and I searched here and saw some reference to possible errors via this method but can't figure out how to correct?
What the data arrays look like:
features
Out[21]:
array([[ 0.,  1.,  1., ...,  0.,  0.,  1.],
   [ 0.,  1.,  1., ...,  0.,  0.,  1.],
   [ 1.,  1.,  1., ...,  0.,  0.,  1.],
   ...,
   [ 0.,  0.,  1., ...,  0.,  0.,  1.],
   [ 0.,  0.,  1., ...,  0.,  0.,  1.],
   [ 0.,  0.,  1., ...,  0.,  0.,  1.]])

labels
Out[22]:
array([[1],
   [1],
   [1],
   ...,
   [1],
   [1],
   [1]])

A: When we do cross validation in scikit-learn, the process requires an (R,) shape label instead of (R,1). Although they are the same thing to some extend, their indexing mechanisms are different. So in your case, just add:
c, r = labels.shape
labels = labels.reshape(c,)

before passing it to the cross-validation function.

A: Adding .ravel() to the Y/Labels variable passed into the formula helped solve this problem within KNN as well.

A: It seems to be fixable if you specify the target labels as a single data column from Pandas.  If the target has multiple columns, I get a similar error.  For example try:
labels = train['Y']

A: try target:
y=df['Survived']

instead , i used
y=df[['Survived']]

which made the target y a dateframe, it seems series would be ok

A: You might need to play with the dimensions a bit, e.g.
et_score = cross_val_score(et, features, labels, n_jobs=-1)[:,n]

or
 et_score = cross_val_score(et, features, labels, n_jobs=-1)[n,:]

n being the dimension.


text:
Q: How to iterate grouped objects in Pandas I have  DataFrame called df_grouped grouped by the "Chr" column as shown below.
   Index Trait Chr  p_adj     ind
422 94  C10.1   1   21.660747   0
470 140 C10.1   1   10.859806   1
471 141 C10.1   1   24.434861   2
472 142 C10.1   1   10.962972   3
473 143 C10.1   1   32.396856   4
... ... ... ... ... ...
1710    15  Pro 22  47.523313   5458
1711    16  Pro 22  48.683401   5459
1713    18  Pro 22  49.804377   5460
1715    20  Pro 22  7.311224    5461
1704    9   Pro 22  15.566230   5462

*Now I want to loop through the grouped object and return a DataFrame called 'group' which contains all the datasets from  Chr 1 to Chr 22. unfortunately, "group" is only returning only Chr 22. How can I solve this problem? *
x_labels = []
x_labels_pos = []
groupin = []

for num, (name, group) in enumerate(df_grouped):
    #fig = px.scatter(group, x='ind', y='p_adj', color="Chr")
    x_labels.append(name)
    x_labels_pos.append((group['ind'].iloc[-1] - (group['ind'].iloc[-1] - group['ind'].iloc[0])/2))
    groupin.append(group)


text:
Q: why my case give me the errors?Why i can't put variables in switch cases? I have 2 errors while trying to put a variable in switch case:
#include <stdio.h>
int main(int argc, char *argv[]) {
  float conversie = 0;
  float leu = 1;
  float usd = 3.6 * leu;
  float eur = 4.4 * leu;
  float aur = 139 * leu;
  float suma;
  float valoare;
  char tipmoneda;
  printf("introdu moneda pe care vrei sa o schimbi:");
  scanf("%c\n", &tipmoneda);
  switch (tipmoneda) {
  case 'usd':

  default:
    break;
  }

}

These are the errors:
Untitled.c:14:8: warning: multi-character character constant [-Wmultichar] case 'usd': ^
Untitled.c:14:8: warning: overflow converting case value to switch condition type (7697252 to 100) [-Wswitch]
2 warnings generated.

A: If you are entering "usd" on the input line, this won't work; scanf will only read and store the leading 'u' character into tipmoneda (which won't match the multi-character constant 'usd').  Also, to be safe, you should put a leading blank space in the scanf control string:
scanf( " %c", &tipmoneda );

This will tell scanf to skip over any leading whitespace.
What you can do is simply enter 'u' for usd, 'e' for eur, 'a' for aur, and then switch as follows:
switch( tipmodena )
{
  case 'u' :
    // process for usd
    break;

  case 'e':
    // process for eur
    break;

  case 'a':
    // process for aur
    break;

  default:
    // unrecognized option
    break;
}

Edit
If you really want to enter "usd" instead of "u", you could do something like the following:
#include <ctype.h>   // needed for the tolower call below
...
char tipmoneda[4] = {0}; // read tipmoneda as a 3-character string instead of
                         // a single char
...
scanf( "%3s", tipmoneda ); // note conversion specifier
switch( tolower( tipmoneda[0] )) // switch on lowercase form of first letter
{
  // same cases as above
}

The tolower call will convert the argument to lower case, so you could enter "usd", "USD", "Usd", etc.,  and still have this work.  Note that if you enter a string that's more than 3 characters long, the remaining characters will remain in the input stream, potentially fouling up the next scanf call.

A: 'usd' is a multi character integer constant (with portability problems), yet tipmodena is simply 1 char.  A new approach is needed.
The below forms the case constants at compile time from 3 char.  At run-time the string read forms the integer to switch on in the same fashion.
[Edit]
Reworked hash function to cope with signed char, overflow shifting of signed char and potential 16-bit int.
#include <stdio.h>
#include <string.h>

#define HASH(a,b,c) \
    ((unsigned char)(a)*0x10000u + (unsigned char)(b)*0x100u + (unsigned char)(c))

int main(void) {
  char denom[4] = { 0 };
  while (scanf("%3s", denom) == 1) {
    switch (HASH(denom[0],denom[1],denom[2])) {
      case HASH('u', 's', 'd'):
        puts("usd");
        break;
      case HASH('e', 'u', 'r'):
        puts("eur");
        break;
      case HASH('a', 'u', 'r'):
        puts("aur");
        break;
      default:
        printf("Unknown '%s'\n", denom);
    }
    memset(denom, 0, sizeof denom);
  }
  return 0;
}

A: C switch case only works with integer or single character types.

A: This is simply part of the language definition. You may only use constant expressions for your case values. Examples include numeric and character literals as well as previously-defined constants.
Technically, 'usd' is a multi-character constant, which is interpreted as a numeric value. See Multiple characters in a character constant for reference.
This is generally not an advisable practice for portable code.
This also appears to conflict with the inferred intentions of the poster. It appears that the poster is attempting to read a currency as a string and calculate totals based on that input. Currently, this code will read a single character and switch on that value.


text:
Q: Set maximum and minimum zooming levels for image
Possible Duplicate:
Imageview issue with zoom in and out,drag with maximum and minimum levels

I have image zooming and dragging in my application. My requirement is the image sets maximum and minimum zooming levels. I have used the below code.
public class PinchZoomListener implements OnTouchListener {

    private static final String TAG = "Touch";
    // These matrices will be used to move and zoom image
    Matrix matrix = new Matrix();
    Matrix savedMatrix = new Matrix();

    // We can be in one of these 3 states
    static final int NONE = 0;
    static final int DRAG = 1;
    static final int ZOOM = 2;
    int mode = NONE;

    // Remember some things for zooming
    PointF start = new PointF();
    PointF mid = new PointF();
    float oldDist = 1f;

    public boolean onTouch(View v, MotionEvent event) {
        ImageView view = (ImageView) v;
        dumpEvent(event);// Dump touch event to log

        switch (event.getAction() & MotionEvent.ACTION_MASK) {
        case MotionEvent.ACTION_DOWN:
            savedMatrix.set(matrix);
            start.set(event.getX(), event.getY());
            Log.d(TAG, "mode=DRAG");
            mode = DRAG;
            break;
        case MotionEvent.ACTION_POINTER_DOWN:
            oldDist = spacing(event);
            Log.d(TAG, "oldDist=" + oldDist);
            if (oldDist > 10f) {
                savedMatrix.set(matrix);
                midPoint(mid, event);
                mode = ZOOM;
                Log.d(TAG, "mode=ZOOM");
            }
            break;
        case MotionEvent.ACTION_UP:
        case MotionEvent.ACTION_POINTER_UP:
            mode = NONE;
            Log.d(TAG, "mode=NONE");
            break;
        case MotionEvent.ACTION_MOVE:
            if (mode == DRAG) {
                // ...
                matrix.set(savedMatrix);
                matrix.postTranslate(event.getX() - start.x, event.getY() - start.y);
            } else if (mode == ZOOM) {
                float newDist = spacing(event);
                Log.d(TAG, "newDist=" + newDist);
                if (newDist > 10f) {
                    matrix.set(savedMatrix);
                    float scale = newDist / oldDist;
                    matrix.postScale(scale, scale, mid.x, mid.y);
                }
            }
            break;
        }
        view.setImageMatrix(matrix);
        return true; // indicate event was handled
    }

    /** Show an event in the LogCat view, for debugging */
    private void dumpEvent(MotionEvent event) {
        String names[] = { "DOWN", "UP", "MOVE", "CANCEL", "OUTSIDE", "POINTER_DOWN", "POINTER_UP", "7?", "8?", "9?" };
        StringBuilder sb = new StringBuilder();
        int action = event.getAction();
        int actionCode = action & MotionEvent.ACTION_MASK;
        sb.append("event ACTION_").append(names[actionCode]);
        if (actionCode == MotionEvent.ACTION_POINTER_DOWN || actionCode == MotionEvent.ACTION_POINTER_UP) {
            sb.append("(pid ").append(action >> MotionEvent.ACTION_POINTER_ID_SHIFT);
            sb.append(")");
        }
        sb.append("[");
        for (int i = 0; i < event.getPointerCount(); i++) {
            sb.append("#").append(i);
            sb.append("(pid ").append(event.getPointerId(i));
            sb.append(")=").append((int) event.getX(i));
            sb.append(",").append((int) event.getY(i));
            if (i + 1 < event.getPointerCount())
                sb.append(";");
        }
        sb.append("]");
        Log.d(TAG, sb.toString());
    }

    /** Determine the space between the first two fingers */
    private float spacing(MotionEvent event) {
        float x = event.getX(0) - event.getX(1);
        float y = event.getY(0) - event.getY(1);
        return FloatMath.sqrt(x * x + y * y);
    }

    /** Calculate the mid point of the first two fingers */
    private void midPoint(PointF point, MotionEvent event) {
        float x = event.getX(0) + event.getX(1);
        float y = event.getY(0) + event.getY(1);
        point.set(x / 2, y / 2);
    }
}

How can I set maximum and minimum zooming levels for image in Android?

A: You ought to rework your code, because you're using relative scales and offsets for every touch event, and there's no possible way to find out what is the absolute value of current image zoom and/or offset.
Save the absolute value of your zoom somewhere, and then you may use the before mentioned min(max(MIN,zoom),MAX) piece of code.


text:
Q: How can I pick images ONLY from gallery/camera? I use this code:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);

But it shows all pictures which I have on phone, from other then gallery/camera files too. How could I change it?

A: use this code to pick images from the gallery/camera only
pick = 0;
    Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(i, pick);

This should work for you.

A: Try this. You need to
import android.provider.MediaStore.Images.Media;

.
.
int IMAGE_PICKER_SELECT = 0;
.
.

Intent i = new Intent(Intent.ACTION_PICK, Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, IMAGE_PICKER_SELECT);

/**
 * After photo is selecte, you can do the processing.
 */
public void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == IMAGE_PICKER_SELECT  && resultCode == Activity.RESULT_OK) {
       // some code
    }
}


text:
Q: Type Error generated when updating a Dash Plotly graph I am running a code that produces a Dash Plotly scatter graph that can be updated using a radio button. An empty graph is generated and I am getting a callback error updating graph.figure each time I click on the radio button.
I am trying to figure out where the error is originating from and why it is occurring.
This is the error message
TypeError                                 Traceback (most recent call last)
TypeError: object of type 'int' has no len()

And this is the code
app.layout = html.Div([

    html.Div(id='radio_output'),
    dcc.RadioItems(
 id='radio_dropdown',

options=[{'label': i, 'value': i} for i in [1.0, 2.0, 3.0]],
value=2.0
),

html.Div([
    dcc.Graph(id="the_graph")]
)])

@app.callback(
    Output("the_graph", "figure"),
    Input("radio_dropdown", 'value')
)

def update_graph(selected_std_dev):
    if len(selected_std_dev) == 0:
        return dash.no_update
    else:
        max_deviations = [(RadioItems(value) == selected_std_dev)]
        dff=pd.DataFrame(dff=df)
        x = dff.TIME
        y = dff.CHANGE
        mean = np.mean(y)
        standard_deviation = np.std(y)
        distance_from_mean = abs(y - mean)
        not_outlier = distance_from_mean < max_deviations * standard_deviation
        no_outliers = y[not_outlier]
        trim_outliers = pd.DataFrame(data=no_outliers)
        dff = pd.merge(trim_outliers, df, left_index=True, right_index=True)

A: The error is pretty self-explanatory. The function is passed an integer, however integers don't have any __len__ method associated with them. The len() calls the __len__ function of the object that is passed to it. docs


text:
Q: Requirejs + Backbone Uncaught TypeError: Cannot read property 'Model' of undefined I have been starting with Backbone. I used Require to load modul and got this error. Can anyone explain this? In file user.js i have this bug when I try to create Backbone.Model.extend. I used Backbone.js 0.9.10, jQuery v1.9.0, RequireJS 2.1.4, Underscore 1.4.4. Thank you.
index.html
<!doctype html>

    <title></title>

    <link rel="stylesheet" type="text/css" href="stylesheets/style.css">

main.js
require.config({
    paths:{
        jquery:'libs/jquery/jquery-min',
        underscore:'libs/underscore/underscore-min',
        backbone:'libs/backbone/backbone-min',
        templates:'../templates'
    }
});

require(['app'], function (App) {
    console.log('____main.js')
    App.initialize();
    console.log('main.js')
});

app.js
define(['jquery', 'underscore', 'backbone', 'router'], function($, _, Backbone, Router) {
    var initialize = function(){
        Router.initialize();
        console.log('app.js');
    };

    return {
        initialize: initialize
    };
});

router.js
define([
    'jquery',
    'underscore',
    'backbone',
    'views/home/login'
    //'views/room',
//    'views/friend',
//    'views/play',
//    'views/money'
], function ($, _, Backbone, loginView) {
    console.log('router.js');
    var AppRouter = Backbone.Router.extend({
        routes:{
            '/home':'showHome',
            '*actions':'defaultAction'
        },
        showHome:function () {
            loginView.render();
        },
        defaultAction:function (actions) {
            console.log('No route:', actions);
        }
    });

    var initialize = function(){
        var app_router = new AppRouter;
        Backbone.history.start();
    };
    return {
        initialize: initialize
    };
});

login.js(Backbone View)
define([
    'jquery',
    'underscore',
    'backbone',
    'collections/home/users',
    'text!templates/home/login.html'
], function($, _, Backbone, usersCollections, homeLoginTemplate){
    var loginView = Backbone.View.extend({
        el: $('container'),
        render: function(){
            var data = {};
            var compiledTemplate = _.template(homeLoginTemplate);
            this.el.append(compiledTemplate);
        }
    });
    console.log('login.js');
    return new loginView;
});

user.js (Backbone Model)
define([
    'underscore',
    'backbone'
], function (_, Backbone) {
    console.log('user model');
    var userModel = Backbone.Model.extend({
        default:{
            username:"",
            password:""
        }
    });

    return userModel;
});

users.js (Backbone Collection)
define(['underscore', 'backbone', 'models/user'], function (_, Backbone, userModel) {
    console.log('user collection');
    var usersCollection = Backbone.Collection.extend({
        model:userModel
    });
    return new usersCollection;
});

I can't post my picture. But you can see in this link http://imageshack.us/photo/my-images/809/devi.jpg/.

A: Maybe you're missing some shim config in your main.js file, read here: http://requirejs.org/docs/api.html#config-shim
You could try to add:
shim: {
    'backbone': {
        deps: ['jquery','underscore'],
        exports: 'Backbone'
    }
}

A: Use that @Ingro said and try to use the default underscore marker when you call to render templates.
for example:
main.js
require.config({
    paths:{
        jquery:'libs/jquery/jquery-min',
        underscore:'libs/underscore/underscore-min',
        backbone:'libs/backbone/backbone-min',
        templates:'../templates'
    },

    shim: {
        backbone: {
            deps: ['jquery','underscore'],
            exports: 'Backbone'
        }
    }
});
require(['app'], function (App) {
    console.log('____main.js')
    App.initialize();
    console.log('main.js')
});

and in anyone file that you use Underscore templates, for example your "login.js" use this:
define([
    'backbone',
    'collections/home/users',
    'text!templates/home/login.html'
], function(Backbone, usersCollections, homeLoginTemplate){
    var loginView = Backbone.View.extend({
        el: $('container'),
        render: function(){
            var data = {};
            var compiledTemplate = _.template(homeLoginTemplate);
            this.el.append(compiledTemplate);
        }
    });
    console.log('login.js');
    return new loginView;
});

jquery and underscore both are used by default in backbone require call.
I hope these help you.


text:
Q: Annotate specific text in pdf using ghost script I am trying to extract entities from the pdf and mark it back to pdf using pdf annotation.
Is there any way I can annotate specific text using ghostscript?
Thanks

A: You're going to have to be more specific. What do you mean by 'annotate specific text' ? Are you talking about;

*

*Altering a FreeText annotation ?

*Finding text in a content stream and altering it ?

*Adding an annotation at a specific point on the page ?

*Something else ?

Ghostscript is not intended as a general purpose PDF editing tool, and so it's quite limited in what you can do with it. You might be better advised to use something like MuPDF, but so much depends on exactly what you are trying to do, it's not really possible to make any specific recommendations.


text:
Q: analyze constrained extremum by projection to tangent space I want to analyze the local behavior of a function $f(\mathbf{x})$ on a manifold at a certain point $\mathbf{x}_0$ which lies on the manifold.
One approach would be to add small disturbances $\mathbf{h}$ to $\mathbf{x}_0$, project $\mathbf{x} = \mathbf{x}_0 + \mathbf{h}$ onto the manifold (closest point $\mathbf{x}'$ on the manifold), and check whether e.g. $\Delta f = f(\mathbf{x}') - f(\mathbf{x}_0) < 0$ for all $\mathbf{h}$ which would indicate a local maximum.
However, it may be difficult to analytically find the projection $\mathbf{x}'$ on the manifold. Therefore I thought of projecting $\mathbf{x}$ onto the tangent space of the manifold at $\mathbf{x}_0$ instead.
My question is: If I can show that $f$ e.g. has a local maximum at $\mathbf{x}_0$ on the tangent space, can I conclude that it also has a local maximum on the manifold?
(Edit: There seems to be an additional difficulty besides the question whether locally the (smooth) manifold can be represented by its tangent space for this analysis: If we derive an expression for $\Delta f(\mathbf{h})$ e.g. at a local maximum, we will always see $\Delta f(\mathbf{h}) = 0$ at the direction normal to the manifold at $\mathbf{x}_0$, i.e. for $\mathbf{h}' = \mathbf{0}$. I wonder whether this can be eliminated afterwards.)


text:
Q: How to display multiple form fields of the same type using jquery and fetch their values in php I have a table named order_master which stores the order_id column. I also have another table order_details having the columns order_id (FK), vendor, purchase_date, delivery_date, and person_name  which stores the details of the order corresponding to the order_id from the order_master table.
I want to display a form wherein a button add new item will be displayed. On clicking this button each time, a new block of fields (like vendor, purchase_date, delivery_date, person_name) will be displayed. The user can click the above button and enter as many items as he wants on the same order_id. And when he submits the form, the items on this form must be entered in the database.
How to achieve this?
actually i am using codeigniter framework (MVC architecture). Here i am attaching the view and js file.
<?php echo form_open(); ?>

                    <select name="item[]" id="item" class="form-control">
                        <option value="">--Select Item--</option>
                        <?php foreach ($items as $item) { ?>
                            <option value="<?php echo $item["id"]; ?>"><?php echo $item["name"]; ?></option>
                        <?php } ?>
                    </select>

                    <select name="vendor[]" id="vendor" class="form-control">
                        <option value="">--Select Vendor--</option>
                        <?php foreach ($vendors as $vendor) { ?>
                            <option value="<?php echo $vendor["id"]; ?>"><?php echo $vendor["name"]; ?></option>
                        <?php } ?>
                    </select>

                    <input type="text" name="po_date[]" id="po_date" class="form-control date" placeholder="Purchase Date">

                    <input type="text" name="quantity[]" id="quantity" class="form-control number" placeholder="Item Quantity Individual">

                    <input type="text" name="unit_price[]" id="unit_price" class="form-control number" placeholder="Unit Price" style="text-align: left;">

                    <textarea name="description[]" id="description" class="form-control"></textarea>

                Add new item

            <input type="button" value="Add Purchase Order" id="addpurchaseOrderBtn" class="btn btn-primary">

        <?php echo form_close(); ?>

                                                                                **JS File**

$("#main_content").css('minHeight', '400px');
$(document).ready(function() {
    $('#add_item').click(function() {
        var def_ht = $("#main_content").height() + 300;
        $("#main_content").css('minHeight', def_ht);
        $("#form-box").clone(true).appendTo("#form-box");
        return false;
    });

    $("#addpurchaseOrderBtn").click(function() {
        focusId = null;
        var isvalid = false;
        if(validateDropDown('item')){
            isvalid = true;
        }
        if(validateDropDown('vendor')){
            isvalid = true;
        }
        if(validatDate('po_date')){
            isvalid = true;
        }
        if(validateTextbox('quantity')){
            isvalid = true;
        }
        if(validateTextbox('unit_price')){
            isvalid = true;
        }
        if(validateTextbox('description')){
            isvalid = true;
        }
        if(isvalid){
            focusId.focus();
            $("#messageBox").html('
There are some error in your submission. Please try again.
');
        }else{
            $("#addPurchaseFrm").submit();
        }
    });

});
                                                                                This code works but i am unable to validate all the elements(items) in the form.

A: You can try the following structure-
<form name="addItem" method="post" action="addItem.php" class="insertItem">

<input type="text" name="vendor" >
<input type="text" name="purchase_date" >
<input type="text" name="delivery_date" >
<input type="text" name="person_name" >

<input type="submit" name="submit" value="Add Item" class="btn btn-primary additem">

$("document").ready(function(){
    $(".additem").click(function(){
        $(".insertItem").append($(".itemAdd").html);
    });
});

Then on addItem.php, you can execute the insert query to insert this data into your database


text:
Q: Publish an Azure Web App via Visual Studio for Mac I've created a sample asp.net core application using Visual Studio for Mac and trying to publish it to Azure. My wizard shows me nothing once opened and hangs at the Querying subscriptions step:

If I go to preferences -> account - I have a similar issue with the account wizard:

A: Currently there is a bug with the authentication in Visual Studio for Mac. It can sometimes be worked around by doing the following:
Close Visual Studio for Mac, delete the ~/.ServiceHub directory, and restart Visual Studio for Mac.
If that does not work you can try deleting both the ~/.ServiceHub and the ~/.IdentityService directory. Then start Visual Studio for Mac and log in again.


text:
Q: A nonstatic member reference error in Array using c++ I am a beginner in programming C++ and I'm learning all about classes and objects right now. For practice, I created a class called Employee and added some members in it. But I noticed that the record array is giving me an error stating a nonstatic member reference must be relative to a specific object. This only happens whenever I create an array in Employee class. But when I called it in my constructor Employee(), it is not highlighted as an error, as well as when I tried initializing it as a global variable, or even a local variable in my main.cpp(this is where main() is located). Kindly give advice or even better solution for this.
   #pragma once
   #include<string>
   #include<iostream>
   using namespace std;

   class Employee
   {
   private:
   int recordSize = 100;
   int fieldSize = 4;
   string record[recordSize][fieldSize];

   public:
   Employee();
   ~Employee();

   };

main.cpp:
   #include "Employee.h"
   #include<string>
   #include<iostream>
   #include<iomanip>
   #include<fstream>
   using namespace std;

   Employee::Employee() {
      ifstream inFile;
      inFile.open("C:\\Users\\RJ\\Desktop\\employee-info.txt");

      for (int index = 0; index < recordSize; index++) {
          for (int index2 = 0; index2 < fieldSize; index2++) {
             inFile >> record[recordSize][fieldSize];
             }
           }
          }

   Employee::~Employee()
   {
   }

I also include content of employee-info.txt
 ID           Firstname            Lastname                 Sales
 1                Bruno                Mars             120000.00
 2               Lebron               James             150000.00

A: The variables recordSize and fieldSize need to be both static and const (or constexpr) to be used as dimensions of std::string record 2D array.
They need to be const because the array bound should be an integer constant.
They need to be static because the record array is not allowed to have different sizes for different instantiations of Employee class.
If you want the 2D array to be able to hold different sizes in different instantiations of Employee class, you should go for an std::vector of std::vector<std::string> instead.

A: The sizes need to be constexpr when used to define array sizes
static constexpr int recordSize = 100;
static constexpr int fieldSize = 4;
string record[recordSize][fieldSize];


text:
Q: byte[] formatting of Cerebrata Azure Management Studio I am trying to debug an issue where my data is stored in Azure Table Store as a byte[]. I am using the Cerebrata Azure Management Studio and it shows the byte[] column as:
16000000010000000E00000001010400000031343230
Does anyone know what format this is stored in? How can I convert this into a byte array? It does not look like a base 64 or UTF encoded string.

A: Haha... the data is literally stored as bytes, just in hex form.
i.e. 16000000010000000E00000001010400000031343230   is really:
16 00 00 00 01 00 00 00 0E 00 00 00 01 01 04 00 00 00 31 34 32 30
:-)
So the rest is trivial... I used a quick function like this:
var hex = "16000000010000000E00000001010400000031343230";
byte[] bytes = new byte[hex.Length/2];
for(int i=0; i<hex.Length;i+=2)
{
    bytes[i/2] = byte.Parse(
        hex.Substring(i, 2),
        System.Globalization.NumberStyles.HexNumber);
}


text:
Q: Is the space $X$ is complete?(TRue/False) Let $f:X\to Y$ be a continuous map between metric spaces. Then $f(X)$ is a complete subset of $Y$ if

*

*the space $X$ is compact

*the space $Y$ is compact

*the space $X$ is complete

*the space $Y$ is complete
My trial :   i was taking $X =Y =R$,,and i know that R is complete as complete map to complete  so the correct option will option 3 that is the space X is complete .
Is my answer is correct or not ? pliz verified and tell me the solution  i would be more thankful...

A: If $X$ is compact, then $f(X)$ is compact too and therefore complete.
All other options are false. Can you see why?


text:
Q: Python3 Problem - Last value printing to new line using format / selenium webdriver My goal: using self.cookie = '{}{}user-data-dir={}'r'{}{}{}'.format("(","'","'",'r',self.line," )")
I am setting that to be used in my main script to set a value, ok so my problem? Well I run it, and it is 99.5% the way it needs to be, I can not for hours now figure out why it keeps printing the last ) on a new line, which i am printing it to debug.. it needs to be on the same line so it can be used in actual code like so: ('user-data-dir='r'C:\Users\0\AppData\Local\Google\Chrome\User Data')

    def __init__(self):

        with open('cookies.txt', 'r+', encoding='UTF-8') as f:
            for self.line in f:

                self.chrome_options = webdriver.ChromeOptions()

                self.cookie = '{}{}user-data-dir={}'r'{}{}{}'.format("(","'","'",'r',self.line," )")
                print(self.cookie)
CookieSet()

A: rstrip() is what you want to remove the newline:
            self.cookie = '{}{}user-data-dir={}'r'{}{}{}'.format("(","'","'",'r',self.line.rstrip()," )")

A: Use string f string is much cleanerz also can use just trim to remove line from both left and right of the string.
self.cookie= (f"(user-data-dir='{self.line.strip()}')")

print(self.cookie)


text:
Q: What normal form are the this relation in? Am I right? -

R(a, b, c, d)

Functional dependencies: None
I think it is 0NF, because there are no functional dependencies.

R(a, b, c, d)

Functional dependencies: b->d AND a,b->c
This should be 3NF, i think.
I am stuck at this one

R(a, b, c, d, e)

Functional dependencies: a->d,e AND a,d->b,c,e

A: There is always the trivial dependency,
a,b,c,d -> a,b,c,d

The key is the entire relation.  Not often useful, but not 0NF.

A:
R(a, b, c, d)
Functional dependencies: b->d AND a,b->c
This should be 3NF, i think.

No, it's 1NF.  The only candidate key is ab. That means b->d represents a partial key dependency, so R's normal form must be lower than 2NF.


text:
Q: Show orthogonal projection is minimal distance In a textbook exercise a bunch of vector spaces were given along with subspaces and a vector $v$. Then the task was to compute the orthogonal projection $\pi(v)$ to that subspace $U$ with their respective scalar products. Simple enough,
now the task after that that asked: Compute the distance $$d(v,U):=min_{u\in U} ||v-u||$$ for all the spaces given in the previous task. Well it's the orthogonal projection we computed above! But how can one prove this? Especially when you move to more abstract spaces like the space of continuous functions, it does not seem that obvious anymore.
So how can we prove it? Maybe we can show $||v-\pi(v)||^2=\gamma(v-\pi(v),v-\pi(v))$ is minimal ( where $\gamma$ is the inner product). I don't know how you would approach showing it is the minimal distance. Finding a minimum seems more like a calculus problem!
Related questions often state that this is the case, but do not show a proof, see for example :
Projection of v onto orthogonal subspaces are the those with minmum distance to v?

A: Using Pythagoras theorem, one has:
$$\|v-u\|^2=\|v-\pi(v)\|^2+\|u-\pi(v)\|^2\geqslant\|v-\pi(v)\|^2.$$
Indeed, $u-\pi(v)\in U$, since $U$ is a vector space and $v-\pi(v)\in U^{\perp}$, for the last point notice that:
$$\pi(v-\pi(v))=0,$$
since $\pi$ is a linear projection, so that $v-\pi(v)\in\ker(\pi)=U^{\perp}$.
Whence the result.

Since you were talking about this result for vector spaces of functions, I'd like to give such an application.
Let $V=L^2(\mathbb{T})$ the vector space of square-integrable $1$-periodic functions and $U$ its subvector space formed by the trigonometric polynomials of degree at most $n$. In this setup, the result of your exercise means that the $n$-th partial sum of the Fourier series of $f$ is the best $L^2$-estimate of $f$ as a trigonometric polynomial of degree at most $n$.


text:
Q: custom generic instanceof function I am performing an instanceof check in *ngIf.
 <span *ngFor="let element of elements">
   <app-text *ngIf="element instanceof BlueElement"></app-text>
 </span>

Unfortunately, instanceof cannot be used, because it is defined by javascript.
Therefore I created my own instanceOf method:
  instanceOf<T,C>(value:T,clss:C){
    if (value instanceof C){
      return true;
    }else{
      return false;
    }
  }

I am getting an error; C is only defined as a type, but is being used as a value here.
How should I rewrite the generic instanceOf() function?

A: You can only use instanceof on a constructor value.
That means it must be a constructor value as opposed to just any old object.  TypeScript only requires the constructor property of a class to be a Function, so at the very least you need to specify that C extends Function.  If you want to be safer, restrict C to actual constructor functions whose singatures are like new(...args: any[])=>any.
It also means it must be a constructor value as opposed to its type.  The value is clss, and its type is C.  As pointed out by @vu1p3n0x, you should writeinstanceof clss.  You can't write instanceof C, since C is just a type and it doesn't even exist at runtime.
Putting that together:
function instanceOf<T, C extends new (...args: any[]) => any>(value: T, clss: C): boolean {
  return value instanceof clss;
}

As an aside, note that in JavaScript value instanceof clss evaluates either true or false.  So you can just return it instead of checking it with if.
Hope that helps; good luck!


text:
Q: Smooth transition between two states (dynamically generated) I have a graphic element. Let's give an initial state.
Defining state: a position on the screen and a custom transformation (scale+rotation+skew) given by the coordonates of 3 corners of the image (top-left, top-right and bottom-left).
And on a moment in time later the app recieves some input giving a new state. At this moment I need the graphical element to start a transition towards the new state, doing a natural transition (not to appear big distortion in the proportions of the element).

Additionally, if a new state is recieved before the transition is over, it is abandoned and the new transition starts from where it remained.
Any suggestions how cand I achieve this?

A: iuliux,
The classic implementation to animate a transition in N steps is as follows:
for (i = 0;  i <= N;  ++i) {
  for (p = 0;  p < nPoints;  ++p) {
    pointsToDraw[p] = initialPoints[p] + (finalPoints[p] - initialPoints[p]) * i / N
  }
  drawFigureAt(pointsToDraw);
}

In English:

*

*For each point, imagine a line between its initial and final positions.

*Calculate points along the line that divide it into N segments of equal size.

*Draw the figure using the first set of points, then the next, etc.
If the figure moves before you've drawn the final state, copy its current position into initialPoints and start the transition again.
Hope that helps!


text:
Q: How to link various Google spreadsheets using IMPORTRANGEs that contain VLOOKUP formulas without getting #N/A returned? The problem:
When using IMPORTRANGE to pull data from a different spreadsheet, cells in the origin spreadsheet that contain a formule containing VLOOKUP often (but not always) return #N/A (ERROR: Did not find value 'xxx'  in VLOOKUP evaluation). In the origin sheet the formulas are calculated correctly and showing a value though. This does not always happen, sometimes it does pull in the proper value.
The intent:
To take data from different spreadsheets, combine them in a different spreadsheet and do some calculations on them. And then pull info from this calculation spreadsheet (or from multiple calculation spreadsheets) into a reporting spreadsheet for some further calculations and formatting.
The set-up:
There are several source data spreadsheets,say dataspreadsheet1, dataspreadsheet2 and dataspreadsheet3. A calculation spreadsheet (calcspreadsheet) is created that creates a copy of sheet1 in each of the data spreadsheets and names these sheets datasheet1, datasheet2 and datasheet3 respectively. The IMPORTRANGE statement used for this is created as follows: importrange(+VLOOKUP("dataspreadsheet1",filelist!A1:C1000,3,FALSE),"sheet1!a1:Z1000") where
filelist!A1:C1000 is a sheet in calcspreadsheet that contains Name, Type and Id in respective columns.
The values in each of these sheets datasheet1-3 are then used for calculations in another sheet, calcsheet1 in the calcspreadsheet. As the main goal of this is to add up daily values from the 3 dataspreadsheets, but those sourcesheets do not all have the same data on the same line a VLOOKUP is used again to make sure additions for a date use the line for the date in datasheet1-3 regardless of its row number. E.g. VLOOKUP($A11,'datasheet1'!$A:$P,4) + VLOOKUP($A11,'datasheet2'!$A:$P,4) + VLOOKUP($A11,'datasheet3'!$A:$P,4) where column A is the date column in all sheets.
This appears to work fine, although upon opening calcspreadsheet it can take a long time for it to go through an update, during which time lots of #N/A's are displayed. Eventually it comes right though.
The problem arise when a reportspreadsheet is created that in turn used an IMPORTRANGE call to pull the info from calcsheet1 in order to be able to work with it. This often, but not always, results in the problem states at the start. The IMPORTRANGE call in this reportspreadsheet is generated in a similar way as that in the calcspreadsheet: =importrange(+VLOOKUP(calc!B1,sheetcodes!A1:C3000,3,FALSE),"sheet1!a1:Z1000") where calc!B1 contains the name of the source spreadsheet (in this calc that would be 'calcspreadsheet' and sheetcodes!A1:C3000 again contains a list of sheets with Name, Type and Id in respective columns
A work-around I tried:
What I did notice that IMPORTRANGE works better on cells that do not contain VLOOKUP So I tried to copy the content of calcsheet to another sheet in calcspreadsheet, called exportsheet but having only the values in there, not formulas and then use IMPORTRANGE on this exportsheet.  The copy script used is as follows:
function exportPrep() {
  // Get the active spreadsheet and the active sheet
  //var ss = SpreadsheetApp.getActiveSpreadsheet();
  //var sheet = ss.getSheetByName("stream");
  //sheet.activate();

  var source = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("calcsheet");
  var sourceDataRange = source.getDataRange();
  var sourceSheetValues = sourceDataRange.getValues();
  var sourceRows = sourceDataRange.getNumRows();
  var sourceColumns = sourceDataRange.getNumColumns();

  var destination = SpreadsheetApp.getActiveSpreadsheet();
  SpreadsheetApp.setActiveSheet(destination.setActiveSheet("exportsheet"));
  destination.getDataRange().offset(0, 0, sourceRows, sourceColumns).setValues(sourceSheetValues);
      }

This seemed to work, but unfortunately the copy script used to copy the value of calcsheet into exportsheet now showed the same behaviour, it would sometimes work and sometimes give the #N/A and so leaves me with the same problem.
My questions:
I've read various posts with similar issues and responses that mentioned this function was temperamental or had a bug. Other stated it is not possible to use dynamic references in IMPORTRANGE. Given that it sometimes works and sometimes not I suspect the function itself might be correct but that there are sync or time-out issues in the set-up.

How can I set up the above functionality. Either with the use of IMPORTRANGE and VLOOKUP at all with some changes/additions, or built in a different way from the get-go.

A: So I've not done this with importrange but I when I have this issue with Vlookup I wrap the vlookup in an IF and test for the #N/A.
Try something like: =IF(ISNA(VLOOKUP(...)),"",VLOOKUP(...))

A: =IFERROR(VLOOKUP(B81,'KAM_Q3_OPPS STAGE_(H/I/L/M/N)'!$F$3:$G$111,2,False),)
This is the best way I found to do it and the last two values [ , ) ] make the new output, in this case it is nothing.
IF you wanted 0 put in then you would do [ ,0) ]


text:
Q: Files don't open in browser I have newly installed Farm of Sharepoint 2013 on single server
I would like that any files Excel, Pdf, word, powerpoint... opens in browser. I was searching and already applied in advanced settings of the library function to open files in browser.
But when I click on the document it's first downloading it then open in the application.

A: I found my Happiness on this link;
https://technet.microsoft.com/en-us/library/e4d51dc4-6460-437d-aa8e-0ae4d3aa8cc5#singleHTTPS
I did not installed OFFICE WEB APP SERVER.

A: This may be helpful, at Site Collection Features:
http://YOURSITE/_layouts/15/ManageFeatures.aspx?Scope=Site

Disable:

*

*Open Documents in Client Applications by Default feature


text:
Q: Generate list of numbers from a list with probability weights How would one go about generating a list of random numbers from a list of 35 numbers with given probabilities:
Probability of number in range (1,5) - p1 = 0.5
Probability of number in range (6,15) - p2 = 0.25
Probability of number in range (16,35) - p3 = 0.25
I tried using numpy.random.choice() but I have no idea how to jam in possible lists of numbers.

A: If you want to select uniformly from each group:
p=np.array([0.5/5]*5+[0.25/30]*30)
np.random.choice(np.arange(1,36),p=p/p.sum())

UPDATE:
and if you would like to select a list of random numbers (you can also set with or without replacement flag):
np.random.choice(np.arange(1,36), size=N, replace=True, p=p/p.sum())

A: You could accomplish this by selecting the appropriate range with the specified probabilities, then use the chosen range as an argument to random.choice:
range_set = [range(1,6), range(6, 16), range(16, 36)]
random.choice(*random.choices(range_set, [0.5, 0.25, 0.25]))

This assumes that you want a uniform choice within a given range.


text:
Q: Persitant backups in Windows Server 2008 I have a system that is updated very often and I'm looking for a solution that would backup and log when file or number of files change on the server. I understand the amazing potential of git and svn but the usage here is different.
Users are uploading modified files to either an ftp or network drive.
DB entries are added and removed multiple times in the day.
System files are modified for testing or configuration.
Any assistance or recommendations would be appreciated.

A: You could enable VSS snapshots on the volume the data will be held.  VSS snapshots will take snapshots of a volume on a specified schedule.  You would be able to restore from a specific snapshot using the "previous Versions Tab" on the file/ folder. check out What is Volume Shadow Copy Service for more details.
This would backup the files at specified intervals but would not log when files are modified other than in their usual file attributes.

A: I did something similar where I work using fossil. Set up a repository with the necessary files, then create a batch script with a couple commands in it.
change to your directory
fossil add "wild card to select files"
fossil commit -m "Automatic repo commit"
repeat as necesssary

Run this as a scheduled task on a short timer. Every time that fossil does an add, it will only add new files to the repository. The commit will then put every new file and edited file into your repository. If you want everything in the directory just use * for your wildcard.


text:
Q: toggling styles on label (active/focus) with styled components and chakra UI I have created an input field along with a label, on active and focus state the label position should change as mentioned in below CSS code. Issue is when I try to add focus and active pseudo-class on input and label after active state the label position is again coming down.
The HTML code
  <MainDiv className="maindiv">
      <InputText
        className="input"
        size="lg"
        borderRadius="lg"
      />
      <LabelText className="text">
        Label
      </LabelText>
    </MainDiv>

The CSS Code
const MainDiv = styled(Box)`
  position: relative;
  width: 21rem;
`;

const InputText = styled(InputField)`
  padding: 20px 0 4px 16px;
  font-size: 16px;
  font-weight: 400;
  letter-spacing: 0.01rem;
  &:focus + .text,
&:active + .text
 {
    top: 0px;
    left: 18px;
    margin: 4px 0 0 0;
    font-size: 12px;
    font-weight: 900;
  }
`;

const LabelText = styled(Text)`
  font-size: 16px;
  font-weight: 400;
  color: "#4d443e";
  width: fit-content;
  height: 16px;
  position: absolute;
  top: 12px;
  left: 18px;
  bottom: 12px;
  transition: 0.2s;
`;

Can anyone help me with the approach? Currently, it works when the pseudo-class is focus


text:
Q: Any way to extract out named IntegerList more elegantly from nested list? I have list of position index in the IntegerList, and I intended to filter them given threshold, and it works well. However, I want to extract out one of specific filtered set for each IntegerList for further usage. I aware that myList is nested list , and data are very much simulated based on real data set. Is there any way to retrieve wanted IntegerList easily and elegantly? How can I make it this extraction happen?
To run mini example, following library is needed:
library(IRanges)
library(S4Vectors)

mini example :
myList <- list(f1=IntegerList(1,2,3,4,1,1,1,integer(0),1,2,4),
               f2=IntegerList(1,5,integer(0),integer(0),2,3,4,6,1,5,6),
               f3=IntegerList(1,4,6,7,2,3,3,7,2,5,7))

len <- Reduce('+', lapply(myList, lengths))
keepMe <- len >= length(myList)

I intended to filter them as follow:
res.filt <- lapply(myList, function(elm) {
  ans <- list(keep=elm[keepMe], droped=elm[!keepMe])
  ans
})

my rough output :
Keep.list <- list(f1.kp=res.filt$f1$keep, f2.kp=res.filt$f2$keep, f3.kp=res.filt$f3$keep)
Drop.list <- list(f1.dp=res.filt$f1$droped, f2.dp=res.filt$f2$droped, f3.dp=res.filt$f3$droped)

Based on my rough output, How can I get more elegant output ? any efficient way to achieve my output ? Can anyone point me how to do? Or any suggestion how to get my expected output ? Thanks in advance

A: Your thought process/flow for filtering the vector lists is logical and pretty optimal, but you can tighten it up a bit if you use purrr:
library(purrr)

map(myList, lengths) %>%
  reduce(`+`) %>%
  map_lgl(`>=`, length(myList)) -> keep_me

keep_list <- map(myList, ~.[keep_me])
drop_list <- map(myList, ~.[!keep_me])


text:
Q: Error when trying to contact MongoDB server inside a vue 3 component I'm doing a small hobby project for learning how to connect and read information from a database. Have done it with a local host JSON server, but want to take it a step further. I'm trying to connect to a MongoDB server inside of a Vue 3 component. The end goal is to read user login credentials from a database and compare it to input from a form. But first, I'm trying to get some simple information to work with to learn the basic concepts. This code list the databases I have in my cluster and works fine when I run it through an index.js file with the node terminal (Except the fake connection string).
  const {
        MongoClient
    } = require('mongodb');

    async function main() {
        const uriTest = "mongodb+srv://notRealUser:password@cluster0.p3imp.mongodb.net/database?authSource=admin&retryWrites=true&w=majority"
        const client = new MongoClient(uriTest);
        try {
            await client.connect();
            await listDatabases(client);
            console.log("Connected correctly to server");
        } catch (e) {
            console.error(e);
        } finally {
            await client.close();
        }
    }

    main().catch(console.error);

    async function listDatabases(clients) {
        const databasesList = await clients.db().admin().listDatabases();
        databasesList.databases.forEach(db => console.log(`${db.name}`));
    }

But whenever I want to run it in my Vue 3 application I get a long error. I get about 27 errors mentioning something similar to this:
If you want to include a polyfill, you need to:
    - add a fallback 'resolve.fallback: { "stream": require.resolve("stream-browserify") }'
    - install 'stream-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
    resolve.fallback: { "stream": false }

I searched the internet for an answer and someone mentioned that this could be because of "web pack 5". I would really like to learn how to solve this for a Vue project. Is it a better way to approach this with MongoDB and Vue3? If I'm doing this all wrong please lecture me. Thank you for reading. :)

A: It's rather not possible to connect to the database directly from the website and even if it's possible, no one will recommend this.
To access any database you should have a code that is running on the server side where malicious users can't access it. This is why web application usually need a backend.


text:
Q: Streaming PDF file from .NET Generic Handler generates Adobe Reader corruption error I have a generic handler that serves files for download:
    Dim request As HttpRequest = context.Request
    Dim response As HttpResponse = context.Response
    response.ContentType = "application/octet-stream"
    response.AddHeader("content-disposition", "inline; filename=" & filename)
    response.Buffer = True
    response.OutputStream.Write(fileBytes, 0, fileBytes.Length)
    response.Flush()
    response.Close()

('fileBites' is my bite array, 'filename' is my file name).
When fileBites is, say, a .txt file - the download is triggered and the file is read perfectly.
I discovered, however, that .pdf and .docx files were being corrupted - In the case of .docx, Word was saying that the file needed to be recovered and asked me for permission to do so. When I granted this permission it fixed it immediately and displayed perfectly.
Obviously I didn't want users to see this corruption dialogue and after researching for a while I discovered this: http://forums.asp.net/t/1301978.aspx/1/10 - which suggested that the reason for the corruption was one extra empty bit was being written at the end of the byte array: I checked by dropping the length by one bit:
response.OutputStream.Write(fileBytes, 0, fileBytes.Length - 1)
and like magic, .docx downloads now work! (This is not my current problem, I include it for context and in case anybody else has the same issue)
My current problem is that although .docx files are now streaming correctly, .pdf files are not. They seem to transfer in one piece (at the correct KB size) but when I try and open the downloaded file Adobe Reader X tells me:
Adobe Reader could not open xxxx because it is either not a supported file type
or because the file has been damaged (for example, it was sent as an email
attachment and wasn't correctly decoded).

There was a fairly long unresolved discussion on the adobe forums dated 2008 (http://forums.adobe.com/thread/391712) that addresses this exact issue but this is now dead. I have tried all of the workarounds that users have posted (content type: /pdf not /octet, disposition: application not inline, different content-encodings and charsets, etc) but all to no avail.
I wonder if anybody has encountered this problem before that could point me somewhere vaguely approximating something that even remotely resembles the right direction!

A: (Answer in the comments and edits. See Question with no answers, but issue solved in the comments (or extended in chat) )
The OP wrote:

Having stared at it for hours, the answer appeared shortly after posting this question - which is so often the way! At any rate, here is the resolution for anybody else stuck with my specific issue:

When I added a file into the database, I also allowed it to be renamed. I would select a file, give it a name and store it in the DB as [Fileblob],[Filename] - I could pick any arbitrary name, I assumed, because it was no longer tied to a specific location in the file system. - Wrong! - With .txt and .docx files, this was fine, the original name was never invoked.
Obviously something has embedded the name of the file into the binary object when it was saved and checks the name provided in the content-disposition against the name embedded into the document when it is opened. It then throws a corruption error if they do not match.
Now, I am storing the file in the database as [Fileblob],[Filename],[originalFilename] and when opening it I am using:
response.AddHeader("content-disposition", "inline;filename=" & originalFilename)

..to give it a name it understands. I suppose the more elegant way would be to strip the original name from the PDF when storing it in the database as it is no longer needed but as a workaround this works just fine.


text:
Q: Recreate the upload folder from a website without having access to the backend/cpanel/filezilla directly from the website Here's my scenario:
I'm working on a website, I have access to the dashboard on WordPress BUT:

*

*I can't install plugins.

*I don't have access to all the folders except for wp-content.

*I don't have access to the Cpanel/filezilla

I'm able to work on the website and copy the database, but I don't have access to the default image folder, UPLOAD but in order to recreate the structure of the website, I should paste and copy ALL the pages, then extract the images, then create other folder and, at the end of the day, place the images files there and then I could be ok.
I'm wondering if it is possible to do it differently..
Like a chrome extension, some WordPress native function, so anything else.. from outside that website because I'm recreating the website locally.
Any suggestion or hint would be appreciated!

A: You don't mention what your user privileges are - are you an admin, editor, author, etc? An admin-level should be able to install plugins via Plugins, Add New.
Most new-to-WP people don't realize that access to the folder structure (via cPanel or FTP) is not needed to admin the site. Any installation of themes/plugins is done via admin access, at the admin-rolelevel. Any adding of images to the uploads folder is done via the admin panel Media entry, or when adding/editing a post/page (assuming you have privs/ro;e to do that).
If your user is an admin-level role, then you should be able to add plugins (via Plugins, Add New), or add media (via Media page, or when adding/editing a page/post). If you aren't an admin-level role (which is different than logging into the admin panel), then your capabilities are limited.
To understand roles and privileges, see https://wordpress.org/support/article/roles-and-capabilities/ .


text:
Q: Решение задачи взаимного исключения Имеется остановка маршрутного такси. С определенными интервалами времени на остановку приходят пассажиры и подъезжают такси. Такси уезжает, когда в него сядет 10 пассажиров. Если пришедший пассажир не обнаруживает стоящего такси, он встает в очередь на посадку. Если такси подъехало на пустую остановку, оно ждет пасажиров. Если такси подъехало, а на остановке уже стоит такси, оно встает в очередь такси.
Не получается сделать модель точно по коду
`#include <pilgrim.h>
float Pas=1.0;  /* интервал прихода пассажиров */
float Tax=10.0; /* интервал прихода такси */
float Mod_time=360.0;
forward
{
 modbeg("Маршр. такси", 5, Mod_time, (long)time(NULL),
         none,2, none, 5, 2);
 ag("Пассажиры", 1, none, expo, Pas, zero, zero, 2);
 ag("Такси", 6, none, norm, Tax, Tax/3, zero, 2);
 network(dummy, dummy)
 {
  top(2): queue("Пассажиры", none, 3);
          clcode
           if (addr[2]->na == 1)
            hold(3); /* начальное размыкание ключа */
          place;
  top(3): key("Есть такси?", 4);
          place;
  top(4): delet("Посадка в такси", 0, 10, 5);
          rels(3);
          hold(8);
          place;
  top(5): term("Такси уехало");
          hold(3);
          rels(8);
          place;
  top(7): queue("Такси", none, 4);
          place;
  top(8): key("Остановка свободна?", 4);
          place;
  fault(123);
 }
 modend("pilgrim.rep", 1, 12, page);
 return 0;
}

`


text:
Q: Effiecient Windows to Linux desktop sharing solution that support multiple screens I am looking for an efficient Windows to Linux desktop sharing software that support multiple screen.
As of now my team develops (mustly Scala) code on our local windows machines (laptops).
For various reasons the data we are working on can't usually be copied to our local machines.
Currently we quite frequently need to exports our code/jars to a different environment that is also connected to an Hadoop cluster containing the data.
We are looking for a desktop sharing solution that will enable us to develop and execute code on remote, strong, stable Linux machines, that are connected via broadband connection to our data clusters.
Its crucial for us that the solution above will be able to run remote GUI based developing tools such as IntelliJ on the Linux machines and display them on our local Windows machine multiple screens smoothly.
Any recommendation?
Thanks in advance,
Mishael

A: One of the options is to use Cygwin - this will allow  you to run UI applications from a remote server on your Windows environment
In order to that you should do the following:
A. On Windows side:
Download and install Cygwin/X from : http://x.cygwin.com/
In the Cygwin/X installer make sure the following packages are chosen:

*

*xorg-server (required, the Cygwin/X X Server)

*xinit (required, scripts for starting the X server: xinit, startx,
startwin)

*X-start-menu-icons (optional, adds icons for X Clients to the Start menu)

*xorg-docs (optional, man pages)

*font-bh-ttf

*font-bitstream-vera-ttf

Setup X Launcher
Create a new shortcut on your desktop which points to the following (assume your cygwin was installed in c:\software):
C:\software\cygwin\bin\run.exe C:\software\cygwin\bin\XWin.exe -multiwindow -clipboard -ac
Double click the shortcut you just created :)  this will start small icon on the left side of windows taskbar.
B. On Linux side
login to your remote server for the same windows machine (use any terminal - e.g Putty)
set the DISPLAY parameter your server:
export DISPLAY=<windows-host-name>:0.0

now you can run any application that requires GUI and it will open up on your windows machine
:)


text:
Q: Data transmission through multiple IoT devices We are implementing a device which will have multiple sensors inside multiple houses in our local area.
Each house will have 1 device fixed at a place and data will be transmitted to one central location. But the problem is we cannot install WiFi on these devices, it should work with cellular network.i.e. 2G,4G Or NB-IoT.
What is the best approach to implement this? Please suggest some good IOT devices which support cellular network transmission.


text:
Q: How to convert an object to a set? so I have a set named "all" that contains objects Doc. Then I have another set called "partDocs" that contains other sets that contains Doc. Let's say that "all" contains = [Doc1, Doc2, Doc3]. I want partDocs to contain those sets like: [[Doc1], [Doc2], [Doc3]]. How can I do that?
I tried
Set<Doc> all = new HashSet<Doc>(); // contains [Doc1, Doc2, Doc3]
Set<Set<Doc>> partDocs = new HashSet<Set<Doc>>();
Set<Doc> set2 = new HashSet<Doc>();

for (i = 0; i < all.size(); i++) {
   set2.clear();
   set2.add(all.stream().toList().get(i)); // adds the i.th element of the all set
   partDocs.add(set2);
}

However when I do this, partDocs only has the last element of the all set, because set2 is always changing, and its last value is [Doc3]
I also tried doing below, but its syntax is wrong
for (i = 0; i < all.size(); i++) {
   partDocs.add(Set<allDocuments.stream().toList().get(i)>);
}

Does anyone have any idea about how to implement this?

A: I don't know if you actually want to do this. It seems like very confusing code but try the following:
Set<Set<Doc>> partDocs = new HashSet<Set<Doc>>();
Set<Doc> all = new HashSet<>();

for(Doc doc : all) {
    partDocs.add(Set.of(doc));
}

And now you have a set (partDocs) that contains sets which contain docs

A: The invalidation of set2 is flawed.
Instead of
set2.clear();

it should be
set2 = new HashSet<Doc>();

This particular bug may be easier to understand if we use a list for partDocs
List<Set<Doc>> partDocs = new ArrayList<Set<Doc>>();

which results in
[[Doc3], [Doc3], [Doc3]]

Essentially, we are adding the same Set to the List and since we are using the same reference, consecutive calls to set2.clear() and set2.add() will affect both the local variable and the Set in the List.
Going back to partDocs being a Set, it will end up with only one entry, because a Set guarantees to not contain duplicate values and three identical instances are  of course duplicates.

So, to fix this bug, we must ensure that the three objects added to partDocs are truly distinct, which is accomplished (partly) by the new invalidation routine
set2 = new HashSet<Doc>();

and otherwise by the fact that we add a different element to it each time.