text:
Q: SOAP PHP Value cannot be null. Parameter name: source I'm trying to call a function from this webservice:
http://www.zulutrade.com/WebServices/Performance.asmx?WSDL
I'm sending all the requested params but I'm getting this error: Value cannot be null. Parameter name: source
I think it's a server issue, but maybe I need to change something in my code:
$client = new SoapClient('http://www.zulutrade.com/WebServices/Performance.asmx?WSDL',
                         array('location' => "http://www.zulutrade.com/WebServices/Performance.asmx",
                               'trace'=>1,
                               "cache_wsdl" => 0));

$params = array
(
    'providerId' => 109206,
    'fromDateStr' => "1985-12-19",
    'toDateStr' => "2013-05-06",
    'validTrades' => true,
    'lotSize' => "Mini",
    'start' => 0,
    'length' => 20,
    'sortBy' => "buy",
    'sortAscending' => true
);

try
{
    $result =  $client->GetProviderTrades($params);
}
catch (SoapFault $fault)
{
    print_r($fault);
}

Any ideas?
thanks

A: I tried with nusoap class and I get this error

HTTP Error: Couldn't open socket connection to server http://www.zulutrade.com:81/WebServices/Performance.asmx, Error (10060): A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond

So maybe it's a bug on their part

A: You set all vars except one. ArrayOfInt currencyIds; is not set.
struct GetProviderTrades {
 int providerId;
 ArrayOfInt currencyIds;
 string fromDateStr;
 string toDateStr;
 boolean validTrades;
 LotSize lotSize;
 int start;
 int length;
 string sortBy;
 boolean sortAscending;
}


text:
Q: How to convert FEN ID onto a Chess Board? So I was wondering on how I can convert a FEN ID onto a chess board.
Code:
import io

def board_to_fen(board):
    # Use StringIO to build string more efficiently than concatenating
    with io.StringIO() as s:
        for row in board:
            empty = 0
            for cell in row:
                c = cell[0]
                if c in ('w', 'b'):
                    if empty > 0:
                        s.write(str(empty))
                        empty = 0
                    s.write(cell[1].upper() if c == 'w' else cell[1].lower())
                else:
                    empty += 1
            if empty > 0:
                s.write(str(empty))
            s.write('/')
        # Move one position back to overwrite last '/'
        s.seek(s.tell() - 1)
        # If you do not have the additional information choose what to put
        s.write(' w KQkq - 0 1')
        return s.getvalue()

board = [
        ['--', '--', '--', '--', '--', '--', '--', '--'],
        ['--', '--', '--', '--', '--', '--', '--', '--'],
        ['--', '--', '--', '--', '--', '--', '--', '--'],
        ['--', '--', '--', '--', '--', '--', '--', '--'],
        ['--', '--', '--', '--', '--', '--', '--', '--'],
        ['--', '--', '--', '--', '--', '--', '--', '--'],
        ['--', '--', '--', '--', '--', '--', '--', '--'],
        ['--', '--', '--', '--', '--', '--', '--', '--'],
    ]
print(board_to_fen(board))

board_to_fen(board)

So we have the board above where '--' represents a square on the board, a blank square. So you can use notation like this: 'w' is for white and 'b' is for black. For the pieces:
R: Rook
N: Knight
B: Bishop
Q: Queen
K: King
p: pawn
As you imagine you place something like: 'wK' in a '--' spot for white King and the rest of the pieces.
As you can tell I've already made the FEN ID for the chess board, but I want to know how I can use a FEN string outside to generate a board on the blank one above.
I appreciate any help I receive. If you need anymore information let me know.

A: It's basically the opposite of what you did.
fen = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1'

def fen_to_board(fen):
    board = []
    for row in fen.split('/'):
        brow = []
        for c in row:
            if c == ' ':
                break
            elif c in '12345678':
                brow.extend( ['--'] * int(c) )
            elif c == 'p':
                brow.append( 'bp' )
            elif c == 'P':
                brow.append( 'wp' )
            elif c > 'Z':
                brow.append( 'b'+c.upper() )
            else:
                brow.append( 'w'+c )

        board.append( brow )
    return board

from pprint import pprint
pprint( fen_to_board(fen) )

[timr@Tims-Pro:~/src]$ python fen.py
[['bR', 'bN', 'bB', 'bQ', 'bK', 'bB', 'bN', 'bR'],
 ['bp', 'bp', 'bp', 'bp', 'bp', 'bp', 'bp', 'bp'],
 ['--', '--', '--', '--', '--', '--', '--', '--'],
 ['--', '--', '--', '--', '--', '--', '--', '--'],
 ['--', '--', '--', '--', '--', '--', '--', '--'],
 ['--', '--', '--', '--', '--', '--', '--', '--'],
 ['wp', 'wp', 'wp', 'wp', 'wp', 'wp', 'wp', 'wp'],
 ['wR', 'wN', 'wB', 'wQ', 'wK', 'wB', 'wN', 'wR']]
[timr@Tims-Pro:~/src]$

redpajama_set_name: RedPajamaStackExchange


text:
Q: ROBOFLOW-tensorflow-object-detection-faster-rcnn_ cannot import name 'get_config' from 'tensorflow.python.eager.context' I was trying to implement Fast RCNN model on my custom dataset using the google colab ROBOFLOW-tensorflow-object-detection-faster-rcnn.ipynb, but when I run the 'Install required packages' section ,Iam getting the error 'cannot import name 'get_config' from 'tensorflow.python.eager.context' . I tried to upgrade tensorflow and Keras , but not working
Tried Upgrade of tensorflow
Also trying to locally download the repository to try to import from tensorflow. Please help

A: Try to upgrade the tensorflow:
pip install --upgrade tensorflow
pip install --upgrade tensorflow-gpu

For me TF2.9 worked for the same ROBOFLOW colab notebook:
!yes|pip uninstall tensorflow
!pip install tensorflow==2.9


text:
Q: ARIMA (0,1,1) or (0,1,0) - or something else? I've just started learning time series so please excuse me if it's painfully obvious; I haven't managed to find the answer elsewhere.
I have a data series showing a pretty obvious trend although it's quite noisy. I can take pretty much any division of the data and run classical tests to show a highly significant difference in means.
I decided to have a look at time series analysis to see if it could help describe the trend. An ARIMA(0,1,1) model comes out with AIC,BIC=34.3,37.3 (Stata), whilst an ARIMA(0,1,0) model comes out with AIC,BIC=55.1,58.1 - so I understand I'm supposed to prefer the (0,1,1) model.
However, the coefficient for the MA(1) is displaying as -0.9999997 (and not showing any p-values). If I try the same in SPSS I get an MA(1) coefficient of 1.000 (I assume SPSS uses opposite signs) with a p-value of 0.990 - does this mean it suggests I drop the term?
My understanding is that the effect of a MA(1) coefficient of -1 is basically to remove the old error term and convert the whole series to a linear trend. Does this mean ARIMA is totally unsuitable for my needs? On the plus side it gives me a sensible value for the trend. If I use the (0,1,0) model then I still get a reasonable value for the trend but it's not significant any more.
Thanks for your help!
EDIT:
Thanks for looking in. The trend looks like a fairly linear decrease; the data points seen to fairly noisily rattle around above and below a trend line. The ARIMA (0,1,1) model produces something that's not far off a straight line decrease which seems sensible - the (0,1,1) produces what is essentially a lagged version of the data, translated down by one month of trend.
The data aren't stationary (due to the trend) - though the first differences seem to be. I don't think the (0,1,1) is a bad model - I'm just a little confused by the p-value seeming to suggest I should drop the MA term - or wondering if it means I should bin ARIMA entirely!
EDIT2
@vinux - thanks for the suggestion; that makes a lot of sense (and seems to be what the -1 MA term is trying to create?).
I've uploaded as many graphs as I could think of as people had requested.

I've also put the monthly data up in CSV format at pastebin

A: It is difficult to give the right answer without looking at the data. Here are some points that may help you in your modelling.
The coefficient of MA(1) very close to 1 indicates the sign of overdifferencing.  This means unit root in Moving averages.
My suggestion would be: Check the original series is stationary (visually) or check the presence of unit root. If you observe deterministic trend (eg: linear), add the trend part with time series model. If the original series is stationary build the time series without differencing.

A: As you say, the data is not stationary, we can find the stationary transformed data by differencing, and checked by the unit root test (e.g Augmented Dickey-Fuller test, Elliott-Rothenberg-Stock test, KPSS test, Phillips-Perron test, Schmidt-Phillips test, Zivot-Andrews test...) We can talk about ARMA model only after confirming the stationarity.
It is a classical way to identify the ARMA(p, q) by the ACF plot and PACF plot. ARMA(0,1) and ARMA(0,0) can be told here. Another method to identify p, q is about the EACF, but it is not widely used for univariate time series.
Empirical studies show that AIC usually tends to overfitting. The advantage of using AIC is for automatic algorithm to find the best model, but it is not usually recommended in traditional time series textbook.


