text:
Q: Identifying and quantifying variables (predictors) to understand the relationship What type of analysis do I need to understand and/or gain information from a set of data?
For example, I have students' data for SATScore, HighSchoolGPA, HighSchoolRank, etc., and FreshmenGPA.
Now I want to develop a model which tells me which of the criteria are important for FreshmenGPA and by how much. I want to quantify the importance of these categories (SATScore, HighSchoolGPA, HighSchoolRank, etc.).
What options do I have? Which is the most accurate methodology to do such analysis?
What I Want to find out from the data:
I want is to identify which of these variables(SATScore, HighSchoolGPA, HighSchoolRank, etc.) can help me predict Students FreshmenGPA.
I did some reading on what I need to do for this but there is no definite source or a definite answer. From what I roughly understand, it looks like I need to find out which of these variables are helpful in predicting FreshmenGPA, and whether there is an interaction variable(combination of two or more variables) which is a better predictor than any individual variable. How can I do this?
Once I know which variables and/or interaction variables are important for my model, I will need to quantify the variable importance, for this I'll need to find out the weights(coefficients) for variables which I found are important for FreshmenGPA.
Could anyone show me the steps I need to follow to understand and do this? Also, It looks like there are multiple ways of doing this, Not sure if this is correct, but If so which of these methods give the most accurate model for the data?

A: As was noted, your question is very general, and as such there are MANY different approaches.

*

*Perform linear regressions on y ~ x (y=one variable only) with FreshmanGPA as your dependent variable. The weights of each variable explain the interactions. Looking at the p-values will determine if the variable is likely to be useful (low p-values are better).

*Calculate the correlation between FreshmanGPA and all other variables. The variable with the highest correlation is the most associated with FreshmanGPA. Then go back and run the linear regression on this variable.

*Run a discriminant analysis on all the data, calculating for FreshmanGPA. The coefficient size are proportional to the predictive power of the variable.

*Run linear regression on the interaction terms and compare how the model performs compared to a single variable.

These are only a few ideas. The calculations can be done in many different programs, such as R, SAS, Stata, and many others that I am not familiar with.
In order to compare which factor is the most important, you are basically looking for a relationship that either (1) explains the current data the best. That is to say, if you have a linear regression, your residual errors is the smallest, or (2) predicts a new dataset the best. For (2) you will need to split your data into a testing and training sample. Each time you run a training model, you then predict the FreshmanGPA on the testing sample and see how close you are (the residual error).
Which you choose depends on the purpose of the test. From the question, I expect the first option is better suited.
For detailed examples on how to run this, you will need to specify what program you are using, and give an example of the dataset. Try searching within the forum for a few specific terms. For example:

*

*linear regression R (SAS, Stata, etc)

*Discriminant Analysis

*Comparing linear regressions

*How to calculate interaction terms in R (SAS, Stata, etc)


text:
Q: functionality of local_fiq_enable() Came across the function local_fiq_enable()
 #define local_fiq_enable()  __asm__("cpsie f    @ __stf" : : : "memory", "cc")

Couldn't understand what the __asm__("cpsie f    @ __stf" : : : "memory", "cc") does.
All I could understand is enables [1st parameter - cpie] something

A: __asm__("cpsie f    @ __stf" : : : "memory", "cc")

is inline assembler.
You didn't specify your architecture (that would be really helpful here, because assembler is different for every CPU instruction set), but this looks ARM-sy:
If that's the case, this enables interrupts. What it really does depends on your device -- not only the ARM generation, but your actual piece of silicon. This happens on the interface between the ARM IP core and the "outer world".

redpajama_set_name: RedPajamaStackExchange


text:
Q: ResultSet could be possibly null, how to fix this? It tells me that the "userRow" ResultSet could be null, do you guys know how can I fix this or why is it happening, I would greatly appreciate it, thanks.
It tells me to add more details: I created this ResultSet method in order to retrieve information from the MySQL database that I made with MySQL Workbench, I'm trying to retrieve the information of the USER_TABLE, username, and password, so it would get the info from these two columns and then check with the database and allow the login. But it has been giving me the exception that the ResultSet might be null, I also indicated the specific location of the error right in the code.
Any kind of help is appreciated.
Thanks.
here are my two classes involved with the issue:
public class Login {

@FXML
private TextField userNameTextField;

@FXML
private PasswordField passwordPasswordField;

@FXML
private Button signUpButton;

@FXML
private Button loginButton;

private sample.database.dbHandler dbHandler;

@FXML
void initialize() {

    dbHandler = new dbHandler();

    loginButton.setOnAction(event -> {

        String loginText = userNameTextField.getText().trim();
        String loginPassword = passwordPasswordField.getText().trim();

        User user = new User();
        user.setUsername(loginText);
        user.setPassword(loginPassword);

        ResultSet userRow = dbHandler.getUser(user);

        int counter = 0;

        try {

            while (userRow.next()) { //it says that "userRow" could possibly be null

                counter++;

            }

            if (counter == 1) {

                System.out.println("Logged in");

            }

        } catch (SQLException e) {

            e.printStackTrace();

        }

    });

    signUpButton.setOnAction(event -> {

        signUpButton.getScene().getWindow().hide();

        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(getClass().getResource("/sample/signup.fxml"));

        try {

            loader.load();

        } catch (IOException e) {

            e.printStackTrace();

        }

        Parent root = loader.getRoot();
        Stage stage = new Stage();
        stage.setScene(new Scene(root));
        stage.showAndWait();

    });

}

public class dbHandler extends Config {

java.sql.Connection Connection;

public Connection getConnection() throws ClassNotFoundException, SQLException {

    String connectionString = "jdbc:mysql://" + dbHost + ":" + dbPort + "/" + dbName;

    Class.forName("com.mysql.cj.jdbc.Driver");

    Connection = DriverManager.getConnection(connectionString, dbUser, dbPass);

    return Connection;

}

public void signUp(User user) {

    String insert = "INSERT INTO " + Constants.USERS_TABLE + "(" + Constants.USERS_FIRSTNAME + "," + Constants.USERS_LASTNAME + "," +
            Constants.USERS_USERNAME + "," + Constants.USERS_PASSWORD + ")" + "VALUES(?,?,?,?)";

    try {

        PreparedStatement preparedStatement = getConnection().prepareStatement(insert);

        preparedStatement.setString(1, user.getFirstName());
        preparedStatement.setString(2, user.getLastName());
        preparedStatement.setString(3, user.getUsername());
        preparedStatement.setString(4, user.getPassword());

        preparedStatement.executeUpdate();

    } catch (SQLException e) {

        e.printStackTrace();

    } catch (ClassNotFoundException e) {

        e.printStackTrace();

    }

}

public ResultSet getUser(User user) {

    ResultSet resultSet = null;

    if (!user.getUsername().equals("") || !user.getPassword().equals("")) {

        String query = "SELECT * FROM " + Constants.USERS_TABLE + " WHERE " + Constants.USERS_USERNAME + "=?"
                + " AND " + Constants.USERS_PASSWORD + "=?";

    try {

        PreparedStatement preparedStatement = getConnection().prepareStatement(query);
        preparedStatement.setString(1, user.getUsername());
        preparedStatement.setString(2, user.getPassword());

        preparedStatement.executeQuery();

    } catch (SQLException e) {

        e.printStackTrace();

    } catch (ClassNotFoundException e) {

        e.printStackTrace();

    }

    } else {

        System.out.println("Error");

    }

    return resultSet;

}

A: If you format your code so as to make it easier to read, you will see that method getUser(), in class dbHandler, will return null if both username and password are empty. When that is the case, you simply print "Error" to the screen and continue. You may be sure that those two values will never be empty, but the compiler doesn't know that. If it is an error when both username and password are empty, then throw an Exception.
public ResultSet getUser(User user) {
    ResultSet resultSet = null;
    if (!user.getUsername().equals("") || !user.getPassword().equals("")) {
        String query = "SELECT * FROM " + Constants.USERS_TABLE + " WHERE "
                + Constants.USERS_USERNAME + "=?" + " AND " + Constants.USERS_PASSWORD + "=?";
        try {
            PreparedStatement preparedStatement = getConnection().prepareStatement(query);
            preparedStatement.setString(1, user.getUsername());
            preparedStatement.setString(2, user.getPassword());
            preparedStatement.executeQuery();
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
        catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    else {
        System.out.println("Error");
    }
    return resultSet;
}

What about replacing this line
System.out.println("Error");

with
throw new RuntimeException("Missing username and/or password.");


text:
Q: How to enable Thread Safety on Apache2 server I am trying to enable Thread Safety on my Apache2 server to ultimately be able to use the PHP pthreads module (PHP multithreading).
So far I compiled PHP from source with options (under COMMON_CONFIG) :
--enable-maintainer-zts

and phpinfo says Thread Safety     disabled
Then I recompiled with :
--enable-maintainer-zts
--enable-roxen-zts

and phpinfo says Thread Safety     disabled
Finally I tried with :
--enable-maintainer-zts
--enable-roxen-zts
--with-tsrm-pthreads

and phpinfo says Thread Safety     disabled
I still tried to install pthreads as a last case scenario, using pecl. After moving the pthreads.so in the correct CLI rep, PHP says :
~ # php -m
PHP Warning:  PHP Startup: Unable to load dynamic library '/usr/lib/php5/20121212/pthreads.so' - /usr/lib/php5/20121212/pthreads.so: undefined symbol: sapi_globals_id in Unknown on line 0

What am I doing wrong ? Do I need to compile Apache from source using special ./configure options ?
Any intel greatly appreciated, thanks!

A: Everything went fine by downloading sources from Apache.org and PHP.net. Then using the right ./configure options successfully enabled Zend Thread Safety PHP-side and the Worker MPM Apache-side.
If you need info on the ./configure options please comment.
Note : building PHP and Apache packages via apt-get source didn't work for me. Even by editing the debian/rules files with required configure options. The packages would install but not taking account for --enable-maintainer-zts and --with-mpm=Worker.


text:
Q: Solving a limit by recognizing the sum as a Riemann sum for a function defined on [0,1].
I understand that the change in x is represented by $$7/n$$ but how would you go about solving the actual limit here?

A: We have $$S=7\lim_{n\to\infty}\sum_{k=0}^n\sqrt{\frac{k}{n}}\frac{1}{n}.$$
Let $a=0, b=1$, so that our subintervals have width $\Delta x = \frac{1}{n}$. Then pick an arbitrary point $x^*_k$ in the $k$-th subinterval. That is, $x^*_k =0 + k\Delta x = \frac{k}{n}$. Also let $f(x) = \sqrt{x}$, so that $f(x^*_k)$ is the height of each rectangle in the $k$-th subinterval. So $f(x^*_k)\Delta x$ is the area of the $k$-th rectangle. To find the area, we add up many rectangles. That is,
$$S=7\lim_{n\to\infty}\sum_{k=0}^n f({x^*_k})\Delta x.$$
This is the definition of the area under a curve $f(x)$. So $$S = 7\int_0^1 \sqrt{x} \, \mathrm{d}x.$$


text:
Q: Instantiating class with internal constructor I am trying to create a new instance of a class that looks to only have two constructors, both of which are internal.
The code for this class can be found at this link: link
Essentially, here's what the code for the constructor looks like:
    //Automatic
    internal CommandBuilder(ModuleBuilder module)
    {
        Module = module;

        _preconditions = new List<PreconditionAttribute>();
        _parameters = new List<ParameterBuilder>();
        _attributes = new List<Attribute>();
        _aliases = new List<string>();
    }
    //User-defined
    internal CommandBuilder(ModuleBuilder module, string primaryAlias, Func<ICommandContext, object[], IServiceProvider, CommandInfo, Task> callback)
        : this(module)
    {
        Discord.Preconditions.NotNull(primaryAlias, nameof(primaryAlias));
        Discord.Preconditions.NotNull(callback, nameof(callback));

        Callback = callback;
        PrimaryAlias = primaryAlias;
        _aliases.Add(primaryAlias);
    }

I'm lost with trying to create a new CommandBuilder object.

A: Actually you could do that by using reflection:
Find the first(or whatever) defined contructor
var constructor = typeof (InternalConstructorClass)
     .GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic).First();

Invoke the constructor by passing null if it's Parameterless like this:
var instance = constructor.Invoke(null);

Otherwise, pass the parameters like this:
var instance = constructor.Invoke(new object[]{param1,param2});


text:
Q: django null value in column violates not-null constraint postgres I am attempting to have a form that a user can upload multiple images on their blog. When the user submits the form I get the error null value in column "post_id" of relation "blog_postimages" violates not-null constraint The form has a foreign key to the blogpost. What confuses me is that the value is not null and I am using it else where (pk). I am running a postgres db
view
def DetailPostView(request, pk):
    model = Post
    post = Post.objects.get(pk=pk)

    if request.method == 'POST':
        test = PostImagesForm(request.POST, request.FILES)
        files = request.FILES.getlist('images')
        if test.is_valid():
            for f in files:
                test.save(commit=False)
                test.post = Post.objects.get(pk=pk)
                test.save()
        else:
            print(PostImagesForm.errors)

    context = {
        'post':post, 'PostImagesForm':PostImagesForm,
        }
    return render(request, 'blog/post_detail.html', context)

models
class Post(models.Model):
    title = models.CharField(max_length=100)
    image = models.ImageField(default='default.jpg', upload_to='hero_car_image')
    content = RichTextUploadingField(blank=True, null=True)
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)

class PostImages(models.Model):
    post = models.ForeignKey('Post', on_delete=models.CASCADE)
    images = models.ImageField(upload_to='post_images')
    date_posted = models.DateTimeField(default=timezone.now)

I do not have any unapplied migrations and I am positive I am calling it properly. Even if I hard code in a number it still errors out.
form
class PostImagesForm(ModelForm):
    class Meta:
        model = PostImages
        fields = ('images',)
        widgets = {
            'images': forms.ClearableFileInput(attrs={'multiple': True}),
        }

A: You should be updating the instance and not the form, so:
instance = test.save(commit=False)
instance.post = Post.objects.get(pk=pk)
instance.save()

No need for test.save()


text:
Q: jQuery Toggle, when new menu opens, close the I have multiple menus (forms) with visibility hidden and I open them with a clickevent on an icon. It all works well, exept when I open another menu when the former menu is still open, they both stay visible. So, i want the fomer menu to hide when a new one is opening.
HTML
S

