text:
Q: Finding Median WITHOUT Data Structures (my code is written in Java but the question is agnostic; I'm just looking for an algorithm idea)
So here's the problem: I made a method that simply finds the median of a data set (given in the form of an array). Here's the implementation:
public static double getMedian(int[] numset) {
    ArrayList<Integer> anumset = new ArrayList<Integer>();
    for(int num : numset) {
        anumset.add(num);
    }
    anumset.sort(null);

    if(anumset.size() % 2 == 0) {
        return anumset.get(anumset.size() / 2);
    } else {
        return (anumset.get(anumset.size() / 2)
                   + anumset.get((anumset.size() / 2) + 1)) / 2;
    }
}

A teacher in the school that I go to then challenged me to write a method to find the median again, but without using any data structures. This includes anything that can hold more than one value, so that includes Strings, any forms of arrays, etc. I spent a long while trying to even conceive of an idea, and I was stumped. Any ideas?

A: The usual algorithm for the task is Hoare's Select algorithm. This is pretty much like a quicksort, except that in quicksort you recursively sort both halves after partitioning, but for select you only do a recursive call in the partition that contains the item of interest.
For example, let's consider an input like this in which we're going to find the fourth element:
[ 7, 1, 17, 21, 3, 12, 0, 5 ]
We'll arbitrarily use the first element (7) as our pivot. We initially split it like (with the pivot marked with a *:
[ 1, 3, 0, 5, ] *7, [ 17, 21, 12]
We're looking for the fourth element, and 7 is the fifth element, so we then partition (only) the left side. We'll again use the first element as our pivot, giving (using { and } to mark the part of the input we're now just ignoring).
[ 0 ] 1 [ 3, 5 ]  { 7, 17, 21, 12 }
1 has ended up as the second element, so we need to partition the items to its right (3 and 5):
{0, 1} 3 [5] {7, 17, 21, 12}
Using 3 as the pivot element, we end up with nothing to the left, and 5 to the right. 3 is the third element, so we need to look to its right. That's only one element, so that (5) is our median.
By ignoring the unused side, this reduces the complexity from O(n log n) for sorting to only O(N) [though I'm abusing the notation a bit--in this case we're dealing with expected behavior, not worst case, as big-O normally does].
There's also a median of medians algorithm if you want to assure good behavior (at the expense of being somewhat slower on average).
This gives guaranteed O(N) complexity.

A: Sort the array in place. Take the element in the middle of the array as you're already doing. No additional storage needed.
That'll take n log n time or so in Java. Best possible time is linear (you've got to inspect every element at least once to ensure you get the right answer). For pedagogical purposes, the additional complexity reduction isn't worthwhile.
If you can't modify the array in place, you have to trade significant additional time complexity to avoid avoid using additional storage proportional to half the input's size. (If you're willing to accept approximations, that's not the case.)

A: Some not very efficient ideas:
For each value in the array, make a pass through the array counting the number of values lower than the current value.  If that count is "half" the length of the array, you have the median.  O(n^2)  (Requires some thought to figure out how to handle duplicates of the median value.)
You can improve the performance somewhat by keeping track of the min and max values so far.  For example, if you've already determined that 50 is too high to be the median, then you can skip the counting pass through the array for every value that's greater than or equal to 50.  Similarly, if you've already determined that 25 is too low, you can skip the counting pass for every value that's less than or equal to 25.
In C++:
    int Median(const std::vector<int> &values) {
        assert(!values.empty());
        const std::size_t half = values.size() / 2;
        int min = *std::min_element(values.begin(), values.end());
        int max = *std::max_element(values.begin(), values.end());
        for (auto candidate : values) {
            if (min <= candidate && candidate <= max) {
                const std::size_t count =
                    std::count_if(values.begin(), values.end(), [&](int x)
                                    { return x < candidate; });
                if (count == half)     return candidate;
                else if (count > half) max = candidate;
                else                   min = candidate;
            }
        }
        return min + (max - min) / 2;
    }

Terrible performance, but it uses no data structures and does not modify the input array.


text:
Q: How can I handle deep links in jetpack compose when logged out I have an app where the user can be logged in or logged out and there are some screens which are only available in loggedInState which are accessed through deep links.
If the user is logged out and opens the app through a deeplink he should be directed to the login screen - login - and then be directed to the deeplink.
I can get this to work if the login screen is not a part of the navHost
if (!loggedIn) {
  LoginScreen(loginViewModel = hiltViewModel() )
} else {
  AppNavHost()
}

The problem in this case is that the Activity somehow gets recreated (I think because navController.handleDeepLink(intent) is being called) and the splashScreen (on phones < Android 12) is being showed twice - when opening the app and after success login.
So then I tried making LoginScreen a composable destination in AppNavHost - which removed the double splash screen - but now the deeplink is processed before the user is logged in.

redpajama_set_name: RedPajamaStackExchange


text:
Q: dojo newbie read json response from web service i have a webservice that is returning this response :
<string xmlns="http://tempuri.org/">{ "Head":[ { "ID":"1","Name":"David"} ]}</string>

when i try to get the response back, i keep getting the error :
"missing ; before statement"
i am just starting to get into this so am probably doing something very wrong.
why is the response not working for me?
my dojo code looks like this
    var targetNode = document.getElementById("foo");

    var def = dojo.io.script.get({
        url: "http://localhost/WebData/PublicData.asmx/HelloWorld",
        timeout: 30000,
        handleAs: "json",
        preventCache: true,
        handle: function(error, ioargs) {
            var message = "";
            switch (ioargs.xhr.status) {
                case 200:
                    message = "Good request.";
                    break;
                case 404:
                    message = "The requested page was not found";
                    break;
                case 500:
                    message = "The server reported an error.";
                    break;
                case 407:
                    message = "You need to authenticate with a proxy.";
                    break;
                default:
                    message = "Unknown error.";
            }
            targetNode.innerHTML = message;
        }
    });

thanks!
david

A: Your server's response mixes XML-like data (<string xmlns="http://tempuri.org/">)with JSON.
For dojo to handle the response using handleAs: 'json' you will need your server to return pure JSON data only, i.e just
{ "Head":[ { "ID":"1","Name":"David"} ]}

Failing that you would need to handle the response as text, strip out the tags and then parse just the JSON content. As a general tip "missing ; before statement" usually means mal-formed JSON.
EDIT
I just noticed the first argument to your handle function is "error". The first argument to the handle function contains the server's response (In this case a javascript object based on the JSON received.).


text:
Q: Add a property to an array based on object at the same index in a different array using Ramda I have an array for example
const array = [
  {
    "id": 1
  },
  {
    "id": 2
  }
]

I want to add a new property to that based on the value at the same index in array2 using Ramda.
const array2 = [
  {
    0: 'Test'
  },
  {
    1: 'Test2'
  }
]

I want the output to be:
const result = [
  {
    "id": 1,
    "name": 'Test'
  },
  {
    "id": 2,
    "name": 'Test2'
  }
]

I have got to something like this so far but not sure how I map the value.
const fn = R.map(R.assoc('name', value??));

const result = fn(array1);

A: You can make use of R.zipWith to combine the elements at each index together from two lists using a function to determine how they're combined.
This lets you make use of R.assoc as you had suggested to combine the two.
It will also make things simpler if you extract the value you are interested in out of the object from your array2 elements. Without assuming much beyond what you've shared here, you can make use of R.map wrapped with R.addIndex to provide the index when mapping over the array to extract the value associated with each index.
Combining all of this together:
const fn = (array, array2) => zipWith(
  assoc('name'),
  addIndex(map)((x, i) => x[i], array2),
  array,
)


text:
Q: PyTorch : GPU execution time I am following different tutorials on PyTorch. And I'm trying to use GPU speed but I am encountering a problem between the execution time announced on the web site and my reality!
https://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html
You can find here the code at the end of the page, and we can read that the program finished in 1min30 against 6/7min on my computer! Can you try it and tell me how many time have you got please! I am very confuse to see a high difference using the same file code than the web site!
This will allow me to understand if the problem comes from my GPU or not :)
My config :
GTX 1080Ti
Windows10
Cuda 9.1
Pytorch 0.4.0
The code:
if __name__ == "__main__":

    plt.ion()   # interactive mode

    ######################################################################
    # Load Data
    # ---------
    #
    # We will use torchvision and torch.utils.data packages for loading the
    # data.
    #
    # The problem we're going to solve today is to train a model to classify
    # **ants** and **bees**. We have about 120 training images each for ants and bees.
    # There are 75 validation images for each class. Usually, this is a very
    # small dataset to generalize upon, if trained from scratch. Since we
    # are using transfer learning, we should be able to generalize reasonably
    # well.
    #
    # This dataset is a very small subset of imagenet.
    #
    # .. Note ::
    #    Download the data from
    #    `here <https://download.pytorch.org/tutorial/hymenoptera_data.zip>`_
    #    and extract it to the current directory.

    # Data augmentation and normalization for training
    # Just normalization for validation
    data_transforms = {
        'train': transforms.Compose([
            transforms.RandomResizedCrop(224),
            transforms.RandomHorizontalFlip(),
            transforms.ToTensor(),
            transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
        ]),
        'val': transforms.Compose([
            transforms.Resize(256),
            transforms.CenterCrop(224),
            transforms.ToTensor(),
            transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
        ]),
    }

    data_dir = 'hymenoptera_data'
    image_datasets = {x: datasets.ImageFolder(os.path.join(data_dir, x),
                                              data_transforms[x])
                      for x in ['train', 'val']}
    dataloaders = {x: torch.utils.data.DataLoader(image_datasets[x], batch_size=4,
                                                 shuffle=True, num_workers=4)
                  for x in ['train', 'val']}
    dataset_sizes = {x: len(image_datasets[x]) for x in ['train', 'val']}
    class_names = image_datasets['train'].classes

    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

    ######################################################################
    # Visualize a few images
    # ^^^^^^^^^^^^^^^^^^^^^^
    # Let's visualize a few training images so as to understand the data
    # augmentations.

    def imshow(inp, title=None):
        """Imshow for Tensor."""
        inp = inp.numpy().transpose((1, 2, 0))
        mean = np.array([0.485, 0.456, 0.406])
        std = np.array([0.229, 0.224, 0.225])
        inp = std * inp + mean
        inp = np.clip(inp, 0, 1)
        plt.imshow(inp)
        if title is not None:
            plt.title(title)
        plt.pause(0.001)  # pause a bit so that plots are updated

    # Get a batch of training data
    inputs, classes = next(iter(dataloaders['train']))

    # Make a grid from batch
    out = torchvision.utils.make_grid(inputs)

    imshow(out, title=[class_names[x] for x in classes])

    ######################################################################
    # Training the model
    # ------------------
    #
    # Now, let's write a general function to train a model. Here, we will
    # illustrate:
    #
    # -  Scheduling the learning rate
    # -  Saving the best model
    #
    # In the following, parameter ``scheduler`` is an LR scheduler object from
    # ``torch.optim.lr_scheduler``.

    def train_model(model, criterion, optimizer, scheduler, num_epochs=25):
        since = time.time()

        best_model_wts = copy.deepcopy(model.state_dict())
        best_acc = 0.0

        for epoch in range(num_epochs):
            print('Epoch {}/{}'.format(epoch, num_epochs - 1))
            print('-' * 10)

            # Each epoch has a training and validation phase
            for phase in ['train', 'val']:
                if phase == 'train':
                    scheduler.step()
                    model.train()  # Set model to training mode
                else:
                    model.eval()   # Set model to evaluate mode

                running_loss = 0.0
                running_corrects = 0

                # Iterate over data.
                for inputs, labels in dataloaders[phase]:
                    inputs = inputs.to(device)
                    labels = labels.to(device)

                    # zero the parameter gradients
                    optimizer.zero_grad()

                    # forward
                    # track history if only in train
                    with torch.set_grad_enabled(phase == 'train'):
                        outputs = model(inputs)
                        _, preds = torch.max(outputs, 1)
                        loss = criterion(outputs, labels)

                        # backward + optimize only if in training phase
                        if phase == 'train':
                            loss.backward()
                            optimizer.step()

                    # statistics
                    running_loss += loss.item() * inputs.size(0)
                    running_corrects += torch.sum(preds == labels.data)

                epoch_loss = running_loss / dataset_sizes[phase]
                epoch_acc = running_corrects.double() / dataset_sizes[phase]

                print('{} Loss: {:.4f} Acc: {:.4f}'.format(
                    phase, epoch_loss, epoch_acc))

                # deep copy the model
                if phase == 'val' and epoch_acc > best_acc:
                    best_acc = epoch_acc
                    best_model_wts = copy.deepcopy(model.state_dict())

            print()

        time_elapsed = time.time() - since
        print('Training complete in {:.0f}m {:.0f}s'.format(
            time_elapsed // 60, time_elapsed % 60))
        print('Best val Acc: {:4f}'.format(best_acc))

        # load best model weights
        model.load_state_dict(best_model_wts)
        return model

    ######################################################################
    # Visualizing the model predictions
    # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    #
    # Generic function to display predictions for a few images
    #

    def visualize_model(model, num_images=6):
        was_training = model.training
        model.eval()
        images_so_far = 0
        fig = plt.figure()

        with torch.no_grad():
            for i, (inputs, labels) in enumerate(dataloaders['val']):
                inputs = inputs.to(device)
                labels = labels.to(device)

                outputs = model(inputs)
                _, preds = torch.max(outputs, 1)

                for j in range(inputs.size()[0]):
                    images_so_far += 1
                    ax = plt.subplot(num_images//2, 2, images_so_far)
                    ax.axis('off')
                    ax.set_title('predicted: {}'.format(class_names[preds[j]]))
                    imshow(inputs.cpu().data[j])

                    if images_so_far == num_images:
                        model.train(mode=was_training)
                        return
            model.train(mode=was_training)

    ######################################################################
    # Finetuning the convnet
    # ----------------------
    #
    # Load a pretrained model and reset final fully connected layer.
    #

    model_ft = models.resnet18(pretrained=True)
    num_ftrs = model_ft.fc.in_features
    model_ft.fc = nn.Linear(num_ftrs, 2)

    model_ft = model_ft.to(device)

    criterion = nn.CrossEntropyLoss()

    # Observe that all parameters are being optimized
    optimizer_ft = optim.SGD(model_ft.parameters(), lr=0.001, momentum=0.9)

    # Decay LR by a factor of 0.1 every 7 epochs
    exp_lr_scheduler = lr_scheduler.StepLR(optimizer_ft, step_size=7, gamma=0.1)

    ######################################################################
    # Train and evaluate
    # ^^^^^^^^^^^^^^^^^^
    #
    # It should take around 15-25 min on CPU. On GPU though, it takes less than a
    # minute.
    #

    model_ft = train_model(model_ft, criterion, optimizer_ft, exp_lr_scheduler,
                           num_epochs=25)

    ######################################################################
    #

    visualize_model(model_ft)

    ######################################################################
    # ConvNet as fixed feature extractor
    # ----------------------------------
    #
    # Here, we need to freeze all the network except the final layer. We need
    # to set ``requires_grad == False`` to freeze the parameters so that the
    # gradients are not computed in ``backward()``.
    #
    # You can read more about this in the documentation
    # `here <http://pytorch.org/docs/notes/autograd.html#excluding-subgraphs-from-backward>`__.
    #

    model_conv = torchvision.models.resnet18(pretrained=True)
    for param in model_conv.parameters():
        param.requires_grad = False

    # Parameters of newly constructed modules have requires_grad=True by default
    num_ftrs = model_conv.fc.in_features
    model_conv.fc = nn.Linear(num_ftrs, 2)

    model_conv = model_conv.to(device)

    criterion = nn.CrossEntropyLoss()

    # Observe that only parameters of final layer are being optimized as
    # opoosed to before.
    optimizer_conv = optim.SGD(model_conv.fc.parameters(), lr=0.001, momentum=0.9)

    # Decay LR by a factor of 0.1 every 7 epochs
    exp_lr_scheduler = lr_scheduler.StepLR(optimizer_conv, step_size=7, gamma=0.1)

    ######################################################################
    # Train and evaluate
    # ^^^^^^^^^^^^^^^^^^
    #
    # On CPU this will take about half the time compared to previous scenario.
    # This is expected as gradients don't need to be computed for most of the
    # network. However, forward does need to be computed.
    #

    model_conv = train_model(model_conv, criterion, optimizer_conv,
                             exp_lr_scheduler, num_epochs=25)

    ######################################################################
    #

    visualize_model(model_conv)

    plt.ioff()
    plt.show()

Thanks every body!

A: A bit late I know, but it might be that you are missing
model.to(cuda)


text:
Q: jquery mobile. add class when tapping button Hi i'm making hybrid app with JQM.
I want to add class when i am pressing or tapping(Holding) the button .
Here is my codes...
button

CSS
.btnWhite { background:gray }
.btnWhite.on { background:black }

jQuery Mobile
$('.btnWhite').bind('touchstart', function() {
 $(this).addClass("on");
});

$('.btnWhite').bind('touchend', function() {
 $(this).removeClass("on");
});

A: Working example: http://jsfiddle.net/Gajotres/LvhdG/
In this example I have used vmousedown, vmouseup and vmousecancel events so I can test it on desktop / mobile devices alike. Just replace them with touchstart, touchend and touchcancel if you want, but it will also work with vmouse events.
HTML :
<!DOCTYPE html>

        <title>jQM Complex Demo</title>
        <meta http-equiv='Content-Type' content='text/html; charset=utf-8'/>
        <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; minimum-scale=1.0; user-scalable=no; target-densityDpi=device-dpi"/>
        <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.css" />

Index page

                button

Javascript :
$(document).on('pagebeforeshow', '#index', function(){
    $(document).on('vmousedown','.btnWhite' ,function(){
        $(".btnWhite").addClass('on');
    }).on('vmouseup', function(){
        $(".btnWhite").removeClass('on');
    }).on("vmousecancel", function() {
        $(".btnWhite").removeClass('on');
     });
});

CSS :
.btnWhite {
    background:gray !important;
}
.on {
    background:black !important;
}


text:
Q: Why do certain characters need to be escaped in this Elixir regular expression? My ultimate goal is to write a function in JavaScript which will escape all regex metacharacters in Erlang. Because I want to construct a Mango $regex query for CouchDB 2 via my HTML5 application using PouchDB and pouchdb-find. I want to perform a search for a substring in a field on the objects in my database, without going to the trouble of setting up couchdb-lucene if I can help it and if that tool isn't needed.
In writing this escaping function, I found that Elixir has already written one.
{:ok, pattern} = :re.compile(~S"[.^$*+?()\[\]{}\\\|\s#-]", [:unicode])
@escape_pattern pattern

@spec escape(String.t) :: String.t
def escape(string) when is_binary(string) do
  :re.replace(string, @escape_pattern, "\\\\&", [:global, {:return, :binary}])
end

I am trying to figure out how to translate this expression to JavaScript, and in that process, I am trying to understand Elixir's and Erlang's regular expression syntax, which I understand to be based off PCRE.
Escaping the [ and ] characters makes enough sense, since they are inside a bracketed expression themselves. As does \, since it's an escape character.
But why are \| and \s being escaped?

A: As Lucas Trzesniewski and Dogbert have deduced in the comments, \| does not need to be escaped, and \s is escaped because if the Regex has the x flag, any unescaped whitespace is ignored, so escaping the space will always have a valid regex not dependent on whether the x flag is present or not: {"a b" =~ ~r/a b/, "a b" =~ ~r/a b/x, "a b" =~ ~r/a\ b/x} #=> {true, false, true}
Here's the escaping function I ended up with:
function escapeRegex (string) {
  return string.replace(/([.^$*+?()\[\]{}\\\s#-])/g, '\\$&');
}


text:
Q: How do I install NPM in a specific directory? I know there is a duplicate here. But no matter how many variation I try, I keep getting a error message:
Error: ENOENT, stat 'd:\wamp\www\test\js\
I've tried:
npm install --prefix video.js ./wamp/www/test/js
npm install --prefix video.js ./wamp/www/test/js -g
npm install video.js ./wamp/www/test/js/video.js
npm install --localapp video.js ./wamp/www/test/js
npm install video.js D:\wamp\www\test\js -g
npm install --prefix video.js D:\wamp\www\test\js

What is the right syntax for installing video.js?
Running npm install --prefix video.js ./wamp/www/test/js creates the following error log:
0 info it worked if it ends with ok
1 verbose cli [ 'E:\\Programs\\nodejs\\\\node.exe',
1 verbose cli   'E:\\Programs\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'install',
1 verbose cli   '--prefix',
1 verbose cli   'video.js',
1 verbose cli   './wamp/test/js' ]
2 info using npm@1.4.28
3 info using node@v0.10.33
4 verbose node symlink E:\Programs\nodejs\\node.exe
5 verbose cache add [ './wamp/test/js', null ]
6 verbose cache add name=undefined spec="./wamp/test/js" args=["./wamp/test/js",null]
7 verbose parsed url { protocol: null,
7 verbose parsed url   slashes: null,
7 verbose parsed url   auth: null,
7 verbose parsed url   host: null,
7 verbose parsed url   port: null,
7 verbose parsed url   hostname: null,
7 verbose parsed url   hash: null,
7 verbose parsed url   search: null,
7 verbose parsed url   query: null,
7 verbose parsed url   pathname: './wamp/test/js',
7 verbose parsed url   path: './wamp/test/js',
7 verbose parsed url   href: './wamp/test/js' }
8 silly lockFile 16638d03-wamp-test-js ./wamp/test/js
9 verbose lock ./wamp/test/js C:\Users\steven\AppData\Roaming\npm-cache\16638d03-wamp-test-js.lock
10 silly lockFile 16638d03-wamp-test-js ./wamp/test/js
11 silly lockFile 16638d03-wamp-test-js ./wamp/test/js
12 error addLocal Could not install ./wamp/test/js
13 error Error: ENOENT, stat 'D:\wamp\www\test\js\wamp\test\js'
14 error If you need help, you may report this *entire* log,
14 error including the npm and node versions, at:
14 error     <http://github.com/npm/npm/issues>
15 error System Windows_NT 6.1.7601
16 error command "E:\\Programs\\nodejs\\\\node.exe" "E:\\Programs\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "--prefix" "video.js" "./wamp/test/js"
17 error cwd D:\wamp\www\test\js
18 error node -v v0.10.33
19 error npm -v 1.4.28
20 error path D:\wamp\www\test\js\wamp\test\js
21 error code ENOENT
22 error errno 34
23 verbose exit [ 34, true ]

A: I think you are mixing relative and absolute paths. You logfile shows this:
...
error Error: ENOENT, stat 'D:\wamp\www\test\js\wamp\test\js'
...

This causes the path you want to be used twice.
Either you need to give an absolute path:
npm install --prefix video.js d:/wamp/www/test/js

or keep it relative:
npm install --prefix video.js ./


text:
Q: Whether to stop windows service depending on precondition? Assume we are creating windows service WS. WS depends on some network infrastructure(3rd party product). This infrastructure is a precondition of WS work. WS can't do its work without this infrastructure. Assume that WS is configured to start automatically. What WS should do in case infrastructure is not accessible? Should it stop execution? This infrastructure is another services. Those services can become available. In simple case Admin can start needed infrastructure and try to start manually WS again.But if WS runs on Grid of several hundreds of nodes it would be great if local OS will try to start WS in some intervals. We can try to use "Recovery" feature of Windows services. Assume that starting phase of WS is lightweight and it's easy to check precondition. So, we can configure "Recovery" feature to try to start WS continually each say 5 minutes. But "Recovery" feature is used by SCM only if service didn't stop voluntarily by its own free will. So, is it good form of using Windows services to use fast fail (fatal) way to stop service so OS will try to restart it with help of "Recovery" feature? Or is there another good practices (or patterns) to achieve the same goal - automatically try to start WS hoping some other network infrastructure becomes available?
Updated: to narrow the scope of question: this one is about whether to stop starting of service and use Recovery feature or start and poll the availability of services WS depends on. that is simple question: to be or not to be.


text:
Q: Добавить windows в grub2 Пришлось мне поставить после Windows Ubuntu 18.04. у меня пропала Windows из grub. Я с помощью "Восстановление загрузки" вернул граб в Корень /dev/sda. Дальше с помощью grub customize добавил винду. Выводит вот такую ошибку.
enuentry "Windows 8" {
insmod part_gpt
insmod chain set root='(hd0,gpt2)'
chainloader /EFI/microsoft/BOOT/bootmgfw.efi
}

Помогите создать правильную настройку. Windows располагается в /dev/sda2 (Диск C).

A: В большинстве случаев ручная правка конфига grub2 (grub.cfg) избыточна и контрпродуктивна — этот файл генерируется специальным скриптом. Также этот же скрипт запускается автомачиске, например при обновлении ядра. В числе прочего этот скрипт находит установленные ОС с помощью утилиты os-prober.
Конкретное имя и как запускать скрипт меняется от дистрибутива к дистрибутиву, но практически всегда разработчики оставляют подсказку в шапке файла /etc/default/grub, например на debian:

# If you change this file, run 'update-grub' afterwards to update
  # /boot/grub/grub.cfg.
  # For full documentation of the options in this file, see:
  #   info -f grub -n 'Simple configuration'

Таким образом, при запуске update-grub (от root'а само собой) должен сам найти все установленные ОС и win в том числе.


text:
Q: Pipenv install from Pipfile fails but works from command line I have been happily using pipenv for a few months, but today I broke something and I can't work out what. It all started when I tried to get line_profiler to work. It doesn't work with pip at the moment so I tried to follow the instructions in the readme. In this end this didn't work as I couldn't figure out how to get cython to install from brew.
The symptoms
If I create a new directory, and do a simple command like pipenv install pandas everything works, and I get a Pipfile that looks like this:
[[source]]
name = "pypi"
url = "https://pypi.org/simple"
verify_ssl = true

[dev-packages]

[packages]
pandas = "*"

[requires]
python_version = "3.7"

If I then copy this Pipfile to a new directory and try to create a virtual environment there with pipenv install it fails with this message:
✘ Failed creating virtual environment
[pipenv.exceptions.VirtualenvCreationException]:   File "/usr/local/Cellar/pipenv/2018.11.26_2/libexec/lib/python3.7/site-packages/pipenv/cli/command.py", line 254, in install
[pipenv.exceptions.VirtualenvCreationException]:       editable_packages=state.installstate.editables,
[pipenv.exceptions.VirtualenvCreationException]:   File "/usr/local/Cellar/pipenv/2018.11.26_2/libexec/lib/python3.7/site-packages/pipenv/core.py", line 1741, in do_install
[pipenv.exceptions.VirtualenvCreationException]:       pypi_mirror=pypi_mirror,
[pipenv.exceptions.VirtualenvCreationException]:   File "/usr/local/Cellar/pipenv/2018.11.26_2/libexec/lib/python3.7/site-packages/pipenv/core.py", line 574, in ensure_project
[pipenv.exceptions.VirtualenvCreationException]:       pypi_mirror=pypi_mirror,
[pipenv.exceptions.VirtualenvCreationException]:   File "/usr/local/Cellar/pipenv/2018.11.26_2/libexec/lib/python3.7/site-packages/pipenv/core.py", line 506, in ensure_virtualenv
[pipenv.exceptions.VirtualenvCreationException]:       python=python, site_packages=site_packages, pypi_mirror=pypi_mirror
[pipenv.exceptions.VirtualenvCreationException]:   File "/usr/local/Cellar/pipenv/2018.11.26_2/libexec/lib/python3.7/site-packages/pipenv/core.py", line 935, in do_create_virtualenv
[pipenv.exceptions.VirtualenvCreationException]:       extra=[crayons.blue("{0}".format(c.err)),]
[pipenv.exceptions.VirtualenvCreationException]: Traceback (most recent call last):
  File "/usr/local/Cellar/pipenv/2018.11.26_2/libexec/lib/python3.7/site-packages/virtualenv.py", line 2502, in <module>
    main()
  File "/usr/local/Cellar/pipenv/2018.11.26_2/libexec/lib/python3.7/site-packages/virtualenv.py", line 793, in main
    symlink=options.symlink,
  File "/usr/local/Cellar/pipenv/2018.11.26_2/libexec/lib/python3.7/site-packages/virtualenv.py", line 1070, in create_environment
    install_python(home_dir, lib_dir, inc_dir, bin_dir, site_packages=site_packages, clear=clear, symlink=symlink)
  File "/usr/local/Cellar/pipenv/2018.11.26_2/libexec/lib/python3.7/site-packages/virtualenv.py", line 1487, in install_python
    shutil.copy(original_python, py_executable)
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/shutil.py", line 245, in copy
    copyfile(src, dst, follow_symlinks=follow_symlinks)
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/shutil.py", line 103, in copyfile
    if _samefile(src, dst):
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/shutil.py", line 88, in _samefile
    return os.path.samefile(src, dst)
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/genericpath.py", line 96, in samefile
    s1 = os.stat(f1)
TypeError: stat: path should be string, bytes, os.PathLike or integer, not NoneType

Failed to create virtual environment.

If I go to one of my previously working directories and try pipenv run jupyter notebook I get an error like this:
pipenv run jupyter notebook
Traceback (most recent call last):
  File "/Users/robertking/.local/share/virtualenvs/decision_quality-DM1iI0uH/bin/jupyter-notebook", line 6, in <module>
    from notebook.notebookapp import main
  File "/Users/robertking/.local/share/virtualenvs/decision_quality-DM1iI0uH/lib/python3.6/site-packages/notebook/notebookapp.py", line 62, in <module>
    from tornado import httpserver
  File "/Users/robertking/.local/share/virtualenvs/decision_quality-DM1iI0uH/lib/python3.6/site-packages/tornado/httpserver.py", line 29, in <module>
    import ssl
  File "/Users/robertking/.pyenv/versions/3.6.8/lib/python3.6/ssl.py", line 101, in <module>
    import _ssl             # if we can't import it, let the error propagate
ImportError: dlopen(/Users/robertking/.local/share/virtualenvs/decision_quality-DM1iI0uH/lib/python3.6/lib-dynload/_ssl.cpython-36m-darwin.so, 2): Library not loaded: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib
  Referenced from: /Users/robertking/.local/share/virtualenvs/decision_quality-DM1iI0uH/lib/python3.6/lib-dynload/_ssl.cpython-36m-darwin.so
  Reason: image not found

I have tried uninstall and re-install of pipenv, plus the usual tricks of pipenv --rm and removing the cache ~/Library/Caches/pipenv
Any idea what else I can check, or what might be happening?

A: I have things working again now. I acknowledge this isn't a great answer, but it might help someone. I'm not sure exactly which part of the process was critical and what was incidental:

*

*I found that the ssl libraries weren't working with basic pip. This led me to reinstall the versions of Python I had installed using pyenv. pip then worked.

*I uninstalled the version of pipenv I had from brew and reinstalled it using pip install.

So basically, reinstall all my python tools seemed to sort things out.


text:
Q: Extend a joomla module I am new to joomla and been trying to fully understand its workings,
There is a Joomla module called Latest News, I want to alter the output of the this module to include images drawn from the articles, i dont want to alter the tmpl/default.php file since I still want to maintain the usual look in other positions, I am guessing then that I have to use a plugin,
How then do I attach the plugin to the module if this is indeed the best way to extend the module in this instance?

A: I'm a bit confused about what you want ... are you saying you sometimes want to include the images and sometimes not?
If you always want to include the images then you can do a regular template override for fault default.php. Don't alter the core file, put the file in your template folder under modules/mod_latest.  If you just want to use it in some instances put the modified file there but with a different name an then edit your module instance to use that layout by selecting that layout as an alternative layout. It's in the Advance Optons tab of J3 and one  of the sliders in J2.5

A: You don't need a plugin but a new module layout.
There are two places you can put your new module layout:

*

*under /modules/your_module/tmpl/newlayout.php

*under /templates/your_template/html/your_module/newlayout.php (but in this case, make sure you also copy the default.php - this is mandatory or the override won't be seen)

Now head to your module configuration and you will find your layout.


text:
Q: Add an incentive for approving/rejecting edits There's a new system for peer-reviewing edit suggestion which allows sub-2k rep users to edit posts as long as two 1k+ users (or one 20k+ user) approve the edit. Of course the overall goal of all parties involved is to just make the site better, but I propose to add some incentives for the users involved.
The user making the suggestions already gets a rep bonus if it's approved; I propose to also add some sort of reward to the user(s) approving the edit. Not necessarily reputation, this could be something as simple as a new badge or two:

Reviewer - voted on 50 edits
Scrutineer - voted on 500 edits

Notice that it's important the reward will be per vote and not for just approving edits - i.e. consider both approving and rejecting edits, since what we want to reward is users reviewing these edits.

A: I was going to make the same suggestion but saw that this was already made, but I'd definitely shy away from the low counts like 50, and tend towards higher things like 500.  Make it something that you'd either have to really really grind for if you were just badge-whoring, but something that's not entirely unlikely to happen if you're approving/rejecting things regularly for a decent length of time.
So, I'd suggest a Bronze badge for 500 approved/rejected edits, and perhaps have it be one that can be earned multiple times (again, to encourage a regular extended period of behavior instead of a grind session to get a check mark on the Badges page)

A: My concern here is that if we introduce a badge people will be more likely to vote and thus make hasty incorrect decisions.
As it stands a suggested edit queue is constantly empty ... on average an item is not even lasting longer than a minute.
Though I agree with the sentiment that a badge would be nice, I am not sure encouraging voting is needed at the moment.
Edit: implemented as the Proofreader badge!

A: Is this needed? It seems to be that approving/rejecting edits are mostly being done quickly enough by 10K users.   Also I don't think a incentive will change what most 10K do.


text:
Q: Nomad cluster per environment What is the standard/convention for Nomad orchestration in the context of environments/deploy-stage, do people generally have a Nomad cluster per environment, or do all environments share a cluster? Other than the cost implications, what are the pros and cons to both methods?

A: I think you will find in most of these situation there is no convention, it really depends on the outcome you are trying to get to.
The benefits of having a larger cluster running multiple environments is that you can get more out of less - i.e run less hardware as you can share it across multiple services in the same cluster.
The benefits of having seperate clusters for seperate environments is that you have a smaller blast zone/radius, your production environment is not sitting along side your development so when someone accidentally breaks something in development environment  it doesn't effect your production environment. As well as this it gives you an upgrade path i.e you can try upgrade your Nomad cluster in development first rather then doing it on the production cluster.
I think it makes sense to take a balanced approach:

*

*1 Cluster for Testing Environments - Even if you have multiple

*1 Cluster for Integration Environments - Even if you have multiple

*1 Cluster for Production Environments - Even if you have multiple

This is a really good read on a high profile application crashing due to the single cluster approach: https://www.theregister.co.uk/2017/10/31/kubernetes_bug_bank_app_monzo/


text:
Q: Ignore a svn:"property" while doing svn merge I have a svn:external property in my trunk project.
From that trunk I have a branch coming out that has a svn:external to a different path.
The branch is constant. That means I don't want to close it a i'm continually working on it.
When changes have been made in the branch I want to merge them back into the trunk.
The thing is, I want all the changes EXCEPT the svn:external property.
When I try to merge, I don't get a conflict because svn is too smart and does update on the property. If I had a conflict I could use mine always.
I thought about using a svn hook to revert that specific change but I want to use that as a last resort.
Any other ideas?
Many thanks!

A: Use the option --record-only once after changing the svn:externals on the branch to mark the revision as already merged without actually merging it.
# changing svn:externals on branch
svn propedit svn:externals branches/foo/externals
svn commit

# mark commit as already merged
svn merge -c rev --record-only branches/foo trunk
svn commit


text:
Q: Does Google Drive API have a api to show the upgrade link? Does Google Drive API have an api to show the storage upgrade link?
I mean a link which can let user to buy more space.
Like Google One, https://one.google.com/plans
Thanks.

A: The google drive api is a file storage api.   It gives you access to the data beind the google drive web application.  It does not give you any control over the google drive web application itself.
Upgrade storage link is outside the scope for this api.


text:
Q: Why is Func ambiguous with Func>? This one's got me flummoxed, so I thought I'd ask here in the hope that a C# guru can explain it to me.
Why does this code generate an error?
class Program
{
    static void Main(string[] args)
    {
        Foo(X); // the error is on this line
    }

    static String X() { return "Test"; }

    static void Foo(Func<IEnumerable<String>> x) { }
    static void Foo(Func<String> x) { }
}

The error in question:
Error
    1
    The call is ambiguous between the following methods or properties:
'ConsoleApplication1.Program.Foo(System.Func<System.Collections.Generic.IEnumerable<string>>)' and 'ConsoleApplication1.Program.Foo(System.Func<string>)'
    C:\Users\mabster\AppData\Local\Temporary Projects\ConsoleApplication1\Program.cs
    12
    13
    ConsoleApplication1

It doesn't matter what type I use - if you replace the "String" declarations with "int" in that code you'll get the same sort of error. It's like the compiler can't tell the difference between Func<T> and Func<IEnumerable<T>>.
Can someone shed some light on this?

A: Your code requires "magic" to take place twice, once to convert from the named method group to a delegate, and once to perform overload resolution.
Despite the fact that you have only one method named X, the compiler rules are built for the case when there are multiple.
In addition, since delegates don't have to match the method signature exactly, the complexity is further increased.  On top of that, any given method can be converted to an unlimited number of different delegate types with identical signatures.
Your particular case looks straightforward enough, but the general case is very very hard, so the language doesn't allow it.
If you do part of the work by hand, you'll solve the problem.  e.g.
Func<string> d = X;
Foo(d);

should compile just fine.

A: OK, here's the deal.
The short version:

*

*The ambiguity error is, bizarrely enough, correct.

*The C# 4 compiler also produces a spurious error after the correct ambiguity error. That appears to be a bug in the compiler.

The long version:
We have an overload resolution problem.  Overload resolution is extremely well specified.
Step one: determine the candidate set.  That's easy. The candidates are Foo(Func<IEnumerable<String>>) and Foo(Func<String>).
Step two: determine which members of the candidate set are applicable. An applicable member has every argument convertible to every parameter type.
Is Foo(Func<IEnumerable<String>>) applicable?  Well, is X convertible to Func<IEnumerable<String>?
We consult section 6.6 of the spec. This part of the specification is what we language designers call "really weird". Basically, it says that a conversion can exist, but using that conversion is an error.  (There are good reasons why we have this bizarre situation, mostly having to do with avoiding future breaking changes and avoiding "chicken and egg" situations, but in your case we are getting somewhat unfortunate behaviour as a result.)
Basically, the rule here is that a conversion from X to a delegate type with no parameters exists if overload resolution on a call of the form X() would succeed. Clearly such a call would succeed, and therefore a conversion exists. Actually using that conversion is an error because the return types don't match, but overload resolution always ignores return types.
So, a conversion exists from X to Func<IEnumerable<String>, and therefore that overload is an applicable candidate.
Obviously for the same reason the other overload is also an applicable candidate.
Step Three: We now have two applicable candidates. Which one is "better"?
The one that is "better" is the one with the more specific type. If you have two applicable candidates, M(Animal) and M(Giraffe) we choose the Giraffe version because a Giraffe is more specific than an Animal. We know that Giraffe is more specific because every Giraffe is an Animal, but not every Animal is a Giraffe.
But in your case neither type is more specific than the other. There is no conversion between the two Func types.
Therefore neither is better, so overload resolution reports an error.
The C# 4 compiler then has what appears to be a bug, where its error recovery mode picks one of the candidates anyways, and reports another error. It's not clear to me why that is happening. Basically it is saying that error recovery is choosing the IEnumerable overload, and then noting that the method group conversion produces an untenable result; namely, that string is not compatible with IEnumerable<String>.
The whole situation is rather unfortunate; it might have been better to say that there is no method-group-to-delegate conversion if the return types do not match.  (Or, that a conversion that produces an error is always worse than a conversion that does not.) However, we're stuck with it now.
An interesting fact: the conversion rules for lambdas do take into account return types. If you say Foo(()=>X()) then we do the right thing. The fact that lambdas and method groups have different convertibility rules is rather unfortunate.
So, summing up, the compiler is actually a correct implementation of the spec in this case, and this particular scenario is an unintended consequence of some arguably unfortunate spec choices.


text:
Q: Teradata regexp_replace to eliminate specific special characters I imported a file that contains email addresses (email_source). I need to join this table to another, using this field but it contains commas (,) and double quotes (") before and after the email address (eg. "johnsmith@gmail.com,","). I want to replace all commas and double quotes with a space.
What is the correct syntax in teradata?

A: Just do this:
REGEXP_REPLACE(email_source, '[,"]', ' ',1,0,i)
Breakdown:
REGEXP_REPLACE(email_source, -- sourcestring
'[,"]', -- regexp
' ', --replacestring
1, --startposition
0, -- occurrence, 0 = all
'i' -- match -> case insensitive
)

A: You don't need a regex for this, a simple oTranslate should be more efficient:
oTranslate(email_source, ',"', '  ')


text:
Q: Recommendation for lightweight embeddable Java web framework with Comet support? I'm working on an open source anonymous decentralized P2P application that will support Twitter-like functionality, you can read more here.
My intention is that the UI will emulate the Twitter UI quite closely, and be accessible through a web-browser communicating with the local app.
I'm therefore looking for a lightweight embeddable web app framework that supports comet (ie. server-initiated modifications to the DOM).  It must be lightweight because I need to keep the size of the eventual application as small as possible.
My intention is that most of the UI work will be handled within the web browser, making use of JQuery, and perhaps using Coffeescript instead of Javascript (although I haven't yet made a full decision on this).
Can anyone recommend (GPL compatible) tools/libraries/frameworks for me to look at?

A: Not sure if you are still working on this since the git activity on the project page is pretty stale. But if you are I would recommend Jetty for your embeddable web app server. It is:

*

*Small

*Embeddable

*Supports Cometd

*Supports Servlets

Throw Vaadin on there for a small, lightweight web development framework and you are g2g.


text:
Q: How to force asp.net web api 2 to response xml without global config changed My WebApiCongig use
    config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

to force to response json.
But there are some specific api that need to return xml format data.
I use
public HttpResponseMessage PostNotify(HttpRequestMessage request)
{
  HttpResponseMessage resp = Request.CreateResponse<PackageModal>(HttpStatusCode.OK, value: package,
                        formatter: Configuration.Formatters.XmlFormatter);
                    return resp;
}

But it doesn't work. Still gets a json-format response.

A: Use the accept-header in your request and the contentnegotiation will take care of the output format!


text:
Q: Discord Bot - Responses If I have a number of responses:
const exampleResponses = [ "name1", "name2", "name3"];
But let's say it's thousands of responses, not just three. Is there a way to pull in the responses from another file? As it stands, with thousands of responses it just clogs up my coding file.

A: There are many ways you can go about this. One way would be to have a separate file with one array containing all the responses, then export that variable and require it in your main file
Responses.js
const responses = ['r1', 'r2', 'r3']
// And so on...

module.exports = {
   responses
}

Main File
const { responses } = require('filePathToResponsesJS')

A: A way to do this is to make a JSON file and call from it with JavaScript.
const { exampleResponses } = require('./example.json')

{
  "exampleResponses": [
    "name1",
    "name2",
    "name3"
  ]
}

A: You can import the FileSystem module and do something like this:
responses= JSON.parse( fs.readFileSync( 'data/responses.json', function( err, data ) { ... }

Similarly, you can write to said file to keep things neat and tidy.


text:
Q: liferay portlet: access forbidden after time period for guest user I created a portlet on Liferay 6.1, JBoss 7 for guests.
It needs to work for the user even if he hasn't made an action for a long period of time.
Actual if I do something in my portlet and wait for about 10 minutes and then do something again (for example changing jsp by hitting a button), this error appears:

It's german, but it means: forbidden, you don't have the permission to access this ressource.
How can I avoid this?

A: I don't know what's your problem... just some suggestions:

*

*Are you sure your portlet has view permission for guest users? To verify login, and go to permission by clicking on icon placed in the upper-right corner.

*Does you code deal with permission? (if "not", then ignore this point)

For your needs, don't forget that it's possible that your portlet can lose data in your guest session after timeout in any case.

A: You have two options that I can think of.
1) Increase the session time out.
2) Make an ajax request to your server to keep your session active.
Hope this helps!


text:
Q: Interpolation error with gsl akima spline I'm getting a 'gsl: interp.c:150: ERROR: interpolation error' with the following code. Some googling says that this error occurs when you try to extrapolate using the interp function but I don't see how that is happening here. Help would be greatly appreciated. Thanks.
The function randomground() just returns a random number (double).
#define NSTEPS 100

int main()
{
           int j, q, space = 1, refine = 100;
           double xi = 0.0, tx[2*NSTEPS] = {0}, theight[2*NSTEPS] = {0};

           double terrain[(int) (2*NSTEPS*100)] = {0};
           double terrainsl[(int) (2*NSTEPS*100)] = {0};

            for (j = 0; j < 2*NSTEPS; j++)
            {
                tx[j] = (double) j*space;
                theight[j] = randomground();
            }

            gsl_interp_accel *acc = gsl_interp_accel_alloc();
            gsl_spline *spline = gsl_spline_alloc(gsl_interp_akima, 2*NSTEPS);
            gsl_spline_init(spline, tx, theight, 2*NSTEPS);

            for (q = 0; q< 2*NSTEPS*100; q++)
            {
                terrain[q] = gsl_spline_eval(spline,xi,acc);
                terrainsl[q] = gsl_spline_eval_deriv(spline,xi,acc);
                xi = xi+(double) space/refine;
            }
return 0;
}

A: Fixed the problem by adding an extra element to tx and theight. I'm guessing this is what you had asked me to do, @ViniciusMiranda. The code now reads
                double tx[2*NSTEPS+1] = {0}, theight[2*NSTEPS+1] = {0};
                double terrain[(int) (2*NSTEPS*100)] = {0};
                double terrainsl[(int) (2*NSTEPS*100)] = {0};

            for (j = 0; j < 2*NSTEPS+1; j++)
            {
                tx[j] = (double) j*space;
                theight[j] = randomground();
            }

            gsl_interp_accel *acc = gsl_interp_accel_alloc();
            gsl_spline *spline = gsl_spline_alloc(gsl_interp_akima, 2*NSTEPS+1);
            gsl_spline_init(spline, tx, theight, 2*NSTEPS+1);

            for (q = 0; q< 2*NSTEPS*100; q++)
            {
                terrain[q] = gsl_spline_eval(spline,xi,acc);
                terrainsl[q] = gsl_spline_eval_deriv(spline,xi,acc);
                xi = xi+(double) space/refine;
            }

I still don't understand why this fix was required though.

A: Akima spline is a local, sub-spline interpolation. For a function f(x), if you are trying to obtain the value of x for x_i <= x <= x_i+1, Akima spline needs the pairs (x_j, f_j) for j = i-2, i-1, i, i+1, i+2, i+3.

A: I found the same error in my code zigzag.sourceforge.net  and resolved by commenting the line in the gsl library source, compiling it and reinstalling.

Before version 1.14 there is in interp.c the line 150

// GSL_ERROR_VAL("interpolation error", GSL_EDOM, GSL_NAN);

that I comment to solve the break !


text:
Q: How save AdditionalField data for a domain in WHMCS I am having a hard time figuring out how does the Additional fields for Domains even work other than being editable on the order form and from admin panel, but what if we have to update its custom fields from a Module such as Registrar module.
I have a requirement where my domain registrar sends a Request ID in its domain register API response, which I have to store with the domain to later fetch domain status using it.
I have created an Additional field for domain
$additionaldomainfields[".co"][] = array(
    "Name" => "RequestId",
    "Type" => "text",
    "Show on Order Form" => false
);

And have AfterRegistrarRegister hook in my registrar module.
add_hook('AfterRegistrarRegister', 1, function($vars) {

        require_once 'init.php';
        $varsjson = json_encode( $vars );
        $domainName = $vars['params']['sld'] . '.' . $vars['params']['tld'];
        $domainid = $vars['domainid'];

        //return array(
        //    'abortWithSuccess' => true,
        //);
    }
);

I tried
$vars['additionalfield']['RequestId'] = 'testtt';

But of course it doesn't work.
I am also referring to the Classdocs of WHMCS https://classdocs.whmcs.com/7.6/WHMCS/Domain/Registrar/Domain.html
But there appears to be no method that updates the values of a domain additional field.
Any help is appreciated.

A: I was able to solve the problem using the Capsule Database interaction as described here -
https://developers.whmcs.com/advanced/db-interaction/
use WHMCS\Database\Capsule;
function updateRequestId( $domainId, $newdata ) {

        $finalRequestId = $newdata;

        $response = array(
            'updated' => false,
            'request_id' => $finalRequestId,
            'errors' => array()
        );

        try {
            $requestId = Capsule::table('tbldomainsadditionalfields')
                        ->where('domainid', $domainId)
                        ->where('name', 'RequestId');

            $reqArr = $requestId->update([
                'value' => $finalRequestId
            ]);

            $response['request_id'] = $finalRequestId;
            $response['updated'] = true;

        } catch (\Exception $e) {
            echo "Error: {$e->getMessage()}";
            $response['errors'][] = $e->getMessage();
        }

        return $response;
    }

Now I can use this function to pass the domain id in the domain register hook and save the data returned by the registrar directly into the database.


text:
Q: Dúvida entre realizar o clearfix utilizando um elemento no DOM ou um pseudo-elemento Eu tenho que usar um float: left no meu logo e float: right no meu menu, porém o background-color desaparece e preciso corrigir com clear: both.
Minha dúvida é: qual a diferença entre usar um
 após os itens flutuantes com clear: both e usar o pseudo-seletor ::after, fazendo:
::after {
  content: '';
  display: table;
  clear: both;
}

Pois já vi gente usando assim pra limpar aquela baguncinha do float.

A: A diferença é que, ao usar um
 (ou qualquer outro elemento para fazer o clearfix), você está inserindo um elemento no DOM. Ao utilizar o pseudo-seletor ::after, você insere um pseudo-elemento no DOM.
Veja alguns exemplos:

.container {
  padding: 10px;
  border: solid 2px #000;
}

.box {
  width: 33.333%;
  height: 50px;
  float: right;
}

.clearfix {
  clear: both;
}

1

2

3

Note, no exemplo acima, que utilizamos o
 para fazer o clearfix. No entanto, não é necessário sequer mexer no HTML para arrumar isso. Pode-se utilizar um pseudo-elemento (criado com o ::after):

.container {
  padding: 10px;
  border: solid 2px #000;
}

.box {
  width: 33.333%;
  height: 50px;
  float: right;
}

.container::after {
  content: ' '; /* Cria o pseudo-elemento */
  display: block;
  clear: both;
}

1

2

3

Como você viu, o efeito é o mesmo.

Para saber mais, sugiro a leitura do excelente artigo "All about Floats". No entanto, é importante observar que, se os navegadores do seu público-alvo suportarem, você pode utilizar o Flexbox, que é uma alternativa mais moderna para os chamados floated layouts.


text:
Q: Java: Fastest way to change brightness of an image I was wondering what the fastest way to alter the brightness of an image.  I have implemented the 'RescaleOp' method but I don't know if this is the fastest method or there are others.  Here is my implementation where I input an Image, change the brightness, and return an Image:
public static Image setBrightness(Image i) {
    BufferedImage buff = new BufferedImage(i.getWidth(null), i.getHeight(null), BufferedImage.TYPE_INT_ARGB);
    buff.createGraphics().drawImage(i, 0, 0, null);
    RescaleOp op = new RescaleOp(brightness, offsets, null);
    BufferedImage buff1 = new BufferedImage(i.getWidth(null), i.getHeight(null), BufferedImage.TYPE_INT_ARGB);
    buff1.createGraphics().drawImage(buff, op, 0, 0);
    return Toolkit.getDefaultToolkit().createImage(buff1.getSource());
}

PS: I also need to convert the BufferedImage back into an Image because my computer doesn't like rendering BufferedImages.

A: Everything I've read leads me to believe that RescaleOp is the best, fastest option


text:
Q: Python int function Can anyone please tell me what are the inner workings of int function.
I know that it converts stuff into an integer but i want to know HOW it converts the stuff, like what are the inner workings of the function


text:
Q: Changing href attribute In need to change a part of this href:
large pic

I have some designs, and some colors, xxxxx stands for designnumber and yyy for colornumber, when one of the designs is clicked or one of the colors the href should
change according to the value:
design1
design2
design3

color1
color2
color3

Is there any way to do this with JQuery?

A: Your variable link would be:
large pic

Your toggling links would look like this:
design1
design2

color1
color2

Your javascript would look like this:
var designNumber = "";
var colorNumber = "";

function UpdateActionLink() {
    $("#colorlink").attr("href", "media/" + designNumber + "-" + colorNumber + ".jpg");
}

You'll probably want to add some validation to the colorLink tags onclick event to check to make sure designNumber and colorNumber have valid values, and if not, cancel the event and give the human a messaging saying they need to choose a valid design and color.  Better would probably be to make a Get Design button, have disabled to start, and in UpdateActionLink check to see if the values are valid and if so enable the Get Design button.

A: You can use the attr method to read and modify the href.
html:
large pic

design1
design2
design3

color1
color2
color3

javascript:
$(".design").click(function() {
  var old = $("#LargePic").attr("href");
  var pos = old.indexOf('-');
  val color = old.substr(pos, 3);
  $("#LargePic").attr("href", "media/" + $(this).text() + "-" + color + ".jpg");
});

Parsing the old value is not bullet proof. You could avoid this by creating two variables to hold the design and color.

A: To minimise teh number of DOM queries you do you could store the current colour and design within an object;
function DesignSwitcher() {
    var params = $("#largePic").attr("id").split["-"],
        des = params[0],
        col = params[1];
    $(".design").click(function() {
       des = this.innerHTML;
       $("#largePic").attr("href", "media/" + des + "-" + col + ".jpg");
    });
    $(".color").click(function() {
       col = this.innerHTML;
       $("#largePic").attr("href", "media/" + des + "-" + col + ".jpg");
    });

}

new DesignSwitcher();

A: Add a class to your links, let's say myClass, and an ID on the main link, let's say myLink, and something like this should work :
$('.myClass').each(function(el) {
    el.bind('click', function(event) {
         $('myLink')attr('href', el.text());
    }
});


text:
Q: Add point at map centre in ggplot in r I want to add point at every state centre.
I know centroid() from geosphere package can do this. It can only compute one longitude and latitude, but I have 49 states and I do not want to compute it one by one.
I also know coordinates() from sp package can do this. It needs the argument class input is SpatialPolygonsDataFrame and sp but the us map I get from map_data() is a dataframe.
Any suggestion?
library(scatterpie)
library(tidyverse)
library(geosphere)
library(ggnewscale)
us <- map_data('state') %>% as_tibble()

n = length(unique(us$region))

# creat fake mapping data

temperature_data <- tibble(region = unique(us$region),
                           temp = rnorm(n = n))

coords <- us %>% select(long, lat, region) %>% distinct(region, .keep_all = T)

coords_data <- tibble(region = unique(us$region)) %>% left_join(coords)

us <- left_join(us, temperature_data)

# add point
p + geom_map(map = us, aes(map_id = region, fill = temp), color = 'grey') +
    geom_point(data = category_data, aes(long, lat))

A: You can compute the centroids by grouping the data by region and then modify for each group using purrr::group_modify():
centroids <- us %>%
  group_by(region) %>%
  group_modify(~ data.frame(centroid(cbind(.x$long, .x$lat))))

Then plot everything together:
ggplot(us, aes(x = long, y = lat)) +
  geom_polygon(aes(group = group)) +
  geom_map(map = us, aes(map_id = region, fill = temp), color = 'grey') +
  geom_point(data = centroids, aes(lon, lat), col = "red")


text:
Q: AngularJS - Directive vs per Controller Code in 'special' cases I have a theoretical case here, well, for me is a practical case, this is what I am doing right now.
I have a SPA, with a lot of partials (3 atm), and I have a menu, that will go through different states, I am doing this to have a fluid feel to entire site, the menu element is at first a small animation, better like this:

*

*The menu is an animation at first that does something on my root template

*The menu transforms into an action button that you can press to enter the actual homepage(not quite, it still has some neat actions tied to it when you open it or press some buttons)

*On the homepage the menu changes states again so it is a normal site menu.

I'm keeping the same element on all the pages for the experience to be fluid.
The menu changes classes, each class has it's on layers of animation and possible manipulation.
In this case, is it better to use a directive for the menu?
What I am wondering is this, If I make a directive out of it, could I change its state with a command from the controller inside the directive? Or should the logic be in the Directive (e.g. detect witch Controller is active and take the appropriate actions ?)
I have the impression that I put a lot of possibly dumb questions here on stackoverflow regarding these issues of mine :), but I really want to do things right, at the moment I do DOM manipulation for the menu from each controller on different click and other events, it works, but I think it is not properly maintainable, I have to alter things in three controllers (at this stage, maybe later there will be more) to make some changes to the look and feel.
A JSFiddle is out of the question, there is A LOT OF CODE.

A: A directive can share state with it's parent controller, so communication is not an issue. You can go with broadcasts if you need more decoupling (highly debatable fact though).
But I would not use a directive unless if you reuse it in different places OR by separating it's logic you end up with more manageable/readable code. In other words my directives tend to be related with a single "concern", not a lot of little stuff. It's pretty common to have directives inside other directives and transclude the contents.
I prefer doing DOM stuff in directives, where you have fine control of it with compile and link, so if I have a component that does a lot of heavy DOM stuff (event listeners, DOM manipulation) I tend to move the code in a directive.
I also like that <my-foo-directive> tags pop out in templates and abstract/simplify them too.


text:
Q: Solving a system of cubic polynomials (to find intersection of Bezier curves) Can anyone suggest a fix or an alternate route to find the solutions to this system?
In particular I only care about solutions (s,t) in [0,1]x[0,1]
Note: I'm looking for the intersection of two cubic Bezier curves here.  I need the method to be guaranteed to find all solutions and hopefully within a reasonable amount of time (for my use this means a few seconds per pair of curves).
I tried using sympy but both solve() and solve_poly_system() returned empty lists.
Here's my code:
from sympy.solvers import solve_poly_system, solve
from sympy.abc import s,t

#here are two cubics.  I'm looking for their intersection in [0,1]x[0,1]:
cub1 = 600*s**3 - 1037*s**2 + 274*s + 1237*t**3 - 2177*t**2 + 642*t + 77
cub2 = -534*s**3 + 582*s**2 + 437*s + 740*t**3 - 1817*t**2 + 1414*t - 548

#I know such a solution exists (from plotting these curves) and fsolve finds an     approximation of it no problem:
from scipy.optimize import fsolve
fcub1 = lambda (s,t): 600*s**3 - 1037*s**2 + 274*s + 1237*t**3 - 2177*t**2 + 642*t + 77
fcub2 = lambda (s,t):-534*s**3 + 582*s**2 + 437*s + 740*t**3 - 1817*t**2 + 1414*t - 548
F = lambda x: [fcub1(x),fcub2(x)]
print 'fsolve gives (s,t) = ' + str(fsolve(F,(0.5,0.5)))
print 'F(s,t) = ' + str(F(fsolve(F,(0.5,0.5))))

#solve returns an empty list
print solve([cub1,cub2])

#solve_poly_system returns a DomainError: can't compute a Groebner basis over RR
print solve_poly_system([cub1,cub2])

This outputs:
fsolve gives (s,t) = [ 0.35114023  0.50444115]
F(s,t) = [4.5474735088646412e-13, 0.0]
[]
[]

Thanks for reading!

A: For the intersection of Béziers, there are better approaches. (http://pomax.github.io/bezierinfo/#curveintersection, http://www.tsplines.com/technology/edu/CurveIntersection.pdf).
My recommendation for a simple solution: implement the Bezier subdivision algorithm (http://www.cs.mtu.edu/~shene/COURSES/cs3621/NOTES/spline/Bezier/bezier-sub.html). For both curves, compute the bounding box of the control vertices. If they overlap, an intersection is possible, subdivide and repeat the process with the halves (there will be four comparisons this time). Continue recursively.
You mustn't fear exponential explosion (1, 4, 16, 256... comparisons), as rather soon many boxes will stop overlapping.
Note that in theory you can work with the convex hulls of the control points, but in practice a simple bounding box is quite enough and much easier to work with.

A: Yves's solution worked well. Here's my code in case it helps anyone:
from math import sqrt
def cubicCurve(P,t):
    return P[0]*(1-t)**3 + 3*P[1]*t*(1-t)**2 + 3*P[2]*(1-t)*t**2 + P[3]*t**3
def cubicMinMax_x(points):
    local_extremizers = [0,1]
    a = [p.real for p in points]
    delta = a[1]**2 - (a[0] + a[1]*a[2] + a[2]**2 + (a[0] - a[1])*a[3])
    if delta>=0:
        sqdelta = sqrt(delta)/(a[0] - 3*a[1] + 3*a[2] - a[3])
        tau = a[0] - 2*a[1] + a[2]
        r1 = tau+sqdelta
        r2 = tau-sqdelta
        if 0<r1<1:
            local_extremizers.append(r1)
        if 0<r2<1:
            local_extremizers.append(r2)
    localExtrema = [cubicCurve(a,t) for t in local_extremizers]
    return min(localExtrema),max(localExtrema)
def cubicMinMax_y(points):
    return cubicMinMax_x([-1j*p for p in points])
def intervalIntersectionWidth(a,b,c,d): #returns width of the intersection of intervals [a,b] and [c,d]  (thinking of these as intervals on the real number line)
    return max(0, min(b, d) - max(a, c))
def cubicBoundingBoxesIntersect(cubs):#INPUT: 2-tuple of cubics (given bu control points) #OUTPUT: boolean
    x1min,x1max = cubicMinMax_x(cubs[0])
    y1min,y1max = cubicMinMax_y(cubs[0])
    x2min,x2max = cubicMinMax_x(cubs[1])
    y2min,y2max = cubicMinMax_y(cubs[1])
    if intervalIntersectionWidth(x1min,x1max,x2min,x2max) and intervalIntersectionWidth(y1min,y1max,y2min,y2max):
        return True
    else:
        return False
def cubicBoundingBoxArea(cub_points):#INPUT: 2-tuple of cubics (given bu control points) #OUTPUT: boolean
    xmin,xmax = cubicMinMax_x(cub_points)
    ymin,ymax = cubicMinMax_y(cub_points)
    return (xmax-xmin)*(ymax-ymin)
def halveCubic(P):
    return ([P[0], (P[0]+P[1])/2, (P[0]+2*P[1]+P[2])/4, (P[0]+3*P[1]+3*P[2]+P[3])/8],[(P[0]+3*P[1]+3*P[2]+P[3])/8,(P[1]+2*P[2]+P[3])/4,(P[2]+P[3])/2,P[3]])
class Pair(object):
    def __init__(self,cub1,cub2,t1,t2):
        self.cub1 = cub1
        self.cub2 = cub2
        self.t1 = t1 #the t value to get the mid point of this curve from cub1
        self.t2 = t2 #the t value to get the mid point of this curve from cub2
def cubicXcubicIntersections(cubs):
#INPUT: a tuple cubs=([P0,P1,P2,P3], [Q0,Q1,Q2,Q3]) defining the two cubic to check for intersections between.  See cubicCurve fcn for definition of P0,...,P3
#OUTPUT: a list of tuples (t,s) in [0,1]x[0,1] such that cubicCurve(cubs[0],t) - cubicCurve(cubs[1],s) < Tol_deC
#Note: This will return exactly one such tuple for each intersection (assuming Tol_deC is small enough)
    Tol_deC = 1 ##### This should be set based on your accuracy needs.  Making it smaller will have relatively little effect on performance.  Mine is set to 1 because this is the area of a pixel in my setup and so the curve (drawn by hand/mouse) is only accurate up to a pixel at most.
    maxIts =  100 ##### This should be something like maxIts = 1-log(Tol_deC/length)/log(2), where length is the length of the longer of the two cubics, but I'm not actually sure how close to being parameterized by arclength these curves are... so I guess I'll leave that as an exercise for the interested reader :)
    pair_list = [Pair(cubs[0],cubs[1],0.5,0.5)]
    intersection_list = []
    k=0
    while pair_list != []:
        newPairs = []
        delta = 0.5**(k+2)
        for pair in pair_list:
            if cubicBoundingBoxesIntersect((pair.cub1,pair.cub2)):
                if cubicBoundingBoxArea(pair.cub1)<Tol_deC and cubicBoundingBoxArea(pair.cub2)<Tol_deC:
                    intersection_list.append((pair.t1,pair.t2)) #this is the point in the middle of the pair
                    for otherPair in pair_list:
                        if pair.cub1==otherPair.cub1 or pair.cub2==otherPair.cub2 or pair.cub1==otherPair.cub2 or pair.cub2==otherPair.cub1:
                            pair_list.remove(otherPair) #this is just an ad-hoc fix to keep it from repeating intersection points
                else:
                    (c11,c12) = halveCubic(pair.cub1)
                    (t11,t12) = (pair.t1-delta,pair.t1+delta)
                    (c21,c22) = halveCubic(pair.cub2)
                    (t21,t22) = (pair.t2-delta,pair.t2+delta)
                    newPairs += [Pair(c11,c21,t11,t21), Pair(c11,c22,t11,t22), Pair(c12,c21,t12,t21), Pair(c12,c22,t12,t22)]
        pair_list = newPairs
        k += 1
        if k > maxIts:
            raise Exception ("cubicXcubicIntersections has reached maximum iterations without terminating... either there's a problem/bug or you can fix by raising the max iterations or lowering Tol_deC")
    return intersection_list

Also just in case anyone wants it, I wrote coded de Casteljau's algorithm for splitting Bezier curves of arbitrary degree.  In the above code I just replace it with halveCubic, which is just de Casteljau's method but made explicit and restricted to the cubic case (with t=0.5).
def splitBezier(points,t):
#returns 2 tuples of control points for the two resulting Bezier curves
    points_left=[]
    points_right=[]
    (points_left,points_right) =  splitBezier_deCasteljau_recursion((points_left,points_right),points,t)
    points_right.reverse()
    return (points_left,points_right)
def splitBezier_deCasteljau_recursion(cub_lr,points,t):
    (cub_left,cub_right)=cub_lr
    if len(points)==1:
        cub_left.append(points[0])
        cub_right.append(points[0])
    else:
        n = len(points)-1
        newPoints=[None]*n
        cub_left.append(points[0])
        cub_right.append(points[n])
        for i in range(n):
            newPoints[i] = (1-t)*points[i] + t*points[i+1]
        (cub_left, cub_right) = splitBezier_deCasteljau_recursion((cub_left,cub_right),newPoints,t)
    return (cub_left, cub_right)

I hope that helps someone out there!
Thanks again for you help Yves!

A: What about simplifying the system ?
By a suitable linear combination, you can eliminate one of s^3 or t^3, and solve the remaining second degree equation. By plugging the result in the other equation, you get a single equation in a single unknown.
Or solve the algebraic equation obtained by resultants:
36011610661302281 - 177140805507270756*s - 201454039857766711*s^2 + 1540826307929388607*s^3 + 257712262726095899*s^4 - 4599101672917940010*s^5 + 1114665205197856508*s^6 + 6093758014794453276*s^7 - 5443785088068396888*s^8 + 1347614193395309112*s^9 = 0

(http://www.dr-mikes-maths.com/polynomial-reduction.html)


text:
Q: How to output file in function in c++? I want to output "a" to the file in the function, how do I do it? The following gives me error.
#include <iostream>
#include <fstream>

using namespace std;

void outputfile(const char* file);

int main()
{
    int a = 1;
    ofstream cc;
    cc.open("123.txt");
    if (cc.fail())
    {
        cout << "\nError in file opening" << endl;
        return(1);
    }
    outputfile("123.txt");
    cc.close();
    return 0;
}

void outputfile(const char* file)
{
    // I want to output a to the file, how can I do it? The following gives me error.
    file << a;
}

The problem is solved, thanks for answering the question.:)

A: I see couple of issues that need to be addressed.

*

*You can either pass the name of the file to outputfile or the ofstream. If you pass the name of the file to outputfile, the file needs to be opened in outputfile, not in main.
There are pros and cons to the two approaches. If the name of the file is passed to outputfile, main becomes very simple. However, if the ofstream object needs to be used to make other function calls, it will be better to pass an ofstream as the argument to outputfile.
If a ofstream is passed to outputfile, outputfile becomes very simple. However, if the ofstream is not going to be used by main for anything else, it is better to leave the details of what mechanism used by outputfile to write the data out. outputfile can even resort to FILE* and fprintf without affecting main.

*a needs to be made available to outputfile. It can be made a global variable or be passed to outputfile. It is better to avoid global data. Hence, prefer to pass it as an argument.
Solution 1
Pass an ofstream to outputfile, in addition to a.
#include <iostream>
#include <fstream>

using namespace std;

void outputfile(std::ofstream& file, int a);

int main()
{
   int a = 1;
   ofstream cc;
   cc.open("123.txt");
   if (cc.fail())
   {
      cout << "\nError in file opening" << endl;
      return(1);
   }
   outputfile(cc, a);

   // No need. The file will be closed when the function returns.
   // cc.close();

   return 0;
}

void outputfile(std::ofstream& file, int a)
{
    file << a;
}

Solution 2
The details of opening and closing the file is left to outputfile. Here, outputfile uses ofstream.
#include <iostream>
#include <fstream>

using namespace std;

void outputfile(char const* file, int a);

int main()
{
   int a = 1;
   outputfile("123.txt", a);

   return 0;
}

void outputfile(char const* file, int a)
{
   ofstream cc(file);
   if (cc.fail())
   {
      cout << "\nError in file opening" << endl;
      return;
   }
   cc << a;
}

Solution 3
The details of opening and closing the file is left to outputfile. Here, outputfile uses FILE*.
#include <iostream>
#include <fstream>

using namespace std;

void outputfile(char const* file, int a);

int main()
{
   int a = 1;
   outputfile("123.txt", a);

   return 0;
}

void outputfile(char const* file, int a)
{
   FILE* fp = fopen(file, "w");
   if ( fp == NULL )
   {
      cout << "\nError in file opening" << endl;
      return;
   }
   fprintf(fp, "%d", a);
   fclose(fp);
}

A: At first, you have declared a in main(). Either you have to pass it as parameter or you have to take it global. I took global in the code below.
Then what do you do passing const char*? You have to write in file, so send the stream instead like below:
#include <iostream>
#include <fstream>
using namespace std;
 void outputfile(ofstream &file);  int a=1;
 int main() {

  ofstream cc;
  cc.open("123.txt");
  if (cc.fail()) {
    cout <<"\nError in file opening" << endl;
    return(1);
  }
  outputfile(cc);
  cc.close();
  return 0;
}
void outputfile(ofstream &file)
{
  // I want to output a to the file, how do I do it? The following gives me error.
  file << a;
}

A: a isn't in scope.  Either declare it outside of main() in global space, or pass it into outputfile, something like:
void outputfile(ofstream &file file, int a) {
    file << a;
}


text:
Q: How can i convert CGFloat to an Integer Value (iPhone SDK) My problem is: I'm trying to convert my CGFloat Values to an integer value and than add them to an NSMutableArray.
For Example;
CGFloat x=ship.center.x
//convert x to integer
?
P.S.:After that, I will send these values to another iPhone with bluetooth. But first I must solve this problem. İf anyone knows how to send an array data to another iPhone with bluetooth, it also works :)

A: Firstly, why do you want to convert to int? CGfloat is just a typedef for float, and can be sent as-is, especially if you know that your sending iPhone to iPhone, since they will use the same memory representation for floats. If you still need to do this for some reason...
// Choose constants m and c so that the resulting integers
// span as much of the range (INT_MIN, INT_MAX) as possible,
// thus minimising aliasing effects. Also consider using
// long long (64-bit integers).
int x = (int)(m*ship.center.x+c)

NSMutableArray only stores objects, so you might want to use a simple array instead:
int* arr = malloc(sizeof(x)*ships.length);
for (int i = 0; i < ships.length; i++) {
    arr[i] = (int)ships[i].center.x;
}
send_data(arr, sizeof(x)*ships.length);

I've never programmed with a Bluetooth stack, so I can't help you there. Sorry.


text:
Q: Does this functional equation have a solution (also is there free functional equation solving software)? I tried typing this into Wolfram and it couldn't solve it, despite it looking simple:
$f(x) = (1/2)f(x)^2.$
Does this have a non-constant solution? (initial values not yet determined)

A: Why resort to software, though? The functional notation is confusing you. Instead of $f(x)$ just use e.g $z$. We have the equation
$$z=\frac{z^2}{2}$$
The only solutions for this are $z=0$ and $z=2$. This means the only possible solutions for $f$ are
$$f:x\mapsto 0 \\ f:x\mapsto 2$$
Good luck finding a non-constant solution, because they don't exist.
EDIT: I spoke to soon. If $f$ attains only the values $0$ or $2$ it will work. E.g,
$$f(x)=\begin{cases}
0 & x< 0\\
2 & x\geq 0
\end{cases}$$
Works.


text:
Q: Is there way to automatically expand a specific folder in Eclipse Project Explorer? I would like to have a certain folder in the Project Explorer expand automatically upon opening the project (or starting Eclipse with the project already open).
When working on multiple projects, you find yourself closing and opening projects a lot, and closing all relevant editors (Ctrl + Shift + w), so the editor link as commented by Torsten is not the solution I am looking for.
Pressing asterisc (*) expands all folders. However, I would like this (1) to happen automatically, and more importantly (2) only expand a certain (sub)folder.
Is this possible?

A: Try Shift+numpad_multiply for exapanding every file under a package/folder and Ctrl+Shift+numpad_divide for collapsing a project. I think this works better on Navigator for a big project because when I tried it in my project explorer, I ended up crashing eclipse.


text:
Q: GraphQL Scalar for java.time.LocalDate parses dates as StringValue I try to parse a date, e.g. "2022-02-02" as java.time.LocalDate.
Why the values passed to the scalar class are wrapped into curly braces? And how do I fix this?
I configured the scalar for java.time.LocalDate:
@Component
public class DateScalar extends GraphQLScalarType {

public DateScalar() {
    super("Date", "java.time.LocalDate", new Coercing() {
        @Override
        public Object serialize(Object o) throws CoercingSerializeException {
            return DateTimeFormatter.ofPattern("yyyy-MM-dd").format((LocalDate) o);
        }

        @Override
        public Object parseValue(Object o) throws CoercingParseValueException {
            return LocalDate.parse(o.toString());
        }

        @Override
        public Object parseLiteral(Object o) throws CoercingParseLiteralException {
            if (o == null) {
                return null;
            }
            return parseValue(o.toString());
        }
        });
    }
}

This is the query:
mutation {
createEvent(createEventRequest: {
    name: "test",
    description: "test description",
    userId: 1,
    participants: [{
        firstName: "first",
        lastName: "last"
    }],
  location: {
    street: "street",
    streetNumber: "streetNumber",
    country: "country"
  },
  duration: {
    entireDay: false,
    recurringDate: false,
    start: "2018-09-03"
  }
}) {
    id
    name
    description
    participantResponses {
        id
        firstName
        lastName
    }
    locationResponse {
        id
        street
        streetNumber
        country
    }
    durationResponse {
        id
        start
        end
        entireDay
        recurringDate
    }
    userResponse {
        id
        firstName
        lastName
        email
    }
}
}

The error says that Text 'StringValue{value='2018-09-03'}' could not be parsed at index 0.
I do not really understand why this is still wrapped into curly brackets.

java.time.format.DateTimeParseException: Text 'StringValue{value='2018-09-03'}' could not be parsed at index 0
at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:2052) ~[na:na]
at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1954) ~[na:na]
at java.base/java.time.LocalDate.parse(LocalDate.java:430) ~[na:na]
at java.base/java.time.LocalDate.parse(LocalDate.java:415) ~[na:na]
at com.projects.calendar.scalar.DateScalar$1.parseValue(DateScalar.java:21) ~[classes/:na]
at com.projects.calendar.scalar.DateScalar$1.parseLiteral(DateScalar.java:29) ~[classes/:na]
at graphql.validation.ValidationUtil.parseLiteral(ValidationUtil.java:113) ~[graphql-java-9.2.jar:na]
at graphql.validation.ValidationUtil.isValidLiteralValue(ValidationUtil.java:90) ~[graphql-java-9.2.jar:na]
at graphql.validation.ValidationUtil.isValidLiteralValue(ValidationUtil.java:141) ~[graphql-java-9.2.jar:na]
at graphql.validation.ValidationUtil.isValidLiteralValue(ValidationUtil.java:107) ~[graphql-java-9.2.jar:na]
at graphql.validation.ValidationUtil.isValidLiteralValue(ValidationUtil.java:141) ~[graphql-java-9.2.jar:na]
at graphql.validation.ValidationUtil.isValidLiteralValue(ValidationUtil.java:107) ~[graphql-java-9.2.jar:na]
at graphql.validation.rules.ArgumentsOfCorrectType.checkArgument(ArgumentsOfCorrectType.java:23) ~[graphql-java-9.2.jar:na]
at graphql.validation.RulesVisitor.checkArgument(RulesVisitor.java:98) ~[graphql-java-9.2.jar:na]
at graphql.validation.RulesVisitor.enter(RulesVisitor.java:65) ~[graphql-java-9.2.jar:na]
at graphql.validation.LanguageTraversal.traverseImpl(LanguageTraversal.java:33) ~[graphql-java-9.2.jar:na]
at graphql.validation.LanguageTraversal.traverseImpl(LanguageTraversal.java:38) ~[graphql-java-9.2.jar:na]
at graphql.validation.LanguageTraversal.traverseImpl(LanguageTraversal.java:38) ~[graphql-java-9.2.jar:na]
at graphql.validation.LanguageTraversal.traverseImpl(LanguageTraversal.java:38) ~[graphql-java-9.2.jar:na]
at graphql.validation.LanguageTraversal.traverseImpl(LanguageTraversal.java:38) ~[graphql-java-9.2.jar:na]
at graphql.validation.LanguageTraversal.traverse(LanguageTraversal.java:28) ~[graphql-java-9.2.jar:na]
at graphql.validation.Validator.validateDocument(Validator.java:42) ~[graphql-java-9.2.jar:na]
at graphql.GraphQL.validate(GraphQL.java:539) ~[graphql-java-9.2.jar:na]
at graphql.GraphQL.parseAndValidate(GraphQL.java:509) ~[graphql-java-9.2.jar:na]
at graphql.GraphQL.lambda$parseValidateAndExecute$3(GraphQL.java:490) ~[graphql-java-9.2.jar:na]
at graphql.execution.preparsed.NoOpPreparsedDocumentProvider.get(NoOpPreparsedDocumentProvider.java:11) ~[graphql-java-9.2.jar:na]
at graphql.GraphQL.parseValidateAndExecute(GraphQL.java:486) ~[graphql-java-9.2.jar:na]
at graphql.GraphQL.executeAsync(GraphQL.java:470) ~[graphql-java-9.2.jar:na]
at graphql.GraphQL.execute(GraphQL.java:401) ~[graphql-java-9.2.jar:na]
at graphql.servlet.GraphQLQueryInvoker.query(GraphQLQueryInvoker.java:92) ~[graphql-java-servlet-6.1.2.jar:na]
at graphql.servlet.GraphQLQueryInvoker.query(GraphQLQueryInvoker.java:88) ~[graphql-java-servlet-6.1.2.jar:na]
at graphql.servlet.GraphQLQueryInvoker.query(GraphQLQueryInvoker.java:39) ~[graphql-java-servlet-6.1.2.jar:na]
at graphql.servlet.AbstractGraphQLHttpServlet.query(AbstractGraphQLHttpServlet.java:265) ~[graphql-java-servlet-6.1.2.jar:na]
at graphql.servlet.AbstractGraphQLHttpServlet.lambda$new$2(AbstractGraphQLHttpServlet.java:183) ~[graphql-java-servlet-6.1.2.jar:na]
at graphql.servlet.AbstractGraphQLHttpServlet.doRequest(AbstractGraphQLHttpServlet.java:236) ~[graphql-java-servlet-6.1.2.jar:na]
at graphql.servlet.AbstractGraphQLHttpServlet.doRequestAsync(AbstractGraphQLHttpServlet.java:227) ~[graphql-java-servlet-6.1.2.jar:na]
at graphql.servlet.AbstractGraphQLHttpServlet.doPost(AbstractGraphQLHttpServlet.java:257) ~[graphql-java-servlet-6.1.2.jar:na]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:681) ~[tomcat-embed-core-9.0.56.jar:4.0.FR]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:764) ~[tomcat-embed-core-9.0.56.jar:4.0.FR]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
at org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:91) ~[spring-web-5.3.15.jar:5.3.15]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.15.jar:5.3.15]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.3.15.jar:5.3.15]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.15.jar:5.3.15]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.3.15.jar:5.3.15]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.15.jar:5.3.15]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.3.15.jar:5.3.15]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.15.jar:5.3.15]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:540) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:895) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1732) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
at java.base/java.lang.Thread.run(Thread.java:833) ~[na:na]

