text:
Q: yii2 exist validator with scenario does not work Scenario "withAppId" was defined and rule for "application_id" was linked to one, an ActiveField was added to form, but model doesn't save the field. What I did wrong?
Controller:
public function actionIndex()
{
    $post = Yii::$app->request->post();
    $model = new Option();
    $model->scenario = 'withAppId';
    if ($model->load($post) && $model->save()) {
        Yii::$app->session->addFlash('success', 'Запись успешно сохранена.');
        return $this->redirect(['index']);
    } else {
        //form rendering
    }
}

Model:
public function rules()
{
    return [
        ['key', 'trim'],
        ['key', 'required'],
        ['key', 'string', 'max' => 100],

        ['option', 'string', 'max' => 255],

        ['type', 'required'],
        ['type', 'in', 'range' => array_keys(self::$TYPES)],

        ['uploaded', 'image',
            'extensions'    => 'png, jpg, jpeg, gif',
            'maxWidth'      => 1000,
            'maxHeight'     => 1000,
            'maxSize'       => 1024*1024,
        ],

        ['application_id', 'exist',
            'targetClass' => Application::className(),
            'on'          => ['withAppId'],
        ],
    ];
}

public function scenarios()
{
    $cenarios = parent::scenarios();
    $cenarios['withAppId'] = $cenarios[parent::SCENARIO_DEFAULT];
    return $cenarios;
}

When 'on' => ['withAppId'], is removed the saving works properly.

A: Your $cenarios[parent::SCENARIO_DEFAULT] is empty. Try this:
public function scenarios()
{
    return [
        self::SCENARIO_DEFAULT => ['key', 'option', 'type', 'uploaded'],
        'withAppId' => ['key', 'application_id', 'option', 'type', 'uploaded']
    ];
}

Or you may write on condition in rules. There is part of doc scenario method:

The default implementation of this method will return all scenarios found in the [[rules()]] declaration. A special scenario named [[SCENARIO_DEFAULT]] will contain all attributes found in the [[rules()]]. Each scenario will be associated with the attributes that are being validated by the validation rules that apply to the scenario.

Note: if you append parent scenarios like this $cenarios = parent::scenarios(); then always append parent rules.


text:
Q: cygpath not able to convert Windows path to Linux path Im trying to convert the file paths to/from Linux and Windows on Windows Machine.
unix path to windows works fine.
$ cygpath -w /cygdrive/c/CYGWIN/CYGBuild/build.mak
C:\CYGWIN\CYGBuild\build.mak

But windows path to Linux gives wrong output. i.e Missing '/' and also cygdrive
$ cygpath -u c:\cygwin\cygbuild\build.mak
c:cygwincygbuildbuild.mak

Anyone faced this issue?? Share your experience.
Thanks

A: Actually as far as I know; you need forward slashes in paths used in cygwin. Single quotations help in cases where there are spaces (and my guess in this case; using backslashes instead of forward slashes) in the path. Otherwise backslashes are like escape characters, while spaces (although not in your case) require escape characters themselves. So quoting the path tends to eliminate such hassles.
Here are links that help me understand this:

*

*This opencv (using cygwin) tutorial, page 4, where there's an example of paths used, with and without quotes, indicating when one might need them.

*Also this is
very useful; a list of Cygwin's FAQs, including how to deal with
spaces (or in this case, backslashes in the path where adding quotes would help).

A: I got answer for this question.
cygpath -u 'c:\cygwin\cygbuild\build.mak'

i.e path should be given in single quotation.

A: cygpath's -m option is probably the easiest solution. Windows software generally accepts / as well as \. (There may be a few exceptions, but the development tools I work with have all been fine with it.)
$ cygpath -m /cygdrive/c/CYGWIN/CYGBuild/build.mak

C:/Cygwin/CYGBuild/build.mak

A: No one seems to have explain why, we here is an explanation.
Cygpath will accept slashes, and back-slashes: c:/cygwin/cygbuild/build.mak c:\cygwin\cygbuild\build.mak. However the shell will interpret the back-slashes, therefore you need to stop the shell from interpreting the back-slashes.
You can stop the shell from interpreting back-slashes, in arguments, by preceding them with a back-slash, or by quoting (with single quotes): c:\\cygwin\\cygbuild\\build.mak or 'c:\cygwin\cygbuild\build.mak'.
Double quotes will not help in this case. Double quotes stops argument breaking on space, but does not stop interpretation of escapes (\), or dollar ($) expansion.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Scilab: Failure to solve an ODE where dy/dt = A I want to solve a differential equation of the form dy/dt = A, where A is a vector of ones.
It shouldn't be a problem at all, yet it does not work. The code is:
t = [1 2 3 4 5 6 7 8 9 10];
var = ones(1:length(t));
y_an = 1*t;
//
function yd = f1(t,y, var)
    yd = var
endfunction
y0 = 1; t0 = 1;
//
y_m1 = ode(y0, t0, t, list(f1, var));

And it returns Error 98 at Line 10. But, if I modify the function as below:
function yd = f1(t,y, var)
    yd = var(1)
endfunction

The code runs and it returns:
y_m1  =

    1.    2.    3.    4.    5.    6.    7.    8.    9.    10.

I am truly baffled and asking for help, ie from @LutzL. This question is also related to two others:
Odd behavior of ODE in Scilab: equation dy/dx=A is not solved properly
Scilab: How to solve an ODE where dy/dt = filter(1, ar, y1)


text:
Q: Excluir valores de todas as colunas sob uma mesma condição (R) Tenho uma tabela no R com 96 colunas e 522 linhas e gostaria criar um filtro manter somente os valores que obedeçam à seguinte condição:
Para qualquer coluna os valores mantidos deverão ser a mediana de cada coluna & (valores >= a mediana de cada coluna + 20)
Por exemplo, a tabela:
A   B   C   D   F
100 49  15  40  60
34  15  14  14  50
14  13  12  13  30
9   12  9   12  2
8   2   8   12  1

Ficaria dessa forma:
A   B   C   D   F
100 49      40  60
34              50
14  13  12  13  30

Alguma sugestão de comando?

A: Talvez o seguinte código resolva o problema.
m <- sapply(dados, median)
i <- dados == m | dados >= m + 20
dados[!i] <- NA_real_
dados
#>     A  B  C  D  F
#> 1 100 49 NA 40 60
#> 2  34 NA NA NA 50
#> 3  NA NA 12 NA NA
#> 4  NA NA NA NA NA
#> 5  NA NA NA NA NA

Created on 2023-03-03 with reprex v2.0.2

Dados
dados <- "A   B   C   D   F
100 49  15  40  60
34  15  14  14  50
14  13  12  13  30
9   12  9   12  2
8   2   8   12  1"
dados <- read.table(text = dados, header = TRUE)

Created on 2023-03-02 with reprex v2.0.2


text:
Q: Is there any reason I should be working out of a branch in Git if I'm a lone developer? I just started using Git recently and I was reading up on Git best practices and it seems the most common one is to never work out of your master branch, always create a separate branch and work out of that.  I'm wondering if this is only true when working with other developers or if this is something I should be doing if I'm the only developer on the project.  If so, why?  And how often should I merge the new branch?  Why is that any different than just working out of the master branch and committing changes when necessary?
Thanks so much for your wisdom!

A: Yes,
Working from branches lets you isolate changes that you aren't ready for integration into your stable branch.
For example: I have been working on a major new feature in a separate branch for several months.  If I was not maintaining a separate branch, it would have been much more difficult for me to issue minor updates and fixes.

A: The beauty of git is that you don't have to do anything. There is no 'best' way to do something because it depends on you, your situation, your project, etc.
So, no, don't do anything that doesn't make sense to you. That said, keeping features in topic branches can be good for future-you reading the code and commit history. And, as others have said, definitely keep stuff in topic branches if you're working on two things in parallel.

A: Working out of a branch maybe a good idea if - for example - you are adding a phat new feature which wont be ready for a few weeks. Whilst you are working on your new feature, the Live app cocks up. What do you do if you havent branched (or tagged) from trunk (in this case the code branch supporting live) ?  you have to revert all your work and maintain copies of your changes, ready to slap them back in when you have resolved your live issue, bad times...

A: One good reason I can think of is that having a master branch allows you to point users to the master for pulling down releases, rather than having them pull straight from your working repository. That allows you to feel free to commit changes to your working repository that may not be quite ready for prime-time (eg: not fullly tested).