text:
Q: Option and command keys in Mac OS X are swapped and keyboard preferences do not set them back On my MacBook Pro, I occasionally use external keyboards, generally Windows ones and things have been fine.
Yesterday, I plugged in a new one, remapped the command/option keys so the windows/alt keys were in the same configuration, again, nothing new here. However, this time when I unplugged the USB keyboard, the laptops option/command keys remained switched.
More annoying is that if I go into the System Preferences -> Keyboards -> Modifier keys, remapping the keys to actions does not work. I can use the drop downs to disable any specific keys, but switching the behaviours does nothing. (Cmd/Option obvious, tried remapping anything to caps lock and a few other combinations, no joy. Restore defaults set the configuration to what I'd expect, but the settings are evidently ignored.)
So: Any ideas?

A: I had the same behavior.
Clicking the Restore Defaults button in the Modifier Keys... pane of the Keyboard & Mouse panel of the System Preferences (take deep breath) of 10.5.8 didn't work to unswap the Command and Options keys. However, I clicked "Restore Defaults" after plugging in a non-Apple (external) keyboard, and the MacBook Pro keyboard started working correctly (a big relief).


text:
Q: Chrome/Edge not starting up from command prompt When reading this you may want to say just not to start chrome from the command prompt, and do it from the start menu.  But there is a reason I need to solve this as I will explain at the end of the post
Both for "msedge" and "chrome" when i try to start from the Windows 10 command prompt, the browser comes up with a blank screen and then dies.  it does not do this from powershell nor git bash.  From those it works fine.  IT Help has been working on this for weeks with me and we can't figure it out.  This occurs only when there is not an instance of the browser up.  When there is, then it starts fine from the command prompt.
When the IT guy opened a window and ran it as him, Chrome started up fine.  Also when he let me run as admin on myh own account it started up fine.
Someone suggested doing an --enable-logging which I did, and there are some messages.  I will attach the picture.  When I do the same thing with a browser window open, there are no error messages.
One suggestion I saw was to disable gpu, so I went to settings advanced and turned off "use hardware accelerator".  I also tried starting up with --disable-gpu but I get the same problem.
Any ideas what could be wrong?
The reason I need this is because it is my assumption that other things try to start Chrome this way.  I am using Visual Studio (C#) with Connect to open a chrome or edge browser and I get the same error (works if window already open).  I don't know how to get it to start any other way.
I should say IE works (well, worked as it is discontinued) fine. And Chrome and Edge start fine on some other machines.
Please see attached log file.


text:
Q: When can compiling c++ without RTTI cause problems? I'm using gcc's -fno-rtti flag to compile my C++ without runtime type information.
Assuming I'm not using dynamic_cast<> or typeid(), is there anything that could lead me to later problems?

A: We have used gcc without rtti for 5 years with no specific problems (not using dynamic_cast or typeid)

A: Since your question is specific to GCC you should consult carefully the documentation for the version you are using. The documentation for GCC 4.5.2 says the following. Which from my reading would indicate that if you avoid dynamic_cast and typeid, you should be ok. That said, I have no personal experience with -fno-rtti. Perhaps you might like to elaborate on why you are using -fno-rtti.

-fno-rtti
  Disable generation of information about every class with
  virtual functions for use by the C++
  runtime type identification features
  (dynamic_cast and typeid). If you
  don't use those parts of the language,
  you can save some space by using this
  flag. Note that exception handling
  uses the same information, but it will
  generate it as needed. The
  dynamic_cast operator can still be
  used for casts that do not require
  runtime type information, i.e. casts
  to void * or to unambiguous base
  classes.

There is discussion about the relationship between virtual functions and RTTI available at No RTTI but still virtual methods. The short version is that virtual functions should be fine without RTTI.

A: I appreciate this posting another answer to a very old question, but I came across it today and would like to point out that the answers given up until now are not accurate in all regards.
There is a potential issue that might occur if your code is using a library which itself uses RTTI information.
The following code is a simple example of this:
#include <stdio.h>

// Library header
struct A     { virtual void fn(); };
struct B : A { virtual void fn(); };
void lib_fn(A* ptr);

// Library code
#ifdef LIB
void A::fn() { puts("a"); }

void B::fn() { puts("b"); }

void lib_fn(A* ptr)
  {
  if (B* b = dynamic_cast<B*>(ptr))
    puts("successful dynamic_cast");
  ptr->fn();
  }
#endif

// Application code
#ifdef APP
struct C : B
  {
  virtual void fn()
    { puts("c"); }
  };

int main()
  {
  C obj;
  lib_fn(&obj);
  return 0;
  }
#endif

Here we have a library which provides a number of classes.  It is compiled with RTTI because it uses dynamic_cast internally, but we are not aware of this (we haven't read the source code, and it wasn't mentioned in the library documentation).  The following command can be used to create the library:
g++ -shared -o libmodule.so -fPIC code.cpp -DLIB
We also have our application.  We subclass a library class and pass an instance of this into a library function.  We compile our application without RTTI since we want to save space and we don't like the fact that RTTI leaches information about the names of our classes in our application binary.  To create the application executable that uses the library:
g++ -s -fno-rtti -o app code.cpp -DAPP -L. -lmodule -Wl,-rpath,.
This application, compiled with the -fno-rtti will crash since the application does not include RTTI information and even though it does not itself use it, the library does.
If this is a third-party library it may not be possible to be sure that it doesn't use dynamic_cast in a way that might affect your code.  Worse, it might not today, but it might be replaced in future with a version that does, at which point the application will then start to crash.


text:
Q: Why is my body element smaller than my html element? all my margins and padding are 0. In the global.css file I only have this small piece of code:
html, body {
    width: 100%;
    height: 100%;
}

body {
    padding: 0;
    margin: 0;
}

Here you can see the highlighted part of <body>. Note the fact that the body pixel size is 1261 x 876.

In the 2nd picture you can see that the <html> part also has the same pixel size of 1261 x 876, but is highlighting the entire screen, without the white bar on top.
EDIT: I have checked the child elements inside the <body> for overflow. They had some overflow padding.

A: To sum up, resetcss lead me to the answer. The answer was a child overflowing the parent element.


text:
Q: Why non-measurable sets exist? What Is the reason behind the fact that $\Bbb R$ is not a complete measure space? Is it only due to the cardinality of  $\Bbb R$? Or other structures on  $\Bbb R$ also play a role? Can one make every subset of  $\Bbb R$ trivially measurable by assigning them to a number of a complete ordered field of the cardinality $\aleph_2$ ?

A: The reason would depend on the particular argument you give but it all boils down to the fact that (with the axiom of choice) one can construct very bizarre sets of real numbers.
You also have to be more precise. There are measures on the set of all subsets of $\mathbb R$, e.g., counting measure. What does not exist is a translation invariant extension of Lebesgue measure to all subsets of $\mathbb R$. For this certainly the additive structure of $\mathbb R$ is important.
For an interesting discussion of this matter together with two proofs of the existence of non-measurable sets as well as what happens in other dimensions see "The joys of Haar measure".

A: There is a lot of inaccuracy in what you are saying. As Ittay notes, you are talking about the Lebesgue measure only, otherwise, for example, pick any singleton (say $\{0\}$) and say that $A\subseteq\Bbb R$ has measure $1$ if and only if $0\in A$. You can check that this is a measure and that it is $\sigma$-additive, and that every set is measurable.
In fact, under additional set theoretic hypotheses you can show it might be possible that there is a measure extending the Lebesgue measure and measures all the subsets of $\Bbb R$. But it is important to note that this measure will not be translation invariant in general.
So why are there non-Lebesgue measurable sets? This is because there are a lot of sets of real numbers. And every Lebesgue measurable set is "essentially Borel" (in the sense that it is equal to a Borel set modulo a null set), but there are very few Borel sets.
Moreover, the axiom of choice allows us to carry all sort of crazy constructions. It will allow us to choose representatives from $\Bbb{R/Q}$ to construct a Vitali set, and it will allow us to create ultrafilters on $\Bbb N$ which can be translated (in a canonical way) to subsets of $\Bbb R$ which are not measurable in general; and it will allow us to do much much more.
Yes, we like to think about sets of real numbers in terms of open intervals, and their intersections, unions and complements. But that much won't get you very far in understanding all the subsets of $\Bbb R$. Even less so when assuming the axiom of choice.
So what happens without the axiom of choice? It can be the same situation if a "sufficient" fragment of the axiom of choice is assumed to hold (for example assume that $\Bbb R$ can be well-ordered, or that free ultrafilters on $\Bbb N$ exist, or so on). Or it can be that all those things fail, and in fact all sets are measurable.
But now the term "measurable" needs to be handled with care. It might be that there are no non-atomic $\sigma$-additive measures, or it might be that there is an extension of the Lebesgue measurable which is not invariant under translations, or it might be that really the Lebesgue measure is $\sigma$-additive and measures every set (which would require additional set theoretic assumptions to achieve). All those things are much more complicated to handle and understand than just understanding where non-measurable sets come from.
And the axiom of choice is far too useful for mathematicians to just drop it.


text:
Q: Sitemesh 2.4.2 decorator issue with pattern I am using sitemesh 2.4.2 and while it seems to be OK according to configuration when the decoration process begins for layout.jsp I get the following error:
Servlet failed with an Exception
java.lang.RuntimeException: java.io.IOException: Stream already closed
My decorator.xml is the following:
<decorators defaultdir="/decorators/templates/default">
<decorator name="layout" page="layout.jsp"><pattern>/*</pattern></decorator>
<decorator name="head" page="/decorators/common/head.jsp"/>
<decorator name="header" page="header.jsp"/>
<decorator name="body" page="body.jsp"/>
<decorator name="footer" page="footer.jsp"/>
<decorator name="content" page="content.jsp"/>
<decorator name="blockContent" page="blockContent.jsp"/>

<decorator name="simpleLayout" page="/decorators/common/layout_nomenu.jsp">
    <pattern>/login.jsp</pattern>
    <pattern>/error.jsp</pattern>
</decorator>
<decorator name="dialog" page="/decorators/common/dialog.jsp">
    <url-pattern>**/edit.jsp</url-pattern>
    <url-pattern>**/view*.jsp</url-pattern>
</decorator>
<decorator name="simpleContent" page="/decorators/common/body_nomenu.jsp"/>

Login page is decorated correctly so I think the problem occurs when the layout decorator is applied.


text:
Q: Single page app, permalinks and ngView? This is my current setup, with each column being represented by a controller:
<navbar></navbar>
[column1] [column2] [column3]

Additionally each column has a bit of information (one or more variables and objects) which when modified, need to be propagated across to its neighbour.
Presently I share these variables by using a factory and injecting that into the relevant controller(s).
Now I want to permalink variable values, e.g.:
http://localhost/column1/vars?var1=2&var2='hi'
                /column2/ls1=%7B%27c%27%3A+1%2C+%27f%27%3A+%27b%27%7D
                /column3/...

This should also allow me to remove my factories.
What's the best way to achieve this setup, e.g.: are ngViews the answer?

A: You could use the angular-ui teams ui-router (https://github.com/angular-ui/ui-router) for this to keep track of what is effectively a set of optional parameters. To do this your code would look something like:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>

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

Go to Foo

Go to Bar

Go to Baz

Go to Bah

      {{$stateParams}}

with a stateprovider setup to accept these optional parameters:
var app = angular.module('plunker', ['ui.state'])
  .config(['$stateProvider', function ($stateProvider) {
        $stateProvider
          .state('foo',
          {
            url: '/foo?var1&var2',
            template: '
Foo
',
            controller: 'subCtrl'
          })
          .state('bar',
          {
            url: '/bar?var1&var2',
            template: '
Bar
',
            controller: 'subCtrl'
          })
          .state('baz',
          {
            url: '/baz?var1&var2&var3',
            template: '
Baz
',
            controller: 'subCtrl'
          })
          .state('bah',
          {
            url: '/bah?var1&var2&var3',
            template: '
Bah
',
            controller: 'subCtrl'
          });
    }])
    .run(['$stateParams', '$rootScope', function($stateParams, $rootScope){
      $rootScope.$stateParams = $stateParams
    }]);

app.controller('MainCtrl', function($scope, $state, $location) {
  $scope.bazVars = {
    var1: 'goodbye',
    var2: 'world'
  }
  $scope.transition = function(name, options){
    $state.transitionTo(name, options);
  }
  $scope.transitionLocation = function(name, options){
    $location.path('/' + name);
    for(key in options){
      $location.search(key, options[key]);
    }
    console.log($location.url());
  }
});

app.controller('subCtrl', function($scope, $stateParams){
  console.log($stateParams);
})

Working plunker of the above: http://plnkr.co/edit/ZVLApU92MVdIhlovailY?p=preview
Note that ui-router allows for nested states using a dot notation as well so you can keep track of sub parameters of your page with this same mechanism (see https://github.com/angular-ui/ui-router/wiki/Nested-States-%26-Nested-Views).

A: Not sure I understand the requirement here all that well...
One thing is sharing parameters and sharing them among controllers... But I am not sure I understand your URLs entirely...
What I am most curious about is the presence of "Column1, Column2 and Column3" in the url? what is the need for those?...
Here is a little plunker to see if I have just gotten close to understand part of the idea:
 - http://plnkr.co/edit/ZkaANVq5tCdLKWqHFa16?p=preview
(Using https://github.com/dotJEM/angular-routing)
It really just propagates all variables into a link for the same "state"...
Note: I Choose a more advanced routing solution than Angulars ngRoute module, but in reality, for this use-case I don't think you need anything more advanced than the basic router... but it does ofc. have the advantage that you won't have to change at a later point if you suddenly find your self needing nested views, ability to filter parameters etc.


text:
Q: dplyr: select columns by position in NSE I am trying to create a function that will select columns in a DF based on their position. I will always need the first column and then a subset of the DF. I have 1 object for each subset I need to select.
So far I have tried the following:
position <- "1,28:31"
DF %>%
  select_(.dots = position)

but I receive the following error:

Error in parse(text = x) : :1:2: unexpected 'x'

It would seem the problem is the comma separation in the column position.
Is there a workaround?

A: Another solution with dplyr :
DF %>%
  select(!!c(1, 28:31))

cf : https://www.rdocumentation.org/packages/dplyr/versions/0.7.6/topics/select
You can also use with the dplyr version 0.8
DF %>%
      select(1, 28:31)

A: You can just use select with a numeric vector of indexes:
positions <- c(1,28:31)
DF %>% select(positions)

A: Using mtcars and:

*

*add auto as my first column

*select `c(auto, the first column, and any column containing an 'a')

*subset the data where only the sums of numeric rows are greater than the mean of all sums of those rows

mtcars %>% mutate(auto = row.names(.)) %>%
   select(auto, 1, contains('a')) %>%
   dplyr::filter(rowSums(.[-1]) > mean(rowSums(.[-1])))
             auto  mpg drat am gear carb
1       Mazda RX4 21.0 3.90  1    4    4
2   Mazda RX4 Wag 21.0 3.90  1    4    4
3      Datsun 710 22.8 3.85  1    4    1
4       Merc 240D 24.4 3.69  0    4    2
5        Merc 230 22.8 3.92  0    4    2
6        Merc 280 19.2 3.92  0    4    4
7        Fiat 128 32.4 4.08  1    4    1
8     Honda Civic 30.4 4.93  1    4    2
9  Toyota Corolla 33.9 4.22  1    4    1
10      Fiat X1-9 27.3 4.08  1    4    1
11  Porsche 914-2 26.0 4.43  1    5    2
12   Lotus Europa 30.4 3.77  1    5    2
13   Ferrari Dino 19.7 3.62  1    5    6
14  Maserati Bora 15.0 3.54  1    5    8
15     Volvo 142E 21.4 4.11  1    4    2

A:  Select.by.pos <- function(pos, dt){

   return(dt[, pos])

 }

The pos argument should not be a string but a numeeic vector :) dt is a dataframe


text:
Q: How can I programmatically delete a python launching executable?
Possible Duplicate:
Can a program delete its own executable

My application is compiled in Py2exe. However after execution is finished, another application will be loaded. The main executable will no longer be needed, so how can I go about having the Python application delete itself?

A: If you control the second executable's source code, you can delete the first executable from the second. Other than that, I can't think of a way to accomplish this.


text:
Q: UnicodeDecodeError from Tensorflow Tutorials "Text classification with TF Hub" I just start learning tensorflow with Tutorials of Tensorflow Core.
import os
import numpy as np
import tensorflow as tf
import tensorflow_hub as hub
import tensorflow_datasets as tfds

train_data, validation_data, test_data = tfds.load(name='imdb_reviews', split=('train[:60%]', 'train[60%:]', 'test'), as_supervised=True)

then I got error like this.
error messages
Some blog says this Error can be resolved by installing tensorflow-gpu.
But in my case, that dosen't work.
How can I fix this error?
(win10, anaconda. conda ver. 4.9.2., windows terminal, anaconda prompt)

A: After re-installation of Anaconda and Tensorflow issue was resolved.
import os
import numpy as np
import tensorflow as tf
import tensorflow_hub as hub
import tensorflow_datasets as tfds

train_data, validation_data, test_data = tfds.load(name='imdb_reviews', split=('train[:60%]', 'train[60%:]', 'test'), as_supervised=True)


text:
Q: How to change column caption names to database values, jqGrid? in the trirands jqGrids's pivot table has a table called many summary values
in it, it uses the following json data
{
  "rows":[
    {
        "CategoryName":"Beverages",
        "ProductName":"Steeleye Stout",
        "Country":"UK",
        "Price":"1008.0000",
        "Quantity":"65"
    },{
        "CategoryName":"Beverages",
        "ProductName":"Laughing Lumberjack Lager",
        "Country":"USA",
        "Price":"140.0000",
        "Quantity":"10"
    },{
        "CategoryName":"Beverages",
        "ProductName":"Guarana Fantastica",
        "Country":"USA",
        "Price":"724.50",
        "Quantity":"10"
    }

]}

Assume i'm sending something similar to above data from DB, in the sample on trirand website shows that are two columns with Captions Price and Qty. But assume i only need the price column and in that price column header instead of printing the caption price i want to print the value in the Price property of above data. so if teh json has 12 objects there will be 12 price columns but those price columns will have the value of the prices printed on the column header caption like this:


text:
Q: TV13 in ubuntu 14.04 64bit error. "Not ready, Please check your connection" everyone,
I have installed tv13 64bit (teamviewer_13.1.3026_amd64.deb) and this is my first attempt to run teamviewer in linux ever. The OS is ubuntu 14.04 64bit.
there are dependency errors (with Qt5) and I could not see the teamviewer window at all. I "fixed" that by installing Qt5 (5.10.1 to be precise), and starting teamviewer with the following line:
LD_LIBRARY_PATH=/opt/Qt5/5.10.1/gcc_64/lib/ /opt/teamviewer/tv_bin/TeamViewer

you'll notice I start the executable directly from the installation directory.
The teamviewer windows pops up now, but I get this messages in the command line :
failed to get the current screen resources
QXcbConnection: XCB error: 173 (Unknown), sequence: 175, resource id: 87, major code: 150 (Unknown), minor code: 20
WARNING: Application calling GLX 1.3 function "glXCreatePbuffer" when GLX 1.3 is not supported!  This is an application bug!
QSGContext::initialize: stencil buffer support missing, expect rendering errors

Not sure if these are related to my issue though.
Also if I run the usual teamviewer script
LD_LIBRARY_PATH=/opt/Qt5/5.10.1/gcc_64/lib/ /usr/bin/teamviewer

I will get the following output
Init...
CheckCPU: SSE2 support: yes
Checking setup...
Launching TeamViewer ...
Starting network process (no daemon)
Network process already started (or error)
Launching TeamViewer GUI ...

In both cases the GUI will be loaded and the edit boxes will be disabled because of the error "Not ready. Please check your connection" .

it may be that the teamviewerd deamon is not running , so I tried starting that as well, but I do not see it running when I check running processes in linux with
ps aux | grep -i teamv

I only see the GUI running.
Anyone knows of any remedies ?
EDIT:
ok I just realized that the teamviewer executable has help menu and it is triggered only by teamviewer help. So I started the daemon with
sudo teamviewer --daemon restart

and I can see it running now. Yet the problem remains.
Thank you in advance for your help

A: I also experienced similar issue with Ubuntu 16.04.4.. However Teamviewer started working normally once I made sure no processes were running and restarted it again. Teamviewer says that 14.04 / LTS should be supported with Qt 5.2 on Ubuntu 14.04 / Debian 8 for the moment. https://community.teamviewer.com/t5/Knowledge-Base/How-to-install-TeamViewer-for-Linux/ta-p/6318
Perhaps try removing or purging Teamviewer 13 and installing from the stable repository? It could be that you have Teamviewer preview -repository enabled, which might have Ubuntu 14.04 incompatible packages.
Installing Teamviewer from the .deb-file downloadable on TV website should add the repositories for Teamviewer in /etc/apt/sources.list.d/teamviewer.list
Currently I have:
        ###   TeamViewer DEB repository list

        ### NOTE: Manual changes to this file
        ###        - prevent it from being updated by TeamViewer package updates
        ###        - will be lost after using the 'teamviewer repo' command
        ###       The original file can be restored with this command:
        ###       cp /opt/teamviewer/tv_bin/script/teamviewer.list /etc/apt/sources.list.d/teamviewer.list
        ###       which has the same effect as 'teamviewer repo default'

        ### NOTE: It is preferred to use the following commands to edit this file:
        ###       teamviewer repo                - show current repository configuration
        ###       teamviewer repo default        - restore default configuration
        ###       teamviewer repo disable        - disable the repository
        ###       teamviewer repo main [stable]  - make all TeamViewer packages available (default)
        ###       teamviewer repo tv13 [stable]  - make TeamViewer 13 packages available
        ###                             stable     omit preview and beta releases

        ### Choose stable main to receive updates for TeamViewer 13 and upcoming major releases
        ### Choose preview main to receive early updates for TeamViewer 13 and to receive major beta releases

        ### Choose stable tv13 to receive updates for TeamViewer 13
        ### Choose preview tv13 to receive early updates for TeamViewer 13

        deb http://linux.teamviewer.com/deb stable main
        #deb http://linux.teamviewer.com/deb preview main

        # deb http://linux.teamviewer.com/deb stable tv13
        # deb http://linux.teamviewer.com/deb preview tv13


text:
Q: Find unbiased for $\theta$ given a uniform distribution on the interval $[0, \theta]$. Let $Y_{(1)} = \min(Y_1,\ldots, y_n)$ Show that $\hat{\theta_1} = (n+1) ~y_{(1)}$ is unbiased for $\theta$.
So far what I got is
$f(y) = 1/\theta$ for , $0 \le y \le \theta$
So $F(y) = P[Y \le y] = \displaystyle \int_\theta^y 1/\theta dy = y/\theta |_\theta^y = 1 - y/\theta$.
Then $g_{(1)} (y) = n [ -y/\theta]^{(n-1)} (y/\theta)$
Are these right? If so, how to go from here? If so, could you show your approach?
Thanks

A: Let $W$ be the minimum. The minimum is $\gt w$ iff all the $Y_i$ are $\gt w$.
The probability a particular $Y_i$ is $\gt w$ is, for $0\lt w\lt \theta$, equal to $1-w/\theta$. Thus the probability all the $Y_i$ are $\gt w$ is $(1-w/\theta)^n$, and therefore
$$F_W(w)=1-(1-w/\theta)^n,$$
(for $0\lt w\lt \theta$).
Thus the minimum has density function $(1/\theta)n(1-w/\theta)^{n-1}$ in our interval. The mean of $W$ is therefore
$$\int_0^{\theta} w(1/\theta)n(1-w/\theta)^{n-1}\,dw.$$
Integrate. I suggest making the substitution $x=1-w/\theta$. Integration by parts will also work well.
If you know a formula for expectation in terms of an integral that involves the cumulative distribution function, use that, it will be somewhat simpler.
Added: Let $1-w/\theta=x$. Then $-dw/\theta=dx$, so $dw=-\theta \,dx$. Also, $w=(1-x)\theta$. Substitute. We get
$$\int_{x=1}^0 (1-x)\theta(1/\theta)nx^{n-1}(-\theta)\,dx.$$
Simplify a bit. We end up with
$$\int_0^1 (\theta n)(x^{n-1}-x^n)\,dx.$$
Integrate. The integral of $x^{n-1}-x^n$ from $0$ to $1$ is $\frac{1}{n}-\frac{1}{n+1}$, which is $\frac{1}{n(n+1)}$. Multiply by $n\theta$. we get $\frac{\theta}{n+1}$.
So the expectation of $W$ is $\frac{\theta}{n+1}$. Thus the expectation of our estimator $(n+1)W$ is $\theta$. It follows that $(n+1)W$ is an unbiased estimator of $\theta$.

A: Actually you are close.
The cdf of $Y_{(1)} =\min(y_1, …, y_n)$ looks like:
$$F_Y(y)=1-(1-F_{y(1)}(y))^n=1-\left(1-\frac{y}{\theta}\right)^n,$$ then the pdf $$w_Y(y)=\frac{n}{\theta }\left(1-\frac{y}{\theta }\right)^{n-1}.$$
So $$\mathbb{E}\{\hat{\theta}\}=(n+1)\int_0^\theta y \  w_Y(y)\mathrm dy=(n+1)\int_0^\theta y \  \frac{n}{\theta }\left(1-\frac{y}{\theta }\right)^{n-1}\mathrm dy=\theta$$
And since the mean value of your estimator ($\hat{\theta}$) equals to $\theta$ it is unbiased.


text:
Q: Unable to translate set operation when matching columns on both sides have different store types var dbHold1 = _context.CompanyDirectorSh.Select(x => new { x.Shareholderid, Fname= x.Fname, Lname = x.Lname , x.Cmpid })
    .Union(_context.CompanyNonDirectorSh.Select(x => new { x.Shareholderid, Fname = x.Fname , Lname = x.Lname , x.Cmpid }))
    .Union(_context.CompanyAnotherCompany.Select(x => new { x.Shareholderid, Fname = x.ExecuterFname , Lname = x.ExecuterLname, x.Cmpid }))
    .Where(x => x.Cmpid == companyId).ToList();


text:
Q: Customizing source-highlight's color schemes? The source-highlight package is installed on my system. It highlights files I view with less using /usr/bin/lesspipe and LESSOPEN environment variable.
Now, I want to change the color scheme this mechanism uses for some/all filetypes. I have root on the machine. How do I do this?
Note: It's a Devuan 3 Beowulf (~= Debian 10 Buster) Linux distribution.

A: Well, you can use a different style file in the source-highlight that's used for less. In  /usr/share/source-highlight/src-hilite-lesspipe.sh, you will find:
source-highlight --failsafe --infer-lang -f esc --style-file=esc.style -i "$source" ;;

you can replace esc.style with a different style file (from usr/share/source-highlight/). However... most style files aren't compatible with emitting ANSI escape codes, and won't work. So, you're basically stuck.
Try contacting the author perhaps.
Haven't found anything relevant in the GNU source-highlight manual


text:
Q: how to update and add entries with attributes to a xml file, sorted by date? I want to store my logged keystrokes with their id and the count by each day to an xml file. The keystrokes are temporaray saved in an Hashtable. I want to move the collected data from the hashtable every 20 sec to the xml file. The Programm should create a new Entry with the Attribute Keyid and the collected amount under the entry Element with the current date. If an Key already exsits, the programm should update the count of this key by adding the new count to the old one. Here is my example XML File:
<?xml version="1.0" encoding="utf-8" ?>
<entrys>
  <entry date="2015_08_31">
    <key id ="4">78</key>
    <key id ="99">4</key>
    <key id ="210">7</key>
  </entry>
  <entry date="2015_08_30">
    <key id ="4">8</key>
    <key id ="9">6</key>
    <key id ="210">8</key>
  </entry>
</entrys>

Working with c#

A: You can do this as follows:

*

*Use XDocument to load your XML file.

*Convert your data to a dictionary of dictionaries.

*Merge the new data into the dictionary of dictionaries.

*Convert the dictionary of dictionaries back to XML.

The following code demonstrates. It expects as input a file called "D:\TEST\INPUT.XML" containing the XML code from your question.
If creates as output a file called "D:\TEST\OUTPUT.XML" containing the merged data. Edit the filenames to suit.
Hopefully you can run this code under the debugger to get an idea of how it works.
Given this input:
<?xml version="1.0" encoding="utf-8" ?>
<entrys>
  <entry date="2015_08_31">
    <key id ="4">78</key>
    <key id ="99">4</key>
    <key id ="210">7</key>
  </entry>
  <entry date="2015_08_30">
    <key id ="4">8</key>
    <key id ="9">6</key>
    <key id ="210">8</key>
  </entry>
</entrys>

Running the code gives the following output:
<?xml version="1.0" encoding="utf-8"?>
<entrys>
  <entry date="2015_08_31">
    <key id="4">78</key>
    <key id="99">14</key>
    <key id="210">7</key>
    <key id="300">20</key>
  </entry>
  <entry date="2015_08_30">
    <key id="4">8</key>
    <key id="9">6</key>
    <key id="210">8</key>
  </entry>
</entrys>

The code is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace Demo
{
    internal class Program
    {
        [STAThread]
        private static void Main()
        {
            var doc = XDocument.Load("D:\\TEST\\INPUT.XML"); // Assume you have the XML file stored here.

            // Convert existing entries to a dictionary of dictionaries:
            // So dict[date][key] == count

            var entries = doc.Elements("entrys").Elements("entry");

            var existing = entries.ToDictionary
            (
                item => item.Attribute("date").Value,
                item => item.Descendants("key").ToDictionary
                (
                    key => (int)key.Attribute("id"),
                    key => (int)key
                )
            );

            // SAMPLE DATA: Add new items for specific date.

            string date = "2015_08_31";

            var newData = new Dictionary<int, int>();

            newData[99]  = 10;
            newData[300] = 20;

            addEntriesForDate(date, existing, newData);

            // Store back to XML.

            var xd = new XDocument(new XDeclaration("1.0", "UTF-8", ""),
                new XElement("entrys", existing.Select(kvp =>
                    new XElement("entry", new XAttribute("date", kvp.Key), kvp.Value.Select(key =>
                        new XElement("key", new XAttribute("id", key.Key), key.Value
             ))))));

            xd.Save("D:\\TEST\\OUTPUT.XML");
        }

        private static void addEntriesForDate(string date, Dictionary<string, Dictionary<int, int>> existing, Dictionary<int, int> newData)
        {
            if (!existing.ContainsKey(date))
                existing[date] = new Dictionary<int, int>();

            var data = existing[date];

            foreach (var entry in newData)
            {
                if (data.ContainsKey(entry.Key))
                    data[entry.Key] += entry.Value;
                else
                    data[entry.Key] = entry.Value;
            }
        }
    }
}


text:
Q: RPM Requires exact release tag I'm working on a Java project were each module creates individual rpm packages that always have a 1.0 Version tag, but the Release tag adopts the build number injected by Jenkins CI.
Each component uses the maven-rpm-plugin.
There's also a main rpm package were we specify the exact version of the deployed modules as requirements in the spec file, as a requirement example:

Requires: module1 = 1.0-10
Requires: module2 = 1.0-123

The packages are deployed to the company's repository and are made available to our development machines that run CentOS 6.
So the issue is:
On one dev machine, the previous main package installed module1-1.0-9
When I install the current main package version using yum, module1 does not get upgraded, even though I specified an exact package version requirement, down to the Release tag.
After removing all packages and trying to install the current main package, module1-1.0-12 get's installed! Another module build was deployed in the meantime.
I've been looking for any kind of documentation about this but haven't had any luck.
Is this normal behavior or a bug?
Any ideas? - even changing versioning strategy would be welcome, if it's indeed not a bug.

A: Is the package name changing somehow?  Yum uses the name, version and the release.  So if you are packaging with a different name then yum is not going to see the newer package as an update to the old one.
Do an rpm -qip *your-rpm-file-name.rpm* and compare the output of the name.  I've seen in the past some people get confused with the file name of the RPM and actual name of the RPM that yum/rpm uses.

A: After another day trying to get to the bottom of this I finally stumbled across this bug report in bugzilla.
I also took a look at the yum related source code and found a comment on the depsolve.py module that explains how dependencies are resolved and corroborates the previously reported behavior in CentOS 6:

*

*If you're installing a package and a required packaged is found, the latest version is installed

*If you're updating a package and a required package is already installed, there is no dependency upgrade


text:
Q: Foreach not looping through all controls while copying them from one form to another I am trying to copy all controls from a dynamic form to another statically declared form. Curiously exactly half of them are getting copied. The code looks like this-
// Constructor of static form
public ApplicationForm(dynamic form)
{
        // Add all controls from the dynamic form to the Application form
        Console.WriteLine("I have total of {0} controls\n", form.Controls.Count);
        int i = 0;
        foreach (Control c in form.Controls)
        {
            i++;
            this.Controls.Add(c);
            Console.WriteLine(" Number of controls rem {1}\n",
                              form.Controls.Count);
        }
        Console.WriteLine("I added a total of {0} controls and still have {1}\n",i,
                           form.Controls.Count);
}

For one particular example, there were 56 controls at the beginning of the loop and there were 27 still remaining at the completion of the loop. And just to test I added the same for loop again after the first one. This time there were 13 remaining.
Why are only half of the controls getting added? Why is the foreach loop exiting prematurely?
PS: I reason I am doing this copy is because I do know a way of capturing keystrokes for a dynamic form. For a static form, I can override ProcessCmdKey and trap keystrokes but I dont know of any equivalent for dynamic forms

A: Your assumption probably is that this:
    foreach (Control c in form.Controls)
    {
        this.Controls.Add(c);
    }

only affects ONE ControlColection, namely the collection on this. A control however can only have ONE parent. The internals of the Add implementation reveals the following:
public virtual void Add(Control value)
{
    // skipped stuff
    if (value.parent != null)
    {
        value.parent.Controls.Remove(value);
    }
    base.InnerList.Add(value);
    // many more
 }

Notice how the Add method calls Remove for the parent controlcollection. The InnerList is an ArrayList. It's size gets reduced on the parent every time you add a control to the other form. Hence you only process half of them.
Before you start adding the Controls copy to a List<Control> first and then add the controls from the list to the ApplicationForm.
    // copy controls to list
    var list = new List<Control>();
    foreach (Control c in form.Controls)
    {
        list.Add(c);
    }
    Console.WriteLine("I have total of {0} controls\n", form.Controls.Count);
    int i = 0;
    // iterate over list
    foreach (Control c in list)
    {
        i++;
        this.Controls.Add(c);
        Console.WriteLine(" Number of controls rem {1}\n",
                          form.Controls.Count);
    }
    Console.WriteLine("I added a total of {0} controls and still have {1}\n",i,
                       form.Controls.Count);


text:
Q: How to get "Enums" objects in a class by reflection I have this class:
public class user
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public EyeColor EyeColor { get; set; }
}
public enum EyeColor
{
    Brown,
    Black
}

I can use user.GetType().GetProperties(); to get properties and then get values of them.
But for enums is different, all I want to do is: getting Enum index, for example brown is 0 and black is 1 for dynamic search on enum fields.
But I have a generic method to get index and I can't use int enumIndex = (EyeColor)user.EyeColor; because I don't know what kind of enum will be pass to the generic method.
public static IQueryable<T> CreateEqualExpressions<T>(IQueryable<T> query, object model)
{
    var result = query;
    var propertiesToSearch = model.GetType().GetProperties()
        .Where(x => Attribute.IsDefined(x, typeof(EqualSearchAttribute)))
        .ToList();
    if (propertiesToSearch.Count > 0)
    {
        foreach (var propertyInfo in propertiesToSearch)
        {
            var propertyValue = propertyInfo.GetValue(model);
            if (!string.IsNullOrWhiteSpace(propertyValue?.ToString()))
            {
                var parameter = Expression.Parameter(typeof(T));
                var property = Expression.Property(parameter, propertyInfo.Name);
                if (propertyValue is string)
                    propertyValue = propertyValue.ToString()?.Trim();
                var constantValue = Expression.Constant(propertyValue);
                var equal = Expression.Equal(property, constantValue);
                var exp = Expression.Lambda<Func<T, bool>>(equal, parameter);
                result = result.Where(exp);
            }
        }
    }

    return result;
}

Everything is ok for strings but for enums not works because propertyValue is: Brown or Black, but for dynamic search, I need to index of them like 0 or 1.
Any suggestion ?

A: What about something like this?
var type = propertyInfo.PropertyType;
if (type.IsEnum)
{
  var enumIndex = (int) propertyValue;
}

A: If I understand correctly, you just need Convert.ToInt64 to convert the enum value to a long, which fits every enum underlying type.
var value = propertyInfo.GetValue(model);
if (propertyInfo.PropertyType.IsEnum) {
    long underlyingEnumValue = Convert.ToInt64(value);
    // construct your expression here...
}

Note that if you are constructing an Expression.Equal, with one of the operands being the EyeColor property access, you should convert that to long too:
var equal = Expression.Equal(
    Expression.Convert(property, typeof(long)),
    Expression.Constant(underlyingEnumValue)
);

Example code:
var prop = typeof(User).GetProperty("EyeColor")!;
var value = prop.GetValue(new User() { EyeColor = EyeColor.Black });
var underlyingEnumValue = Convert.ToInt64(value);

var p = Expression.Parameter(typeof(User));
var lambda = Expression.Lambda(
    Expression.Equal(
        Expression.Convert(
            Expression.Property(p, prop),
            typeof(long)), Expression.Constant(underlyingEnumValue)
    ), p
);

var del = lambda.Compile();
var result1 = del.DynamicInvoke(new User() { EyeColor = EyeColor.Brown });
var result2 = del.DynamicInvoke(new User() { EyeColor = EyeColor.Black });

Console.WriteLine(result1); // False
Console.WriteLine(result2); // True

A: if Property is enum then you can try this also
object underlyingValue = Convert.ChangeType(value, Enum.GetUnderlyingType(value.GetType()));


text:
Q: Can't use langdetect package in python I am trying to detect language of the string with langdetect package. But it does not work.
from langdetect import detect

word_string = "Books are for reading"
print(detect(word_string))

If I use code above I get error ImportError: cannot import name detect
When I replace detect with *
from langdetect import *

word_string = "Books are for reading"
print(detect(word_string))

I get error: NameError: name 'detect' is not defined
So my question is how can I solve these problems ?
So the problem was that my langdetect package and python file was with the same name.... Thank you for your answers.

A: Try installing it first by writing :->
!pip install langdetect on terminal
and then import langdetect

A: You can not import it because it is probably not there. See if the name is correct. Seeing other questions here on SO I assume you mean detect_langs.

A: Your error indicates the Python interpreter couldn't find the module you are importing in it's sys.path.
Add to your code
import os
sys.path.append('absolute_path to your module.py file')

and try again.
Another option is to add your PYTHONPATH environment variable the folder containing your module.
Try import langdetect after validating it's path is in your sys.path variable; if this commands succeeds it means you loaded the module successfully. Now you need to address the detect function as langdetect.detect because it resides in the langdetect namespace. If it doesn't find it - it's not there.


text:
Q: Hide android icon from application list I want to hide my application icon from launcher screen and from Application list as well.
I can hide application icon from launcher using:
PackageManager p = getPackageManager();
p.setComponentEnabledSetting(getComponentName(), PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);`

How can i hide icon from application list as well ???
Any help will be appreciated .

A: Not possible to hide application from list


text:
Q: GWT SerializationPolicy whitelist I have a GWT project which was working earlier on, but have stopped working.
The error I receive is:

com.google.gwt.user.client.rpc.SerializationException: Type 'java.util.ArrayList' was not included in the set of types which can be serialized by this SerializationPolicy or its Class object could not be loaded. For security purposes, this type will not be serialized.

Now the gwt compiling gave this output:

Verifying instantiability
  dk.web.client.Dummy
  Analyzing the fields of type 'dk.web.client.Dummy' that qualify for serialization
  private java.util.ArrayList al
  java.util.ArrayList
  Verifying instantiability
  java.util.ArrayList
  [WARN] Checking all subtypes of Object which qualify for serialization

I have zero argument constructor on all classes that are use in the RPC service and they all implements IsSerializable.
The dummy class above has all classes used in the RPC service in an attempt to add missing classes to the SerializationPolicy whitelist.
What could I be missing?
Thanks

A: As of GWT1.4 there has been support for java.io.Serializable see here. Can you try making your classes extend Serializable instead?
GWT has a JRE emulation for ArrayList so I would guess it was a problem with your class.

A: How are you instantiating your ArrayList, are you giving the generic a type?
ArrayList<Object> for example is not allowed. Where using a serializable object like ArrayList<String> would be.


text:
Q: AttributeError: module 'PIL' has no attribute 'Image' Here is a sample code I was running for opencv
import cv2
from google.colab.patches import cv2_imshow

img = cv2.imread('rose.png')
print("Image Properties")
print(" - Number of Pixels:" + str(img.size))
print("-Shape/Dimensions:" + str(img.shape))

blue, green, red = cv2.split(img) # Split the image into its channels
img_gs = cv2.imread('rose.png', cv2.IMREAD_GRAYSCALE) # Convert image to grayscale
cv2_imshow(img_gs)

Below is the error Im getting. I have tried other solutions suggesting issue with pillow version etc. But somehow this doesn't work.
cv2_imshow(img_gs)
  File "/Users/fazalshaik/.pyenv/versions/myproject/lib/python3.6/site-packages/google/colab/patches/__init__.py", line 29, in cv2_imshow
    display.display(PIL.Image.fromarray(a))
AttributeError: module 'PIL' has no attribute 'Image'


text:
Q: Remove subscribers from a journey data extension via an action in the journey itself Please help me sort this issue.
Subscribers from 70 different countries are injected into a journey data extension via API originating from our Axapta ERP.
I can't control what is injected via Axapta.
Of the subscribers injected only those from 3 of the 70 countries qualify for emails in the journey, the rest are exited from the journey again after 1 minute.
Of the subscribers injected from those 3 countries qualifying, only approx. 50% actually qualify for emails in the journey, the rest are also exited from the journey again after 1 minute.
Can I in any way remove those subscribers exiting the journey after 1 minute from the journey data extension via any action in the journey itself?
(exit criteria or a journey builder activity)
I want to do so, so the journey data extension only reflects those actually on the journey for exclusion purposes.
Thank you
Note: I could probably accomplish this by querying the journey exclusion data extension into a new data extension using the same logic for the decisions splits as in the journey, but I'd have to maintain the logic twice, and the query part would be a little out of reach for my customer

A: Some solutions:

*

*Create a filter on the API entry event

*Use the Update Contact block in the Journey to log in a separate data extension (for your exclusion purposes) who qualified for emails in this journey. Just remember that you need to work around the limitations of this block to dynamically log the values for each customer - I would recommend this approach and that you can only log data to 5 columns this way.

*Manually add a Boolean field to the data extension, use the Update Contact block to write True or False to this field. Then you can either create a new filtered data extension, query based on this DE or have a script delete all records within this DE with a particular value.


text:
Q: what method i must use instead of DeviceListAdapter in android studio I want to scan unpaired devices through Bluetooth. Devices are not shown in the list. is there a problem of not using DeviceListAdapter ?? if it is then which option i have to use to show devices because in android studio there is no option of DeviceListAdapter.
This is button code :
btnScan.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick (View v) {
        if (bluetoothAdapter.isDiscovering()) {
            bluetoothAdapter.cancelDiscovery();
            bluetoothAdapter.startDiscovery();
            IntentFilter discoverDeviceIntent = new IntentFilter(BluetoothDevice
                    .ACTION_FOUND);
            registerReceiver(broadcastReceiver, discoverDeviceIntent);
        }
        if (!bluetoothAdapter.isDiscovering()) {
            bluetoothAdapter.startDiscovery();
            IntentFilter discoverDeviceIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
            registerReceiver(broadcastReceiver, discoverDeviceIntent);

        }
    }
});

//and here is broadcast_receiver code to receive device

broadcastReceiver =new BroadcastReceiver() {
    @Override
    public void onReceive (Context context, Intent intent) {
        final String action = intent.getAction();
        unpaired_list = new ArrayList<>();
        if (action.equals(BluetoothDevice.ACTION_FOUND)) {
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            unpaired_list.add(device);

            Toast.makeText(MainActivity.this, "Showing Unpaired Device", Toast.LENGTH_LONG).show();

            final ArrayAdapter upadapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1);
            unpairlv.setAdapter(upadapter);
        }
    }
};

A: Try  adding as below
upadapter.addAll(unpaired_list);

add it just after creating upadapter in the below line.
final ArrayAdapter upadapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1);

Edited Answer
Declare global variables
ArrayAdapter upadapter;
ArrayList unpaired_list = new ArrayList<>();

Add this in oncreate()
upadapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1);