This is the graphqls file if needed:
type Query {
    user(id : Int) : UserResponse,
    userByEmail(email : String) : [UserResponse]
}

type Mutation {
    createUser(createUserRequest: CreateUserRequest) : UserResponse
    createEvent(createEventRequest: CreateEventRequest) : EventResponse
}

input CreateEventRequest {
    name: String,
    description: String,
    participants: [Participant],
    location: Location,
    duration: Duration,
    userId: Int
}

input Duration {
    start:Date,
    end:Date,
    entireDay:Boolean      ,
    recurringDate:Boolean
}

input Location {
    street:String ,
    streetNumber:String,
    country:String
}

input Participant {
    firstName: String,
    lastName: String
}

type UserResponse {
    id: Int,
    firstName: String,
    lastName: String,
    email: String
}

type EventResponse {
    id: Int,
    name: String,
    description: String,
    participantResponses: [ParticipantResponse],
    locationResponse: LocationResponse,
    durationResponse: DurationResponse,
    userResponse: UserResponse
}

type DurationResponse {
    id: Int
    start: Date
    end: Date
    entireDay: Boolean
    recurringDate: Boolean
}

type LocationResponse {
    id: Int,
    street: String ,
    streetNumber: String ,
    country: String
}

type ParticipantResponse {
    id: Int,
    firstName: String,
    lastName: String
}

