Load data into materializecss slider dynamically using Angular ng-repeat not working

Question: I can hover over the slider div and "copy image url" option is there thus data is setted correctly but slider is showing nothing, its just grey-blank.
If I remove the classes "slider,slides", then all of my data is popped up vertically but not when using "slider,slides" classes.
I have this in my main Html:
         $(document).ready(function () {
              $('.slider').slider();
             });

My Sample Json Data which I get through GET request in angular :
      cast: [
            {
                cast_id: 0,
                character: "Mark Watney",
                credit_id: "53e7e85e0e0a266f9a0029aa",
                id: 1892,
                name: "Matt Damon",
                order: 0,
                profile_path: "/eLAWpp5BLbTwjj35MbGzpL0QkWv.jpg"
            },
            {
                cast_id: 9,
                character: "Melissa Lewis",
                credit_id: "5466c78eeaeb8172820008e4",
                id: 83002,
                name: "Jessica Chastain",
                order: 1,
                profile_path: "/eyv98YlnRuOOUNCD1U6w2yZDRA2.jpg"
            },
            {
                cast_id: 11,
                character: "Annie Montrose",
                credit_id: "5497ab23c3a368054b0009b4",
                id: 41091,
                name: "Kristen Wiig",
                order: 2,
                profile_path: "/eqHjl70yPVAYcpYnqKk62a3pzDd.jpg"
            },
            {
                cast_id: 13,
                character: "Teddy Sanders",
                credit_id: "54a7fe92c3a3680c33001972",
                id: 8447,
                name: "Jeff Daniels",
                order: 3,
                profile_path: "/gai03gCu3DxMYxFympt7hUObpI5.jpg"
            }
          ]

Now i am setting this data from angular but the slider appears grey, I can confirm the image url by hovering over grey area and copying image url. But nothing is displayed in the div.

My angularJS code where I am getting and setting data:
      DetailsService.GetMovieCredits(mid).then(function (response) {
            var json = angular.fromJson(response);
            //var cast = json.cast;
            $scope.actors = json;
            $scope.castShow = true;
        }, function (response) {
        });

Comment: i not getting you question exactly. what do you mean by "I can hover over the slider and copy image url"
Comment: please clarify your question
Comment: my data is getting loaded(as I tested without slider and  slides class ) in ng-repeat actors but  nothing is getting displayed in the div.
Answer: I have found a work around for the same. Why not we create a custom event and dispatch it when cast response has been fetched? And we can attach a listener on the same custom event and within the listener we can call $('.slider').slider();.
The angular code part will look something like this
DetailsService.GetMovieCredits(mid).then(function (response) {
        var json = angular.fromJson(response);
        $scope.actors = json;
        $scope.castShow = true;
        //Creating custom event for slider data loaded
        var event = document.createEvent('Event');
        event.initEvent('slider-ready',true,true);
        document.querySelector('.slider').dispatchEvent(event);
  }, function (response) {
    });

Then instead of calling
$(document).ready(function () {$('.slider').slider();}); from main.html
we have to do something like this
$('.slider).on('slider-ready', function (e) {
            //Adding timeout as direct function call was not working
            setTimeout(function(){
                 $('.slider').slider();
            },1);
});

It worked for me. Hopefully it helps. It is just a hack that I have come up with.


Proof of this (geometric) infinite sum

Question:
Question: Prove that when $\exp(\Re[st])>1$:
$$\sum_{n=0}^{\infty}\exp\left[-nts\right]=\frac{e^{st}}{e^{st}-1}$$

I think that it is an geomeric sum, but I new to this kind of finding a sum. Thanks for any help.
Comment: Note that you might as well replace the product $st$ with some new variable $z$ everywhere, since the statement depends only on $st$.
Answer: It's exactly a geometric sum:
$$
\sum_{n=0}^\infty e^{-nts}=\sum_{n=0}^\infty (e^{-ts})^n=\frac1{1-e^{-ts}}=\frac{e^{ts}}{e^{ts}+1}.
$$
For the series to converge and the above to work you need $|e^{-ts}|<1$. This is $|e^{ts}|>1$. Since
$$
|e^{ts}|=|e^{\text{Re}\,ts+i\,\text{Im}\,ts}|=|e^{\text{Re}\,ts}|>1,
$$
the  hypothesis guarantees that the series converges.
Answer: Observe that if $\;|z|<1\;$ then
$$\sum_{n=0}^\infty z^n=\frac1{1-z}$$
In our case,
$$e^{\text{Re}\,(st)}>1\implies \left|e^{-st}\right|=e^{-\text{Re}\,(st)}<1\implies$$
$$\sum_{n=0}^\infty\left(e^{-st}\right)^n=\frac1{1-e^{-st}}=\frac{e^{st}}{e^{st}-1}$$
Answer: The theorem you want to use (the geometric series) is:
$$\sum_{n=0}^{\infty} z^n = \frac{1}{1-z},$$
for $z \in \mathbb{C}$ such that $|z|<1$. Note that
$$e^{-nts}=(e^{-ts})^n$$
for $n \in \mathbb{N}$. Substituting $z=e^{-ts}$ we obtain the required result, if of course $|e^{-st}|<1$. To see this let $st = x+iy$. We are given that $x>1$. So $$|e^{-st}| = |e^{-x-iy}|=e^{-x}<1.$$

Proof of this (geometric) infinite sum


Finding the closest point on a plane and a given point

Question: I have  a plane, and a point and I am able to interchange between the plane equation and parametric equation quite well now.
I recently figured out how to find a point on the line thats the closest to another point by using the dot product set to zero. I would get the parametric equations for the line of interest and then find its directional vector. Id find the vector from the line to the point and dot product these set to 0, solve for t and resubstitute into my parametric equations.
Im having trouble doing this with planes though, mostly due to the fact of two variables but also I cant visualize how the line connecting the plane to the point will be a perpendicular one. My problem is im rotating this plane in my mind and the line connencting the plane to the point might not be perpendicular.
First can someone tell me the method to use to find the point on the plane closest to that point, and then maybe help me with my visualization.
Thank you
Comment: Are you familiar with the method of Lagrange Multipliers to find max/min values?
Comment: no we have not done that, however I did something interesting to find the least distance between two points earlier, I differentiated a function of t that represented the distance between a point and a line, set it to zero for a  mix/max and solved for t, is this similar?
Comment: yes! that is a somewhat similar idea. Good intuition. you're looking at "constrained optimization," although some multivariable machinery is required before you deal with lagrange multipliers (gradients and such.) I've answered an alternative method, hopefully it makes sense.
Answer: Say that you have
a plane: $ax+by+cz=d$
and a point: $(f,g,h)$.
The basic idea is that because of the ways that planes are constructed (with two different vectors), a perpendicular one will be the cross product of these vectors. Consequently, you can always find a perpendicular vector to a plane (think about putting a stick in the mud, and moving it around a 2-d surface.) This vector looks like: $[a,b,c]$.
For a "proof" of this, consider the following 2 points on the plane:
$(x_{1},y_{1},z_{1})$ and $(x_{2},y_{2},z_{2})$.
Since they are on the plane, they both satisfy the following equation:
$$ax_{1}+by_{1}+cz_{1}=d$$ and $$ax_{2}+by_{2}+cz_{2}=d$$
Now, by subtraction we have that: $$(ax_{1}-ax_{2})+by_{1}-by_{2}+cz_{1}-cz_{2}=0$$
or, better yet:
$$[a,b,c]\cdot[x_{1}-x_{2},y_{1}-y_{2},z_{1}-z_{2}]=0$$
Since $[x_{1}-x_{2},y_{1}-y_{2},z_{1}-z_{2}]$ is a vector made by points on the plane, it is a vector on the plane. Since the dot product is zero, $[a,b,c]$ is perpendicular to this vector.
Now you more explicitly want a "line" given by a parametric that has the direction of $[a,b,c]$ and that goes through the point $(f,g,h)$. But then, just look at: $(x,y,z)=(f,g,h)+t[a,b,c]$. Then you have three different equations for $x,y,z$. Substitute them into the original equation for the plane:
$(x,y,z)=(f,g,h)+t[a,b,c]$ implies that:
$x=f+ta$
$y=g+bt$
$z=h+ct$
Then, by substitution into the first equation for the plane:
$a(f+ta)+b(g+bt)+c(h+tc)=d$
Now you have one variable ($t$) and a bunch of constants so you can solve for $t$ and figure it out!
To provide further intuition: take the stick in the mud picture, and imagine, say... some piece of dust floating (and static) in space above the ground. First you want to get the stick directly under the piece of dust (orient it in the mud so that it is perpendicular and right below the piece of dust)-- then solve for how long the stick needs to be until it reaches it, (solve for the scalar, $t$.) If you can do that, you will find a "line" that goes through the point and intersects the plane perpendicularly.


Ursina not importing in python

Question: I'm getting error:
Traceback (most recent call last):

  File "C:\Users\user\Downloads\blocky\main.py", line 1, in <module>
    import ursina as ue
ModuleNotFoundError: No module named 'ursina'

I tried:
pip install ursina
wait I also did
python -m pip install ursina
Comment: How do you run your Python program?
Comment: What happened when you tried to installed ursina via pip?
Comment: statisfied but still didnt import
 ,runed by idle
Comment: Idle probably runs from a different Python installation than on your shell. Check the settings and search around, this is a very common problem. You have to make sure to install the package for the right Python installation.
Comment: i tried........
Answer: Since you're using import ursina as (custom name), you currently importing ursina as a local namespace and doing this will be annoying for most beginners.
Example: (namespace).function()/PACKAGE CONTENT.function()
I recommend that you use from ursina import * because this will extract everything and remove the need for namespace on every function/PACKAGE CONTENT.
Example: function()/PACKAGE CONTENT.function()
Also, try reinstalling python.
Answer: Try using pipwin.
First do
pip install pipwin,

Then do pipwin install ursina
Comment: That doesn't work on linux neither mac
Answer: You must have any other libraries installed in the same virtual
environment or the default, that causes conflict with 'ursina'
Try store the libraries u use in the project in a new empty virtual environment

1, Install https://pypi.org/project/virtualenv/

 pip install virtualenv

2, Create a new folder for your environment (by convention it is advisable to call it venv.) locate the folder with the console

source /python -m virtualenv .

3, Active (to deactivate it would be the same but in the end it is placed deactivate.)

-- in Windows
 source /venv/Scripts/activate

-- in Linux
 source /venv/bin/activate

the name of the virtual environment will appear at the beginning of the line in the command terminal, (venv in this case).

4, To see the packages that we have installed in our virtual environment we execute the following command:

(venv) source  /pip list

5, install 'ursina' n all the libs u need

(venv) source  /pip install ursina

Answer: If you can't install ursina (neither one option from above worked), just download the GitHub repository and import ursina from there. You will need to put the folder inside your project directory.
Answer: Use the following proper command:
python3.10 pip -m install ursina

