Give flagged products in search API a higher search score?

Question: I have a product catalog running on Search API and Search API SOLR Search. Now I was hoping that when a customer flags a product (with the flag module), there would be a way to boost the search score of that particular product.
So that when it is flagged as favorite it will float to the top, but only for that specific user.
How to alter Search API search scores so flagged items will have a higher score?
Answer: You could have a view that shows flagged nodes by user and a view attachment for the index filtering out nodes that the user has flagged.
Comment: That would be more like two views on top of each other right? So theoretically the same product could appear in both Views. I'd like to prevent that if possible.
Comment: Filtering out nodes the user has flagged would take care of that. Add a relationship and then in filter, do a negative on it. I used search api ages ago but I think it's possible.
Comment: That might work, upvote. But I'd still like to know if there is a better way so I'll keep the question for a little longer.
Answer: TLDR; Use the Boost Query (bq) parameter
function mymodule_search_api_solr_query_alter(array &$call_args, SearchApiQueryInterface $query) {
  $call_args['params']['bq'][] = 'im_field_product$flag_favorite_user:"' . $uid . '"^10';
}

There are several things at play that made this question difficult to solve.
At first I was looking at hook_search_api_query_alter() which I didn't understand, only to find out later (thanks to LeDrupaliste) there is also a hook_search_api_solr_query_alter().
Then there was the challenge to sort the results based on the flag. I wanted to return all relevant content, but have favorite (flagged) products returned first. Mostly on the shop landing page (empty search query).
So I needed to sort the results, giving the results with the matching flag and user higher priority. Too bad flag's integration with Search API exposes it as a multi-value field and SOLR is not capable to sort on mutli-value fields.
So in the end the client and I came to agree that we only display flagged products on the empty query page, which was implemented like this:
function mymodule_search_api_solr_query_alter(array &$call_args, SearchApiQueryInterface $query) {
  if (empty($call_args['query'])) {
    $call_args['query'] = 'im_field_product$flag_favorite_user:7^20 OR *:*';
  }
}

If the query is empty, query for the indexed flag field im_field_product$flag_favorite_user where the value matches the users uid 7 in this case and boost the score 20 times to ensure high relevance. To prevent the query from hiding all other results, also include all other non-empty fields *:*.
It is not yet exactly what I wanted, but it is very close. Now I only need to find a way to append this a regular search. Returning all items matching the keywords, but with the favorite onces on top.
$call_args['query'] = 'im_field_product$flag_favorite_user:7^20 OR ' . $call_args['query'];

Above returns the flagged items always first even if no field matches the rest of the query. Undesirable as it provides irrelevant search results.
(i get a yellow product even though I search for a red one)
$call_args['query'] = 'im_field_product$flag_favorite_user:7^20 AND ' . $call_args['query'];

Above returns only results if the product is flagged and contains the correct query fields. No other products matching the query will be returned.
(only red products that are marked favorite are returned)
$call_args['query'] = 'im_field_product$flag_favorite_user:7^20 ' . $call_args['query'];

Same as with AND.
I will update the answer once I've found a way to do this properly.
ps. I've found the field name through the SOLR web interface, but Search API SOLR probably provides it somehow.
UPDATE
In the end I solved it like this:
if (empty($call_args['query'])) {
  $call_args['query'] .= 'im_field_product$flag_favorite_user:' . $uid . '^9 OR *';
}
else {
  $call_args['query'] .= ' AND (im_field_product$flag_favorite_user:' . $uid . '^9 OR *)';
}

It adds a single filter to the query if no query exists, showing all products, but giving priority to the flagged ones. If there is an existing query, we use the AND clause to again select all products and give priority to the flagged ones, but also match it against the existing query so it honors the provided search terms. It is important to match everything (*) in the AND clause otherwise only flagged products are shown.
UPDATE2
I just discovered the Boost Query parameter.

The bq parameter specifies an additional, optional, query clause that
  will be added to the user's main query to influence the score.

So the code has been updated to:
function mymodule_search_api_solr_query_alter(array &$call_args, SearchApiQueryInterface $query) {
  global $user;
  $uid = $user->uid;

  $call_args['params']['bq'][] = 'im_field_product$flag_favorite_user:"' . $uid . '"^10';
}

Answer: Sounds to me like you would need to add this flag to the index. Given that bit of knowledge, it was only about 5 minutes to find this Drupal issue:
Search API: Flag module integration
Which does have a reasonable snippet of code that helps bring out to the index a count of "flags" per node.
<?php
/**
 * Get the flag count for a given node.
 */
function mymodule_get_count($entity, $options, $name, $entity_type, &$info) {
  // Requiring type node since we're relying on $entity->nid,
  // but this could be used for user objects too.
  if ($entity_type == 'node') {
    $query = db_select('flag_counts' ,'fc');
    $query->fields('fc', array('count'));
    $query->condition('fc.fid', $info['data']['flag']->fid);
    $query->condition('fc.content_type', 'node');
    $query->condition('fc.content_id', $entity->nid);
    $count = $query->execute()->fetchColumn();
  }
  return !empty($count) ? $count : 0;
}

/**
* Implements hook_entity_property_info_alter().
*/
function mymodule_entity_property_info_alter(&$info) {
  if (isset($info['node']['bundles'])) {
    // For each content type.
    foreach ($info['node']['bundles'] as $bundle_type => $bundle) {
      // Find all applicable flags for this content type.
      $flags = flag_get_flags('node', $bundle_type);
      // For each applicable flag.
      foreach ($flags as $fid => $flag) {
        $info['node']['bundles'][$bundle_type]['properties']['flag_' . $flag->name . '_count'] = array(
          'label' => t('@title Flag Count', array('@title' => $flag->title)),
          'description' => t('The total number of @title flags for this node.', array('@title' => $flag->title)),
          'type' => 'integer',
          'getter callback' => 'mymodule_get_count',
          'computed' => TRUE,
          'data' => array('flag' => $flag),
        );
      }
    }
  }
}
?>

But this isn't what you would need. You would need a module like commerce_search_api that provides a referenced entity index (commerce uses a product reference field, similar to the way flag references content entities on flag entities). So, your best bet is to:

Start with the commerce_search_api module
Modify the module for flag
Then you should be able to add the user of the flag to your index

Note: I believe Flag is the reverse relationship which might pose an additional challenge to making a modified module do what you need to do.
Comment: The flag is already indexed. This example adds a newly created field containing the flag count to the index. It would have been really useful if I wanted to sort on total number of favorite flags, but I need to match it for the current user only.
Answer: You can try hook_search_api_solr_search_results_alter (or hook_search_api_solr_multi_search_results_alter if you are doing multi index search)
I can't test for now if changing score here alters the results order but you can use your own sort function if necessary (with usort)
Comment: Thanks, but that seems to be giving problems with pagination (on Views). My View only returns a limited amount of products on the first page and I only get that amount of items in the $results array. So if a featured item is on the second (or other) page I would not be able to access it.


Why the default policy of iptables doesn't work?

Question: I wrote some rules to prevent all incomming packet from other computers in my private network except my router. That is why I still want my computer to access the Internet.
This is my rules:
iptables -F
iptables -P INPUT DROP
iptables -A INPUT -m mac --mac-source xx:xx:Xx:xx:xx:xx -j ACCEPT

It is a simple rule. xx:xx:Xx:xx:xx:xx is mac address of the router. I read the document so I know iptables -P INPUT DROP will drop all packets don't match with the below rule. In fact, the rules don't work. I just access to my router but I can not access the Internet. It's difficult to know because I make sure all incomming packets from the Internet come my computer with mac address of my router.
I wrote the rules to fix it:
iptables -F
iptables -P INPUT ACCEPT
iptables -A INPUT -m mac ! --mac-source xx:xx:xx:xx:Xx:xx -j DROP

It works but I would like the idea "deny all, allow selected". It is simpler in configuration and design.
I hope someone makes me clear why the first rules do not work.
Comment: have you tried adding a logging rule to your first set of rules to debug it further?
Comment: Can you elaborate on how you are testing the drop condition? Keep in mind that the INPUT table only applies to traffic destined for *the machine itself*, and traffic that passes between interfaces is subject to the FORWARD table instead.
Comment: Please show all the rules, (with iptables -S) may be the problem is in other place.
Answer: Thank you for your good advices. I found out the cause of the problem. This is my all rule:
-P INPUT DROP
-P FORWARD ACCEPT
-P OUTPUT ACCEPT
-A INPUT -m mac --mac-source xx:xx:xx:xx:xx:xx -j LOG --log-prefix my_rule --log-level 6
-A INPUT -m mac --mac-source xx:xx:xx:xx:xx:xx -j ACCEPT
-A INPUT -i lo -j ACCEPT

Basically, the rule is right except I forgot the last rule for loopback interface. When I surf the Internet, some dns request needed to send to dns service on my computer via loopback interface. If I forget it, I can not resolv any domains.
At first, my solution is add a rule that accept any incomming request has mac address is 00:00:00:00:00:00 because I see this is the mac address of all requests sent via loopback interface but iptables seem not to know. No packet with 00:00:00:00:00:00 is accepted. I read the iptables manual but I still don't see the description of iptables behavior with mac address 00:00:00:00:00:00. I guess iptables think 00:00:00:00:00:00 means 'no mac address'
P/S: I am learning English. Sorry about my mistake in grammar.


"User warning: The following theme is missing from the file system: media in drupal_get_filename()"

Question: What does this error message mean? How can I fix it?