input CreateUserRequest {
    firstName: String!,
    lastName: String!,
    email: String!
}

scalar Date

A: The parseLiteral method parameter is actually a node of the abstract syntax tree produced from parsing the GraphQL query. The method implementation should extract the literal value from the node:
@Override
public LocalDate parseLiteral(Object o) throws CoercingParseLiteralException {
  if (o instanceof StringValue) {
    var value = ((StringValue) o).getValue();
    try {
      return LocalDate.parse(value);
    } catch (DateTimeParseException e) {
      throw new CoercingParseLiteralException("Cannot parse [" + value + "] to LocalDate", e);
    }
  } else {
    throw new CoercingParseLiteralException(
        "Expected literal of type StringValue but was " + o.getClass());
  }
}

A: The GraphQL is sending the date string as full text as you have declared this as Date. Alternatively, you can declare start as String and parse the string to Date at Java end.
input Duration {
start: String,
end: String,
entireDay:Boolean      ,
recurringDate:Boolean

}


text:
Q: Android SQLite display item "details" In my project I have a SQLite DB with different rows. Right now I have a ListView that displays certain items of this database. Only the  rows name and city (in code named taskName and taskDate) are displayed in  these list items. Now I want to display a "detail" page of these items when you click them. So the detail page should contain/display all rows of the item clicked, not only "name" and "city". So far I have done this, but just the name and city are displayed in the detail activity via .getText().
These 2 rows I'm getting with intent.putExtra(), but I don't know how to display the other rows, because I can't access them with .getText() as they are not displayed in the ListView.
This is the code for my ListAdapter (if you need more code please tell me) :
public class ServiceAdapter extends ArrayAdapter<ServiceItem> {