Fix at the documentation ursina requires python 3.10 or latest to work.
What induces that issues is what when we install any package in Python it self try to fix the broken dependencies by us, in that case that make the ursina installation pends on the python3 installation and not even python3.10 which is required.
Comment: Dear OP, please see [answer]. There are still grammatical mistakes in the answer, I'd request you to correct it.
Answer: use this instead
from ursina import *

app= Ursina()
(code)
app.run()

this will help your issue
Comment: Writing the import in a different way won't help if the import itself fails.

Ursina not importing in python


Enable Twig debug doesn't work?

Question: Why isn't the Twig debug working on my Drupal 8.2.6 site?
This is the folder structure.

These are the folder permissions.

This is the content of the settings.php file.
$settings['hash_salt'] = 'DEVELOPMENT_SALT';
$settings['update_free_access'] = FALSE;
$settings['file_public_base_url'] = 'http://localhost/files';
$settings['file_public_path'] = 'sites/default/files';
$settings['file_private_path'] = 'sites/default/private';
$settings['file_scan_ignore_directories'] = [
  'node_modules',
  'bower_components',
];
if (file_exists(__DIR__ . '/../development/settings.development.php'))     {
  include __DIR__ . '/../development/settings.development.php';
}

Here I include /../development/settings.development.php.
assert_options(ASSERT_ACTIVE, TRUE);
\Drupal\Component\Assertion\Handle::register();

/**
 * Enable local development services.
 */
$settings['container_yamls'][] = __DIR__ . '/development.services.yml';

$databases['default']['default'] = array(
  'database' => 'dbname',
  'username' => 'dbusername',
  'password' => 'pw',
  'prefix' => '',
  'host' => '127.0.0.1',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);

$settings['hash_salt'] = 'DEVELOPMENT';

$config['system.logging']['error_level'] = 'verbose';
$config['system.performance']['css']['preprocess'] = FALSE;
$config['system.performance']['js']['preprocess'] = FALSE;
$settings['cache']['bins']['render'] = 'cache.backend.null';
$settings['cache']['bins']['dynamic_page_cache'] =     'cache.backend.null';
$settings['extension_discovery_scan_tests'] = TRUE;
$settings['rebuild_access'] = TRUE;
$settings['skip_permissions_hardening'] = TRUE;

Here I also add development.services.yml.
parameters:
  http.response.debug_cacheability_headers: true
  twig.config:
    debug: true
    auto_reload: true
    cache: false
services:
  cache.backend.null:
    class: Drupal\Core\Cache\NullBackendFactory

Things I have checked/done:

Checked if all these files are loaded -> They are
Checked the indentation of the development.services.yml -> Checks out
Cleared all the different caches, rebuild them, etc -> If I change a template, it changes, but no Twig debugging

sites/default/files AND sites/default/private are not used by Drupal.
Answer: Try to change your development.services.yml to following. this  works for me correctly(I hope works for you too) .
services:
  cache.backend.null:
    class: Drupal\Core\Cache\NullBackendFactory

# Enable Twig debugging.
parameters:
 twig.config:
   debug: true
   auto_reload: true
   cache: false

also  this article about setting up debugging on Drupal 8 is very good for future visitors of this question.
Comment: Thanks! This is the formatting that finally worked for me.
Comment: @RobbDavis you're welcome, good to hear that.
Answer: Services should come before parameters ...also... If you don't want to enable all the 'stuff' you have in settings.local.php you can just add...
$settings['container_yamls'][] = DRUPAL_ROOT . '/sites/development.services.yml';
to the bottom of your settings.php file to turn on twig debug after adding the parameters to development.services.yml.
I use both this and...
if (file_exists($app_root . '/' . $site_path . '/settings.local.php')) {
   include $app_root . '/' . $site_path . '/settings.local.php';

Commenting out one or the other depending on what I need.
Answer: It seems everything is correct and I guess you just forget check "Show comments" on your browser.
Comment: This is not the case, because I am using Chrome's inspector.
Comment: @user3634184 try to check it on firefox ,just for test.

Enable Twig debug doesn't work?


Is there a way to look into L2 hibernate cache?

Question: I have a task to attach Oracle Coherence (it is cache software) in my project. One way of using it is Level2 Hibernate cache.
I want to see when hibernate takes results from L2 cache. How can i do that? Both ways will be good: listener of some sort, if possible, or direct access to Cache object.
Thanks in advance.
Answer: The Coherence Hibernate L2 integration allows you to specify a system property to point to the coherence cache configuration that will be used by the L2 cache.  If you point the "normal" coherence cache configuration to the same file, this will allow you to access the caches via CacheFactory.getCache.
-Dtangosol.coherence.cacheconfig=sample-cache-config.xml
-Dtangosol.coherence.hibernate.cacheconfig=sample-cache-config.xml
You can download an example here:
http://coherence.oracle.com/download/attachments/16730/hibernate-sample-src.jar
Comment: Wow. Thanks for that! You are some kind of superhero!
Answer:
I want to see when hibernate takes results from L2 cache.

Activate logging of all second-level cache activity. The relevant category is org.hibernate.cache.
Reference

Hibernate Core Reference Guide

3.5 Logging


Running tcsh scripts on startup in bash env

Question: I have a user called foo which is using tcsh by default in /etc/passwd. I cannot change that default shell. Foo has a service called xyz running, for which all the startup scripts and .(dot) file containing ENV variables are in home dir of foo.
Now a startup script is also created to run that service and placed in /etc/init.d/xyz which is written in bash.
Now the issue is that the service is not starting on boot and I cannot run it from my default user on login too. It is only possible to run when I su into foo user and execute the script to start the service.
If I do like this
sudo su foo /home/foo/xyz it will show me errors like then: then/endif not found..
So what I want to run a tcsh program to run on boot from a init.d script which is in bash. At present I tried to do this
su - foo -c "source /home/foo/.env_vars && /home/foo/bin/xyz start" but this is not starting the service at the time of boot.
I am not sure how to make a tcsh script execute on boot time.
Comment: Have you tried `sudo -u foo tcsh /home/foo/script` ?
Comment: Pretty much what @jonathanjo says, just use tcsh on the scripts.
Answer: You can either:

use tcsh -c $script to run the scripts with tcsh
set the shebang (first line) in the script to #!/bin/tcsh and set it executable; you can then just start it with $script as the command.


Could VsCode extension get any language server's completion items?

Question: As the title, I want to get typescript language server's completion items in my own extension. How should I do?
If there is another way except running the language server by myself?
Answer: You can use the vscode.executeCompletionItemProvider built-in command for this:
const list = await vscode.commands.executeCommand('vscode.executeCompletionItemProvider',
    vscode.Uri.file('/path/to/file.ts'),
    new vscode.Position(line, character))

Similar commands exist for other functionality, such as listing references.
Comment: Thank you very much.  the command can get other suggestions, but executing the command in my IntelliSense extension causes a loop call. I didn't find a way to avoid this.
Comment: I use a `flag` to resolve this. Thank you very much to solve my problem.


can't connect myxins to quasar, globally

Question: Encountered an 'Undefined mixin' error when trying to use mixin in a Quasar project running in a Docker container
enter image description here
comments on the screen

here is the mixin itself
connected it in the quasar config as well as app.scss
they are in the same place

project on docker-compose quasar in a separate container, unlikely my problem is related to this but maybe. The problem itself is like this, I connect myxin for mobile layout, I want to use it throughout the project. but it gives an error:
<code>[plugin:vite:css] Undefined mixin.
   ╷
18 │ ┌ @include mobile {
19 │ │ │ flex-direction: column;
20 │ └ }
   ╵
  src/components/base/CustomFooter.vue 18:7 root stylesheet
/app/src/components/base/CustomFooter.vue:52:6
</code>
screenshot of the error in the second photo
enter image description here
enter image description here
This is how I'm trying to use myxin. Of course, if I uncomment line 36 everything will work, but I want to understand how to work globally so that I don't have to import myxin in every component.
I have already searched for solutions related to global mixin import in Quasar, but did not find a suitable one. now everything is done as it is written in the official documentation
Answer: Update:
Sorry didn't saw you already know you can import the mixins. I didn't noticed you posted two screenshots. Unfortunately I can't help you with global including mixins and I doubt this is a quasar topic in general. You should look for vite or vue. Maybe this is some help for you:
globally load sass into vue

you could add an import for the mixin in the .vue file. For example:
<code><style lang="scss" scoped>
@import 'src/css/mixins'

@include my-awesome-mixin {
  // ...
}
</style>
</code>


How to prevent the addition of HTML in "Full HTML" text format?

Question: Sometimes, Drupal has the annoying habit to automatically add HTML to the content's source, generally
 and
, even when the text format is set to "Full HTML".
This is really annoying and I can't find any way to prevent that.  Any idea ?
Answer: Ok, I think I've found the answer:
This is a "feature" of the Full HTML mode.

Full HTML:

Web page addresses and e-mail addresses turn into links automatically.
Lines and paragraphs are automatically recognized. The  line break,  paragraph and  close paragraph tags are inserted
  automatically. If paragraphs are not recognized simply add a couple
  blank lines.

You can disable it in You are here Administration » Configuration » Content authoring » Text formats by unchecking Convert line breaks into HTML (i.e.
 and
).
Source: http://drupal.org/node/503754
Comment: My, too slow ...
Answer: It depends on the configuration of the filters the input format uses.
You can disable the tags you're talking about on the page : http://yoursite/admin/config/content/formats/full_html.
Just uncheck Convert line breaks into HTML (i.e.
 and
).


Easy way to get city from LocationManager on Android?

Question: I'm trying to figure out the city of where the user is using their location. Using LocationManager and Geocoder I get some nice data from the longitude and latitude, but I can't get one thing. The subAdminArea a.k.a. the city. It always returns null for me, even though everything else including the postal code is received. Is there something I am missing?
Basically this is a method I call for getting data.
public String getLocation(Locale locale, Context context, boolean city, boolean postal, boolean state_prov) throws IOException{
    LocationManager locMan = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
    LocationListener locList = new MyLocList();
    Geocoder gC = new Geocoder(context,locale);
    Location gpsLocation = locMan.getLastKnownLocation(locMan.GPS_PROVIDER);
    locMan.requestLocationUpdates(locMan.NETWORK_PROVIDER, 500, 200, locList);
    Location networkLocation = locMan.getLastKnownLocation(locMan.NETWORK_PROVIDER);
    if (city)
        return (gC.getFromLocation(networkLocation.getLatitude(), networkLocation.getLongitude(), 1).get(0).getSubAdminArea());
    else if (postal)
        return (gC.getFromLocation(networkLocation.getLatitude(), networkLocation.getLongitude(), 1).get(0).getPostalCode());
    else if (state_prov)
        return (gC.getFromLocation(networkLocation.getLatitude(), networkLocation.getLongitude(), 1).get(0).getAdminArea());
    else
        return "";
}

and the call to this method is done via:
String city = getLocation(Locale.getDefault(),getBaseContext(),true,false,false);

The only other option I have found through some research is sending a request to
http://maps.googleapis.com/maps/api/geocode/json?address=POSTALCODE&sensor=true

and it gives me a JSON of that location based on the postal code, which I can then parse, but it seems like a lot of work to find the city.
Could there be something I am missing? Or something I did wrong? I am new to location services for android.
Answer: Try this:
   Geocoder gc = new Geocoder(context, Locale.getDefault());
    List<Address> addresses = gc.getFromLocation(latitude, longitude, maxResults);

StringBuilder sb = new StringBuilder();
for (int i = 0; i < addresses.getMaxAddressLineIndex(); i++)
 Log.d("=Adress=",addresses.getAddressLine(i));
}