            w
            <form action='' method='post' class='moveForm'>
                <input class='settingsMakePublicButton' type='submit' value='Make public        ' name='$this->move'/>
            </form>

jQuery
$(".settingsIcon").click(function(event) {
    event.stopPropagation();

    if($(document).find(".settingForms").is(':visible') < 1) {
        HandleSettingsWindow($($(this).children()[0]));
    } else {
    }
});

HandleSettingsWindow = function (el) {
    $(document).click(function () { // Close the menu when clicked outside it
        el.hide();
        document.oncontextmenu = function () { return true; };
    });
    el.toggle();
}

A: Try this please: http://jsfiddle.net/RttT5/
Note if($(document).find(".settingForms").is(':visible'))
Hope rest fits your needs :)
Code
$(".settingsIcon").click(function(event) {
    event.stopPropagation();

    if($(document).find(".settingForms").is(':visible')) {
        HandleSettingsWindow($($(this).children()[0]));
    } else {

    }
});

HandleSettingsWindow = function (el) {
    $(document).click(function () { // Close the menu when clicked outside it
        el.hide();
        document.oncontextmenu = function () { return true; };
    });
    el.toggle();
}

A: the problem is with this line
if($(document).find(".settingForms").is(':visible') < 1)

there is no need for the < 1, you can just use
if($(document).find(".settingForms").is(':visible'))


text:
Q: Create UserControl By using UltraGrid of Infragistics I want to create a custom control using Infragistics UltraGrid control. I want to add a button on top of the UltraGrid which exports data as excel. You can get better idea by viewing below image.

This grid is used many times in my project so that i need it in a user control. I have tried to create it but when i add this control in my project i cannot access all actual properties of that UltraGrid.
please help...

A: You are creating a composite control. Normally this means that you can't access the composing controls from the form where you want to position your usercontrol. Usually you need to provide the code to access the underlying properties and events of the controls that compose your UserControl.
For example, supposing that you want to change the caption of the UltraWinGrid inside your user control, you should write a get/set property like this in the code of the UserControl.
public string GridText
{
    get
    {
        return ultraGrid1.Text;
    }
    set
    {
        ultraGrid1.Text = value;
    }
}

As you can imagine, this is not a trivial task with a control like the Infragistics UltraWinGrid that has probably thousands of properties. Not to mention the long list of events.
See here a tutorial from Microsoft about building a Composite Control and that explain the problem with properties of the underlying controls.
A simple workaround (NOT RECOMMENDED) could be to change the property Modifiers of the UltraWinGrid and of the button from Private to Public. In this way the grid reference is available from the properties of the UserControl and you can program it as before.
 userControl1.ultraGrid1.Text = "My User Control";

However this is not recommended because you give full access to the composing controls and this, in certain situations, could be not desiderable. It largely depends on your using scenario.


text:
Q: Javascript and jquery in same page conflict I am using javascript and Jquery in same page.
Some thing is preventing JQuery from working properly
I tried using $jq = jQuery.noConflict(); it is not solving.
My code
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="js/dropmenu.js"></script>
<script src="js/beaverslider.js"></script>
<script src="js/beaverslider-effects.js"></script>

<script>
$jq = jQuery.noConflict();
$jq(document).ready(function($){
    $("#nav-one").dropmenu();
});
</script>

<script>

    $(function(){
      var slider = new BeaverSlider({
        structure: {
          container: {
            id: "my-slider",
            width: 1000,
            height: 200
          }
        },
        content: {
          images: [
            "images/banner01.png",
            "images/banner02.png"
          ]
        },
        animation: {
          effects: effectSets["fadeSet"],
          interval: 4000
        }
      });
    });

    </script>

Problem
javascript code was image fade effect and jquery code was menu dropdown effect.
when menudrop down appears, i was not able to click the dropdown menu link and when image fades dropdown menu also fades.
Please help me to find soln.

A: After calling $jq = jQuery.noConflict(); $ is no longer a reference to jQuery.
In second script use either $jq or jQuery instead of $.


text:
Q: remove existing div and append to new div on load using jquery i have a set of div's

foo

bar

tags

i need to remove
tags
  and append it to

 when the page is loaded using jquery.
i tried the below but doesnt work
jQuery(function ($) {

 $( '#tags' ).ready(function() {
        $('#q').append(this);

    });

});

instead of ready if y try click it works but i need to show it when the page is loaded
any help will be appreciated

A: Try this : You can use appendTo() or append() as shown below
1) appendTo()
$(function() {
   $('#tags').appendTo('#q');
});

JSFiddle Demo
2) append()
$(function() {
   $('#q').append($('#tags'));
});

JSfiddle DEMO
NOTE - make sure that ids of the elements are unique through out the DOM

A: $( document ).ready(function() {
     var ele= $('#tags').html();
     $('#tags').remove();
     $('#q').append(ele);
 });


text:
Q: Desktop screen overlay - transparency key visual artefacts during CopyFromScreen This is a continuation of my other question (understanding of it is not required, just for reference):

*

*Desktop screen overlay - new form flicker issue
It turns out that Graphics.CopyFromScreen which I'm using has the following artefact - it assumes I want to copy with transparency key = Color.Black, so it skips those very dark areas - part of my desktop background image - they suddenly appear in white, and now it looks rather ugly:

The code I'm currently using is provided below:
private static Bitmap MakeScreenshot()
{
  Rectangle bounds = Screen.GetBounds(Point.Empty);
  Bitmap image = new Bitmap(bounds.Width, bounds.Height);

  using (Graphics g = Graphics.FromImage(image))
  {
    g.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size);
  }

  return image;
}

An answer by Hans Passant suggested using a p/invoke instead, but for a different issue - layered windows - so I tried that, and it worked, below is equivalent code, but now using WinApi:
public static Bitmap CreateBitmapFromDesktopNew()
{
  Size sz = GetDesktopBounds().Size;
  IntPtr hDesk = GetDesktopWindow();
  IntPtr hSrce = GetWindowDC(hDesk);
  IntPtr hDest = CreateCompatibleDC(hSrce);
  IntPtr hBmp = CreateCompatibleBitmap(hSrce, sz.Width, sz.Height);
  IntPtr hOldBmp = SelectObject(hDest, hBmp);
  bool b = BitBlt(hDest, 0, 0, sz.Width, sz.Height, hSrce, 0, 0, CopyPixelOperation.SourceCopy | CopyPixelOperation.CaptureBlt);
  Bitmap bmp = Bitmap.FromHbitmap(hBmp);
  SelectObject(hDest, hOldBmp);
  DeleteObject(hBmp);
  DeleteDC(hDest);
  ReleaseDC(hDesk, hSrce);
  return bmp;
}

Question: Is there a native .NET approach that solves my particular problem? I'm trying to avoid using WinApi if there is a better way of doing it.


text:
Q: Update GET request in Dajax I am trying to make it possible to update search results with Dajax as you change the search parameters. I have a GET request for the word search, and would like to modify it using Dajax.
I understand this query has to be in POST format, but how can I combine the word search (currently GET) with the additional parameters (POST)?
So far I am trying this, where variable 'request' is the GET request.

mytopic

A: The Dajax project is pretty much dead.  He said it himself on the Github page. https://github.com/jorgebastida/django-dajax/  It really offers nothing you're not capable of accomplishing on your own using a simple form post with jquery ajax.
Why not post your search form to your view method using jquery Ajax which returns JSON and display that in your search results?  You can make the post on every space or every few letters etc...
It may take some playing around with to get used to, but you're better off doing that than learning a dead library.


text:
Q: Add new column replacing string as value I have a column that has string 'acute' and 'convalescent'. I want to create a new column replacing acute=20 and convalescent=21 number.

A: We  can just do an assignment which is vectorized in base R
df1$newcol <- df1$col1
df1$newcol[df1$col1 == 'acute'] <- 20
df1$newcol[df1$col1 == 'convalescent'] <- 21

Or in a single line in base R
df1$newcol <-  with(df1, c(20, 21)[as.integer(factor(col1, levels = c('acute',
             'convalescent')))])

data
set.seed(24)
df1 <-  data.frame(col1=sample(c('acute','convalescent'), 20,
     replace = T),stringsAsFactors = FALSE)

A: You can also use ifelse() which is a vectorized function:
#Data
df <- data.frame(Var=sample(c('acute','convalescent'),20,replace = T),stringsAsFactors = F)
#Condition
df$Value <- ifelse(df$Var=='acute',20,ifelse(df$Var=='convalescent',21,NA))

Output:
df
            Var Value
1         acute    20
2         acute    20
3         acute    20
4  convalescent    21
5  convalescent    21
6  convalescent    21
7         acute    20
8         acute    20
9         acute    20
10        acute    20
11        acute    20
12        acute    20
13        acute    20
14 convalescent    21
15        acute    20
16        acute    20
17        acute    20
18 convalescent    21
19        acute    20
20        acute    20