    private List<ServiceItem> taskList;
    private Context context;

    public ServiceAdapter(Context context, List<ServiceItem> listItems) {
        super(context, R.id.listitem_taskitem, listItems);

        this.context = context;
        this.taskList = listItems;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;

        if (v == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = inflater.inflate(R.layout.service_task_list, null);
        }

        ServiceItem task = taskList.get(position);

        if (task != null) {
            TextView taskName = (TextView) v.findViewById(R.id.task_name);
            TextView taskDate = (TextView) v.findViewById(R.id.task_date);

            taskName.setText(task.getCity());
            taskDate.setText(task.getName());
        }

        return v;
    }
}

This is the detail activity so far:
public class ServiceDetails extends Activity  {

    private TextView city;
    private TextView name2;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setupUI();

        Bundle extras = getIntent().getExtras();
        String name = extras.getString("name").toString();
        String description = extras.getString("description").toString();

        city.setText(name);
        name2.setText(description);
    }

    private void setupUI() {
        setContentView(R.layout.activity_service_details);

        city = (TextView) findViewById(R.id.detailName);
        name2 = (TextView) findViewById(R.id.detailWww);
    }
}

A: I see that you have no idea on what you are doing :P
You have a ServiceItem list provided to your adapter and you view it.
When these items contain all the data fetched from database - then you can pass serialized object or all it's data to ServiceDetails activity.
When these items contain only information about name and city you have 2 options:

*

*Fill this data when you fill name and city (when it's not too big)

*In the ServiceDetails activity get object from database by it's name/id or anything you can grab.