User warning: The following theme is missing from the file system: media in drupal_get_filename() (line 268 of core/includes/bootstrap.inc).
drupal_get_filename('theme', 'media') (Line: 291)
drupal_get_path('theme', 'media') (Line: 394)
Drupal\Core\Asset\LibraryDiscoveryParser->drupalGetPath('theme', 'media') (Line: 85)
Drupal\Core\Asset\LibraryDiscoveryParser->buildByExtension('media') (Line: 87)
Drupal\Core\Asset\LibraryDiscoveryCollector->getLibraryDefinitions('media') (Line: 66)
Drupal\Core\Asset\LibraryDiscoveryCollector->resolveCacheMiss('media') (Line: 149)
Drupal\Core\Cache\CacheCollector->get('media') (Line: 44)
Drupal\Core\Asset\LibraryDiscovery->getLibrariesByExtension('media') (Line: 58)
Drupal\Core\Asset\LibraryDiscovery->getLibraryByName('media', 'form') (Line: 54)
Drupal\Core\Asset\LibraryDependencyResolver->doGetDependencies(Array, Array) (Line: 56)
Drupal\Core\Asset\LibraryDependencyResolver->doGetDependencies(Array) (Line: 31)
Drupal\Core\Asset\LibraryDependencyResolver->getLibrariesWithDependencies(Array) (Line: 104)
Drupal\Core\Asset\AssetResolver->getLibrariesToLoad(Object) (Line: 116)
Drupal\Core\Asset\AssetResolver->getCssAssets(Object, ) (Line: 291)
Drupal\Core\Render\HtmlResponseAttachmentsProcessor->processAssetLibraries(Object, Array) (Line: 161)
Drupal\Core\Render\HtmlResponseAttachmentsProcessor->processAttachments(Object) (Line: 45)
Drupal\Core\EventSubscriber\HtmlResponseSubscriber->onRespond(Object, 'kernel.response', Object)  call_user_func(Array, Object, 'kernel.response', Object) (Line: 111)
Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher->dispatch('kernel.response', Object) (Line: 191)
Symfony\Component\HttpKernel\HttpKernel->filterResponse(Object, Object, 1) (Line: 173)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 68)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 57)
Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 99)
Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line: 78)
Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 50)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23)
Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 664)
Drupal\Core\DrupalKernel->handle(Object) (Line: 19)
Comment: I got this from an incorrect path from an attach_library('was-wrong/libname') call in a twig file.
Comment: I had a similar error when trying to add or edit an image media. I cleared my browser caching and it helped. Can't explain why.
Answer: Had same issue. Resolved with:

search THEME-NAME string in themes folder
remove reference to the useless theme

In my case, I was having
User warning: The following theme is missing from the file system: pxrflx in drupal_get_filename()

This warning disappeard once I removed
libraries:
  - pxrflx/global-styling

from the a_differnt_theme_from_pxrflx.yml file
Comment: Thanks, this helped lead me to the apparent cause in my case, which wasn't a reference to the other theme in the *.info.yml or *.libraries.yml files, but related (references in templates to `{{ attach_library('problem_theme/some_library') }}`)
Answer: This warning generally occurs if Drupal can't find the folder of the related module or theme. There is a manual page on how to get rid of this error: How to fix "The following module is missing from the file system..." warning messages.
Looking at the date of the question, there is a big chance this is happening because of version conflict between the Media entity module and source provider modules. If the installed version of the Media entity module is 1.x, then your core media module is not installed. If you are using the 2.x version of the media source provider modules like the Media entity video module or the Video Embed Field module, they are probably looking for the core Media module.
If you're building a new site, you should start over with the core Media module. If you're upgrading your existing site, you should follow the upgrade path. Instructions for both are given on the Media entity project page.
Answer: Another possibility to why this problem exists is when a module or theme is installed, but doesn't enable all the required dependencies it needs to operate. That's often what throws an error like this.
The error can be a bit confusing, since it lists a theme as missing, when the problem could lie with a missing or yet-to-be-enabled module.
In this particular case, you could probably run drush pm:enable media to resolve the issue.
Answer: Used this reference https://www.drupal.org/node/2940438 and found the deprecated functions and this fixed the issue.
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Is css3 -ms-flex available on non MS browsers?

