text:
Q: JavaScript - Find a word string out of strings in an array I am trying to find a word from consecutive strings inside an array and I am stuck at the moment.
For example: array = ['w', 'r', 'a', 'p', 'p', 'l', 'e', 'f', 'k', 'l']; I want to make a function that will return true if the word 'apple' is inside this array. Strings need to be consecutive.
array1 = ['w', 'r', 'a', 'p', 'l', 'p', 'e', 'f', 'k', 'l']; function for this kind of strings with no consecutive 'apple' strings should return false.
Can you help please?

A: One approach would be traverse your array, and get substrings of length that equals the length of the matching substring, and compare the substring with the matching substring
for (int i=0; i<array.length-matching.length; i++) {
    if (array.substr(i, i+matching.length) == matching) return true;
} return false;

A: Try this:

var array = ['w', 'r', 'a', 'p', 'p', 'l', 'e', 'f', 'k', 'l'];

function findWord(arr, word) {
  return arr.join('').indexOf(word) !== -1;
}

// test
console.log('apple: ', findWord(array, 'apple'))
console.log('dog: ', findWord(array, 'dog'))

A:

array = ["w", "r", "a", "p", "p", "l", "e", "f", "k", "l"];

console.log(array.toString().replace(/,/g,"").indexOf("apple")>-1);

A: check this function:
function hasWord(inputSourceList, inputWord) {
    return inputSourceList.join('').indexOf(inputWord) > -1;
};

A: With Array.join(), String.replace() and String.indexOf() functions:

var contains_word = function(arr, w) {
    return arr.join('').replace(new RegExp('[^' + w + ']', 'g'), '')
           .indexOf(w) !== -1;
}

console.log(contains_word(['w', 'r', 'a', 'p', 'l', 'p', 'e', 'f', 'k', 'l'], 'apple'));
console.log(contains_word(['w', 'r', 'a', 'p', 'p', 'l', 'e', 'f', 'k', 'l'], 'apple'));

A: You can use a combination of Array.every(), and Array.indexOf() to check if all letters are found in the correct order:

const findWordInArray = (word, array) => {
  let last = -1; // stores the last index found

  // iterate the letters of the word
  return [...word].every((c) => {
    // search for the letter from the last known position + 1 onwards
    const index = array.indexOf(c, last + 1);
    last = index; // change last to the new found position
    return index !== -1;
  });
}

const array1 = ['w', 'r', 'a', 'p', 'p', 'l', 'e', 'f', 'k', 'l'];
const array2 = ['w', 'r', 'a', 'p', 'l', 'p', 'e', 'f', 'k', 'l'];
const word = 'apple';

console.log(findWordInArray(word, array1));
console.log(findWordInArray(word, array2));


text:
Q: How to get State Code from Region Id in Magento 2.1.9 I am trying to get state code form Region ID.
e.g. If my region id = 12 state code should be CA.
This is what I am doing right now.
$regionObject = $objectManager->get('Magento\Directory\Model\RegionFactory');
$regionModel = $regionObject->create();
$region = $regionModel->loadByCode($regionId, $countryCode);
$shipFromState = $region->getName();

I am trying to get shipping origin address. If there is a good way to get the address that will be nice. Currently I am getting shipping information using following code
$scopeConfig = \Magento\Framework\App\ObjectManager::getInstance()
                ->get('\Magento\Framework\App\Config\ScopeConfigInterface');
$regionId = $scopeConfig->getValue('shipping/origin/region_id', \Magento\Store\Model\ScopeInterface::SCOPE_STORE);

A: Try this one:
    $_regionFactory- = $objectManager->get('Magento\Directory\Model\RegionFactory');
    $regionModel = $_regionFactory->create();

    if (is_numeric($regionId)) {
        $shipperRegion = $this->_regionFactory->create()->load($regionId);
        if($shipperRegion->getId()){
            $shipperRegionCode = $shipperRegion->getCode();
            print_r($shipperRegionCode>getData());
    }
}

Note:Direct use of object manger is not good Idea.
If you  going to add try this on block class,Helper,Model,ResourceModel class Then My suggestion is that
Inject the factory class  at __construct function then get region data by  dependency inject.
protected $_regionFactory;
protected $_scopeConfig;
public function  __construct(
  ...
  \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
  \Magento\Directory\Model\RegionFactory $regionFactory,
  ...
) {
  $this->_scopeConfig = $scopeConfig;
  $this->_regionFactory = $regionFactory;
  ...
}

public function getShippingregion()
{
      $shipperRegionId = (int) $this->_scopeConfig->getValue('shipping/origin/region_id',
          ScopeInterface::SCOPE_STORE,
          [StoreId]
      );

      if (is_numeric($shipperRegionId)) {
          $shipperRegion = $this->_regionFactory->create()->load($shipperRegionId );
          $shipperRegionCode =$shipperRegion->getCode();
      }
}

A: Try below code:
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$region = $objectManager->create('Magento\Directory\Model\Region')->load(12); // Region Id
print_r($region->getData());
?>

Output:
Array
(
    [region_id] => 12
    [country_id] => US
    [code] => CA
    [default_name] => California
    [name] => California
)

Note: Please do not use Object Manager. Instead create function and then call it.

A: <?php
    namespace MODULENAMESPACE\MODULENAME\Helper;

    use \Magento\Directory\Model\RegionFactory;
    use \Psr\Log\LoggerInterface;

    class Data extends AbstractHelper {
           protected $_regionFactory;
           protected $_logger;

           public function __construct(
              RegionFactory $regionFactory,
              LoggerInterface $logger
           ){
              $this->_regionFactory = $regionFactory;
              $this->_logger = $logger;
           }

            /**
             * Gets the region data from state ID.
             * @param $state - numbers state ID
             *
             * @return array [region_id],[country_id],[code],[default_name],[name]
             */

            public function getRegionDataByName($state, $countryId = 'US') {
                try {
                    $region   = $this->_regionFactory->create();
                    $regionData = $region->loadByName($state, $countryId);
                    return $regionData;
                }
                catch(\Exception $e) {
                    $this->_logger->critical($e->getMessage());
                    return false;
                }
            }
    }
?>

* Get code *
call helper
<?php
    $helper = $this->dataHelper; //construct it before call
    $helper->getRegionDataByName($address->getRegion())->getCode();
?>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Potion Tier 2 bug with toItemStack() method this code doesn't work when I put tier_two or 2. However, if I put it to 1 or One it works. Does someone have an idea ?
Potion heal = new Potion(PotionType.INSTANT_HEAL, Tier.TWO, true);
contents[3] = heal.toItemStack(1);

For information the content is an ItemMeta [] which I use to create a kit

A: You need to give a integer as the effect "strength". I don't know what the Tier belongs to, but maybe that will interrupt it?
Try to use:
Potion heal = new Potion(PotionType.INSTANT_HEAL, 2, false)


text:
Q: How to trig a function from Iframe to his parent ? I have a web page loading a iframe (inside a modal Fancybox) and this iframe contains a form with 2 pages.
I want this iframe content to ask the parent to trig a function (so the modal can be resized when the 2nd page of the form is shown)
    $.fancybox.update();

When executed in the iframe, it doesn't work because it needs to be in parent context. So far, I managed to do it with binding a click on the "next page" button inside the iFrame.
    $('body iframe').contents().find('.goToPage2').bind('click', function (e) {
            $.fancybox.update();
    });

This was working.
But now, I have to do it without waiting for a click (it has to happen after getting an ajax response). So I tried to bind a "show" action, and make a div appear with after(), but it didn't work.
    $('body iframe').contents().find('#page2').bind('show', function (e) {
            $.fancybox.update();
        });

I also tried to reach the parent directly from the iframe but with no luck in my case (fancybox) :
    $('#page2', window.parent.document).fancybox.update();

If anyone can explain how I can achieve this, I will be grateful :-)


text:
Q: Hive dynamic partition in insert overwrite from select statement is not loading the data for the dynamic partition Hive dynamic partition in insert overwrite from select statement is not loading the data for the dynamic partition instead it gives the data HIVE_DEFAULT_PARTITION.
If I say show partitions table2;
it just give only one partition detail which is HIVE_DEFAULT_PARTITION
I have a staging table without any partitions which reads data from a sequence file.
CREATE EXTERNAL TABLE IF NOT EXISTS table1(DS string, col1 string, col2 string, col3 string)
ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t'
STORED AS SEQUENCEFILE
LOCATION '/user/'
tblproperties ("skip.header.line.count"="1");
The date format is m/d/yy for the field DS which is coming from the file.
Then I am creating production table like below.
CREATE EXTERNAL TABLE IF NOT EXISTS table2(col1 string, col2 string, col3 string)
PARTITIONED BY (DS string)
STORED AS SEQUENCEFILE
tblproperties ("skip.header.line.count"="1");
set hive.exec.dynamic.partition.mode=nonstrict;
Then the insert query as below
INSERT OVERWRITE TABLE table2 PARTITION (DS)
SELECT col1, col2,col3, cast(DS as date)
FROM table1;
When I query the table 2 I get the result as below
d1 d2 d3 HIVE_DEFAULT_PARTITION
d4 d5 d5 HIVE_DEFAULT_PARTITION
for the last column where I expect a date field from my partition column instead I get HIVE_DEFAULT_PARTITION
My expected data is like
d1 d2 d3 5/1/17
d4 d5 d5 5/1/17
Can anyone help on this?

A: The only format you can cast directly to date is yyyy-mm-dd any attempt to cast from another format results in NULL, therefore all your records go to the default partition.

*

*Define the partition column as DATE (PARTITIONED BY (DS date))

*Use  to_date(from_unixtime(to_unix_timestamp(DS,'M/d/y'))) for conversion

Demo
hive> select cast('5/1/17' as date) as ds;
OK
ds
NULL

hive> select cast('2015-05-01' as date) as ds;
OK
ds
2015-05-01

hive> select to_date(from_unixtime(to_unix_timestamp('5/1/17','M/d/y'))) as ds;
OK
ds
2017-05-01