text:
Q: Understanding Prototype Pattern I have a question regarding Prototype Pattern.
I read that Prototype Pattern is effective as it copies the object instead of creating a new one, which is considered as an expensive operation.
So based on this I tried a sample and I see varied results.
Am I checking it in the right way Or have I missed anything?
    static void Main(string[] args)
    {
        var sw = new Stopwatch();
        sw.Start();
        Employee e;
        for (var i = 0; i < 100000; i++)
        {
            e = new Employee(5, "sandesh", 27, "Bengaluru");
            e.Print();
        }
        sw.Stop();
        Console.WriteLine("New : " + sw.ElapsedMilliseconds);

        sw.Reset();
        sw.Start();
        e = new Employee(5, "sandesh", 27, "Bengaluru");
        for (var i = 0; i < 100000; i++)
        {
            var en = e.Clone();
            en.Print();
        }
        sw.Stop();
        Console.WriteLine("Clone : " + sw.ElapsedMilliseconds);

        Console.ReadLine();
    }

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    public string Place { get; set; }

    public Employee(int id, string name, int age, string place)
    {
        Id = id;
        Name = name;
        Age = age;
        Place = place;
    }

    public Employee Clone()
    {
        return (Employee)this.MemberwiseClone();
    }

    public void Print()
    {
        var sum = Id * Age;
        var full = sum + Name + Place;
    }
}

And the results are below:
1st Run:-
New: 18
Clone: 26
2nd Run:-
New:34
Clone:30
3rd Run:-
New:20
Clone:33
Appreciate if you can help me out in understanding this pattern.
Also what extra does it takes to Create a new object, which doesn't happens in cloning?

A: It appears that you are looking for a metric that can be used to measure creation of an object versus cloning an object. In your sample you are creating objects, via different mechanisms, and looking for a difference in a metric.
What the Prototype pattern intends to do is reduce the creation time of an object, not from the mechanics of the compiler and byte code, but rather by avoiding time consuming operations that would normally be executed.
For example, if your Employee object required a database call to be instantiated properly, then the Prototype pattern could be utilized to avoid that call. You would still be creating objects and setting values, as your code demonstrated, but the logical initialization of your object, the real data, would be short circuited. This is where the time saving comes in.


text:
Q: geom_beeswarm with half plot and not symmetry I am using geom_beeswarm to test the distribution of data in my dataset. In my toy example here, this is my code to do that.
library(survival)
library(ggplot2)
library(ggbeeswarm)
data("pbc")
head(pbc)

ggplot(pbc, aes(x=trt, y= age, color = trt)) +
  geom_beeswarm(cex =2, size =3, priority="density") +
  theme(panel.background = element_blank(), legend.position = "none") +
  facet_wrap(~trt, nrow = 3, ncol = 1)

This is what I get,

However I am interested in only one half of the plot, not symmetry like shown below. Expected plot

I know I can accomplish this using the side=1 or side=-1 option in the original beeswarm library. Not sure how to do the same using the geom_beeswarm option. Any suggestion is much appreciated. Thanks.


text:
Q: Issue with multiple db in codeigniter I have a project that is using mySql and access db. It is working right now but I have my access db info and query in my view which is a no no. I am trying to figure how to fix it to use it correctly in my model, view, and controller. Also how to get 2 db's working for codeiginter and be able to access the second one for my drop down list.
Here is the db config page
     <?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
        $active_group = 'default';
        $active_record = TRUE;
        $db['default']['hostname'] = '10.16.160.155';
        $db['default']['username'] = 'dcman';
        $db['default']['password'] = '123456';
        $db['default']['database'] = 'call_ins';
        $db['default']['dbdriver'] = 'sqlsrv';

This is the view Page
                <?php $msg = $this->session->flashdata('msg'); if((isset($msg)) && (!empty($msg))) { ?>

                  ×
                <?php print_r($msg); ?>

                <?php } ?>
                <?php $msg = $this->session->flashdata('msg1'); if((isset($msg)) && (!empty($msg))) { ?>

                  ×
                <?php print_r($msg); ?>

                <?php } ?>

    <title>Enter CallIns</title>

    <link rel="stylesheet" type="text/css" href="<?php echo base_url();?>assets/css/view.css">
    <link href="<?php echo base_url();?>assets/css/bootstrap.min.css" rel="stylesheet">

<form class="" action="<?php echo base_url();?>callin/insert_callin" method="post">

Enter Data

        Date Scheduled

            <input id="element_1" name="Date_Scheduled" class="element text medium" type="text" maxlength="255" value="<?php echo date('Y-m-d') . "\n";?>" required/>

        Employee_Name

<?php

try {

$dbName = "C:\\inetpub\\wwwroot\\fpdb\\staffing.mdb";
 $db = new PDO("odbc:DRIVER={Microsoft Access Driver (*.mdb)};charset=UTF-8; DBQ=$dbName; Uid=; Pwd=;");

}
catch (PDOException $e) {
  echo $e->getMessage();
}
$sql="SELECT FIRSTNAME, LASTNAME, EMPLOYEE_NUMBER  FROM tbl_USERS WHERE STATUS='A' order by FIRSTNAME";

/* You can add order by clause to the sql statement if the names are to be displayed in alphabetical order */

echo "<select id='Employee_Name' name=Employee_Name value=''>Employee_Name</option>"; // list box select command

echo '<option value="none">Please select a user</option>';
foreach ($db->query($sql) as $row){//Array or records stored in $row
echo "<option value=$row[FIRSTNAME],$row[LASTNAME]>$row[FIRSTNAME]  $row[LASTNAME]</option>";

/* Option values are added by looping through the array */
}
echo "</select>";// Closing of list box

?>

        Employee Number

            <input id="Employee_Number" name="Employee_Number" class="element text medium" type="text" maxlength="255" value="" required/>

        Time Reported

            <input id="Time_Reported" name="Time_Reported" class="element text medium" type="text" maxlength="255" value="<?php echo  date("m/d/Y")." ". date("h:i:sa");?> " required/>

        Reason

        <select class="element select medium" id="Reason" name="Reason" required>
            <option value="" selected="selected">Please Select..</option>
            <option value="Bereavement" >Bereavement</option>
            <option value="Clinic" >Clinic</option>
            <option value="FMLA" >FMLA</option>
            <option value="ILL" >ILL</option>
            <option value="ILL 2nd Day" >ILL 2nd Day</option>
            <option value="Jury Duty" >Jury Duty</option>
            <option value="ILL/PTO" >ILL/PTO</option>
            <option value="IOW" >IOW</option>
            <option value="Late" >Late</option>
            <option value="Late???" >Late??</option>
            <option value="Late FMLA" >Late FMLA</option>
            <option value="Layoff" >Layoff</option>
            <option value="Leave Early" >Leave Early</option>
            <option value="LeaveEarly FMLA" >Leave Early FMLA</option>
            <option value="LeaveEarly ILL" >Leave Early ILL</option>
            <option value="LeaveEarly Personal" >Leave Early Personal</option>
            <option value="LeaveEarly FMLA" >Leave Early FMLA</option>
            <option value="LNTB5H" >LNTB5H</option>
            <option value="MIA" >MIA</option>
            <option value="NCI" >NCI</option>
            <option value="NCIBOD" >NCIBOD</option>
            <option value="NCIFL" >NCIFL</option>
            <option value="NCOFL" >NCOFL</option>
            <option value="Personal" >Personal</option>
            <option value="SAC" >SAC</option>
            <option value="STO" >STO</option>
            <option value="VLO" >VLO</option>
        </select>

        Scheduled Area

            <input id="Scheduled_Area" name="Scheduled_Area" class="element text medium" type="text" maxlength="255" value="" required/>

        Contact

            <?php

try {

$dbName = "C:\\inetpub\\wwwroot\\fpdb\\staffing.mdb";
 $db = new PDO("odbc:DRIVER={Microsoft Access Driver (*.mdb)};charset=UTF-8; DBQ=$dbName; Uid=; Pwd=;");

}
catch (PDOException $e) {
  echo $e->getMessage();
}
$sql="SELECT FIRSTNAME, LASTNAME, SCHEDULEPRIORTY  FROM tbl_USERS WHERE (SCHEDULEPRIORTY = 1) OR (SCHEDULEPRIORTY = 2) OR (SCHEDULEPRIORTY = 3)  order by FIRSTNAME";

/* You can add order by clause to the sql statement if the names are to be displayed in alphabetical order */

echo "<select id='Contact' name=Contact value=''>Contact</option>"; // list box select command
echo '<option value="none">Please select a contact</option>';
foreach ($db->query($sql) as $row){//Array or records stored in $row
echo "<option value=$row[FIRSTNAME],$row[LASTNAME]>$row[FIRSTNAME]  $row[LASTNAME]</option>";

/* Option values are added by looping through the array */
}
echo "</select>";// Closing of list box

?>

        Approval

            <input id="Approval" name="Approval" class="element text medium" type="text" maxlength="255" value="" required/>

          <input id="Complete" class="default" type="hidden" name="Complete" value="NO" />
            <input id="Status" class="default" type="hidden" name="Status" value="1" />

            <input id="saveForm" class="button_text" type="submit" name="submit" value="Submit" />

        </form>


text:
Q: Why CHR(157) is used in oracle? I am not understanding why CHR(157) is used code of ORACLE. When I executed below code i got output as 'HELLO WORLD!'
SELECT 'HELLO' || CHR(157) || ' WORLD!' FROM DUAL;

Some of editors don't display the CHR(157) value. Please let me know if anybody knows why CHR(157) is used in oracle.

A: The glyph which is displayed for  CHR(157) depends on the font you're using. For example, if you're using an "IBM PC Extended ASCII" font, you'll get something that looks like a Y with an = superimposed over the top of it (see the glyph at 9D (the hexadecimal equivalent of 157) below):

If you're using some other font, you'll get something else - or nothing at all, if the font doesn't define a glyph for that character - for example, the "Microsoft Windows" character set doesn't define a glyph for 157 (hex 9D):

Best of luck.


text:
Q: How to add a Claim to a SystemUser as a flag(bool) in C# I need to add a Claim to be passed to the front-end. I want to check "IsSystemUser" of type bool and then value of the bool of course so users are not able to see system settings.
I am using this:
        context.IssuedClaims.Add(new Claim("IsSystemUser", ));

However, I noticed that it has string Type, string Value and/or string ValueType.
The IntentUser already has a field isSystemUser, I just don't know how to add claim to it.
        context.IssuedClaims.Add(new Claim("IsSystemUser", user.IsSystemUser.ToString()));

Is that how I should do it?

A: Claims always have a string value (you can read more here). There is a possibility to specify valueType as Boolean:

context.IssuedClaims.Add(new Claim("IsSystemUser", user.IsSystemUser.ToString(),
                          ClaimValueTypes.Boolean));

However, on the front-end, you have to parse it manually from string.


text:
Q: How can I modify a cert-manager resource via the python kubernetes client? I'm using Python to automate creation of certain resources, and need to create a cert-manager Certificate. How do I access this via the python kubernetes client?
Normally I get the correct client using the format client.<Group><Version>Api, but I'm not sure  how to do that w/ 3rd-party resources such as the Certificate in cert-manager.io/v1alpha2.


text:
Q: Low speed when the output in Android Studio When click on run application to phone or emulator in Android Studio, i should wait 15 min or up !
I have't this problem before and running application in phone / emulator on 1 min! but now when running application in phone / emulator i should wait 15 min or up to build Gradle !!!
How can i fix this problem and faster to build Gradle ?