Question: I am doing some videos from Microsoft Virtual Academy and stumbled upon -ms-flex or so called Flexbox in css3.
I would like to implement a web app on html5 and css3 and this -ms-flex would help me very much.
Is this available in webkit or fennec based browsers on mobile devices?
If this can be used, are there any limitations of use?
Also are there any equivalent for those browser if that is not supported?
I found that : safari has webkit-box and maybe there are others for the rest of the browsers(Opera, Chrome and Mozilla or Dolphin)
Comment: Check out this [can_i_use table](http://caniuse.com/#feat=flexbox)
Comment: That worked, can you provide more links with demos and tutorials for that?
Comment: I would recommend you to visit [MDN](https://developer.mozilla.org/en-US/) for some tutorial. Unfortunately my office is blocking SSL connections again so I can't provide an exact link.
Comment: Convert all this into an answer so that I can mark it as answered.
Answer: Alright, extending from comment:
According to can_i_use, You can use flex box on many modern browsers with proper prefix:

WebKit browsers (Chrome, Safari, Android stocked browser, Chrome for Android, iOS Safari) with -webkit- prefix;
Gecko/Fennec browsers (Firefox, Firefox for Android) with -moz- prefix;
Trident browsers (IE 10) with -ms- prefix;
Presto browsers (Opera desktop) without prefix.

You should be able to find some tutorial/example on MDN, or (as usual) Google.
Comment: Thanks, was of great help!


Consulta SQL utilizando varias vezes a mesma função

Question: Tenho uma função que converte a identificação de uma versão para número, exemplo, de 1.0.0 para 10000, pois assim consigo filtrar os resultados.
Função:
CREATE OR REPLACE FUNCTION f_convert_tag_to_number(ptag varchar2(12))
  RETURN NUMBER IS
  vretorno NUMBER(12);
BEGIN
  SELECT ((regexp_substr(ptag,'[^.\D]+',1,1) * 10000) +
          (regexp_substr(ptag,'[^.\D]+',1,2) * 100) +
          (regexp_substr(ptag,'[^.\D]+',1,3) * 1))
    INTO vretorno
    FROM dual;

  RETURN(vretorno);
END;

Consulta:
SELECT r.tag
      ,f_convert_tag_to_number(r.tag)
  FROM repositorio r
 WHERE f_convert_tag_to_number(r.tag) BETWEEN
       f_convert_tag_to_number('1.0.0') AND
       f_convert_tag_to_number('1.5.0')

Problema, esse exemplo acima de consulta foi somente um exemplo, tenho uma consulta muito maior que utiliza essa função cerca de 15 vezes, e o que eu quero é reduzir a utilização da função f_convert_tag_to_number
Alguém sabe alguma forma?
Obrigado
Comment: Você pode criar uma coluna com a `tag` convertida pra número na tabela e uma trigger que atualizará a coluna toda vez você fizer uma alteração. Exemplo em MySQL [aqui](http://pt.stackoverflow.com/questions/167184/consulta-inteligente-com-mysql/167252#167252) na segunda parte da resposta
Comment: Vou analisar se a coluna calculada com `trigger` atende a todas as situações, caso atender posto a resposta com a `trigger`. Queria que tivesse outra forma, mesmo assim obrigado @Sorack.
Answer: Você pode criar uma nova coluna para espelhar a informação que você quer:
ALTER TABLE repositorio ADD numeric_tag NUMBER(12);

E preenche-la através de uma trigger ao inserir ou atualizar:
CREATE OR REPLACE TRIGGER trigger_conversao_tag
BEFORE INSERT OR UPDATE of tag
ON repositorio
FOR EACH ROW
AS
BEGIN
  :new.numeric_tag = f_convert_tag_to_number(:new.tag);
END;

Utilizando na query da seguinte forma:
SELECT r.tag
      ,r.numeric_tag
  FROM repositorio r
 WHERE r.numeric_tag BETWEEN
       f_convert_tag_to_number('1.0.0') AND
       f_convert_tag_to_number('1.5.0')

Comment: Já melhora e muito, vamos aguardar se alguém tem alguma ideia, ai já marco como aceita.. obrigado @Sorack
Comment: @David Não esqueça de marcar o ✅ para que possa ser utilizada caso alguém tenha uma dúvida similar!
Comment: Pode deixar, esperar mais uns dias, vlw


No provisioned iOS device is connected

Question: I know this question has been asked before - but there are different causes, and the one I'm interested in is as a consequence to updating the test device to iOS4.2.  (I've tried the steps suggested by other threads - they don't help in this case.)
I made the mistake of agreeing to this upgrade on the device - Now my development process is broken.  In XCode, I try to build and run, and I get the error: "No provisioned iOS device is connected"
However - If I drag the apk file into iTunes, I can synch and install to the device that way.
I'm a paid up Apple developer.  I have provisioning profiles that always used to work before.
I have XCode 3.2.4.  I'm reluctant to upgrade.  The download looks like it will take 7 or more hours from the country I'm currently in - plenty of time for a glitch, and a failed download.  (But I will try tonight - I may get lucky).
Can anyone suggest how I can get XCode to test apps on the device WITHOUT the 3.52GB upgrade?
Answer: You will have to upgrade to xcode 3.2.5 since you have upgraded your iOS to 4.2,XCode won't allow you to build any code in a device of higher version.So go ahead and upgrade your xcode,its not a BIG issue,secondly you will also need to upgrade you MAC OS to the latest updates available.
Once you have upgraded everything you can face some issues.You can refer the following  link if you face those issues.
Cheers

No provisioned iOS device is connected


CkEditor deletes Bootstrap  icons

Question: We have a site built on Bootstrap.
Certain HTML modules are maintained with CkEditor.
We use Bootstrap icons according to standard syntax, e.g.: .
Our problem: CkEditor interprets that syntax as an empty tag set (i.e., ) and deletes it.
As a result, we currently can't use Bootstrap icons in any HTML modules maintained with CkEditor.
Any solutions out there?  Thanks!
Comment: Identical question was asked few days ago: http://stackoverflow.com/questions/14829961/ckeditor-and-escaping-elements.
Comment: TY Reinmar. That URL didn't mention Bootstrap, thus didn't find it in my searching. I've been searching SO for an answer for a week, so I'm grateful for your help.
Comment: i came across the same problem , read here for a solution
http://stackoverflow.com/a/18254082/1316372
Answer: Paste this in CKEditor config file:
// allow i tags to be empty (for font awesome)
CKEDITOR.dtd.$removeEmpty['i'] = false

CkEditor deletes Bootstrap  icons


How to pass a file array along with other string/int variables in java script to php

Question: I want to pass imageArray[] along with a variable trackNo. The imageArray[] I can pass it fine with no problem. I'm just uncertain on how to append/include other variables to the FormData()
Online I only see examples of people passing only a file array to a php file and never with other information.
$('#ad_post_btn').click(function () {
    ad_errmsg = "";

    imageList = myImageList(); //my array of images imageList[]

    console.log(imageList); //display files in imageList[]

    var trackNo = Math.round(Math.random() * (100000 - 1) + 1); // random number

    console.log(trackNo); // shows the random generated number

    var data = new FormData();
    var dataString = 'trackno=' + trackNo; //the variable a want to pass along with the array

    for (var i = 0; i < imageList.length; i++) {
        data.append('images[]', imageList[i]); //where I store my image files, work fine
    }

    $.ajax({
        url: 'uploadimage.php',
        type: 'post',
        data: data,
        contentType: false,
        processData: false,
        success: function (data) {
            console.log(data);

        }
    });

I've tried
data: data,dataString ,

Thank you for your time
Comment: Can we see myFileList() function?
Comment: data: data+"&dataString =dataString" , you can pass in this way too
Comment: @MarkOverton `function myImageList() {
    return imageList;
}`  anyways my problem was fixed
Answer: Solution:
data.append("key", value);

Source:
https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects
Answer: data.append('trackno', trackNo);
You can put this right before or after your for loop.
.append('key', value) will allow you to keep adding more fields.
https://developer.mozilla.org/en-US/docs/Web/API/FormData/append
Comment: this worked out fine, thanks


Does a formal system having inference rules imply that it is a logic system?

Question: From Wikipedia

Formal systems in mathematics consist of the following elements:

A finite set of symbols (i.e. the alphabet), that can be used for    constructing formulas (i.e. finite strings of symbols).
A grammar, which tells how well-formed formulas (abbreviated wff) are    constructed out of the symbols in the alphabet. It is usually
  required that there be a decision procedure for deciding whether a
  formula is well formed or not.
A set of axioms or axiom schemata: each axiom must be a wff.
A set of inference rules.

I was wondering if "inference rules" of a formal system means inference rules of a logic system? If yes, is a formal system therefore also a logic system?
But a logic system is just an example or a model of a formal system by an interpretation mapping to $\{ true, false\}$, isn't it? From the last link

A logical system or, for short, logic, is a formal system together
  with a form of semantics, usually in the form of model-theoretic
  interpretation, which assigns truth values to sentences of the formal
  language, that is, formulae that contain no free variables. A logic is
  sound if all sentences that can be derived are true in the
  interpretation, and complete if, conversely, all true sentences can be
  derived.

Thanks and regards!
Comment: Your question makes no sense in the absence of a *definition* of "logic system" and "inference rules of a logic system." As such, your confusion seems to be self-inflicted. An inference rule is merely a mechanism/function/rule that takes wffs as inputs, and produces a wff as an output; we call the inputs "premises" and the output "conclusion" or "inference", exactly as described in the wikipedia page.
Comment: PS Your title is ungrammatical. What is the "it" to which "is" refers? Not "inference rules"; so it must be "inference rules of a formal system". But then they aren't an "it is", they are a "they are".
Comment: So, logic systems are a special case of formal systems, and you are asking if a formal system is a special case of a logic system? No. Note, moreover, that "rules of inference" appear nowhere explicitly in the definition of "logic system", so why would you assume that the definition of "formal system" somehow requires "rules of inference" to be defined in terms of "logic systems"? Rules of inference have nothing to do with *semantics*; they are purely syntactical.
Comment: Even though it seems to have a Wikipedia entry, the general specification of what one might mean by a "logic system," and the term itself, are not useful.
Comment: http://en.wikipedia.org/wiki/Inference_rule.
Comment: @ArturoMagidin: Thanks! I had my questions after reading that.
Comment: @ArturoMagidin: Thanks! Please see my update.
Comment: @ArturoMagidin: (1) Re your first sentence, yes, that is what I perceive as a contradiction. (2) Do you mean rules of inference can exist outside of any logic system? Are there some examples?
Comment: @Tim: As I said: A rule of inference is a function/mechanism/rule that takes wffs as inputs and produces wffs as outputs. They can be purely syntactical, with absolutely no semantic meaning. Hofstadter gives examples in "Goedel, Escher, Bach". Here's a perfectly valid rule of inference: a wff is a finite sequence of $0$s and $1$s. The rule of inference takes a wff, and produces the wff that is obtained from the input by replacing every `0` by `01`, and every `1` by `11`.
Answer: As already noted in the comments, this depends essentially on what you choose to take as your definition of "a logic".
However, you would need an extremely expansive definition of "logic" in order to have the term cover all formal systems. In computer science, formal systems according to the description you quote crop up everywhere: they are the framework for discussing generative grammars, a diverse selection of models of computation, type systems, most styles of operational semantics for programming languages, and much more.
The general formalism and vocabulary of formal systems are deeply influenced by logic -- logics are in some sense paradigmatic examples of formal system, but that doesn't mean that every formal system is logic. Most of the examples I've listed here lack the central semantic characteristic of logic, namely that formulas can be thought of as being true or false (or at least have properties that are generalizations of truth and falsehood), and that the truth value of a formula depends in some way on the truth value of its components.
For example, the strings derived by a generative grammar usually don't represent any claims that can be true or false -- except in the rather vacuous sense that one can consider a string of letters to represent the proposition that this particular string of letters can be generated by the grammar. But the grammar can still be studied as an example of a formal system.
Answer: As I think already pointed out, the formal system also needs a particular semantics to qualify as a logical system.  Nothing in the definition of a formal system says anything about a semantics.  Sometimes in logic it comes as just as useful, if not more useful, to notice what a definition does NOT say than to notice what it does say.
Additionally, the semantics of any arbitrarily given logical system, even if happening in a "truth-value" interpretation, need not happen on the truth set {true, false}.  Mulit-valued logics, such as a three-valued logic where we have truth-values of {true, undecided, false} do get studied.  Also, if we let "1" represent "truth" (or "absolute truth"), "0" falsity, and any number between 0 and 1 represent a degree of truth, there exist formal systems which have [0, 1] as its truth set.


journalctl: Cannot filter ownCloud log lines, fail2ban will not ban

Question: Using a general journalctl command, the log line of interest appears:
[root@bee server]# journalctl -n
-- Logs begin at Mon 2015-01-26 19:44:33 EET, end at Wed 2015-06-10 21:41:12 EEST. --
...
Jun 10 21:41:12 bee ownCloud[25476]: {core} Login failed: 'ewrf' (Remote IP: '172.16.0.2', X-Forwarded-For: '')

How could I reach this ownCloud line with the -u option, aka _SYSTEMD_UNIT?
[root@bee server]# journalctl -u ownCloud
-- Logs begin at Mon 2015-01-26 19:44:33 EET, end at Wed 2015-06-10 22:01:02 EEST. --

I need to specify the journalmatch variable in the relevant owncloud filter file for fail2ban.
[root@bee server]# cat /etc/fail2ban/filter.d/owncloud-login.conf
[Definition]
failregex = {"app":"core","message":"Login failed: '.*' \(Remote IP: '<HOST>', X-Forwarded-For: '.*'\)","level":2,"time":".*"}

Ignoreregex =
[Init]

# "maxlines" is number of log lines to buffer for multi-line regex searches
maxlines = 10

journalmatch = _SYSTEMD_UNIT=ownCloud

Could I possibly use a regex pattern? How?
$man journalctl
...
-u, --unit=UNIT|PATTERN
           Show messages for the specified systemd unit UNIT (such as a service unit), or for any of the units matched by PATTERN. If a pattern is specified, a list of
           unit names found in the journal is compared with the specified pattern and all that match are used. For each unit name, a match is added for messages from
           the unit ("_SYSTEMD_UNIT=UNIT"), along with additional matches for messages from systemd and messages about coredumps for the specified unit.
...

Answer: I have own cloud running under uWSGI/Nginx on ArchLinux and while my journalctl entries show uwsgi the actual system unit name is firstname.lastname@example.com. You should be able to use the command below to find out the correct _SYSTEMD_UNIT name. The command will find a single entry that matches the wildcard unit name and then output it in JSON format.
journalctl -u *ownCloud* -n 1 --output json --no-pager

Comment: Thank you for the answer. Using the solution above, I get the following error in Fedora: ```Failed to add filter for units: No data available```. However I have implimented the following solution: ```journalmatch = SYSLOG_IDENTIFIER=ownCloud```


Unity3D static splash image scalling options not working

Question: Unity3D Version: 2018.4.8c3 (2018.4.16f1 same problem)
I am trying to make a static, full screen splash image for Unity3D Android app. however, I found that the splash image could not scal/resize properly on different resolution android phones.
Unity Doc says three different kinds of scalling unity doc:
Center (only scale down) draws your image at its natural size unless it is too large, in which case it is scaled down to fit.
Scale to fit (letter-boxed) draws your image so that the longer dimension fits the screen size exactly. Empty space around the sides in the shorter dimension is filled in black.
Scale to fill (cropped) scales your image so that the shorter dimension fits the screen size exactly. The image is cropped in the longer dimension.
In my Player settings:

the splash sprite is 720*1440 resolution.
But when I runs it on 2080*2340 phones, ends up like this

I know the splash image is white and not proper scalling results blank gaps that looks augly.
Changing scalling setting does not shown change after build. I find there must be a scalling method taking the screen size into account. Different notch on android phones results in difference scalling looking.
what's the proper way making a full screen splash for all android devices? what's a optimal size for splash image?
Thanks
Comment: Might be worth reporting as issue on Unity forums. Also, might see if the following advice for a similar issue works https://gamedev.stackexchange.com/questions/138345/how-to-fix-stretched-splash-image-in-unity Change the rect type prop on the textures setting to full rect.
Answer: The reason is wrong attribute in final apk AndroidManifest.xml.
<meta-data android:name="unity.splash-mode" android:value="0" />

You could just drag and drop the apk to Android Studio, then check AndroidManifest.xml.
You should change it to 2, which represent 'Scale to fill (cropped)':
<meta-data android:name="unity.splash-mode" android:value="2" />

Maybe your build process is modified by PostProcessor or something else, then the attribute is replaced to 0.


O que é isso? private List> gastos;

Question: Uma lista de mapas? É sério fiquei assustada com isso. Nunca vi isso na minha vida...
private List<Map<String, Object>> listarGastos() {
  gastos = new ArrayList<Map<String, Object>>();
  Map<String, Object> item = new HashMap<String, Object>();
 item.put("data", "04/02/2012");
 item.put("descricao", "Diária Hotel");
 item.put("valor", "R$ 260,00");
 item.put("categoria", R.color.categoria_hospedagem);
 gastos.add(item);

   return gastos;
 }
}

Comment: è isso mesmo uma lista de mapas...
Comment: Esse método poderia muito bem retornar apenas o `Map` criado, já que o que ele está criando é uma lista com um único elemento, e portanto não há muito sentido de que seja uma lista para começar. Gostaria de saber onde esse método é utilizado para entender se há sentido em isso ser uma lista de mapas ou se deveria ser outra coisa. Onde esse método é utilizado?
Comment: A resposta lhe foi útil? Não esqueça de marcar o ✅ para que possa ser utilizada caso alguém tenha uma dúvida similar!
Answer: Sim, é uma lista de mapas. Ela permite que você insira um conjunto de chaves e valores formando uma estrutura como a do seu exemplo:
[
  {"data": "04/02/2012"},
  {"descricao": "Diária Hotel"},
  {"valor": "R$ 260,00"},
  {"categoria": R.color.categoria_hospedagem}
]

No caso de você saber quais são os atributos colocados no Map é mais efetivo criar um objeto no formato esperado. Torna o código mais legível e mais fácil de ser trabalhado.
Seria melhor representado por:
import java.time.LocalDate;

public class Item {

  private LocalDate data;
  private String descricao;
  private double valor;
  private String categoria;

  public LocalDate getData() {
    return data;
  }

  public void setData(LocalDate data) {
    this.data = data;
  }

  public String getDescricao() {
    return descricao;
  }

  public void setDescricao(String descricao) {
    this.descricao = descricao;
  }

  public double getValor() {
    return valor;
  }

  public void setValor(double valor) {
    this.valor = valor;
  }

  public String getCategoria() {
    return categoria;
  }

  public void setCategoria(String categoria) {
    this.categoria = categoria;
  }
}

E a utilização seria:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
List<Item> gastos = new ArrayList<>();
Item item = new Item();

item.setData(LocalDate.parse("04/02/2012", formatter));
item.setDescricao("Diária Hotel");
item.setValor(260.00);
item.setCategoria(R.color.categoria_hospedagem);
gastos.add(item);

O que é isso? private List> gastos;


Trying to use powershell to selectively erase old backup files

Question: I am working with a drive with thousands of backup files, many of which are just cluttering space.
The program our employees use creates a backup of a spreadsheet every time they open one for editing. Each backup is a new file named according to the spreadsheet + the date + the time. We have a separate backup directory for each of our clients, and each directory has multiple spreadsheets and multiple backups of each spreadsheet.
In the end, we have a file structure filled with files like this:
Companyx/backup/abssheet_091210_111006.bps
Companyx/backup/abssheet_091210_133335.bps
Companyx/backup/xyzsheet_091210_145223.bps
Companyx/backup/xyzsheet_100803_100332.bps
Companyx/backup/xyzsheet_100812_111244.bps
Companyy/backup/gnu_sheet_081029_110455.bps
Companyy/backup/gnu_sheet_081029_111233.bps
Companyy/backup/gnu_sheet_081029_112355.bps

We only need to keep the most recent 2 backups of any particular sheet. Out of the 8 files I listed here, I would want to keep 6. The date and time in the filename is unimportant, as I can use the date and time from the file information. But the filenames cannot end up changed.
I have played around with powershell some, and I already used gci to move these to a file location of their own. I can also strip the date and time strings from the filenames. I also found a powershell script to remove all but the 2 newest files from a particular directory. But I am at a loss on how to selectively delete what I want to.
So far, I have written/modified the following code:
$newlist = New-Object System.Collections.Generic.List[System.String]
$fulllist = gci . | where {-not $_.PsIsContainer} | sort Name
$array = @()

foreach ($object in $fulllist)
{
    $string = $object.name
    $psworiginal = $string.Replace("_"+($string -split "_")[-1]," ")
    $psworiginal2 = $psworiginal.Replace("_"+($psworiginal -split "_")[-1]," ")
    $newlist.Add($psworiginal2)
}

$newlist = $newlist | select -unique

This gives me a list of the individual spreadsheets. But them I'm not sure how to work from that list to go back through the original list and remove all but the latest 2 backup of each spreadsheet.
Ideally, I would like to put the -Recurse parameter back in the gci call and have it go through a complex directory structure to weed out older backups in every directory.
Comment: This should point you in the right direction http://superuser.com/questions/794282/deleting-all-but-latest-revision-of-a-file
Comment: If you have a recent Powershell (>= 3) you can specify files with `gci -File` and save the extra pipeline. If your file names are consistent for the first *y* chars, you can `Group-Object -Property {$_.name[y]}` to group the files. And finally, if you can trust your file time stamps, all of this becomes much easier.
Comment: I've read this post a few times and I'm still not clear on what you're trying to do.  Probably just me though.
Comment: I finally figured out how to do what I wanted. I'm not sure it was the most efficient, but it worked well to use a hashtable to keep track of how many times each file was found. As I found a file, I checked to see if it was in the hashtable or not. If it was not, I added it with a value of 1. If it was there with a value of 1, I changed the value to 2. Otherwise, I deleted the file. If it would be helpful to see some of the specific code, I can post it.
Answer: This will remove every file based on 'key' from each company folder except two newest one
Filtering is based on LastWriteTimeUTC
In this code, the $local:allFiles = @{}; in Filter-BackupFiles function is a key-value hastable where THE KEY is part of filename before 12345_12345.bas (the fileKey named selection in RegEx, in my example it is everything before last _ symbol) ans THE VALUE is array of file objects (not file names). For each file I add (using Add-Member) an attribute for soring (in my case it is LastWriteTimeUTC, you can do something else in your case)
Then for each key (which is filename prefix) I sort the list of file objects and adding to removal list all except two ($Script:KeepMostRecent = 2) first files (this means two newest files because they were sorted by date desceding).
$Script:StartPath = 'D:\Test_1'
$Script:KeepMostRecent = 2;
$Script:BackupSubfolder = 'backup'
$Script:RegexFilter = '^(?<fileKey>.*)_\d+_\d+\.bps$'
$Script:SimulatingMode = $true
#In my case regex is overriden because of file names
$Script:RegexFilter = '^(?<fileKey>.+)_[^_]+\.txt$' #THIS IS DEV OVERRIDE
Function Log-Error {
    Param (
        [Parameter(Mandatory=$true)]
        [String]$LogMessage
    )
    Write-Host -ForegroundColor Yellow "Error: $($LogMessage)";
}
#End of Log-Error

Function Get-Companies {
    Param (
        [Parameter(Mandatory=$true)]
        [String]$SearchBase
    )
    $local:companyDirectoies = @()
    try {
        $local:companyDirectoies = @(Get-ChildItem -Path $SearchBase -Recurse:$false -ErrorAction Stop | Where-Object {$_.psIsContainer -eq $true} -ErrorAction Stop | ForEach-Object {return $_.FullName} -ErrorAction Stop )
    } catch {
        Log-Error -LogMessage $([String]::Format("Error while getting companies list: {0}", $_.Exception.Message))
        return $null
    }
    return $local:companyDirectoies
}

Function Get-BackupFiles {
        Param (
        [Parameter(Mandatory=$true)]
        [String]$CompanyDirectoryPath
    )
    $local:files = @();
    try {
        $local:files = @( Get-ChildItem -Path $CompanyDirectoryPath -Recurse:$false -ErrorAction Stop | Where-Object {$_.psIsContainer -eq $false} -ErrorAction Stop)
    } catch {
        Log-Error -LogMessage $([String]::Format("Error while getting Backup file list for path {0}: {1}", $CompanyDirectoryPath ,$_.Exception.Message))
        return $null
    }
    return $local:files
}

Function Filter-BackupFiles {
    Param (
        [Parameter(Mandatory=$true)]
        [Object[]]$CompanyBackupFiles
    )
    $local:allFiles = @{};
    $local:filesToRemove = @()
    foreach ($local:f in $CompanyBackupFiles) {
        $local:lastFileDate = $local:f.LastWriteTimeUtc
        $local:f | Add-Member -MemberType NoteProperty -Name 'LastDate' -Value $( $local:lastFileDate )
        $local:fileName = $local:f.Name
        if ($local:fileName -match $Script:RegexFilter) {
            $local:fileKey = $Matches['fileKey']
            #Use NotCContains ir you need case-sensitive filtering
            if ($local:allFiles.Keys -notcontains $local:fileKey) {
                $local:allFiles[$local:fileKey] = @()
            }
            $local:allFiles[$local:fileKey] += @($local:f)
        } else {
            Log-Error -LogMessage $([String]::Format( "Error - the file name {0} does not match regEx. None will be processed for this list",$local:fileName))
            return $null
        }
    }
    foreach ($local:k in $local:allFiles.Keys) {
        Write-Host -ForegroundColor White "Checking files for key $($local:k)"
        $local:files = @( $local:allFiles[$local:k] | Sort-Object -Property 'LastDate' -Descending  )
        $local:filesToKeep = $Script:KeepMostRecent
        foreach ($local:f in $local:files) {
            $local:filesToKeep--
            Write-Host -ForegroundColor White -NoNewline "$($local:f.FullName)`t$($local:f.LastDate)"
            if ($local:filesToKeep -lt 0) {
                $local:filesToRemove += @($local:f.FullName)
                Write-Host -ForegroundColor Red "`tMARKED TO REMOVE"
            } else {
                Write-Host -ForegroundColor Green "`tMARKED TO LIVE"
            }
        }
    }
    return $local:filesToRemove
}

Function _main {
    $local:AllFilesToRemove = @()
    $local:companiesPathList = @(Get-Companies -SearchBase $Script:StartPath)
    if ($local:companiesPathList.Count -le 0) {
        Log-Error -LogMessage "Companies list is empty"
        return
    }
    forEach ($local:comanyPath in $local:companiesPathList) {
        Write-Host -ForegroundColor White "`r`n`r`nProcessing company on path $($local:comanyPath)"
        $local:companyBackupFolder = ""
        try {
            $local:companyBackupFolder = $( Join-Path -Path $local:comanyPath -ChildPath $Script:BackupSubfolder -ErrorAction Stop )
            $local:allCompanyFiles =  Get-BackupFiles -CompanyDirectoryPath $local:companyBackupFolder -ErrorAction Stop
        } catch {
            Log-Error -LogMessage "Error getting backup files for company $($local:comanyPath) : $($_.Exception.Message)"
        }
        if (($local:allCompanyFiles.Count -le 0) -or ($local:allCompanyFiles -eq $null)) {
            Log-Error -LogMessage "Company $($local:companyBackupFolder) does not have files in backup. Will ignore it."
            continue
        }
        $local:companyFilesToRemove =  Filter-BackupFiles -CompanyBackupFiles $local:allCompanyFiles
        if (($local:companyFilesToRemove.Count -le 0) -or ($local:companyFilesToRemove -eq $null)) {
            Write-Host -ForegroundColor Cyan "Company $($local:comanyPath) does not have files to remove. Will ignore it."
            continue
        }
        Write-Host -ForegroundColor White "Company $($local:comanyPath) have $($local:companyFilesToRemove.Count) file to remove"
        $local:AllFilesToRemove += @( $local:companyFilesToRemove )
    }
    Write-Host -ForegroundColor White "Totally we have $($local:AllFilesToRemove.Count) files to remove"
    foreach ($local:f in $local:AllFilesToRemove) {
        Write-Host -ForegroundColor White "Removing $($local:f)"
        try {
            Remove-Item -Path $local:f -Force -Confirm:$false -WhatIf:$Script:SimulatingMode -ErrorAction Stop
        } catch {
            Log-Error -LogMessage "Error removing file $($local:f) : $($_.Exception.Message)"
        }
    }
}

_main

So the output will be
Processing company on path D:\Test_1\Company1
Checking files for key File1_Custom_Name
D:\Test_1\Company1\backup\File1_Custom_Name_bak1.txt    02/28/2016 07:07:38 MARKED TO LIVE
D:\Test_1\Company1\backup\File1_Custom_Name_Bak2.txt    02/28/2016 07:06:38 MARKED TO LIVE
D:\Test_1\Company1\backup\File1_Custom_Name_Bak3.txt    02/28/2016 07:05:38 MARKED TO REMOVE
Checking files for key File2
D:\Test_1\Company1\backup\File2_Bak1.txt    02/28/2016 07:07:38 MARKED TO LIVE
D:\Test_1\Company1\backup\File2_Bak2.txt    02/28/2016 07:06:38 MARKED TO LIVE
D:\Test_1\Company1\backup\File2_Bak3.txt    02/28/2016 07:05:38 MARKED TO REMOVE
Company D:\Test_1\Company1 have 2 file to remove

Processing company on path D:\Test_1\Company2
Checking files for key File2
D:\Test_1\Company2\backup\File2_Bak3.txt    02/28/2016 07:58:34 MARKED TO LIVE
D:\Test_1\Company2\backup\File2_Bak2.txt    02/28/2016 07:58:31 MARKED TO LIVE
D:\Test_1\Company2\backup\File2_Bak1.txt    02/28/2016 07:58:28 MARKED TO REMOVE
Checking files for key File4
D:\Test_1\Company2\backup\File4_Bak1.txt    02/28/2016 07:59:43 MARKED TO LIVE
D:\Test_1\Company2\backup\File4_Bak3.txt    02/28/2016 07:58:42 MARKED TO LIVE
D:\Test_1\Company2\backup\File4_Bak2.txt    02/28/2016 07:58:39 MARKED TO REMOVE
Checking files for key File1
D:\Test_1\Company2\backup\File1_Bak3.txt    02/28/2016 07:58:25 MARKED TO LIVE
D:\Test_1\Company2\backup\File1_Bak2.txt    02/28/2016 07:58:22 MARKED TO LIVE
D:\Test_1\Company2\backup\File1_bak1.txt    02/28/2016 07:58:17 MARKED TO REMOVE
Company D:\Test_1\Company2 have 3 file to remove

Processing company on path D:\Test_1\Company3
Checking files for key File2
D:\Test_1\Company3\backup\File2_Bak1.txt    02/28/2016 07:07:38 MARKED TO LIVE
D:\Test_1\Company3\backup\File2_Bak2.txt    02/28/2016 07:06:38 MARKED TO LIVE
D:\Test_1\Company3\backup\File2_Bak3.txt    02/28/2016 07:05:38 MARKED TO REMOVE
Checking files for key File4
D:\Test_1\Company3\backup\File4_Bak1.txt    02/28/2016 07:07:38 MARKED TO LIVE
D:\Test_1\Company3\backup\File4_Bak2.txt    02/28/2016 07:06:38 MARKED TO LIVE
D:\Test_1\Company3\backup\File4_Bak3.txt    02/28/2016 07:05:38 MARKED TO REMOVE
Checking files for key File1
D:\Test_1\Company3\backup\File1_bak1.txt    02/28/2016 07:07:38 MARKED TO LIVE
D:\Test_1\Company3\backup\File1_Bak2.txt    02/28/2016 07:06:38 MARKED TO LIVE
D:\Test_1\Company3\backup\File1_Bak3.txt    02/28/2016 07:05:38 MARKED TO REMOVE
Company D:\Test_1\Company3 have 3 file to remove
Totally we have 8 files to remove
Removing D:\Test_1\Company1\backup\File1_Custom_Name_Bak3.txt
Removing D:\Test_1\Company1\backup\File2_Bak3.txt
Removing D:\Test_1\Company2\backup\File2_Bak1.txt
Removing D:\Test_1\Company2\backup\File4_Bak2.txt
Removing D:\Test_1\Company2\backup\File1_bak1.txt
Removing D:\Test_1\Company3\backup\File2_Bak3.txt
Removing D:\Test_1\Company3\backup\File4_Bak3.txt
Removing D:\Test_1\Company3\backup\File1_Bak3.txt


do thumbnail image styles lower the page load

Question: This may not be a Drupal specific question, but when I use image styles to resize from a full to thumbnail size, will the page load still behave as if its a hiqh quality image, or does it lower the page load?
I'm trying to figure out if there should ever be a reason to provide two upload fields on a content type, one for a high quality image and one for a lower one.
Answer: Uploaded images are scaled depending on the preset you choose for display. Thus, a typical high resolution image which might have 8 MB is reduced to maybe 150 kB when using a thumbnail preset. This of course lowers the bandwidth, the original image is not loaded.
So, there is no need to create a second image field. If you haven't seen it yet, you might want to take a look at the Colorbox module. It lets you choose to display an image as a thumbnail and only upon clicking on that preview the full image is loaded (or just another size you defined).
Just a note: Colorbox is not the only module that is providing that feature, there are a lot of similar modules, the original was called Lightbox. On drupal.org, there's a page comparing all available lightbox clones.
Answer: Using thumbnail image, your page load time will be decreased. You should use only one field to upload image.You can use different image styles in drupal.
By default, drupal provides your three images styles.
1)Thumbnail
2)Medium
3)Large
You can also create more image styles at following page.
Click on Configuration-> Media->Image Style. Click on Add style link.


Link Mini Panel thumbnail formatter to node

Question: Working on a site that shows images and video with a Mini Panel formatter in a View withe File Entity and Media modules. The Mini Panel has a piece of content of file display that shows an Image display as well as Vimeo Video and YouTube. The Image display settings uses an Image style.
How do I link the media from the mini-panel to the referencing entity? (User clicks on the thumbnail in the view listing and is taken to the node's path).
Comment: i have changed the view to display rendered file and installed https://drupal.org/project/file_entity_link. this is an incomplete solution.
Answer: If you go to the view display page and click on the field of your thumbnail, on the settings page scroll down and you should see a drop-down with title of Link image to. Choose content and save.
Comment: Content fields have the option, "Link this field to the original piece of content" But the Media field does not.
Answer: To  link the media to the node,you need to follow some steps as:-

Edit the view which contains images and videos which are to be linked to a node.
In the fields section,Just Click on the field which would link to some node.

3.1 In the REWRITE RESULT's tab,check the checkbox :Output this field as a link and specify the destination url to which you want to link to.
3.2. or to link the formatter, just click on the field and in the LINK IMAGE TO and select a option to which you want your formatter to be linked to.
Comment: Thanks neetu, can you suggest the token replacement for option 3.1? I do not understand 3.2, but it got me wanted to have the mini panel set up to link to content so can easily have consistency a cross my views.


Log4j.xml dynamic file attributes

Question: I am deploying my application in websphere server and i want to set param File attribute of log4j.xml. Locally i am doing like
<param name="File" value="C:\\logs\\cle_error.log" />

My server name is App_Admin and path where i want to generate debug.log file is /waslib/appadmin/uat/logs.
Answer: You could use System property for this like:
<param name="File" value="${mylog.path}" />

And when you start your application, you could just pass system property like:
java -Dmylog.path="/waslib/appadmin/uat/logs" ...

Log4j.xml dynamic file attributes


Connecting to specific Azure Redis database in asp .NET core

Question: I want to connect to a specific database in our new Azure Redis cache but can't seem to figure out how to do it.
I've tried adding the database id to connection string in various forms as well as looking for GetDatabase(dbid) on the IDistributedcache object (which doesn't seem to exist).
FYI, I want to use the same cache for our testing and production without having to pay for an additional redis cache so I'm open to alternative approaches.
Comment: I've seen the same cache used for non-prod and production before and it can potentially be a huge pain point.  Be sure to consider the risk of accidentally having data cross between the two while you're determining how your keys are going to work.
Comment: And this is why I really wanted to separate them using different databases in the redis cache.
Comment: So I think the best way to do this is to use a ConnectionMultiplexer as a singleton service (which means you can use a config object and also means a lot less time creating connections to Redis too). I'll experiment and add my answer later for anyone else that runs in to this as it took me a while to figure out this was the best approach.
Answer: You could also use the ConnectionMultiplexer object directly and access the Database via the GetDatabase method.
Comment: This is what I did in the end.


Proportional odds assumption for multilevel data

Question: I'm running model in which I analyze salary of recent graduates. People graduated from different majors and in different years. The dependent variable (salary) is measured using intervals, e.g., "less than 1000", "between 1000 - 2000; "between 2000 - 5000", not the actual amount that people make. Because of the fact that data is hierarchical and the DV is ordinal, I use the Cumulative Link Mixed Model (CLMM) in the ordinal package in R.
The important assumption here is the proportional odds assumption. Unfortunately, I didn't find information on how to test this assumption in multilevel models and from my reading, it is not possible to do in the ordinal package.
That's why I have the following questions:
1) Does it make sense to test the proportional odds assumption using cumulative link model (CLM) which does not take into account the hierarchical structure of the data I have?
2a) if this is not a correct approach, what would you recommend to use as an alternative?
2b) if such a testing makes sense (and the assumption is not met), what should be the alternative model? Is it the multinomial logistic regression model(with the random effects specification)? Could you recommend a package to do it for multilevel data?
Thank you!
Answer: 1) Obviously it does not make any sense to test the proportional odds assumption using cumulative link model disregarding the hierarchical structure of the data.
2) One valuable option is the multinom function from nnet package. MCMCglm package is also good and easy to implement despite its Bayesian approach.
Comment: Thank you Paolo! In fact, this idea of testing the assumption of proportional odds without specifying the random effects have been suggested for example here http://rcompanion.org/handbook/G_12.html (section "Check model assumptions"). However, it doesn't "sound" right to me. Could you elaborate on this why you also think that this is not a correct approach?