text:
Q: USAMO 2005, Problem3 (Triangle Geometry)- Is my solution correct? USAMO 2005, Problem 3: Let $ABC$ be an acute-angled triangle, and let $P$ and $Q$ be two points on its side $BC$. Construct a point $C_{1}$ in such a way that the convex quadrilateral $APBC_{1}$ is cyclic, $QC_{1}\parallel CA$, and $C_{1}$ and $Q$ lie on opposite sides of line $AB$. Construct a point $B_{1}$ in such a way that the convex quadrilateral $APCB_{1}$ is cyclic, $QB_{1}\parallel BA$, and $B_{1}$ and $Q$ lie on opposite sides of line $AC$.  Prove that the points $B_{1}$, $C_{1}$, $P$, and $Q$ lie on a circle.
Here is a solution I found for the problem mentioned above:
Define $X=C_1Q \cap AB$ and $Y=B_1Q \cap AC$. Since $AX \parallel QY$ and $AY \parallel QX, AXQY$ is a parallelogram $(1)$.
By power of point $X$ in $(APB)$ and of point $Y$ in $(APC)$ we have $XA\times XB=XC_1 \times XQ$ and $YA \times YC= YB_1 \times YQ$.
Therefore $\frac{XB}{XC_1}=\frac{XQ}{XA}=\frac{AY}{QY}=\frac{YB_1}{YC}$ (using  $AX=QY$ and $XQ=AY$ derived from $(1)$ ). $(2)$
Also, from $(1)$ we have that   $\angle{C_1XB}=\angle{CYB_1}$ and by combining this with $(2)$ we have that $\triangle{C_1XB}$ and $\triangle{CYB_1}$ are similar.
Since the two pairs of corresponding sides in this similar triangles are parallel, the third pair is parallel too. i.e., $C_1B\parallel B_1C$ $(3)$.
Note that $\angle{BC_1A}=\angle{APC}=180^{\circ}- \angle{AB_1C}$ and from $(3)$ $C,A,B$ collinear.
Then the result follows, since $\angle B_1C_1P=\angle AC_1P=\angle ABP=\angle B_1QC=\pi-\angle B_1QP$.
Am I doing something wrong?
(this solution seems pretty easy, and nobody noticed it before. That makes me question its validy)

A: Let $\ell$ be an arbitrary line through $A$ not passing through the interior of triangle $ABC$. Let $B_3$ and $C_3$ be the second intersections (other than $A$) of $\ell$ with the circumcircles of triangles $APC$ and $APB$, respectively; these points both lie on the same side of the line $BC$ as does $A$. (note that one of these intersections may coincide with $A$ in case $\ell$ is tangent to one of the two circles.) Let $Q_1$ be the second intersection (other than $P$) of the line $BC$ with the circumcircle of triangle $B_3C_3P$. (Again, this may coincide with $P$ in case $BC$ is tangent to the circle at $P$.) In case $Q_1$ lies between $B$ and $P$, we have$$\angle C_3Q_1P = 180^\circ - \angle PB_3C_3 = 180^\circ - \angle PB_3 A = \angle ACP,$$by noting that $B_3C_3Q_1P$ and $AB_3CP$ are cyclic; in case $P$ lies between $B$ and $Q_1$, we have$$\angle C_3 Q_1P = \angle C_3B_3P = \angle AB_3P = \angle ACP$$by noting that $B_3C_3PQ_1$ and $AB_3CP$ are cyclic. In either case, $C_3Q_1$ is parallel to $AC$; similarly, $B_3Q_1$ is parallel to $AB$.

In case $Q = Q_1$, the points $C_1$ and $C_3$ both lie on the line through $Q$ parallel to $AC$, and both lie on the same side of $BC$ as does $A$. There is only one such point, so $C_1 = C_3$; similarly $B_1 = B_3$. In particular, if $Q = Q_1$, then the points $B_1 = B_3$, $C_1 = C_3$, $P$, $Q = Q_1$ lie on a circle.
It thus suffices to show that there exists some $\ell$ such that $Q = Q_1$. To see this, note that $\ell$ may be rotated continuously between the position where it coincides with $AB$, in which case $C_3 = Q_1 = B$, and the position where it coincides with $AC$, in which case $B_3 = Q_1 = C$. As $\ell$ rotates, $Q_1$ moves continuously along the line $BC$, so at some point it must pass through $Q$. As noted above, this implies the desired result.
Remark. The point $Q_1$ need not move directly from $B$ to $C$; it may first move in the opposite direction (away from $C$) before changing course and heading towards $C$. Likewise, it may overshoot $C$ before finally settling at $C$. All that matters is that the motion is continuous, so the point $Q$ must be passed through somewhere along the way.


text:
Q: How many even 3 digit integers greater than 700
How many even 3 digit integers greater than 700 with distinct non zero
  digits are there ?

My answer is:

*

*the only hundred digit that are possible are 7, 8 and 9 (3)

*the only ten digit that are possible are 1, 2, 3, 4, 5, 6, 7, 8, 9
(9)

*the only unit digit that are possible are 2, 4, 6, 8 (4)

what I did is: $$ 3 \times 9 \times 4 = 108 $$
Where is my problem? Answer is given 77.

A: Your problem is not taking into account the word "distinct".
Edit: I'm adding some in response to further questioning in the comments.
Because of the "distinct" condition (combined with the even condition), you have to consider cases more carefully. The digit choices are not independent, so you can't just multiply.  But if you break things up into mutually exclusive cases where the digit choices are independent, you can multiply for each, then add them all together.
For example, counting numbers with first digit odd, second digit odd yields $2\times 4\times 4$.
There are essentially $4$ cases to work with in this way. Count each then add them up.

A: It's a bit like combinations. You have possible first digits $7,8,9$. For $7$ there are $8$ possible second digits $1,2,3,4,5,6,8,9$ and for each of the latter either $3$ or $4$ third digits. I guess, you know hot to proceed from here.

A: There are 299 numbers between 700 and 999.
Out of those you need to exclude, digits having 0 in the units place and digits having 0 in the tens place. So that's 30+27=57.
There are 149 odd numbers between the range. So your premise reduces to 93. These are all the zero less even numbers.
Out of the remaining, remove the numbers having multiple of 11 in tens and unit place,and Which are even like 722,744,822 and so on. These are 4 per 100 range so that's 12.  So we reach to 81.
Finally, remove remaining numbers with non distinct digits,which did not belong to above criteria. These are only four 988,998,898 and 848. So the answer is 77 even,non zero distinct digit numbers.


text:
Q: JSP - Continue only if this id exists I am very new to JSP. I have following code.
         var code = $('#codeForm').find('#disCode');
         var disCodeVal = disCode.val().trim();

The #discode is an input field which is either defined or not based on some condition. How can i add an if condition to test if #discode is defined and only if it is defined then proceed to getting disCodeVal?
EDIT: Based on a condition when the page loads it will either have an input field called disCode or not.
  <c:if test="${url eq 'test'}">
         <a:fixedGridColumn position="${'last'}" fixedColumn="${'left'}" >
              <a:textInput id="disCode" name="code" value="${disCode}" required="true" />
        </a:fixedGridColumn>
  </c:if>