change the broadcastReceiver onReceive method.
broadcastReceiver =new BroadcastReceiver() {
    @Override
    public void onReceive (Context context, Intent intent) {
        final String action = intent.getAction();
        if (action.equals(BluetoothDevice.ACTION_FOUND)) {
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            unpaired_list.add(device);
            Toast.makeText(MainActivity.this, "Showing Unpaired Device", Toast.LENGTH_LONG).show();
            upadapter.add(device);
            unpairlv.setAdapter(upadapter);
        }
    }
};


text:
Q: Run regression in data.table Please see the fake data set.
library(data.table)
library(MASS)
n=5000
DT = data.table(
      grp=1:n,
      name=as.character(as.hexmode(1:n)),
      x= sample(c(1:400),n,replace = TRUE)
    )

setkey(DT,grp)

UIDlist <- unique(DT[,grp])
IDnamelist <- paste0("V", 1 : length(UIDlist), sep = "")
test <- DT[, (IDnamelist):=lapply(UIDlist,function(x) grp ==x)][, V5000:= NULL]

I have a data.table, in which there're 4 columns, "grp", "Name", "x", "y". And then I add dummy on each level in "grp".
Then I need to run the regression using glm.nb in MASS package.
First I tried this
SumResult <- glm.nb(x ~ factor(uid), data = test)