Rails - creating a new model and error "uninitialized constant"

Question: I created a new table (through a migration) and then I manually added a model - the model looks like this:
class UserData < ActiveRecord::Base
  belongs_to :user

  def self.save_user_data(data, cur_user)
    data.each do |d|
      puts "Saving: #{cur_user.id}, #{d['id']}, #{d['name']}"
      UserData.create!(:user_id => cur_user.id,
                       :name => d['name'])
    end
  end
end

The table is properly created.
I call this method from /controllers/users/omniauth_callbacks_controller.rb like this:
UserData.save_user_data(@data, current_user) if @data

And getting this error:
uninitialized constant Users::OmniauthCallbacksController::UserData

What am I missing in this case?
Comment: Are you using scopes in your project? Sounds to me like Rails tries to find the `UserData` class underneath the `Users::OmniauthCallbacksController` namespace...
Comment: No, I don't (I am not very familiar with scopes, that's why I don't use them).
Answer: Try using ::UserData instead of UserData in your controller class.
Comment: I've tried, but got a different error message. However, I found the problem - the file with model was named **user_datas.rb** instead of **user_data.rb**. I need some sleep.


How to determine or diagnose that time series data contain seasonality pattern for SARIMA in R by function

Question: I want to ask about seasonal ARIMA (SARIMA)  in R function
how to determine that time series data has affected or influenced by seasonal pattern
Thank you very much
Comment: Look at the help file of function `auto.arima` of "forecast" package in R. There you will find a couple of tests for seasonality.
Answer: Pradita, You will need to go beyond auto.arima to find seasonality.  If only one period has seasonality(ie June) then auto.arima won't find it.  You need to consider more than just seasonal differencing, 11 monthly dummies or an AR12 and consider the possibility for the need of only 1 monthly dummy needing to exist(or maybe 2?). If there is a change in the seasonality(similar concept---Monday is low and then half way into the series Friday's become high) then auto.arima won't find it. If you have an example data set, post it here.