Then when submit button is clicked a function is attached to it as follows.
<script type="text/javascript">
 P.when("jQuery").execute(function($) {

     $("#submitBtn").click( function(e) {
            var code = $('#codeForm').find('#disCode');
            var disCodeVal = disCode.val().trim();
            ..// more validation code for other input fields which are always present

Now i want to only activate the above two lines on the click of the button if disCode input field exists.

A: Sounds like you are having JQuery code in your JSP. It is simple. If the element doesn't exist (not defined), the JQuery selector will give you 0 as its length.
Do it like following:
if($('#disCode').length > 0) {
   ...
}


text:
Q: How to set up query arguments to `link_to` mojolicious helper? I want to pass arguments for link generated by link_to helper:
%= link_to 'Change password' =>  'auth_remind', { login => $login }

but this does not work.
How to set up query arguments?

A: It is not documented yet, but in default welcome.html.ep we can found:
%= link_to 'click here' => url_for

So we can do next:
%= link_to 'Change password' =>  url_for( 'auth_remind' )->query( login => $login )

If we need to set up some arguments for route we may:
%= link_to 'Change password' =>  url_for( 'auth_remind', { format => 'txt' } )->query( login => $login )


text:
Q: Flatten RDD[(String,Map[String,Int])] to RDD[String,String,Int] I am trying to flatten an RDD[(String,Map[String,Int])] to  RDD[String,String,Int] and ultimately save it as a dataframe.
    val rdd=hashedContent.map(f=>(f._1,f._2.flatMap(x=> (x._1, x._2))))
    val rdd=hashedContent.map(f=>(f._1,f._2.flatMap(x=>x)))

All having type mismatch errors.
Any help on how to flatten structures like this one?
EDIT:
    hashedContent -- ("A", Map("acs"->2, "sdv"->2, "sfd"->1)),
                     ("B", Map("ass"->2, "fvv"->2, "ffd"->1)),
                      ("c", Map("dg"->2, "vd"->2, "dgr"->1))

A: You were close:
rdd.flatMap(x => x._2.map(y => (x._1, y._1, y._2)))
   .toDF()
   .show()
+---+---+---+
| _1| _2| _3|
+---+---+---+
|  A|acs|  2|
|  A|sdv|  2|
|  A|sfd|  1|
|  B|ass|  2|
|  B|fvv|  2|
|  B|ffd|  1|
|  c| dg|  2|
|  c| vd|  2|
|  c|dgr|  1|
+---+---+---+

Data
val data = Seq(("A", Map("acs"->2, "sdv"->2, "sfd"->1)),
               ("B", Map("ass"->2, "fvv"->2, "ffd"->1)),
               ("c", Map("dg"->2, "vd"->2, "dgr"->1)))

val rdd = sc.parallelize(data)

A: For completeness: an alternative solution (which might be considered more readable) would be to first convert the RDD into a DataFrame, and then to transform its structure using explode:
import org.apache.spark.sql.functions._
import spark.implicits._

rdd.toDF("c1", "map")
  .select($"c1", explode($"map"))
  .show(false)

// same result:
// +---+---+-----+
// |c1 |key|value|
// +---+---+-----+
// |A  |acs|2    |
// |A  |sdv|2    |
// |A  |sfd|1    |
// |B  |ass|2    |
// |B  |fvv|2    |
// |B  |ffd|1    |
// |c  |dg |2    |
// |c  |vd |2    |
// |c  |dgr|1    |
// +---+---+-----+


text:
Q: Pokemon basic moves: Higher damage strictly better? Normal moves seem generally more damaging than types like electricity. Do "Thunder Shock" at 5 damage have any advantage over "Tackle" at 12?
If the "Thunder Shock" would grant 2x damage against Water type, then would it still be 10 damage versus 12 of "Tackle"?

A: TL;DR
There's more to a move than just the damage. There's a speed factor that affects the overall DPS. Faster moves also make it easier to dodge.

The moves have three main characteristics to them: Damage, Speed, and Type.
Damage is the number next to the attack, showing how much damage it will do to an enemy. Type is shown below the name and is used when determining type advantages for additional or reduced damage. Speed doesn't not seem to appear anywhere, but it determines how quickly your pokemon can attack.
For speed, I need to do additional testing, but there are some attacks that obvious attack at a faster rate. My Pinsir attacks at blinding speed with Fury Cutter, much faster than my Pidgeot's Steel Wing. But you should note that Fury Cutter does 3 damage while Steel Wing is at 15.
Therefore, it is possible for a lower damage skill to actually out DPS a higher damage skill.
Another important aspect is dodging. If you are using a skill with a long wind-up, your pokemon cannot move for that time. That leaves you vulnerable to attacks. Having a fast move will make it easier for you to react to and dodge attacks. Therefore, even if the DPS is lower, it might be worth it to use the faster, weaker moves.

A: From my experience, the moves with lower attack often have higher attack rates, so you'll get more attacks in within a certain amount of time than the more powerful attacks. So, higher numbers don't necessarily mean better moves.


text:
Q: Removing handlers from python's logging loggers I am playing with Python's logging system. I have noticed a strange behavior while removing handlers from a Logger object in a loop. Namely, my for loop removes all but one handler. Additional call to .removeHandler removes the last handler smoothly. No error messages are issued during the calls.
This is the test code:
import logging
import sys
logging.basicConfig()
dbg = logging.getLogger('dbg')
dbg.setLevel(logging.DEBUG)

testLogger = logging.getLogger('mylogger')
sh = logging.StreamHandler(sys.stdout)
fh = logging.FileHandler('mylogfile.log')
dbg.debug('before adding handlers: %d handlers'%len(testLogger.handlers))
testLogger.addHandler(fh)
testLogger.addHandler(sh)

dbg.debug('before removing. %d handlers: %s'%(len(testLogger.handlers),
                                              str(testLogger.handlers)))
for h in testLogger.handlers:
    dbg.debug('removing handler %s'%str(h))
    testLogger.removeHandler(h)
    dbg.debug('%d more to go'%len(testLogger.handlers))

#HERE I EXPECT THAT NO HANDLER WILL REMAIN
dbg.debug('after removing: %d handlers: %s'%(len(testLogger.handlers),
                                              str(testLogger.handlers)))
if len(testLogger.handlers) > 0:
    #Why is this happening?
    testLogger.removeHandler(testLogger.handlers[0])
dbg.debug('after manually removing the last handler: %d handlers'%len(testLogger.handlers))

I expect that at the end of the loop no handlers will remain in the testLogger object, however
the last call to .removeHandler apparently fails, as can be seen from the output below. Nevertheless
additional call to this function removes the handler as expected. Here is the output:
DEBUG:dbg:before adding handlers: 0 handlers
DEBUG:dbg:before removing. 2 handlers: [<logging.FileHandler instance at 0x021263F0>, <logging.StreamHandler instance at 0x021262B0>]
DEBUG:dbg:removing handler <logging.FileHandler instance at 0x021263F0>
DEBUG:dbg:1 more to go
DEBUG:dbg:after removing: 1 handlers: [<logging.StreamHandler instance at 0x021262B0>]
DEBUG:dbg:after manually removing the last handler: 0 handlers

More interestingly, if I replace the original loop with the following one, the loop
works as expected and no handlers remain in the testLogger object at the end of the loop.
Here is the modified loop:
while len(testLogger.handlers) > 0:
    h = testLogger.handlers[0]
    dbg.debug('removing handler %s'%str(h))
    testLogger.removeHandler(h)
    dbg.debug('%d more to go'%len(testLogger.handlers))

What explains this behaviour? Is this a bug or am I missing something?

A: I would say if the intent for removing the logging handlers is to prevent sending logs to additional handlers (this is the case most of the times) then an alternative approach I follow is to set propagate to False for your current logger.
logger = logging.getLogger(__name__)
logger.propagate = False

That way your log messages will only go to the handlers you explicitly add and will not propagate to parent loggers.

A: I've just found out that you can also do that within a logging .ini file, with the following block:
[logger_stpipe]
handlers=
propagate=1
qualname=stpipe

It basically deactivates all handlers for a given logger. But it's somewhat limited because you have to know the Logger's name in advance.

A: instead of mutating undocumented .handler:
Option 1
logging.getLogger().removeHandler(logging.getLogger().handlers[0])

this way you remove exactly the preexisting handler object via offical api.  Or to remove all handlers:
logger = logging.getLogger()
while logger.hasHandlers():
    logger.removeHandler(logger.handlers[0])

Option 2
logging.config.dictConfig(config={'level': logging.DEBUG, 'handlers': []}

Not only removes but prevents its creation. List root will have [] handlers

A: If you don't want to delete them all (thanks for the tip @CatPlusPlus):
testLogger.handlers = [
    h for h in testLogger.handlers if not isinstance(h, logging.StreamHandler)]

A: This isn't logger-specific behaviour. Never mutate (insert/remove elements) the list you're currently iterating on. If you need, make a copy. In this case testLogger.handlers.clear() should do the trick.


text:
Q: What does REG bits become when you insert a number into the ram address directly? Currently testing stuff in emu8086, and I was wondering, if we had this code:
MOV [0002H], 0005H

In the machine instruction, what would the REG bits become? Does the assembler use a registry to make this possible? If so, which register?
I am not an expert and really just experimenting because of my CS classes.


text:
Q: Inheritance in datacontracts I have a class say supplierAddress which comes from a webservice (it is a datacontact). I then have a second class myAddress which inherits from that class and has a few more constructors and metods.
What I want to do is pass a myAddress back to the webservice. When I pass a cast down myAddress it throws seriazation errors, which makes sence as its a refrence object and the whole object is still being passed even if im casting down.
Is it possible to clone just the base class of an object? Is what im trying to do possible/correct ?

A: You should specify Known types for your base class.
UPDATE: additional clarification.
SOA (Service-Oriented Architecture) paradigm doesn't support such common features like polymorphism or method overloading. This behaviour based on very simple fact: you don't know which platform will consume your service. Its definitely possible to consume your service in platform or language that doesn't support such thing like inheritance or method overloading.
That's why you should create your service functions with unique names and that's why you should explicitly stated what types you're going to pass instead of base class reference.
When you specify known types this information would expose out of your service through metadata and every client could understand how to deal with your responses.


text:
Q: How to removing spacing in SQL I have data in DB2 then i want to insert that data to SQL.
The DB2 data that i had is like :
select char('AAA   ') as test from Table_1

But then, when i select in SQL after doing insert, the data become like this.
select test from Table_1

result :
test
------
AAA

why Space character read into box character. How do I fix this so that the space character is read into.
Or is there a setting I need to change? or do I have to use a parameter?
I used AS400 and datastage.
Thank you.

A: Datastage appends pad characters so you know that there are spaces there. The pad character is 0x00 (NUL) by default and that's what you're seeing.
Research the APT_STRING_PADCHAR environment variable; you can set it to something else if you want.
The 0x00 characters are not actually in your database. The short answer is, you can safely ignore it.

A: When you said:
select char('AAA   ') as test from Table_1

You were not actually showing any data from the table.  Instead you were showing an expression casting a constant AAA as a character value, and giving that result column the name test which coincidentally seems to be the name of a column in the table, although that coincidence doesn't matter here.
Then your 2nd statement does show the contents of the database column.
select test from Table_1

Find out what the hexadecimal value actually is.


text:
Q: Understanding continuity lemma In Mesure Theory, we have a continuity lemma that says $$\text{if} \ u\colon (a,b) \times X \rightarrow \mathbb{R} \ \text{ satisfies that} \ x \mapsto u(t,x) \in \mathcal{L}^1(\mu) \forall t, \ t \mapsto u(t,x) \ \text{is continuous for all }x \in X, \ \text{and} |u(t,x)| \le w(x) \ \forall (t,x) \in (a,b) \ \text{and some} \ w \in \mathcal{L}^1_+(\mu), $$
then the following function is continuous $$t \mapsto \int u(t,x) \ \mu(dx)$$
Okay, but what if $u$ is just a regular function that is not multivariate, and depends on $x$ alone? If $u$ is Lebesgue integrable, can we then write $u(x) = u(t,x)$, and conclude that $t \mapsto \int u(x) \mu(dx)$ is continuous?


text:
Q: Diagnose external hard drive to see if it still works About 3 years ago my husband dropped my connected Western Digital external hard drive from the desk and now it will not connect to the computer. I plug it in and I get an error message

The disk you inserted was not readable by this computer. Initialize...
  Ignore   Eject

Is it possible that the hard drive is not compatible with a Mac? I used the hard drive with my old and now broken HP.
I plugged it into a Windows computer. The computer knows that there is hardware attached but I cannot access the information held on it. Is it hopeless?

A: if the drive stopped working for a windows PC immediately after being dropped, then it is damaged and needs to be replaced.
Since it was formatted for Windows, it is likely that the Mac cannot read the file systems on it, and I would tell you to initialize it, but since you indicate that it was dropped and does not work on windows, you are much better off buying a new one. even if you got it to take a format, it would still be unreliable.

A: It seems odd, that the hard drive would stop working just recently because of a fall 3 years ago. It may just have reached its end of life, but it could also be because of an (accidental) unsafe disconnection.
Unfortunately I don't know how to diagnose failing harddrives on Mac OS. It may help to try with another OS and hope for a more useful error message (or no error at all).
Edit: From the additional info I conclude that most likely at least the USB controller of the harddisk still works.


text:
Q: Transistor bias circuit How can I find the base current of this circuit. I was trying to find \$\beta \$ from \$(\beta+1)I_B = I_E \$. where \$V_{BE}=0.7V, I_E=0.5mA\$

simulate this circuit – Schematic created using CircuitLab

A: That PNP is biased off. I suspect you really intended to put an NPN there, and exchange the E & C ?

A: Edit, now that you've exchanged the PNP for an NPN. Ve = (Ic * R2)-5V. Vb = Vbe + Ve. Ib = (Vc - Vb)/ R3
IF your drawing is correct, then you're thinking about this too much. Vbe = 0.7V. There's a 100,000 ohm resister that the voltage appears across. I= V/R. That's the base current.
BTW, the current should be flowing out of the base in this case.

A: You know the emitter current.  That current through the emitter resistor gives the emitter voltage.  Adding the base-emitter voltage to the known emitter voltage gives the base voltage.  The difference between the collector voltage (known) and the base voltage (just calculated), divided by the base bias resistor, gives you the base current, and you can now calculate beta.


text:
Q: C# Get keyboard input from other application? Currently I'm working on a project that requires me to get keyboard input from another application not written in C# or .NET for that matter.
Let's say I'm in a game (The game is written in C++), and I want to activate something in my program, so I tell my program to activate when I press a key in the game.
I want to make the activation key to be F5.
Is there any way to do this in C#?

A: Thanks xxbbcc!
For anyone stumbling upon this, please use the UserActivityHook in .Net


text:
Q: Conditional Expectation - $E[f(X,Y)|Y]$ I'm trying to prove the following:
Let X and Y be independent random variables on $(\Omega, \mathcal{A}, P)$ with images $(\Omega_X, \mathcal{A}_X)$, $(\Omega_Y, \mathcal{A}_Y)$ and $f: \Omega_X \times \Omega_Y \rightarrow \mathbb{R} $ integrable. Show that $$E[f(X,Y)|Y] = \int f(x,Y) \space \space P^X(dx) $$ I think that I understand why this is true on an intuitive level, but I just can't seem to prove this using the formal definition of conditional expectation. I've been trying to show $$ \int_A \int f(x,Y) \space \space P^X(dx) \space \space dP = \int_A f(X,Y) \space \space dP$$
for every $A \in \sigma(Y)$. Any hints on how to approach this would be very much appreciated - thanks in advance.

A: For suitable $g:\Omega_Y\to\mathbb R$ we find:
$$\begin{aligned}\mathbb{E}\left[g\left(Y\right)\int f\left(x,Y\right)P^{X}\left(dx\right)\right] & =\int g\left(y\right)\int f\left(x,y\right)P^{X}\left(dx\right)P^{Y}\left(dy\right)\\
 & =\int\int g\left(y\right)f\left(x,y\right)P^{X}\left(dx\right)P^{Y}\left(dy\right)\\
 & =\int\int g\left(y\right)f\left(x,y\right)P^{X}\otimes P^{Y}\left(d\left(x,y\right)\right)\\
 & =\int\int g\left(y\right)f\left(x,y\right)P^{\left(X,Y\right)}\left(d\left(x,y\right)\right)\\
 & =\mathbb{E}\left[g\left(Y\right)f\left(X,Y\right)\right]
\end{aligned}
$$where the $4$-th equality is based on independence of $X$ and $Y$.
This states that indeed: $$\int f\left(x,Y\right)P^{X}\left(dx\right)=\mathbb{E}\left[f\left(X,Y\right)\mid Y\right]$$


text:
Q: WordPress add meta box does not save values I am trying to add custom meta fields to save some values and display in the loop. Custom Field shows up on the edit post but it does not save any values. I have read many articles but cannot figure out the solution.
add_action( 'add_meta_boxes', 'add_atomic_score' );
function add_atomic_score()
{
add_meta_box( 'score', 'Atomic Score:', 'atomic_score', 'post', 'side', 'high' );
}
function atomic_score( $post ){
echo '<p>Enter Atomic Score Here: </p>';
$text = get_post_meta($post->ID, 'score', true);
    ?>
<label for="score">Atomic Score: </label>
<input type="text" name="score" id="score" value="<?php echo $text; ?>" />
<?php
}

add_action( 'save_post', 'atomic_reach_save' );
function atomic_reach_save( $post_id )
{

if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;

if( !isset( $_POST['meta_box_nonce'] ) || !wp_verify_nonce( $_POST['meta_box_nonce'], 'my_meta_box_nonce' ) ) return;

if( !current_user_can( 'edit_post' ) ) return;

if( isset( $_POST['score'] ) )
    update_post_meta( $post_id, 'score', esc_attr( $_POST['score'] ) );

}
?>


text:
Q: How to enable Chrome flags for Chrome Web Store extension I am looking for a way to enable getUserMedia flag in chrome://flags for application in Chrome Web Store. Is there a way so that user does not need to go and switch the flag manually ?

A: Any feature that has to be enabled by a flag in Chrome is considered in development or experimental. There is no way to enable them besides a user doing it manually. You should not recommend that general users mess around with flags as they don't have the knowledge or experience to know what they are doing.
Plus since features behind flags can change at anytime without warning, it's only a matter of time before that API changes, breaking your app and then all your users will give your app bad reviews.

A: Currently works as
chrome://flags/#enable-experimental-web-platform-features


text:
Q: How to fix IDE0017 when using File Dialogs I am getting three "Suggestions" IDE0017 Object Initialization cab be simplified.
    private string dbSelect()
    {
        // This is the User File Name Selection
        OpenFileDialog openThis = new OpenFileDialog();
        openThis.DefaultExt = "sqlite";
        openThis.Filter = "SQLite Databases|*.sqlite";
        if (openThis.ShowDialog() == DialogResult.OK)
        {
            return openThis.FileName;
        }
        return null;
    }

    public bool openDatabase()
    {
        OpenFileDialog openThis = new OpenFileDialog();
        openThis.DefaultExt = "sqlite";
        openThis.Filter = "SQLite Databases|*.sqlite";
        if (openThis.ShowDialog() == DialogResult.OK)
        {
            m_dbConnection = new SQLiteConnection("Data Source=" + openThis.FileName + ";Version=3;");
            m_dbConnection.Open();
            return true;
        }
        return false;
    }

   public bool createDatabase()
    {
        SaveFileDialog createThis = new SaveFileDialog();
        createThis.DefaultExt = "sqlite";
        createThis.Filter = "SQLite Databases|*.sqlite";

        if (createThis.ShowDialog() != DialogResult.OK || createThis.FileName.Trim() == "")
        {
            return false;
        }

        m_dbConnection = new SQLiteConnection("Data Source=" + createThis.FileName + ";Version=3;");
        m_dbConnection.Open();

        return true;
  }

How do I reform these to simplify them? They've been fine until VS2017...
And, so far, Google hasn't really helped.
And, I am not sure I like the idea that simplification means placing everything in a single line.
I was taught that readability is important and all in one line is just plain cluttered.
But, I'd hate to miss a trick... I suppose I can just turn it off...

A: Uppon creating a new instance of anything instead of doing MyType myVariable = new MyType(); and then set every property from myVariable line by line you can do MyType myVariable = new MyType() {}; and between the {} you can set the properties you want to set.
For the SaveFileDialog for example you can do :
SaveFileDialog createThis = new SaveFileDialog()
{
    DefaultExt = "sqlite",
    Filter = "SQLite Databases|*.sqlite"
};


text:
Q: Setting AlertDialog with complex string-array resource I have a simple alert dialog as shown below working with a simple string-array (a). I'd like to replace, (a) with a more complex string-array (b) but I am getting a null pointer exception when the dialog tries to resolve the view.
Is this possible or have I done something wrong?
(a)
AlertDialog Code:

  final AlertDialog.Builder dialog = new AlertDialog.Builder(new ContextThemeWrapper(ctx,   R.style.mytheme));
  dialog.setTitle(title);
  dialog.setIcon(R.drawable.ic_launcher);
  dialog.setSingleChoiceItems(R.array.array_items, -1, itemSelectedListener);
  final AlertDialog alertDialog = dialog.create();

array_items.xml:

  <string-array name="array_items">
    <item>option a</item>
    <item>option b</item>
  </string-array>

(b)
array_items_2.xml:

  <string-array name="array_items_2">
    <item>@array/array_items.xml</item>
    <item>@array/array_items.xml</item>
  </string-array>

The second xml will cause the AlertDialog to crash with a NullPointerException.
Have I made a mistake or is this not possible with the AlertDialog without a custom view?

A: Good point ,but not possible ! For this you have to maintain your xml file containing all the information/relation you want to have as static data and grammatically you will have to parse the file and extract information.Other possible ways are SQLite but i won't suggest you to try that because there is no meaning to maintain a table if you are not going to do CRUD operations or so.


text:
Q: perl6/rakudo: Does perl6 enable "autoflush" by default? #!perl6
use v6;

my $message = "\nHello!\n\nSleep\nTest\n\n";

my @a = $message.split( '' );

for @a {
    sleep 0.3;
    .print;
}

Does perl6 enable "autoflush" by default. With perl5 without enabling "outflush" I don't get this behavior.

A: Rakudo enables autoflush by default; the specification is silent about the default.

A: Quoting from the docs regarding auto flush:
'No global alternative available. TTY handles are unbuffered by default, for others, set out-buffer to zero or use :!out-buffer with open on a specific IO::Handle.'
So any printing to stdout is unbuffered and I guess would behave similar to auto flushed stdout of perl5.
Other handles depend on the out-buffer size set.


text:
Q: sqlplus not connecting as "/ AS SYSDBA" I installed oracle database express edition 18c. I'm using windows 10.
when I execute "/ AS SYSDBA" in sqlplus to user-name, it gives the following error.

ERROR:
ORA-28056: Writing audit records to Windows Event Log failed
ORA-28056: Writing audit records to Windows Event Log failed

when I execute below
Enter user-name: SYS AS SYSDBA
Enter password: <password I gave on installation>

it prints below error

ERROR:
ORA-28056: Writing audit records to Windows Event Log failed
OSD-32765: Message 32765 not found;  product=RDBMS; facility=SOSD
O/S-Error: (OS 5) Access is denied.
ORA-28056: Writing audit records to Windows Event Log failed
OSD-32765: Message 32765 not found;  product=RDBMS; facility=SOSD
O/S-Error: (OS 5) Access is denied.

when I try to execute below
Enter user-name: SYSTEM
Enter password: <password I gave on installation>

it prints below error

ERROR:  ORA-01034: ORACLE not available  ORA-27101: shared
memory realm does not exist  Process ID: 0  Session ID: 0
Serial number: 0

So how can I connect to the database?
Note: I cleared all the event logs from event viewer. not worked!!
Additionally by default there are no environment variable set. so I set
set ORACLE_HOME=C:\app\user\product\18.0.0\dbhomeXE
set ORACLE_SID=CLRExtProc

After setting above it provides below error

ERROR:
ORA-12560: TNS:protocol adapter error

so please help me to connect to database
Thank you!!!

A: Probably you have not configured properly the sqlnet.ora file
Try to run this
C:\>sqlplus / as sysdba
SQL*Plus: Release 18.0.0.0.0 - Production on Wed Aug 26 15:49:17 2020
Version 18.4.0.0.0
Copyright (c) 1982, 2018, Oracle. All rights reserved.
ERROR:
ORA-01017: invalid username/password; logon denied

If you get this error, then open the SQLNET.ORA file and edit the following parameter AUTHENTICATION_SERVICES value to NTS. Save it.
SQLNET.AUTHENTICATION_SERVICES= (NONE)
to
SQLNET.AUTHENTICATION_SERVICES= (NTS)

Try again and it should work, as long as the windows service is running. Don't forget to set the ORACLE_SID environment variable
set ORACLE_SID=sid

Where sid is the name of the database you want to connect to. Finally
C:\>sqlplus / as sysdba
SQL*Plus: Release 18.0.0.0.0 - Production on Wed Aug 26 15:49:34 2020
Version 18.4.0.0.0
Copyright (c) 1982, 2018, Oracle. All rights reserved.
Connected to:
Oracle Database 18c Express Edition Release 18.0.0.0.0 - Production
Version 18.4.0.0.0
SQL>

Update
The database can't write into the Windows Event Log.

*

*Open Event Viewer, click Start, click Control Panel, click Performance and Maintenance, click Administrative Tools, and then double-click Event Viewer. You must be logged on as an administrator or a member of the Administrators group to free an event log.

*Then use any of the next options:
When a log is full, it stops recording new events. Clearing the log is one way to free the log and start recording new events. You can also free a log and start recording new events by overwriting old events. To overwrite events, on the Action menu, click Properties, and then click Overwrite events as needed. This ensures that all new events are written to the log, even when the log is full.
You can also start logging new events by increasing the maximum log size. To increase the log size, on the Action menu, click Properties, and then increase the Maximum log size.


text:
Q: Check if a field exists in a context.table in python-behave I'm having trouble trying to check whether a field exists or not in a table:
| category    | info                       |
| Electrician | 74300 Paris 04 50 65 43 21 |

Let's say my table usually contains a "name" field, but in this specific case it doesn't. How do I check the existence of the "name" field in this case?

A: You can simply check if your column is present in the headings attribute of the table. This attribute is also present when dealing with a single row instance, just so you know.
if 'name' in context.table.headings:

    do_something()

However, I personally prefer handling tables as dictionaries, using something like this
def make_dict_from_row(row):
    """
    creates a dictionary of arguments (**kwargs) from a behave
    table row.
    """

    cells = [cell if cell != '' else None for cell in row.cells]
    return dict(zip(row.headings, cells))

Using this you could simply do this
if 'name' in row:

    do_something()

See the table model for further reference.


text:
Q: Proof for formula that finds angle between two curves In the textbook it states this formula but doesn't go into how it was derived.  My geometric intuition is to somehow project the tangent lines out at the point of intersection thus creating a right triangle, but I can't seem to figure out how they get the formula.

The angle between two curves is the angle between their tangent lines at the point of intersection.  If the slopes are $m_1$ and $m_2$, then the angle of intersection $\alpha$ can be obtained from the formula
  $$\tan\alpha=\bigg|\dfrac{m_2-m_1}{1+m_1m_2}\bigg|$$

A: Hint: remember the trig identity $\,\tan(\alpha_2-\alpha_1) = \cfrac{\tan(\alpha_2)-\tan(\alpha_1)}{1+ \tan(\alpha_2)\tan(\alpha_1)}\,$ with $m_{1,2}=\tan(\alpha_{1,2})\,$.

A: Let the slope and inclination of the first tangent line be $m_1$ and $\theta$, while the second be $m_2$ and $\phi$. It is not difficult to see, for the angel $\alpha$ between them, we have
$$\alpha=\pm\theta\mp\phi$$
Thus,
$$\tan{\alpha}=\tan{\pm\theta\mp\phi}$$
By compound angel formula, it is easy followed, as $\tan\theta=m_1$ and $\tan\phi=m_2$,
$$\tan\alpha=\frac{\pm\tan\theta\mp \tan\phi}{1+\tan\theta\tan\phi}=\frac{\pm m_1\mp m_2}{1+m_1m_2}$$
If we are talking about the acute angle between them, that is, if $\alpha$ is acute, then
$$\tan\alpha=\left|\frac{m_1-m_2}{1+m_1m_2}\right|$$


text:
Q: MongoDB - Query a value in a dictionary I have a Conversations collection, containing Conversation documents like so (simplified to get to the point):
public class Conversation
{
    public ObjectId Id { get; set; }
    public Dictionary<ObjectId, DateTime> Members { get; set; }
}

The Dictionary Members is mapping the Member Ids to their entry date in the conversation.
Then, in the Conversations collection, if, for a particular User, I want to query all the Conversations he's in, what I'm doing is the following:
public List<Conversation> GetConversations(in User user)
{
    Query = Builder.Eq(doc => doc.Members.ContainsKey(user.Id), true);
    return Find(Query).ToList();
}

The question being, is this the right way to do it?

*

*If it is, why? How does MongoDB process this kind of query (which at
first glance looks to be complex and demanding lot of computing
power)?

*If it's not how'd you do it better?

A: Query = Builder.Eq(doc => doc.Members.ContainsKey(user.Id), true);

Looks like a collection scan.
Is it possible for you to track conversations in every Member document?
It can be achieved with array or subcollection.


text:
Q: How to escape XPath quotes "" with C# I'm trying to scrape Pinterest using XPath and HTMLAgilityPack, but XPath writes "" (//*(@id="XX") to represent the id attribute value, so in C# the strings are split and I get a syntax error. ("["@id="XX(error)"]") What should I do?

A: First, fix your XPath syntax error: Change //*(@id="XX" to //*[@id="XX"].
Then, to represent //*[@id="XX"] as a C# string, use either C# escaping or XPath alternative attribute value delimiters.
C# escaping
Escape the " in C# via \"
"//*[@id=\"XX\"]"

or via verbatim string literal syntax
@"//*[@id=""XX""]"

XPath alternative attribute value delimiters
Use ' as the attribute value delimiter, which both XML and XPath allow:
"//*[@id='XX']"

See also

*

*Escape double quotes in a string (C#)

*Escape double quote character in XML (XML and XPath)


text:
Q: Erro ao tentar criar em ambiente Windows um controller em RubyOnRails usando no Gemfile gem tiny_tds Configurei no SO Windows um ambiente RubyOnRails e preciso acessa um banco MSSQL com uma base já criada e populada, queria apenas consultar o banco e retornar dados através das Query. Vi que existe uma Gem chamada tiny_tds, configurei certinho no arquivo Gemfile, porém quando tento criar um controller ou rodar o server retorna um erro. Descrevo abaixo:
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:292:in `require': cannot load such file --
tiny_tds/tiny_tds (LoadError)
from C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:292:in `block in require'
        from C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:258:in `load_dependency'
        from C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:292:in `require'
        from C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/tiny_tds-2.0.0-x86-mingw32/lib/tiny_tds.rb:26:in `rescue in <top (required)>'
        from C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/tiny_tds-2.0.0-x86-mingw32/lib/tiny_tds.rb:29:in `<top (required)>'
        from C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/bundler-1.15.3/lib/bundler/runtime.rb:82:in `require'
        from C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/bundler-1.15.3/lib/bundler/runtime.rb:82:in `block (2 levels) in require'
        from C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/bundler-1.15.3/lib/bundler/runtime.rb:77:in `each'
        from C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/bundler-1.15.3/lib/bundler/runtime.rb:77:in `block in require'
        from C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/bundler-1.15.3/lib/bundler/runtime.rb:66:in `each'
        from C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/bundler-1.15.3/lib/bundler/runtime.rb:66:in `require'
        from C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/bundler-1.15.3/lib/bundler.rb:108:in `require'
        from C:/Users/daciolima/Documents/DESENVOLVIMENTO/Ruby/gerencial/config/application.rb:7:in `<top (required)>'
        from C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/railties-5.1.4/lib/rails/commands/server/server_command.rb:133:in `require'
        from C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/railties-5.1.4/lib/rails/commands/server/server_command.rb:133:in `block in perform'
        from C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/railties-5.1.4/lib/rails/commands/server/server_command.rb:130:in `tap'
        from C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/railties-5.1.4/lib/rails/commands/server/server_command.rb:130:in `perform'
        from C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/thor-0.20.0/lib/thor/command.rb:27:in `run'
        from C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/thor-0.20.0/lib/thor/invocation.rb:126:in `invoke_command'
        from C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/thor-0.20.0/lib/thor.rb:387:in `dispatch'
        from C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/railties-5.1.4/lib/rails/command/base.rb:63:in `perform'
        from C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/railties-5.1.4/lib/rails/command.rb:44:in `invoke'
        from C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/railties-5.1.4/lib/rails/commands.rb:16:in `<top (required)>'
        from bin/rails:4:in `require'
        from bin/rails:4:in `<main>'

Alguém tem alguma idéia do que seja?
Já configurei o mesmo projeto em ambiente Linux e funcionou perfeitamente.

A: Você precisa do tinytds disponível no S.O.
Como você instalou o ruby?
Se usar esta distribuição vem tudo pronto para usar:
http://www.railsinstaller.org/pt-BR


text:
Q: ReactJS v4 routing i was wondering how is it possible to change component in Onclick event so far ive came across these and none of them works
1)this.props.history.push('/')
which causes this error: Cannot read property 'push' of undefined
2)this.context.router.history.push('/')
which causes this error:Cannot read property 'history' of undefined
3)this.context.history.push('/')
which causes this error:Cannot read property 'push' of undefined
4)using BrowserRouter
which as it seems is not available in react v4 so this is not a solution
5)creating new instance of sth with the name of hash history and then using that object push method
which causes sth like myurl.com/#/navigatelink, and that # in url ruins everything
6) using window.location.href
which causes to refresh and reload the page which is undesired
7)creating new instance of BrowserHistory from history/createBrowserHistory
which works fine in url of my browser and expected url appears but the component wont change and this time i have to manually press f5 and refresh the page
so can you please tell me how im supposed to navigate to other page or component with onclick event without refreshing the page in react v4