But when adding dummies, we must notice that when there're N levels in "grp", we add N-1 dummies. So this method is not appropriate as far as I think.
So I tried this:
SumResult <- glm.nb( x ~ V1 + V2 + V3 + V4 + .....+ V4999  , data = test)

It's stupid to write all of the V1, V2, ... V4999 to do the regression.
Is there code can achieve the purpose?
Thanks

A: You can try to create your formula object by string manipulation
formula <- as.formula(paste0("x ~ ", paste(names(test)[-(1:3)], collapse = " + ")))
sumresult <- glm.nb(formula, data = test)

You can also use the more readable code of @BrandonBertelsen
glm.nb(x ~ ., data = test[-c(1:3)])


text:
Q: how to convert a base64 string in to normal image and show it in a web page in react js I'm using fetch to retrieve data from an API, it returns an image in base 64 string format. How can i convert it in to a normal image and show it in a web page using react?

A: Try to use

A: Try to use:

this was the solution that worked for me...

A: I think following information might help you.
So, base64 encoding has encoded binary information into textual data and to decode it back you can use - atob
To show it in a web-page using react - you may consider to use "img" tag itself, as suggested by @tico in comment using data-uri.
In general data uri, let you put your image( and other data) in the form of url.
So, simple steps would be -
1. Fetch the base64 encoded image.
2. Make a data-uri.
3. Load the source into the image tag, using state preferably.
4. And you are done!
Hope this helps.