A: I encountered the same issue.Try these steps to make faster builds upto 3x faster:

*

*Make sure you don't have unnecessary gradle dependencies

*In the settings go to compiler-check combine independent modules parallel

*In the settings go to gradle and then click on offline mode.(This will cause your gradle to not to use internet while building project,dont use this if you are adding any new dependency)

Thanks,hope it'll help.


text:
Q: Hiding html table on page loading I have a system, where once a user has logged in, there are two tables. I only want one table to be displayed initially, but I can't seem to get it to hide.
So far I've tried
style="display:none;"

within the table initiation, and also have tried using javascript to set it on load again, with no luck. My tables are mostly created in php because of using variables etc, and that all works fine, it's just hiding the table that I am having issues with.

    <?php
         .... code creating table ....
    ?>

And then the second table, which I want hidden on loading

    <?php
        .... code creating table ....
    ?>

The JS I tried was
function initialDisplay()
{
    document.getElementById('mainView').style.display = "initial";
    document.getElementById('directoryView').style.display = "none";
}

which I called from my main php file using
echo "";

Any help would be greatly appreciated.

A: Html:

            <?php
                 .... code creating table ....
            ?>

            <?php
                .... code creating table ....
            ?>

Use JS

A: Try this
In Javascript

test content1

test content2

In jquery

test content1

test content2


text:
Q: CSS background-image gradient and border-line on bigger element I'd like to have a background-image with a line on the end.
The border or line should begin where the background-size ends.
The border line is grey in the concept. It should stay just one element.
  background-image: gradient-y(@color-grey-2, @color-white);
  background-position: left top;
  background-size: 100% 40px;
  background-repeat: no-repeat;

A: http://jsfiddle.net/8Q79p/ OLD JSFIDDLE. (Wrapper)
http://jsfiddle.net/8Q79p/1/ Updated; if you want just one element, you can use color-stop
<div id="gradient">

</div>

#gradient{
    background: rgb(221,221,221); /* Old browsers */
    background: -moz-linear-gradient(top, rgba(221,221,221,1) 1%, rgba(255,255,255,1) 46%, rgba(149,149,149,1) 47%, rgba(149,149,149,1) 48%, rgba(255,255,255,1) 49%, rgba(252,252,252,1) 100%, rgba(27,27,27,1) 100%); /* FF3.6+ */
    background: -webkit-gradient(linear, left top, left bottom, color-stop(1%,rgba(221,221,221,1)), color-stop(46%,rgba(255,255,255,1)), color-stop(47%,rgba(149,149,149,1)), color-stop(48%,rgba(149,149,149,1)), color-stop(49%,rgba(255,255,255,1)), color-stop(100%,rgba(252,252,252,1)), color-stop(100%,rgba(27,27,27,1))); /* Chrome,Safari4+ */
    background: -webkit-linear-gradient(top, rgba(221,221,221,1) 1%,rgba(255,255,255,1) 46%,rgba(149,149,149,1) 47%,rgba(149,149,149,1) 48%,rgba(255,255,255,1) 49%,rgba(252,252,252,1) 100%,rgba(27,27,27,1) 100%); /* Chrome10+,Safari5.1+ */
    background: -o-linear-gradient(top, rgba(221,221,221,1) 1%,rgba(255,255,255,1) 46%,rgba(149,149,149,1) 47%,rgba(149,149,149,1) 48%,rgba(255,255,255,1) 49%,rgba(252,252,252,1) 100%,rgba(27,27,27,1) 100%); /* Opera 11.10+ */
    background: -ms-linear-gradient(top, rgba(221,221,221,1) 1%,rgba(255,255,255,1) 46%,rgba(149,149,149,1) 47%,rgba(149,149,149,1) 48%,rgba(255,255,255,1) 49%,rgba(252,252,252,1) 100%,rgba(27,27,27,1) 100%); /* IE10+ */
    background: linear-gradient(to bottom, rgba(221,221,221,1) 1%,rgba(255,255,255,1) 46%,rgba(149,149,149,1) 47%,rgba(149,149,149,1) 48%,rgba(255,255,255,1) 49%,rgba(252,252,252,1) 100%,rgba(27,27,27,1) 100%); /* W3C */
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#dddddd', endColorstr='#1b1b1b',GradientType=0 ); /* IE6-9 */
    width: 100%;
    height: 100px;
    border: solid 1px black;
}


text:
Q: Reading CSV file in Java: extra line I'm reading this CSV:
A;San Antonio;Tercer Barrio
B;Camino de la Miranda;Campus
C;San Lázaro;Cementerio
E;Cristo;H. Río Carrión
H;H. San Telmo;H. Río Carrión
M;Plaza de León;Monte el Viejo
P;Allende el Río;Campus

and I want to populate a SQLite database in Android using this method:
private void insertRoutes(SQLiteDatabase db) {
  try {
     BufferedReader reader = new BufferedReader(
             new InputStreamReader(context.getAssets().open(SQL_FILE_ROUTES)));

     String query =
             "insert into routes (name, rfrom, rto) values (?, ?, ?)";

     db.beginTransaction();
     SQLiteStatement stmt = db.compileStatement(query);
     String line;

     while ((line = reader.readLine()) != null) {
        String[] dic = line.split(";");
        stmt.bindString(1, dic[0]);
        stmt.bindString(2, dic[1]);
        stmt.bindString(3, dic[2]);
        stmt.execute();
        stmt.clearBindings();
     }
     db.execSQL(query);
     db.setTransactionSuccessful();

  } catch (IOException e) {
     e.printStackTrace();
  } finally {
     db.endTransaction();
  }
}

It "works" and my database get populated, but with and extra row. This is the result when I check the sqlite database:
sqlite> select * from routes;
1|A|San Antonio|Tercer Barrio
2|B|Camino de la Miranda|Campus
3|C|San Lázaro|Cementerio
4|E|Cristo|H. Río Carrión
5|H|H. San Telmo|H. Río Carrión
6|M|Plaza de León|Monte el Viejo
7|P|Allende el Río|Campus
8|||

There are 8 rows, but the CSV file has just 7 lines. What I'm doing wrong?
Thanks.
EDIT
I have checked the file. It has 7 lines:
wc default_android_routes.csv
7  25 198 default_android_routes.csv

EDIT
Like @flopo has said, db.execSQL(query); was the guilty. Just remove it.

A: CSV may have blank line, check in text pad. Try selecting the whole text file and see whether the next line is also getting selected.
You can do this to avoid empty line.
while ((line = reader.readLine()) != null) {
        if (line.trim().length() == 0) { // this will check empty line
             break;
        }
        String[] dic = line.split(";");
        stmt.bindString(1, dic[0]);
        stmt.bindString(2, dic[1]);
        stmt.bindString(3, dic[2]);
        stmt.execute();
        stmt.clearBindings();
     }

A: Not pretty sure, but I think db.execSQL(query) is the one that is causing your extra row.
In the while loop you execute the statement for each row. Outside the loop, you don't need to execute again the query.
As I said, I haven't used SQLiteDatabase, but I think that's the problem you have.


text:
Q: Algorithm to encapsulate voxels/data in box I have a cube with 8 variable corners. I also have a voxel data set which has all dimensions of same set size.
Does anyone know of an algorithm, to find the smallest possible area (and with that all 8 corner positions) for the cube while the cube still encapsulates all the voxels?
Preferably a not too heavy algorithm.

A: If you mean a cuboid -- a 3D shape with 6 rectangular faces -- and if these faces must be aligned with the axes of your voxel data, then this is just the (3D) bounding box.  All you need to do is calculate the minimum and maximum values of the x, y and z co-ordinates of every voxel in your dataset.  Taking all 8 combinations of {minimum, maximum} for these 3 dimensions will give you the co-ordinates of the 8 corners, although you would normally record just the two points (min_x, min_y, min_z) and (max_x, max_y, max_z), which completely describe the shape.
If the shape must be a cube (i.e. all dimensions equal) then you will have to increase the size of the 2 smaller dimensions to the size of the largest.
If you're looking for shapes to bound volumes with that you can use for efficient intersection testing (with points, lines, planes or other bounding volumes) then another good choice is a sphere.  The intersection test between two spheres is particularly simple: all you need to do is check whether the distance between their centres exceeds the sum of their radii.

A: j_random_hacker already gave a good answer with cuboids aligned with axes, cubes aligned with axes, and spheres. However, if you really want to find the optimal cuboid, the algorithm becomes much more complicated.
I will assume you have a set of voxels in a grid. If your voxels represent a solid or form a dense cloud, you may want to create a set of voxels which represents the outer shell of the shape. The inner voxels are not important when creating a convex hull (whether it is a sphere or any convex polyhedron).
One possible method for this is:

*

*for each line along X-axis find the elements with smallest and largest X coordinate, and remove all elements between them

*repeat the same for lines along Y axis and lines along Z axis

If this sounds odd, think of the geometry. If you try to draw a plane outside the solid (or), the plane can never reach to any of the middle positions along a line, so no points which are on a line segment between two other points can help to create a tighter fit. (This is not an optimal algorithm in the sense that it would not leave unnecessary points to the set, but it is easy and fast.)
If you want to create a polyhedron containing all points, you create it from a set of planes (6 in the case of a cuboid). A plane is quite simple in the sense that for any optimal limiting planes the following holds true:

*

*all points are at a non-negative distance from the plane (i.e. on the same side)

*there is at least one point on the plane (zero distance)

The distance from a point to a plane is a very simple calculation (ax+by+cx+d for each point). Finding the limiting plane at each direction is thus a relatively fast and easy O(n) operation (where n is the number of voxels remaining).
Worse news is that picking the correct directions for the planes is not easy. I do not know if there is an optimal algorithm for this, but I can only think of clumsy or slow algorithms with either a lot of brute force calculation (plane distances at many directions) or iterative guessing.
Even these may be useful, but really the question remains: why? There might be better ways than trying to make a small cuboid.


text:
Q: Как реализовать "рисование" во Flash с последующим сохранением данных в файл? Здравствуйте, интересует такой вопрос. Нужно реализовать на сайте некую "доску рисования", на которой можно будет рисовать (ну очевидно, же). Данные должны сохранятся в виде картинки .png формата (то есть с прозрачностью). Есть ли какие-нибудь исходники сея чуда?
A: Советую вот такую библиотечку: The Graffiti AS3 Bitmap Drawing Library
Использовал в проекте для вконтакта, сохранял не напрямую в файл, а на сервер. Довольно приличная рисовалка получилась.
Класс для декодирования bitmap - PNGEncoder.
A: Посмотрите компоненты flash и методы самого canvas. Возможно есть такая возможность как в GDI с их метаформатом.


text:
Q: Problems with database setup on cookiecutter-django I'm trying to use cookiecutter-django according to the instructions on github. First of all i created a postgres database by means of docker with:
docker run -p ::5432 \
--name db \
-e POSTGRESQL_DB=hartl \
-e POSTGRESQL_USER=docker \
-e POSTGRESQL_PASS=docker \
kamui/postgresql

and it worked fine from terminal.
After this i used the DATABASE_URL as an environment variable, according to the instructions:
export DATABASE_URL=postgres://docker:docker@dbserver_ip:5432/hartl

as my variable is postgres://docker:docker@dbserver_ip:5432/hartl.
BUT when i try:
python myapp/manage.py migrate

i'm having this error:
django.core.exceptions.ImproperlyConfigured: Error importing module dj_database_url: "No module named dj_database_url"

what can be wrong?

A: Just a problem with pip. After installing all dependencies, everything is working fine.


