text:
Q: Modify an element on-the-fly so it matches a given selector Let's say I've got element like:

and selector like:
#mydiv.super.another-class[some-attribute="true"]

I'd like to make my div match this selector. It would require

*

*Adding id mydiv

*Adding classes super, another-class

*Adding attribute some-attribute with value true
So final div would look like

Is there any way to do something like
$(".some-class").makeMatch('#mydiv.super.another-class[some-attribute="true"]');

That would parse selector and execute steps listed above for any valid selector?
I know I can do some function that will parse selector and do it, but selectors can be so complex and same selector may be composed in so many different ways that I've decided to try to find some solid existing solution.
Do you know anything like that, or maybe is there any native way?

Edit: According to comments I'll try to explain my question in different way.
The main point of problem is:
Is it possible to parse any valid selector with javascript to know what id, what classes and what attributes is it pointing?
So we'd have like
var selectorData = parseSelector('#my-id.class-one.class-two[attr-one="value-one"]');
selectorData.id //my-id
selectorData.classes //class-one class-two
selectorData.attributes["attr-one"] //value

Because having this data about selector it's very easy to make any element match it.

A: One possible approach, albeit with a somewhat naive approach, would be:
// create a jQuery plug-in, 'makeMatch()' and pass a selector
// string as an argument:
(function ($) {
    $.fn.makeMatch = function (selector) {
        // finding a string of one or more alphanumeric characters,
        // underscores and hyphens that starts with the '#' character,
        // using String.prototype.match() with a regular expression:
        var id = selector.match(/#[\w-]+/),
            // similar to the above, though this string starts with a
            // period (escaped with a back-slash because the period
            // is a special character in regular expressions), using
            // the 'g' (global) flag to retrieve all matching
            // sequences:
            classes = selector.match(/\.[\w-]+/g),
            // this string looks for strings starting with a '['
            // (again escaped because it's a special character) and
            // continuing until it matches a character that is *not*
            // ']':
            attributeValuePairs = selector.match(/\[[^\]]+/g);
        // if we have an 'id' sequence:
        if (id) {
            // assigning the found id sequence to the id variable
            // (preventing us from accessing a property of a null
            // object) after replacing the leading '#' character
            // with an empty string:
            id = id[0].replace(/^#/,'');
        }

        // iterating over the passed-in jQuery object, 'this' (here)
        // is the collection of nodes:
        return this.each(function () {
            // caching the current node found in the collection:
            var self = this;

            // if we have an id (it's not null):
            if (id) {
                // setting the id to that matched-id:
                self.id = id;
            }
            // if we have an array of classes:
            if (classes) {
                // adding the classes from the array, by joining
                // each class-string together with spaces and replacing
                // the period characters (though we could simply do:
                // classes.replace(/\./g,' ') instead):
                $(self).addClass(classes.join(' ').replace(/\./g, ''));
            }
            if (attributeValuePairs) {
                // creating a variable to avoid re-initialising a
                // variable within the forEach():
                var av;
                attributeValuePairs.forEach(function(avp) {
                    // replacing the initial '[' character from
                    // each element of the array with an empty string
                    // and splitting that string on the '=' character
                    // to form a two-part array (if a '=' character
                    // is found):
                    av = avp.replace(/^\[/, '').split('=');
                    // if we do have a two-part array:
                    if (av.length === 2) {
                      // setting the attribute held in 'av[0]' with
                      // the value held in 'av[1]' (after replacing
                      // any quotes held in that string):
                      self.setAttribute(av[0], av[1].replace(/"|'/g, ''));
                    }
                });
            }
        });
    };
})(jQuery);

(function($) {
  $.fn.makeMatch = function(selector) {
    var id = selector.match(/#[\w-]+/),
      classes = selector.match(/\.[\w-]+/g),
      attributeValuePairs = selector.match(/\[[^\]]+/g);
    if (id) {
      id = id[0].replace(/^#/,'');
    }
    return this.each(function() {
      var self = this;
      if (id) {
        self.id = id;
      }
      if (classes) {
        $(self).addClass(classes.join(' ').replace(/\./g, ''));
      }
      if (attributeValuePairs) {
        var av;
        attributeValuePairs.forEach(function(avp) {
          av = avp.replace(/^\[/, '').split('=');
          if (av.length === 2) {
            self.setAttribute(av[0], av[1].replace(/"|'/g, ''));
          }
        });
      }
    });
  };
})(jQuery);

$(".some-class").makeMatch('#mydiv.super.another-class[some-attribute="true"]');
div {
  border: 1px solid #000;
  width: 200px;
  height: 200px;
}

#mydiv.super.another-class[some-attribute="true"] {
  border: 2px solid red;
  background: transparent url(http://lorempixel.com/200/200/nightlife) 50% 50% no-repeat;
}

It's worth noting, though, that I've not addressed the issue of boolean attributes/properties (such as checked, selected, etc) or the ability to add attributes without a value. This could be done, I just don't have the time, as yet, to account for all the edge-cases that might be implied by such a feature.
References:

*

*JavaScript:

*

*Array.prototype.forEach().

*Array.prototype.join().

*Element.setAttribute().

*JavaScript Regular Expressions Guide.

*String.prototype.match().

*String.prototype.replace().

*jQuery:

*

*addClass().

*each().

*"How to create a basic [jQuery] plugin."

A: i have written you a small jquery function for that
$.fn.makeMatch = function(ids, classes, attr) {
    this.attr('id', ids).addClass(classes).attr(attr);
    return this;
}

you now just have to:
$('div').makeMatch('firstComesOneId', 'then classes seperated by space', {'data-arrayKey1' : 'value1', 'data-arrayKey2' : 'value2'})

that would output:

hope thats what you needed.

after the op told me this above is not the way he needs it ( althoug it works ) here is I HOPE the desired function he needs:
    $.fn.stringToObject = function(values) {

    var selectorData = [];

    var start_posID = values.indexOf('#') + 1;
    var end_posID = values.indexOf('.',start_posID);
    selectorData['id'] = values.substring(start_posID,end_posID);

    var classSplit = values.split('.');
    var classLength = classSplit.length -1;
    var attrSplit = values.match(/\[/g);
    var attrLength = attrSplit.length;

    var start_posClass = end_posID;
    var end_posClass = values.indexOf('[',start_posClass);
    var stringClass = values.substring(start_posClass, end_posClass);
    selectorData['classes'] = stringClass.replace(/\./g, " ");

    for (var i = 0; i <= attrLength; i++) {
        if (i == 0) {
            var start = values.indexOf('[') + 1;
        } else if(i == attrLength) {
            start = nextstart -1;
        } else {
            start = nextstart +2;
        }

        var end                 = values.indexOf(']',start);
        var newstring           = values.substring(start, end);
        var nextstart           = end;

        var newstringLength     = newstring.length;
        var firstPartOffset     = newstring.indexOf('=');
        var firstPart           = newstring.substring(0, firstPartOffset);
        var secondPart          = newstring.substring(firstPartOffset +1, newstringLength);

        selectorData[firstPart] = secondPart;

    };

    return selectorData;
}

here is how you use it:
var valueArray = $( "div" ).stringToObject('#mydiv.super.another-class[some-attribute1="true"][some-attribute2="truesdsda"][some-attribute3="trueasd"][some-attribute4="true"][some-attribute5="truedfg"]');

console.log(valueArray); // gives you everything
console.log(valueArray.id); // = gives you the id
console.log(valueArray.classes); // = gives you the classes
console.log(valueArray['some-attribute5']); // = gives you the value from some-attribute5

took me some time, i really hope that helps :)
greetings timmi

A: Hope it will work.
$(".some-class").addClass('super');
$(".some-class").addClass('another-class');
$(".some-class").attr('id','myDiv');
$(".some-class").attr('some-attribute',true);


text:
Q: trying to find asymptotic or approximate solutions to coupled diffusion-advection-decay equations I am trying to solve a set of diffusion-advection equations with coupled decay (see unanswered coupled diffusion-advection-decay equations). The equations are as follows:
\begin{align}
 u_t - \alpha u_{xx} + c u_x +\lambda (u-v) = 0 \tag{1}
\end{align}
\begin{align}
 v_t - \alpha v_{xx} - c v_x +\lambda (v-u) = 0 \tag{2}
\end{align}
on $\mathbb R \times \mathbb R_+$ with $\lambda \geq0$, $\alpha > 0$, $c>0$. The functions at $t = 0$ are
$~u(x,0) = \delta(x), ~x \in \mathbb R$ and $v(x,0) = -\delta(x), ~x \in \mathbb R$.
I'm interested in the steady state ($v_t = u_t = 0$). This can be solved analytically if $\lambda = 0$ (just two uncoupled diffusion-advection solutions).
Am I wrong to conclude that in steady state at large $x$ , $u = v$? The analytic solutions without $\lambda$ do not have $u = v$. What surprises me is that turning on $\lambda$ by even the smallest amount forces $u = v$. I've tried to tackle these numerically and I don't get $u=v$ but I think it's because of numerical accuracy.
I'm also interested in long-time dependence of the solutions. Numerically I find the power law behavior.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Batch change file extensions in Mac OS X? I used wget to download a website into a folder. When files have the same names, wget stores the new one as name.extension.#
Now I have hundreds of files like 1.jpg, 1.jpg.1, 1.jpg.2, etc.
How can I change every file with a .jpg* extension into plain .jpg?
EDIT: I used freeware NameChanger, which let me organize by EXIF data before changing the extension.

A: Use Name Mangler to do this. Shareware, but: Trial version: Name Mangler will work for 25 launches without limitation.
You can see the original and future file  names on the left, and the configuration of Number Sequentially I used on the right. Important here is to manually define .jpg suffix, and not appending the original extension.

The free NameChanger also can do this. (thanks slhck!)

A: I'm assuming you want 1.jpg.1 to be renamed to 1-1.jpg, or you'll lose them.
Quick and dirty comes to mind: just use sed to construct a shell script on the fly and have sh run it:
$ ls -1 *jpg* | sed -e 's@\(.*\)\(\.jpg\.\)\(.*\)@mv \1\2\3 \1-\3.jpg@' | grep ^mv | sh

Strongly suggest you check the output just before the sh to make sure it's actually going to do the right thing.

A: IFS=$'\n'; for f in `find . -name '*.jpg.*'`; do echo mv "$f" "`sed -E 's/(.*)\.jpg\.(.*)/\1-\2.jpg/' <<< "$f"`"; done
Another version that applies to files in all subfolders and should work with filenames that have spaces.

A: This is an easy to remember way of renaming multiple files in the Terminal:
rename 's/\.jpg.1/\.jpg/' *.jpg.1

Just put whatever extension after each /\. and make sure to specify the existing files in the second argument (*.jpg.1 in this case)


text:
Q: Echarts: How to disable zoom and animation in echarts treemap? link to example
In this example, I would like to fix treemaps position and disable zoom on mouse-scroll.
I would also like to prevent the animation when we click on a section of treemap.
I have tried to use 'zoomLock: true' and 'animation: false' in the options but couldnt achieve what i wanted

A: you can use roam: 'move' to disable zoom on mouse-scroll and u can try using nodeClick: false to prevent the animation when you click on a section of treemap
series: [
    {
      roam: 'move',
      nodeClick: false,
      ...
    }
]


text:
Q: Check if mouse is hovering on any object I have a jQuery animation example here: http://jsfiddle.net/p7Eta/
I would like all the titles to pop out if the mouse is not within the container div at all. I have tried to do something like:
$("#container").mouseout(

     function() {
    //slides spans up
    $('.popup').stop().animate({
        bottom: 0 + 'px'
    });

});

But it does not work with the prior animations. What is the correct way to achieve this effect?
EDIT: I'd like something similar to this: http://jsfiddle.net/RE3XK/ but on mouseover I'd like the individual span titles to pop up like in the first example instead of having them all dissapear

A: You mean like this.
Check working example http://jsfiddle.net/p7Eta/8/
Update
$("#slider div.popup").hover(
function() {

    //slides spans up
    $('span', this).animate({
        bottom: 0 + 'px'
    });
}, function() {

    //slides spans down
    $('span', this).animate({
        bottom: '-' + 200 + 'px'
    });
});

$(document).mouseover(
function(e) {
    e.stopPropagation()
    $('#slider div.popup').find(' span').animate({
        bottom: 0
    });
});

A: My guess is that you're going for something along the lines of this one, am I right? The only issue with the way I tried it, is that the element you're entering on, also slides down (which it shouldn't, I guess).

A: Finally, jsFiddle cooperated...
I'm doing something hacky, but it's the only way that I could get it to work. I had to add a .hover class to the currently hovered element, as my code doesn't work properly without it.
Just don't look at the code, and it'll look nice!
Here's a working example: http://jsfiddle.net/p7Eta/41/
And the code:
// JavaScript Document

//When div.popup is moused over moused over
$("#slider div.block").hover(

function() {

    //slides spans up
    $(this).addClass('hovered');
    $(this).find('span').stop().animate({
        bottom: '0px'
    });
}, function() {
$(this).removeClass('hovered');
    //slides spans down
    $(this).find('span').stop().animate({
        bottom: '-200px'
    });
});

$('#container').hover(function() {
    $('#slider div.block:not(.hovered) span').animate({
        bottom: '-200px'
    });
}, function() {
    $('#slider div.block span').stop().animate({
        bottom: '0px'
    });
});

A: Or something like this... which actually stops the animations before resetting it. http://jsfiddle.net/NDtMW/

A: Please clarify what you're asking for.  Do you

*

*want the animations to continuously so they're in constant motion whenever they're not hovered on?

*want them to be at the motion-up state whenever they're not hovered on?

BTW, your original script only works in IE.  If you're only concerned with one browser, please say so in the future.  IE users are probably the minority on SO.


text:
Q: Not able to load the saved graph using torch.utils.tensorboard.SummaryWriter.add_graph method I am saving the scalar summary along with model graph using  add_scalar and add_graph methods from torch.utils.tensorboard.SummaryWriter.
While running tensorboard on the summary file, it doesnt show the model graph. Just 2 small rectangle at the bottom right, However, it is able to show the scalar variable and images.
Sample code from the pytorch documentation attached
import torch
import torchvision
from torch.utils.tensorboard import SummaryWriter
from torchvision import datasets, transforms

# Writer will output to ./runs/ directory by default
writer = SummaryWriter()

transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))])
trainset = datasets.MNIST('mnist_train', train=True, download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True)
model = torchvision.models.resnet50(False)

print(model)

# Have ResNet model take in grayscale rather than RGB
model.conv1 = torch.nn.Conv2d(1, 64, kernel_size=7, stride=2, padding=3, bias=False)
images, labels = next(iter(trainloader))

grid = torchvision.utils.make_grid(images)
writer.add_image('images', grid, 0)
writer.add_graph(model, images)
writer.close()

Any pointer to the solution would be appreciated

PyTorch version - 1.2.0 Tensorboard version - 1.15.0a20190828

A: I had the same problem.
Check out this thread:
https://github.com/pytorch/pytorch/issues/24157
TLDR: Update PyTorch to PyTorch-nightly and the problem should be solved.
https://pytorch.org/get-started/locally/


text:
Q: How to use sklearn's Gaussian Process Regression parameters? I have been trying to play around with Gaussian process Regression. I have constructed a fake 1D data for this. I am using a Squared exponential kernel. I solved the regression problem using inbuilt sklearn.gaussian_process. Now, using these parameters I am simulating to check if I can get the original data with some error. This is where I am getting it wrong. I am not sure where it is wrong though.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import itertools
import sklearn.gaussian_process as gp
np.random.seed(42)

def y(x):
    return (x**3 + 3*(x**2) + 7*x + 4)

def kernel_function(x, y, const):
    """Define squared exponential kernel function."""
    kernel = const[0] * const[0] * np.exp(- (np.linalg.norm(x - y)**2) / (2 * const[1]*const[1]))
    return kernel

def compute_gpr_parameters(K):
        """Compute gaussian regression parameters."""
        n = K.shape[0]
        # Mean.
        f_bar_star = np.zeros((n,1))
        # Covariance.
        cov_f_star = K

        return (f_bar_star, cov_f_star)

def init_cov_mat(x, const):
    n = x.shape[0]
    K = [kernel_function(i, j, const) for (i, j) in itertools.product(x, x)]
    K = np.array(K).reshape(n, n)
    return K
n1 = 15
x1 = np.random.random(n1)
x1 = x1.reshape(-1,1)
y1 = u(x1).reshape(-1,1)
kernel = gp.kernels.ConstantKernel(1.0, (1e-3, 1e3)) * gp.kernels.RBF(10.0, (1e-3, 1e3))
model1 = gp.GaussianProcessRegressor(kernel=kernel, n_restarts_optimizer=10, alpha=0.1, normalize_y=True)
model1.fit(x1,y1)
params1 = model1.kernel_.get_params()
sigma_f = params1['k1__constant_value']**0.5
l = params1['k2__length_scale']
const = []
const.append(sigma_f)
const.append(l)

k1 = init_cov_mat(x1,const)

f_bar_star, cov_f_star = compute_gpr_parameters(k1)

fig, ax = plt.subplots(figsize=(12,6))
for i in range(0, 100):
    # Sample from posterior distribution.
    z_star = np.random.multivariate_normal(mean=f_bar_star.squeeze(), cov=cov_f_star)
    # Plot function.
    sns.lineplot(x=x1.reshape(-1), y=z_star, color="blue", alpha=0.2, ax=ax);

# Plot "true" linear fit.
sns.scatterplot(x=x1.reshape(-1), y=y1.reshape(-1), color='red', label = 'f(x)', ax=ax)
ax.set(title=f'sigma_f = {const[0]} and l = {const[1]}')
ax.legend(loc='upper left');

I am now crosschecking this with the GP model predict and plotting the mean, mean+2std, mean-2std.
y1_pred,std1 = model1.predict(x1,return_std=True)
std1 = std1.reshape(-1,1)
plt.figure(figsize=(12,6))
sns.scatterplot(x=x1.reshape(-1), y=y1_pred.reshape(-1), color='blue', label = 'GP prediction')
sns.scatterplot(x=x1.reshape(-1), y=y1.reshape(-1), color='red', label = 'actual data')
sns.scatterplot(x=x1.reshape(-1), y=(y1+2*std1).reshape(-1), color='yellow', label = 'pred+2*std')
sns.scatterplot(x=x1.reshape(-1), y=(y1-2*std1).reshape(-1), color='black', label = 'pred-2*std')

I would be more than happy if people could point out where I am doing wrong.


text:
Q: Python: Calling multiple recursions simultaniously I'm getting this error:
TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
For this code:
def a(n):
    if n < 0:
        return 0
    if n == 1:
        return 1
    if n > 1:
        return a(n-1) + a(n-2) + a(n-3)

How should I call multiple recursions?

A: You are missing the condition: - 1 > n >= 0. And thus, you are not returning any value in case your n >= 0 and n < 1.
May be your first condition is supposed to be: -
if n < 1:
    return 0

A: To elaborate on Rohit's answer: if a python function gets to the end without returning anything, then it implicitly returns None.  So a(0.5) will return None.  If you call eg a(1.5), then you'll end up with a(0.5)+a(-0.5)+a(-1.5) which evaluates to None+0+0 which gives you the error you describe.

A: The problem is when n = 0, there is no if statement to handle this, so the python function implicitly return a NoneType object, change it to this:
def a(n):
    if n <= 0:
        return 0
    if n == 1:
        return 1
    if n > 1:
        return a(n-1) + a(n-2) + a(n-3)

A: Try this:
def a(n):
    if n <= 0:
        return 0
    elif n == 1:
        return 1
    else:
        return a(n-1) + a(n-2) + a(n-3)

The trick is, that you have to cover all the possible values. You weren't covering n == 0, and the last condition should be an else, so it's explicit that there can be no other choices.
Notice that the error unsupported operand type(s) for +: 'int' and 'NoneType' happened before because if none of the conditions was met (for example, when n == 0) then None was returned, and at some point in the recursion an int was added to None, causing the error. This is why it's important to be very exhaustive when covering all possibilities in a recursion, making sure that all possible cases are being considered.
And by the way: something tells me that you're missing one case. What happens if n == 2? there should be yet another case for handling this.


text:
Q: heroku web crashes So I'm following the tutorial in this link: https://devcenter.heroku.com/articles/django#deploy-to-heroku
once i do "heroku ps" i get:
=== web: `python manage.py runserver 0.0.0.0:$PORT --noreload`
web.1: crashed 2013/02/18 20:22:37 (~ 8m ago)

I don't exactly understand what is the problem here, can someone help? am i suppose to have my Procfile where manage.py is? I tried to move it over to there, but the same error still shows up.
btw my logs are:
2013-02-19T04:36:22+00:00 heroku[api]: Scale to web=1 by deathlordx87@yahoo.com
2013-02-19T04:41:14+00:00 heroku[api]: Scale to web=1 by deathlordx87@yahoo.com
2013-02-19T04:43:10+00:00 heroku[web.1]: State changed from crashed to starting
2013-02-19T04:43:17+00:00 heroku[web.1]: Starting process with command `python manage.py      runserver 0.0.0.0:31831 --noreload`
2013-02-19T04:43:18+00:00 app[web.1]: python: can't open file 'manage.py': [Errno 2] No such file or directory
2013-02-19T04:43:19+00:00 heroku[web.1]: Process exited with status 2
2013-02-19T04:43:19+00:00 heroku[web.1]: State changed from starting to crashed
2013-02-19T04:44:05+00:00 heroku[api]: Scale to web=1 by deathlordx87@yahoo.com

A: I faced the same problem once. You need to configure your settings.py file properly. Since Heroku doesn't support sqlite3 databases so you should check that the database portion of the settings.py file is configured correctly.
Check my minimal sample app successfully deployed to Heroku https://github.com/shinigamiryuk/Django-Heroku-Sample-Application

A: The log line can't open file 'manage.py' suggests that the file is missing or can't be found. Did you add manage.py to your git depo before deploying to heroku? Is manage.py stored in a different directory from your Procfile/where the program runs?

A: I suspect your project (if it follows the Two Scoops layout) has manage.py inside a project directory and not in your repository root.
To keep this layout, create a Procfile and within it script a directory change before running gunicorn.
See this answer for an example.


text:
Q: Change screen resolution and size of all items when a specific application starts My problem is that I am using a hiDPI screen with resolution 3200x1800 but when I launch some specific application, I cannot use this resolution because the text is too small.  I tried to change the resolution to 1920x1800 and changed the size of all items from 200% to 150% from Control Panel\Appearance and Personalization\Display.  The application works fine at these settings.  Is there a way to automatically change the resolution and size to this one when I launch a specific application?
I want it to be changed when I start that specific application, and then returned to 3200x1800 when the application is closed.

A: You could always create a batch script that

*

*Changes the screen resolution

*Launches the application

*Changes the resolution back when the application is terminated.

To do this you would want to download Qres then create a .bat script with the following:
@echo off
Qres.exe /x:1920 /y:1080
applicationYouWantToLaunch.exe
Qres.exe /x:3200 /y:1800

A: Might try checking the 'Let me chose one scaling level for all my displays' setting in Control Panel>Appearance and Personalization>Display.  This will disable Windows' automatic per-app HiDPI scaling and allow you to set one single scaling level for all programs.  I prefer this over allowing Windows to 'guess' when it should use HiDPI scaling.  With this setting, I find less dramatic difference between HiDPI and non-HiDPI-aware apps.
I also found http://www.atrandom.iansharpe.com/setres.php


text:
Q: Autodesk Forge API with Codeigniter class MyClass extends CI_Controller
{
    function __construct(){

        parent::__construct();
        $this->load->library('ForgeApi');
    }

    public function save(){

        $this->func("test_bucket_name");

    }//save

}//End of class

ERROR MESSAGE
Unable to locate the specified class: Session.php
I am trying to integrate forge API with coeigniter
Can you please help me to resolve this issue or at least put me on the right path.
Thx


text:
Q: Password fields attribute not rendering correctly registration page Django I'm creating a registration page in Django and everything works fine, and gets rendered correctly except the password fields. Why can that due to? I've tried building a form without the inbuild Django methods but it doesn't work either. It is very weird as I think all the code is working fine and everything is build correctly.
Here is the html:

Create an Account!

                            <form class="user" method="POST">
                              {% csrf_token %}

                                      {{ form.first_name }}

                                        {{ form.last_name }}

                                  {{ form.email }}

                                      {{ form.password1 }}

                                        {{ form.password2 }}

                                <button type="submit" class="btn btn-primary btn-user btn-block">
                                    Register Account
                                </button>

                                     Register with Google

                                     Register with Facebook

                            </form>

                                Forgot Password?

                                Already have an account? Login!

Here is the forms.py:
from django.forms import ModelForm
from django.contrib.auth.forms import UserCreationForm
from django import forms
from django.contrib.auth.models import User
from django.forms import ModelForm, TextInput, PasswordInput, EmailInput
from django.contrib.auth import get_user_model

class CreateUserForm(UserCreationForm):
    class Meta(UserCreationForm.Meta):
        model = get_user_model()
        widgets = {
            'first_name': TextInput(attrs={'class': 'form-control form-control-user', 'placeholder': 'First Name'}),
            'last_name': TextInput(attrs={'class': 'form-control form-control-user', 'placeholder': 'Last Name'}),
            'email': EmailInput(attrs={'class': 'form-control form-control-user', 'placeholder': 'Email Address'}),
            'password1': PasswordInput(attrs={'class': 'form-control form-control-user', 'placeholder': 'Password'}),
            'password2': PasswordInput(attrs={'class': 'form-control form-control-user', 'placeholder': 'Repeat Password'}),
        }
        fields = ['first_name', 'last_name', 'email']

Here is the models.py
from django.db import models
from django.contrib.auth.forms import UserCreationForm
from django import forms
# Create your models here.
class User(models.Model):
    first_name = models.CharField(max_length=40000)
    last_name = models.CharField(max_length=40000)
    email = models.EmailField(max_length=40000)
    password1 = models.CharField(max_length=40000)
    password2 = models.CharField(max_length=40000)

class Emails(models.Model):
    name = models.CharField(max_length=40000)
    urls = models.URLField(max_length=200)
    emails = models.TextField()

    def __str__(self):
        return self.name

Here is the register page:
def register(request):

    if request.user.is_authenticated:
        return redirect('login')
    else:

        form = CreateUserForm()
        if request.method == 'POST':
            form = CreateUserForm(request.POST)
            if form.is_valid():
                form.save()
                messages.success(request, 'Account was created for' + user)
                return redirect('login')

    context = {'form':form}

    return render(request, 'leadfinderapp/register.html', context)

A:
EDIT

The parts you added allowed me to reproduce the problem
This works for me
class CreateUserForm(UserCreationForm):
    class Meta(UserCreationForm.Meta):
        model = get_user_model()
        widgets = {
            'first_name': TextInput(attrs={'class': 'form-control form-control-user', 'placeholder': 'First Name'}),
            'last_name': TextInput(attrs={'class': 'form-control form-control-user', 'placeholder': 'Last Name'}),
            'email': EmailInput(attrs={'class': 'form-control form-control-user', 'placeholder': 'Email Address'}),
        }
        fields = ['first_name', 'last_name', 'email']

    def __init__(self, *args, **kwargs):
        super(CreateUserForm, self).__init__(*args, **kwargs)
        self.fields['password1'].widget = PasswordInput(
            attrs={'class': 'form-control', 'placeholder': 'Password'})
        self.fields['password2'].widget = PasswordInput(
            attrs={'class': 'form-control', 'placeholder': 'Repeat Password'})

The answer is taken from here:


text:
Q: DeepStack custom model building on GPULab fails I'm trying to use GPULab environment to build a custom model for DeepStack. It fails with the following error:
[W NNPACK.cpp:79] Could not initialize NNPACK! Reason: Unsupported hardware.
Traceback (most recent call last):
  File "deepstack-trainer/train.py", line 530, in <module>
    train(hyp, opt, device, tb_writer, wandb)
  File "deepstack-trainer/train.py", line 90, in train
    model = Model(opt.cfg or ckpt['model'].yaml, ch=3, nc=nc).to(device)  # create
  File "/home/jovyan/deepstack-trainer/models/yolo.py", line 96, in __init__
    self._initialize_biases()  # only run once
  File "/home/jovyan/deepstack-trainer/models/yolo.py", line 151, in _initialize_biases
    b[:, 4] += math.log(8 / (640 / s) ** 2)  # obj (8 objects per 640 image)
RuntimeError: a view of a leaf Variable that requires grad is being used in an in-place operation.

Looking around, people are treating the NNPACK as a warning to be dismissed, but in my case it ends with RuntimeError: a view of a leaf Variable that requires grad is being used in an in-place operation.. Not sure how to continue (if possible).
All project's packages in requirements.txt were satisfied and the environment do hold CUDA and cuDNN

A: Apparently the NNPACK error (warning) is not related to the part comes after.
The real error is the second part and is due to incompatible pytorch versions as was found and stated on this closed issue by @marcokloeckler
running @marcokloeckler proposal:
pip install torch==1.7.1+cu110 torchvision==0.8.2+cu110 torchaudio==0.7.2 -f https://download.pytorch.org/whl/torch_stable.html

downgrade the pytorch version on GPULab environment and allowed the project to run.


text:
Q: Growpart throws unexpected error "unexpected output in sfdisk --version" I am trying to grow GPT table for enlarged QEMU virtual disk. But when running growpart, it throws:
~ growpart /dev/sda 2
unexpected output in sfdisk --version [sfdisk,来自 util-linux 2.36.2]

Where is it wrong?

A: The problem lies at the fact that I am using zh_CN.UTF8 as locale. growpart checks sfdisk's output but didn't take other languagues in consideration.
To mitigate this, just add LANG=en_US.UTF-8 at the beginnning:
~ LANG=en_US.UTF-8 sudo growpart /dev/sda 2
[sudo] password for root:
CHANGED: partition=2 start=1026048 old: size=187717599 end=188743647 new: size=535844831 end=536870879


text:
Q: JAVA two-dimensional array страны Всем доброго времени суток. Столкнулся с задачей по JAVA и не могу с ней разобраться.
Есть такой массив:
String[][] arr = {
        {"Kenya", "Nairobi"}, {"Rwanda", "Kigali"},
        {"Gambia", "Banjul"}, {"Ghana", "Accra"},
        {"Niger", "Niamey"}, {"Zambia", "Lusaka"}
};

Нужно, чтобы программа запрашивала название страны и выводила её столицу. Если данной страны не существует, то вывести соответствующее сообщение.

A: public static String getCapital(String[][] arr){
    for (String[] countryCapital: arr) {
        if (countryCapital[0].equals("Rwanda")){
            return countryCapital[1];
        }
    }
    return "no country";
}

input думаю понятно как сделать

A: Можно из этого массива собрать карту:
String[][] arr = {
        {"Kenya", "Nairobi"}, {"Rwanda", "Kigali"},
        {"Gambia", "Banjul"}, {"Ghana", "Accra"},
        {"Niger", "Niamey"}, {"Zambia", "Lusaka"}
};

Map<String, String> map = new HashMap<>() {
    @Override
    public String get(Object key) {
        return super.getOrDefault(key, "Такой страны не существует");
    }
};

map.putAll(Arrays.stream(arr)
        .collect(Collectors.toMap(row -> row[0], row -> row[1])));

System.out.println(map.get("Kenya")); // Nairobi
System.out.println(map.get("Zambia")); // Lusaka
System.out.println(map.get("Лфв2ыло")); // Такой страны не существует

A: String countryName = getCountryNameFromConsole;
for(String country : arr) {
   if (country.name is countryName)
       then return countryCapital;
}

return some errorMessage;

думаю алгоритм понятен


text:
Q: Jquery hover hide/show: setTimeout clearTimeout So I have an element(link) that controls the visibility of another element(target) by hovering on it.
When the the mouse hovers the link the target is supposed to turn to visible and when the mouse leaves the target is supposed to turn invisible after 2 seconds.
So far so good. But how do I make it so that if the mouse goes hover the visible target before the 2 seconds go up, the target stays visible?
I got it to sort of work with setTimeout and clearTimeout but its really buggy and it doesn't feel good at all.
var time = 1000;
$(".link").hover(

      function () {
        $('.target').css('display', 'none');
        clearTimeout($(this).data('timeout'));
          $('.target').css({'display': 'block'});
      },

      function () {

        var timer = setTimeout(function() {$('.target').fadeOut(1000).delay(100).css('display', 'none'); clearTimeout(timer); }, time);

        $('.target').hover(
              function () {
                clearTimeout(timer);
              },
              function () {
                var timer = setTimeout(function() {$('.target').fadeOut(1000).delay(100).css('display', 'none'); clearTimeout(timer); }, time);
              }
            );
      }

);

(http://jsfiddle.net/VfDkq/)
Any help would be greatly appreciated.
Cheers

A: Try re-factoring your code a bit:
(function() {

    var time = 1000,
        timer;

    function handlerIn() {
        clearTimeout(timer);
        $('.target').stop(true).css('opacity', 1).show();
    }
    function handlerOut() {
        timer = setTimeout(function() {
            $('.target').fadeOut(3000);
        }, time);
    }

    $(".link, .target").hover(handlerIn, handlerOut);

}());

Live demo
This should be really close to your described behavior. I've also added an extra line to display it right back when you mouseenter while it's fading out, as you can see in the handlerIn.

A couple mistakes that I took away from your code:

*

*You had another timer var declared inside one of the mouseleave handlers, which couldn't be cancelled anywhere. The timer must be accessible in a common scope;

*You were applying animation delays before the synchronous method .css, which has no effect;

*There's no point to set the display to none after a fadeOut has completed, it automatically does so;

*There's no point to clear a setTimeout after it has executed either.

A: You are using too much delays and fadeout durations. Browsers do not like it. Do you mind using hide() instead of those?
http://jsfiddle.net/VfDkq/4/
  var timer = setTimeout(function() {$('.target').hide().css('display', 'none'); clearTimeout(timer); }

Or you can lessen delay time and fadeout duration.


text:
Q: how to access specific control in datatemplate generated listbox So i have dataTemplate generated listbox like this:
<ListBox.ItemTemplate>
    <DataTemplate>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition />
            <ColumnDefinition />
            <ColumnDefinition />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <Rectangle Fill="{Binding color}" Height="10" Width="10" Grid.Column="1"/>
        <TextBlock Text=" " Grid.Column="2"/>
        <TextBlock Text="{Binding ID}" FontSize="10" FontWeight="Bold" Grid.Column="3"/>
    </Grid>
    </DataTemplate>
</ListBox.ItemTemplate

and I bind it to ObservableCollection. I need to access specific item in this listbox and change colour of its rectangle element.

A: I would use a StyleSelector. make a styleselector like this:
ListViewItemStyleSelector.cs
public class ListViewItemStyleSelector : StyleSelector
{
    public override Style SelectStyle(object item,
         DependencyObject container)
    {
         Style st = new Style();
         st.TargetType = typeof(ListViewItem);
         Setter backGroundSetter = new Setter();
         backGroundSetter.Property = ListViewItem.BackgroundProperty;
         ListView listView =
             ItemsControl.ItemsControlFromItemContainer(container)
              as ListView;
        int index =
        listView.ItemContainerGenerator.IndexFromContainer(container);
        if (index % 2 == 0)    <-- here your own criteria
        {
            backGroundSetter.Value = Brushes.LightBlue;
        }
        else
        {
            backGroundSetter.Value = Brushes.Beige;
        }
        st.Setters.Add(backGroundSetter);
        return st;
    }
 }

use of the styleselector
xaml
<ListView
      ItemsSource="{Binding Source={StaticResource EmployeeData},
                                    XPath=Employee}"
      ItemContainerStyleSelector="{DynamicResource myStyleSelector}" >
  <ListView.View>
    <GridView>
      <GridViewColumn DisplayMemberBinding="{Binding XPath=FirstName}"
                  Header="First Name" Width="120"/>
      <GridViewColumn DisplayMemberBinding="{Binding XPath=LastName}"
                  Header="Last Name" Width="120"/>
      <GridViewColumn DisplayMemberBinding="{Binding XPath=FavoriteCity}"
                  Header="Favorite City" Width="120"/>
    </GridView>
    </ListView.View>
</ListView>


text:
Q: How to make vue app tree-shake to get smaller files? I have created an app using Vue CLI 3, I have been watching the build and it warned me there are large files:
$ vue-cli-service build --modern --mode production --dest dist --target app --dashboard

-  Building legacy bundle for production...

 WARNING  Compiled with 2 warnings12:40:54 PM

 warning

asset size limit: The following asset(s) exceed the recommended size limit (244 KiB).
This can impact web performance.
Assets:
  js/chunk-vendors-legacy.443e5f8f.js (1.44 MiB)

 warning

entrypoint size limit: The following entrypoint(s) combined asset size exceeds the recommended limit (244 KiB). This can impact web performance.
Entrypoints:
  app (1.46 MiB)
      js/chunk-vendors-legacy.443e5f8f.js
      js/app-legacy.4b3e4352.js

I have no idea how to reduce this file size, it comes completely from external libs:

I assumed it could not be gotten rid of. Just today I did the "Coverage" tool in chrome and it shows that its mostly unused. How do I get rid of this unused code to make my app load faster?
I am already gzipping, my question is more about how to actually make those files tree-shake to drop in file size.


text:
Q: jQuery extend $.fn and calling method syntax I understand that you call a method like this when you are extending $.fn.
( $ == jQuery )
//$("div").myMethod();

$.fn.extend({
   myMethod: function(){...}
});

And like this when you extend the jQuery Object:
//$.myMethod2();

$.extend({
    myMethod2: function(){...}
});

But I don't quite understand what the $() is doing here:
// There are a few methods being called here. Some with the same method name (initiate) which is bad.
// But maybe that is why the blank jQuery object is needed so the method names don't clash
$(function() {

    $().functionName({
      something: 'something'
    }).myMethod();

    $().func1({
      x: 1
    }).initiate();

    $().func2({
      y: 2
    }).initiate();

});

Does it have to do with the fact the method is being called including the function name?
Thanks in advance and hope this makes sense.

A: $() creates an empty jQuery object (wrappet set). I wouldn't know why someone would do something like this. Basically, you're calling functionName and myMethod on an empty set of elements = nothing should happen.
jQuery().css({
   'foo': 'bar'
}).show();

A: Before jQuery 1.4 calling jQuery() would have been the same as jQuery(document). Since then it's been changed to return an empty set instead. So since jQuery 1.4, jQuery() is the equivalent of jQuery([]). Even so, the latter was and is the recommended way of getting an empty set just to make sure not to confuse anyone.
Anyways, my guess is that the code you're asking about is old, and uses a deprecated way to access the document node, not to mention that it is/was a bad practice to do so even back then. $() is probably supposed to be $ or $(document).
But, that's not to say that an empty jQuery set is wrong or useless. Adam Kiss have written a post on his blog about the usefulness of empty sets.
And finally, some other ways to extend jQuery:
(function($){
    $.myMethod = function() {
    };

    $.fn.myMethod = function() {
    };
})(jQuery);


text:
Q: Thomson's Plum Pudding and Rutherford's scattering Why did Rutherford's scattering experiment disprove the plum pudding? Assuming a gold-atom to be a large homogeneous ball and hitting it with small homogenuous $\alpha$-balls should lead to the actually observed scattering angle distribution, why would anyone assume that the $\alpha$-particles would go through the gold-atom (am I right that back then the idea was that the gold atom is indeed a more or less solid ball)?

A: wiki:
At the time of the experiment, the atom was thought to be analogous to a plum pudding (as proposed by J. J. Thomson), with the negatively-charged electrons (the plums) studded throughout a positive spherical matrix (the pudding). If the plum-pudding model were correct, the positive "pudding", being more spread out than in the correct model of a concentrated nucleus, would not be able to exert such large coulombic forces, and the alpha particles should only be deflected by small angles as they pass through.
However, the intriguing results showed that around 1 in 8000 alpha particles were deflected by very large angles (over 90°), while the rest passed through with little deflection. From this, Rutherford concluded that the majority of the mass was concentrated in a minute, positively-charged region (the nucleus) surrounded by electrons.


text:
Q: Managing consistency in distributed database I have question regarding system design. Lets say I want to design a Flight booking system ( such as American Airlines). So, consistency when booking a ticket is very important. This booking system is also used across the world. A high level view of the system would look some thing like below (lets say servers are in NYC-New York).

Consider that people from Germany, USA , Canada all uses this system .
In this case would every user ( booking the same flight AE-101 on a given day) across the world would be hitting the same load balancer and then same DB ( present in NYC).
OR
Do we maintain the distributed copy of DB across multiple regions so that clients from Europe hit a different Load Balancer and clients from Canada hit a different one. If that's the case how do we maintain consistency over geographically separated master DB. Does the write server waits until all the replicas of DB present across the world gets updated?

A: This depends on the consistency guarantees you want to fulfil. There are many different consistency models, but some are easier to achieve than others.
Normally, the use of read replicas is consistent in the sense that the read replica sees an older but consistent state of the primary database. So transactions are either successful or they aren't applied at all, all constraints are still satisfied. Different read replicas may represent snapshots at different points in time. Writes must be executed on the primary node. Some databases may wait to confirm a transaction until all replicas are up to date, but of course that slows down writes a lot.
This model works fairly well if you have way more reads than writes. But it can violate other consistency models. If a user observes the state in replica A and then in replica B, they might see different states. When they apply a modification on the primary and then observe the state of the replica, the replica might not yet know about that state.
If you want to have multiple database nodes to handle writes, then things get very tricky. This is not impossible, just difficult to do efficiently. At best, you can simply shard your booking database e.g. by flight number, so that for every booking there is only a single authoritative node. Google's Cloud Spanner uses sharding in combination with distributed locks and consensus protocols such as Paxos with the result that most writes can be executed on nearby nodes, without acquiring locks on all nodes.
But all of that is too complicated:

*

*a single database server to handle writes, with reasonable hardware and a reasonable schema design, is likely able to handle the entire write load. Bookings involve money so are somewhat rare, compared to truly web-scale problems like Twitter or analytics.

*there's no problem by keeping your database in a single geography. Sucks for users for Australia due to increased latencies, but is much more efficient than trying to maintain consistency in a globally distributed database. If you do want to go down the route of globally distributed writes, definitely use an existing cloud service like Cloud Spanner.

*the flight booking industry doesn't offer such strong consistency at the business level, so trying to guarantee strong consistency on the database level is a bit pointless. Airlines routinely overcommit bookings in order to ensure a full plane despite no-shows. Bookings are sold through a complex network of affiliates and partners that makes it nigh impossible to get a consistent view of bookings – this is instead resolved at check-in time.
This doesn't mean that inconsistency is OK, but that the technical solution must be aligned with the business processes.


text:
Q: PDO: Using same bind variable multiple times I'm having an issue with PDO Prepared statements, where if you need to use the same bind variable multiple times, the query won't validate.
Example:
$params = array (
    ':status' => $status,
    ':userid' => $_SESSION['userid']
);

$stmt = $pdo->prepare ('
    INSERT INTO
        tableName
        ( userId, status )
        VALUES
        ( :userid, ":status" )
        ON DUPLICATE KEY UPDATE
            status = ":status"
');

if ( ! $stmt->execute ( $params ))
{
    print_r( $stmt->errorInfo ());
}

EDIT: The values of the $params are:
Array ( [:status] => PAID [:userid] => 111 )
EDIT 2:
I've noticed that instead of the original values, instead of userid, 0 is inserted, and instead of status an empty string is inserted.

A: Problem was the quotes around the :status. Removed quotes and all is good.

A: Your array keys don't need to contain a colon.  The colon is purely for PDO to know that what follows is a named parameter.
$params = array (
    ':status' => $status,
    ':userid' => $_SESSION['userid']
);

should be
$params = array (
    'status' => $status,
    'userid' => $_SESSION['userid']
);

A: You're not calling the bindParam method anywhere, why? Just before you invoke execute, try adding
$stmt->bindParam(':userid', $_SESSION['userid'], PDO::PARAM_INT);
$stmt->bindParam(':status', $status, PDO::PARAM_STR);

And then just call $stmt->execute(); see how that works for you. Also turn your error messages up to full, and after instantiating your PDO instance, add this $db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); to ensure errors are always thrown.
the docs are handy things

A: Works fine for me. E.g.
<?php
$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'localonly', 'localonly');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
setup($pdo);

echo 'client version: ', $pdo->getAttribute(PDO::ATTR_CLIENT_VERSION), "\n";
echo 'server version: ', $pdo->getAttribute(PDO::ATTR_SERVER_VERSION), "\n";
echo "before:\n";
foreach( $pdo->query('SELECT * FROM tmpTableName', PDO::FETCH_ASSOC) as $row ) {
    echo join(', ', $row), "\n";
}

$status = 1;
$_SESSION['userid'] = 'foo';

$params = array (
    'status' => $status,
    'userid' => $_SESSION['userid'],
);

$stmt = $pdo->prepare ('
    INSERT INTO
        tmpTableName
        (userId, status)
    VALUES
        (:userid, :status)
    ON DUPLICATE KEY UPDATE
        status = :status
');

if ( ! $stmt->execute ( $params ))
{
    print_r( $stmt->errorInfo ());
}

echo "after:\n";
foreach( $pdo->query('SELECT * FROM tmpTableName', PDO::FETCH_ASSOC) as $row ) {
    echo join(', ', $row), "\n";
}

function setup($pdo) {
    $pdo->exec('
        CREATE TEMPORARY TABLE tmpTableName (
            userId varchar(32),
            status int,
            unique key(userId)
        )
    ');
    $pdo->exec("INSERT INTO tmpTableName (userId,status) VALUES ('foo', 0)");
    $pdo->exec("INSERT INTO tmpTableName (userId,status) VALUES ('bar', 0)");
}

prints
client version: mysqlnd 5.0.10 - 20111026 - $Id: b0b3b15c693b7f6aeb3aa66b646fee339f175e39 $
server version: 5.5.25a
before:
foo, 0
bar, 0
after:
foo, 1
bar, 0

on my machine


text:
Q: Integrated-circuit identification I need help identifying two SMD parts. One says (1G5) and the other says (1P)
 they each have six pins.

A: *

*The 1P could be one  of several things You'll have to try matching the circuit around it to the various components.

*1G5 isn't coming up anywhere for a 6 pin device.


text:
Q: Thymleaf how to take an input and then redirect to another page I'm learning Spring boot. I have a list of products with unique ids, and I want to implement a "lookup by id" functionality, but I don't know how to do it, I searched but got totally different stuff.
I already have a @Getmapping method like this:
@Getmapping(/products/{id})

If I manually type in the id in the url I'll get what I what. But I want to have an input box in the HTML page like:
<form>
   Look up by id: <input/>
</form>

and after I submit the form it'll redirect to that page. For example, if I enter input of 1, it'll go to localhost:8080/products/1
I've been searching but all I got was stuff about @Postmapping.

A: Add a @PostMapping to your controller:
@Controller
@RequestMapping("/products")
public class ProductController {

  @GetMapping //Controller method for showing the empty form
  public String index(Model model) {
    model.addAttribute("formData", new SearchFormData()); // Create an empty form data object so Thymeleaf can bind to it

    return "index";
  }

  @PostMapping
  public String searchById(SearchFormData formData) {
    return "redirect:/products/" + formData.getId(); //Use the value the user entered in the form to do the redirect
  }

  @GetMapping("/{id}")
  public String showProduct(@PathVariable("id") long id) {
    ...
  }
}

With SearchFormData representing the form fields (there is only 1 field in this case):
public class SearchFormData {
  private long id;

  // getters and setters

And update Thymeleaf template like this:
<form th:action="@{/products}" th:method="post" th:object="${formData}">
  <input th:field="*{id}" type="number">
  <button type="submit">Search</button>
</form>

Note that the value of th:object needs to match with the name used to add the SearchFormData instance to the model.
See Form handling with Thymeleaf for more info.

A: The following simple code will direct you to a URL that is generated from a concatenation of the base address of the <form>'s action attribute and the value of its first <input>:

document.querySelector("form").addEventListener("submit",function(ev){
 ev.preventDefault();
 this.action="/product/"+this.querySelector("input").value;
 console.log(this.action);
 // in real code: uncomment next line!
 // this.submit()
})
<form>
   Look up by id: <input type="text" value="123" />
</form>

In the real code you will delete the console.log() und uncomment the following line: this.submit().
Alternatively you could also do:
document.querySelector("form").addEventListener("submit",function(ev){
 ev.preventDefault();
 location = "/product/"+this.querySelector("input").value;
})

This will redirect you to the page without actually submitting the form.


text:
Q: Filtering items in list view using query string - FilterName & FilterMultiValue 32 values limit? Basically what I am trying to do is to filter list view using query string parameters FilterName=ID & FilterMultiValue=1;2;3;...
Let say we have list with default view. We want to filter items in this view by ids. URL will look like this:
http://server/sites/bla/Lists/MyListWithItems/AllItems.aspx?FilterName=ID&FilterMultiValue=2;3;4;5;6;7;8;9;10;11;12;13;14;15;16;17;18;19;20;21;22;23;24;25;26;27;28;29;30;31;32;33;

*

*We have 32 ids in query string param - This shows correct items on the first page but on next pages items are not filtered.

*If I add one more item id to FilterMultiValue param (in total 33 ids in query string param) items are not filtered at all. Is like the parameter and values in FilterMultiValue are ignored.

Have anyone encountered this issue before? Is this bug in list view web part or am I doing something wrong here?
I tried to use Query String (URL) filter web part connected to list view web part but I couldn't make it to filter by multiple values.
Thanks


text:
Q: Irritating Google API Client (Java) Issues So what I'm doing requires that I hit a document with the google sheets api, grab a sheet, pull data from it, and generate another sheet. So initially I followed an example using a service account as follows:
@Bean(name = "google-creds")
@DependsOn(value = {"google-http-transport", "google-data-store", "json-factory"})
public GoogleCredential authorize(HttpTransport transport, JsonFactory factory) throws Exception {
    // Load client secrets.
    InputStream in = new FileInputStream(new File("config/oauth.json"));
    return GoogleCredential.fromStream(in, transport, factory).createScoped(SCOPES);
}

My oauth.json file is using the json files generated in the API console credentials tab. I generated a service account as instructed...I was a bit dubious.
I was able to pull data from the document I wanted, and I was able to create another document. However from what I can tell there is no possible way to view documents created with a service account. Which...I mean that makes it completely and utterly useless. If there is a way where I can view these documents from the master account the service account was created with that'd be fantastic. A few google answers seem to imply this is not possible however.
So alright I decided how about I try using a client ID from the master account. I download the json file provided and...it errors and says unknown field 'type'. So..I guess it serializing using the RuntimeTypeAdapter from gson or something. So it's completely incompatble with the credential format from the master account.
So next I tried to do this
    @Bean(name = "google-creds")
    @DependsOn(value = {"google-http-transport", "google-data-store"})
    public Credential authorize(HttpTransport transport) throws Exception {
        // Load client secrets.
        InputStream in = new FileInputStream(new File("config/oauthnew.json"));
        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JacksonFactory.getDefaultInstance(), new InputStreamReader(in));
        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(transport, factory, clientSecrets, SCOPES)
                .setDataStoreFactory(new MemoryDataStoreFactory()).build();
        Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
        return credential;
    }

So I hadn't really read into this, and it turns out it creates a local jetty server for...some inexplicable reason. It also asks me to go visit a URL which then bitches about redirects. I have no desire for any kind of redirection, or...anything outside of parsing and making a goddamned spreadsheet. Also visiting a URL is already a deal breaker if it requires the account to be authenticated already. This needs to run programmatically once every 10 minutes or so.
Further, when I used the upper example I couldn't find anywhere to configure sharing or permissions in any way shape or form. Google usually has good APIs, but this is the single most irritating API I've used in nearly a decade of Java development. I just need to be able to A) Parse sheet A B) Create sheet B if necessary and C) Be able to view sheet B
Can someone point me in a direction that doesn't have me screaming at my monitor?

A: Service account is used to access user date programatically and it hasn't got its own documents / drive. You need to provide the email address of a user while creating GoogleCredential. Than the service account will access that user document required (Granted that it has Domain wide delegation enabled). There is currently an open issue with the GoogleCredentials fromStream, please have a look at  (work around it) https://github.com/google/google-api-java-client/issues/1007#issuecomment-318493967
If the user account is a gsuite account you can give the service account permission to the scopes through the Google Admin console https://admin.google.com/
For details on domain wide delegation and granting access, please have a look at https://developers.google.com/admin-sdk/directory/v1/guides/delegation
In order to view a document that was created by Service account with domain wide delegation you will have to access it with the user account.
Now in case of an account that you can grant access to with Google admin console, you will have to use the flow (your second approach). This will unfortunately require that you will have to grant permission to the documents through the url provided. You could store the tokens once the permission is granted, that way there would be no need to repeat this process.


text:
Q: How can I retrieve contents from a URL when I click on a link using jQuery? I have the following HTML:

Login

What I need to do is when the user clicks on the div then I
want to call the URL "/User/Account/Login" and then get the
contents. I have the following code but I am not sure. Do I
need to use Ajax and if so how can I code it to call the URL.
   $('#loginLink')
      .click(function () {

      return false;
      });

I want to take the contents and place these inside this HTML:

Any advice on how I can do this would be much appreciated.

A: You may use data to get the href and load to load the content :
 $('#loginLink').click(function () {
     $('#article').load($(this).data('href'));
     return false;
  });

A: Use jQuery 'Load' function  here is a link to the documentation

A: Since it's located on the same origin, you can use jQuery's load() function:
$('#loginLink').click(function (e) {
    e.preventDefault();
    $('#article').load('/User/Account/Login');
});


text:
Q: Automating Salesforce to Salesforce with Apex I came across Rakesh' Salesforce-to-Salesforce sharing through Flow & Process.  But I am curious on how to get it down with Apex.
I was able to create this trigger and save it:
trigger AutoShareOpportunity on Opportunity (after insert) {

    List<PartnerNetworkConnection> connMap = new List<PartnerNetworkConnection>(
    [select Id, ConnectionStatus, ConnectionName from PartnerNetworkConnection
        where ConnectionStatus = 'Accepted']
);
for(PartnerNetworkConnection network : connMap) {
     PartnerNetworkRecordConnection newrecord = new PartnerNetworkRecordConnection();

    newrecord.ConnectionId = network.Id;
    newrecord.LocalRecordId =OpportunityId;
    newrecord.RelatedRecords = 'Contact,Opportunity,Orders__c';
    newrecord.SendClosedTasks = true;
    newrecord.SendOpenTasks = true;
    newrecord.SendEmails = true;

    insert newrecord;
}

But I am getting the following error:

Apex trigger AutoShareOpportunity caused an unexpected exception, contact your administrator: AutoShareOpportunity: execution of BeforeInsert caused by: System.DmlException: Insert failed. First exception on row 0; first error: INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY, Insufficient access on the entity.: []: Trigger.AutoShareOpportunity: line 19, column 1

A: You can't share a record before it's been inserted and has an Id. Your line newrecord.LocalRecordId = tid; wouldn't appear to have an Id on before insert. From the Object Reference on PartnerNetworkConnection, note the following:

*

*To share a record, use the following fields: LocalRecordID and ConnectionId

*To share a child of a parent record, use the following fields: LocalRecordID, ConnectionId, and ParentRecordID

*To share a child of a parent record and its child records, use the following fields: LocalRecordID, ConnectionId, ParentRecordID, and RelatedRecords

Here's some sample sharing code from the Object Reference that could be used within your trigger that once you modified it for AfterInsert, instead of BeforeInsert:
List<PartnerNetworkConnection)> connMap = new List<PartnerNetworkConnection>(
    [select Id, ConnectionStatus, ConnectionName from PartnerNetworkConnection
        where ConnectionStatus = 'Accepted']
);
for(PartnerNetworkConnection network : connMap) {
     PartnerNetworkRecordConnection newrecord = new PartnerNetworkRecordConnection();

    newrecord.ConnectionId = network.Id;
    newrecord.LocalRecordId = accountId;
    newrecord.RelatedRecords = 'Contact,Opportunity,Orders__c';
    newrecord.SendClosedTasks = true;
    newrecord.SendOpenTasks = true;
    newrecord.SendEmails = true;

    insert newrecord;
}


text:
Q: WPF - Image hide userControl : how access the userControl contextMenu? In my application I have a userControl and some images on a canvas.
The userControl can be moved and has a contextMenu.
Everything work well, but sometimes an image has a zIndex higher than the zIndex of the userControl (I can see the userControl because the image has an reduced opacity). As the control is hidden by the image, I no longer have access to the contextMenu. It's logical, the right click event is linked to the image and not the userControl.
There is the possibility to disable the events on the image, and activate the events on the userControl ?
Or may be it is possible to translate the event on the image to the userControl ?
Thanks you for your help
Damien
PS : I hope my english is not too bad.

A: Try setting IsHitTestVisible="False" on the image.


text:
Q: Why is the front camera (CAMERA_FACING_FRONT) not detected? I'm trying to get pictures using front camera (selfie) and back camera and save it to an imageview. When I tried to take a picture using the front camera (selfie) the image is getting flipped upside down (vertical) and when using the back camera, the image is getting flipped horizontally.
I'm trying to detect the camera usage using "camInfo.facing ==(Camera.CameraInfo.CAMERA_FACING_FRONT" and "camInfo.facing ==(Camera.CameraInfo.CAMERA_FACING_BACK" but only "camInfo.facing ==(Camera.CameraInfo.CAMERA_FACING_BACK" is working. I hope I can give some rotation to get it to work.
Dont know how to proceed. Help much appreciable.
compileSdkVersion 28
    defaultConfig {
        applicationId "com.austurn.keikonew.keiko"
        minSdkVersion 19
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"

 @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data){

        try {
                if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
                    Uri uri = photoURI;
                    Bitmap myImg = BitmapFactory.decodeFile(photoFile.getAbsolutePath());
                    Matrix matrix = new Matrix();
                    int width = myImg.getWidth();
                    int height=myImg.getHeight();
                    Camera cam = null;
                    Camera.CameraInfo cameraInfo = new Camera.CameraInfo();

                        Camera.CameraInfo camInfo = new Camera.CameraInfo();

                        if (camInfo.facing ==(Camera.CameraInfo.CAMERA_FACING_FRONT)) {
                            matrix.postRotate(90);
                            Toast.makeText(this.getActivity(), "Front camera", Toast.LENGTH_LONG).show();
                             }

                        if (camInfo.facing ==(Camera.CameraInfo.CAMERA_FACING_BACK)) {
                            Toast.makeText(this.getActivity(), "back camera", Toast.LENGTH_LONG).show();
                            float[] mirrorY = { -1, 0, 0, 0, 1, 0, 0, 0, 1};
                            Matrix matrixMirrorY = new Matrix();
                            matrixMirrorY.setValues(mirrorY);
                            matrix.postConcat(matrixMirrorY);
                            matrix.postRotate(270);
                        }

                    Bitmap bitPicFinal = Bitmap.createBitmap(myImg, 0, 0, width, height,matrix, true);
                    myImg.recycle();
                    int desWidth;
                    int desHeight;
                    desWidth = bitPicFinal.getWidth();
                    desHeight = desWidth;
                    Bitmap croppedBitmap = Bitmap.createBitmap(bitPicFinal, 0,bitPicFinal.getHeight() / 2 - bitPicFinal.getWidth() / 2,desWidth, desHeight);
                    croppedBitmap = Bitmap.createScaledBitmap(croppedBitmap, 528, 528, true);
                    camview.setImageBitmap(croppedBitmap);
                }
        }catch(Exception e){
            Toast.makeText("Something went wrong", Toast.LENGTH_LONG).show();
        }
    }
}

A: You are creating a new instance of Camera.CameraInfo that does not actually refer to the camera that was used to capture photo.
You should use exif metadata contained in the captured file, try the solution described here:
Why does an image captured using camera intent gets rotated on some devices on Android?

A: The Camera.CameraInfo() default constructor says nothing about the actual device you use. One should fill this object using Camera#getCameraInfo() static method. Then, you would know whether the camera device at index 1 is facing back or front, and also have the hardware orientation of this device, which can help to adjust the images taken by this camera through Camera API.
This orientation info is irrelevant for images received via ACTION_IMAGE_CAPTURE intent, because the Camera app may choose to rotate or not to rotate the Jpeg before storing it to the MediaStore.
On most devices, the EXIF of stored image will have some indication of front or back-facing camera, but there is no officially documented way to determine this.
Note that the EXIF orientation "0" does not mean "portrait", it means that the Jpeg is stored in a natural way, and shoudl be displayed without adjusting orientation. If you get an image with orientation "0" and width < height, then it's portrait; if you get an image with orientation "0" and width > height, it's landscape.


text:
Q: Passing data from one view to email template view on checkbox checked in code-igniter I'm using a code-igniter to develop an web application. I'm trying to create a dynamic email template which loads data dynamically when I'm check a checkbox from other view.
Here is my scenario:

If I'm checking a checkbox for HMO_001, then all data that will loaded in the table for HMO_001 will pass to my email template, and when I'm click on Send button the mail will send to particular landlord.
Now I'm able to send an email to multiple landlords at a time on button click when I'm check multiple checkbox, but the email is hard coded. I'm trying to make it dynamic, but no success.
Here is my Code:
Controller to load table data:
public function index()
    {
        # code...
        $user = $this->ion_auth->user()->row();
        $data['username'] = $user->username;
        $data['user_id'] = $user->id;

        $landlord = $this->input->post('landlord_id');
        $property = $this->input->post('property_id');
        $certificate = $this->input->post('certificate_id');

        if( $landlord =='') {
            $landlord = 0;
        }
        if($property == ''){
            $property = 0;
        }
        if($certificate == ''){
            $certificate = 0;
        }

        $data['landlords'] = $this->c->landlordList();
        //$data['properties'] = $this->c->propertyList();
        $data['certificates'] = $this->c->certificateList();
        //$data['certified'] = $this->c->certificate_List();

        $data['certified'] = $this->c->getcertificateByLandlordProperty($landlord, $property, $certificate);

        // print_r($data['landlords']);
        // print_r($data['properties']);
        // echo "
";
        // print_r($data['certificates']);
        // echo "
";
        // exit();
        $data['title'] = 'Certificate List';

        $this->load->view('template/header', $data);
        $this->load->view('certificate/certificate_list', $data);
        $this->load->view('template/footer');
    }

Controller to send mail:
public function sendMail()
    {
        # code...
        //$data['certified'] = $this->c->getcertificateByLandlordProperty($landlord, $property, $certificate);

        if(isset($_POST['submit'])){//to run PHP script on submit
            if(!empty($_POST['sendMail'])){
            // Loop to store and display values of individual checked checkbox.
                foreach($_POST['sendMail'] as $selected){
                    //echo $selected."
";
                }
            }
        }

        $email_to = $this->input->post('sendMail[]');

        $body = $this->load->view('emailTemplate/certTemplate', $data);

        $this->load->library('email');
        $config = array();
            $config['protocol'] = 'mail';
            $config['smtp_port'] = 587;
            $config['smtp_host'] = 'smtp.office365.com';
            $config['smtp_user'] = 'info@admin.com';
            $config['smtp_pass'] = '**********';
            $config['smtp_crypto'] = 'STARTTLS';
            $config['newline'] = "\r\n"; //REQUIRED! Notice the double quotes!
            $config['crlf'] = "\r\n";
            $config['mailtype'] = "html";

        $this->email->initialize($config);

        $this->email->from('info@admin.com', 'Administrator');
        $this->email->to($email_to);
        $this->email->subject('Your Subject');
        $this->email->message('$body');

        $sent = $this->email->send();

        if ($sent)
        {
            echo 'OK, mail send successfully';

        } else {
            echo $this->email->print_debugger();
        }
    }

Any kind of help is welcome, Thanks in advance.

A: To make a customized email message template, you could do like it this :
1. Move each recipient part to foreach loops that you've made prevously, this way you know each of email to recipient that is not being sent.
2. Add a third TRUE parameter on message $body (to return data as a string & not sending it to browser).
3. Add clear() method so each recipient only receive their customized message (to prevent showing all recipients on each recipient).
public function sendMail()
{
    # code...
    //$data['certified'] = $this->c->getcertificateByLandlordProperty($landlord, $property, $certificate);

    if(isset($_POST['submit'])){//to run PHP script on submit
        if(!empty($_POST['sendMail'])){
            $this->load->library('email');
            $config = array();
            $config['protocol'] = 'mail';
            $config['smtp_port'] = 587;
            $config['smtp_host'] = 'smtp.office365.com';
            $config['smtp_user'] = 'info@admin.com';
            $config['smtp_pass'] = '**********';
            $config['smtp_crypto'] = 'STARTTLS';
            $config['newline'] = "\r\n"; //REQUIRED! Notice the double quotes!
            $config['crlf'] = "\r\n";
            $config['mailtype'] = "html";

            $this->email->initialize($config);

            // Loop to store and display values of individual checked checkbox.
            foreach($_POST['sendMail'] as $selected){
                $data['email_to'] = $selected;

                $body = $this->load->view('emailTemplate/certTemplate', $data, TRUE); // the TRUE parameter will return data as a string instead of sending it to browser (access recipient email on certTemplate with $email_to variable)

                $this->email->clear();
                $this->email->from('info@admin.com', 'Administrator');
                $this->email->to($email_to);
                $this->email->subject('Your Subject');
                $this->email->message($body); // remove quotes from $body

                $sent = $this->email->send();

                if ($sent)
                {
                    echo 'OK, mail send successfully';

                } else {
                    echo $this->email->print_debugger();
                }
            }
        }
    }

}

Hope it helps..


text:
Q: Criteriabuilder DATE comparison I would like to compare a date to a timestamp in the database. I currently use
predicates.add(criteriaBuilder.between(eventRoot.<Date>get("time"), dBegin, dEnd));

*

*dBegin = Thu Feb 04 00:00:00

*dEnd = Thu Feb 04 23:59:59

eventRoot
private Date time;

I also tried formatting the date with the following format, to no success.
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

And changing
predicates.add(criteriaBuilder.equal(eventRoot.<String>get("time"), curDformat));

where curDformat is the formatted date to
2016-02-04

And changing the type to String in my eventRoot.
How would I go about only checking the date with the database? And would this improve performance or is it fine doing it with between?

A: SimpleDateFromat dateFormat = new SimpleDateFromat("yyyy-MM-dd hh:mm:ss");
Date dBegin = dateFormat.parse("2018-02-04 00:00:00");
Date dEnd = dateFormat.parse("2018-02-04 23:59:59");

predicates.add(criteriaBuilder.between(<Date>get("time"), dBegin, dEnd));

You could use between, it works too.

A: The criteriaBuilder predicate for date comparison without time
cb.equal(cb.function("date", Date.class, myObj.get("createdAt")), cb.function("date", Date.class, cb.literal(new Date())));

It produces the following SQL where clause.
where date(myObj0_.created_at)=date(?)


text:
Q: Ruby on Rails Active Admin: Email Not Displaying after Login So I have a regular user, an admin user, and an oauth user type.  I changed quite a few things to get them to work right, but now active admin is no longer displaying the email address in the upper-right hand corner when logging in.
My apps/admin/user.rb (formerly admin_user.rb) is just the regular ActiveAdmin user... so no point in posting that.
Here's the file that has changed (users.rb in the models.)
class User < ActiveRecord::Base
acts_as_voter

devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable

# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :provider, :uid, :name,     :remember_me
# attr_accessible :title, :body
has_many :posts
has_many :tasks
has_many :dailies
has_many :authentications

 def self.create_with_omniauth(auth)
   create! do |user|
   user.provider = auth['provider']
   user.uid = auth['uid']
   user.password = user.password_confirmation = SecureRandom.urlsafe_base64(n=6)
   if auth['info']
     user.name = auth['info']['name'] || ""
     user.email = auth['info']['email'] || ""
   end
   end
  end
 end

Am I missing an index or something?
I tried adding:
index({ email: 1 }, { unique: true, background: true })

But it told me the index method was not defined...
(While I'm at it I should also ask: How does that function work? How do I get the current users email/username to display somewhere after a successful login? And how do I get a "login" link to switch to a "logout" link once you're logged in?)

A: Ok. This should be simple enough.
Anyone with a three-stage user solution (users, admin users, oauth users) might run into this problem. (I only discovered the solution after finally getting Oauth to work.) After getting something like OmniAuth working the tendency is for Active-Admin to default to the Name (i.e. Facebook username) instead of the email address. This is why it shows nothing for your normal users because, by default, they don't have usernames. Just email addresses.
All you have to do is find the part of the code where it's setting the display to name and switch it back to email. (wherever that may be in your case.)


text:
Q: use `exivtool` to rename Photos by location This is how you can rename all Jpegs in a folder by geolocation and date:
exiftool '-filename<${gpslatitude;} ${gpslongitude} ${datetimeoriginal}' -d "%Y-%m-%d %H.%M.%S%%-c.%%e" *.JPG

this results in very long filenames like
53 33 36.95000000 N 9 58 29.37000000 E 2015-11-04 19.22.49.JPG

How can I use the short locations instead? So it would result in
53.560308 9.975458 2015-11-04 19.22.49.JPG

Or even better, Is it possible to get and add the City of the geolocation and add it to the name?

A: This will result in a shorter version:
exiftool -coordFormat '%.4f' '-filename<${gpslatitude;} ${gpslongitude} ${datetimeoriginal}_$filename' -d "%Y-%m-%d_%H.%M.%S%%-c.%%e" *.JPG

But it still adds the compass point N,E,S or W
If you want to add the city, this could be added with a loop, using the nominatim API:
#!/bin/bash
#exiftool '-filename<${datetimeoriginal}_$filename' -d "%Y-%m-%d_%H.%M.%S%%-c.%%e" *.JPG
for f in *.JPG; do
  echo "$f"
  LAT="$(exiftool -coordFormat '%.4f' "$f"|egrep 'Latitude\s+:'|cut -d\  -f 23)"
  if [ "$LAT" == "" ]; then
    echo 'no geo coordinates';
  else
    LON="$(exiftool -coordFormat '%.4f' "$f"|egrep 'Longitude\s+:'|cut -d\  -f 22)"
    URL='http://nominatim.openstreetmap.org/reverse?format=xml&lat='$LAT'&lon='$LON'&zoom=18&addressdetails=1'
    RES="$(curl -s "$URL"|egrep "<(city|village|town|ruins|state_district|country)")"
    LOC="$(echo "$RES"|grep '<city>'|sed 's/^.*<city>//g'|sed 's/<\/city>.*$//g')"
    if [ "$LOC" == "" ]; then
      LOC="$(echo "$RES"|grep '<city_district>'|sed 's/^.*<city_district>//g'|sed 's/<\/city_district>.*$//g')"
    fi
    if [ "$LOC" == "" ]; then
      LOC="$(echo "$RES"|grep '<village>'|sed 's/^.*<village>//g'|sed 's/<\/village>.*$//g')"
    fi
    if [ "$LOC" == "" ]; then
      LOC="$(echo "$RES"|grep '<town>'|sed 's/^.*<town>//g'|sed 's/<\/town>.*$//g')"
    fi
    if [ "$LOC" == "" ]; then
      LOC="$(echo "$RES"|grep '<ruins>'|sed 's/^.*<ruins>//g'|sed 's/<\/ruins>.*$//g')"
    fi
    if [ "$LOC" == "" ]; then
      LOC="$(echo "$RES"|grep '<state_district>'|sed 's/^.*<state_district>//g'|sed 's/<\/state_district>.*$//g')"
    fi
    if [ "$LOC" == "" ]; then
      LOC="$(echo "$RES"|grep '<country>'|sed 's/^.*<country>//g'|sed 's/<\/country>.*$//g')"
    fi
    if [ "$LOC" == "" ]; then
      echo "no city found at $URL";
    else
      BASE="${f%.*}"
      mv -v "$f" "$BASE-$LOC.JPG"
    fi
  fi
done

When you are done, you can count your images by location with
ls -1|cut -d- -f 4|sort|uniq -c|sort -n


text:
Q: Create a new user's profile from the command line I am creating an installation script that should create a few users, and set some registry settings for them. In order to use reg.exe to modify their registry, I need to have the location of their ntuser.dat, normally residing in the users' home directories.
The home directories are only created during the users' first login, which is a little late for my batch file. I don't wish to have to log into each user.
Is there a way to create the home directories without logging into the users?
I assume it would involve copying the "\Users\Default" directory, but what else needs to be done?
This question is similar to mine, but does not refer to the registry.

A: To store default user-settings for new users the registry-key HKEY_USERS -> .DEFAULT was made.
http://blogs.technet.com/b/chad/archive/2012/04/25/tip-49-how-do-you-set-default-user-profile-registry-settings.aspx
But this approach works for all users logged in from the point of change.
If you want to add registry-entries for particular users of your (Active Directory-)Domain then you should have a look at Group Policies http://en.wikipedia.org/wiki/Group_Policy

A: i think what you need might be /homedir and /profilepath switches of net user command, you can find full help on syntax in net help user output
ps:
you can also try making user directories using mkdir before creating accounts and then add users


text:
Q: Installing signal handler inside handler of another signal, is it possible? I have to write a stack crawler/traceback code. I am installing my own sigsegv handler. All works fine as long as my traceback is not called from another handler.
More precisely, if my traceback is called from another handler (lets say for SIGALRM) where that handler blocks all other signals , my handler for sigsegv does not get invoked. I understand that this is be because of the previous handler blocking all other signals (please correct me if i am wrong). I want to understand, if my handler for sigsegv will even be installed or not? Because even though the my handler is not invoked the pending bit for sigsegv should be set for that process and once the current handler (for SIGALRM) finishes at least that time my handler should be invoked.
Also, is there a way to I can ensure that SIGSEGV will be caught in this case where traceback is being called from another handler which has blocked that signal.
Thanks.


text:
Q: How to efficiently do a R Shiny comma hunt I have packaged a shiny app with all good check on Windows (0 error, 0 warning, 0 note). The app works fine on my windows computer and install also without problem using :
remotes::install_local("my_app.tar.gz")

I have then attempted to dockerize this app. This is something I have done before with success so I am looking for a R code error, but who knows here is my Dockerfile :
FROM rocker/tidyverse:3.6

RUN apt-get update && apt-get install -y libv8-3.14-dev
RUN apt-get install -y xdg-utils --fix-missing && apt-get install -y apt-utils

# === R packages dependency
RUN R -e 'install.packages("pacman")'

RUN R -e "pacman::p_load('DT')"
RUN R -e "pacman::p_load('circlize')"
RUN R -e "pacman::p_load('data.table')"
RUN R -e "pacman::p_load('dplyr')"
RUN R -e "pacman::p_load('DT')"
RUN R -e "pacman::p_load('ggplot2')"

# === To use shiny package ===
COPY my_app_*.tar.gz  /app.tar.gz
RUN R -e "remotes::install_local('/app.tar.gz')"

# --- stuff to have it running whith docker run

This gives the error message on the linux container while installing the package :
* installing *source* package my_app ...
** using staged installation
** R
** inst
** byte-compile and prepare package for lazy loading
Error in tag("div", list(...)) : argument is missing, with no default
Error: unable to load R code in package my_app
Execution halted
ERROR: lazy loading failed for package

Believed cause of problem : I have seen from an other SO question here that I should look for an extra comma lurking somewhere in the UI code.
Actual question : could anyone advise a way to solve this in an easier way than checking all my UI files for that/those extra comma(s) please ? I though of writing a function that parse and trim white spaces then look for 2 successive commas symbol but I am not sure how to begin...
Thanks in advance !


text:
Q: 'MySQL server has gone away' after Flask app restart I believe the problem of 'MySQL server has gone away' error is quite common but what I've found related to long running or long not used application.
In my case the issue happens mainly only after the application is (re)started. First several requests are failed with that error and then everything is ok.
I have pool_pre_ping: true set as suggested in SQLAlchemy docs. But it doesn't seem to help.
Also it happens only at the production server and never dev.
I don't use Session object. Instead I initialise the SQLAlchemy in __init__.py:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()

def create_app():
  flask_app = Flask(__name__)
  db.init_app(flask_app)


text:
Q: how to remove association in sequelize without extra query? I have many to many association between exercise and muscle models.
I remove single association
models.Exercise.find({where: {id: exerciseId}})
                .then(function(exercise){
                    exercise.removeMuscle(muscleId);
                    res.sendStatus(200);
                });

ORM runs 3 queries and 2 of them are similar
Executing (default): SELECT `Muscule`.`id`, `Muscule`.`title`, `Muscule`.`description`, `Muscule`.`video`, `Muscule`.`createdAt`,
    `Muscule`.`updatedAt`, `muscle_exercise`.`createdAt` AS `muscle_exercise.createdAt`, `muscle_exercise`.`updatedAt` AS `muscle_
    exercise.updatedAt`, `muscle_exercise`.`MusculeId` AS `muscle_exercise.MusculeId`, `muscle_exercise`.`ExerciseId` AS `muscle_exercise.ExerciseId` FROM `Muscules` AS `Muscule` INNER JOIN `muscle_exercise` AS `muscle_exercise` ON `Muscule`.`id` = `muscle_exercise`.`MusculeId` AND `muscle_exercise`.`ExerciseId` = 11;

 Executing (default): SELECT `Muscule`.`id`, `Muscule`.`title`, `Muscule`.`description`, `Muscule`.`video`, `Muscule`.`createdAt`,
    `Muscule`.`updatedAt`, `muscle_exercise`.`createdAt` AS `muscle_exercise.createdAt`, `muscle_exercise`.`updatedAt` AS `muscle_
    exercise.updatedAt`, `muscle_exercise`.`MusculeId` AS `muscle_exercise.MusculeId`, `muscle_exercise`.`ExerciseId` AS `muscle_exercise.ExerciseId` FROM `Muscules` AS `Muscule` INNER JOIN `muscle_exercise` AS `muscle_exercise` ON `Muscule`.`id` = `muscle_exercise`.`MusculeId` AND `muscle_exercise`.`ExerciseId` = 11;

    Executing (default): DELETE FROM `muscle_exercise` WHERE `ExerciseId` = 11 AND `MusculeId` IN (52)

Is there any way to avoid duplicate query? And it would be perfect if I can escape first and second query and run only third one that actually do something useful?

A: You can do it like in documentation using set function passing array of associated objects without the one you try to remove. But this basically leaves you with three queries anyways.
In order to make it in just one DELETE query you need to add a tie model in your code. In your case it will look something like this:
models.Exercise = sequelize.define("exercise", {
   /* attributes */
});

models.Muscle = sequelize.define("muscle", {
   /* attributes */
});

models.exercise_muscle_tie = sequelize.define("exercise_muscle_tie", {
}, {
    freezeTableName: true
});

models.Exercise.belongsToMany(models.Muscle, { as: 'muscles', foreignKey: 'exerciseId', through: models.exercise_muscle_tie });
models.Muscle.belongsToMany(models.Exercise, { as: 'exercises', foreignKey: 'muscleId', through: models.exercise_muscle_tie });

After you defined it and associated it with belongsToMany to the models your remove script will be:
models.exercise_muscle_tie.destroy({ where: { exerciseId: 1856, muscleId: 57344 } })

Generated SQL:
Executing (default):
DELETE FROM `exercise_muscle_tie` WHERE `exerciseId` = 1856 AND `muscleId` = 57344


text:
Q: want to update only value element of specific key on mongodb I have a dataset like this:
{
    "_id" : ObjectId("5a7bee68996b551034015a15"),
    "sequenceid" : 1,
    "fruit" : [
        {
            "name" : "@APPLE",
            "value" : 2
        },
        {
            "name" : "@BANANA",
            "value" : 1
        },
        {
            "name" : "@ORANGE",
            "value" : 5
        }
}

want to update only Apple value i.e from 2 to 25. Expected result will be:
{
    "_id" : ObjectId("5a7bee68996b551034015a15"),
    "sequenceid" : 1,
    "fruit" : [
        {
            "name" : "@APPLE",
            "value" : 25
        },
        {
            "name" : "@BANANA",
            "value" : 1
        },
        {
            "name" : "@ORANGE",
            "value" : 5
        }
}

I tried the code but this will replace all entry and do only one entry. My code is
db.Collection.update({'sequenceid': 1}, {$set: {'fruit' : {'name': '@APPLE', 'value': parseFloat(25)}}}, function(error, result){
  if(error){
console.log('error');
} else {
 console.log('success');
}
});

It can produce the result:
{
    "_id" : ObjectId("5a7bee68996b551034015a15"),
    "sequenceid" : 1,
    "fruit" : [
        {
            "name" : "@APPLE",
            "value" : 25
        }
}//Delete all my rest entry

How I can Do this. I am a newbie on MongoDB

A: This will update only the first occurrence of record.For reference MongoDB - Update objects in a document's array (nested updating)
db.collection.update({ _id: ObjectId("5a7bf5586262dc7b9f3a8422") ,"fruit.name" : "@APPLE"},
   { $set:
      {
       "fruit.$.value" : 25

      }
   })

A: If you are writing JavaScript query then you can update like this

 db.collection.find({'sequenceid': 1}).forEach(function(x){
        x.fruit.forEach(function(y){
                if(y.name=="@APPLE")
                {
                    y.value = 25
                }
            })
        db.collection.update({_id:x._id},x)
    })

A: db.Collection.update({
            _id: ObjectId("5a7bee68996b551034015a15"),
            "fruit": {
                $elemMatch: {
                    "name": "@APPLE"
                }
            }
        }, {
            $set: {
                "fruit.$.value": 25

            }
        })

In above update operation $elemMatch operator is used to search a value in an array and in $set stage positional operator $ is used to update value of specific key belonging to an array element


text:
Q: How to position sidebar in bootstrap? I'm trying to position sidebar on the right side in a site based on Bootstrap grid.
Well, this is very simplified layout that I've made - jsFiddle
I admit it's not the good use of bootstrap classes (rows etc.) but it works.
The problem is: the sidebar html code must be under the text and content (because of SEO), so it must be somehow positioned next to content (class .content).
I tried positioned it as an relative element but didn't have any luck.

*

*The text in .text div does not have static height, it will change

*The .content will have same height every time

A: Is this more what you were after?

Main

Lorem

sidebar

jsFiddle
Basically I've split your entire container 3 to 9, and then made your 'content' and 'text' blocks children of the '9' column. I then applied both the pull-left and pull-right class to the relevant containers.
I also fixed up your HTML a bit as it was missing a div tag. I also got rid of some of the text to make the code more readable to me!


text:
Q: Compile Linux executable with specific version number
Possible Duplicate:
How to specify the library version to use at link time?

Resolved in question:
How to specify the library version to use at link time?
Thank you.
probably is lame question, but I have no answer after couple hours of searching.
I have two libraries in /usr/lib/
libmy.so.0.0.0
libmy.so.0 -> libmy.so.0.0.0
libmy.so.1.0.0
libmy.so.1 -> libmy.so.1.0.0
libmy.so -> libmy.so.1.0.0
I have an app, whose next branch builds against version 1.0.0, and current branch builds against 0.0.0. But I can't tell the compiler which version I want to compile against. E.g. I cant say -lmy.so.1
Is there a way of doing that in Linux?


text:
Q: Supported music files by BASS audio library Is there any way to know if a file extension is supported by Bass audio library (such as WAV/AIFF/MP3/MP2/MP1/OGG )? I would like to write a function like :
Public void  Play(string File)
{
   if(IsSupportedFile(file)
     {

       // Add the appropriate code to play the file
     }

}
Public bool isSupported(string File)
{
  // Should return true if the file extension is supported by bass audio and add ons
}

A: Give this a try:
Public bool isSupported(string File)
{
  return Un4seen.Bass.Utils.BASSAddOnIsFileSupported(Nothing, file);
}


text:
Q: problem in ajax while passing parameter..404 not found ajax 404 not found while passing a parameter...but it works when i didnt pass a parameter..plz help. onchange i want the items of selected event.
view
        echo $this->Html->image("/images/loader/loader.gif", array("alt" => "", 'class' => 'loader', 'id' => 'ajximg2', 'style' => 'display:none'));
            echo $this->Form->input('item_id', array('label' => 'Competition Name', 'empty' => '-----Select-----', 'id' => 'item'));

controller:
public function event_item_ajax($eventId) {
        $items = $this->Item->find('list', array('conditions' => array('Item.event_id' => $eventId)));
        $this->set('items', $items);
    }

Jquery:
$(function() {
    $( "#event").change(function( event ) {
        $("#ajximg2").show();
        alert($(this).val());
        $.ajax({
            url: '/results/event_item_ajax/' +escape( $(this).val()),
            cache: false,
            type: 'GET',
            dataType: 'HTML',
            success: function (html) {
                $("#item").html(html);
                $("#ajximg2").hide();
            },
        });

    });
});


text:
Q: What is a better design for storing user preference in Google App Engine? I have this object model in Google app engine
class UserPref(ndb.Model):
  user_id = ndb.KeyProperty(kind='User')
  setting_a = ndb.BooleanProperty(default=True)
  setting_b = ndb.BooleanProperty(default=True)
  setting_c = ndb.BooleanProperty(default=True)

Recently I have to rename an attribute and it prompts me thinking what could be a better design:
A) use three rows to capture one row of information in the original design
class UserPref(ndb.Model):
  user_id = ndb.KeyProperty(kind='User')
  setting_name = ndb.StringProperty()
  setting_value = ndb.StringProperty()

B) Repeated property
class UserPrefProp(ndb.Model):
  setting_name = ndb.StringProperty()
  setting_value = ndb.StringProperty()

class UserPref(ndb.Model):
  user_id = ndb.KeyProperty(kind='User')
  Prop = ndb.StructuredProperty(UserPrefProp, repeated=true)

What are the pro and cons to these designs? Search for a setting is not important now, but it could change in the future

A: In general, I think this is the way to go unless you have an unholy number of preferences:
class UserPref(ndb.Model):
  user_id = ndb.KeyProperty(kind='User')
  setting_a = ndb.BooleanProperty(default=True)
  setting_b = ndb.BooleanProperty(default=True)
  setting_c = ndb.BooleanProperty(default=True)

The reason is that you can always add preferences, and unlike a relational datastore, you won't need to modify existing rows to get them up to date. For example if you add setting_d to the above schema midway through your project, existing entries will just have a None value returned for setting_d until the property is populated.
I think having setting_name and setting_value properties completely misses the point of ndb. That kind of schema is only useful in relational databases where you need to know the entire schema ahead of time. Since you can dynamically add properties to an ndb model, there's no reason to not just make each preference its own property.


text:
Q: Java class values getting overridden when calling constructor in a test case / different class I have test case that does something like this
TestSquare.java
public void testEncaps() {
    Shifting shift = new Shifting(150,260);
    Square s = new Square(new Point(101,201),130,140,shift);
    Point p = s.getMidPoint();
    p.x = 215;
    p.y = 315;
    assertEquals(new Point(101,201),s.getMidPoint());
}

So on the last line, the s.getMidPoint() don't equal to the Point(101, 201) but instead gets overridden with 215,315. Here is my constructor code and get method.
Square.java
public Square(Point newP, int width, int height, Shift newS) {
    this.newMidPoint = newP;
    this.newWidth = width;
    this.newHeight = height;
    this.newShift= newS;
}
public Point getMidPoint() {
    return newMidPoint;
}

So, s.getMidPoint() shouldn't be replaced with the Point object. What am I doing wrong?
This two codes are in different class. So there is no main method in Square.java

A: If you don't want another class to be able to edit Square's middle, return a new Point:
public Point getMidPoint() {
    return new Point(newMidPoint);
}

Then your test will run green.