text:
Q: Deselect a selected object in Fabric.js I have multiple type objects on my canvas.
I can do scaling, rotation, etc. everything on a particular object.
But when I select a particular object, I want to change its stroke color.
canvas.observe('mouse:down', function(e) {

    activeInstance = canvas.getActiveObject();
    activeGroupInstance = canvas.getActiveGroup();
    if (activeInstance!=null){
        activeInstance.set("stroke","#FF0000");
    }
}

The code works well. But the issue is that the stroke color or any other valid property doesn't reflect directly which means I have to deselect a currently selected object to see the change in its properties. So my question is what's going wrong? If this is the usual behavior that we have to deselect/click the selected object, then, how to deselect the selected object using code i.e without using mouse clicks simply using a code-snippet.

A: We can use below mentioned solutions.
To discard all active groups you can use below function.Discards currently active group and fire events If the function is called by fabric as a consequence of a mouse event, the event is passed as a parmater and sent to the fire function for the custom events. When used as a method the e param does not have any application.
canvas.discardActiveGroup();

To discard sigle object you can use like this. Discards currently active object and fire events. If the function is called by fabric as a consequence of a mouse event, the event is passed as a parmater and sent to the fire function for the custom events. When used as a method the e param does not have any application.
canvas.discardActiveObject();

And i the last finally renders both the top canvas and the secondary container canvas like this.
canvas.renderAll();


text:
Q: create new array from old array column I'm new to OOP, but I'm trying to create my first bigger program.
I've read a txt-file and stored the  values (doubles) into an array, I call it originalArray. The text has two columns and 20 lines. So when I want to print the values in the first column of the txt-file I simply write:
 System.out.println(originalArray[0]);

 OUTPUT: 1991.00
         300.50
         498.50 .... et cetera...

My problem is that i'd like to use a for-loop (or whatever) to create two new arrays, each consisting one column from the "original array".
I thought it would be as simple as using a for-loop, like this;
  double [] newArray = new double [20];

  for(int i = 0; i < originalArray.length; i++){

  newArray[i] = originalArray[0] //if I want to fill it with the first

  //columns data... the second would be newArray2[i] = originalArray[1]
   }

But this fills the new array with ONE element from the column in the originalArray... So - I need help to figure of how to write the loop to fill the new arrays with all elements from one chosen column.
Very grateful for help!
Regards/ frustrated newbie
EDIT: This is how I read the txt file:
String file = "C:\\Users\\komena\\Desktop\\30th-sales.csv";

 BufferedReader br = null;
 String line = "";
 String splitBy = ";";

originalArray = new double [20];
br = new BufferedReader(new FileReader(file));
br.readLine();//skip the first line to get rid of header…
while ((line = br.readLine()) != null) {

String[] readlineArray = line.split(splitBy);

for (int i = 0; i < readlineArray.length; i++) {
originalArray[i] = Double.parseDouble(readlineArray[i]);

}

Whole text (csv) file:
300.50;330.00
489.50;296.50
34.50;399.50
900.00;1890.00
2052.00;568.00
354.00;0.00
399.00;0.00
1299.50;0.00
426.00;259.00
29.50;2300.50
99.50;349.50
2500.50;0.00
358.50;113.00
789.00;239.50
998.00;348.00
16.50;679.00
800.00;723.00
1899.50;950.50
550.50;568.00

A: Create the new 2D array with the size of the 1st dimension the same as the originalArray's length and the 2nd dimension the size of 2 (2 columns). Then simply loop it and add the old values to one column and also the new ones if reuqired, otherwise they will be set as 0.0 defaultly.
double originalArray[] = {1991.00, 300.50, 498.50};
double newArray[][] = new double[originalArray.length][2];
for (int i=0; i<originalArray.length; i++) {
    newArray[i][0] = i                              // Fill the 1st column with sth like ID
    newArray[i][1] = originalArray[i];              // Copy the 1D array to the 2nd column
}
System.out.println(Arrays.deepToString(newArray));  // Print all the array values

Output:
[[1.0, 1991.00],
 [2.0, 300.50],
 [3.0, 498.50]]

Moreover you read the file wrong. Notice that you have 2 values in the each line separated with ; and lines separated with \n. So read the line by line and add 2 values to the array.
The i variable represents the actual index of the originalArray[].
BufferedReader br = null;
String line = "";
int i=0;
double originalArray[] = new double[20];
br = new BufferedReader(new FileReader(file));
br.readLine();//skip the first line to get rid of header…

while ((line = br.readLine()) != null && i<originalArray.length) {
    String[] readlineArray = line.split(";");
    originalArray[i] = Double.parseDouble(readlineArray[0]);
    originalArray[i+1] = Double.parseDouble(readlineArray[1]);
    i+=2;
}
System.out.println(Arrays.toString(originalArray));


text:
Q: libprotobuf ERROR when training cifar10 on the windows Caffe Hi I'm new to DNN and I'm trying Caffe on windows 7. I have successfully compiled Caffe and also made train and test leveldb files of CIFAR10 and mean.binaryproto file. Now it's time to start train and test the CIFAR10, but when I try train, I get the errors that I couldn't solve even after googling long time..Please help!
Here's my version info : Anaconda2, Cuda 7.5, Cudnn 4, Visual Studio 2013
C:\caffe-master\Build\x64\Release>caffe train -solver=cifar10_quick_solver.prototxt
[libprotobuf ERROR ..\src\google\protobuf\text_format.cc:274] Error parsing text
-format caffe.SolverParameter: 4:10: Invalid escape sequence in string literal.
[libprotobuf ERROR ..\src\google\protobuf\text_format.cc:274] Error parsing text
-format caffe.SolverParameter: 4:23: Invalid escape sequence in string literal.
[libprotobuf ERROR ..\src\google\protobuf\text_format.cc:274] Error parsing text
-format caffe.SolverParameter: 4:32: Invalid escape sequence in string literal.
[libprotobuf ERROR ..\src\google\protobuf\text_format.cc:274] Error parsing text
-format caffe.SolverParameter: 4:40: Invalid escape sequence in string literal.
[libprotobuf ERROR ..\src\google\protobuf\text_format.cc:274] Error parsing text
-format caffe.SolverParameter: 24:22: Invalid escape sequence in string literal.

[libprotobuf ERROR ..\src\google\protobuf\text_format.cc:274] Error parsing text
-format caffe.SolverParameter: 24:35: Invalid escape sequence in string literal.

[libprotobuf ERROR ..\src\google\protobuf\text_format.cc:274] Error parsing text
-format caffe.SolverParameter: 24:44: Invalid escape sequence in string literal.

[libprotobuf ERROR ..\src\google\protobuf\text_format.cc:274] Error parsing text
-format caffe.SolverParameter: 24:52: Invalid escape sequence in string literal.

F1019 14:25:21.171140  5692 upgrade_proto.cpp:1063] Check failed: ReadProtoFromT
extFile(param_file, param) Failed to parse SolverParameter file: cifar10_quick_solver.prototxt
*** Check failure stack trace: ***

I also tried to update prototxt using upgrade_net_proto_binary, upgrade_net_proto_text, upgrade_solver_proto_text, I get the error...
C:\caffe-master\Build\x64\Release>upgrade_solver_proto_text c:\caffe-master\examples\cifar10\cifar10_full_solver.prototxt cifar10_full_new_solver.prototxt

[libprotobuf ERROR ..\src\google\protobuf\text_format.cc:274] Error parsing text
-format caffe.SolverParameter: 25:22: Invalid escape sequence in string literal.

[libprotobuf ERROR ..\src\google\protobuf\text_format.cc:274] Error parsing text
-format caffe.SolverParameter: 25:35: Invalid escape sequence in string literal.

[libprotobuf ERROR ..\src\google\protobuf\text_format.cc:274] Error parsing text
-format caffe.SolverParameter: 25:44: Invalid escape sequence in string literal.

[libprotobuf ERROR ..\src\google\protobuf\text_format.cc:274] Error parsing text
-format caffe.SolverParameter: 25:52: Invalid escape sequence in string literal.

E1018 20:49:33.715873  5896 upgrade_solver_proto_text.cpp:30] Failed to parse in
put text file as SolverParameter: c:\caffe-master\examples\cifar10\cifar10_full_solver.prototxt

A: After all those trials and errors, I got the answer.
For those who suffer the same thing, please refer.
at the solver file, I have indicated the source file and mean file to absolute address.
But the mistake I made is, I have written the address with \ not /.
Even I type in the command in cmd window with using \, in the prototxt, it does not allow it.
So you should write the address in prototxt file, with /.
i.e. C:/caffe-master/examples/cifar10/cifar10_full_train.prototxt.
Cheers.


text:
Q: Removing underline from specific anchor tag Why does the following anchor tag has text underlined?

.pagerLink {
  background-color: #E4F5F8;
  border: 1px solid #C0DEED;
  text-decoration: none;
}
test

A: Probably because another style block has better precedence than your pagerLink class. Try:
.pagerLink {
    background-color: #E4F5F8;
    border: 1px solid #C0DEED;
    text-decoration: none !important;
}

A: use text-decoration:none for a in your styles
Ex:

    test

You can use firebug(a firefox plugin) to findout which style is being used for the element now and whether its being overwritten by some other style definition
http://getfirebug.com/

A: I cant yet leave comments and I respect this is an old question but be extremely careful when using !important in your declarations:

text-decoration: none !important;

You'll probably get away with it in smaller projects but with any non-trivial project that involves collaboration from multiple sources this sort of thing can be incredibly annoying when it over-rides a property I need to set further down the line.  Not only do I have to change this to make my fix stick but I also have to check that changing it does not break anything else, which it probably will.
Better is to refactor your declaration or restructure your code so that you dont need to use !important and only fall back to !important when you cant.

A: To remove underline you need to follow following style code snippet.
.pagerLink{
  background-color: #E4F5F8;
  border:1px solid #C0DEED;
  text-decoration:none !important;
}


text:
Q: Find Increment # of X I have a number X can range between 1 to N
lets assume X = 5
I need to find out 3 set of numbers

1st Set of Numbers: 1,4
2nd Set of Numbers: 2,5
3rd Set of Numbers: 3

and now if X = 12 then
lets assume X = 5
I need to find out 10 set of numbers

1st Set of Numbers: 1,4,7,10
2nd Set of Numbers: 2,5,8
3rd Set of Numbers: 3,6,9

So the question is how can I find out those 3 sets of numbers when the X is unknown, what is the equation? or do I have to iterate the numbers?
I assume it has to do with division also rounding???