text:
Q: Trying to extend a base html but not working properly I have a form that I am trying to access when pressing a button on my navbar. I have a base template file that consists of the code for the navbar and background color and I have another template that has the code for the form. The navbar button seems to work every time I remove the {% extends 'base.html' %} but only the form shows up. I want to be able to extend the base template so the navbar background color and nav bar show up too but this is not working.
code snippet from base.html

    TweetyBird
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarText" aria-controls="navbarText" aria-expanded="false" aria-label="Toggle navigation">

    </button>

          Search by Tweet (current)

          Twitter Bot

          To be added

search.html
% extends 'base.html' %}
{%load static%}

      <container >
        <form action="/searchoutput/" method="post">
          {% csrf_token %}
          Input Text:
          <input type="text" name="param" required>

          {{data_external}}

          {{data}}

          <input type="submit" value="Check tweet">

          </form>
      </container>

snippet from  url.py
    path('', views.noreq), #shows the html template for the website
    path('search/',views.search),
    path('searchoutput/',views.searchoutput),

snippet from views.py
def noreq(request):
  #when no request is made the html is rendered
  return render(request,'base.html')
################The method above is required############################################

def search(request):
  return render(request,'search.html')

A: There are a couple of issues here. For one, I noticed you don't have the opening bracket on % extends 'base.html' %} in search.html but I'm not sure if that was just a pasting error here.
Secondly, you have no content blocks. You need to specify where in your base.html the content from extended templates will go. For instance:
example base.html:

    <title>My Site</title>

    TweetyBird
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarText" aria-controls="navbarText" aria-expanded="false" aria-label="Toggle navigation">

    </button>

          Search by Tweet (current)

          Twitter Bot

          To be added

    {% block content %}

    {% endblock %}

In the template that extends base.html:
{% extends 'base.html' %}
{%load static%}

{% block content %}
<container >
        <form action="/searchoutput/" method="post">
          {% csrf_token %}
          Input Text:
          <input type="text" name="param" required>

          {{data_external}}

          {{data}}

          <input type="submit" value="Check tweet">

          </form>
      </container>
{% endblock %}

More documentation: https://docs.djangoproject.com/en/3.0/ref/templates/language/

A: Alright, you have the right idea but are implementing it a bit wrong let me explain.
base.html
In your base html you want to put everything that every single page will share this normally includes: {% load static %}, <!DOCTYPE html>, , , , , etc Take a look below for what you base html would sort of look like.
{% load static %}
{% load employee_filters %}
<!DOCTYPE html>

        Site Header

            TweetyBird
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarText" aria-controls="navbarText" aria-expanded="false" aria-label="Toggle navigation">

            </button>

                  Search by Tweet (current)

                  Twitter Bot

                  To be added

        {% block content %}{% endblock %}

That {% block content %}{% endblock %} is the key. That is where the code will be placed that it another file extends. So in your search.html you would have what is below:
{% extends 'base.html' %}
{% block content %}
    <form action="/searchoutput/" method="post">
        {% csrf_token %}
        Input Text:
        <input type="text" name="param" required>

        {{data_external}}

        {{data}}

        <input type="submit" value="Check tweet">

    </form>
{% endblock %}

Think of it this way, you are saying that search.html is extending from base.html and then you are replacing the {% block content %} with whatever you have in that new file.


text:
Q: vue-cli resolve xlink:href in svgs when referenced in  In my vue-cli project, I need to reference an svg-file in an <img>-tag. That works.
Now inside this svg file, I have an <image xlink:href="..."> – And this path is not touched or resolved by webpack.
Example:

<!-- MyComponent.vue -->
<img src="@/assets/someImage.svg" />

<!-- someImage.svg -->
<svg ...>
  <!-- none of these are working -->
  <image ... xlink:href="@/assets/arcade-bg-4.jpg"/>
  <image ... xlink:href="~@/assets/arcade-bg-4.jpg"/>
  <image ... xlink:href="./assets/arcade-bg-4.jpg"/>
  <image ... xlink:href="/src/assets/arcade-bg-4.jpg"/>
</svg>

The question now is, how I can tell webpack to solve paths inside this svg file?
Possible workarounds:
* put arcade-bg-4.jpg in /public and reference this in the xlink:href
* use inline-<svg> in MyComponent.vue
But I'd like to keep the <img />-tag and also keep the file-hashing feature from vue-cli.
Background:
I use this setup to achieve a (relatively) cross-browser-ready clip-mask with a .jpg instead of a .png, which is way smaller and more performant.

A: You should be using just href instead of xlink:href in <image> of <svg>
or
You need to use require along with v-bind like so
<image ... :href="require('@/assets/arcade-bg-4.jpg')" />
or
In case of webpack you will need to add this to vue-loader's options as either transformToRequire or transformAssetUrls according to the version
// webpack.config.js
module.exports = {
  // ...
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
          transformToRequire: {
           image: ['xlink:href', 'href']
          }
        }
      }
    ]
  }
}


text:
Q: TypeError when working on a Minimax algorithm with tuples and floats I'm currently working on a project where I need to implement a Minimax algorithm to create a tic-tac-toe game. At some point I'm comparing tuples and floats, and while I know this can't actually be done, I don't know where that problem comes from or how do I fix it. If anyone could help me understand that would be amazing. Thanks!
Here's my code
import copy

X = "X"
O = "O"
EMPTY = None

def initial_state():
    """
    Returns starting state of the board.
    """
    return [[EMPTY, EMPTY, EMPTY],
            [EMPTY, EMPTY, EMPTY],
            [EMPTY, EMPTY, EMPTY]]

def player(board):
    Xboard_count = board[0].count(X) + board[1].count(X) + board[2].count(X)
    if Xboard_count % 2 == 1:
        return 0
    else:
        return X

def actions(board):
    """
    Returns set of all possible actions (i, j) available on the board.
    """
    move = []
    for i in range(3):
        for j in range(3):
            if board[i][j] == EMPTY:
                move.append((i, j))

    return move

def result(board, move):
    """
    Returns the board that results from making move (i, j) on the board.
    """
    if move not in actions(board):
        raise Exception("this action is not a valid action")

    dcopb = copy.deepcopy(board)
    dcopb[move[0]][move[1]] = player(board)

    return dcopb

def winner(board):
    """
    Returns the winner of the game, if there is one.
    """
    for x in range(3):
        if board[x][0] == board[x][1] == board[x][2] != EMPTY:
            return board[x][0]
    for y in range(3):
        if board[0][y] == board[1][y] == board[2][y] != EMPTY:
            return board[0][y]
    if board[0][0] == board[1][1] == board[2][2] != EMPTY:
        return board[0][0]
    if board[2][0] == board[1][1] == board[0][2] != EMPTY:
        return board[2][0]
    else:
        return None

def terminal(board):
    """
    Returns True if game is over, False otherwise.
    """
    if winner(board) == X:
        return True
    elif winner(board) == O:
        return True

    for x in range(3):
        for y in range(3):
            if board[x][y] is None:
                return False
    return True
    ('si winner est égal à X :\n'
     '            return True\n'
     '        si winner est égal à 0\n'
     '            return true \n'
     '            \n'
     '        si le nombre de cases vides == 0\n'
     '            return true\n'
     '        else:\n'
     '            return false')

def utility(board):
    """
    Returns 1 if X has won the game, -1 if O has won, 0 otherwise.
    """
    if winner(board) == X:
        return 1
    if winner(board) == 0:
        return -1
    else:
        return 0

def minimax(board):
    """
    Returns the optimal action for the current player on the board.
    """
    if terminal(board):
        return None

    if player(board) == X:
        v = v = float('-inf')
        for move in actions(board):
            temp = MinValue(result(board, move))
            if temp > v:
                v = temp
                best = move
    else:
        v = float('inf')
        for move in actions(board):
            temp = MaxValue(result(board, move))
            if temp < v:
                v = temp
                best = move
    return best

def MaxValue(board):
    if terminal(board):
        return utility(board), None

    v = float('-inf')
    for move in actions(board):
        v = max(v, MinValue(result(board, move)))
    return

def MinValue(board):
    if terminal(board):
        return utility(board), None

    v = float('inf')

    for move in actions(board):
        v = min(v, MaxValue(result(board, move)))
    return v

I get this exact error message
TypeError: '>' not supported between instances of 'tuple' and 'float'

A: You're returning a tuple at return utility(board), None in MinValue. So when you call the function at temp = MinValue(result(board, move)), temp is a tuple if that return statement was invoked
v is a float. Now when you try to compare it with temp at if temp < v:, you're comparing a float with a tuple

A: First of all, there was a problem with the MinValue and MaxValue function, they were sometimes returning two values instead of one.
Then, there was the same TypeError, this time with a problem when comparing NoneType variables with floats. Turns out there was just a small mistake because my MaxValue function wasn't returning anything.


text:
Q: No headphone or speakers plugged in - Windows 7 issue I am facing a wierd issue between my sound card driver and Windows7(any edition). I have a sony vaio notebook (VPCEB24EN). Two days ago, on start I got diabled wifi, charging and speakers. Then I restart the PC and everthing worked fine. Later on I again restarted my machine, and then I found the my speakers were not working. I thought, restart will work. I restarted many more times but it did'nt work. I searched google and found that , it might be due to :
1. Hardware is not switched on from bios.
2. No hardware.
3. overriding 64-bit drivers with 32-bit drivers.
To make it working, I restored my laptop from scratched, but while restoring pc, the realtek HD drivers, it gave me an error 505. I then formatted the drive and installed Win7 Ultimate 32bit (With PC was, Win7 64-bit Home Basic). I got lots of yellow exclamation in device manager, thinking now this will resolve my issue. But Even after the installing all drivers on a fresh installation, I was still with the same position.
A red cross on speaker- No Speakers or Headphone plugged in.
Please Note:

*

*My Laptop is Vaio , E Series, VPCEB24EN.

*Audio : Intel® High Definition Audio compatible but accepts Realted Audio. While using BIOS Agent, I got Intel Chipset 5 Series Audio Adapter and ATI RV370 Audio adapter found on my board.

*Installed is Win7 32bit Ultimate. factory default was Win7 64-bit Home Basic

*Memory: RAM 3GB/ 320GB HDD

*Display : ATI Mobility Radeon™ HD 5145 Graphics

A: try to install the updates from Sony


text:
Q: AIX 5.3 - Howto backup operating system to a bootable ISO image We would like to backup the AIX 5.3 IntelliStation at our company. Unfortunately it does not have a tapedrive nor a DVD-Writer. It only has a DVD-ROM drive.
The idea is to mount a directory via NFS and to create an ISO image there. Afterwards We would use a different machine to create a bootable DVD from the ISO image.
How can this be done? I have tried the mkdvd command from a smitty terminal, but it seems that mkdvd does not accept a filename, e.g. /nfsmount/aixbackup/system-image.iso.
Any help on this is very appreciated!

A: Mkdvd can be used for this.
It will take the rootvg (or a backup made with mksysb) and will write it on the specified device.
To create a bootable dvd, you can simply use the following:
mkdvd -d /dev/cd1

You should have a look at mkdvd, mksysb and savevg documentation before doing anything nasty on your server..

A: meanwhile I found out how to create a bootable DVD .iso image.
Instructions:

unset LC_ALL

# note: I have unmounted /home before creating the iso image. Otherwise I would need multiple DVDs

# note: I have mounted an NFS directory below /volumes/aixsav
extdir=/volumes/aixsav

# create some needed subdirectories
for i in mksysb_target tmp iso mkcd; do
       test -d $extdir/$i || mkdir $extdir/$i || exit 1