A: use this below, make sure there is no comma in between them


text:
Q: Will a Fibonacci heap be optimal for my task on hierarchical clustering? I am working on a class project that deals with image segmentation. Given an initial oversegmentation of the image, we are planning to merge pairs together via agglomerative clustering.

*

*We will firstly iterate through clusters and push the pair-wise distance and the ID of these pairs of clusters (used for referencing when updating distance due to a merge operation) into a data structure.

*At each iteration, the pair of clusters with the minimum distance will be merged and the node that stores this distance will be deleted.

*All other nodes that were originally connected to said pair will have their distance recomputed and information updated (i.e. it is now connected to cluster a-b instead of cluster a).
We have been advised to use a Fibonacci heap as it can find the minimum key in O(1). However, because there is still the issue of searching for neighbors and updating their distances, I was wondering if Boost's implementation of Fibonacci heaps allows me to locate a certain node in O(1) if I have a label for each node?
TLDR: I'd like to know if there is a data structure that can efficiently locate nodes and delete min.

A: According to a summary made by John Ahlgren of an SO q&a about performance of std containers :

+------------------+---------------------+---------------------+---------------------+------------------+----------------------+
| Container        | Insertion           | Access              | Erase               | Find             | Persistent Iterators |
+------------------+---------------------+---------------------+---------------------+------------------+----------------------+
| vector / string  | Back: O(1) or O(n)  | O(1)                | Back: O(1)          | Sorted: O(log n) | No                   |
|                  | Other: O(n)         |                     | Other: O(n)         | Other: O(n)      |                      |
+------------------+---------------------+---------------------+---------------------+------------------+----------------------+
| deque            | Back/Front: O(1)    | O(1)                | Back/Front: O(1)    | Sorted: O(log n) | Pointers only        |
|                  | Other: O(n)         |                     | Other: O(n)         | Other: O(n)      |                      |
+------------------+---------------------+---------------------+---------------------+------------------+----------------------+
| list             | Back/Front: O(1)    | Back/Front: O(1)    | Back/Front: O(1)    | O(n)             | Yes                  |
| forward_list     | With iterator: O(1) | With iterator: O(1) | With iterator: O(1) |                  |                      |
|                  | Index: O(n)         | Index: O(n)         | Index: O(n)         |                  |                      |
+------------------+---------------------+---------------------+---------------------+------------------+----------------------+
| set / map        | O(log n)            | N/A                 | O(log n)            | O(log n)         | Yes                  |
+------------------+---------------------+---------------------+---------------------+------------------+----------------------+
| unordered_set    | O(1) or O(n)        | O(1) or O(n)        | O(1) or O(n)        | O(1) or O(n)     | Pointers only        |
| unordered_map    |                     |                     |                     |                  |                      |
+------------------+---------------------+---------------------+---------------------+------------------+----------------------+
| priority_queue   | O(log n)            | O(1)                | O(log n)            | N/A              | N/A                  |
+------------------+---------------------+---------------------+---------------------+------------------+----------------------+