React-Native Run-Android

Question: React-native run-android not working It will build an app 99% then it will show error like this:
<code>:app:installDebug
Installing APK 'app-debug.apk' on 'Moto G (4) - 7.0' for app:debug
Installed on 1 device.

BUILD SUCCESSFUL

Total time: 8.603 secs
Running D:\Android_SDK\Sdk\tools\bin/platform-tools/adb -s ZY2238WJXB reverse tc
p:8081 tcp:8081
Could not run adb reverse: spawnSync D:\Android_SDK\Sdk\tools\bin/platform-tools
/adb ENOENT
Starting the app on ZY2238WJXB (D:\Android_SDK\Sdk\tools\bin/platform-tools/adb
-s ZY2238WJXB shell am start -n com.localpropertys/com.localpropertys.MainActivi
ty)...
events.js:167
      throw er; // Unhandled 'error' event
      ^

Error: spawn cmd.exe ENOENT
    at Process.ChildProcess._handle.onexit (internal/child_process.js:229:19)
    at onErrorNT (internal/child_process.js:406:16)
    at process._tickCallback (internal/process/next_tick.js:63:19)
Emitted 'error' event at:
    at Process.ChildProcess._handle.onexit (internal/child_process.js:235:12)
    at onErrorNT (internal/child_process.js:406:16)
    at process._tickCallback (internal/process/next_tick.js:63:19)