A:
what is the actual value of X ? And I'm seeing 3 set of numbers here, not 10 set. So please, before posting please check your question again.
From given 2 outputs, it seems(as your problem isn't clear) output will always consists of 3 sets. 1st will start from 1, second one from 2 and 3rd one from 3. Difference between two neighboring number will be 3 in a set. You just have continue until X is reached. If this is the problem, it is too easy. Am I getting wrong anything ?


text:
Q: Make sure that the wamp server is online before pull data from mysql database -Android Before to get data from mysql database I need to make sure that the wamp server is online, if not, the app tell the user to put it online before pull data, how can this achieve in android? as if it is offline android app stopped!
PHP code to conect to database is:
<?php

//receive datatbase Info. from android app
$json=$_SERVER['HTTP_JSON'];
var_dump($data);
$data=json_decode($json);
$dbname=$data->dbname;
$dbpass=$data->dbpass;
$link=mysql_connect("localhost","root",$dbpass);

if (!$link) {
    echo "error";
    die(mysql_error());
}

$db_selected=mysql_select_db($dbname,$link);

if (!$db_selected) {
    die ('error'. mysql_error());
}

mysql_query("set names 'utf8'");
mysql_query("set CHARACTER set 'utf8'",$link);
mb_internal_encoding("UTF-8");

?>

But in andorid app it does not receive "error" when there is no connection (I mean when wamp server is offline)?
In sum please, If there is any way to make sure that the wamp server is online before  pull data start from database? and if not give user msg.
with tired mood I tried but with no result, really any help will be appreciated!

A: One of the possible solution for you question is by creating an Http request for the wamp server address and that can be easily done in Android. The following code shows you how the http request is created for any URL you need.
Thread thread = new Thread(new Runnable(){
        @Override
        public void run() {
            try {
                try {
                    URL url = new URL("http://220.13.81.33");

                    HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
                    urlc.setConnectTimeout(1000 * 5); // mTimeout is in seconds
                    urlc.connect();

                    if (urlc.getResponseCode() == 301) {

                    }
                } catch (MalformedURLException e1) {
                    e1.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                catch (Exception e)
                {

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

    thread.start();

It is obvious that you just put the IP or URL that you want in the URL constructor, but you have to take care about two important notes:
1-To make a request, you need to do that by using threading or by creating async task or, if you don't want to use threading you can enforce the android to deal with such requests in the main process of the android by adding the following policy in the code. However, this kind of solution needs SDK version more than 9.
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

2-If you are working on emulator and you want to connect on the local host, you have to use this address http://10.0.2.2:8080  since it is the local host address for Android.
Once the connect function is issued, a respond code will be returned otherwise an exception will be arise. The interpretations of the respond codes can be found in this link
 http://en.wikipedia.org/wiki/List_of_HTTP_status_codes  , note please if the returned respond code was 301 that means the used will be redirected to the given URI and this an indication the Wamp sever is online. For the arise exceptions, most likely the Wamp server is offline. Thus, you need to do several testing for different scenario and see the outputs.
I hope that everything goes very well with you.

A: I answered that within another question, but it might be an answer to this one too. My solution, basically, is based on setting a Socket to your wamp server 80 port.
I use the following code on many of my projects:
Socket socket;

// Adjust it to your case, it might be a public IP too
final String host = "192.168.1.X";
final int port = 80;
final int timeout = 30000;   // 30 seconds of timeout

try {
  socket = new Socket();
  socket.connect(new InetSocketAddress(host, port), timeout);
}
catch (UnknownHostException uhe) {
  Log.e("WampSock", "I couldn't resolve the host you've provided!");
}
catch (SocketTimeoutException ste) {
  Log.e("WampSock", "After a reasonable amount of time, I'm not able to connect, your WAMP server is probably down!");
}
catch (IOException ioe) {
  Log.e("WampSock", "Hmmm... Sudden disconnection, probably you should retry once again!");
}

A: Would this not be a lot simpler?
<?php
    $link = @mysql_connect('127.0.0.1','a_userid','a_password');
    $err = mysql_errno();
    switch ($err) {
        case 2002 :
            echo 'Error Start MySQL Please';
            exit;
        case xxxx : // any other possible errors
             ...

    }
    // MySQL is there so proceed as normal


text:
Q: Mailcore2 iOS Test sample duplicating emails when loading more I am using MailCore2 email library in my iOS app. I am following "iOS Test" sample mail core project. When I click on "Load 10 more" option at the bottom of email table view, emails are getting duplicated in the table "iOS Test" sample project. I want to integrate this and not getting how to fix this, I tried to comment out this line [combinedMessages addObjectsFromArray:strongSelf.messages]; in loadLastNMessages function, but not helped.
 Could someone please advise me how to solve this duplicate email listing in this table view issue?
Screenshot where duplicating email date being displayed when loading more mails.

A: I have the same problem.
Step to reproduce:
1-Load email message successfully (account A).
2-Send an email from "Account B" to "Account A".
3-Load more messages.
If I change strongSelf.messages = nil before I execute this code "combinedMessages addObjectsFromArray:strongSelf.messages];". Not duplicate.
But It's not working if my account doesn't receive an new email.


text:
Q: Fetching information from a facebook WebCal in iOS5 I'm building my first app which should fetch some events from a Facebook CalDAV. But I can't seem to define the source with EventKit. Am I reading the documentation wrong and is it only possible to get information from the iPhones calendar?
The source I'm trying to reach is:
webcal://www.facebook.com/ical/u.php?uid=614013015&key=AQCJQo9Dh5NqgP1Z
Does it provide a problem that it is a webcal and not an official CalDAV standard?
Thanks in advance
-Villars

A: I've looked it through and as I see it, EventKit doesn't give the option of connecting to a calendar outside iOS' own.


text:
Q: Ajuda com menu pós login no JSF no JavaWeb Fala galera, beleza ? Estou fazendo um gerenciador de projetos em JavaWeb com Hibernate, TDD, MVC, JSF, Primefaces e mais que não lembro kk, Seguinte, quando eu efetuo o login no meu projeto eu faço o menu aparecer mas quando clico em alguma função, ele some. O teste de autenticação está funcionando ok mas é como se o usuário fechasse e perdesse o login.
Fazendo o Login, aparece:

Quando clico em qualquer função, ele some:

O Menu está feito assim no JSF:
<p:submenu label="Usuários" rendered="#{autenticacaoBean.usuarioLogado.funcao != null}">
        <p:menuitem value="Pesquisa e Listagem" outcome="/pages/usuarioPesquisa.xhtml" icon="ui-icon-search" />
        <p:menuitem value="Criar" outcome="/pages/usuarioCadastro.xhtml" icon="ui-icon-disk">
             <f:param name="usuAcao" value="criar" />
        </p:menuitem>
    </p:submenu>

A parte de login está assim:
<h:form>

    <h:panelGrid columns="2">

    <p:outputLabel value="Email"></p:outputLabel>
    <p:inputText size="30" value="#{autenticacaoBean.usuarioLogado.email}">
    <f:validateBean />
    </p:inputText>

    <p:outputLabel value="Senha"></p:outputLabel>
    <p:password size="30" value="#{autenticacaoBean.usuarioLogado.senha}">
    <f:validateBean />
    </p:password>

    </h:panelGrid>

    <h:panelGrid>

    <p:commandButton value="Entrar" update=":msgGlobal :formLogin:painelMenu"
    actionListener="#{autenticacaoBean.autenticar}"></p:commandButton>

    </h:panelGrid></h:form>

A Autenticação Bean tá assim:
public class AutenticacaoBean {

private Usuario usuarioLogado;

public Usuario getUsuarioLogado() {
    if(usuarioLogado == null){
        usuarioLogado = new Usuario();
    }
    return usuarioLogado;
}

public void setUsuarioLogado(Usuario usuarioLogado) {
    this.usuarioLogado = usuarioLogado;
}

public void autenticar(){
    try {
        UsuarioDAO usuariodao = new UsuarioDAO();
        usuarioLogado = usuariodao.autenticar(usuarioLogado.getEmail(), DigestUtils.md5Hex(usuarioLogado.getSenha()));

        if(usuarioLogado == null){
            FacesUtil.addMsgErro("Email ou Senha inválidos !");
        } else {
            FacesUtil.addMsgInfo("Usuário Autenticado com sucesso!");
        }

    } catch(RuntimeException ex) {

        FacesUtil.addMsgErro("Erro ao tentar autenticar no sistema.");
    }
}}

e no UsuarioDAO está assim:
public Usuario autenticar(String email, String senha){
    Session sessao = HibernateUtil.getSessionFactory().openSession();
    Usuario usuario = null;

    try {
        Query consulta = sessao.getNamedQuery("Usuario.autenticar");
        consulta.setString("email", email);
        consulta.setString("senha", senha);
        usuario = (Usuario) consulta.uniqueResult();
    } catch (RuntimeException ex) {
        throw ex;
    } finally {
        sessao.close();
    }
    return usuario;
}

A: AutenticacaoBean está com escopo de sessão? tente adicionar a anotação @SessionScoped em AutenticacaoBean.


text:
Q: Why doesn't Kotlin let me use writeText extension? I have a Kotlin class with a method, which creates some text and then I want to write it to a file:
import java.io.File
import java.util.*
import kotlin.io.*

class MyClass {
    fun run() {
        val result = html {
            head {
                title { +"Entry page" }
            }
            body {
                h1 {
                    +"Map"
                }
                +"Some HTML code"
            }
        }
        File("target/wdef/index.html").writeText(result)
    }
}

I get an error - the writeText(result) is highlighted red and I get the error message Error:(26, 40) Kotlin: Unresolved reference: writeText.
How can I fix it?

A: A problem might be that you pass a wrong type to writeText. It requires String, but you pass an html building object HTML. Try to convert it with toString:
File("target/wdef/index.html").writeText(result.toString())


text:
Q: What does vertical bar mean in X(k|k-1)? I understand that "|" can mean many things.
Here, only 2 appear relevant: "Such that" or "Divided by" however for the equation I am trying to understand neither seems right.
What does it mean?
$\chi_i(k | k - 1) = f(\chi^a_i (k | k - 1), u(k - 1), t_{k - 1}).$


text:
Q: Store paused/stopped chronometer time on button click , then compare the stored value with another value and show toast message I've checked a lot of similar topics and read a lot of examples, but could not find anything that would help me.
I'm making an app using Chronometer and displaying toast messages.
I want to store paused/stopped chronometer time on button click (button2), then compare the stored value with another value time (15 seconds, 30 seconds and etc.) and if it is bellow 15 sec show message "Good" , if it between 16 sec and 29 sec to show toast message "Super" and etc.
At the moment my code have start, pause/stop , reset buttons and it is showing toast message at 15 sec, 30 sec and etc.
This is the my MainActivity.java code:
package com.example.bobby.chronometer;

import android.os.Bundle;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Chronometer;
import android.widget.Toast;

import static com.example.bobby.chronometer.R.id;
import static com.example.bobby.chronometer.R.layout;

public class MainActivity extends AppCompatActivity {
private Chronometer chronometer;
private long pauseOffset;
private boolean running;
private View v;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(layout.activity_main);
    chronometer = findViewById(id.chronometer);
    chronometer.setFormat("(%m,%s)");
    chronometer.setBase(SystemClock.elapsedRealtime());
    chronometer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
        @Override
        public void onChronometerTick(Chronometer chronometer) {
            if (((SystemClock.elapsedRealtime() - chronometer.getBase()) / 1000) * 1000 == 15000L) {

                Toast.makeText(MainActivity.this, "Good!", Toast.LENGTH_LONG).show();
            }
            if (((SystemClock.elapsedRealtime() - chronometer.getBase()) / 1000) * 1000 == 30000L) {

                Toast.makeText(MainActivity.this, "Super!", Toast.LENGTH_LONG).show();
            }
            if (((SystemClock.elapsedRealtime() - chronometer.getBase()) / 1000) * 1000 == 45000L) {

                Toast.makeText(MainActivity.this, "Extra!", Toast.LENGTH_LONG).show();
            }
            if (((SystemClock.elapsedRealtime() - chronometer.getBase()) / 1000) * 1000 == 60000L) {

                Toast.makeText(MainActivity.this, "Great!", Toast.LENGTH_LONG).show();
            }
            if (((SystemClock.elapsedRealtime() - chronometer.getBase()) / 1000) * 1000 == 90000L) {

                Toast.makeText(MainActivity.this, "Amazing!", Toast.LENGTH_LONG).show();
            }
            if (((SystemClock.elapsedRealtime() - chronometer.getBase()) / 1000) * 1000 == 120000L) {

                Toast.makeText(MainActivity.this, "Awsome!", Toast.LENGTH_LONG).show();
            }
        }
    });
}
public void startChronometer(View v) {
    if (!running) {
        chronometer.setBase(SystemClock.elapsedRealtime() - pauseOffset);
        chronometer.start();
        running = true;
    }
}
public void pauseChronometer(View v) {
    if (running) {
        chronometer.stop();
          pauseOffset = SystemClock.elapsedRealtime() - chronometer.getBase();
          running = false;

    }
}
public void resetChronometer(View v) {
    chronometer.setBase(SystemClock.elapsedRealtime());
    pauseOffset = 0;
}

}

This is my activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#B2EBF2"
android:gravity="center"
tools:context="com.example.bobby.chronometer.MainActivity"
android:keepScreenOn="true">/

<Button
    android:id="@+id/button"
    android:layout_width="142dp"
    android:layout_height="70dp"
    android:layout_marginBottom="62dp"
    android:layout_marginTop="200dp"
    android:background="@drawable/button1"
    android:onClick="startChronometer"
    android:text="@string/start"
    android:textColor="#FFFFFF"
    android:textSize="24sp"
    app:layout_constraintBottom_toTopOf="@+id/button2"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<Button
    android:id="@+id/button2"
    android:layout_width="142dp"
    android:layout_height="72dp"
    android:layout_marginTop="265dp"
    android:background="@drawable/button2"
    android:onClick="pauseChronometer"
    android:text="@string/stop"
    android:textColor="#FFFFFF"
    android:textSize="24sp"
    app:layout_constraintBottom_toTopOf="@+id/button3"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<Button
    android:id="@+id/button3"
    android:layout_width="142dp"
    android:layout_height="72dp"
    android:layout_marginTop="290dp"
    android:background="@drawable/button3"
    android:onClick="resetChronometer"
    android:text="@string/reset"
    android:textColor="#FFFFFF"
    android:textSize="20sp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.501"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.387" />

<Chronometer
    android:id="@+id/chronometer"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    android:background="#00E676"
    android:backgroundTint="#CCFF90"
    android:textSize="34sp"
    android:visibility="invisible"
    app:layout_constraintBottom_toTopOf="@+id/button"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/textAuthorSign"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:lineSpacingExtra="20sp"
    android:shadowColor="#030302"
    android:shadowDx="0"
    android:shadowDy="0"
    android:shadowRadius="3"
    android:text="@string/Press"
    android:textAlignment="center"
    android:textAllCaps="false"
    android:textColor="#7e1fdc"
    android:textIsSelectable="false"
    android:textSize="20sp"
    android:textStyle="bold|italic"
    android:typeface="normal"
    android:visibility="visible"
    app:layout_constraintBottom_toTopOf="@+id/button"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.638" />

<TextView
    android:id="@+id/myTextView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:layout_editor_absoluteX="-78dp"
    tools:layout_editor_absoluteY="533dp" />

</android.support.constraint.ConstraintLayout>


text:
Q: Encrypting SD card I have a small capacity SSD drive on my laptop, to compensate I got a 32GB SD card in my laptop which goes in /media/usr/... and I want to store files and stuff on it. The problem would be if someone take out the SD card from laptop they can access the content. So how can I encrypt the SD card in a way that it only works on my laptop and nothing else?

A: You create an LUKS container on a partition or your whole SD card.
I give you the GUI version:
Open up Disks, choose your SD card, click on the wheel and choose Format. For Type, choose Crypted compatible with linux, enter a passphrase and choose Format.
You will be asked for this passphrase when you mount your SD card. Don't forget it.
Caution: You will loose all the data on the SD card.

A: The accepted answer did not worked for me:

*

*

*

*

*

*

*
Source: https://www.howtoforge.com/tutorial/encrypt-usb-drive-on-ubuntu/


text:
Q: String from Database set as public string
Ok from the answer from the previous question the reasoning still applies here but this time A different issue. There is a login system (Loginvb.vb) that I got for the launcher I was creating and was wondering 2 things:

*

*Is there a better way to do the Login check with the database (as in
more secure) (the login style will have a web based registration
setting via PHP script)?

*Is there a way to take a certain column (labled as access) in the database and put it
as a public string so I can check if it will equal 1 2 or 3 in a
different form labeled as Main.vb

Here is the current login check:
Public Sub login_Click(sender As Object, e As EventArgs) Handles login.Click
    If txtuserName.Text = "" Or txtpassWord.Text = "" Then
        MsgBox("You cannot progress until you login....(moron =p)")
    Else
        'Connects To the Database
        Dim connect As MySqlConnection
        connect = New MySqlConnection()
        connect.ConnectionString = "server=127.0.0.1;user id=sc;Password=derp;database=sclaunch" 'not the actual login ;)
        Try
            connect.Open()
        Catch myerror As MySqlException
            MsgBox("Error Connecting to Database. Please Try again !")
        End Try
        'SQL Query To Get The Details
        Dim myAdapter As New MySqlDataAdapter
        Dim sqlquerry = "Select * From login where username = '" + txtuserName.Text + "' And password= '" + txtpassWord.Text + "'"
        Dim myCommand As New MySqlCommand()
        'My fail attempt at what I am trying to do :(
        Dim sql22 As MySqlConnection
        sql22 = New MySqlConnection()
        sql22.ConnectionString = "Select * From login where access ="
        'End of fail attempt
        myCommand.Connection = connect
        myCommand.CommandText = sqlquerry
        'Starting The Query
        myAdapter.SelectCommand = myCommand
        Dim mydata As MySqlDataReader
        mydata = myCommand.ExecuteReader
        'To check the Username and password and to validate the login
        If mydata.HasRows = 0 Then
            MsgBox("Invalid Login")
        Else
            'fail testing xD
            Label3.Text = sql22
            MsgBox("You are now Loged In!")

        End If
    End If
End Sub

Still basically learning more and more as I am coding all this got to love trial and error and the moments where you get stuck =/ (Sorry to the admins or whatever for fixing tag issues still new to the site xD)

A: Assuming that the same table login that contains the credentials contains also the access column that you want to retrieve, then I have changed a lot of your code
    Dim sqlquerry = "Select * From login where username = @name AND password=@pwd"
    Dim myCommand As New MySqlCommand(sqlquery, connect)
    myCommand.Parameters.AddWithValue("@name", txtuserName.Text)
    myCommand.Parameters.AddWithValue("@pwd", txtpassWord.Text)
    Dim mydata = myCommand.ExecuteReader

    If mydata.HasRows = False Then
        MsgBox("Invalid Login")
    Else
        ' the same record that contains the credentials contains the access field'
        mydata.Read()
        Label3.Text = mydata("access").ToString()
        MsgBox("You are now Loged In!")
    End If

What I have changed:

*

*Removed the string concatenation and added the appropriate parameters

*Removed myAdapter and every references to it (not needed, you don't
fill DataTable/DataSet)

*Removed sql22 and every references to it. It's a Connection and you
try to use like a Command

*Fixed the check on HasRows (Returns a boolean not an integer. Are you
using Option Strict Off?)


text:
Q: Downcast protocol conformance in extension Let's say I have two non-generic protocols (1)
protocol StringValue {
    var asString: String {get}
}

protocol StringProvider {
    var value: StringValue {get}
}

I want to have a generic version of the second one (2)
protocol TypedStringProvider: StringProvider { // inherits from StringProvider
    associatedtype TypedStringValue: StringValue
    var typedValue: TypedStringValue { get }
}

And extension with default implementation of non-generic version to have a code free conformance to StringProvider (doesn't work, pls read below)  (3)
extension TypedStringProvider {
    var value: TypedStringValue { return typedValue }
}

Now I want several classes to conform both generic TypedStringProvider and non-generic StringProvider protocols (4)
extension UIView: TypedStringProvider {
    typealias TypedStringValue = String
    var typedValue: String { return "Some String" }
}

extension Double: TypedStringProvider {
    typealias TypedStringValue = String
    var typedValue: String { return String(self) }
}

extension String: StringValue {
    var asString: String { return self }
}

And get compiler error: Type 'UIView' does not conform to protocol 'StringProvider'.
Seemingly extension (3) doesn't work like I want because TypedStringValue is not a StringValue in despite of this constraint associatedtype TypedStringValue: StringValue from (2)
The question is how to conform to non-generic StringProvider while keeping value typed
Example:
0.5.value.lowercased()

Of course StringValue doesn't have lowercased method from String so it won't compile.
What I have tried:
First is to add untyped property to extension (3)
extension TypedStringProvider {
    var value: TypedStringValue { return typedValue }
    var value: StringValue { return typedValue }
}

Doesn't work because of Invalid redeclaration of 'value' error
Second is to extend my classes and add untyped property there (5)
extension UIView {
    var value: StringValue { return typedValue }
}

extension Double {
    var value: StringValue { return typedValue }
}

It works without compiler errors but

*

*No autocompletion for lowercased in our example.

*With extensions (5) I need to write a lot of code for every class conforming StringProvider and every property this protocol has
Any ideas?

A: value is defined as type StringValue, so this is the type you should specify in your extension of TypedStringProvider in order to complete the protocol conformance:
extension TypedStringProvider {
    var value: StringValue {
        return typedValue
    }
}

A: Found solution
extension StringProvider where Self: TypedStringProvider {
    var value: StringValue { return typedValue }
}

With this extension there's no need to write similar extensions to every class and autocompletion works too.
Full code:
protocol StringValue {
    var asString: String {get}
}

protocol StringProvider {
    var value: StringValue {get}
}

protocol TypedStringProvider: StringProvider {
    associatedtype TypedStringValue: StringValue
    var typedValue: TypedStringValue { get }
}

extension StringProvider where Self: TypedStringProvider {
    var value: StringValue { return typedValue }
}

extension TypedStringProvider {
    var value: TypedStringValue { return typedValue }
}

extension UIView: TypedStringProvider {
    typealias TypedStringValue = String
    var typedValue: String { return "some string" }
}

extension Double: TypedStringProvider {
    typealias TypedStringValue = String
    var typedValue: String { return String(self) }
}

extension String: StringValue {
    var asString: String { return self }
}

let doubleValue = 0.5.value.lowercased()

A: Problem
On StringProvider you are defining value to a StringValue:
protocol StringProvider {
    var value: StringValue { get }
}

but here you are defining the type to TypedStringValue which is not the same as StringValue. (underlying value can be TypedStringValue, however it needs to be typecasted from StringValue to TypedStringValue when using it)
extension TypedStringProvider {
    var value: TypedStringValue { return typedValue }
}

Solution
There are two solutions that I can come up for this scenario right now:
1. Generic Approach
If you want to make value generic and change the type based on TypedStringProvider you can:
protocol StringProvider {
    associatedtype StringProviderValue: StringValue
    var value: StringProviderValue { get }
}

Conform to the protocol by defining StringProviderValue to TypedStringValue
extension TypedStringProvider {
    var value: TypedStringValue { return typedValue }
}

2. StringValue approach
Keep the StringProvider as it is:
protocol StringProvider {
    var value: StringValue { get }
}

Conform to the protocol by using the correct StringValue type, and inside it return typedValue: TypedStringValue which can be downcasted to StringValue
extension TypedStringProvider {
    var value: StringValue { return typedValue }
}

Output
Both solutions give the same output:


text:
Q: Kubernetes Service - which type to use NodePort or LoadBalancer? I've read a lot about Services (NodePort and LB) https://kubernetes.io/docs/concepts/services-networking/service/ but I still have dilemma what to use.
I have AKS cluster in Azure. In the same Virtual Network I have VM outside the cluster that should target specific app, container pod on port 9000.
App in container pod is being run on Port 9000.
I have two options:

*

*expose that service as NodePort on some port in range from 30000-32767 let's say 30001 but in that case I must change all my outside VMs and apps that they should not target and connect to port 9000 which is regular port for this application but this new Port 30001 which for this app really sounds strange

*expose that service in Azure as Load Balancer (I can do that because it is Cloud Platform but I do not like that in that case it will expose my service via Public Address. This is very bad, I do not want for this to be accessible from the internet on public IP address.

I am really confused what should I choose.
I will appreciate advices.
Thank you

A: There is a good option to create Internal Load Balancer which is accessible only within Virtual Network.


text:
Q: If a matrix is positive semi-definite is the associated jacobian also positive semi-definite? I'm studying the consistency of the Extended Kalman Filter and I'm trying to work through a proof that the covariance matrix is monotonically decreasing.
Theorem 1 from this paper, shows the proof for the Kalman Filter, so I'm working along the same lines.
The proof for the KF uses the fact that the process and observation matrices are positive semi-definite.  For the EKF, the proof relies on the jacobians of the process and observation functions.
My question is: are these jacobian matrices also positive semi-definite, and why?
I believe this is true, but I'm not sure how to approach it.  I know a matrix $A$ is positive semi-definite if its eigenvalues are all greater than 0.  I don't know where to start to work out is if this property holds for the jacobian as well.


text:
Q: Documenting moderator impeachment actions Un-modding diamond users by Community Managers should be documented somewhere. At the very least, date, and name of the moderator should be recorded, plus links to relevant meta posts.
Rationale: accountability. Some drama is unavoidable, Agnew was impeached (but not Nixon), after all.
Not a duplicate of this question - I'm asking for a centralized roster for all SE sites, and this information can be gathered (albeit more slowly) independently.
Background reading

A: It is documented internally. We recently went over the list and the vast majority of diamonds are removed at the request of the moderator or because of inactivity. We encourage those moderators to post something on meta if they want, but there's no reason for the community to pry into the ex-moderators' personal lives. It's a volunteer position and people have lives outside the site that often interfere with their ability to moderate.
A very small number of moderators have been removed involuntarily. The most common reason was violating the moderator agreement, but you can find the details of the other situations on the relevant per-site meta.
We do retain the results of all moderator elections. (Stack Overflow is the only exception. Election #1 was the first to use the current election system, not the first election.) We also track pro tempore moderators on meta unless we forget. So it is usually possible to piece together a history of site moderation from public information. But I can't see why that would be needed to participate on the site day-to-day.

A: I don't think this is useful. In cases with significant public drama there is a record on meta anyway. And in all other cases there isn't much benefit to drawing more attention to the demodding.
This should be handled similar to user suspensions, they're intentionally not logged forever in a public place. Drawing attention to them is usually avoided, if possible. Similar to supensions, such a demodding would also involve a lot of private data in most cases which makes it much harder for anyone on the outside to judge what happened. So any public record would likely be incomplete anyway.


text:
Q: Reset Auto_Increment on MySql via MSSQL? I'll even settle for Truncate I have a MSSQL Server 2008 R2 system that updates various tables on various systems during a nightly process. I have a MySQL linked server that has an Auto_Increment on one of it's tables. This tables contents are deleted and replaced each night. This of course does not reset the increment. I have tried:
 ALTER TABLE REMOTEMYSQL...[TableWithAI] AUTO_INCREMENT = 1

And I get:
 Incorrect syntax near 'AUTO_INCREMENT'

I can successfully:
 delete from REMOTEMYSQL...[TableWithAI]

But obviously that doesn't reset the increment on the MySQL side
I tried:
 Truncate TABLE REMOTEMYSQL...[TableWithAI]

and I get:
 Cannot find the object "TableWithAI" because it does not exist or you do not have permissions.

But the MySql user that is used in the link has full permissions. How can I ether delete the contents and zero the increment, or zero the increment by itself?

A: Assuming you have your MySQL already configured as a linked server, you can fire off non-query statements to linked servers with EXEC:
EXEC('ALTER TABLE TableWithAI AUTO_INCREMENT = 1') AT LinkedMySQLServerName;

I believe the query should be in MySQL syntax, but I'm not in a position to test from where I'm at.


text:
Q: Implicit assumptions in proofs of statements about limits I was recently writing out a proof that a certain real valued function is continuous, and something bothered me along the way.
Suppose we have a function $f: D \subset \mathbb{R} \to \mathbb{R}$, and we want to prove that $$\lim_{x\to a} f(x) = L.$$
In order to do so we show that for all positive real $\epsilon$, there exists a positive real $\delta$ such that for all $x \in D$ such that $0< |x-a| < \delta$, we have $|f(x) - f(a)| < \epsilon$.
Suppose we are confident that  we have found such a $\require{enclose} \enclose{horizontalstrike}{\delta}$ for which the above holds for any $\require{enclose} \enclose{horizontalstrike}{\epsilon > 0}$  given any $\epsilon >0$, we can find a $\delta$ such that the above holds and want to prove the statement using it.
We let $\epsilon >0$, and define our $\delta$.
Then, we let $x \in D$ such that $|x-a|<\delta$. But hold on, how do we know that such an $x$ exists? Have we implicitly assumed that such an $x$ exists, and do not consider the case where one doesn't exist, since the statement "for all $x \in D$ such that $|x-a|<\delta$, we have $|f(x) - f(a)| < \epsilon$" would be vacuously true?
I'm confident that it can be proved that such an $x$ would exist (although I'm not sure  exactly how), but I am pretty sure that it is not necessary to include such proofs when proving statements about limits.
My main question is: is it okay to assume the existence of a real number in the domain of $f$ such that $|x-a| < \delta$, and if so, why?

A: Generally speaking, the definition of the functional limit at a point $x=a$ necessitates that $f(x)$ has the definition over some one deleted neighborhood of $x=a$,which is a premise. Of course, in some more advanced calculus courses, $x=a$ may be the accumulating point.


text:
Q: Add CSS class to button disabled by Vue I have the following button that gets disabled if the user is in the first page:
<button :disabled="page==1" v-on:click="page=1;run()" class="page-link" :class="{'disabled' : disabled}">First</button>

However i would like to add the class .disabled if said button is disabled by Vue. Is it possible to do this through Vue?

A: You can put the same condition directly to the class directive:
 :class="{'disabled' : page === 1}"

A: Try changing disabled to false in the onclick, something like this: v-on:click="page=1;run();!disabled" or v-on:click="page=1;run();disabled=false".


text:
Q: hitting time of one of two barriers Let's consider a one-dimensional Random Walk. At each time the walker moves of one step to the right with probability $p$ and to the left with probability $q$, with $p+q=1$. The walk is not symmetric, then $p \neq q$
How can I find the explicit formula of the probability to hit for the first time one of the two walls located in $x=n$ and $x=-n$ at time $t$, given that the walk started from $x=0$ at time $t=0$?

A: In order for the walker to reach position $x$ at time $t$. A necessary condition is $x \equiv t \pmod 2$. Assume this is true, the walker have make $s = \frac{t+x}{2}$ steps forward and $t - s = \frac{t-x}{2}$ steps backward.
In the absence of walls, the probablity for the walker to be at position $x$ is given by
$$P_{free}(x,t) = \operatorname{Prob}\left[\,X(t) = x\,\right]
=\binom{t}{\frac{t+x}{2}} p^{\frac{t+x}{2}} q^{\frac{t-x}{2}}
$$
In the presence of walls, the probability for the walker at position $x$ and never hit the walls before will be modified to:
$$\begin{align}
P(x,t)  &= \operatorname{Prob}\left[\,X(t) = x : -n < X(t') < n,\,\forall t' < t\,\right] \\&=\sum_{r = \lceil\frac{x-t}{2n}\rceil}^{\lfloor\frac{x+t}{2n}\rfloor} (-1)^{r} \binom{t}{\frac{t+x-2rn}{2}} p^{\frac{t+x}{2}} q^{\frac{t-x}{2}}
\end{align}$$
The formula can be derived using reflection principle. It is equivalent to start the random
walk at time $t = 0$ with $(-1)^r$ phantom walker at position $\pm 2rn$ for each $r \in \mathbb{N}$. The range of summation over $r$ in above formula is limited to those which will actually contribute to $P(x,t)$ at time $t$.
For the walker to hit the wall $\pm n$ at time $t$, we again require $t \equiv n \pmod 2$. Furthermore, the walker must be at position $\pm (n-1)$ at time $t - 1$. In next move,

*

*(case $X(t-1) = n - 1$) the walker has a probability $p$ to turn right and hit the right wall.

*(case $X(t-1) = 1 - n$) the walker has a probability $q$ to turn left and hit the left wall.

This implies the probability for first hit (assume $t \equiv n \pmod 2$) is given by:
$$\begin{align}
P_{hit}(t) &= p P(n-1,t-1) + q P(-n+1,t-1)\\
&= \sum_{r = \lceil\frac{n-t}{2n}\rceil}^{\lfloor\frac{n+t-2}{2n}\rfloor} (-1)^{r} \binom{t-1}{\frac{n+t-2rn}{2} - 1} \left( p^{\frac{t+n}{2}} q^{\frac{t-n}{2}} +  q^{\frac{t+n}{2}} p^{\frac{t-n}{2}} \right)
\end{align}$$
For $t = n + 2k$, we can simplify this to:
$$P_{hit}(n+2k) = \sum_{-\lfloor\frac{k}{n}\rfloor}^{\lceil\frac{k}{n}\rceil}(-1)^r\binom{n+2k-1}{nr+k}(p^n + q^n) (pq)^k$$

A: The idea is to compute $u(s,x)=\mathbb E_x(s^T)$ for every integer  $|x|\leqslant n$ and complex number $|s|\leqslant1$, where $T$ is the first hitting time of $\pm n$. Then $u(s,0)$ is the generating function of the sequence of general term $\mathbb P_0(T=k)$, that is, $u(s,0)=\sum\limits_k\mathbb P_0(T=k)s^k$.
Each family $(u(s,x))_{|x|\leqslant n}$ solves a recursion based on the Markov property of the random walk after one step. More precisely, $u(s,x)=s(pu(s,x+1)+qu(s,x-1))$ for every $|x|\leqslant n-1$. For each fixed $s$ this is a second order linear recursion hence $u(s,x)=av^x+bw^x$ for every $|x|\leqslant n$, where $v$ and $w$ solve the characteristic equation $\xi=s(p\xi^2+q)$. Using the boundary conditions $u(s,\pm n)=1$, one gets
$$
a=\frac{w^{-n}-w^n}{v^nw^{-n}-v^{-n}w^n},
\quad
b_n=\frac{v^{n}-v^{-n}}{v^nw^{-n}-v^{-n}w^n}.
$$
Thus, $u(s,0)=a+b$, that is, after some simplifications,
$$
\sum\limits_k\mathbb P_0(T=k)s^k=\frac{1+v^nw^n}{v^n+w^n}=\frac{1+(q/p)^n}{v^n+w^n},\quad v,w=\frac{1\pm\sqrt{1-4pqs^2}}{2ps}.
$$
Thus,
$$
\sum\limits_k\mathbb P_0(T=k)s^k=s^n\frac{p^n+q^n}{x_n(4pqs^2)},
$$
with
$$
x_n(t)=\frac1{2^n}\left(\left(1+\sqrt{1-t}\right)^n+\left(1-\sqrt{1-t}\right)^n\right).
$$
Note that $x_n$ is a polynomial with degree $\lfloor n/2\rfloor$ and constant term $1$, hence expanding $1/x_n(t)$ as a series  yields every coefficient $\mathbb P_0(T=n+2k)$ for $k\geqslant0$ (the others being zero). More explicitly,
$$
x_n(t)=\frac1{2^{n-1}}\sum_{i\geqslant0}{n\choose 2i}(1-t)^i=\sum_{j\geqslant0}(-1)^j\left(\sum_{i\geqslant j}\frac1{2^{n-1}}{n\choose 2i}{i\choose j}\right)t^j=1-z_n(t),
$$
hence
$$
\mathbb P_0(T=n+2k)=(p^n+q^n)(4pq)^k\times\text{the coefficient of $t^k$ in}\sum_{\ell=0}^kz_n(t)^\ell.
$$


text:
Q: Importing quoted data into SQL, losing data I have 3 large txt files with tab delimited data that is enclosed in quotes. Here is an example line from one of the files:
"deleted for privacy"   185 "12/31/2005"    "01/16/2009"    "deleted for privacy"   false   1   "Accounting Issues" "deleted for privacy"   0   0   0                           1               0               0   "deleted for privacy"

I've removed some potentially sensitive information, but you get the idea. It seems to be tab delimited, most values are enclosed in quotes, but not all of them.
The problem is the two date columns are showing up blank for some rows after I import the file into SQL. So, for instance, one of the original files has 5 million rows like the one above with NO blanks in those date columns. Once I bring it into SQL, about a million of those 5 million rows have no value in those date columns. I'm not getting any errors during the import process.
One of the 3 large files is small enough that I'm able to open it in notepad and remove the quotes from all of the values before importing into SQL. This seems to fix the problem. No date values seem to be lost if I remove the quotes before importing into SQL. The problem is 2 of the 3 files are too large to open in notepad to remove the quotes PRIOR to importing.

A: You don't mention the tool that you're using to do the bulk import, I'll assume bcp or BULK INSERT statement.
I assume that the datatypes of the corresponding columns are of date-time type. In that case SQL server is probably mis-interpreting the date format as dd/mm/yyyy format (European), rather than mm/dd/yyyy (American) style. Values that cannot be converted in the given style are set to NULL.
I usually solve data import issues such as this by importing into a scratch table, where all columns are varchar(max), and then running a post processing stored procedure to transfer imported rows from the scratch table into the final table, defining explicit conversions as required. An alternative to this would be to import using a custom dtsx package, and define the conversions required as a Data Conversion Transformation task.


text:
Q: How to make an exe command run from inside Python? I have a command like that spins off some calculations and stores some output in a folder. So, I have this command that works on the bash command (in Ubuntu).
/home/usr2/AXE/prog1.exe -k 1 -m /home/usr2/AXE/config.txt

However, I would like to "call" this from inside a python program.
The final idea is to generate lots of serial processes of this nature inside python.
/home/usr2/AXE/prog1.exe -k 1 -m /home/usr2/AXE/config.txt
/home/usr2/AXE/prog1.exe -k 2 -m /home/usr2/AXE/config.txt
/home/usr2/AXE/prog1.exe -k 3 -m /home/usr2/AXE/config.txt
...
...
/home/usr2/AXE/prog1.exe -k 2000 -m /home/usr2/AXE/config.txt

SO FAR
import os
os.system('"/home/usr2/AXE/prog1.exe -k 1 -m /home/usr2/AXE/config.txt"')

This gives me command line output of Out[11]: 32512, but the output file is not produced in the requisite folder.
What am I doing wrong?
P.S. No idea about Bash programming. But would be interested in Bash solutions as well.

A: The immediate problem seems to be an excess of quotation marks.  os.system takes a string containing the command you want to execute.  So to execute the shell command echo hello, you would call os.system('echo hello') from Python.  Calling os.system('"echo hello"') tries to execute the shell command "echo hello"; in other words, it looks for a single executable file in your PATH named echo hello, which presumably doesn't exist and certainly isn't what you want.  So get rid of one set of quotes.  Either one is fine since Python treats single and double quotes the same.
You can also try replacing your use of os.system with subprocess.run, also from the standard library.  Instead of a single string containing the command, you pass it a sequence of strings, each of which is one token from the shell command you'd like to run.  So in our example you could do subprocess.run(('echo', 'hello')).  The os.system function is more or less deprecated in favor of subprocess.run.


text:
Q: Android - SAX and Pull Parser - Performance I am building an android app which gets the xml from a remote url and gets saved in an SD Card location.
Xml is relatively big (3 MB - approximately about 30000 elements). I need to parse whole document and build a java model out of it..
I used out-of-the box android's SAX and Pull parser implementations, but the performance is not satisfactory.. I tested with different types of mobile devices armv7/998MHZ, 500MHZ, 260MHZ, but the performance is not linearly improving when testing with more powerful devices..
SAX:
xmlIn.parse(new InputSource(new FileInputStream(myfile)));
Pull:
 parser.setInput(new FileInputStream(myfile), null);
In my case SAX is doing little bit better than Pull. Are there any ways to improve any of these parsers? Like NIO, non-blocking/buffering techniques to improve performance?
Since StAX is not supported in Android, I can't use FasterXML Aalto.
Any inputs are appreciated.


text:
Q: Bootstrap Bigger Icon in the screenshot below, i have tried to add 2 button icons in 2 different columns which are also children of a row.
I want that buttons to fit as much as big they can in the column as you see.

Here is my code for that specific row;

                                    VIP ($7000):
                                    <input type="number" class="form-control" id="departure" placeholder="0" value="" required>

I have tried some things but couldn't get the proper design

A: The font-size CSS options will work best.
So you could do.
i{
font-size: 50px;
}

The above will affect all icon tags and probably all HTML5 italic tags too.
Or you can add a Class to your icons. The CSS would be....
i .big-icon{
font-size: 50px;
}

With the HTML being....

Here is a link to the GetBootstrap Docs....
https://icons.getbootstrap.com/#styling


text:
Q: graph with customised grid and tick Latex users,
I want to create a set of axes filled with fine grid suitable for sketching graphs on, like the graph shown below. I also want to put labels on both x and y axes.

But with the code I have the x ticks and y ticks misalign with the grid.
\documentclass[]{article}
\usepackage[margin=0.5in]{geometry}
\usepackage{pgfplots}
\usepackage{mathtools}
\usepackage{cancel}
\usepackage{pgfplots}
\usepackage{amsmath}
\newtheorem{theorem}{THEOREM}
\newtheorem{proof}{PROOF}
\usepackage{tikz}
\usepackage{amssymb}
\usetikzlibrary{patterns}
\usepackage{fancyheadings}
\usepackage{bigints}
\usepackage{color}
\usepackage{tcolorbox}
\usepackage{booktabs,array}
\usepackage{hyperref}
\usepgfplotslibrary{fillbetween}
\begin{document}
\setlength{\parindent}{0cm}
%\pagecolor{blue!13}
\fancyhf{}
\fancyhead[C]{\thepage}
\voffset = 0.1cm
\pagestyle{fancy}
\definecolor{web}{RGB}{56, 102, 166}
\setlength{\parindent}{0mm}
\setcounter{page}{1}
\begin{tikzpicture}
\begin{axis}[
axis lines=middle,
%grid=major,
xmin=-0.3,
xmax=10.8,
ymin=-0.6,
ymax=10.8,
height=9cm,
width=12cm,
%xtick={0,1.2,...,9.6,12},
%xticklabel={0,1,...,8,10},
%ytick={0,1,...,9,10},
%tick style = {line width = 0.1pt},
%tick style={very thick},
%tick style={very thick},
%enlargelimits=false,
%grid=both,
%axis line style={shorten >=-10pt, shorten <=-10pt},
%xlabel style={
%   anchor=west,
%   at={(ticklabel* cs:1.0)},
%   xshift=10pt
%},
%xlabel=\text{NZD(\$)},
xtick={0,1.265,2.53,3.795,5.06,6.325,7.59,8.855,10.12,11.385,12.65},
xticklabels={$0$,$1$,$2$,$3$,$4$,$5$,$6$,$7$,$8$,$9$,$10$}
%ylabel style={
%   anchor=south,
%   at={(ticklabel* cs:1.0)},
%   yshift=10pt
%},
%ylabel=\text{AUD}(\$),
]
\draw[step=0.245cm,gray!50,very thin,opacity=0.9] (axis cs: 0,0) grid (axis cs: 10,10);
%\addplot[ultra thick,samples=100,domain=0:1] {0};
\node at (axis cs: -0.15, -0.3) {$O$};
\end{axis}
\end{tikzpicture}
\end{document}

this is the resulting graph from the code:

Could you please suggest any modification so I get the desired output?
Many thanks


text:
Q: Image resized when using NSUrl I'm working on an OSX app and I'm trying to get an image from a NSUrl. It works well, but with some images (not every image), the size is not good.
For example, I'm trying to get a 1600 * 1200 image from the NSUrl, but when I NSlog the value I get the result is 384 * 288, so the quality is decreased.
But this bug is not on every images.
I have tried this with PNG and JPG, the result is the same, some are resized, some are not.
I dont want the image to be resized because the quality is my main concern.
Here's my code :
 - (IBAction)loadImageAction:(id)sender {
    NSArray* fileTypes = [[NSArray alloc] initWithObjects:@"jpg",@"png", nil];
    NSOpenPanel *panel = [NSOpenPanel openPanel];
    [panel setCanChooseFiles:YES];
    [panel setCanChooseDirectories:NO];
    [panel setAllowsMultipleSelection:NO];
    [panel setAllowedFileTypes:fileTypes];

    NSInteger clicked = [panel runModal];
    if (clicked == NSFileHandlingPanelOKButton) {
        for (NSURL *url in [panel URLs]) {
            NSImage *img = [[NSImage alloc] initWithContentsOfURL:url];
            NSLog(@"IMAGE FROM URL : image.width = %f, image.height = %f", img.size.width, img.size.height);
            if (img != nil) {
                [_imageView setImage:img]; // just a NSImageView to display the image
            }
        }
    }
}


text:
Q: How do I set values in existing Forms and return to original form from a new form? So I have a form InvCert
I open an instance of form GetSomeInfo
within GetSomeInfo I have textboxes etc and would like those .Text values to become values in the original form InvCert. I assumed Form.stringname = would allow me to do this, but my values are not crossing over to the original form. I have no error messages somehow at the same time.
'frmInvCert.certType = comboInvLvl.Text;
frmInvCert.thisYear = dateTimeCurrent.Text;
frmInvCert.myFileName = txtInvestor.Text;
frmInvCert.getAdress = txtAddress.Text;
string certType = comboInvLvl.Text;
new frmInvCert().Show();
this.Close();`

Then, these values were made to be used in methods. But the program does not wait until we return to the original form to fill in these values. It just creates blanks.
this.Hide();
                new frmGetSomeInfo().Show();
                //creates even if values not filled!
                //May need to retun to original instead somehow or find out how to put these mthods into the new form
                //initialize checkboxes after with paths connected
                //initialize tab pages with paths connected
                if(thisYear != null && certType != null && myFileName != null)
                {
                    CreateCertificate();
                }
                CreateCertificate();

A: in this line:
new frmInvCert().Show();

you are oppening a new instance not the one that you have set the values. change it like this:
frmInvCert frm = new frmInvCert();
frm.certType = comboInvLvl.Text;
frm.thisYear = dateTimeCurrent.Text;
frm.myFileName = txtInvestor.Text;
frm.getAdress = txtAddress.Text;
frm.Show();


text:
Q: Convert text grid to nested dictionary in python Imagine a grid in a text file like this:
  A  B  C
A 0  1  2
B 3  0  5
C 6  7  0

What would be the nicest way to convert this into a dictionary in python like the following:
{
  'A': {'A': 0, 'B':3, 'C':6},
  'B': {'A': 1, 'B':0, 'C':7},
  'B': {'A': 2, 'B':5, 'C':0}
}

So I can access cells with:
matrix['A']['B'] # 3

I currently do have some very rough code (please don't judge me too harshly):
matrix = {}
f = open(filepath, 'r')
lines = f.readlines()
keys = lines[0].split()

for key in keys:
    matrix[key] = {}

for line in lines[1:]:
    chars = line.split()
    key_a = chars[0]
    for i, c in enumerate(chars[1:]):
        key_b = keys[i-1]
        matrix[key_a][key_b] = int(c)

print matrix

# Outputs {'A': {'A': 1, 'C': 0, 'B': 2}, 'C': {'A': 7, 'C': 6, 'B': 0}, 'B': {'A': 0, 'C': 3, 'B': 5}}

Whilst this isn't wrong, I've spent a long time away from python, is there a nicer way? Perhaps a nested dictionary isn't actually the best way?
UPDATES:

*

*Unfortunately I need to do this in vanilla python so using external libraries (which believe me I would love) isn't possible

*Updated my sample code form pseudocode to actual code. Hangs head in shame.

A: Your code is reasonable, but here is an alternative:
import collections
with open('grid_file.txt', 'r') as f:
    columns = next(f).split()
    matrix = collections.defaultdict(dict)
    for line in f:
        items = line.split()
        row, vals = items[0], items[1:]
        for col, val in zip(columns, vals):
            matrix[col][row] = int(val)
print(matrix)

which yields
defaultdict(<type 'dict'>, {'A': {'A': 0, 'C': 6, 'B': 3}, 'C': {'A': 2, 'C': 0, 'B': 5}, 'B': {'A': 1, 'C': 7, 'B': 0}})

Some tips:

*

*Use
with open(...) as f
    ...

instead of
f = open(...)
f.close()

because the file handle is closed for you when Python leaves the
with-block. By using with you'll never forget to close a filehandle, and even if an exception occurs, the filehandle will still be closed upon leaving the with-block.

*Generally, it is better to avoid f.readlines() if you can. This
slurps the entire file into a list. That can be onerous on memory,
especially if the file is huge. Usually
with open(...) as f:
    for line in f:

can be used instead.

*If you make matrix a collections.default(dict) then
matrix[field] will be a dict by default. So you can skip the
initialization:
for key in keys:
    matrix[key] = {}

*A defaultdict is a subclass of dict, so you can use it very much
as you would a dict. If you don't like the way it prints or would
like to stop matrix from automagically assigning an empty dict to
matrix[key] for any key, you can convert the defaultdict back to
a regular dict with:
matrix = dict(matrix)

*Avoid using numerical indices in for-loops if you can.
for i, c in enumerate(chars[1:]):

Although this is de rigueur for most C-like languages, Python has a
better way: looping over the items themselves:
for col, val in zip(columns, vals):

This makes the code more readable, because it assigns a variable name
to the object you are actually interested in, not just an index which
you then have to compose into things like keys[i-1]. It also helps
you avoid "off-by-one" errors which can occur when you have to adjust
the index by one, as is done in keys[i-1].

Another possibility is to not use nested dicts, but rather 2-tuples (column, row) as keys:
with open('grid_file.txt', 'r') as f:
    columns = next(f).split()
    matrix = {}
    for line in f:
        items = line.split()
        row, vals = items[0], items[1:]
        for col, val in zip(columns, vals):
            matrix[col, row] = int(val)
print(matrix)

yields
{('B', 'C'): 7, ('A', 'A'): 0, ('B', 'B'): 0, ('B', 'A'): 1, ('C', 'A'): 2, ('C', 'B'): 5, ('C', 'C'): 0, ('A', 'B'): 3, ('A', 'C'): 6}

Then you can access a (column, row) in the matrix like this:
print(matrix['A','C'])
# 6

By the way, if you install pandas:
import pandas as pd
import io

text = '''\
A  B  C
A 0  1  2
B 3  0  5
C 6  7  0'''

df = pd.read_table(io.BytesIO(text), sep='\s+')
print(df.to_dict())

yields
{'A': {'A': 0, 'B': 3, 'C': 6},
 'B': {'A': 1, 'B': 0, 'C': 7},
 'C': {'A': 2, 'B': 5, 'C': 0}}


text:
Q: Usage of auto concerning templates and functions Is this the correct C++14 style to pass in a lambda function and return a std::vector that contains n calls to the lambda function?
// gen is a lambda function
auto returnN(auto gen, auto n){
    std::vector< decltype(gen()) > vec;
    for(auto i=0; i<n; i++){
       vec.push_back( gen() );
    }
    return vec;
}

A: No.

*

*You need to explicitly use template, unless your compiler allows it as an extension. It might come in C++17.
Is auto as a parameter in a regular function a GCC 4.9 extension?

*You probably want to take the functor/function-pointer by universal reference.

*You forgot to decay the vector's element-type.

*Your loop has a loop-variable of type int. Whether that is enough...
template<class F>
auto returnN(F&& gen, size_t n) {
    std::vector<std::decay_t<decltype(gen())>> vec; // Needs to decay
    while(n--)
        vec.push_back(gen());
    return vec;
}


text:
Q: Asterisk BridgeWait How to bridge into a general bridge I need to connect two channels from a bunch of channels. The upcoming channel is pushed into BridgeWait. Waiting music is played. Under the data is placed about the current case. I want to find out why we need BridgeWait. I try to create new ordinal bridge with the channel by AMI Bridge I do not see an error. New bridge is not created. Channels are still in the bridge "Waiting". If I kick from the waiting bridge the channel is closed so it is impossible to bridge them again.
How should I bridge channels from the waiting bridge correctly.
extensions.conf
exten => 2002,1,NoOp
exten => 2002,n,BridgeWait("Waiting")
exten => 2002,n,Hangup

Channels
924fa28457df*CLI> core show channels
Channel              Location             State   Application(Data)
SIP/100-0000000a     2002@default:2       Up      BridgeWait("Waiting")
SIP/103-00000009     2002@default:2       Up      BridgeWait("Waiting")
2 active channels
2 active calls
11 calls processed

Holding bridge There are two channels.
924fa28457df*CLI> bridge show f57050e0-b6ae-4bfc-b8e3-295ce7371fef
Id: f57050e0-b6ae-4bfc-b8e3-295ce7371fef
Type: base
Technology: holding_bridge
Num-Channels: 2
Channel: SIP/103-00000009
Channel: SIP/100-0000000a

A: It is not possible to implement without AGI.
; Queue processing pipe.
exten => 2002,1,NoOp
exten => 2002,n,BridgeWait("Waiting")
exten => 2002,n,AGI(agi://10.1.2.1:3007)
exten => 2002,n,Hangup

BridgeWait Asterisk application holds the call for further processing with less resources.
Dialplan consists of piped operations: bridge wait and the next AGI management.
BridgeWait is broken from outside through the AMI interface to be managed by AGI when an operator is defined.
Short AGI pipe connects this predefined client and operator by dial command.


text:
Q: Python: ModuleNotFound error when file is in the same folder I was trying to load a dataset with pickle, when this error popped up:
Exception has occurred: ModuleNotFoundError
No module named 'treeUtil'

I was confused at first because I wasn't importing a module called treeUtil, but then I realized that the file I was loading was. I tried to re-organize the file with the dataset so that treeUtil was in the same folder as ibcData(the dataset), but it still didn't work, and gave me the same error. I'm pretty sure this is a misunderstanding of modules on my part, but here is my code:
import pickle, pandas as pd
from sklearn.neural_network import MLPClassifier
from sklearn.model_selection import train_test_split
from zeugma.embeddings import EmbeddingTransformer
from sklearn.metrics import accuracy_score

class PoliticalBiasDetector():
    def __init__(self):
        self.model = None
        self.vectorizer = None

    def train(self):

        df = pd.DataFrame(columns=["text","label"])
        [lib, con, neutral] = pickle.load(open('full_ibc/ibcData.pkl', 'rb'))

        for tree in lib:
            df = df.append({'text':tree.get_words(), 'label': "Liberal"})

        for tree in con:
            df = df.append({'text':tree.get_words(), 'label': "Conservative"})

        for tree in neutral:
            df = df.append({'text':tree.get_words(), 'label': "Neutral"})

        self.model = MLPClassifier()
        self.vectorizer = EmbeddingTransformer('glove')

        x_train, y_train, x_test, y_test = train_test_split(df[text], df[label],test_size=0.2,shuffle=True)

        train = self.vectorizer.transform(x_train)
        test = self.vectorizer.transform(x_test)

        self.model.fit(train,y_train)
        y_predict = self.model.predict(test)
        score = accuracy_score(y_test,y_predict)

        print ('Program Log: Model has been trained on the dataset.')
        print ("The accuracy is:",round(score*100,2))

This is the picture of the file I'm trying to load from.


text:
Q: PlayOnLinux Equivalent for windows Like the PlayOnLinux do we have a similar application in windows that allows us to run a Ubuntu application on Windows OS.
Or is there any simulator to run the ubuntu terminal in Windows(for learning purpose).

A: Why not simply use a virtual machine with a Linux Operating System?
You can use VirtualBox by Oracle, or VMware player. They are both free, and allow you to create a Virtual Machine, which essentially is a virtual computer inside your computer, acting like a normal program, and running anything a physical computer with the same operating system can run (with the exception of games).
[EDIT #1]: I found some interesting tutorials on how to install Ubuntu inside VirtualBox here. It should help you to get started if you decide to follow this route.

A: You can also try Cygwin.

Cygwin is:
a collection of tools which provide a Linux look and feel environment for Windows.
Cygwin is not:
a way to run native Linux apps on Windows.
You must rebuild your
application from source if you want it to run on Windows. a way to
magically make native Windows apps aware of UNIX® functionality like
signals, ptys, etc.

A: Yes. You can install virtual box on your system. What is virtual box?
How to install it:

*

*download virtual box (windows version).

*install it.
Then you can load your Ubuntu OS in that and learn.Visit this for extra information.


text:
Q: Rules to choose hardware for OLTP systems (sql server) Ok. We know database size, number of concurrent users, number of transactions per minute;
should choose number of processors, RAID, RAM, mirroring and clustering.
There are no exact rule.. but may be there are no rules at all?
In my practice in every case I have "legacy" system, and after some inspections and interview I can form an opinion how hardware and design can be improved.
But every time when I meet "absolutely" new system (I guess there are no new systems, but sometimes are such tasks) I can't say anything trustful. So I'm interesting how people deal with such tasks? They map task on theirs experience or have some base formulas?

A: It probably depends more on what the types of transactions are and how good your database was designed. Things that are also relevant will be how much of it's read vs write (very important for RAID config), are there complex JOINs, etc. It's really about the quality of database and application design, as much as it is about how many concurrent users and transactions. Thus, I would say that there are no rules for a generic OLTP database, all you can do is make rules (and possible optimizations) for your OLTP database and application. Imagine if you had no indexes - your database is going to perform very poorly.
Start with a test server and put a known load against it and see where the bottlenecks are, with Profiler. Then fix those, and increase the load.

A: If you have a certain test server, you can make some tests without having installed SQL or deployed any database.
I heard good stuff about sqliosim.exe tool used to simulate the SQL activity on brand new Operating System without anything running on it. I never tested it because I didn't have such an environment but it is not so hard to configure.
The results will guide you in figuring out whether CPU, Memory or Disk are enough for you system.
You need to have some benchmarks to know how much CPU, Memory or disk you need. However, there are some best practices on OLTP databases for Disk config: RAID 10 and RAID 5 seem to be best choice.
Raid 10 suited for increased write activity - Log files (100 % is write activity) and Data files (if write activity is more than 10 % of I/O operations).
Raid 5 suited for increased read activity - Data Files if write activity is less than 10 % of I/O operations.
Also Paul Randal's blog can help you because he had done many Hardware testings and came to reasonable conclusions: http://www.sqlskills.com/BLOGS/PAUL/category/Performance.aspx


text:
Q: How to implement a counter of current depth of \input Suppose first.tex contains \input{second.tex} and second.tex contains \input{third.tex}.
I would like to have an automated input depth counter whose value is 0 when used inside first.tex, 1 inside second.tex , and 2 inside third.tex. It should increase when \input is used and decreased on completion of the input.
How can I implement it?

A: Try like this:
\documentclass{article}
\usepackage{mathtools}
\usepackage{pifont}
\usepackage{bbding}
\usepackage{wasysym}
\newcounter{InputDepth}

\let\oldinput\input
\def\input#1{\stepcounter{InputDepth}\oldinput{#1}\addtocounter{InputDepth}{-1}}
\begin{document}
\theInputDepth

\input{first}

\theInputDepth

\input{second}

\theInputDepth

\end{document}

first.tex:
\theInputDepth

second.tex:
\theInputDepth

\input{third}

third.tex:
\theInputDepth

Output:

A: If you have a recent (after 2020-10-01) release of LaTeX, you can use the new hook mechanism.
\begin{filecontents*}{\jobname-first}
This is first: \theinputdepth

\input{\jobname-second}

Again: \theinputdepth
\end{filecontents*}

\begin{filecontents*}{\jobname-second}
This is second: \theinputdepth

\input{\jobname-third}

Again: \theinputdepth
\end{filecontents*}

\begin{filecontents*}{\jobname-third}
This is third: \theinputdepth
\end{filecontents*}

\documentclass{article}

\newcounter{inputdepth}

\AtBeginDocument{%
  \AddToHook{file/before}{\addtocounter{inputdepth}{1}}%
  \AddToHook{file/after}{\addtocounter{inputdepth}{-1}}%
}

\begin{document}

This is main: \theinputdepth

\input{\jobname-first}

Again: \theinputdepth

\end{document}

The hooks are set at begin document in order to avoid spurious settings of the counter. Not a big deal, though, you can just set the hooks in the preamble; there will be other settings to the counter, but the state will be 0 at the beginning of the document.


text:
Q: MIME RSA encryption i have this scheme
how can i use session-key in MIME to encrypt the message?
i used this command but i don't think it is correct
openssl enc -e -des3 -salt -in MSg_sign.txt -out session.txt

can you tell me the command to encrypt MIME using session-key


text:
Q: Getting infinite recursion with ObjectMapper even though entities' fields are annotated with @JsonIgnore Got two entities:
class Entity1{
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "entity1Id", unique = true, nullable = false)
private Integer entity1Id;

@OneToMany(mappedBy = "entity1", cascade=CascadeType.ALL,fetch=FetchType.EAGER)
Set<Entity2> entity2set = new Hashset<>();

}

class Entity2 {
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "entity1Id")
private Entity1 entity1;
}

No matter how I annotate those fields with @JsonIgnore or @JsonIgnoreProperties, I still get infinite recursion when I try to:
Entity1 entity1 = dao.saveEntity1(fields...);
String json = new ObjectMapper().writeValueAsString(entity1);

org.codehaus.jackson.map.JsonMappingException: Infinite recursion (StackOverflowError) (through reference chain: org.hibernate.Entity1["entity2set"]->org.hibernate.collection.internal.PersistentSet[0]->gis.hibernate.Entity2["entity1"]->gis.hibernate.Entity1["entity2set"]->org.hibernate.collection.internal.PersistentSet[0]-> ...

What am I doing wrong? Here are the attempts that I tried:
@JsonIgnoreProperties("entity1")
private Set<Entity2> entity2set = new HashSet<>();
together with
@JsonIgnoreProperties("entity2set")
private Entity1 entity1;

@JsonIgnore
private Entity1 entity1; (inside Entity2)

@JsonIgnore
private Set<Entity2> entity2set = new HashSet<>();  (inside Entity1)

What am I doing wrong?

A: You are using @JsonIgnoreProperties incorrectly. It is supposed to be on the class level.

A: I've solved with JsonView and with
String json = new ObjectMapper().writerWithView(MyView.class).writeValueAsString(entity);

This was the only thing that worked for me


text:
Q: Get the hidden input when clicking on textbox i need a little help about how to do it..
I have done lot of search but haven't find it.. So please if someone can help me out.
I have this little code here:-

    <textarea class="mytextbox" id="myuniquetextbox" cols="50" rows="10" style="height: 50px;"></textarea>

    <input type="submit" name="aw-whats-new-submit" id="aw-whats-new-submit" value="Submit">

As you can see i added style="display: none;" in the div where is situated the submit button.
I don't have lot of knowledge in jQuery or javascript but i need a simple javascript code that will change the "display:none" to "display:block" when someone click on the textbox..
Please i need your help, thank you very much...

A: Another way to do this is:

$(function () {
   $('#myuniquetextbox').click(function(e) {
      $('#whats-new-options').css('display', 'block');
   });
});

A: Try this
$("#myuniquetextbox").on("focus",function(){
  $("#whats-new-options").show();
})

A: Try below code
 $("#mytextbox").focus(function() {

    // this is when textarea is focused and button should show
    $("#whats-new-options").show();

    });

$("#mytextbox").blur(function() {

    // this is when textarea is not focused and button should hide
    $("#whats-new-options").hide();

    });

A: Try using bellow

A:

$("#aw-whats-new-submit").hide();
$("#myuniquetextbox").click(function() {
  $("#aw-whats-new-submit").show();
});

    <textarea class="mytextbox" id="myuniquetextbox" cols="50" rows="10" style="height: 50px;"></textarea>

    <input type="submit" name="aw-whats-new-submit" id="aw-whats-new-submit" value="Submit">

A: you can also do this
 $(function () {
       $('#myuniquetextbox').on('click',function(e) {
          $('#whats-new-options').css('display', 'block');
       });
    });

Check your code here


text:
Q: Adding element to a array works, but doesnt show up in other switch statement In my code, I try to create 2 arrays and be able to add more elements to those arrays and then print them out. I print whole arrays in switch case 3 and nothing happens, but when I copy that code to case 1 it works perfectly. That means it takes the old array instead of the "updated" one. Can someone help me?
 using System;
    using System.Collections.Generic;
    using System.Linq;

namespace ConsoleApp1
{
class Program
{
    static void Main(string[] args)
    {

        bool fortsatt = true;

        while (fortsatt)
{
        Console.WriteLine("Lägg till blogginlägg (1)");
        Console.WriteLine("Skriv ut inlägg (Skriv titeln) (2)");
        Console.WriteLine("Skriv ur alla blogginlägg (3)");
        Console.WriteLine("Avsluta (4)");

            string[] posts = { "jag åt inte frukost", "jag åt gott middag", "jag åt hamburgare" };
            string[] titles = { "Frukost", "Middag", "Mat" };

            string menu = Console.ReadLine();

            switch (menu)
            {
                case "1":

                    Console.WriteLine("Mata in en text");
                    string inmatat = Console.ReadLine();

                    List<string> list = new List<string>(posts.ToList());
                    list.Add(inmatat);
                    posts = list.ToArray();

                    Console.WriteLine("Mata in en titeln");
                    string titel_imatning = Console.ReadLine();

                    List<string> list_of_titles = new List<string>(titles.ToList());
                    list.Add(titel_imatning);
                    titles = list_of_titles.ToArray();

                    break;

                case "2":

                    Console.WriteLine("Skriv titeln:  ");
                    string search = Console.ReadLine();
                    bool found = false;
                    for (int i = 0; i < posts.Length; i++)
                    {
                        if (titles[i] == search)
                        {

                            Console.WriteLine("\tDet är vad jag har hittat: " +
                                "\n\tTiteln: " + titles[i] +
                                "\n\tInlägg: " +
                                posts[i] + "\n\t");
                            found = true;
                            break;
                        }
                    }

                    if (!found)
                        Console.WriteLine("\t Kunde inte hitta ");
                    break;

                case "3":

                    foreach (var value in posts)
                    {
                        Console.WriteLine(value);
                    }

                    break;

                case "4":
                    Console.WriteLine("Tack för att du använde min kod");
                    fortsatt = false;
                    break;

                default:

                break;
            }
        }
    }
}

}

A: You are each time creating the arrays from scratch in each of your main while loop run.
Put the Arrays outside the
while(true)

Like this:
      bool fortsatt = true;

            string[] posts = { "jag åt inte frukost", "jag åt gott middag", "jag åt hamburgare" };
            string[] titles = { "Frukost", "Middag", "Mat" };

        while (fortsatt)
        {
         Console.WriteLine("Lägg till blogginlägg (1)");
         Console.WriteLine("Skriv ut inlägg (Skriv titeln) (2)");
         Console.WriteLine("Skriv ur alla blogginlägg (3)");
         Console.WriteLine("Avsluta (4)");

            string menu = Console.ReadLine();

            switch (menu)
            {
                case "1":

                    Console.WriteLine("Mata in en text");
                    string inmatat = Console.ReadLine();

                    List<string> list = new List<string>(posts.ToList());
                    list.Add(inmatat);
                    posts = list.ToArray();

                    Console.WriteLine("Mata in en titeln");
                    string titel_imatning = Console.ReadLine();

                    List<string> list_of_titles = new List<string>(titles.ToList());
                    list.Add(titel_imatning);
                    titles = list_of_titles.ToArray();

                    break;

                case "2":

                    Console.WriteLine("Skriv titeln:  ");
                    string search = Console.ReadLine();
                    bool found = false;
                    for (int i = 0; i < posts.Length; i++)
                    {
                        if (titles[i] == search)
                        {

                            Console.WriteLine("\tDet är vad jag har hittat: " +
                                "\n\tTiteln: " + titles[i] +
                                "\n\tInlägg: " +
                                posts[i] + "\n\t");
                            found = true;
                            break;
                        }
                    }

                    if (!found)
                        Console.WriteLine("\t Kunde inte hitta ");
                    break;

                case "3":

                    foreach (var value in posts)
                    {
                        Console.WriteLine(value);
                    }

                    break;

                case "4":
                    Console.WriteLine("Tack för att du använde min kod");
                    fortsatt = false;
                    break;

                default:

                break;
            }

A: You seem to show the menu in a loop. And you initialize the arrays posts and titles within that loop. So all changes made by the user in the first run, will be discarded by the array re-initalization in the next run / loop.
Solution: initialize the array outside the loop.
    bool fortsatt = true;
    string[] posts = { "jag åt inte frukost", "jag åt gott middag", "jag åt hamburgare" };
    string[] titles = { "Frukost", "Middag", "Mat" };

    while (fortsatt)
    {
        Console.WriteLine("Lägg till blogginlägg (1)");
        Console.WriteLine("Skriv ut inlägg (Skriv titeln) (2)");
        Console.WriteLine("Skriv ur alla blogginlägg (3)");
        Console.WriteLine("Avsluta (4)");
        //....


text:
Q: Equation with 2 unknowns I'm trying to calculate the coefficients of $2$ numbers. I know $2$ values and the answer of their equation. I tried doing an equation with $2$ unknowns, but when I try different equations with the values I have, the answer may vary, which I don't understand.
This are my values :

I thought the coefficient for $x$ was $0.5$ and $y$ was $0.45$ to get the answer, BUT if I try on another line it won't work. I am confused on what would be the equation with $X$ and $Y$ to get the answer?

A: You want to write
$ z_i = a x_i + b y_i , \hspace{30pt} i = 1, 2, ..., 16 $
Let
$ Z = \begin{bmatrix} z_1 \\ z_2 \\ \vdots \\ z_{16} \end{bmatrix} $
and
$ X = \begin{bmatrix} x_1 && y_1 \\ x_2 && y_2 \\ \vdots && \vdots \\ x_{16} && y_{16} \end{bmatrix}$
Then, we want to write
$ Z = X u $
where $ u = \begin{bmatrix} a \\ b \end{bmatrix} $
The least-squares solution for $u$ is
$ u = (X^T X)^{-1} X^T Z $
Performing this calculation, will results in
$ u = \begin{bmatrix} 0.474090909 \\ 0.474090909 \end{bmatrix} $
These are the optimal value for the coefficients $a$ and $b$ in the least squares sense.  If you compute the errors, you'll find that the root mean squared error (RMSE) is $ \approx 0.1776 $
However, if you modify the model to include a constant, as @ClaudeLeibovici commented, i.e.
$ z_i = a + b x_i + c y_i \hspace{30pt} , i = 1, 2, \dots, 16 $
Then in this case, the matrix $X$ is modified to
$ X = \begin{bmatrix} 1 && x_1 && y_1 \\ 1 && x_2 && y_2 \\ \vdots && \vdots && \vdots \\ 1 && x_{16} && y_{16} \end{bmatrix} $
And
$ u = \begin{bmatrix} a \\ b \\ c \end{bmatrix} $
And after applying the formula, you get
$ u = \begin{bmatrix} -0.225 \\ 0.525 \\ 0.525 \end{bmatrix} $
Using these model values results in a root mean squared error (RMSE) of $ \approx 0.16413$
which is better than the previous model.
To make things even better, we can make the model as follows
$z_i = a + b x_i + c y_i + d x_i^2 + e x_i y_i + f y_i^2 $
which is a quadratic model.
In this case, matrix $X$ becomes
$ X = \begin{bmatrix} 1 && x_1 && y_1 && x_1^2 && x_1 y_1 && y_1^2 \\
1 && x_2 && y_2 && x_2^2 && x_2 y_2 && y_2^2\\
\vdots && \vdots && \vdots && \vdots && \vdots && \vdots \\
1 && x_{16} && y_{16} && x_{16}^2 && x_{16} y_{16} && y_{16}^2 \end{bmatrix} $
And
$ u = \begin{bmatrix} a \\ b \\ c \\ d \\ e \\ f \end{bmatrix} $
Using the same formula, one finds that
$ u = \begin{bmatrix} 0 \\ 0.475 \\ 0.475 \\ -0.05 \\ 0.116 \\ -0.05 \end{bmatrix}$
And the root mean squared error (RMSE) is $\approx 0.0302 $ which, as expected, is better than the previous models.