text:
Q: AWS RDS What is the best practice to keep the staging database up to date with production database? Is there any best practice to keep the staging database up to date with the production database?
For example,
every day at midnight, the production database overwrites the staging database.

A: If your goal is to make the Staging database an exact copy of the Production database, then you could:

*

*Take a Snapshot of the Production database

*Delete the Staging database

*Restore a new Staging database from the Snapshot of the Production database

These steps can be automated via a script that calls the AWS Command-Line Interface (CLI). For example, it could use:

*

*aws rds create-db-snapshot

*aws rds delete-db-instance

*aws rds restore-db-instance-from-db-snapshot

A: You can achieve the task as said by @John, but there are a few points which we can not know, such as

*

*the status of the clone

*notification once complete

Below official Blog will help with everything we need to know during every clone.
Blog: Orchestrating database refreshes for Amazon RDS and Amazon Aurora | AWS Database Blog
CloudFormation Git Repo: aws-samples
/
database-refresh-orchestrator-for-amazon-rds-and-amazon-aurora

[Optional] Migrate from RDS to Aurora
Migrating an RDS for MySQL snapshot to Aurora - Amazon Aurora


text:
Q: jsTree: How to expand all nodes on first visualization and then save and restore state with 'cookies' plugin I plan to use jsTree to visualize tree like structures and I would like to achieve the following behavior:

*

*on first time visualization I want to have all nodes expanded

*any consecutive visualizations will restore to the previous state of the tree structure utilizing the "cookies" plugin

Constraints:

*

*I use json objects to populate the tree

*I can't use 'initially_open' attribute to list IDs for the first visualization because it will be hard to determine the initial IDs