</code>
How can I resolve that?
environment set up  D:\Android_SDK\Sdk\tools\bin
Answer: You're code is throwing the error not the CMD. The reason why you can't trace it is because you didn't catch the error. A function in your code isn't working and it's throwing an error.
Comment: Do you have an event handler or a listener? If so... throw a catch in them and see if you can pin point the error.

React-Native Run-Android


Getting a specific item value in a ListBox

Question: I'm trying to get to specific item in a ListBox (asp.net, C#)
and check if it's null or not:
if (ListBox.Items[0] == null )
{
     if (HowMany.Text == arrOfWords[0])
     {
          ListBox.Items.Add(arrOfWords[0]);
          ErrorMessege.Text = "Good!";
     }
}

it's returning that :  Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
Why is that?
Thanks!
Answer: It looks like in this case the Items collection is empty hence even 0 is outside the bounds of the collection.  You need to test for the index being valid as well as the item being non-null.
if (ListBox.Items.Count > 0 && ListBox.Items[0] == null) {
  ...
}

Comment: Then it's likely one of the other indexes. I would try the same fix for all of them.
Answer: Add a null check before accessing the array elements as well.
if ((ListBox.Items.Count > 0) && (ListBox.Items[0] == null))
{
    if((arrOfWords.count>0)&&(arrOfWords[0]!=null))
        {
          if (HowMany.Text == arrOfWords[0])
          {
              ListBox.Items.Add(arrOfWords[0]);
              ErrorMessege.Text = "Good!";
          }
        }
}

EDIT : From your comment "its ok that there are 0 items there for me, my intention is that if there is 0 items there, then it should add an Item from the arrOfWords"
So if you mean, even if there are zero items in the Listbox, you need to add an item from the array to listbox, then take out the First if condition
if((arrOfWords.count>0)&&(arrOfWords[0]!=null))
{
   if (HowMany.Text == arrOfWords[0])
   {
       ListBox.Items.Add(arrOfWords[0]);
       ErrorMessege.Text = "Good!";
   }
}

Comment: put break points in the first if condition and see how many items are present in the list box and arrOfWords
Comment: so you have to check why listbox is having 0 items if you are expecting some items there. Where are you loading items to the list box ? Are you clearing those on a postback ?
Comment: in the debug mode, its not even enter the first if statement.  even if I try to make if ((ListBox.Items.Count > 0) && (ListBox.Items[0] == null))
Comment: by default, the listbox presenting 0 items when the application is running for the first time, and "arrOfWords" presenting at least one everytime.
Comment: no, its ok that there are 0 items there for me, my intention is that if there is 0 items there, then it should add an Item from the arrOfWords.


Open IE page through client side

Question: How can I open a IE page in client side ?
Example:
We use FireFox as default browser for our web system. My users in a specific moment has to print a page. How can I print a page through FireFox ?
Details:
To access the printer we need ActiveX, but FireFox doesn't accept ActiveX. I tried access the printer through Dll but works just localhost, because this is server side, so if I deploy my application in my server, the printer won't work in client side. My third try, was open the IE via code-behind, but this is also server side, just works in localhost.
I just need open a specific page in IE (because of activex), when I'm using FireFox, but in client side.
How can I do that ?
Comment: Why not just let them print the page using Firefox? Open a window with the content, perhaps with a print-specific stylesheet, and issue a `window.print();` on it. Firefox will handle the rest.
Comment: [window.print();](https://developer.mozilla.org/en-US/docs/DOM/window.print)
Comment: But `window.print()` will print in the default printer, I need print in a specific one.
Comment: Other browsers do not offer this sort of functionality, sorry. Try writing the instructions on the webpage itself for non-IE users.
Comment: window.print() should automatically provide a dialog? You mean this dialog doesn't show the right printer? Does your system have something weird in place to prevent users from selecting a printer.
Comment: But look, I open a page to my user, if I click to print, I will print the page but in different formats, words, etc. So, `window.print()` its not appropriate, because this will print the page the same way that are showed.
Answer: You can't use client-side code to open IE from Firefox without installing a plug-in or protocol handler or similar. That's a complex route to go down and, of course, requires that your users install something specific.
Instead, I'd suggest letting them print the page using Firefox. Open a window with the content, perhaps with a print-specific stylesheet, and issue a window.print(); on it. Firefox will handle the rest.
Comment: But `window.print()` will print in the default printer, I need print in a specific one.
Comment: @Lucas_Santos: No, it won't. `window.print` will open a dialog box (or similar) which allows the user to select the printer to use.
Comment: But look, I open a page to my user, if I click to print, I will print the page but in different formats, words, etc. So, `window.print()` its not appropriate, because this will print the page the same way that are showed.
Comment: @Lucas_Santos: Read the answer again. My suggestion was to open a window with the content you want to print, and (optionally) to use a print style sheet (`@media print { ... }`). You can control what gets printed, and how it looks. Search for "using a print style sheet" for more.
Answer: Browsers do not provide web pages with the means to run arbitrary software, so you cannot.
Answer: If you call in javascript window.print(); the standard print dialog will get opened. So no need for any dll's or activex.
Comment: But `window.print()` will print in the default printer, I need print in a specific one.
Comment: @Lucas_Santos How can you know what printer a client has? You can't know that for sure.
Comment: @SynerCoder It might be an in-house application.
Comment: But look, I open a page to my user, if I click to print, I will print the page but in different formats, words, etc. So, `window.print()` its not appropriate, because this will print the page the same way that are showed.

Open IE page through client side


Perfect Secrecy and Kullback-Leibler divergence

Question: Perfect Secrecy can be defined by
$I(M;Z^n) = D(P_{MZ^n}||P_MP_{Z^n}) = 0$
there the true joint distribution $P_{MZ^n}$ is compared to the product distributions $P_M P_{Z^n}$.
The system can be viewed as follows:
<code>M -> Enc E -> X^n -> P_{yz|x} -> Y^n -> Dec -> ^M
                              -> Z^n -> Eve -> ?
</code>
I'm struggeling with the interpretation of the Kullback-Leibler divergence. Can someone give me some intuitive explanation?
Comment: What is $D(P_{MZ^n}||P_MP_{Z^n})$?
Comment: I thought it is the Kullback-Leibler divergence? So the "distance" between the probability-distributions.
Comment: Yes.  Okay, this looks to be a nice summary https://www.researchgate.net/profile/John_Hershey3/publication/4249249_Approximating_the_Kullback_Leibler_Divergence_Between_Gaussian_Mixture_Models/links/56b46b9d08ae61c480592ca9/Approximating-the-Kullback-Leibler-Divergence-Between-Gaussian-Mixture-Models.pdf
Comment: Thanks. I think I have now some explanation. $P_{MZ^n}$ should be $P_M P_{Z^n}$, meaning that both are statistical independent.
Answer: The KL-Divergence is defined as
$$
   D(p_x || q_x) = \sum _x p(x) \log \frac{p(x)}{q(x)}
$$
and the mutual information is defined as
$$
   I(X;Y) = H(X) - H(X|Y) = \sum_x \sum_y p(x,y) \log \frac{p(x,y)}{p(x)p(y)}
$$
from the above it's clear that $I(X;Y) = D(p_{xy} || p_xp_y )$
Comment: Okay, thanks. :) But why should I define it like that? I'm searching for some visualization or intuitive explanation.
Comment: This only holds for statistical independence?