You will get postal code, city , country, ....
Comment: It seems as though changing my location to another area got a city reading. This is weird. But this still returns null for the subAdminArea at home. Not sure what's causing this.
Answer: I used this answer and it worked perfectly fine. It was able to get the location despite the problems I initially had in this question.


Remoção de espaços em branco em excesso

Question: Como remover espaços em branco dentro de uma string?
Seria no sentido de remover os espaços de uma cadeia de texto, com exceção dos espaços simples entre palavras, como é na função "arrumar" do Excel.
Comment: Alguma das respostas resolveu sua dúvida? Acha que pode aceitar uma delas? Veja o [tour] como fazer isso, se ainda não o fez. Você ajudaria a comunidade identificando qual foi a melhor solução para você. Pode aceitar apenas uma delas. Mas pode votar em qualquer pergunta ou resposta que achar útil no site todo.
Answer: A função AllTrim() resolve a maioria dos casos. Se desejar que elimine no meio:
Function MiddleTrim(cText)
    Local cClean := ""
    Local cLast := " "
    Local nLen := Len(cText)
    Local i
    Local cChar
    For i := 1 To nLen
        cChar := Substr(cText, i, 1)
        If cChar != " "
            cClean += cChar
        ElseIf cLast != " "
            cClean += " "
        EndIf
        cLast := cChar
    Next
    If Substr(cClean, Len(cClean), 1) == " "
        cClean := Substr(cClean, 1, Len(cClean) - 1)
    EndIf
Return cClean

Também coloquei no GitHub para referência futura.
Desta forma lê caractere por caractere identificando se já existia um espaço antes, só copia o caractere se não for espaço ou se for o espaço imediatamente seguinte a um não espaço, ou seja, fica apenas um espaço. Como pode ficar um último espaço no final, ele limpa também. Percorrer caractere por caractere é o que o StrTran() e o AllTrim() fariam, por isso tem chance de ser mais eficiente desta forma por percorrer só uma vez.
No Harbour talvez não porque ele seria executado em C de forma bem eficiente. Não sei como está hoje, mas ADVPL tinha implementação bem ineficiente em muitas coisas, tanto que alguns recursos comuns no Harbour ou mesmo Clipper até recomendam evitar o uso.
Comment: Para eliminar os espaços no meio, acredito que o `StrTran(cText, " ")` seja mais simples
Comment: Aí tira todos espaços.
Comment: Ok, porém mais fácil verificar se existe um espaço no final e/ou começo, usar o strtran, e depois adicionar se precisar. Aí executa direto no servidor de aplicação, e não via advpl.
Comment: Tenta fazer assim. Não dá o resultado desejado na pergunta. Faz tempo que não mexo na plataforma, não sei como está essa questão do servidor de aplicação e por isso não entendi o que quis dizer com isso, pode me explicar?
Answer: Uma alternativa:
Function MiddleTrim(cText)
    While "  " $ cText
        cText = StrTran(cText, "  ", " ")
    End
    Return AllTrim(cText)

Lembrando que apesar de mais curta que a resposta do @Maniero (que já recebeu meu +1), ela não necessariamente seja mais performática, pois pode percorrer a string várias vezes.
Pontos de interesse:

StrTran(cText, "  ", " ") troca ocorrências de dois espaços por um só. Mas como a função não é recursiva, precisa de um loop;
While "  " $ cText faz o loop enquanto "  " estiver contindo em cText;
Finalmente o AllTrim remove os espaços das "pontas" da string.

Nota:
Tomei por base a sintaxe do Harbour, se houver alguma diferença em Advpl provavelmente vai ser só um ajuste no While .. End. O relevante aqui é a lógica.

Remoção de espaços em branco em excesso


Analyze scatter plot

Question: I want to study the relationship between two variables. I've got the following scatter plot.

But now I'm hesitating on what to do with this:

Should I check the assumptions of OLS and then use the lm function?
Or should I remove some outliers first?
Or should I use ridge regression with the rlm function?
Or should I check whether there's an quadratic relation?
...
Comment: I've taken R out of the title. What software you are using or might use is secondary to the question.
Answer: The scatterplot shows a bunch of problems that indicate that regular regression will not be a good way of capturing the relationship:
1) Both variables are right skew
2) The variable on the y-axis appears to be bounded by 0 and 1 - is it a proportion?
3) There are "bands" in the plot.
4) No straight line comes close to showing the relationship.
So, what to do?
The problem is not just outliers and removing some outliers is unlikely to solve the problems.
If the 0's on the Y variable are indicative of problem data, you might want to remove them. It's hard to know without context. If you remove them, then it might be sensible to take logs of both variables. If you don't remove the 0's then it is possible to add a small value and then take logs, but this always strikes me as arbitrary.
A smoothed regression (loess or splines or something similar) might be useful on the untransformed variables.
More context will definitely help.
Comment: @PeterFlom Wouldn't it be better to model the absolute values using Poisson regression? The bands in the plot are a result of only a discrete set of percentage values being possible for a given word count.
Comment: I see no reason to believe that you should strain towards a model. Echoing @PeterFlom, I'd start with some smooth of response given predictor and perhaps stop with that. For example, if the smooth is nearly flat, there is no relationship to model. Pedantic point: if something is shown as a proportion between 0 and 1, please don't call it a percent[age]. People here should all know the difference (or the identity), but using the less appropriate word is a minor distraction.
Comment: Hello! Thanks for the answer. The context of the problem is the following: There are 6000 documents. I've deleted some words out of these documents because it was garbage. So on the x-axis, you can read how many words a document contains BEFORE removing. On the y-axis, you can read how many (percent) garbage there is. Now I want to check if there's a relationship betweens how many words the documents contained en how many words that were removed in that document
Comment: You might want to look into beta regression, which deals with bounded dependent variables.
Answer: Your plot is pretty consistent with proportion data with varying denominator. That is, the error in the estimate of the proportion of bad words is more variable in documents with fewer words to begin with, and the runs of curvy lines are a result of the discrete nature of the outcome.
A useful addition to the plot for exploratory purposes is to add a funnel for the confidence intervals of the global percentage given the varying number in the denominator. See Funnel plots for comparing institutional performance (Spiegelhalter, 2005), PDF Here, for a fuller description of funnel plots.
Here is a brief example in R for somewhat similar data (at least in the total estimated proportions and the range of document sizes).
x <- trunc(runif(500,1,150)) #generate vector of integers
pop_prob <- 0.2              #population probability
suc <- sapply(X=x,rbinom,n=1,prob=pop_prob,simplify=TRUE)
prob <- suc/x                #fake data to mock yours

plot(x,prob)                 #base plot

#generate 99% confidence intervals based on overall probability of pop_prob
alph <- 0.01
seq <- 1:(max(x)+5)

#via http://r.789695.n4.nabble.com/inverse-binomial-in-R-td4631935.html
invbinomial <- function(n, k, p) {
   uniroot(function(x) pbinom(k, n, x) - p, c(0, 1))$root
}

low <- mapply(invbinomial,n=seq,k=seq*pop_prob,p=1-alph/2)
high <- mapply(invbinomial,n=seq,k=seq*pop_prob,p=alph/2)

lines(low,col='red')              #low and high funnel lines
lines(high,col='red')

The lines give a better sense of the typical error, allow you to identify outliers, and also provide a guide on whether the proportions in the higher range are perhaps trending upwards or downwards, or more generally provide graphical evidence that the observed set of proportions come from a mixture of different processes. (As an example, one might see a trend for higher homicide rates in police jurisdictions with larger populations in a blog post I write, which is pretty consistent with criminological literature).
Note that with many observations you would expect a few points outside the bands simply by chance (as can be seen in my example), but they provide a useful exploratory guide nonetheless.

Analyze scatter plot


Derive Euler angles derivative from angular velocity

Question: I am using a robotics simulator named V-Rep. In V-Rep Euler angles $\alpha$, $\beta$ and $\gamma$ describe a rotation composed by three elemental rotations:
$$Q=R_x(\alpha) R_y(\beta) R_z(\gamma)$$
where $R_x$, $R_y$ and $R_z$ represent elemental rotations about axes $x$, $y$ and $z$ respectively of the absolute reference frame.
If the angular velocity of an object, whose orientation with respect to the reference frame is described by the Euler angles above, is $\omega=[\omega_x,\omega_y,\omega_z]$ with respect to the reference frame, then am I right to say that $\dot \alpha=\omega_x$, $\dot \beta=\omega_y$ and $\dot \gamma=\omega_z$ ?
Answer: No, Euler angles are a poor choice for representing the orientation. Apart from that not all orientations can be represented it complicates the calculations.
What you instead could do is to use quaternion representation of orientation or use a rotation matrix. That would make the maths more easy, the relation between angular velocity and orientation is $\omega q = {1\over 2}{d\over dt}\operatorname{vec}(q)$, where $\operatorname{vec}(q)$ is the vector part of the quaternion.
Comment: @LukeHutchison Thanks for pointing that out. I've checket into the relation and corrected it (so hopefully I got it right this time)
Comment: At first squint that almost looks right; however, it probably is not correct, because quaternion differentiation does not follow the chain rule, since quaternion multiplication is not commutative. See "pure exponential derivative" here: http://www.neil.dantam.name/note/dantam-quaternion.pdf
Answer: If you have the individual Euler angles, produce three quaternions (using an axis-angle to quaternion conversion function) representing rotations of each Euler angle around each corresponding axis, and multiply the three quaternions together in the appropriate order so that they form a quaternion product that represents the same rotation as $Q$. Or if you have only the final rotation matrix, you can convert it into a quaternion using this method:
https://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/
Then to calculate the angular velocities with respect to the local reference frame, you have to differentiate this quaternion over time. See equations (1) and (2) in the answer here:
Converting from quaternion to angular velocity then back to quaternion
Or this cheat sheet might help (see "Finite Difference" and then "Logarithm" for quaternions):
http://www.neil.dantam.name/note/dantam-quaternion.pdf


NN Classifiers: Can inputting a known normal example alongside the example to classify assist classification?