In other words I want to achieve something similar to a) change the default state of node to 'open' or b) determine if this is the first visualization (probably by examining the 'cookie' plugin attributes if we don't have state persisted) and if so then call 'open_all'
Ideas are appreciated.
Thanks!

A: To expand all nodes, simply use
$("#treeView").jstree("open_all");

You can include it in the initial load, like so
$('#treeView').jstree(
{
    "themes": {
        "theme": "default",
        "dots": false,
        "icons": false
    },
    "plugins": ["themes", "html_data", "checkbox", "ui"]
}).jstree("set_theme", "apple")
.bind("loaded.jstree", function (event, data) {
    $(this).jstree("open_all");
});

Likewise, if you want to check all elements, use
$(this).jstree("check_all");

Regarding cookies, I haven't used it, but there is a plugin named jquery.cookie.js available. I suppose it contains methods to load/save data from/to a cookie. You have to bind another event, such as
.bind("change_state.jstree", function (evt, data) { ... } );

to capture the state-change and the initial loading in the loaded.jstree event would read from the cookie. Please check out this link to read more about cookie handling, both is mentioned - how you can use it with or without this plugin.
Update: jquery.cookie.js has been superseded by js-cookie, which has the functions Cookies.set('name', 'value'), var cval = Cookies.get('name'); and Cookies.remove('name'); for cookie handling.

The following snippet, which is a modified jsTree example,  has 2 child nodes beneath Root node 2, which expands immediately after the control is loaded:

$(document).ready(function() {
  $('#treeView').jstree({
      'core': {
        'data': [{
            "id": "ajson1",
            "parent": "#",
            "text": "Simple root node"
          },
          {
            "id": "ajson2",
            "parent": "#",
            "text": "Root node 2"
          },
          {
            "id": "ajson3",
            "parent": "ajson2",
            "text": "Child 1"
          },
          {
            "id": "ajson4",
            "parent": "ajson2",
            "text": "Child 2"
          },
        ]
      }
    })
    .bind("loaded.jstree", function(event, data) {
      $(this).jstree("open_all");
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" rel="stylesheet" />

<script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>

<div id="treeView">
</div>

A: Matt's answer is all fine, but as jstree v3 is concerned use the ready.jstree event instead. Long story short:
$('#treeView').jstree(treeOptions)
.bind("ready.jstree", function (event, data) {
     $(this).jstree("open_all");
});

A: $(function () {
    $('#userTree').jstree({
        core: {
            data: [
                { "id": "ajson1", "parent": "#", "text": "Simple root node" },
                { "id": "ajson2", "parent": "#", "text": "Root node 2" },
                { "id": "ajson3", "parent": "ajson2", "text": "Child 1" },
                { "id": "ajson4", "parent": "ajson2", "text": "Child 2" },
            ]
        }
    }).bind('loaded.jstree', function (event, data) {
        $(this).jstree('open_all');
    });
});


text:
Q: Navigate between angular and other routes on express If I open an incognito window and go straight to myurl.com/test I get back Hello this is test as I should. As soon as I visit myurl.com for the first time and my angular page loads, I am never able to return to myurl.com/test, it seems I am trapped in the angular app? When I type in myurl.com/test the screen goes blank and the endpoint on the server is never hit.
server.js
const { mongoose } = require('./database/db');
const express = require('express');
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server);

const path = require('path');

const bodyParser = require('body-parser');
const cors = require('cors');

var userController = require('./controllers/userController');

app.use(cors({ origin: '*' }));

const port = process.env.PORT || 3000;

server.listen(port, () => console.log('Server started at port : ' + port));

app.use(bodyParser.json());

app.use('/api/user', userController);

app.get('/test', (req, res) => {
  console.log('sad face!');
  res.send('Hello this is test');

});

app.use('/', express.static(path.join(__dirname, 'angular')));

I'm not sure if this is helpful but this is the routes form angular, I've tried changing the '' path but that did nothing
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { UserComponent } from './user/user/user.component';
import { OverviewComponent } from './messenger/overview/overview.component';
import { CompanyProfileComponent } from './user/company-profile/company-profile.component';

const routes: Routes = [
  {
    path: '',
    component: UserComponent,
  },
  {
    path: 'company',
    component: CompanyProfileComponent,
  },
  {
    path: 'messenger',
    component: OverviewComponent
  },
  {
    path: 'messenger/:id',
    component: OverviewComponent
  },
  {
    path: 'messenger/archive/:id',
    component: OverviewComponent
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
})
export class AppRoutingModule {}

A: What you going to do with NodeJs server in angular ?.
Routes in angular Hane not rapport with your Server routes.
Try to call you Server.js routes in Call Api in service in Angular.

A: You must build your angular project to get the build file in the ./dist filles. after this you can return the index.html files in your nodeJs Server.

A: First time when you load the application then it hit's node server.js file and your test page is opened successfully , As You are using angular It's a SPA (single page application)/ Javascript running at browser end  and changing of routes in Angular is managed at client side (Browser does it behind the scene without hitting server or just push a state in url). No server interaction needed.
Simple like your node js just start the application once and serve to browser, Rest is angular in browser.
once you are in angular application it will try to resolve every route with it's configuration
if you want to open your page i guess you must try
<a href="htttp://yourdomain/test" > test link </a> -- href it not the way we use routes in angular, though it will reload your website and open test page.


text:
Q: My HTML button is not working, or it wont call my javascript function I am new to coding, and i am trying to make a game in javascript. I don't know why my HTML button is not calling my javascript function. I have tried moving the button to the bottom of the code, I have tried it with different functions, I have looked on some reference sites and i can't figure out why it is not working. Here is my button:

let waveActive = false;
let waveNumber = 0;
let enemyCount = 4;
let enemyAmount = 0;
let enemyHealth = 30;

function newWave() {
  enemyCount + 25 %
    Math.floor(enemyCount);
  enemyHealth + 10 %
    Math.floor(enemyHealth);
}

function startWave() {
  waveNumber + 1;
  waveActive = true;
  newWave()
  class enemySpawn {
    main(Stringargs) {
      int(i = enemyAmount)
      while (i < enemyCount) {
        Enemy = new component(30, 30, "purple", 10, 120);
        enemyAmount + 1;
      }
    }
    enemyAmount = 0;
  }
}

  <button type="button" id="startRoundBtn" onclick=startWave();>Start Round</button>

A: Try to increment your wave number. waveNumber + 1 will not change the property.
waveNumber += 1;

Here too (along with other places):
function newWave() {
  enemyCount = enemyCount + 25 %
    Math.floor(enemyCount);
  enemyHealth = enemyHealth + 10 %
    Math.floor(enemyHealth);
}

The other issue is your class definition inside your click handler.
You probably do not need the main function.  It seems you want something more like this
class EnemySpawn {
  constructor(...args) {
     // do stuff here
  }
}

enemyAmount = 0;  // not sure if you even want to reset this...

while (enemyAmount < enemyCount) {
 const enemy = new EnemySpawn(30, 30, "purple", 10, 120);
 enemyAmount += 1;
}

A: Try it in Script tag in html it should work. Below code is working for me :)

  <button type="button" id="startRoundBtn" onclick="startWave();">
    Start Round
  </button>


text:
Q: D3 / JavaScript load data and return value I do not seem to understand why I cannot return the following values. I want to use custom colors for coloring a bar chart.
function farbe() {
  d3.csv("./Barchart_Farben.csv", function(data) {

    farbdat = new Array;
    for (var i = 0; i < data.length; i++) {
        farbdat.push(data[i].Farbe);
    }
      console.log(farbdat);
      return(farbdat);
  });
  };

console.log(farbe());

Output:

undefined
Array(5) [ "yellow", "violet", "orange", "red", "lightyellow" ]

Nothing gets returned. Why?
// ./Barchart.csv:
// Farbe
// yellow
// violet
// orange
// red
// lightyellow

A: I guess d3.csv function doesn't return anything. Try this.
function farbe() {
  var returnData = [];
  d3.csv("./Barchart_Farben.csv", function(data) {

    farbdat = new Array;
    for (var i = 0; i < data.length; i++) {
      farbdat.push(data[i].Farbe);
    }
    console.log(farbdat);
    returnData = farbdat;
  });
 return returnData;
};

you must check typeof and undefined for input parameter 'data' before looping on it.

A: return is not a function, is a statement. You should write return farbdat instead of return(farbdat).


text:
Q: Ignoring header X-Firebase-Locale because its value was null. (flutter with firebase) enter image description here
**ERROR ---Ignoring header X-Firebase-Locale because its value was null.**

I use the flutter authentication function, firstly user can register after I added that registered email verification function, that function provides a verification email to the relevant email, after verification I can log in successfully,
actually, that functionality worked as well the last couple of weeks, after that break, I started to implement it again occurred that error.
enter code here


text:
Q: How to avoid the drop down menu from resizing its width when clicking on it?
when i click the dropdown menu it is reducing its size.. how to avoid it from resizing?
the dropdown content is set to absolute, as i want to avoid it from pushing the contents below it.

                <input type="text" class="form-control form-control-sm rounded-4" placeholder="Search here.." [(ngModel)]="search"
                (ngModelChange)="this.userQuestionUpdate.next($event)">

                        <button class="btn btn-danger rounded-0 " type="button" *ngIf="searchBox"
                        (click)="search='';clearSearch();">

                        </button>

                    <button class="btn btn-secondary rounded-right hand searc-opt search_new user_search"
                        type="button" pack="eva" (click)="clearMainSearch();searchToggle = !searchToggle">

                    </button>

                        <form [formGroup]="vendorSearchForm" (ngSubmit)="searchBox=true;onSubmit()">

                                            Vendor Code

                                                <input
                                                    class="form-control transparent-field rounded-0 border-top-0 border-left-0 border-right-0"
                                                    type="text" formControlName="vendorCode" placeholder=""
                                                    oninput="this.value = this.value.toUpperCase()"
                                                    [ngClass]="{ 'status-danger': submitted && f.vendorCode.errors }" />

                                            Vendor Name

                                                <input
                                                    class="form-control transparent-field rounded-0 border-top-0 border-left-0 border-right-0"
                                                    type="text" formControlName="vendorName" placeholder=""
                                                    oninput="this.value = this.value.toUpperCase()"
                                                    [ngClass]="{ 'status-danger': submitted && f.vendorName.errors }" />

                                            Approved

                                                <select class="form-control form-control-sm rounded-0 border-top-0 border-left-0 border-right-0"
                                                    placeholder="Choose vendor approved or not" fullWidth
                                                    formControlName="approvedVendor"
                                                    [ngClass]="{ 'status-danger': submitted && f.approvedVendor.errors }">
                                                <option *ngFor="let stat of statuslist" [value]="stat.id" class="drop-bg form-control ">
                                                {{stat.name}}
                                                </option>
                                                </select>

                                            Currency

                                                <ng-autocomplete [data]="currencylist" (selected)="changeSelection($event.name)"
                                                [searchKeyword]="keywordCurrency" placeHolder="Enter Currency name"
                                                [itemTemplate]="currencyTemplate" [notFoundTemplate]="notFoundTemplate"
                                                [initialValue]="currencyName">
                                                </ng-autocomplete>
                                                <ng-template #currencyTemplate let-item>

                                                </ng-template>
                                                <ng-template #notFoundTemplate let-notFound>

                                                </ng-template>

                                            Active

                                                <input type="checkbox" formControlName="status"
                                                    [ngClass]="{ 'is-invalid': submitted && f.status.errors }" status="warning" />

                                            <button type="submit" class="btn btn-sm btn-primary mr-1 search_user_btn"
                                                [disabled]="searchLoader">
                                              Search</button>
                                            <button type="button" class="mr-1 btn-sm btn btn-default cancel_btn_1 btn-danger"
                                                (click)="searchToggle = !searchToggle">
                                            Close</button>
                                            <button type="button" class="btn btn-sm btn-default  reset_user" (click)="clearSearch()">
                                              Reset </button>

                        </form>

        <button type="button" class="btn btn-default border border-right-0  btn-color btn-bg-color theme-btn-icon  btn-sm " style="border-bottom-left-radius: 3px;border-top-left-radius: 3px;border-top-right-radius:0px;border-bottom-right-radius:0px;">

        </button>
        <button type="button" class="btn border btn-default  btn-color btn-bg-color theme-btn-icon btn-sm" style="border-bottom-right-radius: 3px;border-top-right-radius: 3px;border-top-left-radius:0px;border-bottom-left-radius:0px;">

        </button>

             Here is the css code of dropdown content:-
    .dropdown-content {
    position: absolute;
    width: 754px;
    height: 430px;
    z-index: 1;
    left: -738px;
    top: 28px;

A:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>my dropdown</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

  <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Dropdown button
  </button>

    Action
    Another action
    Something else here

  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Incidunt ducimus reprehenderit corporis, totam molestias eum doloremque exercitationem ex, laborum quam rerum, nulla dicta unde. Perferendis praesentium provident quos facere cupiditate unde adipisci recusandae iure cumque, eos impedit veniam eum amet ipsam dolorem culpa nisi reprehenderit, labore perspiciatis. Natus non veritatis dignissimos consequatur, suscipit deleniti quo est totam, earum atque hic aliquam quisquam praesentium consequuntur pariatur tenetur sequi consectetur recusandae, illo laborum dolorem dolore. Laborum ea, dolor mollitia molestias doloremque praesentium corporis obcaecati in illum fuga esse, cumque ad illo a nesciunt impedit ducimus doloribus iste porro quaerat soluta exercitationem accusantium possimus. Iure ipsam doloremque cupiditate animi quo excepturi id dicta ratione porro architecto voluptatibus omnis aliquam repellendus labore quibusdam consectetur nemo velit, magni, voluptatem, rerum ex quia mollitia! Eos minus delectus neque maxime provident, quae dicta natus nemo, nihil, consequatur repellendus, quo aut! Consequuntur fugit, sint commodi maxime asperiores, sapiente omnis voluptas, quasi excepturi iusto officiis harum hic nesciunt nostrum ad. Similique fugiat excepturi esse itaque cupiditate impedit velit assumenda tempore labore, quos, dicta voluptatibus voluptas quae minima necessitatibus. Atque unde vitae dolores impedit consectetur corrupti alias. Voluptates nihil soluta velit vitae eveniet, repudiandae, repellendus laudantium, molestiae cupiditate, mollitia nesciunt unde. Nihil a dolores reiciendis perferendis quod perspiciatis dolore explicabo ex eius eligendi natus sequi soluta nostrum cumque unde facilis possimus repellat, omnis labore esse inventore, distinctio quae voluptates aut! Reiciendis hic distinctio nesciunt atque incidunt non, excepturi molestias quasi, dolore vero accusantium. Dolore distinctio nulla cum amet quia. Quas amet aperiam eaque reprehenderit nemo quasi ipsam repellat odit voluptate ea voluptatem deserunt, iste aliquam odio numquam nobis, laudantium id saepe ad minima. Aliquam quae earum, fugit natus consequuntur incidunt maxime nobis eum

if you want a dropdown that when opens, does not push other contents of site, you can use the bootstrap4 dropdown documentation (https://getbootstrap.com/docs/4.4/components/dropdowns/), like the code that I inserted in your answer, and you don't need any position:absolut.
the other thing that I think is helpful to mention is that when you use a framework like bootstrap that uses classes for width (like col-md-12 , ...) it is better that you avoid using "width" property in your own style sheet.


text:
Q: Meaning of the term "Sledgehammer" I know a Sledgehammer is a special type of hammer, but I still do not quite get the exact meaning of the word in such a paragraphs as:

The computational sledgehammer par excellence is the spectral sequence; these are essential in the Cartan-Eilenberg and Tohoku approaches where they are needed, for instance, to compute the derived functors of a composition of two functors. Spectral sequences are less essential in the derived category approach, but still play a role whenever concrete computations are necessary.

Does it mean something like the key to decipher a problem, to facilitate or easy up computation, or does it mean something like the nemesis in this context, a fatal flaw which makes everything crash?

A: A sledgehammer is not just a special hammer, but a very large and heavy hammer.  Normally one uses it for demolition, to break big things.  You wouldn't want to use it to drive a nail, much less a small nail.


text:
Q: Carousel-caption is not showing in full width header carousel Using full width header carousel with captions it is showing images but not captions. trying to find out since morning but unable.
please check jsfiddle
html,
body {
height: 100%;
}

/* You can change the height of the carousel by changing the height in the class below. It is set to 50% by default, but can be any height! */

.carousel {
height: 70%;
 }

.item,
.active,
 .carousel-inner {
height: 100%;
 }

/* Background images are set within the HTML using inline CSS, not here */

.fill {
width: 100%;
height: 100%;
background-position: center;
-webkit-background-size: cover;
-moz-background-size: cover;
background-size: cover;
-o-background-size: cover;
}

  .carousel .item,
  .carousel .item.active,
 .carousel-caption h2 {
  font-family:Arial;
  font-size:60px;
  text-align:center;
 z-index:10;
  }

.carousel-caption .btn-default-outline {
font-family:Century Gothic;
background:none;
border: 4px solid #fff;
color:#fff;
padding: 15px 25px;
 }

.carousel-caption .btn-default-outline:hover {
background-color:#fff;
color:#000000;
}

  footer {
  margin: 50px 0;
}

it is not showing carousel caption.
Any one can figure out what is missing or i m doing wrong.
Thanks

A: You might kick yourself when you realize the simplicity of this issue...
this character " is wrong for the style attribute in your code and has malformed your HTML.
its starts on this line:

The closing quote is wrong and should be normal quotation mark ".
Its a very subtle difference but can cause a lot of issues. It might be a good idea to check all the quotes!

A: Your inline-css is blocking the code below that to run. Simply put the inline-css of the three containers to css file.
See the fiddle
s1 {
background-image:url('http://upload.wikimedia.org/wikipedia/commons/archive/0/07/20060606172916%21UCT_Upper_Campus_landscape_view.jpg');

}
http://jsfiddle.net/coxuLkn6/4/


text:
Q: Pasar valor de un arreglo php a jquery primero que nada me disculpo si esta duplicado el tema o no me doy a entender correctamente
tengo el siguiente codigo en php
<?php
$qry_res=mysqli_query($link,"SELECT * FROM animalestipo");
$j=0;
while ($rowres=mysqli_fetch_array($qry_res)) {
    $elementos[$j]=$rowres['Nombre'];
}?>

y quiero recibirlo en otra pagina js con el siguiente codigo
 var i = 0;
var arreglo = new Array();

$(document).ready(function(){
    $("#mas").click(function(){
        i++
        var j = $("#j").val();
        for (var k =1; k < j; k++) {
            arreglo[k] = $("#elementos[k]").val();
            console.log(arreglo[k]);
        }
        agregar(i);
    });
});

lo que quiero es en la pagina js obtener los valores del arreglo guardado en la pagina php
alguna idea?? Me disculpo de antemano por los errores pues soy nuevo y quizas no es el mejor metodo

A: si la estoy haciendo a mano a la pagina y tengo algo como el siguiente esquema
lista.php (esta envia la consulta y lo que recibe lo muestra en un select y un boton para agregar una nueva fila que llama a rellena.js)
rellena.js (aqui utilizo ajax para enviar datos a rellenatabla.php y la respuesta la devuelvo a lista.php) tengo el siguiente codigo en pagina.js
function agregar(consulta){
    $.ajax({
        url:'includes/rellenatabla.php',
        type:'POST',
        dataType:'html',
        data:{consulta: consulta},
        })
    .done(function (respuesta) {
        $("#tabla tbody").append(respuesta);
    })
    .fail(function() {
        console.log('Failed');
    })
}
var i = 1;

$(document).ready(function(){
    $("#mas").click(function(){
        i++;
        agregar(i);
    });
});

el tema es que en la pagina rellenatabla.php tengo que volver a hacer la consulta para hacer el select dinamico para luego pasarlo a lista.php
lo que quiero evitar es que cada que apreto el boton agregar nuevo select en lista.php se realice la consulta en rellenatabla.php
espero haberme explicado bien


text:
Q: Alterar parte de pattern ou regex javascript dinamicamente Estou fazendo uma requisição ajax que vai me devolver uma página "X". Meu objetivo é cortar a página e manipular o outerHTML para retornar apenas as
 que correspondem a um pattern/regex específico.
var xmlhttp = new XMLHttpRequest();

xmlhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    var body = this.responseXML.body.outerHTML;
    var main = body.slice(body.indexOf("<main"), body.indexOf(""));
    var regex = /
]*>(?:(?!<|AQUI)[\s\S])*(?:<(?!\/?tr)[^>]*>(?:(?!<|AQUI)[\s\S])*)*AQUI[\s\S]*?<\/tr>/gi;

    if(regex.test(main)) {
      var matches = main.match(regex);
      $('#resposta').html('
Os ramais relacionados à ' + setor + ' são:');
      for(i = 0; i < matches.length; i++){
        $('#resposta').append(matches[i]);
        $('#resposta').append('
Para mais detalhes acesse os Ramais do TJPB
');
      }
    } else {
      $('#resposta').html('Nenhuma combinação encontrada');
    }
  }
};

xmlhttp.open("GET",url, true);
xmlhttp.responseType = "document";
xmlhttp.send();

O Pattern está funcionando perfeitamente, só que está estático. A questão é que não estou conseguindo manipular ele, alterá-lo:
/
]*>(?:(?!<|AQUI)[\s\S])*(?:<(?!\/?tr)[^>]*>(?:(?!<|AQUI)[\s\S])*)*AQUI[\s\S]*?<\/tr>/gi

Onde tem AQUI gostaria de mudar o valor dinamicamente de acordo com um parâmetro. Vamos supor que eu precise mudar para "abcd" ou "efgh", por exemplo.
ps. a variável url é populada anteriormente e retorna a url da página

A: Para registro. Consegui resolver da seguinte forma:

*

*Deixei o pattern como string

*Criei uma variável com um novo pattern para o replace dinâmico

*Executei um replace de string passando o valor dinâmico em val

*E o resto ficou praticamente da mesma forma

O Importante é ficar atento que tratando o pattern como string vc precisa fazer o escape das "" usando "\". E a regra final \gmi é inserida no new RegExp.
var pattern = '
]*>(?:(?!<|CODE)[\\s\\S])*(?:<(?!\\/?tr)[^>]*>(?:(?!<|CODE)[\\s\\S])*)*CODE[\\s\\S]*?<\\/tr>';
var rgxreplace = /CODE/gmi;
pattern = pattern.replace(rgxreplace,val);
var newRegex = new RegExp(pattern,'gmi');


text:
Q: How to prefill date in google form I'm trying to pre fill the date in google form. so It will put the date of the day it filled as default.
I tried using the TODAY() function in google sheets . so i change the url to get the date from cell in google sheets . works for everything except the Date..
https://docs.google.com/forms/d/e/1FAIpQLSf7cdT34eHp-GXagq3DsnxX1MD_c-G6lbF6yFWOMnUvtPYUUQ/viewform?entry.178275308=**&A6&**

Any idea how can i do it in the simplest way?

A: Deploy your script as a Web App

*

*Publish your Apps Script as a Web App and provide the URL of the web deployment to the users

*Write your code inside a doGet() function, so it gets evaluated every time a user open the link

*Get the current date with new Date() and pass it as an itemResponse to a prefilled Form

*Create a redirection to the URL to the prefilled form with the Java Script method window.top.location.href inside of <script> </script> tags and return it with HtmlService
// will be automatically run every time the user opens the URL of the web deployment
function doGet(){
  //open your form
  var form = FormApp.openById('1Zs5Wo0wS9esNkcq8ztOZmQs3f5NrO7hgJ_0fYk262z4');
  //get the questions
  var questions = form.getItems();
  //get the question where you want to prefill the date as an answer, e.g. first question
  var question1=questions[0];
  //get the current date
  var time=Utilities.formatDate(new Date(), "GMT+2", "dd-MM-yyyy");
  // prefill form with current date
  var prefilledTime=form.createResponse().withItemResponse(question1.asTextItem().createResponse(time));
 // Get the link to the prefilled form
  var URL=prefilledTime.toPrefilledUrl();
 // redirect to the prefilled form URL dynamically created above
  return HtmlService.createHtmlOutput("<script>window.top.location.href=\"" + URL + "\";</script>");
}

A: If you just want the date the Form is submitted, Google Forms provides this automatically in it's Timestamp.
If you want to pre-fill a date from an existing spreadsheet, then provided you obey Google's date-format, you can use the URL approach (months & days must be 2 digits i.e. "01" not "1").
=substitute('Sheet_with_Form_Link'!$A$1,"2099-01-01",text(Sheet_with_date!A1,"yyyy-mm-dd"))

WhereSheet_with_Form_Link'!$A$1 is a cell in a Sheet in a Google SpreadSheet containing the URL obtained via 'Get Prefilled Link'
"2099-01-01" is the data you Pre-filled into the Form whilst using 'Get Pre-filled Link'
Sheet_with_date!A1 is a cell in a Sheet in a Google SpreadSheet containing your desired date e.g. one of
=today()
1920/03/26
17Oct2002

A: I took the code from ziganotschka as base, but I had to make some changes, maybe it helps somebody:
function doGet(){
  //open your form open by URL
  var form = FormApp.openByUrl('https://docs.google.com/forms/d/1M-zgHyDOz2ob5StkwIoDCShJ9tePw-I5TGhdx/prefill')
  //get the questions
  var questions = form.getItems();
  //get the question where you want to prefill the date as an answer, e.g. first question
  var question1=questions[0];
  //get the current date
  var time=new Date();
  // prefill form with current date
  var prefilledTime=form.createResponse().withItemResponse(question1.asDateItem().createResponse(time));
  // Get the link to the prefilled form
  var URL=prefilledTime.toPrefilledUrl();
  // redirect to the prefilled form URL dynamically created above
  return HtmlService.createHtmlOutput("<script>window.top.location.href=\"" + URL + "\";</script>");
}

And when you're done, don't forget to Publish ->  Deploy as a Web App...