How to force RDP to accept my stored credentials, when my computer is under a domain?

Question: So i've setup TERMSRV/* in the Group Policy Editor, but RDP will still not allow me to use saved credentials because the computer is under a domain. I found this by reading the description in the policy editor: "If the client is domain-joined, by default the delegation of saved credentials is not permitted to any machine".
I understand this is a "security" feature but it is pretty stupid in my case. Is there is a way to bypass it?

Kind regards
Answer: I know this is an 8 month old post, but I just found my self on the same situation. Well, the solution (at least for me) was really simple. But this has to be done in the DC, you have to edit your Default Domain Policy or create a new one with the following:
Computer Configuration > System > Credentials Delegation
- Allow delegating default credentials with NTLM-only server authentication
- Enabled > Add servers to the list > Show > add TERMSRV/*

The same goes to "Allow delegating saved credentials with NTLM-only server authentication"
Computer Configuration > System > Credentials Delegation
- Allow delegating saved credentials with NTLM-only server authentication
- Enabled > Add servers to the list > Show > add TERMSRV/*

After this, in the DC just force a gpupdate and do the same on the computer you need to use the saved credentials.
This worked for me in an Windows Server 2012 R2 environment.
Hope it helps in the future.
Regards!
Comment: i did fix it after all, but don't remember how ;p


update a node field when flagging

Question: I want to achieve the following :
I have a node 'proposal' with a flag 'accept' and another node 'project'.
I want when a user flag the 'proposal' with the 'accept' flag, a field value in the 'project' node is updated.
I wrote this code but it seems not to work
function mymodule_flag_flag($flag, $entity_id, $account, $flagging)
{

$node =  node_load($entity_id);
$freelancer = $node-> uid;
$project_node = node_load($node->field_projet['und'][0]['target_id']);
$wrapper = entity_metadate_wrapper('node', $project_node);
$wrapper->field_freelancer->value = $freelancer;
}

Answer: I do not see that you are saving the project node, after changing field value.
function mymodule_flag_flag($flag, $entity_id, $account, $flagging) {
  $node =  node_load($entity_id);
  $freelancer = $node-> uid;
  $project_node = node_load($node->field_projet['und'][0]['target_id']);
  $wrapper = entity_metadate_wrapper('node', $project_node);
  $wrapper->field_freelancer->set($freelancer);
  // You missed
  $wrapper->save();
}

update a node field when flagging


What are the best strategies for a game winning run with 1 out and a runner on 3rd?

Question: Say the game is tied in the bottom of the 9th, you have a runner on third and one out, what is the best strategy for scoring a run and winning the game? Is it a play that requires the current batter to sacrifice himself, or is that risky since you're then down to only having one batter left? Should the batter bunt it, or only bunt it when the strike count is at 2?
Comment: What kind of guarantee are you looking for? There's not even a garuntee that the last two hitters are going to put the ball in play, let alone putting a run in.
Comment: Sorry, you're right. I'll edit my question a bit
Answer: There are five basic strategies when there is a runner on 3rd and less than 2 outs (1-0 doesn't matter much). Provided its a tie game or you are down by one.

The riskiest is the suicide squeeze. This is a decent percentage play, but comes with a good amount of risk. The batter bunts the ball and as the ball is pitched the runner on third breaks for the plate. The batter must get the bat on the ball or the play becomes a straight steal of home which requires a good bit of luck (or panache on the part of the runner) to pull off.
Similar to the first, the safety squeeze is another option. This play is very similar to the squeeze bunt, but the runner waits until the batter has the bunt down to commit to going home. If the opposing team elects to go to first with the ball, the runner is usually safe, but if the fielder goes home, it's a much lower percentage play than a squeeze with a successful bunt. In general squeeze plays are desperate attempts when there is no other hope (generally a terrible batter is up). Article here goes more in depth.
The most conventional option here is the sacrifice fly. In this play the batter attempts to hit a fly ball deep enough to score the runner from third (the runner is allowed to tag the base and advance if the ball is caught and there aren't 3 outs). The problem here is that trying to hit a sac fly isn't actually something hitters have much control over.
For a lot of hitters, hitting a deep fly ball isn't a great option (they just don't have the power or that's simply not their game). In this case, a sharp grounder to the right side of the infield may lead to the run that they need. Usually when there is a runner on third and the game is very close, the infield will play in on the grass, this provides them with ample opportunity to throw the ball home, but leaves them susceptible to well hit grounders getting through to the outfield scoring hte runner. Again, this isn't necessarily something hitters have a huge amount of control over.
The last option is actually the best in a late and close situation if you are down a run. That is simply to change nothing about your approach. Here's the thing, if there are fewer than 2 outs, there is a runner on third, just simply taking a normal approach leaves you with a run expectancy of between 1.43 (0 out), and .989 (1 out). The odds of scoring a single run are between 85% (1 out) and 67%.

So from the fact that squeezes are high risk, relatively low reward (back yourself out of a potential big inning or worse any run scoring situation at all) and the fact that how you hit the ball is something of a crapshoot, the absolute best thing you can do is...rely on your hitters to do their jobs.
The truth is, with an average ML hitter at bat (or even any hitter above replacement level one to be honest), your best bet is actually to just let them bat. You'll score about 1 run per inning in a situation with a runner on third and 1 out. That's not a guarantee, but that's probably about as close as you come in baseball.


CSS Transition Questions

Question: I've got 2 questions (and I'm pretty novice, so be gentle please). The questions are related to this jsfiddle.

On the sample url below, why aren't my transitions working at all on chrome. I thought webkit was what I needed for chrome!
Is there an easier way to override a transition? I'm currently adding a mouseDown specifically just so I can nix the transition, but it feels clunky.
Answer: Try this. Syntax for transition in the JavaScript was wrong.
This is the correct way :)
testDiv.style.setProperty("-webkit-transition", "top .3s linear");

testDiv.style.top = "100px";

theBtn.addEventListener('mouseup', function(e) {
  btnUpFunc();
}, false)

theBtn.addEventListener('mousedown', function(e) {
  btnDownFunc();
}, false)

function btnDownFunc() {
  testDiv.style.setProperty("-webkit-transition", "none");
  testDiv.style.top = "50px";
}

function btnUpFunc() {
  testDiv.style.setProperty("-webkit-transition", "top .3s linear");
  testDiv.style.top = "100px";
}
#testDiv {
  position: absolute;
  background-color: rgba(255, 0, 0, .5);
  width: 125px;
  height: 40px;
  -webkit-transition: top 0.4s ease-in-out 0;
}
#theBtn {
  left: 150px;
}

Hello World

<button id="theBtn" type="button">Click Me!</button>
Comment: Thanks, that makes more sense for sure. However, why won't it do the initial slide down in chrome like it does in firefox. In FF, the second the page loads, the div slides down because I've to a transition in the CSS and I adjust the top for that div immediately in the JS. Works on FF, but not Chrome :-\
Answer: The transition property is now fully supported by all major browsers for a while, so -webkit- is no longer needed (http://caniuse.com/#search=transition)
For your issue, just change
transition: top 0.4s ease-in-out 0;

to
transition: top 0.4s ease-in-out;

I know it seems weird, but since a delay of 0s is not recognized, the browsers assume that 0 is a new duration time, and override the 0.4s duration that was set before, resulting in a 0s transition.
Comment: Most excellent, thanks a bunch! I have so much to learn. And so happy to just use transition, my main code has all of the -moz -o -ms stuff in it, it's ugly. I have to get in the habit of checking caniuse i suppose!
Answer: If you remove the below lines
testDiv.style.webkitTransition = "none";
testDiv.style.webkitTransition = "top 0.4s ease-in-out 0";

And remove the delay value (or change it to 0s), then works properly.
http://jsfiddle.net/hpm6wzuh/5/

CSS Transition Questions


Distributing candies

Question: Suppose ther are B boys and G girls in a classroom.Teacher wants to distribute candies among B boys and G girls such that:
1.Each student gets atleast one candy and atmost N candies.
 2.sum of candies given to all boys equals sum of candies given to all girls.
find the number of different ways to do it.
Note:Two ways are considered different if there exists a student that received different number of candies in these two candies' distributions.
Example:
if B=1 G=2 N=3 there are 3 ways, they are: (2, 1, 1), (3, 1, 2), (3, 2, 1).
if B=2 G=2 N=2 there are 6 ways, they are: (1, 1, 1, 1), (1, 2, 1, 2), (1, 2, 2, 1), (2, 1, 1, 2), (2, 1, 2, 1), (2, 2, 2, 2).
How to approach this problem?
Comment: There need not be more than $N(B+G)$ candies or in fact $2N\min(B,G)$ candies
Comment: Due to the symmetry of the problem, you may as well assume that $B \leq G$.
Comment: what is the total number of candies?
Comment: Assume Candies are infinite...
Comment: @Henry: yes you are right about that
Comment: is G<B or B<G${}{}{}$
Comment: no such restriction is there on G and B.
Answer: With the function $c(m,x,t)$ counting the number of ways of distributing $m$ candies among $x$ people so nobody received more than $t$ (but they could receive zero), the answer would be $$\sum_{m=\max(B,G)}^{N\min(B,G)}\; c(m-B,B,N-1)c(m-G,G,N-1)$$
Added:  To calculate $c(m,x,t)$, note that for all $t$ you start with $c(0,0,t)=1$ and $c(m,0,t)=0$  for $m \gt 0$, and then for $x\gt 0$ you can use:
$$c(m,x,t)=\sum_{j=0}^{\min(m,t)} c(m-j,x-1,t).$$
E.g. if $t=1$ then you get a table for $c(m,x,t)$ starting
x  m:0 1 2 3
-  ---------
0    1 0 0 0
1    1 1 0 0
2    1 2 1 0
3    1 3 3 1

while if $t=2$ then you get a table for $c(m,x,t)$ starting
x  m:0 1 2 3
-  ---------
0    1 0 0 0
1    1 1 1 0
2    1 2 3 2
3    1 3 6 7

Considering your example of $B=1$, $G=2$, $N=3$ we get $$c(2-1,1,3-1)c(2-2,2,3-1)+c(3-1,1,3-1)c(3-2,2,3-1)$$ $$=c(1,1,2)c(0,2,2)+c(2,1,2)c(1,2,2)$$ $$=1\times 1 + 1\times 2 = 3$$
while considering your example of $B=2$, $G=2$, $N=2$ we get $$c(2-2,2,2-1)c(2-2,2,2-1)+c(3-2,2,2-1)c(3-2,2,2-1)+c(4-2,2,2-1)c(4-2,2,2-1)$$ $$=c(0,2,1)c(0,2,1)+c(1,2,1)c(1,2,1)+c(2,2,1)c(2,2,1)$$ $$=1\times 1 + 2\times 2 + 1\times 1 = 6$$
so this approach reproduces your expected results.
Comment: how to check if sum of candies given to boys is equal to sum of candies given to girls!!also each student receives atleast one candy!!
Comment: @savvi singh: the number of ways of distributing $m-B$ balls among $B$ boys so each gets no more than $N-1$ is the same as the the number of ways of distributing $m$ balls among $B$ boys so each gets no more than $N$ and each gets at least one. Similarly the number of ways of distributing $m-G$ balls among $G$ girls so each gets no more than $N-1$ is the same as the the number of ways of distributing $m$ balls among $G$ girls so each gets no more than $N$ and each gets at least one. So this  meets both your points. Calculating $c(m,x,t)$ is the hard part.
Answer: Each boy should get G number of candies and each girl should get B number of candies.  This would ensure that sum of the candies received by boys and girls is equal.

Distributing candies


Find $f:\mathbb R\to\mathbb R$ such that $f(x)=f'(x)$.

Question:
Find $f:\mathbb R\to\mathbb R$ such that $f(x)=f'(x)$.

I know that $f(x)$ can be $e^x$, but how to solve this mathematically? Are there any other solutions? Thank you.
Answer: Let $f : \mathbb{R} \to \mathbb{R}$ such that $f'(x)=f(x)$ for all $x \in \mathbb{R}$. Set $g(x)=f(x)e^{-x}$. Then $g'(x)=0$, hence $f(x)=C \cdot e^{x}$ for some $C \in \mathbb{R}$.
Comment: $g'=0$ so $g$ is constant, say $g(x)=C$. Therefore, $f(x)=g(x)e^{-x}=C. e^x$.
Comment: How to get $f(x)=Ce^x$?
Answer: By integrating $f'/f$, you can get to the solution $f(x) = Ce^x$. Now if you want to prove that it is the only solution, my suggestion is as follows:
Hint: Let $f$ be such a function, and let $g(x) = f(x)e^{-x}$. Now calculate $g'(x)$. Can you now prove the result?
Answer: You have the problem
$$f'(t) = f(t)$$
$$f(0) = x_0$$
The solution you already know is
$$f(t) = x_0e^t$$
Suppose $Y(t)$ is another solution of the same problem. Consider
$$y(t,s) = e^{(t-s)}Y(s).$$
The map $s \to y(t,s)$ is continuosly differentiable and
$$\frac{\partial y(t,s)}{\partial s} = e^{(t-s)}\frac{dY(s)}{ds} -e^{(t-s)}Y(s) = e^{t-s}Y(s) - e^{t-s}Y(s) = 0.$$
This implis that $y(t,s)$ is constant in $s$ and therefore
$$x_0e^t = y(t,0) = y(t,t) = Y(t)$$
I hope this can help you!
Comment: Oh, no @user67133 : I *do* like your answer. It is pretty elegant and nice. I just pointed out about the *apparent* level of the asker and his probable problems to understand it, but it is just cool and, in fact, +1 since it can help others (say, I myself :) to see things slightly different. Thanks.
Comment: Why go into partial diff. equations? It seems to be the OP is new to this stuff (otherwise he wouldn't make such an elementary question), and going into this seems to be way too advanced to her/him.
Comment: I only did it because there were other good answers and because I wanted to share this, in my opinion, elegant proof that I read some time ago. I am sorry that you don't like my comments :(
Answer: Simple elementary differential equation. Put $\,y=f(x)\,$ , then::
$$f'(x)=f(x)\iff \frac{dy}{dx}=y\implies \int\frac{dy}{y}=\int dx\implies$$
$$\implies \log y=x+c\implies y=e^{x+c}=Ke^x\;,\;\;K:=e^c=\text{ a constant}$$
Comment: This method leaves out the zero solution. A small remark: $y$ could be negative, so you want $\log|y|=x+c$, so then $y=\pm e^c e^x$.


Given day, month and year, calculate weekending date

Question: Given day, month and year as integer columns in the table, calculate the date and weekending date from these values.
I tried the following but it gives me an incorrect result for the derived date as '2022-08-05 00:00:00'
select to_date(2020||03||20,'YYYYMMDD')

Even tried below but results in a string without leading zeros for month and day
select  (cast (2020 as varchar)+cast (03 as varchar(2))+cast (02 as varchar(2)))

Result for above is : 202032
Comment: Could you please edit your question to provide some sample inputs and their corresponding outputs that you would like to see?
Answer: The problem is that you have numbers -- so leading zeros are missing.  You can try:
select to_date('2020'||'03'||'20', 'YYYYMMDD')

Or, if these have to be numbers:
select to_date( (2020 * 10000 + 03 * 100 + 20)::text, 'YYYYMMDD')


Non-flatness of the map $\mathbb C[s,t]\to \mathbb C[x, y]$ sending $s$ to $x$ and $t$ to $xy$.

Question: I would like to ask if there is a simple way to prove the non-flatness of the above morphism of rings using just the definition of a flat module.
Answer: Consider the injection $(s,t) \rightarrow \mathbb{C}[s,t]$. Tensor with $\mathbb{C}[x,y]$ and notice that the result is not injective. Indeed, the natural map $(s,t) \otimes_{\mathbb{C}[s,t]}\mathbb{C}[x,y]\rightarrow \mathbb{C}[x,y]$ sends $s \otimes y$ and $t \otimes 1$ to the same place. It is easy to check that these are not the same element of the tensor product.
In general, if something is not flat then there is some finitely generated ideal $I \subset R$ that will witness this failure.
Comment: Dylan, many thanks for your answer!
Comment: In fact, I have one more question. How have you found out this proof, i.e. why did you chose $I=(s,t)$? What is the intuition?
Comment: I knew there had to be some finitely-generated ideal that worked... and it sort of felt right that the equation $sy = t$ would be important for reasons that I don't know how to put in words... so I tried $(s,t)$, and it worked.
Comment: I'm failing to see why $s \otimes y$ and $t \otimes 1$ are distinct in the tensor product.  They, of course, LOOK different, but can you give an explanation as to why they are different?  Like, why there's no way to rewrite $s \otimes y$ as $t \otimes 1$ with some tricky maneuvering?


alternative of time for a seed to a random number generator?

Question: In Go what value can one use as an alternative of current time
for a seed to a random number generator?
This simple question came to me as I was following the Tour of Go
where they say the current time in their sandbox environment is fixed.
Comment: Generally, instead of something as deterministic as the current time, you can use another PRNG or even a true source of random to seed the PRNG. This is not specific to Go though, it applies to any programming language. Why would you need that though?
Comment: Anything in the sandbox used by the tour/docs/playground can be assumed to be somewhat deterministic; the random seed is fixed, the time is fixed, and repeated executions of the same code return cached results. None of this matters when running code in any real environment.
Comment: If you're worried about the `math/rand` PRNG being deterministic (which it is for a reason), you should be using `crypto/rand`
Comment: I was asking exactly with the Tour of Go in mind i.e. how to get a random number there.
Comment: You can't really. It's just a test environment to learn how the language works.
Comment: @Adrian Seems I can with the answer given below by Burak. Also the Tour itself says we can, we just need to think how to do it without using current time. Not sure why my question was downvoted. Seems a good question to me, not too obvious how to do that in the Tour. But lately anything is downvoted here in SO...  Seems like all good questions have been asked already :)
Comment: You still can't. If you keep running the same code, you'll keep getting the same results. `crypto/rand` also likely does not have a real random source in the playground. See here for more info on how playground works: https://blog.golang.org/playground
Comment: @Adrian I tried it and it seems to work pretty well. So I am not sure how likely is the likely you mentioned. I needed something simple here, not to dig so deeply at this stage. Thanks anyway.
Answer: You can use crypto.rand package to read some random bytes, and convert that to a int64:
import (
  "crypto/rand"
  "encoding/binary"
)
...

b:=make([]byte,8)
rand.Read(b)
seed:=binary.BigEndian.Uint64(b)

Comment: Just as a warning, this doesn't turn the PRNG into a source of randomness suitable for cryptography!
Comment: Yes, this is simply a random seed value.
Answer: If you want access to the math/rand convenience functions without the deterministic PRNG, you can create a new secure rand.Source yourself.
type cryptoSource [8]byte

func (s *cryptoSource) Int63() int64 {
    const mask = (1 << 63) - 1
    crand.Read(s[:])
    i := int64(binary.BigEndian.Uint64(s[:]))
    return i & mask
}

func (cryptoSource) Seed(int64) {}

https://play.golang.org/p/sD4fOkE8LeD