done

# finally: create the .iso image.
/usr/sbin/mkdvd -M $extdir/mksysb_target -C $extdir/tmp -I $extdir/iso -S

This needs some time. But after all I had my image in the iso subdirectory. I went to another machine and burned the image to a DVD (under linux).
For testing I have shut down the AIX machine and replaced the existing harddisk with a another empty one. Then I booted up and followed the onscreen instruction for restoring from DVD.
Everything went fine. Even the Usernames/Passwords, Hostname, IP-Address everything was like on the original harddrive!
a final note: be patient! creating the Image and booting from the DVD will need some time. Just lay back and wait ...


text:
Q: matlab quadrature I'm trying to use MATLAB dblquad for such an equation:
f(x,y)=\int_{0}^{1}(exp(-int_{0}^{y}f(x)dx))dy

But it does not work. Is there any suitable MATLAB function for these type of double integrations?
Thanks a lot,
mg

A: You have a nested integral rather than a double integral so dblquad will not work. How about
q = quad(@(y)arrayfun(@(w)exp(-quad(f,0,w)),y),0,1)


text:
Q: Regular Expression to remove all lines containing only 1 word I am attempting to create a regex that will find any line that contains exactly one word on it. Words separated by a hyphen or symbol (e.g test-word) or leading white space should still be treated as a single word.
$cat file1
this line has many words
hello
  test-hi
this does aswell

Using the regular expression
'/^\s*(\w+)\s$/GM'
Returns only "hello" and ignores "test-hi"
I am able to capture all single words but not ones with hyphens etc!

A: This is easier to do with awk, by default it will separate each record into fields based on one or more continuous whitespaces and whitespace at start/end of line won't be part of field calculations
$ awk 'NF==1' ip.txt
hello
  test-hi
$ awk 'NF>1' ip.txt
this line has many words
this does aswell

NF is a built-in variable that indicates number of fields in the input record

A: You can use
^\s*([\w-]+)\s*$

which adds support for hyphens, makes the second \s match "zero or more" spaces. Keep your GM flags.
Demo

A: Try using \S to match any non whitespace character:
'/^\s*(\S+)\s$/GM'


text:
Q: How do I find the Chart Id of an existing chart in Google Sheets? How do I go about finding the the ChartID for a chart I've already created in google sheets.
I've searched through the documentation and can't get anything to work.

A: Unfortunately, there are no methods for directly searching a chart ID. But you can retrieve all chart IDs in a Spreadsheet using the method of spreadsheets.get in Sheets API. The official document says as follows.

The placeholder chartId is also used to indicate the ID of a given chart. You can set this ID when creating a chart with API, or allow the API to generate one for you. You can read the IDs of existing charts with the spreadsheet.get method.

Endpoint:
For example, in order to retrieve only chart IDs, when fields of sheets/charts/chartId is used, the endpoint is as follows.
GET https://sheets.googleapis.com/v4/spreadsheets/### spreadsheetId ###?fields=sheets%2Fcharts%2FchartId

Result:
When 1st sheet and 2nd sheet have 2 charts and 1 chart, respectively, the following result is returned. If you want to search the chart ID, you can search it from the following result.
{
  "sheets": [
    {
      "charts": [
        {
          "chartId": ###
        },
        {
          "chartId": ###
        }
      ]
    },
    {
      "charts": [
        {
          "chartId": ###
        }
      ]
    }
  ]
}

References:

*

*spreadsheets.get

*Charts
If I misunderstood your question, I apologize.

A: Here's how to do it in Ruby.
require 'google/apis/sheets_v4'
require 'googleauth'
require 'googleauth/stores/file_token_store'

sheet_name = 'Sheet1'

response = service.get_spreadsheet(SPREADSHEET_ID)

response.sheets.each do |sheet|
  title = sheet.properties.title
  if title = sheet_name
     unless sheet.charts.nil?
        charts = sheet.charts
        charts.each do |chart|
           chart_id = chart.chart_id
           puts chart_id
        end
     end
  end
end


text:
Q: Renew login when logged in with cookies and without php session? I have a login script with session and cookies,(Remember me) Username, token, selector hashed and set to cookies, but no userID and cookie expire date set to 1 month.
I need to set userID for cookies is well to use it in site to display data,
But setting all critical data to cookies doesn't look right to me.
I can switch userName to userID, but userID is more importand than userName in my site that is why I dont want to make it public.
Require relogin to set php sessions for important pages is an option.
Any other advice ?
All kinds of advice are welcome, Thanks.


text:
Q: LaTeX Uglifier / obfuscator For JavaScript you have e.g. js uglifier, which obfuscates the javascript so that it is infeasible for humans to read the javascript code. Also, judging by @DavidCarlisle's xii.tex (see below), obfuscations is definitely possible in TeX.
\let~\catcode~`76~`A13~`F1~`j00~`P2jdefA71F~`7113jdefPALLF
PA''FwPA;;FPAZZFLaLPA//71F71iPAHHFLPAzzFenPASSFthP;A$$FevP
A@@FfPARR717273F737271P;ADDFRgniPAWW71FPATTFvePA**FstRsamP
AGGFRruoPAqq71.72.F717271PAYY7172F727171PA??Fi*LmPA&&71jfi
Fjfi71PAVVFjbigskipRPWGAUU71727374 75,76Fjpar71727375Djifx
:76jelse&U76jfiPLAKK7172F71l7271PAXX71FVLnOSeL71SLRyadR@oL
RrhC?yLRurtKFeLPFovPgaTLtReRomL;PABB71 72,73:Fjif.73.jelse
B73:jfiXF71PU71 72,73:PWs;AMM71F71diPAJJFRdriPAQQFRsreLPAI
I71Fo71dPA!!FRgiePBt'el@ lTLqdrYmu.Q.,Ke;vz vzLqpip.Q.,tz;
;Lql.IrsZ.eap,qn.i. i.eLlMaesLdRcna,;!;h htLqm.MRasZ.ilk,%
s$;z zLqs'.ansZ.Ymi,/sx ;LYegseZRyal,@i;@ TLRlogdLrDsW,@;G
LcYlaDLbJsW,SWXJW ree @rzchLhzsW,;WERcesInW qt.'oL.Rtrul;e
doTsW,Wk;Rri@stW aHAHHFndZPpqar.tridgeLinZpe.LtYer.W,:jbye

Is there any such software that would obfuscate a .tex-file, so that it is fairly hard to make sense of?
Possibly related and helpful files:

*

*Obfuscating TeX

*Can I see a plain TeX source file please?

*Can you explain how this code works?