Question: As an (overly simplified) example, lets say I have some samples of audio, and each sample only has either sine, square, or triangle waves. The waves will appear as either normal or abnormal.
The goal is to classify each wave in the sample as normal or abnormal. The problem is that a normal triangle wave and a abnormal sine wave look very similar, and our model is struggling to learn features to differentiate the two.
Would it be beneficial to pass an example normal wave from elsewhere in the sample as an additional input? Like telling the model: "for this sample, a normal wave looks like this: ^--^--".
I'd like to know if additional context information like this can help a classifier make a correct decision. I haven't been able to find any papers relating to this, so any would be appreciated.
Comment: do you know what wave-type each sample is in (sine/square/triangle) at test time? do all the waves have the same period and phase? even if not i suspect it would be pretty easy to normalize them to have roughly the same period and phase -- would you agree?
Comment: The example is not my actual problem, just a demonstration. I've edited to clarify. Normalizing is not an option for my dataset. At test time there will be at least one known normal wave available, and the goal is to identify the rest of the waves as normal/abnormal.
Comment: do you know what wave-type each sample is in (sine/square/triangle) at test time? otherwise how can you find a matching normal wave as additional input?
Comment: A normal wave would be selected by a human
Answer: It might be beneficial to split the problem: you might train a first network, that differentiates sine, triangle and square waves. Then, for each class, you may train another model, that operates solely on one class and checks, whether the data are normal or not.


Numpy object arrays

Question: I've recently run into issues when creating Numpy object arrays using e.g.
a = np.array([c], dtype=np.object)

where c is an instance of some complicated class, and in some cases Numpy tries to access some methods of that class. However, doing:
a = np.empty((1,), dtype=np.object)
a[0] = c

solves the issue. I'm curious as to what the difference is between these two internally. Why in the first case might Numpy try and access some attributes or methods of c?
EDIT: For the record, here is example code that demonstrates the issue:
import numpy as np

class Thing(object):

    def __getitem__(self, item):
        print "in getitem"

    def __len__(self):
        return 1

a = np.array([Thing()], dtype='object')

This prints out getitem twice. Basically if __len__ is present in the class, then this is when one can run into unexpected behavior.
Comment: @astrofog That's why I asked and said it wasn't related.
Comment: Not related, but why `np.object` and not just `object`?
Comment: The two are equivalent (``object == np.object`` returns ``True``) so this is not related to the issues I'm seeing.
Comment: BTW, I don't think one can solve your problem without seeing the class and some error messages.
Comment: [Possible duplicate](http://stackoverflow.com/questions/2641701/storing-record-arrays-in-object-arrays)
Answer: In the first case a = np.array([c], dtype=np.object), numpy knows nothing about the shape of the intended array.
For example, when you define
d = range(10)
a = np.array([d])

Then you expect numpy to determine the shape based on the length of d.
So similarly in your case, numpy will attempt to see if len(c) is defined, and if it is, to access the elements of c via c[i].
You can see the effect by defining a class such as
class X(object):
    def __len__(self): return 10
    def __getitem__(self, i): return "x" * i

Then
print numpy.array([X()], dtype=object)

produces
[[ x xx xxx xxxx xxxxx xxxxxx xxxxxxx xxxxxxxx xxxxxxxxx]]

In contrast, in your second case
a = np.empty((1,), dtype=np.object)
a[0] = c

Then the shape of a has already been determined.  Thus numpy can just directly assign the object.
However to an extent this is true only since a is a vector.  If it had been defined with a different shape then method accesses will still occur. The following for example will still call ___getitem__ on a class
a = numpy.empty((1, 10), dtype=object)
a[0] = X()
print a

returns
[[ x xx xxx xxxx xxxxx xxxxxx xxxxxxx xxxxxxxx xxxxxxxxx]]

Comment: This is exactly what I needed - basically if ``__len__`` is defined then that is when I run into issues!

Numpy object arrays


Hypothesis testing- how to find a p-value?

Question: I cannot get my head around a statistics issue.
So I have run a test with 10 participants as a basic short memory test. It was found that the mean difference in correct answers to the test between before and after treatment was 2.4 with a standard deviation of 0.8. My null hypothesis is that the difference in the wider population would be <2.4 and my alternative is that the difference would be greater or equal to 2.4.
How would I go about getting a p-value in this case?
Any help would be much appreciated
Comment: How is it that your hypothesis happens to have exactly the same number as the difference in your sample? Did you base the hypothesis of the results of the experiment?
Answer: It is more usual in a case like this to let the null hypothesis be that there is no effect of the treatment. The alternative is then that the effect is positive (one-sided test) or that there is an effect at all (two-sided test).
Now let's assume the difference is zero and normally distributed. The p-value is then how surprised you are to see 2.4 as the actual mean, and 0.8 as the actual standard deviation of your sample.
Much simplified, we estimate the standard deviation of the mean of such a sample to be 0.8 (over the whole population), we find a mean of 2.4, which is 3 times the standard deviation, so the p value is roughly 0.01 (using the one-sided test).
That is the amount of samples from a normal distribution with standard deviation 0.8 that exceed the value 2.4, or in the graph below, the surface under the density (the probability), right of the red line.

It is useful to understand this procedure, but you should be aware that this is just a model, where you assume that everything is normally distributed, there are no selection issues in your data gathering and so on. All of these things are never actually true, and it takes common sense, an understanding of the underlying real-world problem, and statistical understanding to define a level of trust in these findings. Even with all of that expertise, many errors are made.
A more technical problem is that estimating the standard deviation of your population, and also the mean, actually introduces more uncertainty than is estimated here.
Comment: Hi again,

Apologies, really struggling to understand the whole topic. I have found that I should know the "population mean" in order to find the p-value, however I am not sure how I could know the population mean as I only have the sample mean for this treatment.

I would like to state the null hypothesis as "no effect" and the alternative hypothesis as "some effect (whether positive or negative)". Would you be able to explain this in a formula?

Thank you for your help!
Comment: Hey Terip, no problem, but I think you can best just read a bit on the topic. Maybe start with Wikipedia! https://en.wikipedia.org/wiki/P-value.
Answer: The statistic you have used is $$t = \frac{d - d_0}{sd(d)}$$ which theoretically under the null hypothesis follows the t distribution with $n-1$ degrees of freedom. We suppose that all the basic assumptions are valid for that paired t-test. Then, p-value is the probability $$P[t_{n-1} > t^{obs}] = P[t_{9} > \frac{2.4 - 2.4}{0.8}] = P[t_{9} > 0] $$ which is of course 0.5 because the $t$ distribution is symmetric. In case of not having the value $t^{obs} = 0$, you should compute p-value with a statistical software. In R for example we take
<code>tobs = 0
1-pt(tobs,9)
[1] 0.5
</code>
I hope I helped you.


Creating a for Loop in bs4 for Ebay listings

Question: I have the following code that goes to an ebay url and extracts the name of a listing and sale price, see below:
from urllib.request import urlopen
from bs4 import BeautifulSoup
import request

html = urlopen('https://www.ebay.com/sch/i.html?_from=R40&_nkw=manga&_sacat=0&rt=nc&LH_Sold=1&LH_Complete=1')
soup = BeautifulSoup(html.read(), 'html.parser')

soldItem = soup.find('h3', class_='s-item__title s-item__title--has-tags')
salePrice = soup.find('span', class_='POSITIVE')

#data = soup.find('div', class_='s-item__info clearfix')

itemData = {soldItem.get_text():salePrice.get_text()}

I want to create a for loop that iterates over the first page and gives me the name and sale price of every listing.
However, every single attempt that I've made returns either the same listing five times or all sold items and thereafter all sale prices.
Any hints as to how to format my for loop ?
Answer: You can try this code that will create all items and their prices in a dictionary by the key of the item name and the value of the price.
from urllib.request import urlopen
from bs4 import BeautifulSoup
import requests

html = urlopen('https://www.ebay.com/sch/i.html?_from=R40&_nkw=manga&_sacat=0&rt=nc&LH_Sold=1&LH_Complete=1')
soup = BeautifulSoup(html.read(), 'html.parser')

soldItem = soup.find_all('h3', class_='s-item__title s-item__title--has-tags')
salePrice = soup.find_all('span', class_='POSITIVE')

itemsData = {item.text: price.text for item, price in zip(soldItem, salePrice)}

print(itemsData)

Comment: well that's one way to solve my problem, I still have a problem with creating the for loop. that being said can you go over your variable named itemsData, idk why that works
Comment: I'm not sure what is required can you provide a bit more details?
Comment: thanks for your help ! No worries, I was able to find the answer to this problem. I'll have to study your reply in more detail to see why it works. Thanks


DNN 8 unable to install extension

Question: I created my module and it used to work properly but after uninstalling I get this error:
<code>AbsoluteURL:/Default.aspx

DefaultDataProvider:DotNetNuke.Data.SqlDataProvider, DotNetNuke

ExceptionGUID:0fe3f4ae-48e2-4d82-818b-b4e0cb639672

AssemblyVersion:8.0.3

PortalId:0

UserId:95

TabId:36

RawUrl:/Host/Extensions/tabid/36/ctl/Install/rtab/36/portalid/0/language/en-US/Default.aspx?popUp=true

Referrer:http://localhost/Host/Extensions/tabid/36/ctl/Install/rtab/36/portalid/0/language/en-US/Default.aspx?popUp=true

UserAgent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36

ExceptionHash:Lv0u7/ELvn42FpwfPTPUTQ==

Message:The system cannot find the file specified.

StackTrace:

InnerMessage:The system cannot find the file specified.

InnerStackTrace:

   at SchwabenCode.QuickIO.Internal.InternalQuickIOCommon.NativeExceptionMapping(String path, Int32 errorCode)
   at SchwabenCode.QuickIO.QuickIOFile.OpenFileStream(QuickIOPathInfo pathInfo, FileAccess fileAccess, FileMode fileOption, FileShare shareMode, Int32 buffer)
   at SchwabenCode.QuickIO.QuickIOFile.OpenText(QuickIOPathInfo pathInfo)
   at DotNetNuke.Common.Utilities.FileSystemUtils.ReadFile(String filePath)
   at DotNetNuke.Services.Installer.Installers.PackageInstaller.ReadTextFromFile(String source)
   at DotNetNuke.Services.Installer.Installers.PackageInstaller.ReadManifest(XPathNavigator manifestNav)
   at DotNetNuke.Services.Installer.Installers.PackageInstaller..ctor(String packageManifest, InstallerInfo info)
   at DotNetNuke.Services.Installer.Installer.ProcessPackages(XPathNavigator rootNav)
   at DotNetNuke.Services.Installer.Installer.ReadManifest(Boolean deleteTemp)
   at DotNetNuke.Modules.Admin.Extensions.Install.wizInstall_NextButtonClick(Object sender, WizardNavigationEventArgs e)
   at System.Web.UI.WebControls.Wizard.OnNextButtonClick(WizardNavigationEventArgs e)
   at System.Web.UI.WebControls.Wizard.OnBubbleEvent(Object source, EventArgs e)
   at System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args)
   at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
Source:

FileName:

FileLineNumber:0

FileColumnNumber:0

Method:
</code>
Do you know why this would happen? I tried to install it several times. I am going crazy over this error. I am using DNN 8. The above is what I see in Event viewer. If any more details is needed please let me know.
Comment: it seems the uninstall removed more that it should have. Can you add the files from the module manually to the `bin` and `/DesktopModules/YourModule` and see what happens. But try to find out which file is missing.
Comment: Thanks the license.txt file was missing. After I put it back it worked as normal.
Answer: When an install happens, it extracts the zip file to a temporary location before processing it using the manifest file (.dnn).
Ensure the following:

Permissions are set correctly to allow the service account running DNN To write to a temporary location
Ensure the contents of your manifest file matches the contents of your module zip install file

DNN 8 unable to install extension


I can't post because it says: "This post does not meet our quality standards." Where are the quality standards explained?

Question: I want to ask: "Is there a version or analogue of Gibbard's theorem for voters with cardinal utility functions?" but I can't.
What should I do?
Where can I read the quality standards?
Why isn't this error message more informative?
Answer: Thanks for coming to our community. The filter that is blocking your post is set at a global level by the Stack Exchange network, and is not under the control of the Economics Stack Exchange community. You can read more about the filter here, including the kinds of things that can trigger this message:
What can I do when getting "This question body does not meet our quality standards"?


Jquery datapicker block some date

Question: I have to field start date and end date. How to make in end date, user can select date only more from start day, like in screen

this my js where I call data picker for my input
$(document).ready(function () {
    var $task_executions_from_date = $('#task_executions_from_date');
$task_executions_from_date.datepicker({
    dateFormat: 'dd.mm.yy'
});

$task_executions_from_date.on('change', function () {
    var test = $task_executions_from_date.val();
    console.log(test);
});

var $task_executions_to_date = $('#task_executions_to_date');

$task_executions_to_date.datepicker({
    dateFormat: 'dd.mm.yy',
    beforeShowDay: function(date){
        var arrayDate = $task_executions_from_date.val().split('.');
        var start_date = new Date(arrayDate[2], arrayDate[1]-1, arrayDate[0]).getTime();
        if (start_date) {
            return date.getTime() > start_date;
        }

        return true;
    }
});

what need put in beforeShowDay for task_executions_to_date.datepicker ? like all days which > test
Now I have all date disabled, why not understand
Comment: Possible duplicate of [Jquery UI datepicker. Disable array of Dates](http://stackoverflow.com/questions/15400775/jquery-ui-datepicker-disable-array-of-dates)
Comment: ok `beforeShowDay` for visible day, but how get select date from `start_date` and create array with all date with > select date from `start_date` ?
Comment: just read the field value with `.val()`.
Comment: I get start date `    $task_executions_from_date.on('change', function () {
        var test = $task_executions_from_date.val();
        console.log(test);
    });
    ` how to select all date which more test ?
Comment: I update my question
Answer: Have a look to https://jqueryui.com/resources/demos/datepicker/date-range.html.

$(document).ready( function() {
  var dateFormat = "mm/dd/yy",
    from = $( "#from" )
      .datepicker({
        defaultDate: "+1w",
        changeMonth: true,
        numberOfMonths: 3
      })
      .on( "change", function() {
        to.datepicker( "option", "minDate", getDate( this ) );
      }),
    to = $( "#to" ).datepicker({
      defaultDate: "+1w",
      changeMonth: true,
      numberOfMonths: 3
    })
    .on( "change", function() {
      from.datepicker( "option", "maxDate", getDate( this ) );
    });

  function getDate( element ) {
    var date;
    try {
      date = $.datepicker.parseDate( dateFormat, element.value );
    } catch( error ) {
      date = null;
    }

    return date;
  }
} );
body {
  font-family: Arial, Helvetica, sans-serif;
}

table {
  font-size: 1em;
}

.ui-draggable, .ui-droppable {
  background-position: top;
}

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

From
<input type="text" id="from" name="from">
to
<input type="text" id="to" name="to">
Answer: You could use a date range picker like this one: http://tamble.github.io/jquery-ui-daterangepicker/
Comment: I need visible all date which > `task_executions_from_date.val()`

Jquery datapicker block some date


I have column with value (200ML) and I need to separate the (ML) from the column

Question: I have column with value (200ML) and  I need to separate the (ML) from the column !
Comment: Ok, what the code you have already tried and what was wrong with it?
Comment: This is a bad design.  You should separate values from their units.  Two columns, not one.
Answer: I assume you mean that you want the leading numeric portion and the trailing alpha portion of the string '200ML' to be returned as separate columns. If that's correct you can use REGEXP_SUBSTR to do this:
SELECT REGEXP_SUBSTR(TEXT_STRING, '^[0-9]+', 1, 1) AS LEAD_NUMERIC,
       REGEXP_SUBSTR(TEXT_STRING, '[A-Za-z]+$', 1, 1) AS TRAILING_ALPHA
  FROM TABLE_A

db<>fiddle here


Why doesn't $P(A\cup B \cap C) = P(A) + P(B\cap C) - P(A\cap B \cap C)$?

Question:
Why doesn't $P(A\cup B \cap C) = P(A) + P(B\cap C) - P(A\cap B \cap C)$?

I understand that this isn't true looking at a Venn diagram, but mathematically it doesn't make sense if $P(A\cup B) = P(A) + P(B) - P(A\cap B)$.
Comment: More generally, $A\cup (B\cap C)\neq (A\cup B)\cap C.$
Comment: It is true if the left side is $P(A\cup(B\cap C))$, but this is $P((A\cup B)\cap C)$.
Comment: Looks true to me, under a reasonable assumption about what $A \cup B \cap C$ means. What makes you think it's not true?
Comment: @ThomasAndrews Why do you say that it is $P((A\cup B)\cap C)$? If we agree that there is a rule, intersections should always come first (as with the usual operations). Otherwise, we should agree that there is no rule.
Comment: I know of no standard "order of operations" between $\cup$ and $\cap,$ which means "left to right" is the default.  @JohnB In any event, the OP said that when he draws the venn diagram, it is obviously false, so I suspect the OP is interpreting it as left-to-right when drawing the Venn diagram.
Comment: And why do you think $\cap$ is like $\times$ and $\cup$ is like $+?.$  $+$ and $\times$ and exponentiation rise in complexity, while $\cap$ and $\cup$ are dual operations - neither primary. @JohnB
Comment: That's absurd. You have only asserted it is the canon. I also assert that my impression of the facts is the canon. And I gave a reason why neither should be given precedence. "I declared it canon first" is hardly an argument. If it is canon, you should be able to provide some evidence or a reason.  This answer suggests $\cap$ and $\cup$ are at the same precedence level. I haven't found any page that agrees with your assertion. https://www.quora.com/What-is-the-precedence-of-set-operations @JohnB
Comment: That makes a lot more sense. I didn't know that order mattered. Thank you very much!
Comment: Gonna have to provide a reference better than just "I say so." @JohnB
Comment: Actually you should provide some reference for the unsupported claim in your first comment that it is in the other way. Why should it be as you say?
Comment: @JohnB Another example: "1. Evaluate complement first
2. Evaluate $\cup$ and $\cap$ second." https://www.uow.edu.au/~bmaloney/wuct121/LogicWeek8Lecture1.pdf
Answer: It is true that $$P(X\cup Y) = P(X)+P(Y)-P(X\cap Y).\tag{1}$$
And if we substitute $X=A, Y=B\cap C$ blindly, that would seem to mean:
$$P(A\cup B\cap C) = P(A)+P(B\cap C) - P(A\cap B\cap C).$$
But that is an improper substitution. In the text, we have to substitute $(B\cap C)$ into the formula for $Y.$

A numeric example
We know that $3\times 2 = 6$ and that $2=1+1.$ But we can't just replace the string $2$ in the first expression with the string $1+1$ and get:
$$3\times 1+1 = 6\quad\color{red}{\text{wrong}}$$
We have to replace $2$ by $(1+1)$ to get:
$$3\times(1+1) = 6\quad \color{green}{\text{correct}}$$

So it is true that, from $(1)$, we get:
$$P(A\cup(B\cap C))=P(A)+P(B\cap C) - P(A\cap B\cap C)$$
but it is not true that:
$$P((A\cup B)\cap C) =P(A)+P(B\cap C) - P(A\cap B\cap C)$$
and $A\cup B\cap C$ is normally interpreted as $(A\cup B)\cap C,$ and it is not, in general, true that:
$$(A\cup B)\cap C=A\cup (B\cap C).$$

The standard notation we use, where we put operators like $+$ and $\times$ and $\cap$ and $\cup$ in between operands is called "infix notation." Infix notation does not play well with string substitution.
Another notation, reverse Polish notation, actually does okay with string substitutions. If we write $3,2,\times = 6$ and $2=1,1,+$ then we can replace the $2$ in the first expression with $1,1,+$ and still get a valid equality:
$$3,1,1,+,\times=6$$
(I  use infix $=$ because $=$ is not a operator, but we could be more pedantic.)
Comment: There's a typo in $(1)$, last term should be substracting...
Comment: Thanks @leonbloy


Extrapolate NaN values in a numpy array

Question: I have two values and know their index in an array full of nans. I want to interpolate / extrapolate all the nan's
import numpy as np
y = np.array([np.nan, np.nan, 0.75, np.nan, np.nan, np.nan, np.nan, np.nan, 2.25])

With the help of this answer I write the following:
nans, x = np.isnan(y), lambda z: z.nonzero()[0]
y[nans] = np.interp(x(nans), x(~nans), y[~nans])

My output looks as follows:

[0.75 0.75 0.75 1.   1.25 1.5  1.75 2.   2.25]

However, I would like it to be:

[0.25 0.5 0.75 1.   1.25 1.5  1.75 2.   2.25]

The increment is always a constant.
When I read the documentation of np.iterp I see that I can specify the input-parameters left and right. If I don't specify left, the value to return for x < xp[0] is fp[0].
How can I specify left and right in order to get the desired output?
Answer: np.interp doesn't seem to make extrapolation,
but scipy.interpolate.interp1d does.
The arguments to give are a bit different, you can make it a function for your particular case:
import numpy as np
from scipy.interpolate import interp1d

def interp_nans(y, x=None):
    if x is None:
        x = np.arange(len(y))
    nans = np.isnan(y)

    interpolator = interp1d(
        x[~nans],
        y[~nans],
        kind="linear",
        fill_value="extrapolate",
        assume_sorted=True,
    )

    return interpolator(x)

Check that it works:
y = np.array([np.nan, np.nan, 0.75, np.nan, np.nan, np.nan, np.nan, np.nan, 2.25])
expected = np.array([0.25, 0.5, 0.75, 1.0, 1.25, 1.5, 1.75, 2.0, 2.25])

result = interp_nans(y)

assert np.array_equal(result, expected)

Answer: You can't specify left and right to achieve extrapolation with interp, they are just constant values.
If you prefer a pure numpy solution, you can linearly extrapolate based on the first/last two values of the interpolated array:
def extrap(x, xp, fp):
    m = (fp[1] - fp[0]) / (xp[1] - xp[0])
    n = fp[0] - m * xp[0]
    result = m * x[x < xp[0]] + n
    m = (fp[-1] - fp[-2]) / (xp[-1] - xp[-2])
    n = fp[-1] - m * xp[-1]
    return np.concatenate([result, m * x[x > xp[-1]] + n])

(you may want to add verification of len(xp) > 1 and len(xp) == len(yp))
Example:
y = np.array([np.nan, np.nan, 0.75, np.nan, np.nan, np.nan, np.nan, np.nan, 2.25, np.nan])

nans, x = np.isnan(y), lambda z: z.nonzero()[0]
y[nans] = np.interp(x(nans), x(~nans), y[~nans], np.nan, np.nan)

nans, x = np.isnan(y), lambda z: z.nonzero()[0]
y[nans] = extrap(x(nans), x(~nans), y[~nans])

Result
array([0.25, 0.5 , 0.75, 1.  , 1.25, 1.5 , 1.75, 2.  , 2.25])

Extrapolate NaN values in a numpy array


Porque eu não consigo maximizar a janela no segundo monitor?

Question: Estou tentando maximizar a janela do wpf no segundo monitor, mas a janela fica maximizada no monitor principal quando inicia.
Se eu tirar a linha que maximiza a janela vai aparecer no segundo monitor normalmente, mas vai ter pequenos espaços e não vai estar totalmente preenchido. Eu precisava maximizar no segundo monitor, inclusive sobrepor a barra de tarefas.
Eis o código
public partial class View02 : Window
{
    public View02()
    {
        InitializeComponent();
        showInMonitor(1, this);
    }

    public void showInMonitor(int monitor, Window window)
    {
        List<Screen> screens = Screen.AllScreens.ToList();
        if (screens.Count > 1)
        {
            Screen screen = screens[monitor];
            if (!window.IsLoaded)
                window.WindowStartupLocation =
            WindowStartupLocation.Manual;
            window.Left = screen.WorkingArea.Left;
            window.Top = screen.WorkingArea.Top;
            window.Width = screen.WorkingArea.Width;
            window.Height = screen.WorkingArea.Height;
            window.WindowStyle = WindowStyle.None;
            window.WindowState = WindowState.Maximized;
        }
    }
}

Porque esse código não maximiza a janela no segundo monitor??
Answer: Em WPF, se vc define o WindowState para Maximized, seja no XAML ou no construtor, então a sua janela sempre vai aparecer no monitor principal e não no secundário.
Para isso eu estive vendo esse site
Ali mostra que precisamos maximizar a janela depois que ela é carregada
private void Window_Loaded(object sender, RoutedEventArgs e) {
    WindowState = WindowState.Maximized;
}

Comment: Obrigado, salvou meu dia!


Can you create a view to display all files within a certain directory?

Question: I have a Node Type A that is referred to by a bunch of other nodes. Within the nodes that are referring to Node Type A, there are various and separate CCK file fields. I have configured all of these files to be saved in a directory that is named with the title of each Node Type A (with the FileField Paths module)...so all of the corresponding files for a Type A node are in one place. I need to create a view that displays all of the files from the referring nodes in a sortable table. The problem that I'm running into, is that I have to add each separate CCK file field from an assortment of different node types to the view, which generates empty fields in the rows ouput.
So can I build a view that pulls the files from a specific directory on the server?
Answer: Only tools I've seen dealing with showing file are more like this...
http://drupal.org/project/elfinder
http://drupal.org/project/webfm
http://drupal.org/project/manager
http://drupal.org/project/filebrowser
You can create a view of all attachments to nodes, but that's not what you want either.
Answer: In Drupal 7 you can create a view of files, with path as one of the available filters.
In Drupal 6 the Table Wizard and the Data allow you to pull database tables in to views, so it's an extra step but perhaps you could create a table to maintain a list of files and their paths then use one of these modules to create a view.
Comment: You can create a view of files and add a filter where path contains a string in Drupal 6 views too.
Comment: That works. Post your comment as an answer if you want the points.
Answer: Look at the Style Settings/Theme Information on your view and dive into the Row style output template for your view.  You most probably can throw some php code in there to skip the empty fields...
Answer: As Jim Kirkpatrick said, you want to create a new View selecting "Files".
Then in the Filters you enter the path you want to view (you could also use attributes, if you have very many node types, it would be faster but requires you to enter the node type in the view path... although you can later hide that using URL aliases.)
Note that only works for files that appear in the Drupal Core file upload table. Any other file is not known by the system and thus won't just show up in the view.
Comment: That works! I'll mark your answer as correct unless Jim moves his comment into the answers.
Comment: a long shot since this is such an old thread, but am failing to see a key piece of the puzzle. D7. I have a 'files' based View. In the list of files I  note that some subfolders of root (eg public://feeds) have their files listed, but others such as public://images do not. any thoughts?
Comment: @petednz-fuzion I'm not using Drupal anymore, so I have no clue where it's at. In the old days, we did not have the protocol (public: and private:). Actually, it was problematic. You could have a site with files that are either all public or all private...
Comment: thanks for responding.
Answer: From another drupal.stackexchange answer, this module called Filebrowser looks like an ideal solution (I've yet to test) for discrete folder listing of files. From the Filebrowser project page:

You will create one node (node type dir_listing) for each each
  Directory Listing (DL). Node settings are used to control access and
  other features of the DL. These settings can vary per node and per
  user.
This module offers the following features:
Private downloads so that files (such as PHP files) can be downloaded.
  File blacklists so that specific files can be removed from directory
  listings. Node-based. All features available to nodes, such as path
  aliasing and access control can be applied to directory listings.
  Settings to limit exploration of subdirectories

The latest Filebrowser version 7.x-4.0-rc1 can do multiple file uploads (drag and drop) if the Plupload module along with the Plupload library dependency (ie extract zip file into library folder at sites/all/libraries/plupload) are available. Looks like it offers file meta-information options as well.

The .info file for Filebrowser does not have a Views dependency so it is likely Views contextual filters or Views relationships needs tweaking, or alternately some type of views enhancement module such as the popular EVA - Entity Views Attachment, or block or entity reference module possibly with Context module, could be needed to solve the display/view/layout in cases like this question. Also, depending on the roles/permissions that Filebrowser does, or may not have, coded into this module with its content type, ACL (Access Control Lists) with Content Access might be additional modules for privacy of the custom file listings/nodes.
Kudos to the community developers for this module, that is showing active development activity at the time of this answer. Try to contribute back folks!


GCP Pipeline Datafusion Respond code: 302

Question: while running a data injection pipeline I get the following error :
java.io.IOException: Failed to send message for program run program_run:default.test-to-gcs.-SNAPSHOT.workflow.DataPipelineWorkflow.3 to https://r-clouddatafusion:443/v3Internal/runtime/namespaces/default/apps/test-to-gcs/versions/-SNAPSHOT/workflows/DataPipelineWorkflow/runs/43-b80f-1-99-0ebf/topics/metrics6 Respond code: 302. Error: unknown error
the data is not recovered successfully
Comment: Could you elaborate on what you're trying to do and where you're getting errors? Is it possible to share a screenshot of the data fusion pipeline?
Answer: 302 unknown error usually occurs in case the authentication scope of dataproc IAM account is not wide enough.
If you're using Bigquery or any other GCP service, you need to make sure the dataproc cluster is created with wider scope.
--scope


Como fechar uma "pasta"

Question: Tenho um projecto em Delphi 2010 que quando clico em um botão abre um directório, este é o código:
DirFolder := 'C:\teste';
ShellExecute(Handle, 'open', PChar(DirFolder), nil, nil, SW_SHOWNORMAL);

Abre isto:

Deixo a questão, é possível quando fechar o projecto também fechar essa pasta?
Comment: quando você diz pasta, se refere a pasta do Windows?
Comment: sim pasta do windows, este é o directório dela:
"C:\teste"
Answer: Existem diversas formas de fazer isto, uma delas é usar a função FindWindow para retornar o identificador da janela através do nome da classe ou título.
Para fechar, você pode usar a função SendMessage e usar o sinal WM_CLOSE para indicar que a aplicação deve ser finalizada.
Veja um exemplo:
procedure TForm1.Button2Click(Sender: TObject);
var
  Janela: THandle;
begin
  Janela := FindWindow(nil, 'teste'); // "teste" é o título da janela
  if Janela > 0 then // Se conseguir encontrar a janela
     SendMessage(Janela, WM_CLOSE, 0, 0);
end;

Comment: obrigado pela explicação, era isso mesmo que precisava!

Como fechar uma "pasta"


How to show that $a_n = (1+\frac12)(1+\frac14)\cdots(1+\frac1{2^n})$ converges?

Question: How do I show, using only basic methods, that a product
$$a_n=(1+{1 \over 2}) \cdot (1+{1 \over 4}) \cdot ... \cdot(1+{1 \over 2^n})$$
converges?
I know, that $a_1 = {3\over2}$, and that $a_{n+1} = a_n \cdot (1+ {1 \over 2^{n+1}})$.
Going further:
$$ {{a_{n+1}}\over{a_n}} = 1+ {1 \over 2^{n+1}} > 1$$

Now I can prove by induction, that $a_n$ is monotonically increasing, and is greater than one.
Now, I want to prove, that $a_n$ is convergent. How can I do this? I can't seem to find any sequence greater than $a_n$ with a limit other than + infinity.
Edit
Following @Barry Cipra comment, i tried taking $ln(a_n)$, so:
$$ ln(a_n) = ln((1+{1 \over 2}) \cdot (1+{1 \over 4}) \cdot ... \cdot(1+{1 \over 2^n}))$$
$$ ln(a_n) = ln(1+{1 \over 2}) + ln(1+{1 \over 4}) + ... +ln(1+{1 \over 2^n})$$
$$ ln(a_n) < 1+{1 \over 2}+1+ {1 \over 4}+...+1+{1 \over 2^n} = n +1$$
$$ ln(a_n) < n+1 $$
$$ a_n < e^{n+1} $$
But I still don't know how this gets me any closer to the answer
Comment: Try looking at $\log a_n$ and use the fact that $\log(1+x)\approx x$ for small $x$.
Comment: @BarryCipra updated the question with your method
Answer: It is true that $\ln (x)\le x$ for every $x$, but a sharper inequality is:
$$
\ln (x) \le x-1\qquad{\text{for all $x$}}.
$$
Using this inequality you get
$$\ln (a_n) \le \sum_{k=1}^n \frac1{2^k}\le 1,
$$
which implies that $(a_n)$ is bounded above. From this, along with what you've already established, we deduce that $(a_n)$ converges.


Can thinking-sphinx ransack work together?

Question: Our project is using Ransack at the moment, we are thinking to introduce Thinking-Sphinx. However they both use search keyword. Is any way to use Thinking-Sphinx and Ransack in a same project?
Thank in advance.
Answer: Ransack's search method is just an alias. You can use the ransack method instead.
Instead of:
@q = Person.search(params[:q])
@people = @q.result(:distinct => true)

Use:
@q = Person.ransack(params[:q])
@people = @q.result(:distinct => true)

Person.search should call ThinkingSphinx as usual.
Comment: But what if I`m using it in a single form - so that i would like to have search quiery be separated form ransack params? Should i employ custom params processing or digg into ransack code?


ElasticSearch index template versioning

Question: My application creates an index template on ElasticSearch. Later on, the application is updated and needs to update the index template to support new fields.

Is there a way to set a some identifier for the index template
(except its name which is always the same), such that my app can
compare these values between the app version and the deployed
version? (unique ID / ETag / anything else)
Alternatively, if I can't detect a difference: What is the cost of
modifying the index template multiple times, mostly modifications
that perform no actual change?
Can I find for an index which template it uses (and which version of it,
if such ability exists)?

Thanks.
Answer: When creating an index template, you can use the mapping metadata to store the extra info needed to know from which version of the application the mapping was created.
PUT _template/my_template
{
  "template" : "logstash-*",
  "mappings" : {
      "logs" : {
        "_meta" : {
          "product" : "my_product",
          "version" : "1.0.1"
        },
        "_source" : {"enabled" : "true"},
        "properties" : {
        }
      }
  }
}

Then query for existing indices to find the index last created and then get its mappings.
GET logstash-2015.10.08/_mapping

You'll find the mappings and the metadata inside.
This can be useful to store the version of the product the mapping correlates to.
Comment: Excellent answer! Just what I needed for an automated index mapping update
Answer:
Yes, you can use ElasticSearch's template versioning feature by including "version": <version number> in your template.

Source: https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-templates.html#versioning-templates

There's no cost in modifying the template, as it's just stored in ES's database {read as 'storage used by ES'}. The only difference is that updates to the templates will only be applicable to the new index being created and won't be applied to the existing indices.
Comment: Nice! This answer works on ElasticSearch version 5.0 or higher (released a year after I asked this question :) )
Comment: I see. Just saw the date posted :)
Answer: I've solved for this before by using version numbers, build IDs or time stamps as part of the index name (and using index aliases to point to the relevant index for each application).
See this post for a more detailed example:  https://www.elastic.co/blog/changing-mapping-with-zero-downtime
Comment: I don't know of the Elasticsearch equivalent to a database migration tool.  Since you can retrieve the current mapping from ES, it would be possible to build something like this.  Let me know what you come up with.
Comment: Thanks for the quick reply. This is an interesting article. The indexes themselves are formatted as `logstash-2015.08.31` in my case, so no need to change their names as I am only adding new fields. The problem is detecting a difference between the deployed index template and the one that exists in my application code.
Comment: Perhaps the simple solution would just be a regression test that produces the latest application mapping json, and then requests the latest mapping json from Elasticsearch to compare (failing your deploy if there's a diff?)

ElasticSearch index template versioning


How can I copy multiple nodes and reset fields belonging to the copies in one operation?

Question: I want to copy a list of nodes, create one copy of each node, and at the same time, reset the contents of two fields on each new copy node.
I am using Views Bulk Operations to select the nodes, and Replication with Replication UI to make copies of them.
I think I should be able to reset the two fields on my new copy nodes just with Rules, but I've been unable to work out a Rule that actually works, and several widely linked resources that refer to using VBO with Rules seem to have been deleted recently.
Comment: another way would be to login to the database and empty the fields over there.
Comment: I'm trying to create a system that the site manager can use on her own without my assistance.  Ideally I want just one button that does it all...
Answer: In my opinion is easier if you write the code in a custom module.
You should create a custom form with form api with a button that call a function that select the nodes with db_select and after does the operations, copy :
<code>// Load a node
$node = node_load(1);

// unset version and node id's
unset($node->nid);
unset($node->vid);
unset($node->path);
</code>
and unset values of the two fields for each node and save node
<code>unset($node->field1);
unset($node->field2);
node_save($node);
</code>
After create a custom block and in block_view load the custom form.
Answer: I was trying to fire my Rule on the 'after replication' event supplied by Replication module, but it appears that event doesn't do what you'd think.  My rule wasn't firing at all.
I fired my rule on node creation instead and in the end that worked fine with VBO, although I did consider using a component.
I asked about this on drupal.org and got some helpful comments which I link here in case they are valuable to anyone else.  https://www.drupal.org/node/2254055


Android application to detect when Google maps direction is finished

Question: I am building an android application, that will show certain points on google maps, for which I have (lat,lang) for all the points shown, with me. Whenever, a user clicks on one of these locations on google maps, I am starting a new Google Maps intent which shows navigation to the user and is supposed to take the user to that (lat, lang).
//suppose this function is called on onclick of google maps event
    function onclick(){
            Uri gmmIntentUri = Uri.parse("google.navigation:q=32.885240,-96.763475");
            Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
            mapIntent.setPackage("com.google.android.apps.maps");
            if (mapIntent.resolveActivity(getPackageManager()) != null) {
                startActivity(mapIntent);
            }
    }

This will start the navigation for the user. Now what I want to achieve is this - Whenever this navigation is complete, I want some kind of flag to be passed to my android application, so that my application knows that the navigation has been finished.
If it is possible to automatically close the google maps application after the navigation has been completed, it will be nice to have.
Comment: the google maps app does not return anything when the route has finished
Comment: I think the best you could do would be use `startActivityForResult(mapIntent, num)` and then detect when `onActivityResult()` is called with requestCode of num, this might work to detect if the user clicks back to go back to your app.
Comment: So to confirm my understanding of your answer, this will detect only if the user clicks back to my app, Right? Not when the Google Maps intent has finished navigation. If someone clicks back on my app during the navigation, it will detect that as well which is not what I want. But, thanks, this information may come in handy somewhere else. I did not know this.
Answer: As @Daniel mentioned, you can use onActivityResult() to detect when users are back. However, if you really want to detect if Google maps direction had finished... You can look at the notifications.
So the catch here is, when Google Maps direction is a services, and when it is running, it posts updates to the notifications center.
Which means either you can keep looking at what services are running, or.. get permission to the notifications center and keep checking if Google Maps exists.
Comment: Thanks, this approach may work for me. Let me try to implement this.However, if I find some difficulty in implementing this, I will post a comment here asking for more help.
Comment: @NalinAgrawal Did you try this? Please provide feedback if you did. Thanks!
Comment: No I did not. I stopped developing the project. However, I would only go to this solution if nothing else works. Because this means constant polling, every second which is going to take a lot of cpu cycles and battery consumption. Plus it is dependent on a feature provided by maps. Not by their APIs.
Answer: I think a better answer since you built the intent for navigation and have the coordinates, is to set up geofencing for the destination or any milestone you want in the trip. After that, you can use your IntentService to retrieve your app at the appropriate activity.
https://developer.android.com/training/location/geofencing#java
Comment: That's what I did.


Como multiplicar em Python sem o operador multiplicação?

Question: Tenho uma tarefa e estou com dificuldade em concluí-la. O que fiz foi o seguinte:
m= int(input('Digite o primeiro fator:'))
n= int(input('Digite o segundo fator:'))

def multiplica(numero):
    while m > 0:
        print (n + multiplica (m-1) n)
def multiplicaneg(numero):
    while m < 0:
        print ((-n) + multiplica (m+1) n)

if m or n == 0:
    print (0)
elif m > 0:
    return multiplica
else:
    return multiplicaneg

O que tentei foi criar uma função pra multiplicar e depois, na hora de imprimir, retornar a função com o resultado adequado.
Comment: Muito bom seu código, mas não consegui entende-lo. POderia me explicar o que está acontecendo no código? Porque eu mesma queria fazer o código, entende? Perceber a ideia  e criar os meus :/
Answer: Isso tudo pode ser feito a partir de uma só função e sem recursividade, usando valores absolutos abs():
def multiplica(i, j):
  res = 0
  while i > 0:
      res += j
      i -= 1
  return res

i = int(input('Digite o primeiro fator:')) # 11
j = int(input('Digite o segundo fator:')) # -356

res = multiplica(abs(i), abs(j)) # usamos os valores absolutos de ambos, mais tarde verificamos se vai ser negativo ou positivo
if(i < 0 < j or j < 0 < i):
  res = -res

print('{} * {} = {}'.format(i, j, res)) # 11 * -356 = -3916

DEMONSTRAÇÃO
Caso optes por continuar a usar recursividade:
def multiplica(i, j):
  if(j == 0 or i == 0):
    return i
  return i + multiplica(i, j-1)

i = int(input('Digite o primeiro fator:')) # 11
j = int(input('Digite o segundo fator:')) # -356

res = multiplica(abs(i), abs(j)) - i # usamos os valores absolutos de ambos, mais tarde verificamos se vai ser negativo ou positivo
if(i < 0 < j or j < 0 < i):
  res = -res

print('{} * {} = {}'.format(i, j, res)) # 11 * -356 = -3916

DEMONSTRAÇÃO
Comment: "res += j" ? Nunca tinha visto essa sintaxe, o que significa?
Comment: Estamos a incrementar na própria variável a que estamos a atribuir o valor, é o mesmo que `res = res + j`, neste caso é por facilitismo (escrever menos)
Comment: Muito obrigada, acho que começo a entender o código. Última dúvida: dá pra aproveitar alguma coisa do meu código? :/
Comment: @PaulaJaquelineSilva por lapso meu esqueci-me de cobrir a hipotese de ambos serem negativos (dá positivo), mas está corrigido, dsculpa. No caso desta resposta consegui aproveitar `int(input('Digite o primeiro fator:'))`, o `while` e quase o nome da função d: , e os nomes das variáveis podes colocar como quiseres
Answer: Outra opção é utilizar a função nativa sum:
def multiply(a, b):
    result = sum(b for _ in range(abs(a)))
    return result if a > 0 else -result

Veja funcionando no Repl.it | Ideone | GitHub GIST
Em que será somado o valor de b uma quantidade igual ao valor absoluto de a, independente do sinal de b, pois somar números negativos resulta em um número negativo. A única questão é se deverá inverter o sinal do resultado conforme o sinal de a. Se positivo, mantém o sinal, mas, se negativo, inverte.
Assim:
print(multiply(2, 5))   # 10
print(multiply(-2, -5)) # 10

print(multiply(-2, 5))  # -10
print(multiply(2, -5))  # -10

Answer: Esta questão traz à tona a própria definição de multiplicação.
O que é multiplicação?
A multiplicação nada mais é do que soma de parcelas iguais.
Exemplo 1: Quanto é 2 x 4?
 (2 * 4) == 4 + 4 == 8

Isto significa que 2 x 4 é a soma de 2 parcelas de 4.
Exemplo 2: quanto é 3 x 9?
(3 * 9) == 9 + 9 + 9 == 27

Isto significa que 3 x 9 é a soma de 3 parcelas de 9.
Se aceitarmos a condição que a multiplicação no conjunto dos números reais é comutativa, podemos dizer que:
(2 * 4) == (4 * 2) == 2 + 2 + 2 + 2 == 8

Isto é, 4 x 2 é a soma de 4 parcelas de 2 e...
(3 * 9) == (9 * 3) == 3 + 3 + 3 + 3 + 3 + 3 + 3 + 3 + 3 == 27

Isto é, 9 x 3 é a soma de 9 parcelas de 3.
Agora, com esta explicação fica muito mais fácil implementar um laço de repetição para calcular o produto entre dois fatores sem utilizar o operador de multiplicação.
Se quiser utilizar o laço for para resolver esta questão, pode utilizar o seguinte algoritmo...
f1 = int(input('Digite o primeiro fator: '))
f2 = int(input('Digite o segundo fator: '))

soma = 0
for c in range(f1, f2 + f1):
    soma += f1
print(f'\033[32mO produto é: {soma}')

Observe o funcionamento do algoritmo no repl.it
Observe que f1 é o primeiro fator e f2 é o segundo fator.
Answer: Tenho uma resposta nessa forma, porem funciona apenas para numeros naturais.
n1=int(input("Fator:"))
n2=int(input("Fator:"))
x=1
soma=n1
while x<n2:
    soma=soma+n1
    x=x+1
print(f"Resultado: {soma}")

Comment: Na verdade não funciona para o caso de `n2` ser igual a zero, pois a resposta deveria ser zero e sempre será `n1`


How to include a juery ui file in drupal 7?

Question: In my code for drupal 6 I had added the following js, jquery-ui and css files
 jquery_ui_add('ui.draggable');
  drupal_add_css(drupal_get_path('module', 'ort') . '/js/jquery.alerts.css');
  drupal_add_js(drupal_get_path('module', 'ort') . '/js/jquery.alerts.js');
  drupal_add_js(drupal_get_path('module', 'ort') . '/js/ort.js');

For drupal 7 I have to write the above code..
I have read that drupal 7 has jquery ui as part of core so how should add the
jquery_ui_add('ui.draggable'); //drupal 6

code given above in drupal 7 ?
Comment: http://drupal.stackexchange.com/questions/3947/how-do-i-correctly-add-jquery-ui-widgets?rq=1 or http://drupal.stackexchange.com/questions/26062/adding-jquery-ui-selectmenu-to-drupal-form?rq=1
Answer: It should be drupal_add_library('system', 'ui.draggable');


There is another site pointing to my site without my permission

Question: I have a site 'aaa.com' for instance on a dedicated server. And there is another site 'bbb.com' which became able to display all my site content. It was able to get all the traffic that is coming from google.com to his domain. When I checked its info on who.is, it gave me the same ip address of my server but a different dns.  How could that happen?
Comment: This is a common scam. To defend against this, it is possible to configure the Apache webserver to only show your content when the HTTP request contains the correct HTTP_HOST in the URL. For any other hostname, you can direct the request to a different directory and serve different content (An error message, note from your lawyer, pictures of cats, etc.) See http://serverfault.com/questions/271656/apache-scammers-point-dozens-of-domain-names-at-my-dedicated-ip-how-to-prevent
Comment: What web server are you using?  Everyone's assuming that it's apache.
Comment: @mrdenny Yes it is apache server installed on a rhel 6 server
Comment: Excellent, doesn't hurt to check. Wouldn't want you looking for IIS answers. :)
Answer: It's called DNS. Specifically a CNAME record. A CNAME points to another DNS name. So bbb.com would point to aaa.com which then resolves to an IP address. If people go to bbb.com it resolves to your dedicated server's IP address with aaa.com in the host headers so your web server displays your website. (The last part may or may not be entirely true about host headers and can depend on how Apache is set up)
A while back there was a domain name: the source.ofallevil.com that pointed to Microsoft.com. If you want to http://thesource.ofallevil.com, the URL in the browser would not show Microsoft.com, but the content was purely Microsoft.com. It's all DNS. There is no modification of content, no smoke and mirrors.
To rectify this, you could possibly get a lawyer involved. Just sit back and enjoy the traffic.
Comment: @Manhal: You can't prevent them from pointing to your server. However, you could create an additional Apache configuration for another VirtualHost. In that configuration, you would set the `ServerName` to `bbb.com`. Then *that* configuration would be used for requests that use their redirection.
Comment: DNS CNAME records could be analogized to bookmarks. If you write a book, can you prevent someone from using a certain bookmark in it? Not really. From a technical standpoint, I'm not sure if it's possible. From a legal standpoint, I think you might have a case if you have the time and money to devote to it. Certainly I don't think Microsoft liked thesource.ofallevil.com - and I don't know why that domain no longer resolves, so maybe they send a pointed letter to the owner and he took it down. Maybe you can do the same.
Comment: @OliverSalzburg The virtual server is the best solution as it prevents another domain to access the real site. This should be an answer (and, compared to the current answers, should be accepted..)
Comment: Thanks for the reply. Can't I prevent him from pointing to my server?
Comment: @OliverSalzburg Thank you so much.. your idea solved the problem
Answer: DNS allows any domain to point to any IP. If you really do not want this to happen, then you should set up your web server accordingly...You can have it serve documents to only a certain domain, but as it stands, you are serving to any domain (including the ip, i.e: http://188.8.131.52)


My css is not showing properly using codeIgniter

Question: I'm trying to show css on my table using the codeigniter but it is not working. If I added the css at header part of my html, it works, but the problem is when I created a separate folder for css the design is not working. I do it correctly as I followed the example online.
Here's my code in View:

<title>No title</title>
<link rel="stylesheet" href=<?php echo base_url(); ?>"css/style.css" type="text/css" media="screen" charset="utf-8">

 Super pagination with CodeIgniter

    <?php echo $this->table->generate($records); ?>
    <?php echo $this->pagination->create_links(); ?>

Here's my code in Controller:
    <?php

    class Site extends CI_Controller {

    function __construct() {
        parent::__construct();
    }

    function index() {
        $this->load->library('pagination');
        $this->load->library('table');
        $config['base_url']='http://localhost:81/nine/index.php/site/index';
        $config['total_rows']=$this->db->get('data')->num_rows();
        $config['per_page']=1;
        $config['num_links']=20;
        $config['full_tag_open']='
';
        $config['full_tag_close']='
';

        $this->pagination->initialize($config);
        $data['records']=$this->db->get('data', $config['per_page'], $this->uri->segment(3));
        $this->load->view('site_view', $data);
    }
}

Here's the Autoload:
$autoload['libraries'] = array('database');
$autoload['helper'] = array('url');

Here's the Config
$config['base_url'] = 'http://localhost:81/nine/';

Here's the database
$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '';
$db['default']['database'] = 'datadb';

I don't know if the problem is on the version of the codeigniter. I'm using 2.2.0 while online is 1.7.2.

should be...
Answer: Your stylesheet is incorrectly linked up (watch the double quotes after href):
<link rel="stylesheet" href="<?php echo base_url(); ?>css/style.css">


Determining why file transfers are so slow

Question: I'm trying to transfer large files (3+ gigs each) across the lan. My connection is 100 megabit to the box, with a gigabit backbone. However, when transfering files between servers and from a server to my local computer, transfer speed hovers around 11 to 13 megabits per second.
Large downloads from the Internet, however, go significantly faster.
I have brought up this problem with my network infrastructure folks, but they insist that everything is fine with the network configuration.
Are there any tools out there that I can install on my computer or the servers to try to isolate the source of the slowdown?
Comment: What OS are you on?
Comment: Windows Server 2003/8
Comment: If you were able to find a solution to your problem, would you please edit your question (or leave a comment on the correct solution) with an explanation.
Answer: Firstly check the interface counters on each server, there should be 0 or close to 0 errors reported.
Secondly, check the duplex of both servers. If you are mixing 100mbit and GbE then you may have a duplex mismatch. Ensure that both sides are set to auto/auto, or manually set the speed and the duplex on all interfaces.
Thirdly, what kind of contention is there on the GbE backbone, can you confirm that sufficient headroom exists for your transfer ?
Finally, is your sending server capable of transmitting fast enough. As the comments below suggest, are you limited by the IO bandwidth of the senders drives, or by CPU (if you are using scp or similar) ?
Btw, 11 to 13 mega bytes per second is the theoretical max for 100mbit, are you sure the tool you are using to measure is reporting the correct units?
Comment: Altough I cannot tell you a tool which simply shows you the different throughputs, I have to add something to what Dave Cheney already said. Is your "sending" hard drive fast enough ? Is maybe ssh-compression/encryption tearing down the CPU so much there is no headroom left for NIC/RAID-driver ?
I've had it once that scp was incredibly slow, so I set up a lighttpd simultanously, which ended up to be the FAR faster way.
Comment: Good point, I didn't think of that. You say when sending from server A to server B you get 11-13 mbit, but when receiving from a remote server, you can achieve higher bitrates. I've updated my answer with a simple test of io bandwidth
Answer: Check out the following procedure that I use, which might help narrow down where the problem is.

When I test network throughput, it's best to remove as many variables as possible such as disk i/o or CPU limitations.  Here's the procedure I use, which can illustrate the typical max you will ever see in your network.
Tools:
Both these utilities should be available on most modern *nix systems, either preinstalled, via packages, or able to be compiled from source.

Netcat
PV

Procedure:

Run the following command on one computer to set up the UDP listener.  (Using UDP will give higher performance numbers because of the lack of TCP overhead to transfer.)
nc -ulp 5000 > /dev/null
On the other machine, run the following command, substituting the listener's ip address, to send a stream of zeros across the network to the nc listener.  The pv utility will show the current performance as tracked by the receiver.
pv < /dev/zero | nc -u listener-ip-address 5000

Notes:

The theoretical max on a Gig Ethernet connection is 119MB/s (notice, MB, not Mb)
TCP can also be tested by removing the -u in both nc commands
In real world applications, you'll never reach the performance numbers illustrated in the pv output.

This method gives predictable results in a well designed network with properly functioning equipment.  For that reason, it is a good tool to help discover if the network itself or the networking equipment is contributing to the perceived "slowness".
Answer: Are you on Windows Vista? Note that Vista throttles LAN transfers any time you have a multimedia app open (including a web browser with flash).
I had this issue with transfers being capped at 10MB/s when they should've been xfering at 30-40MB/s.
You can disable the throttling in a registry key detailed here:
http://www.anandtech.com/systems/showdoc.aspx?i=3233&p=2
Answer: Also consider differences in protocol between the two scenarios.  "Large downloads from the Internet" sounds like HTTP or FTP over TCP/IP.  On the LAN, are you using something different?  Perhaps a mismatched set of SMB implementations, or Apple filesharing?  I only mention it because I've seen SMB traffic between Windows and UNIX/Linux systems behave in some really braindead ways.
Try experimenting with different transfer mechanisms and see if that yields different results.
Answer: When you're transferring files 'between servers', are the servers talking directly?
Or, are you in Windows and do you have drives mapped to each server and you're dragging files across those?
In that second scenario, everything is going via your computer, so the fastest transfer you will get will be around 11MBps.
If you're on a *nix system, use ttcp to determine whether your TCP connection is the bottleneck.
Answer: If you are using windows I highly recommend using the free utility RichCopy. It is multithreaded and can pause and resume file copy operations. I have had very good luck using it to transfer files between severs.
Answer: It is a really old tool, but I've had good success with Netperf in the past.  It should give you a starting idea of the bandwidth between two devices.
Answer: Stupid suggestion, but is it possible that the transfer is not happening over the LAN but is actually going out over the internet?  How are you connecting between the machines?  I ask because your symptoms sound similar to those discussed in a recent episode of DotNetRocks.  See the transcript of the solution start reading at:

Carl Franklin:   Yeah.  The Brain Buster, we wanted people to send in their suggestions or the answers they think, to what happened.