A:
You can import createHistory from the history package separately and create your own history object instance that you pass to the Router component, which you can use anywhere you see fit in your app.
Example
import { Router, Route, Switch } from "react-router-dom";
import createHistory from "history/createBrowserHistory";

const history = createHistory();

class App extends React.Component {
  render() {
    return (
      <main>
        <Router history={history}>
          <button onClick={() => history.push('/')}> Click me </button>
          {/* ... */}
        </Router>
      </main>
    );
  }
}

A: have you used the withRouter HOC to make sure the react router props are actually being passed down to your component? It sounds like that isn't happening. Log out the props directly below the routes and make sure you pass the props down as necessary. You could also use the withRouter HOC on the component you want the props in and it'll inject them.


text:
Q: Convergence of moments implies convergence in total variation for Normal distribution? I would appreciate some proof verification on the following statement concerning convergence in total variation for Normal Distributions, given convergence of the first and second moments.
I suppose it is true, but a quick google search and search on this site did not bring it up, so this made me doubt.
Question:
We are dealing with the total variation norm, defined as $$||P-Q||_{TV} = \underset{B}{\sup} |P(B) - Q(B)|.$$
Suppose we have sequences of random variables $\mu_n$,$\sigma_n^2$, such that
$$\mu_n \overset{d}{\rightarrow} M$$
and
$$\sigma_n^2 \overset{\mathbb{P}}{\rightarrow} c ,$$
where $c$ is some constant and $M$ is a random variable. We want to show that $$||\mathcal{N}(\mu_n,\sigma_n^2) - \mathcal{N}(M,c)||_{TV} \overset{\mathbb{P}}{\rightarrow} 0$$
Proof:
We can use Pinsker's inequality, which states that
$$ ||P-Q||_{TV} \leq \sqrt{D_{KL}(P||Q)}.$$
The Kullback-Leibler Divergence for the two normal distributions in question is given by
$$ \frac{1}{2} ( \frac{\sigma_n^2}{c} - 1 + \frac{(\mu_n - M)^2}{c} + \ln (\frac{c}{\sigma_n^2}) ,$$
which converges in probability to $0$ by our assumptions (using Slutsky's Lemma, continuos mapping theorem and the fact that weak convergence to a constant implies convergence in probability to a constant). Thus the proof is complete
Additional question:
Could one also replace the convergence of the variances by convergence to some random variable? We could then not use Slutsky's theorem any more to get the convergence to $0$ of the last expression.


text:
Q: What should I do to make UTF-8 vs ASCII strings equals? code:
$utf8 = "32572_zał nr 13  wybór marszałka.pdf";
$target = "32572_za' nr 13  wybÆr marsza'ka.pdf";
var_dump($utf8 == $target)

I need to change string in $utf8 to bo equals $target.
What can I do in this case?
Something more advance than str_replace.


text:
Q: Does production mode in Hills 2.0.0.beta1 (Vaadin) require a pro license? This is happening also for Hilla version 2.0.0.beta1.
See: Does production mode in Vaadin 24 require pro license?
It always asks for a license and I'm using just core components. Any other work-around or is the same case as Vaadin 24.0.0?
When you compile for production mode is ask for a pro license

A: It's currently a know bug in 24.0.0.beta1 which is hopefully fixed in the next beta or you can downgrade to the latest alpha, where this problem isn't present.


text:
Q: ExtJS TabItem Click Event Good Morning All,
I have an ExtJS 5 tabpanel. When the tabpanel first appears there is a single tab inside with a star for the title. What I need is when the user clicks the star for it to create a new tabItem. I have tried the activate event but that only works with more than one tab present. I have also tried binding to the a click event and nothing happens for that. Here is the code I have now:
{
                xtype:'tabpanel',
                itemId:'tabCtr1',
                width:785,
                items:[
                    { iconCls: 'btn-NewTab', html : 'A simple tab' }
                ]
            }

function assetDetailsDialog_AfterRender(sender, eOpts)
{
   parent.down('tabpanel').items.getAt(0).on('click', function(){
            alert('Hello World');
        });
}

Thanks everyone
Follow On Issue:
I am having one more issue with setting the active tab. When the button is click it creates the new tab not issue, but when I call setActiveTab it appears to do nothing. When I stepped through it in Chrome I can see it is actually changing the tab to the specified one but then switching it back to the original. Any help would be great. Any idea's?

A: I have created a fiddle which demonstrates how to add tabs dynamically on click, the code is also listed below in case the link breaks. In the code below, the significant thing is adding the listener to the tabConfig
Ext.application({
    name: 'Fiddle',

    launch: function() {
        var tabPanel = Ext.create('Ext.tab.Panel', {
            width: 800,
            height: 400,
            renderTo: document.body,
            items: [{
                title: 'Click me to add another tab',
                tabConfig: {
                    listeners: {
                        click: function(tab) {
                            alert("Adding another tab");
                            var newTab = tabPanel.add({
                                // we use the tabs.items property to get the length of current items/tabs
                                title: 'Tab ' + (tabPanel.items.length + 1),
                                html: 'Another one'
                            });
                        }
                    }
                }
            }, {
                title: 'Bar',
                tabConfig: {
                    title: 'Custom Title',
                    tooltip: 'A button tooltip'
                }
            }]
        });
    }
});

Most of this code was taken from the documentation here


text:
Q: What is by.js locator for in Protractor/WebDriverJS? Recently, I've noticed a new locator being added to the Protractor documentation - the by.js():

Locates an elements by evaluating a JavaScript expression, which may be either a function or a string.

I understand what this locator provides, but I am missing the real-world use cases when this locator can be useful. When should I prefer to use by.js instead of other built-in locators like by.css?

A: I think the cases for this are pretty slim, but I can see this being of use when there's data on the client that is not available (or unreliably so) through selenium.
The example on the docs page includes a reference to offsetWidth:
spans[i].offsetWidth > 100

Used in context:
var wideElement = element(by.js(function() {
  var spans = document.querySelectorAll('span');
  for (var i = 0; i < spans.length; ++i) {
    if (spans[i].offsetWidth > 100) {
     return spans[i];
    }
  }
}));
expect(wideElement.getText()).toEqual('Three');

Alternatively, there may be a use case if there's a third party API on the window or some other service that can help locate an element.

A: I feel the use case is to get elements using core javascript functions, whenever css and other element locators won't help or are don't have properties that we could use. Scenarios -

*

*If you are getting an element using core javascript functions passing it to browser.executeScript then by.js can be used to replace it.

Example: -
Suppose if you had to get an element that appears on top between the two, you could get it this way -
var ele = element(by.js(function(){
    var ele1 = document.getElementById('#ele1');
    var ele2 = document.getElementById('#ele2');
    var val = ele1.compareDocumentPosition(ele2);
    if(val === 4) return ele1;
    else return ele2;
}));

*If you want to get element using its css values like color, font, etc... Though filter can be used in this case, but by.js also supports it.

*If the elements are not accessible by css or xpath or any other locators, for example pseudo-elements that have animations or transitions.

Example: -
Suppose if there's element which has :before and :after transitions -
.element:before {
    color: rgb(255, 0, 0);
}

To verify the color of the element, we could use by.js passing in a javascript statement to get the element -
var ele = element(by.js(function(){
    return window.getComputedStyle(document.querySelector('.element'), ':before');
}));
expect(ele.getCssValue('color')).toEqual('rgb(255, 0, 0)');

Hope it helps.


text:
Q: Need the no. of projects from inside the list(billCustLst) of values which is again inside a list(custLst) of values, java I am trying to return a number returned by a query, which is running inside a list loop,which again runs inside another list loop. May be I am missing something out which is giving me a wrong data. The code as below.
for (CfCust cust : custList) {
    int custCount = 0;
    int billCustCount = 0;
    List<CfBillCust> billCustList = projectMasterDAO.getCfBillCust(bu,cust);
    System.out.println("BillCust List size "+billCustList.size());
    for (CfBillCust cfBillCust : billCustList) {
        int i = (int) projectMasterDAO.getProjectByCfBillCust(bu, cfBillCust);
        billCustCount = i + billCustCount;
    }
    custCount = billCustCount;
    cust.setNoOfProjects(custCount);
    custLst.add(cust);
}
return custLst;

The data above is expected to be custCount=14, which is returned from the database calculated separately. The lists are declared globally and few in the snapshot.


text:
Q: Print output to different columns or make table from output I'am currently working on a script and I have a problem formatting the output.
The index and input Files look like:
index
Pseudopropionibacterium propionicum
Kibdelosporangium phytohabitans
Steroidobacter denitrificans

File 1
Pseudopropionibacterium propionicum 1591.0
Kibdelosporangium phytohabitans 907.0
Olsenella sp. oral taxon 807    7323.0  oral bacterium
Steroidobacter denitrificans    6673.0  sludge bacterium

File 2
Pseudopropionibacterium propionicum 123.0
Caulobacteraceae bacterium OTSz_A_272   1019.0
Saccharopolyspora erythraea 939.0   soil bacterium
Rhodopseudomonas palustris  900.0
Nitrospira moscoviensis 856.0   soil/water bacterium

File 3
Pseudopropionibacterium propionicum 1591.0
Kibdelosporangium phytohabitans 907.0
Verrucosispora maris    391.0   deep-sea actinomycete
Tannerella forsythia    389.0   periodontal pathogen
Actinoplanes missouriensis  376.0   soil bacterium

what the script does is looking with the help of the index for a match in File 2 and prints out field one and two of File 2. However this is done for more than one File 2 (the all look the same) and I wanted to create a new column for the output of each new File 2.
My Code until now:
#!/bin/bash

for file in ./*_TOP1000
do
basename $file >> output
awk 'BEGIN{FS="\t"}NR==FNR{a[$1]=$0;next}$1 in a{print $1,$2}' index $file >> output
done

And the output looks like:
File 1
Pseudopropionibacterium propionicum 1591.0
Kibdelosporangium phytohabitans 907.0
Steroidobacter denitrificans    6673.0
File 2
Pseudopropionibacterium propionicum 4326.0
File 3
Kibdelosporangium phytohabitans 1591.0
Pseudopropionibacterium propionicum 907.0

But it would like to have in in that way:
File 1                                       File 2                                        File 3
Pseudopropionibacterium propionicum 1591.0   Pseudopropionibacterium propionicum 4326.0    Pseudopropionibacterium propionicum 907.0
Kibdelosporangium phytohabitans 907.0                                                      Kibdelosporangium phytohabitans 1591.0
Steroidobacter denitrificans    6673.0

with the matching results directly under them. All the files could have different matches.
I tried solving it with the column command sneaking in separator but it was not working. So how can I archive the desired output?

A: $ cat tst.awk
BEGIN { OFS="\t" }
NR==FNR { indices[$1]; next }
FNR==1 { filenames[++numCols] = FILENAME }
$1 in indices {
    vals[numCols,++rowCnt[numCols]] = $1 FS $2 FS $3
    numRows = (rowCnt[numCols] > numRows ? rowCnt[numCols] : numRows)
}
END {
    for (colNr=1; colNr<=numCols; colNr++) {
        printf "%s%s", filenames[colNr], (colNr<numCols ? OFS : ORS)
    }
    for (rowNr=1; rowNr<=numRows; rowNr++) {
        for (colNr=1; colNr<=numCols; colNr++) {
            printf "%s%s", vals[colNr,rowNr], (colNr<numCols ? OFS : ORS)
        }
    }
}

$ awk -f tst.awk index file1 file2 file3 | column -s$'\t' -t
file1                                       file2                                      file3
Pseudopropionibacterium propionicum 1591.0  Pseudopropionibacterium propionicum 123.0  Pseudopropionibacterium propionicum 1591.0
Kibdelosporangium phytohabitans 907.0                                                  Kibdelosporangium phytohabitans 907.0
Steroidobacter denitrificans 6673.0

The pipe to column is just to show the output in aligned columns rather than tab-separated.

A: Something like this, in GNU awk since the third argument of match:
$ awk '
NR==FNR { a[$0]; next }               # read and hash index file to a
FNR==1 { print FILENAME }             # print filename at start of data files
{
    match($0,/^([^0-9]+)([0-9.]+)/,b) # get the name part and first value
    gsub(/^ +| +$/,"",b[1])           # trim name
    if(b[1] in a)                     # print indexed
        print b[1],b[2]
}' index file1 file1
file1
Pseudopropionibacterium propionicum 4326.0
Kibdelosporangium phytohabitans 3819.0
file1
Pseudopropionibacterium propionicum 4326.0
Kibdelosporangium phytohabitans 3819.0

The field version would be for GNU awk due to 2D arrays:
$ cat program.awk
NR==FNR { a[$0]; next }                 # read and hash index file to a
FNR==1 { c[++i][j=1]=FILENAME }         # print filename at start of data files
{
    match($0,/^([^0-9]+)([0-9.]+)/,b)   # get the name part and first value
    gsub(/^ +| +$/,"",b[1])             # trim name
    if(b[1] in a) {                     # print indexed
        c[i][++j]=b[1] OFS b[2]
        if(m<j||m=="") m=j              # max col count
        if(l[i]<=length(b[1] OFS b[2])||l[i]=="")
            l[i]=length(b[1] OFS b[2])  # this is for printf width
    }
}
END {
    for(k=1;k<=m;k++)
        for(j=1;j<=i;j++)
            printf "%-" l[k] "s %s", c[j][k], (j==i?ORS:OFS)
}

Test it:
$ awk -f index file1 file2 file3
file1                                       file2                                       file3
Pseudopropionibacterium propionicum 1591.0  Pseudopropionibacterium propionicum 123.0  Pseudopropionibacterium propionicum 1591.0
Kibdelosporangium phytohabitans 907.0                                                   Kibdelosporangium phytohabitans 907.0
Steroidobacter denitrificans 6673.0

A: It might be easier to rearrange the table with Perl than with Awk.
If you feed column with the data in the right order, it will format the columns correctly.  Use the option -t and specify the column delimiter with -s.
#! /usr/bin/perl
use strict;
use warnings;

my $table;      # declares variables.
my $col = -1;
my $row = 0;

while (<DATA>)   # loop through the input line by line
{
  chomp;                              # remove end of line
  if (/^File/) { $col++; $row = 0; }  # increment col and init row if line starts with File
  $table->[$row++]->[$col] = $_;      # set value in two dimensional array and increment row
}

open (my $out, '|-', "column -s ^ -t");   # open pipe to columns
foreach (@$table)                         # loop over the rows of the table
{
  print $out join('^', map { $_ or ' ' } @$_), "\n";  # join the elements of a row with the delimiter ^ and replace undefined values with a space
}
close $out;

__DATA__
File 1
Pseudopropionibacterium propionicum 1591.0
Kibdelosporangium phytohabitans 907.0
File 2
Pseudopropionibacterium propionicum 4326.0
File 3
Kibdelosporangium phytohabitans 2019.0
Pseudopropionibacterium propionicum 1542.0

Prints the columns in this way:

File 1                                      File 2                                      File 3
Pseudopropionibacterium propionicum 1591.0  Pseudopropionibacterium propionicum 4326.0  Kibdelosporangium phytohabitans 2019.0
Kibdelosporangium phytohabitans 907.0                                                   Pseudopropionibacterium propionicum 1542.0

If you want to read standard input instead of Perl's data segment, change <DATA> to <*>.


text:
Q: How to set Vertical Coordinate system when creating a 3D shapefile? I'm working with GDAL v1.11 and am seeing the vertical CS stripped when exporting a 3D shapefile (from oracle spatial). This is the command I'm running:
ogr2ogr -f "ESRI Shapefile" B_POINT.shp (oci_url) -sql(sql_select_statement) -nlt POINT25D -a_srs "EPSG:4326+3855" -nln B_POINT
I've tried specifying the a_srs with several different options
EPSG Code: "EPSG:4326+3855"
PROJ.4 Definition: "+proj=longlat +datum=WGS84 +geoidgrids=egm08_25.gtx +vunits=m +no_defs"
Filename: /apps/gdal-1.11.0/compound_wkt.wkt
Where file>cat /apps/gdal-1.11.0/compound_wkt.wkt
COMPD_CS["WGS 84 + EGM2008 geoid height",
GEOGCS["WGS 84",
    DATUM["WGS_1984",
        SPHEROID["WGS 84",6378137,298.257223563,
            AUTHORITY["EPSG","7030"]],
        AUTHORITY["EPSG","6326"]],
    PRIMEM["Greenwich",0,
        AUTHORITY["EPSG","8901"]],
    UNIT["degree",0.0174532925199433,
        AUTHORITY["EPSG","9122"]],
    AUTHORITY["EPSG","4326"]],
VERT_CS["EGM2008 geoid height",
    VERT_DATUM["EGM2008 geoid",2005,
        AUTHORITY["EPSG","1027"],
        EXTENSION["PROJ4_GRIDS","egm08_25.gtx"]],
    UNIT["metre",1,
        AUTHORITY["EPSG","9001"]],
    AXIS["Up",UP],
    AUTHORITY["EPSG","3855"]]]

I haven't had any luck in exporting the vertical CS with any of these ogr2ogr a_srs options. I've even installed PROJ.4 and tried setting the s_srs and t_srs with no luck.
The egm08_25.gtx file is downloaded and copied to /apps/proj-4.8.0/nad/ directory, per this post: http://osgeo-org.1560.x6.nabble.com/GTX-format-td3840948.html
Is there any way to export the vertical CS for a 3D shapefile, or is this still a bug? I have the same issue trying to export a FileGDB.
EDIT: I can view the WKT of the compound CS here:
gdal-1.11.0>testepsg epsg:4326+3855
Validate Succeeds.
WKT[epsg:4326+3855] =
COMPD_CS["WGS 84 + EGM2008 geoid height",
    GEOGCS["WGS 84",
        DATUM["WGS_1984",
            SPHEROID["WGS 84",6378137,298.257223563,
                AUTHORITY["EPSG","7030"]],
            AUTHORITY["EPSG","6326"]],
        PRIMEM["Greenwich",0,
            AUTHORITY["EPSG","8901"]],
        UNIT["degree",0.0174532925199433,
            AUTHORITY["EPSG","9122"]],
        AUTHORITY["EPSG","4326"]],
    VERT_CS["EGM2008 geoid height",
        VERT_DATUM["EGM2008 geoid",2005,
            AUTHORITY["EPSG","1027"],
            EXTENSION["PROJ4_GRIDS","egm08_25.gtx"]],
        UNIT["metre",1,
            AUTHORITY["EPSG","9001"]],
        AXIS["Up",UP],
        AUTHORITY["EPSG","3855"]]]

Simplified WKT[epsg:4326+3855] =
COMPD_CS["WGS 84 + EGM2008 geoid height",
    GEOGCS["WGS 84",
        DATUM["WGS_1984",
            SPHEROID["WGS 84",6378137,298.257223563]],
        PRIMEM["Greenwich",0],
        UNIT["degree",0.0174532925199433]],
    VERT_CS["EGM2008 geoid height",
        VERT_DATUM["EGM2008 geoid",2005],
        UNIT["metre",1]]]

Old Style WKT[epsg:4326+3855] = GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]]
ESRI'ified WKT[epsg:4326+3855] =
GEOGCS["GCS_WGS_1984",
    DATUM["D_WGS_1984",
        SPHEROID["WGS_1984",6378137,298.257223563]],
    PRIMEM["Greenwich",0],
    UNIT["Degree",0.017453292519943295]]
PROJ.4 rendering of [epsg:4326+3855] = +proj=longlat +datum=WGS84 +geoidgrids=egm08_25.gtx +vunits=m +no_defs

The "ESRI'ified WKT" is what I see in my exported shapefile and filegeodb:
shapefile>ogrinfo -al B_POINT.shp | more
INFO: Open of `B_POINT.shp'
      using driver `ESRI Shapefile' successful.

Layer name: B_POINT
Geometry: 3D Point
Feature Count: 1
Extent: (39.212616, -6.130917) - (39.212616, -6.130917)
Layer SRS WKT:
GEOGCS["GCS_WGS_1984",
    DATUM["WGS_1984",
        SPHEROID["WGS_84",6378137,298.257223563]],
    PRIMEM["Greenwich",0],
    UNIT["Degree",0.017453292519943295]]

I know that shapefiles support vertical coordinate systems (e.g., page 26 here: http://www.geo.hunter.cuny.edu/gis/docs/Whats_New_In_ArcGIS_92.pdf). There must be a configuration in GDAL to get the shapefile ESRI WKT to pickup the compound CS.


text:
Q: How to use "this" with webpack built js I spent my day searching for a solution but I didn't mange to solve this, first am new to webpack and not much advanced with js I managed after a long day to export my 2 simple functions :
script.js
function scrollright(el) {
...
}

function scrollleft(el) {
...
}

export {
scrollright,
scrollleft,
}

and import them in index.js
import { scrollleft, scrollright } from './script';
scrollleft();
scrollright();

building finishes successfully but the problem is that those function take parameters and those parameters are passed to js (previously before webpack) through html onclick tag like this :
onclick="scrollleft(this)"

I didn't figure out how I can transfer this completely to webpack maybe it's a newbie question but I can't find anything that helps me or at least if this is not possible a simple clarification or a proposed solution would be appreciated.

A: Okay so I managed to solve it like this :
index.js
import { scrollleft, scrollright } from './script';
window.scrollleft = scrollleft;
window.scrollright = scrollright;

so it seems that adding window will make the function global or smthg like that I don't understand 100% what this mean but if anyone faced this problem hope this newbie Q/A will help you and save you a day or more ;)
reference (for maybe clearer explanation) :
https://stackoverflow.com/a/35825562/9153588


text:
Q: Google Translate API in Javascript I have this fiddle here : https://jsfiddle.net/gsrgfd8e/
$(".word_split").lettering('words');

I want every word to display a google translation on mouseover.
The documentation doesn't specify a way to do that in Javascript. Apparently I could do that with node.js but I'm not sure how.
How am I supposed to do this?

A: For the JavaScript part of the solution, you can check the reply to the "Html text hover over each word for translation" question.
On how to call the Translate API, you have an example in "Translate Content in JavaScript an HTML with the Google Translate API".


text:
Q: Send toast from F# I would like to send a ToastNotification in the Windows 8.1 style from a F# console application.
Here is my code:
let gotMessage message =
    let xdoc = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText03)
    let children = xdoc.ChildNodes
    children.[0 |> uint32].AppendChild(xdoc.CreateTextNode "Message coming") |> ignore
    children.[2 |> uint32].AppendChild(xdoc.CreateTextNode message) |> ignore
    let toast = new ToastNotification(xdoc)
    toast.add_Activated (fun notification _ -> 0 |> ignore) |> ignore

But I get the following exception:
First the German:
System.IO.FileNotFoundException wurde nicht behandelt.
Message: Ein Ausnahmefehler des Typs "System.IO.FileNotFoundException" ist in Ineedtea.Server.exe aufgetreten.
Zusätzliche Informationen: Die Datei oder Assembly "Windows, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null" oder eine Abhängigkeit davon wurde nicht gefunden. Das System kann die angegebene Datei nicht finden.

Now the English
System.IO.FileNotFoundException was not handled.
Message: An exception of type "System.IO.FileNotFoundException" appeared in Ineedtea.Server.exe.
Additional information: The file or assembly "Windows, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null" or a dependency wasn't found. The system cannot find the file.

Does anyone have an idea?

A: I found a work around, I created a C# library and there I wrote the Toaster class.
Check this Github repository for the code :) https://github.com/DerKnerd/ineedtea/tree/master/WinRTMapper


text:
Q: how can do this in laravel with eloquent and db how can do this in laravel with eloquent and db
SELECT thread.threadid, MATCH(thread.title) AGAINST ('title_seatch_word') AS score
FROM  thread AS thread
WHERE MATCH(thread.title) AGAINST ('title_seatch_word')
    AND thread.open <> 10
    " . iif($threadid, " AND thread.threadid <> $threadid") . "
LIMIT 5

i tray this
Thread::whereRaw('MATCH (`title`) AGAINST (?)', ['title_search_word'])
  ->where('open', '<>', 10)
  ->when(isset($threadid), function ($query) {return $query->where('threadid', '<>', $threadid);})
  ->take(5)
  ->get();

put i cant write this
SELECT thread.threadid, MATCH(thread.title) AGAINST ('title_seatch_word') AS score

so i want complete query

A: Use this:
Thread::select('threadid')
    ->selectRaw('MATCH (`title`) AGAINST (?) AS score', ['title_search_word'])
    ->where('open', '<>', 10)
    ->when(isset($threadid), function ($query) {
        return $query->where('threadid', '<>', $threadid);
    })
    ->havingRaw('`score`') // OR: ->having('score', '>', 0)
    ->take(5)
    ->get();

This way, score has to be calculated only once.


text:
Q: State error propagation of ODE with uncertain parameters I have an idea on how to integrate uncertainty of the parameters of an ODE in the state error propagation. But I am unsure if my idea is correct. I have a non-linear ODE of the form:
$$ \frac{d}{dt} \mathbf{x} = \mathbf{F}(\mathbf{x}, t, \boldsymbol{\beta}) = \sum_{i=1}^N \phi_i(\mathbf{x}, t) \cdot \beta_i$$
whereby $\phi_i(\mathbf{x}, t)$ are non-linear basis functions of $\mathbf{x}$.
When I use this ODE to propagate a state $\mathbf{x}_k = \mathbf{x}(t_k)$ with associated covariance matrix $\Sigma_{x_kx_k}$ I would like to also do error propagation in order to get the updated state $\mathbf{x}_{k+1}$ with associated $\Sigma_{x_{k+1}x_{k+1}}$.
The error propagation can be done using a linearization:
$$ \mathbf{T} = \frac{\partial \mathbf{F}(\mathbf{x}, t, \boldsymbol{\beta})}{\partial \mathbf{x}}|_{\mathbf{x}_k, t_k} $$
$$\boldsymbol{\Theta} = e^{\mathbf{T}\Delta t} $$
$$ \Sigma_{x_{k+1}x_{k+1}} = \boldsymbol{\Theta} \Sigma_{x_kx_k} \boldsymbol{\Theta}^T$$
Now to my problem: The coefficients of the ODE, $\boldsymbol{\beta}$, have their own covariance matrix $\Sigma_{\boldsymbol{\beta}\boldsymbol{\beta}}$ which I would also like to incorporate into the error propagation.
My idea for this is the following: Extend the linearized ODE to have $\boldsymbol{\beta}$ as part of the state vector:
$$ \frac{d}{dt}\begin{bmatrix} \mathbf{x} \\ \boldsymbol{\beta} \end{bmatrix} = \begin{bmatrix} \frac{\partial \mathbf{F}}{\partial \mathbf{x}} && \frac{\partial \mathbf{F}}{\partial \boldsymbol{\beta}} \\ 0 && 0\end{bmatrix} \begin{bmatrix} \mathbf{x} \\ \boldsymbol{\beta}\end{bmatrix} = \mathbf{T}^* \mathbf{x}^*$$
This extended system leaves the coefficient $\boldsymbol{\beta}$ unchanged and I can use it for the error propagation as before:
$$ \boldsymbol{\Theta}^* = e^{\mathbf{T}^*\Delta t} $$
Using the power series expansion:
$$ \boldsymbol{\Theta}^* = \mathbf{I} + \begin{bmatrix} \frac{\partial \mathbf{F}}{\partial \mathbf{x}} && \frac{\partial \mathbf{F}}{\partial \boldsymbol{\beta}} \\ 0 && 0\end{bmatrix} t +\begin{bmatrix} \frac{\partial \mathbf{F}}{\partial \mathbf{x}} && \frac{\partial \mathbf{F}}{\partial \boldsymbol{\beta}} \\ 0 && 0\end{bmatrix}^2 \frac{t^2}{2!} + \dots + \begin{bmatrix} \frac{\partial \mathbf{F}}{\partial \mathbf{x}} && \frac{\partial \mathbf{F}}{\partial \boldsymbol{\beta}} \\ 0 && 0\end{bmatrix}^n \frac{t^n}{n!} + \dots $$
$$ = \mathbf{I} + \begin{bmatrix} \boldsymbol{\Theta}^*_1 && \boldsymbol{\Theta}^*_2 \\ 0 && 0\end{bmatrix} $$
$$ \boldsymbol{\Sigma}^* = \boldsymbol{\Theta}^* \begin{bmatrix} \Sigma_{x_{k}x_{k}} && 0 \\ 0 && \Sigma_{\beta\beta} \end{bmatrix} \boldsymbol{\Theta}^{*^T} $$
$$ = \begin{bmatrix} \Sigma_{x_{k+1}x_{k+1}} && \Sigma_{x_{k+1}\beta_{k+1}} \\ \Sigma_{\beta_{k+1}x_{k+1}} && \Sigma_{\beta_{k+1}\beta_{k+1}}\end{bmatrix} = \begin{bmatrix} \Sigma_{x_{k}x_{k}} + 2\boldsymbol{\Theta}^*_1\Sigma_{x_{k}x_{k}} + \boldsymbol{\Theta}^*_1 \Sigma_{x_{k}x_{k}} \boldsymbol{\Theta}^*_1 + \boldsymbol{\Theta}^*_2 \Sigma_{\beta \beta} \boldsymbol{\Theta}^*_2 && \boldsymbol{\Theta}^*_2\Sigma_{\beta \beta} \\ \boldsymbol{\Theta}^*_2\Sigma_{\beta \beta} && \Sigma_{\beta\beta}\end{bmatrix} $$
Is this idea correct?


text:
Q: Django clean() change field requirement I want to change the requirement of some modelForm fields as shown below.
certs is a checkbox. If this checkbox is "True" the ca,cert and key fields shall be required. If not, they shall be left blank (null=True is set in models).
class CreateMVPConnectionsForm(forms.ModelForm):
    class Meta:
        model = MVPConnections
        fields = '__all__'
        exclude = ['created_by_user', 'parent_project_id']

    def clean(self):
        print("clean started")
        cleaned_data = super().clean()

        certs = cleaned_data.get('certs')
        ca = cleaned_data.get('ca')
        cert = cleaned_data.get('cert')
        key = cleaned_data.get('key')

        if certs == True:
            if ca and cert and key:
                pass
            else:
                raise ValidationError(_('If certs is checked, please fill in "ca", "cert" and "key".'))
        else:
            ca = forms.CharField(required=False)
            cert = forms.CharField(required=False)
            key = forms.CharField(required=False)

Any suggestions on how to solve this?

A: Although the primary way you'll use Field classes is in Form classes, you can also instantiate them and use them directly to get a better idea of how they work. Each Field instance has a clean() method, which takes a single argument and either raises a django.forms.ValidationError exception or returns the clean value:
>>> from django import forms
>>> f = forms.EmailField()
>>> f.clean('foo@example.com')
'foo@example.com'
>>> f.clean('invalid email address')
Traceback (most recent call last): ... ValidationError: ['Enter a valid email address.']