A: Using the new tokcycle package (https://www.ctan.org/pkg/tokcycle), we can map tokens from the input into gibberish and write them to an external file.  Then, in a second document, as long as the mapping is known from the 1st document, we can unmap the externally input gibberish back into LaTeX code:
MAPPING
This maps a block of input and writes it to the file xform.tex.    Any characters not mapped (e.g., capital letters, numerals, etc.) are presented in the clear.  Obviously, the mapping must be one-to-one, or the unmapping will be ambiguous.
EDITED to avoid using the \expanded option of \addcytoks, for those users who still have an older LaTeX installation.
After mapping, I also show a detokenized form of the gibberish:
\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{tokcycle}
\newwrite\xfile
\long\def\remaptext#1#2\endremaptext{\tokcycle
  {\addcytoks[4]{\tcremap{##1}}}
  {\processtoks{##1}}
  {\addcytoks{##1}}
  {\addcytoks{##1}}{#2}%
  \immediate\openout\xfile=#1
  \immediate\write\xfile{\the\cytoks}
}
\newcommand*\tcmapto[2]{\expandafter\def\csname tcmapto#1\endcsname{#2}%
  \tcmapfrom{#1}{#2}}
\newcommand*\tcmapfrom[2]{\expandafter\def\csname tcmapfrom#2\endcsname{#1}}
\newcommand*\tcremap[1]{\ifcsname tcmapto#1\endcsname
\csname tcmapto#1\expandafter\endcsname\else\expandafter#1\fi}
\tcmapto am \tcmapto bf \tcmapto cz \tcmapto de \tcmapto ey
\tcmapto fl \tcmapto gx \tcmapto hb \tcmapto ic \tcmapto jn
\tcmapto ki \tcmapto lr \tcmapto mh \tcmapto nt \tcmapto ok
\tcmapto ps \tcmapto qa \tcmapto ro \tcmapto sq \tcmapto tw
\tcmapto uj \tcmapto vp \tcmapto wd \tcmapto xg \tcmapto yu
\tcmapto zv \tcmapto ^& \tcmapto &^ \tcmapto +- \tcmapto -+
\begin{document}
\remaptext{xform.tex}%
\section{We can map sectioning, as well}

What can't we \textit{accomplish} if we try?
\begin{equation}
y = f(x) = \frac{1 + x^a}{47b}
\end{equation}
Let us be of good spirit and put our minds to it!
\endremaptext
Encoded input (detokenized):\\
\detokenize\expandafter{\the\cytoks}
\end{document}

An examination of the file xform.tex shows the same (line breaks added by me):
\section {Wy zmt hms qyzwcktctx, mq dyrr} \par Wbmw zmt'w dy
\textit {mzzkhsrcqb} cl dy wou? \begin {yajmwckt} u = l(g) =
\frac {1 - g&m}{47f} \end {yajmwckt} Lyw jq fy kl xkke qscocw
mte sjw kjo hcteq wk cw!

UNMAPPING
Now, we run the unmap of the gibberish (contained in the external file xform.tex), using the mappings from the original encode:
\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{tokcycle,etoolbox}
\tokcycleenvironment\unmaptext
  {\addcytoks[4]{\tcunmap{##1}}}
  {\processtoks{##1}}
  {\addcytoks{##1}}
  {\addcytoks{##1}}
\newcommand*\tcmapto[2]{\expandafter\def\csname tcmapto#1\endcsname{#2}%
  \tcmapfrom{#1}{#2}}
\newcommand*\tcmapfrom[2]{\expandafter\def\csname tcmapfrom#2\endcsname{#1}}
\newcommand*\tcunmap[1]{\ifcsname tcmapfrom#1\endcsname
\csname tcmapfrom#1\expandafter\endcsname\else\expandafter#1\fi}
\tcmapto am \tcmapto bf \tcmapto cz \tcmapto de \tcmapto ey
\tcmapto fl \tcmapto gx \tcmapto hb \tcmapto ic \tcmapto jn
\tcmapto ki \tcmapto lr \tcmapto mh \tcmapto nt \tcmapto ok
\tcmapto ps \tcmapto qa \tcmapto ro \tcmapto sq \tcmapto tw
\tcmapto uj \tcmapto vp \tcmapto wd \tcmapto xg \tcmapto yu
\tcmapto zv \tcmapto ^& \tcmapto &^ \tcmapto +- \tcmapto -+

\newread\infile
\makeatletter
\newcommand\unmapfile[1]{%
\def\fcont{}
\openin\infile=#1
{\endlinechar=-1
 \everyeof{}%
 \loop\unless\ifeof\infile
  \read\infile to \temp
  \ifx\temp\empty\else
\expandafter\g@addto@macro\expandafter\fcont\expandafter{\temp}%
  \fi
 \repeat
}%
\closein\infile
\expandafter\unmaptext\fcont\endunmaptext
}
\makeatother
\begin{document}
\unmapfile{xform.tex}
\end{document}

which provides the desired output:

So, if you have possession of the original mapping function and the file containing the mapped text, you can reconstitute the original!


text:
Q: Best scraper/crawler needed for multipage forms (Nokogiri, Scrapy, other?) I've read that Nokogiri/Mechanize (Ruby) for example are not good at traversing multiple pages, but may be better with sites that use Ajax.
The sites I want to scrape are multi-page forms, with some ajax overlays.  Speed is important.  These sites all display prices, so I am making a price aggregator.

A: I use Capybara with Webkit to a headless browser.
You'll need install capybara gem, and webkit gem as well.
https://github.com/thoughtbot/capybara-webkit
The syntax is very simple.
agent.visit 'some url'
agent.execute_script 'javascript here'

The gem also have page management, or you may simply go back to previous page by execute a javascript going back.
ag.execute_script("window.history.go(-1)")


text:
Q: handing data to a config when running a flask app? I looked at a fairly generic structure to base my app off of, which looks something like this in directory structure:
run.py
config.py
app/
  __init__.py
  views.py
  blueprints/
  sql/

I put some variables in my config.py, which is then read by __init__.py when the app is made. Some pieces are completely static and don't matter, but some parts I want to be configurable on each different run. For example, queries = [x for x in os.listdir(os.path.join(_basedir, sql_path))] where sql_path is configurable, or changing the port_number
The absolute ideal would be to use command line arguments on the run.py script.
My first reaction was clearly to do the following in run.py to configure it:
from app import app
import argparse
import os

_basedir = os.path.abspath(os.path.dirname(__file__))
parser = argparse.ArgumentParser(description='run the app')
parser.add_argument('--port', type=int, default=1225)
parser.add_argument('--sql_path', type=str, default='/app/sql/')
parser.add_argument('--debug', type=boolean, default=False)
args = parser.parse_args()

app.config['queries'] = [x for x in os.listdir(os.path.join(_basedir, args.sql_path))]
app.config['port_number'] = args.port
app.config['debug'] = args.debug

app.run(debug=args.debug, port=app.config['port_number'])

this will result in a KeyError when I run the app, saying that sql_path is not configured, as one of the blueprints uses it.
Is there a way to configure this with command line arguments? I want to be able to do python run.py --sql_path=../sql/ --port_number=5000, for example, and have that configure in the app.

A: So you can do this as follows with a decorator that Flask provides:
from flask import Flask

app = Flask(__name__)

@app.cli.command()
def initdb():
    """Initialize the database."""
    print 'Init the db'

Then on the command like call that function like so:
$ flask -a hello.py initdb

Flask uses the Click package to pass through command line args, so anything available there should be available from Flask as well.
app.cli is an instance of click.Group (docs here) meaning things like @click.option() should translate over to be @app.cli.option() pretty nicely.
If you wanted to actually pass an option it might look something like this:
@app.cli.command()
@app.cli.option('--test', help='test')
def takearg(test):
    print test

And then call it as follows:
$ flask -a hello.py --test=teststring


text:
Q: como trabalhar com aes_decrypt no symfony 3 Eu tenho um banco de dados que é criptografado por outro sistema e eu preciso descriptografar os dados para exibição no sistema feito em symfony 3.
Eu tenho a chave de descriptografia e preciso fazer isso. Eu tenho pouca experiência no Symfony.
Como eu devo fazer isso? Seria no Entity ou no Controller?

A: Resolvido ao seguir o passo-a-passo desse link.
https://github.com/ambta/DoctrineEncryptBundle/blob/master/Resources/doc/installation.md


text:
Q: @Async vs. Reactor thread pool in Spring What is the difference between @Async annotated method and Reactor set to use thread pool of the same size. Is there any advantage to one of this methods and what it would be? For my use, I do not care to return any value with the asynced method.

A: The most obvious difference is that Reactor doesn't crosscut @Async annotated methods and implicitly submit events to a Reactor. If you're using the Reactor @Selector annotation on beans then you're getting the opposite of what you would with @Async: an event handler, not an event publisher.
With that said, there is some support in Reactor for @Async-style event publishing through the DynamicReactorFactory. It uses an interface instead of an annotation, but the concept is similar.
Regarding "advantages" to using one or the other: it really depends on what other things you're doing in your application and whether or not you're using Reactor in a more general sense. Reactor isn't designed to be a thread pool replacement. The ThreadPoolExecutorDispatcher in Reactor just uses a plain ThreadPoolExecutor underneath. The advantages to using Reactor in that scenario come from the optimized event publishing used in Reactor versus creating new Callables and Runnables all the time, as well as using Reactor's Stream and Promise API to handle asynchronous execution.
Looked at from the API prespective, there is a distinct and measurable advantage to using Reactor over a plain TaskExecutor for background jobs.


text:
Q: Sorting a query string ABC order (using Unix-style case sensitive sorting order) with no delimiters Here is my query string that I would like to sort:
string queryString = "Called=%2B12475&ToState=I&CallerCountry=US&Direction=inbound&CallerState=IN&ToZip=&CallSid=CA9fa6986e19f98c3413923a6af1c694&To=%2B128375&CallerZip=&ToCountry=US&ApiVersion=2010-04-01&CalledZip=&CalledCity=&CallStatus=ringing&From=%2B1200582&AccountSid=ACc6d06b4cb61ccbfa61bf1957a5a626&CalledCountry=US&CallerCity=&Caller=%2B2602582&FromCountry=US&ToCity=&FromCity=&CalledState=IN&FromZip=&FromState=IN"

Example results = "CallSidCA1234567890ABCDECaller+14158675310Digits1234From+14158675310To+1800555121212345"
What I have so far:
string request = "Called=%2B12475&ToState=I&CallerCountry=US&Direction=inbound&CallerState=IN&ToZip=&CallSid=CA9fa6986e19f98c3413923a6af1c694&To=%2B128375&CallerZip=&ToCountry=US&ApiVersion=2010-04-01&CalledZip=&CalledCity=&CallStatus=ringing&From=%2B1200582&AccountSid=ACc6d06b4cb61ccbfa61bf1957a5a626&CalledCountry=US&CallerCity=&Caller=%2B2602582&FromCountry=US&ToCity=&FromCity=&CalledState=IN&FromZip=&FromState=IN"

string[] separator = { "&" };
Int32 testcount = 200;
String[] strlist = request.Split(separator,testcount,StringSplitOptions.RemoveEmptyEntries);
string[] testArray = new string[]
{
   "aa",
   "ab",
   "ac",
   "ad",
   "ab",
   "af"
};

Array.Sort(testArray, StringComparer.InvariantCulture);

What would be the best way to do this?

A: If I understand you correctly, you want to perform an Ordinal Comparison on the characters in the string.
You'll first want to split the string.
Next, you can use Array.Sort, passing the array you want to be sorted and a a string comparison enum of Ordinal type. This tells the sort to be done following Ordinal(binary) sort rules.
Here's the code:
string queryString = "Called=%2B12475&ToState=I&CallerCountry=US&Direction=inbound&CallerState=IN&ToZip=&CallSid=CA9fa6986e19f98c3413923a6af1c694&To=%2B128375&CallerZip=&ToCountry=US&ApiVersion=2010-04-01&CalledZip=&CalledCity=&CallStatus=ringing&From=%2B1200582&AccountSid=ACc6d06b4cb61ccbfa61bf1957a5a626&CalledCountry=US&CallerCity=&Caller=%2B2602582&FromCountry=US&ToCity=&FromCity=&CalledState=IN&FromZip=&FromState=IN";

string[] stringArr = queryString.Split('&');

Array.Sort(stringAsCharArray, StringComparer.Ordinal);

Sorted Results:
Sorted:
AccountSid=ACc6d06b4cb61ccbfa61bf1957a5a626
ApiVersion=2010-04-01
CallSid=CA9fa6986e19f98c3413923a6af1c694
CallStatus=ringing
Called=%2B12475
CalledCity=
CalledCountry=US
CalledState=IN
CalledZip=
Caller=%2B2602582
CallerCity=
CallerCountry=US
CallerState=IN
CallerZip=
Direction=inbound
From=%2B1200582
FromCity=
FromCountry=US
FromState=IN
FromZip=
To=%2B128375
ToCity=
ToCountry=US
ToState=I
ToZip=

You can find a working dotnetfiddle, with print statements to show the results. here.

A: Try using LINQ to split the string, order it, then put it back together:
string queryString = "Called=%2B12475&ToState=I&CallerCountry=US&Direction=inbound&CallerState=IN&ToZip=&CallSid=CA9fa6986e19f98c3413923a6af1c694&To=%2B128375&CallerZip=&ToCountry=US&ApiVersion=2010-04-01&CalledZip=&CalledCity=&CallStatus=ringing&From=%2B1200582&AccountSid=ACc6d06b4cb61ccbfa61bf1957a5a626&CalledCountry=US&CallerCity=&Caller=%2B2602582&FromCountry=US&ToCity=&FromCity=&CalledState=IN&FromZip=&FromState=IN";

var ordered = queryString.Split('&').OrderBy(x => x).ToList();

var orderedQueryString = string.Join("&", ordered);

This will produce a string that matches the format of your query string. Then, from here you can remove delimiters by doing standard string replaces:
var noDelim = orderedQueryString.Replace("&", "").Replace("=", "");

I hope this is your intended output... It's unclear based off the question and sample you provided.


text:
Q: Tossing a fair coin for 100 times and count the number of heads. Repeat this simulation 10**5 times Write a program to simulate tossing a fair coin for 100 times and count the number of heads. Repeat this simulation 10**5 times to obtain a distribution of the head count.
I wrote below code to count number of heads 100 times, and outer loop should repeat my function 100K times to obtain distribution of the head:
import random
def coinToss():
    return random.randint(0, 1)

recordList = []

for j in range(10**5):

    for i in range(100):
        flip = coinToss()
        if (flip == 0):
            recordList.append(0)

    print(str(recordList.count(0)))

but each time I run my program, instead of getting a list of 100K heads probability, I get no#s higher, can anyone tell me what I doing wrong ?

42
89
136
....
392
442
491

A: Here's a version with numpy that allows you to more elegantly produce random numbers, as you can also specify a size attribute.
import numpy as np

n_sim = 10
n_flip = 100

sims = np.empty(n_sim)
for j in xrange(n_sim):
    flips = np.random.randint(0, 2, n_flip)
    sims[j] = np.sum(flips)

A: Since the original problem asks for a distribution of head counts, you need to keep track of two lists: one for the number of heads per 100-toss trial, and one for the number of heads in the current 100-toss trial.
import random
def coinToss():
    return random.randint(0, 1)

experiments = [] # Number of heads per 100-toss experiment

for j in range(10**5):
    cnt = [] # Number of heads in current 100-toss experiment
    for i in range(100):
        flip = coinToss()
        if (flip == 0):
            cnt.append(0)
    experiments.append(cnt.count(0))
    print(str(cnt.count(0)))

However, I would strongly suggest doing this in something like numpy which will greatly improve performance. You can do this is one line with numpy:
import numpy as np
experiments = np.random.binomial(n=100, p=0.5, size=10**5)

You can then analyze/plot the distribution of head counts with whatever tools you want (e.g. numpy, matplotlib).

A: You might notice that your number of heads is ~50 more each time. This is because you don't reset the record counter to [] each time you loop. If you add "recordList = []" straight after your print statement and with the same indentation, it will basically fix your code.
Another nifty way to do this would be to wrap the 100 coin flips experiment in a function and then call the function 10**5 times. You could also use list comprehension to make everything nice and concise:
import random

def hundred_flips():
    result = sum([random.randint(0, 1) for i in range(100)])
    return result

all_results = [hundred_flips() for i in range(10**5)]

A: You can simulate a matrix with all your coin flips and then do your calculations on the matrix.
from numpy import mean, std
from numpy.random import rand
N_flip = int(1e5)
N_trials = int(1e2)
coin_flips = rand(N_flip, N_trials) > 0.5
p = mean(coin_flips, axis=0) # Vector of length N_trials with estimated probabilites
print('Mean: %3.2f%%, Std: %3.2f%%' % (mean(p)*100, std(p)*100))


text:
Q: Informix: procedure with output parameters? I searched a lot, but couldn't find anything.. I just want to ask if there's any way to create and call a procedure (Informix) with out parameters. I know how to return one or more values (for procedures and for functions), but this is not what I want. It would be really strange, if Informix does not allow output parameters..
Thanks in advance!
EDIT: Yes, I saw it's possible, but I still can't execute such procedure. For example:
  CREATE PROCEDURE mytest(batch INT,OUT p_out INT)
  DEFINE inc INTEGER;
  LET inc = 1;
  LET p_out = 5;
  END PROCEDURE;

and what I receive is:
The routine mytest can not be resolved
and this happens only on executing functions with output parameters..

A: Why do you need 'out' parameters?  Informix procedures can return multiple values from a single call (or, in this case, a single value):
  CREATE PROCEDURE mytest(batch INT) RETURNING INT AS p_out;
      DEFINE inc INTEGER;
      DEFINE p_out INTEGER;
      LET inc = 1;
      LET p_out = batch + inc;
      RETURN p_out;
  END PROCEDURE;

There are only a limited number of places where you can use an OUT parameter.  One is in a query - there is a name SLV (statement local variable) that turns up in some error messages.  I believe there's a way to get to OUT parameters via Java (JDBC) too.  AFAIK, other APIs do not allow it.
Code written for Informix assumes that it won't need output parameters.  Code migrated to Informix from other (impoverished?) systems that do not provide multiple output values from a single procedure need to be rethought to work sensibly with Informix.


text:
Q: Fillna in multiple columns in place in Python Pandas I have a pandas dataFrame of mixed types, some are strings and some are numbers. I would like to replace the NAN values in string columns by '.', and the NAN values in float columns by 0.
Consider this small fictitious example:
df = pd.DataFrame({'Name':['Jack','Sue',pd.np.nan,'Bob','Alice','John'],
    'A': [1, 2.1, pd.np.nan, 4.7, 5.6, 6.8],
    'B': [.25, pd.np.nan, pd.np.nan, 4, 12.2, 14.4],
    'City':['Seattle','SF','LA','OC',pd.np.nan,pd.np.nan]})

Now, I can do it in 3 lines:
df['Name'].fillna('.',inplace=True)
df['City'].fillna('.',inplace=True)
df.fillna(0,inplace=True)

Since this is a small dataframe, 3 lines is probably ok. In my real example (which I cannot share here due to data confidentiality reasons), I have many more string columns and numeric columns. SO I end up writing many lines just for fillna. Is there a concise way of doing this?

A: Came across this page while looking for an answer to this problem, but didn't like the existing answers.  I ended up finding something better in the DataFrame.fillna documentation, and figured I'd contribute for anyone else that happens upon this.
If you have multiple columns, but only want to replace the NaN in a subset of them, you can use:
df.fillna({'Name':'.', 'City':'.'}, inplace=True)

This also allows you to specify different replacements for each column.  And if you want to go ahead and fill all remaining NaN values, you can just throw another fillna on the end:
df.fillna({'Name':'.', 'City':'.'}, inplace=True).fillna(0, inplace=True)

Edit (22 Apr 2021)
Functionality (presumably / apparently) changed since original post, and you can no longer chain 2 inplace fillna() operations. You can still chain, but now must assign that chain to the df instead of modifying in place, e.g. like so:
df = df.fillna({'Name':'.', 'City':'.'}).fillna(0)

A: You could use apply for your columns with checking dtype whether it's numeric or not by checking dtype.kind:
res = df.apply(lambda x: x.fillna(0) if x.dtype.kind in 'biufc' else x.fillna('.'))

print(res)
     A      B     City   Name
0  1.0   0.25  Seattle   Jack
1  2.1   0.00       SF    Sue
2  0.0   0.00       LA      .
3  4.7   4.00       OC    Bob
4  5.6  12.20        .  Alice
5  6.8  14.40        .   John

A: define a function:
def myfillna(series):
    if series.dtype is pd.np.dtype(float):
        return series.fillna(0)
    elif series.dtype is pd.np.dtype(object):
        return series.fillna('.')
    else:
        return series

you can add other elif statements if you want to fill a column of a different dtype in some other way. Now apply this function over all columns of the dataframe
df = df.apply(myfillna)

this is the same as 'inplace'

A: You can either list the string columns by hand or glean them from df.dtypes.  Once you have the list of string/object columns, you can call fillna on all those columns at once.
# str_cols = ['Name','City']
str_cols = df.columns[df.dtypes==object]
df[str_cols] = df[str_cols].fillna('.')
df = df.fillna(0)

A: The most concise and readable way to accomplish this, especially with many columns is to use df.select_dtypes.columns.
(df.select_dtypes, df.columns)
df.select_dtypes returns a new df containing only the columns that match the dtype you need.
df.columns returns a list of the column names in your df.
Full code:
float_column_names = df.select_dtypes(float).columns
df[float_column_names] = df[float_column_names].fillna(0)

string_column_names = df.select_dtypes(object).columns
df[string_column_names] df[string_column_names].fillna('.')

A: There is a simpler way, that can be done in one line:
df.fillna({'Name':0,'City':0},inplace=True)

Not an awesome improvement but if you multiply it by 100, writting only the column names + ':0' is way faster than copying and pasting everything 100 times.

A: If you want to replace a list of columns ("lst") with the same value ("v")
def nan_to_zero(df, lst, v):
    d = {x:v for x in lst}
    df.fillna(d, inplace=True)
    return df

A: Much easy way is  :dt.replace(pd.np.nan, "NA").
In case you want other replacement, you should use the next:dt.replace("pattern", "replaced by (new pattern)")

A: If you don't want to specify individual per-column replacement values, you can do it this way:
df[['Name', 'City']].fillna('.',inplace=True)

If you don't like inplace (like me) you can do it like this:
columns = ['Name', 'City']
df[columns] = df.copy()[columns].fillna('.')

The .copy() is added to avoid the SettingWithCopyWarning, which is designed to warn you that the original values of a dataframe is overwritten, which is what we want.
If you don't like that syntax, you can see this question to see other ways of dealing with this: How to deal with SettingWithCopyWarning in Pandas


text:
Q: Mocking EventHandler Having defined an interface
 public interface IHandlerViewModel {
         EventHandler ClearInputText { get; }
}

I would like to test if ClearInputText is invoked by some method.
To do so I do something like this
SomeType obj=new SomeType();
bool clearCalled = false;
var mockHandlerViewModel=new Mock<IHandlerViewModel>();
mockHandlerViewModel.Setup(x => x.ClearInputText).Returns(delegate { clearCalled = true; });

obj.Call(mockHandlerViewModel.Object);//void Call(IHandlerViewModel);
Assert.IsTrue(clearCalled);

which fails. Simply the delegate is not called.
Please help me with this.

A: The example you give isn't clear. You're essentially testing your own mock.
In a scenario where the mocked proxy is passed as a dependency to an object under test, you do no set up the event handler, you Raise it.
var mockHandlerViewModel = new Mock<IHandlerViewModel>();
var objectUnderTest = new ClassUnderTestThatTakesViewModel(mockHandlerViewModel.Object);
// Do other setup... objectUnderTest should have registered an eventhandler with the mock instance. Get to a point where the mock should raise it's event..

mockHandlerViewModel.Raise(x => x.ClearInputText += null, new EventArgs());
// Next, Assert objectUnderTest to verify it did what it needed to do when handling the event.

Mocks either substitute the event source by using .Raise(), or they substitute an object that will consume another class under test's event (to assert the event was raised), in which case you use .Callback() to record "handling" the event in a local flag variable.


text:
Q: "macros have been disabled" message in Word 2007 but no macros I open a .doc file in Word 2007 (sorry I am unable to supply the .doc) which pops up with a message above the document "Security warning: Macros have been disabled" but there are no macros shown in the macros listing and no functionality displayed in the VBScript editor.
Why does Word think this document contains macros and how can I remove them to prevent the warning?
Thanks,
Tom

A: I think Word is simply reporting that the properties of the document are configured to disable macros.
This is not the same as saying there are any macros.
If there were macros, they would be disabled.
And it's only a warning message. If you can configure the document not to disable macros, the warning should disappear.

A: If the file used to have macros and they were removed, it can still get incorrectly flagged by the security features as it can see the module exists even with no code in it.
Steps to reproduce problem:
Open Word document.
Open VB IDE (ALT-F11)
Find the document project in the navigation pane.
Right click > insert module. This creates a branch for "Modules" containing "Module1".
Don't add anything to Module1.
(This is basically the same as if someone recorded a macro then went and deleted it but did not actually remove the module).
So, for your troublesome document, open it, then ENABLE the content (if you don't you won't see it in the IDE).
Alt-F11, go find the (empty) module and right click > remove. Don't bother to export before doing this (since it's empty, right?)
Save and close the document.
If you are unsure about the provenance of the document and don't feel happy enabling the content, this should work (your mileage may vary):
Open doc. Don't enable content
Alt-F11
Find the document and right click > insert a module.
Now remove that module and the IDE deletes the modules container with it, along with the disabled modules.
Save and close

A: Install share components can solve this problem.

A: I solved this problem at last and the solution is not obvious.
First go to installed programmes from control panel.
Find add or remove features, Microsoft office Word.
Enable Visual basic for applications.
Then from word Options Macros, choose the level you want. In my case do not run macros without warning prompt.
Andre IILTD.COM

A: I feel that I have to update this answer, as I was also looking to remove VBA from my document.  With my own, my old primary template had modules to format documents as I needed them, and this affected new documents created with it.
So, the correct way to remove VBA from your Office document is by using the Organiser.  To do this, ensure that the Developer ribbon is visible, and click the Marcos button...

Now click the Organiser button...

Select the module(s) that you want to remove from the current document to the left, or from the Normal.dot on the right, and click Delete...

Though the images show the ribbon for Word 2016, not that much has cosmetically changed between 2007 and 2016.


text:
Q: Does gravitational red shift test the equivalence principle or general relativity? These comments seem to say gravitational redshift experiments would only verify theories that obey the equivalence principle (ep), not specifically general relativity: https://arxiv.org/abs/0806.0528
(see 2nd paragraph p.16)
and this (by one of the same authors) seems to show even the ep is not needed to explain the shift: https://arxiv.org/abs/gr-qc/0403082
But this paper (published in Nature, 2011): https://arxiv.org/abs/1109.6571 (see p.8 for key graph)
says the TeVeS theory is "inadequate" based on gravitational redshift measurements. I only have a vague understanding of the ep and have not studied general relativity or TeVeS but I have read that TeVeS is meant to obey the ep. So do the "comments" and experimental paper not contradict each other?
Should gravitational redshift be considered a central test of general relativity or the ep or neither?

A: It's a test of the equivalence principle. Tensor-scalar theories such as Brans-Dicke and TeVeS do violate the e.p.

I have read that TeVeS is meant to obey the ep.

This seems odd to me. I'm not claiming that this is a totally airtight argument, but basically when we augment the metric with other properties of space such as scalar or tensor fields, we expect  the e.p. to be violated for the following reason. The e.p. says that locally, special relativity always applies. SR says that the only built-in structure of spacetime is the metric (which can be made trivial in SR through an appropriate choice of coordinates).