text:
Q: Using BeginInvoke in a recursive function adding nodes to a TreeView in a BackgroundWorker My code has a function that scans a root directory and showing txt files (for example) in a TreeView:
private TreeNode DirectoryToTreeView(TreeNode parentNode, string path,
                                     string extension = ".txt")
{
    var result = new TreeNode(parentNode == null ? path : Path.GetFileName(path));
    foreach (var dir in Directory.GetDirectories(path))
    {
        TreeNode node = DirectoryToTreeView(result, dir);
        if (node.Nodes.Count > 0)
        {
            result.Nodes.Add(node);
        }
    }
    foreach (var file in Directory.GetFiles(path))
    {
        if (Path.GetExtension(file).ToLower() == extension.ToLower())
        {
            result.Nodes.Add(Path.GetFileName(file));
        }
    }
    return result;
}

This function should by called from the button like:
treeView1.Nodes.Add(DirectoryToTreeView(null, @"C:\Users\Tomer\Desktop\a"));
Its obviously freezing the UI.
I am new to this and I have searched the web and nothing seemed relevant to my problem because no one used recursive function and I cant simply call BeginInvoke on the entire function because it will have no effect.
What path should I take? Maybe change the function to work with a while loop and then calling BeginInvoke inside the if statements? Creating a TreeNode object in memory to populate (which may be too large)?

A: Here's an example for async Task method to populate a TreeNode with a directory-tree for a given file type. The inner CreateTree(...) is a local function called recursively to traverse the directories.
private async Task<TreeNode> CreateTreeAsync(string startDir, string fileExt)
{
    var di = new DirectoryInfo(startDir);
    var result = new TreeNode(di.Name);
    var searchPattern = $"*.{fileExt.TrimStart('.')}";

    return await Task.Run(() =>
    {
        void CreateTree(DirectoryInfo dirInfo, TreeNode node)
        {
            try
            {
                foreach (var fileInfo in dirInfo.EnumerateFiles(searchPattern))
                    node.Nodes.Add(fileInfo.Name);

                foreach (var subDir in dirInfo.EnumerateDirectories())
                {
                    try
                    {
                        // Optional to skip the branches with no files at any level.
                        if (!subDir.EnumerateFiles(searchPattren,
                            SearchOption.AllDirectories).Any()) continue;

                        var newNode = new TreeNode(subDir.Name);
                        node.Nodes.Add(newNode);
                        CreateTree(subDir, newNode);
                    }
                    catch (Exception ex)
                    {
                        // Skip exceptions like UnauthorizedAccessException
                        // and continue...
                        Console.WriteLine(ex.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        CreateTree(di, result);
        return result;
    });
}

Note: You don't need the try..catch blocks if you're under .NET 5+/.NET Core to skip the inaccessible directories and files. Use the EnumerateXXX method overload that takes the EnumerationOptions parameter.
Now you need async caller like so:
private async void someButton_Click(object sender, EventArgs e)
{
    // Optional...
    treeView1.Nodes.Clear();

    var dir = @"...";
    var ext = "txt";
    var node = await CreateTreeAsync(dir, ext);

    if (node.Nodes.Count == 0)
        MessageBox.Show($"No '{ext}' files were found.");
    else
    {
        treeView1.Nodes.Add(node);
        node.Expand();
    }
}

A: You could convert the DirectoryToTreeNode method to an asynchronous method, and offload any blocking I/O operation to the ThreadPool, by using the Task.Run method:
private async Task<TreeNode> DirectoryToTreeNodeAsync(string path,
    TreeNode parentNode = null)
{
    var node = new TreeNode(parentNode == null ? path : Path.GetFileName(path));
    string[] subdirectories = await Task.Run(() => Directory.GetDirectories(path));
    foreach (string dirPath in subdirectories)
    {
        TreeNode childNode = await DirectoryToTreeNodeAsync(dirPath, node);
        node.Nodes.Add(childNode);
    }
    string[] files = await Task.Run(() => Directory.GetFiles(path));
    foreach (string filePath in files)
    {
        node.Nodes.Add(Path.GetFileName(filePath));
    }
    return node;
}

Notice that no UI control is touched while running on the ThreadPool (inside the Task.Run delegate). All UI controls should be manipulated exclusively by the UI thread.
Usage example:
private async void Button1_Click(object sender, EventArgs e)
{
    Button1.Enabled = false;
    Cursor = Cursors.WaitCursor;
    try
    {
        TreeView1.Nodes.Clear();
        TreeView1.Nodes.Add(
            await DirectoryToTreeNodeAsync(@"C:\Users\Tomer\Desktop\a"));
    }
    finally
    {
        Cursor = Cursors.Default;
        Button1.Enabled = true;
    }
}


text:
Q: What is the right way to run query in SAP HANA I have several tables that loaded from Oracle into HANA.
Among these tables ,one is a fact table, and the others are dimension tables.
I write a sql that do two things:

*

*Join fact table and dimension tables

*Calculate measures(such as min, sum, count) against fact table by grouping by two dimensions,
I would ask what is the correct way to do this,

*

*Write the SQL and run the sql directly without modeling

*Creating Attribute View and Analytic View with the fact table and dimension tables, and then do query against the Analytic View.
I am new to HANA, and I am not sure which one is preferred and why, could someone please help?

A: Your question assumes that writing SQL queries is not data modelling. That's not correct.
While the basic structures of SQL databases (e.g. tables and views) are pre-defined and "schema-on-write" what you make of those structures is completely up to your query design.
That's one of the strengths (if you will) of SQL: it allows you to change your point of view of the data and ask different questions.
But the questions you ask are the models of your inquiry and your thinking.
In short: writing SQL is modeling..
Anyhow, I got what you meant by your question in the sense of "modelling" == "using the HANA graphical modeller".
The answer to your question is of course "it depends".
Graphical modelling is easy (for simple models), requires less typing and one can very easily expose those models to reporting tools and/or OData services.
SQL, on the other hand, is a very versatile tool for many data processing tasks and can quickly lead to results even in very complex scenarios.
Personally, I usually fiddle in SQL first and only use graphical models if I want to use specific features in them (e.g. anonymization functions in HANA 2 are not available in SQL).
Coming back to your example: if you want to reuse the dimension tables (especially when these are in fact not simple tables but complete join constructs on their own), I'd probably go with the graphical modelling approach first to establish the "cube"-structure.
The queries against that cube structure would then be written as SQL.
Finally, the execution performance should be very similar in most cases. I would use whatever tool I feel is best suited for a specific modelling task before I pick one due to "better performance". The reason for that is that fully understanding your data model (both the schema design and your query) is the best option to improve performance once you established that the results are correct.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to describe "hyper-scared?" I am looking for a wider expression for someone who is hyper-scared of pain and things that cause pain. I came up with "afraid of as much as a needle," but I get nowhere when I search for it on Google books. "Agliophobia" sounds too complex to me. Would an average teenager in the USA understand Agliophobia? Any other ideas?

A: Dictionary.com defines petrified as:

to benumb or paralyze with astonishment, horror, or other strong emotion:

In a sentence:

Sarah is petrified from pain, she suffers from agliophobia.

A: Terrified is your best option if you want a word readily understood.
terrified

very frightened:
terrified (of somebody/something) to be terrified of spiders
terrified (of doing something) I'm terrified of losing you.
terrified (that…) He was terrified (that) he would fall.
terrified (at something) She was terrified at the thought of being alone.
You look absolutely terrified! She looked at him with wide, terrified eyes.

So you could say:

Terrified of pain.

-- Oxford


text:
Q: Extract number from desired position of div classes content, and sum them using jQuery and regex I need to get the numbers from divs with specific classname and sum them.
code example looks like this:

38440 (19)

38444 (4)

31993 (6)

For example, i want here to get all the latest numbers 19,4,6 and then sum them (sum = 29).

A: You can use each to loop over all the elements and regex to extract the number form the string.
See comments inline in the code:
var total = 0; // Initialize to zero

// For all the elements having refineItem class
$('.refineItem').each(function() {
    total += parseInt($(this).text().match(/\((\d+)\)/)[1], 10) || 0; // Use zero when no matching number
});
$('#myInput').val(total); // Update the value of textbox

Regex Explanation

*

*/: Delimiters of regex

*\(: Matches literal (

*\): Matches literal )

*(): Capturing group

*\d+: Matches one or more digits

DEMO

A: Try
var count = 0;
$('.refineItem').each(function() {
    count += parseInt($(this).text().split("(")[1].split(")")[0]);
});
 alert(count);

Fiddle

A: With JQuery you can iterate over each div by using class name you have provided and also can get the text written inside the div and after that using the match function you can get the number from that text and convert it into number so that you can add that into a variable and get the output.
var total = 0;
$(".refineItem").each(function(){
total += Number(Number($(this).text().trim().match(/\((\d+)\)/)[1]));
});

Or
var total = 0;
$(".plz3").each(function(){
total += Number(Number($(this).text().trim().match(/\((\d+)\)/)[1]));
});

You can also check this example on JSFiddle
http://jsfiddle.net/harshgupta69/pgugh65e/


text:
Q: How do I get a list of users with the Core Service? I'm trying to get a list of the available users from the Core Service. I spend quite some time looking at the available service methods and the most obvious seemed to be this:
TrusteesFilterData trusteesFilterData = new TrusteesFilterData
                                        {
                                            BaseColumns = ListBaseColumns.IdAndTitle,
                                            IsPredefined = false,
                                            ItemType = ItemType.User
                                        };
XElement listTrustees = client.GetSystemWideListXml(trusteesFilterData);

However, the code throws an error when calling GetSystemWideListXml - Unable to create Abstract Class. Am I using the correct approach and, if so what am I doing wrong? If not, what should I be doing instead?

A: Take a look at the samples in the open source project for workflow notification
http://code.google.com/p/tridion-notification-framework/source/browse/NotificationService/NotificationService/Worker.cs
Lines 22 - 26 in the DoWork() method should do what you need - I think need to use UsersFilterData rather than TrusteesFilterData
var users = client.GetSystemWideList(new UsersFilterData { BaseColumns = ListBaseColumns.IdAndTitle, IsPredefined = false });


text:
Q: Unordered List loads slowly, causes it to align vertical for 1-2 seconds after which aligns horizontal? I saw this post Navigation Menu CSS loads slowly, causes it to align vertically for a few seconds?
Tried it but it didn't help.
Using it in asp.net project.
Site.Master code:

                            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">

                            </button>

ADMIN

CONFIGURATION

REPORTS

UPLOAD

BILLING

after 1-2 seconds:

----------------------EDIT STARTS HERE-----------------------
Note: Bootstrap css were not used, extremely sorry for that.
Plain css and html in site.master page are used.
Ok, So I finally, kind of, found the issue myself.
Trials: Tried all the suggestions provided in the answers, Thank you all for that but they didn't help.
Issue: I created an empty aspx page with no content in it and loaded it with master page. What I see is below:

On the other hand when the page with some content loads it sets the navbar correctly like this, looks like when the Admin page loads it is empty for 1-2 seconds and when it renders it sets the correct style:

So what I did is I put below code to make it less ugly :(
li{
display: inline;
}

which now will show up like :

Any other suggestions guys ?

A: Your code is missing the part where you include Bootstrap, and that is the main point. Your navbar is styled by Bootstrap, so it won't be styled until the Bootstrap's CSS file is loaded.
Put the Bootstrap CSS in the  part of your page in a <link> element.
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

This is your code without bootstrap: https://jsfiddle.net/xa2ychxn/ and this is your code with the Bootstrap's CSS file in the  section: https://jsfiddle.net/edaovwjt/
You are using class names from Bootstrap (navbar navbar-default). As you don't have any CSS code to make the navbar inline, when you finally get the expected result that means that something else gets loaded: that's Bootstrap.
I think you are loading something in the page using Ajax, and the content that is loaded contains bootstrap's CSS. That's why you don't know that you are using it, and why it is loaded some time after the page rendering.

A: Have you tried putting the styles in a CSS file or in a style tag in the head?

                            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">

                            </button>

ADMIN

CONFIGURATION

REPORTS

UPLOAD

BILLING

Alternatively, if you do have a linked CSS sheet, check the styles applied to the classes in your header. Some of the elements are probably rendered according to the CSS styles first, then the inline styles are overriding them as elements are rendered.

A: I know this might be a longshot but can you try using Minified versions of the bootstrap and jquery.Just give it a try and let me know
Try using these :
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

A: The problem seems to come from external style sheets.
During the brief period where the LI elements are displayed vertically, i guess you're still busy loading CSS from external files.
Does it still happen if you add the following CSS to the style element in the head of your page?
.navbar ul
{
  list-style:none;
}

.navbar ul li
{
  display:inline-block;
}

.navbar ul li a
{
 /* i have no idea if this is right. it is just an approximation. */
 /* you will have to fiddle with it until it is right. */
  padding:10px 20px;
}

(or see this codepen)


text:
Q: How to update multiple computers with QGIS on a network? We have ca. 30 Computers with QGIS 2.14 and I want to update them to QGIS 2.16
for the first step and in the future simply update, when it's necessary.
The operating system is windows 7. I tried to make a configured installation like it is described in the following article http://planet.qgis.org/planet/tag/windows/
But the changed bat file doesn't work.
Has anyone experience with this?


text:
Q: transform the data and create histogram with facets in R I have 400 columns with dynamic names (t_namelist1_namelist2). There are 20 names in each namelist1 and namelist2. I have to create a histogram with facets 20 by 20, with labels -

*

*along row - namelist1

*along col - namelist2

Can someone please show how to transform the data using pivot_longer() using _ which separates the three parts t, namelist1 and namelist2
In the sample problem, I have a tibble with 4 columns, I want to create 4 individual histograms in 2by2 facets with labels -

*

*along row - a and b

*along col - x and y

Thanks
library(tidyverse)

t_a_x <- rnorm(100)
t_b_x <- rnorm(100)
t_a_y <- rnorm(100)
t_b_y <- rnorm(100)

tbl <- tibble(t_a_x, t_a_y, t_b_x, t_b_y)

# create a histogram in 2 by 2 facets with labels -
# along row - a and b
# along col - x and y

A: The first chunk of code below rearranges the example data into three-column data frame, each column corresponding to either "ab", "xy", or the value ("t"); basically separating the original column name by "_". Then you can plot and facet based on "xy" and "ab".

# Rearrange table by separating the column names by "_" using pivot_longer()
tbl_formatted <- tbl %>% pivot_longer(everything(),
   names_to = c(".value", "ab", "xy"),
   names_sep = c("_")
     )

# Plot
tbl_formatted %>% ggplot(aes(x = t, y = t)) +
   geom_point() +
   facet_wrap(facets = ab ~ xy)

A: This is a very basic version of the plot; you can customize it with colors and more.
To get it, you need to properly rearrange your dataframe:
library(tidyverse)

tbl <- tibble(value = c(t_a_x, t_b_x, t_a_y, t_b_y),
              lab1 = rep(c("a", "b", "a", "b"), each = 100),
              lab2 = rep(c("x", "x", "y", "y"), each = 100))

ggplot(tbl) +
  geom_histogram(aes(value), binwidth = 0.5) +
  facet_grid(lab1~lab2)


text:
Q: How to use a custom debug.keystore in Delphi? We often need to set debug.keystore fingerprint in libraries (like Facebook SDK or Firebase).
However, as I understand this file is unique and generated for each user and even for each version of Delphi. So for every Delphi update or new user in the team we need to log and update the fingerprint in every API we use.
Is there any way we can specify in project settings exact debug.keystore file we want to use (for debugging).

A: Delphi does not have setting allowing you to specify location of debug.keystore.
It uses file located in C:\Users\YOURUSERNAME\AppData\Roaming\Embarcadero\BDS\19.0
You have to manually copy file you want to use into that location (use appropriate version number - above path is for Delphi Tokyo). Also when upgrading from one version to another just copy existing file to location appropriate for new version.
Yo can also freely share same debug.keystore among internal developers using different computers.


text:
Q: Is _gaq.push (Google Analytics) really asynchronous? According to the documentation, Google Analytics asynchronous tracking code is "asynchronous" in the sense that you can push items to the _gaq array before ga.js is loaded. Once it is loaded, push calls are executed immediately:

At this point, _gaq is no longer an
  Array, but an [Analytics] Object, and
  instant execution of the tracking
  methods is possible.

Does this mean that calling push in onclick (after ga.js is loaded) can block my other code until the call is complete? Or is it really asynchronous? In this case, can navigating away from my page prevent the call to push from completing?

A: I can confirm that navigating away from the page prevents Analytics from tracking anything. Possible workaround is to open the target page in a blank window using target="_blank" or wrapping the _gaq.push call in a custom function that waits for the onload of tracking gif. The latter causes a delay before the response to the user click, which might get more significant on high latency network (e.g. mobile).

A: I found an unobfuscated version of ga.js. The tracking information is sent to Google using an image object that is not added to the DOM. A handler is added to the image's onload event. Based on this, I don't believe that calling push will block my code (at least not for long), and whatever it is doing in onload will be asynchronous. This means that navigating away from the page can possibly prevent some of my analytics tracking from being logged. If anyone can confirm these things, I will mark your answer as correct.


text:
Q: CiscoAnyconnect : could not connect to server after prévious config reload We have a Cisco 881 router hosting a SSL webvpn gateway. This gateway is used by mobile users to connect through AnyConnect 4.4.
This system was correctly configured and working perfectly. (Certificates, trustpoints, SSL gateway, SSL context, ...)
Yesterday, we made a "bad" modif in the router config. So we have reloaded the previous good configuration that was working correctly. (copy tftp start and router reloaded)
Now, AnyConnect says :

Could not connect to server. Please verify Internet connectivity and server address.

The web page https://fqdn:port is unavailable.
I've telneted publicip:port. No error
In the router "show webvpn gateway SSL1" says the gateway is up and "show webvpn context SSL" says also context is up.
What could be damaged in the router config despite good config reload and multiple reboots ?

A: As stated in the third comment above, the solution was to recreate the full certificate chain :

*

*Import the RSA key pair

*Recreate the trustpoint for this RSA key pair

*Import CA root and intermediate certificates and recreate the corresponding trustpoints

*Import the final SSL certificate

Not sure that the first step (normally impossible if the RSA keypair has not been previously exported or is not exportable) was really necessary. But it works.
Best regards,
Guy


text:
Q: /etc/lightdm/unity-greeter.conf file missing I have no /etc/lightdm/unity-greeter.conf file. but there is /etc/lightdm/lightdm.conf and /etc/lightdm/users.conf but there isn't a background=path/to/image line in either of those files.
Related:

*

*How do I change the wallpaper of the login screen?

A: In Ubuntu 12.04, your lightDM background is automatically set to your background image in session as long as your background image is in the /usr/share/backgrounds/ folder. If your background image is not in that folder, you can copy it there via sudo cp /location/of/image/here.png /usr/share/backgrounds/, then add it to your background images in the Appearance Settings and set it as your background image. Now when you log out, you should see your background image as your lightDM background!

A: GNOME's dconf editor has a quick and easy GUI way to fix this (same directions as the gsettings answer already given).
Navigate to com.canonical.unity-greeter and change the background field to the path of the image you want.

A: I created a script that would let me define if the grid is to be displayed in the unity-greeter, whether the background image is to be gotten dynamically from the user (that does not work for me, but other posts suggested, that the image must fit the screen dimensions for it to work) and you can define the background image to be displayed (if you do not use the dynamic background image):
#!/bin/bash
GRID=$1
DYNAMIC_BG=$2
BG_IMAGE=$3

usage ()
{
  echo "Usage: ConfigureUnityGreeter <draw grid> <draw user bg> <bg image>" >&2
  echo "         <draw grid>   : true or false" >&2
  echo "         <draw user bg>: true or false" >&2
  echo "         <bg image>    : full path to image file" >&2
}

if [ -z "$GRID" ]
then
  usage
else
  if [ "$GRID" != "true" -a "$GRID" != "false" ]
  then
    echo "Grid parameter must be 'true' or 'false'!\n" >&2
    usage
  fi
fi

if [ -z "$DYNAMIC_BG" ]
then
  usage
else
  if [ "$DYNAMIC_BG" != "true" -a "$DYNAMIC_BG" != "false" ]
  then
    echo "User background parameter must be 'true' or 'false'!\n" >&2
    usage
  fi
fi

if [ "$DYNAMIC_BG" == "false" ]
then
  BG_IMAGE_CMD="set"
  if [ -z "$BG_IMAGE" ]
  then
    echo "Missing background image file name." >&2
    usage
  fi
else
  BG_IMAGE_CMD="reset"
  if [ -n "$BG_IMAGE" ]
  then
    echo "Background image file name ignored!" >&2
    BG_IMAGE=""
  fi
fi

sudo xhost +SI:localuser:lightdm
sudo su lightdm -s /bin/bash <<EOF
set -x
gsettings set com.canonical.unity-greeter draw-grid $GRID
gsettings set com.canonical.unity-greeter draw-user-backgrounds $DYNAMIC_BG
gsettings $BG_IMAGE_CMD com.canonical.unity-greeter background $BG_IMAGE
exit
EOF

Feel free to use to your liking!

A: In 12.04, unity-greeter no longer uses /etc/lightdm/unity-greeter.conf.  It took me hours to figure this out... luckily I found this link on the Ubuntu forums (see post #6).  Now the greeter uses gsettings for configuration.  Now my question is (but perhaps I should post this as a new question)... how am I supposed to use gsettings to configure unity-greeter?
In post #173 on page 19 of that thread above, someone suggests
gsettings set com.canonical.unity-greeter background '/path/to/wallpaper.jpg'

but the above doesn't work (at least for me).  Maybe someone more familiar with gsettings can shed some light here.
Update: Here's how to configure unity-greeter in 12.04:  https://askubuntu.com/a/121594/43660  It turns out you need to be the 'lightdm' user for those settings to take.


text:
Q: Reference for singular integral operators such as $(-\Delta)^{-1}$ or $\nabla(-\Delta)^{-1}$ I'm currently working on understanding certain mean-field limits in kinetic theory, and the equations I'm working with are usually of the form
$$\partial_t f +v\cdot\nabla_x f \pm c\nabla(-\Delta)^{-1}\rho_f\cdot\nabla_v f=0$$ for $f:\mathbb R_x^d\times\mathbb R_v^d\times\mathbb R_t\to\mathbb R$ and where $\rho_f = \int\! f\,\mathrm dv$, or
$$\partial_t f + A\nabla(-\Delta)^{-1}f\cdot\nabla f=0$$ for $f:\mathbb R_x^d\times\mathbb R_t\to\mathbb R$, for some matrix $A:\mathbb R^d\to\mathbb R^d$.
What all of these equations have in common is that they are integro-differential equations, where we must understand the boundedness properties of the operator $\nabla(-\Delta)^{-1}$, typically expressible on a suitable domain $\Omega$ using Green's functions as
$$
\mathscr K u(x):=\nabla(-\Delta)^{-1}u(x)=\int_\Omega\!\nabla_x G_\Omega(x,y)u(y)\,\mathrm dy.
$$
Now, when $d=2$, I know that we have $\mathscr K:L^1\cap L^\infty(\Omega)\to C^{1,\mathrm{log}}(\Omega)$, where $C^{1,\log}(\Omega)$ denotes the log-Lipschitz functions. This fact is used to develop the 2D well-posedness theory of the incompressible Euler equation.
Are there any similar results and references that can be used generally for SIOs like $\mathscr K=\nabla(-\Delta)^{-1}$? I suspect some tools from harmonic analysis and PDO theory will come in handy, but I don't know of any good reference for integrating SIOs – the main reference I know, Christ's Lectures on Singular Integral Operators deals mainly with degree $0$ operators.

A: Make $0$-order operator applying extra $\partial_j$ and use your reference.


text:
Q: specify parent MDI form I am trying to specify the parent MDI form when showing a form in c#
All the examples suggest just using
FormVariable.Parent = this;

this works ok assuming you want the form to be opened from the parent window all the time.
I want to be able to open a form and set the Parent form to my MDI Parent form by specifying the name.
in VB.net I have used
Me.MdiParent = TheNameOfMyParentForm

When I try anything similar in c#
this.MdiParent = CruxMDI();

I get

'Crux.CruxMDI' is a 'type' but is used like a 'variable'

A: Form.MdiParent has to reference a concrete instance. So, maybe it would be a good idea to implement a Singleton pattern (you probably don't want to allow multiple parent windows either way, do you?) in your Parent container, so that you can reference it from wherever you need to. Then you'll just type:
this.MdiParent = CruxMDI.Instance;

If you want to add such behavior automatically and it needs to happen in many Forms in your application, you may consider an option when you'd create a custom base class inheriting from Form. That way you specify this once and then you just need to be sure to inherit your new Forms from this baseclass instead of a default Form.
Either way, you need to have some kind of mechanism to reference the instance of your MDI container.


text:
Q: How to take a screenshot in Java without AWT / Robot (entire screen) I've seen the usual way of taking a screenshot in Java where you use a Robot and a BufferedImage to take a screenshot. But is there a way of doing this without using Robot and BufferedImage?
Why?
I am working with JavaFX and I don't like mixing up AWT (Swing) and JavaFX.
Not a big problem, I know, but I would love to keep everything within one library.
I've also heard that Robot is a bit slow, but that's not the main reason.
EDIT: I would like to capture the whole screen and not just an area like a scene.
Thanks in advance :D


text:
Q: MaxJsonLength Error in MVC while Binding data to KendoGrid I have been working on this Issue for quite some time now.
Basically, I'm using Kendo Grid to display data from Controller to the ViewPage.
But, when I run the view, I Keep getting this error
maxJsonLengthError
How do i rectify this problem?? Appreciate all the help in advance.
Refer to my EDIT
Here is my ControllerCode:-
public ActionResult Index()
{
    ViewData["DealsList"] = objDealerModel.listDeals;
    return View();
}

And Here is my ViewPage Code:-
@(Html.Kendo().Grid((IEnumerable<WCB.Models.DealerQueue>)ViewData["DealsList"])
        .Name("Grid")
        .Columns(columns =>
        {
            columns.Bound(p => p.DealId).Visible(false);
            columns.Bound(p => p.DealRefNo).Title("Deal No");
            columns.Bound(p => p.CustomerName).Title("Customer Name");
            columns.Bound(p => p.DealType).Title("Deal Type");
            columns.Bound(p => p.Location).Visible(false);
            columns.Bound(p => p.CreatedDate).Title("Created Date");
            columns.Bound(p => p.Currency).Title("Currency");
            columns.Bound(p => p.Amount).Title("FCY Amount");
            columns.Bound(p => p.DealValue).Title("Deal Amount").ClientTemplate("#= kendo.toString(DealValue, 'n') #");
            columns.Bound(p => p.Status);
            columns.Command(command => command.Custom("ViewDetails").Click("ViewDealDetails")).Title("View");
        })
                .Pageable(pageable => pageable
                .Refresh(true)
                .PageSizes(true)
                .ButtonCount(20))
        .Sortable()
        .Scrollable(scr => scr.Height("auto"))
        .Filterable()
        .DataSource(dataSource => dataSource
        .Ajax()
        .ServerOperation(false)
    )

)
EDIT:
i've tried using this piece of code in myController:-
var jsonResult = Json(objDealerModel.listDeals, JsonRequestBehavior.AllowGet);
jsonResult.MaxJsonLength = int.MaxValue;
return jsonResult;

Can anyone suggest based on this what changes need to be made in my viewPage for KENDO GRID?? Not too familiar with Kendo

A: I have a same problem and i solve this by setting a higher value for aspnet:MaxJsonDeserializerMembers in the appSettings:
<appSettings>
  <add key="aspnet:MaxJsonDeserializerMembers" value="150000" />
</appSettings>

If those options are not working you could try creating a custom json value provider factory using JSON.NET as specified in this thread.
Edit:
Or if this is related to the Kendo Grid binding then you can try this.
public class MySerializer : Kendo.Mvc.Infrastructure.JavaScriptInitializer
{
    public override IJavaScriptSerializer CreateSerializer()
    {
        var serializer = base.CreateSerializer() as DefaultJavaScriptSerializer;
        serializer.MaxJsonLength = serializer.MaxJsonLength * 100;
        return serializer;
    }
}

Kendo.Mvc.Infrastructure.DI.Current.Register<Kendo.Mvc.Infrastructure.IJavaScriptInitializer>( () => newMySerializer() );


text:
Q: How to incorporate drift back into my Sql Server Database Project? With the usual source control solutions, a programmer will update his code from the repository and then check in his changes to the repository.
The only way I know how to incorporate drift back into my project would be to use the Schema Compare feature, however this feature just tells me what the differences between my project and the target db are without giving any indication as to what changes originated where so I could potentially revert changes I've made on my end if I'm not careful to exclude those items when updating my project using Schema Compare.
Is there a better way to incorporate drift back into my project without having to worry about being very careful not to blow away changes I've made?

A: If you use SSMS, you could try using SQL Source Control in conjunction with your database project. We've announced a beta build with this functionality working here:
http://social.msdn.microsoft.com/Forums/en-US/ssdt/thread/0c763f98-c55a-44a7-9100-80a6d9223d04
This will distinguish between changes made on the database that have yet to be sync'ed down to the project, and changes that are in the project that need to be applied to the database. If this doesn't meet your needs, the SQL Source Control project team would love to hear from you!

A: sqlpackage.exe has an option to detect database drift (i.e. changes that have been made since a database was deployed):
DriftReport Parameters.
A SqlPackage.exe report action creates an XML report of the changes that have been made to the registered database since it was last registered.
It requires you to register the database when you deploy it, but I don't think that's a particularly big deal.
Hope that helps.
JT

A: You can compare your database project (SSDT) as target, and the "drifted database" as source, and the "update" button will update your model just as easily.
In other words you can use the schema compare to import the changes into your SSDT project, then turn around and publish your schema (with those changes newly incorporated) back onto the database.


text:
Q: Mouse undetected, Graphics crazy - trying to save my dinosaur desktop Thanks in advance for your help on this one!
I've been trying to save my HP Pavilion a1540n, retiring it purely to word processing in my office. The sequence of events was triggered when I tried to upgrade to Ubuntu 14 and the desktop environment became very slow (I was warned the graphics card was not supported). Since then I've tried downgrading to several systems (everything from 10-13) and have encountered different but more crippling graphics problems (screen gets frozen blocks of colorful fuzz or other disorganized patterns of color). I've wound up on Ubuntu 11 and my mouse is not responding (although the keyboard is and I can use the terminal). The mouse works in boot repair envt so it's not a physical malfunction. If I could get any operating system where the graphics and mouse are modestly functional I'd be quite satisfied.

A: The problem with Ubuntu 14.04 probably isn't driver related, it's more likely to be that the demands on your graphics card are too great. As you go back through older unsupported versions, there will be less and less hardware supported, which may explain the mouse problems.
I'd recommend installing either Lubuntu or Xubuntu which are both lightweight desktop environments. Lubuntu is slightly less resource hungry than Xubuntu, so is often a better choice for older PCs, but it does have quite a plain feel to it. Xubuntu definitely looks more swish. Whichever you choose, I'd recommend downloading LibreOffice for word processing etc.
As a side note, it's generally not a good idea to use an old unsupported release, security fixes aren't maintained, and you can't ask questions about them on Ask Ubuntu either! Using an LTS version is the best way to guarantee stability in your system, 12.04 and 14.04 are the current LTS releases, and 16.04 is just around the corner (it's in final Beta testing at the moment). Personally I normally wait for the first point (16.04.1) release of a new version to give it time for bugs to be ironed out.


text:
Q: Rotating line with pythagoras formula I want to rotate a line but i don't want to use radians or pi.I created an algorithm (if i can call  it like that).I use pythagoras formula with two functions and two timers to rotate the line ,but i think there's an error because it rotate faster after 180 degrees rotation.Why?Here's my code:
Public Class Form1
Private Structure poi
    Dim x As Integer
    Dim y As Integer
End Structure

Dim x1 As Integer, y1 As Integer
Dim x As Integer, y As Integer
Dim val As Integer
Dim obxy As poi
Dim moupos As poi
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick

    Call calcxy(val, 100)

    x = obxy.x
    y = obxy.y
    val = val - 1

    Refresh()
    If -val > 100 Then
        Timer1.Enabled = False
        Timer2.Enabled = True
    End If
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If Button1.Text = "Start" Then
        Timer1.Enabled = True
        Button1.Text = "Stop"
    Else

        Timer1.Enabled = False
        Timer2.Enabled = False
        Button1.Text = "Start"
    End If

End Sub

Sub calcxy(choice As Integer, radius As Integer)
    Dim yval As Integer
    yval = Math.Sqrt(radius ^ 2 - choice ^ 2)

    obxy.x = moupos.x - choice
    obxy.y = moupos.y - yval
End Sub
Sub recalcxy(choice As Integer, radius As Integer)
    Dim yval As Integer
    yval = Math.Sqrt(radius ^ 2 - choice ^ 2)

    obxy.x = moupos.x - choice
    obxy.y = moupos.y + yval
End Sub

Private Sub Form1_MouseClick(sender As Object, e As MouseEventArgs) Handles Me.MouseClick
    moupos.x = e.X
    moupos.y = e.Y
End Sub

Private Sub Form1_Paint(sender As System.Object, e As System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint
    Dim pen As New System.Drawing.Pen(System.Drawing.Color.Black, 1)
    e.Graphics.DrawLine(pen, moupos.x, moupos.y, x, y)
End Sub

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    val = 100
End Sub

Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
    val = val + 1

    Call recalcxy(val, 100)

    x = obxy.x
    y = obxy.y
    Refresh()
    If val + 1 > 100 Then
        Timer2.Enabled = False
        Timer1.Enabled = True
    End If
End Sub
 End Class


text:
Q: Can you instantiate the unspecialized version of a template and inherit from it inside the specialization? I am trying to define a Vector as a row/column Matrix. Vector needs some methods which Matrix doesn't have, so I specialized Matrix:
template<typename T, unsigned N, unsigned M>
struct Matrix {
    T data[N][M];
};

template <typename T, unsigned N>
struct Matrix<T, N, 1> : public Matrix<T, N, 1> {
    T at(unsigned index) {
        return data[index][0];
    }
};

template <typename T, unsigned N>
using Vector = Matrix<T, N, 1>;

This code does not compile, because the specialization is a recursive type. The reason I want inheritance here is so that I can include all of the content of Matrix into the specialization without copy&paste.
Is there a way that I can instantiate the original Matrix and inherit from it? And if there was, would my type become non-recursive?
Another way of solving this problem that comes to mind is to simply #include the contents of a regular Matrix into both the initial definition and all specializations. But this is far from idiomatic.

A: Here is one way to do it:
template<typename T, unsigned N, unsigned M>
struct Matrix {
    T data[N][M];
};

template<typename T, unsigned N>
struct MatrixTN : Matrix <T, N, 1> {
    T at(unsigned index) {
        return this->data[index][0];
    }
};

template<typename T, unsigned N>
using Vector = MatrixTN <T, N>;

Note that this->data is needed to delay evaluation of data to the second phase of template lookup.
Live demo

A: In C++20, you might use requires to discard methods:
template<typename T, unsigned N, unsigned M>
struct Matrix {
    T data[N][M];

    T at(unsigned index) requires (M == 1) {
        return data[index][0];
    }
};

In previous standard, you might use SFINAE instead.

A: You can use SFINAE to disable method. It's necessary to have template method with template argument dependent on the class template parameter.
C++11:
#include <type_traits>

template<typename T, unsigned N, unsigned M=1>
struct Matrix
{
    T data[N][M];

    template<typename V = T>
    typename std::enable_if<M == 1, V>::type at(unsigned index)
    {
        return data[index][0];
    }
};

template <typename T, unsigned N>
using Vector = Matrix<T, N, 1>;

int main()
{
    Matrix<int, 2, 3> m;
    Vector<int, 5> v;

    // m.at(0);
    v.at(1);
}

C++14:
#include <type_traits>

template<typename T, unsigned N, unsigned M=1>
struct Matrix
{
    T data[N][M];

    template<typename V = T>
    std::enable_if_t<M == 1, V> at(unsigned index)
    {
        return data[index][0];
    }
};

template <typename T, unsigned N>
using Vector = Matrix<T, N, 1>;

int main()
{
    Matrix<int, 2, 3> m;
    Vector<int, 5> v;

    // m.at(0);
    v.at(1);
}

C++20 (Thanks to Jarod42):
template<typename T, unsigned N, unsigned M = 1>
struct Matrix
{
    T data[N][M];

    T at(unsigned index) requires (M == 1)
    {
        return data[index][0];
    }
};

template <typename T, unsigned N>
using Vector = Matrix<T, N, 1>;

int main()
{
    Matrix<int, 2, 3> m;
    Vector<int, 5> v;

    // m.at(0);
    v.at(1);
}

godbolt


text:
Q: Strange result when inserting object to NSMutableArray at Index 1 In my application, I want to insert object into NSMutableArray:
NSMutableArray *test = [NSMutableArray arrayWithObjects:[NSNumber numberWithInt:1], [NSNumber numberWithInt:3], [NSNumber numberWithInt:4], nil];
[test insertObject:[NSNumber numberWithInt:2] atIndex:1];

I put breakpoint at second code line and the result in debug area is OK:
self = (MasterViewController *) 0x074b9cb0
test = (NSMutableArray *)   0x07462c50 @"3 objects"
   [0] = (id)   0x07461f10 (int) 1
   [1] = (id)   0x07473ec0 (int) 3
   [2] = (id)   0x074cbd30 (int) 4

But after run second code line, the result is unexpected:
self = (MasterViewController *) 0x074b9cb0
test = (NSMutableArray *)   0x07462c50 @"4 objects"
   [0] = (id)   0x074713f0 (int) 2
   [1] = (id)   0x07473ec0 (int) 3
   [2] = (id)   0x074cbd30 (int) 4
   [3] = (id)   0x07461f10 (int) 1

Can anyone explain why after insert at index 1 the first object (int 1) become last object, or this case is bug of ios 6.1?
When insert object at index > 1, there is no problem.

A: I rarely trust the results that come out of that area.  Use debugger commands instead.  The array is getting created correctly.  I copied and pasted those two lines and I got

(lldb) po test
  $0 = 0x1dda1ad0 <__NSArrayM 0x1dda1ad0>(
  1,
  3,
  4
  )

After the first line, and

(lldb) po test
  $1 = 0x1dda1ad0 <__NSArrayM 0x1dda1ad0>(
  1,
  2,
  3,
  4
  )

after the second line.  However, the results are the way you say in the variables window.  The moral of the story is, trust the debugger instead of the variables window!


text:
Q: Why doesn't json.loads('{"Testing": "This quo\\\\"te String"}')) work? I'm trying to understand why the code below doesn't work in Python:
import json

s = json.loads(' {"Testing" : "This quo\\\\"te String"} ')

print(s)

Theoretically, what I should get back is {'Testing' : 'This quo\"te String'}.
These ones work fine:
print(json.loads(' {"Testing" : "This quo\\"te String"} ')) ----> {'Testing' : 'This quo"te String'}

print(json.loads(' {"Testing" :"This quo\\\\\\"te String"}')) ----> {'Testing' : 'This quo\\"te String'}

I'm guessing it has something to do with the Idiosyncrasy of having a \" in the dict, but can't figure out what exactly is happening.

A: The string This quo\"te String requires two escapes in normal Python: one for the \ and one for the ", making three backslashes in all:
>>> print("This quo\\\"te String")
This quo\"te String

For json, all those backslashes must be themselves escaped, because the string is embedded inside another string. Thus, six backslashes are required in total:
>>> print(json.loads('"This quo\\\\\\"te String"'))
This quo\"te String

However, if raw-strings are used, no extra escapes are required:
>>> print(json.loads(r'"This quo\\\"te String"'))
This quo\"te String

In your first example, the four backslashes will be parsed as a single literal \ (i.e. as an escaped backslash), leaving the " unescaped.
Note that it makes no difference if the string is inside a dict - the result will be exactly the same:
>>> dct = json.loads('{"Testing": "This quo\\\\\\"te String"}')
>>> print(dct['Testing'])
This quo\"te String

A: You need an odd number of pairs of backslashes in your python string to end up with an odd number of backslashes in the json. Each pair of backslashes then becomes a single backslash and you need one more -- the odd one -- to escape the quote mark.


text:
Q: How to login to instacart using requests? So I tried the following rough version:
import requests
from bs4 import BeautifulSoup

headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36'
    }

session = requests.Session()

res1 = session.get('http://www.instacart.com', headers=headers)
soup = BeautifulSoup(res1.content, 'html.parser')
token = soup.find('meta', {'name': 'csrf-token'}).get('content')
data = {"user": {"email": "user@gmail.com", "password": "xxxxx"},
        "authenticity_token": token}
res2 = session.post('https://www.instacart.com/accounts/login', headers=headers, data=data)
print(res2)

I always get the following error:
<Response [400]>
apparent_encoding:'ascii'
connection:<requests.adapters.HTTPAdapter object at 0x0000021F3FF8F940>
content:b'{"status":400,"error":"There was a problem in the JSON you submitted: Empty input () at line 1, column 1"}'

What am I doing wrong?

A: Actually you were missing the correct Params for the POST request.
I've made a GET request to the main site to collect the necessary authenticity_token which is used within the POST request. and then made the POST request for the correct login url.
import requests
from bs4 import BeautifulSoup

params = {
    'source': 'web',
    'cache_key': 'undefined'
}

data = {
    'email': 'email@email.com',
    'grant_type': 'password',
    'password': 'yourpassword',
    'scope': '',
    'signup_v3_endpoints_web': 'null'
}

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:75.0) Gecko/20100101 Firefox/75.0",
}

def main(url):
    with requests.Session() as req:
        r = req.get(url, headers=headers)
        soup = BeautifulSoup(r.content, 'html.parser')
        data['authenticity_token'] = soup.find(
            "meta", {'name': 'csrf-token'}).get("content")
        r = req.post(
            "https://www.instacart.com/v3/dynamic_data/authenticate/login", params=params, json=data, headers=headers).json()
        print(r)

main("https://www.instacart.com")


text:
Q: How to set Project Linking in VS2019 I basically got the same error as this post from 3 years ago: Xamarin Android Build Failed "Invalid value for outputAssembly" but I don't understand the solution and was looking for help.
After not changing any code in my master branch, today in VS2019 and Xamarin.Forms 4.4.0.991477, I went to build my app in android, when I got this error
obj\Debug\...\Appname.Droid.dll is an invalid value for the
"OutputAssembly" parameter of the "Csc" task. Multiple items
cannot be passed into a parameter of type
"Microsoft.Build.Framework.ITaskItem".

Now I don't understand the solution from the previous post,

You have to set your Project Linking to Sdk Assemblies Only and set support architecture to armeabi - v7 and x86.
  After try to clean and rebuild the project

I don't really understand how to go about doing this, where do I go in VS to access these settings? And also is this the best answer in 2020, or is there another one? Thanks!


text:
Q: How to search an entire CVS repository (all branches/history/comments)? If I want to essentially grep every line ever in the repository, is there a way to do it? I know this would take a long time for large projects.
If not all inclusive, at least just the current branch and its entire source history?
Edit: I should have been more explicit. What if I don't have direct access to the server that the CVS repository is on? So I couldn't directly grep the filesystem that has the CVS repository.

A: There is no way to do this with standard CVS tools without access to the repository. A third party tool out there may do it (I don't know of one, although CS-CVS seems to claim to), but to do it programatically, you would have to do CVS logs on all the relevant files, and then retrieve and search each version reported by cvs in the logs (cvs log is a command line option in CVS that shows you the revision history of any file, but it doesn't show you the contents).

A: Here's what I recently used, in a case where I didn't have access to the server. It seemed to work that time. Call it from inside a working copy, with cvs in the PATH. Note that this doesn't search commit messages, but you can simply grep 'cvs log' for that.
#!/usr/bin/perl

# Searches CVS diffs and first revisions behind the current working
# directory for an expression (perlre syntax).

# Synopsis: cvsgrep [-n] <search-expression> [<file_1> ... <file_n>]

# -n means that contents of matching files should not be printed to stdout.

use Getopt::Std;

my %options=();
getopts("n",\%options);
my $no_content_dump=$options{"n"};

my $search_term=shift
    or die "Error: usage is: cvsgrep [-n] <search-expression>".
    " [<file_1> ... <file_n>]";

sub quote_fn
{
    my $fn=shift;
    $fn =~ s/\'/\'\"\'\"\'/g;
    "'".$fn."'";
}

my $args_str;
while(@ARGV)
{
    my $arg=shift;
    $args_str.=' ' if $args_str;
    $args_str.=&quote_fn($arg);
}

print
    "Searching for term: $search_term",
    ($args_str?" in: $args_str":""),
    "\n";

open CVSLOGH,"cvs log -N $args_str|" or die "Cannot execute cvs log: $!";

my @files_revisions=();

my $cur_file;
my $cur_revision;

while(<CVSLOGH>)
{
    chop;
    if(/^Working file\:\s*(.*)$/)
    {
        $cur_file=$1;
        $cur_revision='';
    }
    elsif(/^revision\s+(.*)$/)
    {
        $cur_revision=$1;
    }
    elsif((/^\=\=\=\=/ || /^\-\-\-\-/) && $cur_revision)
    {
        push @files_revisions,{file=>$cur_file,rev=>$cur_revision};
    }
}

close CVSLOGH;

my $matchcount=0;
my $count=0;
my $progress_msg="Scanned %d out of %d commit(s)\r";
my $erase_ln=(" " x (length($progress_msg)+20)) . "\r";

foreach my $file_revision(@files_revisions)
{
    printf($progress_msg,$count++,scalar(@files_revisions));

    my($file,$rev) = ($file_revision->{file},$file_revision->{rev});

    $rev =~ /^(.*\.)([0-9]+)/;
    my $revbase=$1;
    my $revlastdigit=$2;
    my $rev1=$revbase.($revlastdigit - 1);
    my $diffcommand = "cvs diff -N -r $rev1 -r $rev ".&quote_fn($file);
    open CVSDIFFH,"$diffcommand|" or die "Cannot execute cvs diff: $!";

    my $diffresult;
    while(<CVSDIFFH>)
    {
        if(/^[\<\>]/)
        {
            s/^.//;
            $diffresult.=$_;
        }
    }
    close CVSDIFFH;

    if($diffresult =~ /$search_term/s)
    {
        print "${erase_ln}FOUND: in diff for $file $rev1:$rev\n";
        $matchcount++;
        system($diffcommand) unless $no_content_dump;
    }
}

print "${erase_ln}Done ($matchcount match(es)).\n";

A: It depends on what you're looking for. CVS version files contain all of the edits that have ever happened to the file, in plaintext. So if you're simply looking for all files that contain a particular word, do a recursive grep on the repository.
If you're looking to find specific versions that contain those words, then you're going to have to extract the versions from the repository, which is expensive. However, if you can limit the set of files by grepping the repository, then it's not so bad.


text:
Q: ECPublicKey Serializability I am working on a project in which I need to pass generated public key (ECPublicKeyParameter)
over the network between two parties. But I am having problems serializing it. How can I serialize an instance of this class?


text:
Q: c# regex matches example I am trying to get values from the following text. How can this be done with Regex?
Input

Lorem ipsum dolor sit %download%#456 amet, consectetur adipiscing %download%#3434 elit. Duis non nunc nec mauris feugiat porttitor. Sed tincidunt blandit dui a viverra%download%#298. Aenean dapibus nisl %download%#893434 id nibh auctor vel tempor velit blandit.

Output
456
3434
298
893434

A: So you're trying to grab numeric values that are preceded by the token "%download%#"?
Try this pattern:
(?<=%download%#)\d+

That should work. I don't think # or % are special characters in .NET Regex, but you'll have to either escape the backslash like \\ or use a verbatim string for the whole pattern:
var regex = new Regex(@"(?<=%download%#)\d+");
return regex.Matches(strInput);

Tested here: http://rextester.com/BLYCC16700
NOTE: The lookbehind assertion (?<=...) is important because you don't want to include %download%# in your results, only the numbers after it. However, your example appears to require it before each string you want to capture. The lookbehind group will make sure it's there in the input string, but won't include it in the returned results. More on lookaround assertions here.

A: public void match2()
{
    string input = "%download%#893434";
    Regex word = new Regex(@"\d+");
    Match m = word.Match(input);
    Console.WriteLine(m.Value);
}

A: All the other responses I see are fine, but C# has support for named groups!
I'd use the following code:
const string input = "Lorem ipsum dolor sit %download%#456 amet, consectetur adipiscing %download%#3434 elit. Duis non nunc nec mauris feugiat porttitor. Sed tincidunt blandit dui a viverra%download%#298. Aenean dapibus nisl %download%#893434 id nibh auctor vel tempor velit blandit.";

static void Main(string[] args)
{
    Regex expression = new Regex(@"%download%#(?<Identifier>[0-9]*)");
    var results = expression.Matches(input);
    foreach (Match match in results)
    {
        Console.WriteLine(match.Groups["Identifier"].Value);
    }
}

The code that reads: (?<Identifier>[0-9]*) specifies that [0-9]*'s results will be part of a named group that we index as above: match.Groups["Identifier"].Value

A: It looks like most of post here described what you need here. However - something you might need more complex behavior - depending on what you're parsing. In your case it might be so that you won't need more complex parsing - but it depends what information you're extracting.
You can use regex groups as field name in class, after which could be written for example like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;

public class Info
{
    public String Identifier;
    public char nextChar;
};

class testRegex {

    const string input = "Lorem ipsum dolor sit %download%#456 amet, consectetur adipiscing %download%#3434 elit. " +
    "Duis non nunc nec mauris feugiat porttitor. Sed tincidunt blandit dui a viverra%download%#298. Aenean dapibus nisl %download%#893434 id nibh auctor vel tempor velit blandit.";

    static void Main(string[] args)
    {
        Regex regex = new Regex(@"%download%#(?<Identifier>[0-9]*)(?<nextChar>.)(?<thisCharIsNotNeeded>.)");
        List<Info> infos = new List<Info>();

        foreach (Match match in regex.Matches(input))
        {
            Info info = new Info();
            for( int i = 1; i < regex.GetGroupNames().Length; i++ )
            {
                String groupName = regex.GetGroupNames()[i];

                FieldInfo fi = info.GetType().GetField(regex.GetGroupNames()[i]);

                if( fi != null ) // Field is non-public or does not exists.
                    fi.SetValue( info, Convert.ChangeType( match.Groups[groupName].Value, fi.FieldType));
            }
            infos.Add(info);
        }

        foreach ( var info in infos )
        {
            Console.WriteLine(info.Identifier + " followed by '" + info.nextChar.ToString() + "'");
        }
    }

};

This mechanism uses C# reflection to set value to class. group name is matched against field name in class instance. Please note that Convert.ChangeType won't accept any kind of garbage.
If you want to add tracking of line / column - you can add extra Regex split for lines, but in order to keep for loop intact - all match patterns must have named groups. (Otherwise column index will be calculated incorrectly)
This will results in following output:
456 followed by ' '
3434 followed by ' '
298 followed by '.'
893434 followed by ' '

A: Regex regex = new Regex("%download#(\\d+?)%", RegexOptions.SingleLine);
Matches m = regex.Matches(input);

I think will do the trick (not tested).

A: This pattern should work:
#\d

foreach(var match in System.Text.RegularExpressions.RegEx.Matches(input, "#\d"))
{
    Console.WriteLine(match.Value);
}

(I'm not in front of Visual Studio, but even if that doesn't compile as-is, it should be close enough to tweak into something that works).


text:
Q: How can I treat a short integer as an array of elements in C? So I have an integer stored as a short. Let's say:
short i = 3000;

Which in binary is:
0011 0000 0000 0000

I was told I can treat it as an array of two elements where each element is a byte basically, so:
i[0] = 0011 0000
i[1] = 0000 0000

How can I accomplish this?

A: You could do it like this (assuming short is 2 bytes)
short i = 3000; // 3000 in Binary is: 00001011 10111000
unsigned char x[2] = {0};
memcpy(x, &i, 2);

Now x[0] will be 10111000 and x[1] 00001011 if this code runs on little endian machine. And reverse will hold true in case of big endian machine.
Btw. Your binary representation of 3000 looks wrong


text:
Q: dynamic programming approach for max sum GOLD MINE PROBLEM
This was asked in  an interview question but I am not able to understand the test cases
Like in ex 1->I know that max ans is coming on adding 6,4,2 but how {(1,0)->(2,1)->(2,2)} these move taking these values 6,4,2;
and
on (1,0) it will move top to bottom which is not a valid move
Gold Mine Problem
Given a gold mine of n*m dimensions. Each field in this mine contains a positive integer which is the amount of gold in tons. Initially the miner is at first column but can be at any row. He can move only (right->,right up /,right down) that is from a given cell, the miner can move to the cell diagonally up towards the right or right or diagonally down towards the right. Find out maximum amount of gold he can collect.
    Input : mat[][] = {{1, 3, 3},
                       {2, 1, 4},
                      {0, 6, 4}};
    Output : 12
    {(1,0)->(2,1)->(2,2)}

    Input: mat[][] = { {1, 3, 1, 5},
                       {2, 2, 4, 1},
                       {5, 0, 2, 3},
                       {0, 6, 1, 2}};
    Output : 16
    (2,0) -> (1,1) -> (1,2) -> (0,3) OR
    (2,0) -> (3,1) -> (2,2) -> (2,3)

    Input : mat[][] = {{10, 33, 13, 15},
                      {22, 21, 04, 1},
                      {5, 0, 2, 3},
                      {0, 6, 14, 2}};
    Output : 83

A: I believe you misunderstood the notation.
   C0 - C1 - C2
R0 1    3    3
R1 2    1    4
R2 0    6    4

Rows are marked with R and Columns with C.

Output : 12
{(1,0)->(2,1)->(2,2)}

Means:
{(R1, C0) -> (R2, C1) -> (R2, C2)}

*

*Since you can start on any row of the first column, you start on column 1.

*Then move right-down

*Then move right.

The same notation is used on the other example. Hope this helped!


text:
Q: how can i display two columns in listview. that columns data is coming from SQLite database How can i display two columns in listview that columns data is coming from sqlite database?In that columns first column is TextView and another column is EditView.
i have tried below code. But I got the following exception
unable to start the activity ComponentInfo:java.lang.NullPointerException.

the code is shown below.
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.categorynew);
    lv = (ListView)findViewById(android.R.id.list);
    getList();
}

public void getList()
{
    int x = 0;
    cur=db.rawQuery("SELECT * FROM detaillist ORDER BY symbol",null);
    ArrayList<String> al = new ArrayList<String>();
    ArrayList<String> al1 = new ArrayList<String>();
    cur.moveToFirst();
    while (cur.isAfterLast() == false) {
        al.add(cur.getString(cur.getColumnIndex("symbol")));
        al1.add(cur.getString(cur.getColumnIndex("position")));

        cur.moveToNext();
    }
    cur.close();
    String[] str = new String[al.size()];
    strArray = al.toArray(str);
    String[] str1 = new String[al1.size()];
    strArray1 = al1.toArray(str1);
    lv.setAdapter(new EfficientAdapter(this));
}

private static class EfficientAdapter extends BaseAdapter {
    static class ViewHolder {
        TextView text;
        EditText text2;

    }

    private LayoutInflater mInflater;
    public EfficientAdapter(Context context) {
        mInflater = LayoutInflater.from(context);
    }
    public int getCount() {
        return symbols.size();
    }
    public Object getItem(int position) {
        return position;
    }
    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            // convertView = mInflater.inflate(android.R.layout.simple_list_item_1, null);
            convertView = mInflater.inflate(R.layout.editcategorylist, null);
            holder = new ViewHolder();

            holder.text = (TextView) convertView.findViewById(R.id.symbol);
            holder.text2 = (EditText) convertView.findViewById(R.id.postion);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.text.setText(strArray[position]);

        Log.e("text",holder.text.toString());
        holder.text2.setText(strArray1[position]);
        Log.e("text2",holder.text2.toString());

        return convertView;
    }
}

A: This link here has slightly different implementation but you can use bits of the tutorial and cook something of your own. A starting point if you would. It makes use of a DB and display the results in a tabular form.
http://www.anotherandroidblog.com/2010/08/04/android-database-tutorial/


text:
Q: How to check text in editText and switch between activity accordingly I have written a simple code to check username and password entered by user and to act accordingly.
However when I run it I am getting error asking to FORCE QUIT
Please find the code:
Plz help
    public void onClick(View v)
    {
      EditText username = (EditText)findViewById(R.id.EditTextUsername);
      EditText password = (EditText)findViewById(R.id.EditTextPassword);
      String CheckUsername = username.getText().toString();
      String CheckPassword = password.getText().toString();

      TextView status = (TextView)findViewById(R.id.TextViewErrorMsg);
      if(CheckUsername=="")
        status.setText("please enter username");
      if(CheckPassword=="")
        status.setText("please enter password");
      if(CheckUsername=="xyz" && CheckPassword == "abcd") {
        i = new Intent(LoginActivity.this, SignUpActivity.class);
        startActivity(i);
      } else {
        i = new Intent(LoginActivity.this, AppLockActivity.class);
        startActivity(i);
      }
    }

A: USE CheckUsername.equals("") and CheckUsername.equals("abcd") equals compares value of 2 objects where as = compares whether they are same object.


text:
Q: Understanding linux server process logs So I got this little snippet from a server admin saying that my script was responsible for a server overload. I didn't quite understand how this log tells that.
Can some one explain what this output actually means ?
nobody 227949 6.2 45.4 21198032 11187052 ? S 08:40 0:19 _ /usr/local/apache/bin/httpd -k start -DSSL
user 232019 4.1 0.1 150748 25872 ? S 08:41 0:11 | _ /usr/bin/php /home/user/public_html/results.php
All I got from this was:user processid __ ___ ___ _____ ? S ___ ___   process-location(apache/php) file-in-use
Is that even correct ? Can someone fill in the blanks explaining what's what. And what is S ?

A: What your system administrator is telling you, is that something in results.php was using resources.  He may have been able to surmise this in conjunction with a tool like top or htop so that he could watch the processes in 'real' time.  Cross referenced the PID (Process ID) and viola he can asses that your file results.php was using more resources than 'normal' or 'expected'.  But from the log itself, all that you can see is that a user ran a process numbered 232019 and what that process 'was'.  He needed the log to tell him what PID 232019 was and why said ID was eating resources.  Apache logs are designed for error reporting, not for monitoring kernal processes and their performance.
So in short, I believe the troubleshooting must have go something like:
hmmmmm  Server is slow
Ok I'll look at HTOP
HTOP says that PID 232019 is pegging the CPU's and eating memory
hmmmmm  Wonder what PID 232019 really is?  -  All I can see is that apache is running it.  Better look in the logs.
Search the log file for 232019.
Ahh, there it is ...  results.php.  The culprit.

A: This is output provided py ps au or ps aux, the columns are:
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
https://superuser.com/questions/117913/ps-aux-output-meaning has an explanation, or look at man ps.
Status S means 'sleeping', which is quite a normal state for a process to be in. This output doesn't really help you that much in tracking down the problem. All you now is that the problem is in results.php, so you have to investigate that more closely. I'd hazard a guess and say this script does some data processing which probably takes too long.


text:
Q: How to center the contents inside of a div I am trying to center the contents of a  tag. This is the div that I am trying to center:

        Page1 From @Model.CountPage

        Record

            @{
                 int i1 = (Model.CurrentPage-1)*Model.CountRecordInPage;
                 if (i1 == 0)
                 {
                     i1 = 1;
                 }

                 string recordFrom = i1.ToString(CultureInfo.InvariantCulture);
             }@recordFrom

        To
        @Model.CountRecordInPage
        From @Model.AllRecord

There must be something that I am missing, but I am out of ideas.

A: just use

Live Demo

A: Give a width of your div if you want to use margin: auto
.Paging {
width :70%;
margin : auto;

}

A: add a width to the div!!
or if you want the text to be centered add
text-align:center;


text:
Q: Binding function from other class to Kivy Button Kivy app screenshot
I have 2 .py files in the same project called dailyReports.py and weeklyReports.py and they each generate a different excel sheet, one daily report and the other a weekly report. When I click run, it opens the excel file directly which is what I want.
I am trying to make a simple user-friendly interface that will allow a user to select which report they want to generate and for it to run the according report generator and output the excel file. This is my first time dealing with python and kivy but so far I was able to make my two report generators work and the visual aspect of my kivy GUI is exactly as I want it. My problem is when I try to bind the two buttons in the drop down menu to their according excel generator functions. Could someone please help me? here is my code so far for my .py file containing my kivy code along with a picture of how my current kivy GUI looks like when I click the drop down button.
I would really appreciate it !!!!
    from kivy.uix.label import Label
    from kivy.uix.dropdown import DropDown
    from kivy.app import App
    from kivy.graphics import Color, Rectangle
    from kivy.uix.floatlayout import FloatLayout
    from kivy.graphics.context_instructions import Color
    from kivy.config import Config
    from kivy.uix.image import Image
    from kivy.uix.button import Button
    dropdown = DropDown()

    class Panel(FloatLayout):

        def __init__(self, **kw):
            super(Panel, self).__init__(**kw)

            # Make the background solid white
            color = Color(1.0, 1.0, 1.0, 1.0)
            self.canvas.add(color)
            rect = Rectangle(pos=self.pos, size=self.size)
            self.canvas.add(rect)

            dropdown = DropDown()

            # Add the label
            label = Label(text="Report Generator", pos_hint={'x': 0, 'y': 0.20}, size_hint=(None, None))
            label.color = [0.0, 0.0, 0.0, 1.0]
            label.size_hint = (1, 1)
            label.font_size = 26
            label.bold = True
            self.add_widget(label)

            choice = Button(text="Select Summary Report to Generate", pos_hint={'center_x': .5, 'center_y': .58},
                    size_hint=(0.6, 0.2))
            choice.color = [1.0, 1.0, 1.0, 1.0]
            choice.size_hint = (0.45, 0.1)
            choice.font_size = 18
            choice.bold = False
            choice.bind(on_release=dropdown.open)
            self.add_widget(choice)

            btn1 = Button(text='Daily Report', font_size=18, size_hint_y=None, height=60)
            btn1.color = [1, 1, 1, 1]
            btn1.txt= 'Generating Daily Summary Report...'
            btn1.bind(on_release=lambda btn1: dropdown.select(btn1.txt))
            dropdown.add_widget(btn1)
            btn2 = Button(text='Weekly Report', font_size=18, size_hint_y=None, height=60)
            btn2.color = [1, 1, 1, 1]
            btn2.txt = 'Generating Weekly Summary Report...'
            btn2.bind(on_release=lambda btn2: dropdown.select(btn2.txt))
            dropdown.add_widget(btn2)
            dropdown.bind(on_select=lambda instance, x: setattr(choice, 'text', x))

    class Report(App):
       def build(self):[enter image description here][1]
            Config.set('graphics', 'width', '450')
            Config.set('graphics', 'height', '250')
            return Panel(size=(1000,1000))

    # Application Code
    if __name__ == '__main__':
        Report().run()

A: You have add the following code as per snippet. Please refer to the example below for complete details.
Snippet
from DailySummaryReport import DailySummary
from WeeklySummaryReport import WeeklySummary
...
        btn1.bind(on_release=lambda btn1: dropdown.select(btn1.txt))
        btn1.bind(on_release=lambda btn1: DailySummary())
...
        btn2.bind(on_release=lambda btn2: dropdown.select(btn2.txt))
        btn2.bind(on_release=lambda btn2: WeeklySummary())

Example
main.py
from DailySummaryReport import DailySummary
from WeeklySummaryReport import WeeklySummary

from kivy.uix.label import Label
from kivy.uix.dropdown import DropDown
from kivy.app import App
from kivy.graphics import Color, Rectangle
from kivy.uix.floatlayout import FloatLayout
from kivy.graphics.context_instructions import Color
from kivy.config import Config
from kivy.uix.image import Image
from kivy.uix.button import Button

class Panel(FloatLayout):
    def __init__(self, **kw):
        super(Panel, self).__init__(**kw)
        self.size = (1000, 1000)
        # Make the background solid white
        color = Color(1.0, 1.0, 1.0, 1.0)
        self.canvas.add(color)
        rect = Rectangle(pos=self.pos, size=self.size)
        self.canvas.add(rect)

        dropdown = DropDown()

        # Add the label
        label = Label(text="Report Generator", pos_hint={'x': 0, 'y': 0.20}, size_hint=(None, None))
        label.color = [0.0, 0.0, 0.0, 1.0]
        label.size_hint = (1, 1)
        label.font_size = 26
        label.bold = True
        self.add_widget(label)

        choice = Button(text="Select Summary Report to Generate", pos_hint={'center_x': .5, 'center_y': .58},
                        size_hint=(0.6, 0.2))
        choice.color = [1.0, 1.0, 1.0, 1.0]
        choice.size_hint = (0.45, 0.1)
        choice.font_size = 18
        choice.bold = False
        choice.bind(on_release=dropdown.open)
        self.add_widget(choice)

        btn1 = Button(text='Daily Report', font_size=18, size_hint_y=None, height=60)
        btn1.color = [1, 1, 1, 1]
        btn1.txt = 'Generating Daily Summary Report...'
        btn1.bind(on_release=lambda btn1: dropdown.select(btn1.txt))
        btn1.bind(on_release=lambda btn1: DailySummary())
        dropdown.add_widget(btn1)
        btn2 = Button(text='Weekly Report', font_size=18, size_hint_y=None, height=60)
        btn2.color = [1, 1, 1, 1]
        btn2.txt = 'Generating Weekly Summary Report...'
        btn2.bind(on_release=lambda btn2: dropdown.select(btn2.txt))
        btn2.bind(on_release=lambda btn2: WeeklySummary())
        dropdown.add_widget(btn2)
        dropdown.bind(on_select=lambda instance, x: setattr(choice, 'text', x))

class Report(App):
    def build(self):
        Config.set('graphics', 'width', '450')
        Config.set('graphics', 'height', '250')
        return Panel()

# Application Code
if __name__ == '__main__':
    Report().run()

Output


text:
Q: Django Not in for Related Fields How would I do a not in filter in Django when I have related fields?
class Publisher(Model):
  pass

class Author(Model):
  name = models.CharField(...)
  publisher = models.ForeignKey(Publisher)

I can write:
Publisher.objects.filter(author__name__in=XXX)

this does not work:
Publisher.objects.filter(author__name__not_in=XXX)

And while this Django equivalent of SQL not in claims you can use exclude, this is not correct:
Publisher.objects.exclude(author__name__in=XXX)

XXX is a list of names.
To clarify what I want to get:  I would like to find all publishers that have an author NOT in that list. Note: these publishers may also have an author IN that list.
Let's say I have two publishers A, B and the following Authors for the publishers:
A: Alex, Bob, Greg
B: Alex, Greg

xxx is ['Alex', 'Greg']
I would like to find any Publisher that has an Author not in that list. In this case A should be returned since A has author Bob which is not in that list.

A: It looks Q objects would be a good fit for this query.
You can build up the query params first.
import operator

query = reduce(
    lambda x, y: operator.or_(Q(author__name=x), Q(author__name=y)),
    XXX
)
# query would be something like Q(author__name='Alex') | Q(author__name='Greg')

Publisher.objects.exclude(query)

Example using exact matches, if you're looking to search in a CharField you have to use contains or icontains. Just update Q object with Q(author__name__icontains=n).

A: Check the exclude() function. It's the inverse of the filter() function, but does exactly what you're looking for.
Note that you can also chain functions together:
>>> Entry.objects.filter(
...     headline__startswith='What'
... ).exclude(
...     pub_date__gte=datetime.date.today()
... ).filter(
...     pub_date__gte=datetime(2005, 1, 30)
... )

A: What is XXX, If it is a list you should be able to use exclude in your query.
Publisher.objects.exclude(author__name__in=XXX)  # Remember XXX must be a list

If it is a string you should use:
Publisher.objects.exclude(author__name__contains=XXX)

Or if case does not matter:
Publisher.objects.exclude(author__name__icontains=XXX)

A: The following can be used:
Publisher.author.filter(author__in=Author.objects.exclude(name__in=xxx))

There is a performance cost associated with the potentially huge subquery, especially on MySQL which doesn't handle subqueries all that well.
An alternative is to implement a NOT IN custom lookup, which has been possible since 1.7. It would look something like this:
class NotInLookup(Lookup):
    lookup_name = 'not_in'

    def as_sql(self, compiler, connection):
        lhs, lhs_params = self.process_lhs(compiler, connection)
        rhs, rhs_params = self.process_rhs(compiler, connection)
        params = lhs_params + rhs_params
        return '%s NOT IN (%s)' % (lhs, rhs), params

You'll have to investigate the documentation and possibly the source code of IN for the right way to write this lookup. There might be interest to add it to core, so if you get it working, feel free to bring it up on the mailing list at https://groups.google.com/forum/#!forum/django-developers.


text:
Q: Asus UEFI/BIOS options - How to boot from DVD? I just bought a new PC and the default installed OS is Windows 8. I want to install Windows 7 but when I go into the boot options screen I only have one option:
Windows Boot Manager

I can't find my DVD drive. It is plugged in and visible under SATA options. How is it that I don't see it in the boot options menu?
The weirdest thing is that the drive is working perfectly inside Windows. So Windows 8 can detect it but the BIOS can't? I'm stuck with Windows 8... Any ideas?

A: To get the DVD drive to show up in the boot menu, you might need to go into the BIOS (actually (U)EFI Settings) and enable Legacy (BIOS) Mode or the UEFI Compatibility Support Module (CSM) or similarly worded option:

(Screenshot of Asus Zenbook Prime UX31A-DH51 BIOS with CSM disabled.)

(Screenshot of Asus K55A BIOS with CSM enabled.)
Note: You might also have to disable both Boot / Fast Boot and Security / Secure Boot Control.

A: See my answer to THIS post. Try to change the UEFI boot options by "restarting" Windows8 while holding down the shift key, to enter advanced reboot menu.

A: The Asus VivoBook Max X541N is very hard to get to boot from USB or DVD.
I found only one way to make the system boot from a USB:

*

*Use the USB2 port, not the blue USB3 port.

*Turn off secure boot in the BIOS settings.

*Using Rufus, write the UEFI:NTFS as the Boot Selection option.
Do not select the ISO to burn, instead choose the UEFI:NTFS from the dropdown in Rufus, and burn that by pressing "START".

*Now, the USB will have two partitions; the empty bigger partition (that's actually writeable) is where you must copy the CONTENTS of the .iso file that you want to boot. (Not copying the .iso file, but copy and paste everything that is in the ISO file system onto the USB that you just wrote the UEFI:NTFS to).

*Now when you boot, it will load the UEFI:NTFS Rufus boot loader, which will then go and load the contents of the partition where you copied the file contents of the iso to.
This was the result of much testing, DVDs, MBR and GPT USB,
every single setting; nothing would boot this laptop from USB or DVD.
Only this UEFI:NTFS partition type works a charm.

A: Easiest option.... put the windows DVD into an external USB DVD drive... works fine without the mucking about.


text:
Q: Обработчик радиокликов для выбора фигуры Имеется код для приложения на WinForms
// обработчик радиокликов для выбора фигуры
private void radioGroup_CheckedChanged_Figures(object sender,EventArgs e)
{
    string text=(sender as Radiobutton)?.Text; // тут приведение отправителя к элементу типа RadioButton, но непонятен синтаксис ?Техт - что это такое?
    Figure=text;


text:
Q: friendly-id: Undefined method slug for Movie I downloaded the friendly_id gem in order to make my URLs more user friendly. To honor their instructions, I am asking this here instead of on GitHub.
Here is my Show Method
def show
  @movie = Movie.friendly.find(params[:id])
end

This is in compliance with their documentation
Finders are no longer overridden by default. If you want to do friendly finds, you must
do Model.friendly.find rather than Model.find. You can however restore FriendlyId
4-style finders by using the :finders addon:

In my Model.rb file, I have the following
extend FriendlyId
friendly_id :title, use: :slugged

From their documentation
friendly_id :foo, use: :slugged # you must do MyClass.friendly.find('bar')

also from their documentation
def set_restaurant
  @restaurant = Restaurant.friendly.find(params[:id])
end

For reference, here is their guide.
Granted, I haven't generated a migration yet, because I had already created the table.
I'm unsure of what my next step should be?
Thank you for your help.

A: Marina is correct that you have to add slug field.
But lot's of people got confused because FriendlyID generates friendly_id_slugs table which contains sluggable_id and sluggable_type field.
create_table "friendly_id_slugs", force: :cascade do |t|
t.string   "slug",                      null: false
t.integer  "sluggable_id",              null: false
t.string   "sluggable_type", limit: 50
t.string   "scope"
t.datetime "created_at"
t.index ["slug", "sluggable_type", "scope"], name: "index_friendly_id_slugs_on_slug_and_sluggable_type_and_scope", unique: true
t.index ["slug", "sluggable_type"], name: "index_friendly_id_slugs_on_slug_and_sluggable_type"
t.index ["sluggable_id"], name: "index_friendly_id_slugs_on_sluggable_id"
t.index ["sluggable_type"], name: "index_friendly_id_slugs_on_sluggable_type"
end

Basically it generates friendly_id_slugs table for History Module.
Have a look at their documentation about History__Avoiding_404_s_When_Slugs_Change : http://norman.github.io/friendly_id/file.Guide.html#History__Avoiding_404_s_When_Slugs_Change

A: You need to run a migration to add the slug column to your table:
class AddSlugToMovies < ActiveRecord::Migration
  def change
    add_column :movies, :slug, :string, unique: true
  end
end

Run rake db:migrate, and then in your rails console run Move.find_each(&:save) to populate the slug column.

A: If you are getting started with a new table you can also do this:
class CreateMovies < ActiveRecord::Migration
  def change
    create_table :movies do |t|
      ...
      t.string :slug
      t.index :slug, unique: true, using: :btree
    end
  end
end


text:
Q: Have biblatex output the same ordinal edition as bibtex in IEEE (bib) style? Consider this MWE:
\documentclass{article}
\usepackage{filecontents} % tlmgr install filecontents
\begin{filecontents*}{btest.bib}
@BOOK{Mittelbach2005,
  author = {Frank Mittelbach},
  edition = {2. ed.},
  publisher = {Addison-Wesley},
  title = {The LATEX companion},
  year = 2005
}
\end{filecontents*}

\ifx\ubl\undefined %
  \def\tubl{bibtex}
\else %
  \usepackage[%
    style=ieee,
    isbn=true,
    doi=false,
    url=true,
    backend=biber
  ]{biblatex}
  \bibliography{btest}
  \def\tubl{bibLAtex}
\fi

\begin{document}

Citing... HERE: \cite{Mittelbach2005} (\tubl)

\ifx\ubl\undefined %
  \bibliographystyle{IEEEtranS} %
  \bibliography{btest} %
\else %
  \printbibliography[resetnumbers] %
\fi

\end{document}

You can quickly compile it with the following bash one-liner:
for ib in {b,bl}; do \
  if [ "$ib" = "b" ]; then \
    TCMD='-jobname=testA "\input{test.tex}"'; \
    pdflatex $TCMD; bibtex testA; pdflatex $TCMD; pdflatex $TCMD; \
  else \
    TCMD='-jobname=testB "\def\ubl{1}\input{test.tex}"'; \
    pdflatex $TCMD; biber testB; pdflatex $TCMD; \
  fi; \
done

The TestB.pdf, which utilizes biblatex+biber looks like this:

... and the TestA.pdf, which utilizes bibtex, looks like this:

Note that the bibtex one shows "2nd ed.", while biblatex+biber one shows "2. ed.". Looking at Biblatex customization - Thesis in LaTeX [khirevich.com], one may think this would make biblatex do ordinal suffixes:
\DeclareFieldFormat{edition}%
                   {\ifinteger{#1}%
                    {\mkbibordedition{#1}\addthinspace{}ed.}%
                    {#1\isdot}}

... however, that is only for purely numerical fields - and notice, here the field is:
  edition = {2. ed.},

... that is - it is alphanumeric; and bibtex seemingly parsed into it, and replaced '2.' with '2nd', and appended the rest!
So how can biblatex be persuaded to produce the same output as bibtex, "2nd ed.", from this same field?
(By the way, side question: you can notice also the spacing is different; how can I get the same spacing with biblatex as I get it with bibtex?)

A: Before we commence, I would like to quote what the biblatex documentation says about the edition field

edition field (integer or literal) The edition of a printed
  publication. This must be an integer, not an ordinal. Don't say
  edition={First} or edition={1st} but edition={1}. The
  bibliography style converts this to a language dependent ordinal. It
  is also possible to give the edition as a literal string, for example
  "Third, revised and expanded edition".

So the best you could do is to make sure your .bib files adherer to this practice and write edition = {2} instead of edition = {2. ed.}.
We can let Biber do some of this work, however.
In this example we use a RegEx of the form ^(\d+)\.\s+(ed.|edition)$, this will match numbers followed by a full stop some space and the word "ed." or "edition".
A more liberal RegEX might be  ^(\d+).* which will match all numbers regardless of what they are followed by.
In any case we copy the first group into the edition field.
\DeclareSourcemap{
  \maps[datatype=bibtex]{
    \map{
      \step[fieldsource=edition,
            match=\regexp{^(\d+)\.\s+(ed.|edition)$},
            replace=\regexp{$1}]
    }
  }
}

MWE
\documentclass{article}
\usepackage{filecontents} % tlmgr install filecontents
\begin{filecontents*}{\jobname.bib}
@BOOK{Mittelbach2005,
  author = {Frank Mittelbach},
  edition = {2. ed.},
  publisher = {Addison-Wesley},
  title = {The LATEX companion},
  year = 2005
}
\end{filecontents*}
  \usepackage[%
    style=ieee,
    isbn=true,
    doi=false,
    url=true,
    backend=biber
  ]{biblatex}
  \addbibresource{\jobname.bib}

\DeclareFieldFormat{edition}{%
  \ifinteger{#1}
    {\mkbibordedition{#1}\addnbthinspace\bibstring{edition}}
    {#1\isdot}}

\DeclareSourcemap{
  \maps[datatype=bibtex]{
    \map{
      \step[fieldsource=edition,
            match=\regexp{^(\d+)\.\s+(ed.|edition)$},
            replace=\regexp{$1}]
    }
  }
}

\begin{document}
Citing... HERE: \cite{Mittelbach2005}

\printbibliography[resetnumbers] %
\end{document}


text:
Q: Sending messages from Python using osc4py3? I'm currently trying to figure out how to send OSC messages from Python to Max/MSP. I'm currently using osc4py3 to do so, and I have a sample code from the documentation that should hypothetically be working, written out here:
from osc4py3.as_eventloop import *
from osc4py3 import oscbuildparse

# Start the system.
osc_startup()

# Make client channels to send packets.
osc_udp_client("127.0. 0.1", 5000, "tester")

msg = oscbuildparse.OSCMessage("/test/me", ",sif", ["text", 672, 8.871])
osc_send(msg, "tester")

The receiver in Max is just a udprecieve object listening to port 5000. I managed to get Processing to send OSC messages to Max and it worked pretty simply using the oscp5 library, but I can't seem to have the same luck in Python.
What is it I'm missing? Moreover, I don't entirely understand the structure for building OSC messages in osc4py3, even after doing my best with the documentation; if someone would be willing to explain what exactly is going on (namely, the arguments) in something like
msg = oscbuildparse.OSCMessage("/test/me", ",sif", ["text", 672, 8.871])

then I would be forever grateful.
I'm entirely open to using another OSC library, but all I ask is a run-through on how to send a message (I've attempted using pyOSC but that too proved too confusing for me).

A: Maybe you already solved it but in the posted code there are two problems. One is the IP address format (there is a space before the second "0"). Then you need the command osc.process() at the end. So the following way should work
from osc4py3.as_eventloop import *
from osc4py3 import oscbuildparse

# Start the system.
osc_startup()

# Make client channels to send packets.
osc_udp_client("127.0.0.1", 5000, "tester")

msg = oscbuildparse.OSCMessage("/test/me", ",sif", ["text", 672,
8.871])
osc_send(msg, "tester")
osc_process()

Hope it will work out

A: There are different possible scheduling policies in osc4py3. The documentation uses the event-loop model with as_eventloop, where user code must periodically call osc_process() to have osc4py3 deal with internal messages queues and communications.
The client example for sending OSC messages wrap osc_process() call in a loop (generally it is into an event processing loop).
You may dismiss osc_process() call simply by importing names with full multithreading scheduling policy at the beginning of your code:
from osc4py3.as_allthreads import *

The third scheduling policy is as_comthreads, where communications are processed in background threads, but received messages (in server side) are processed synchronously at the osc_process() call.
(by the author of osc4py3)


text:
Q: How does PDF's BitsPerComponent translate to Bits Per Pixel for images? My goal is to convert a PDF into an image (specifically in TIFF).
There is a PDF property called BitsPerComponent
And According to description on the page,

This property can take the value 1, 2, 4, 8 or 16. Other values are not supported in the PDF Specification

Does that mean, 1, 2, 4, 8 or 16 translates to bits per pixel in images?

A: Sounds more like bits per color component, where color component is one of either (Alpha)/Red/Green/Blue or Grey. So take the bits per component and multiply by the components per pixel to get bits per pixel. For example, if you're talking an RGB image you have 3 components. An RGB at 8 bit per component would be a 8 * 3 = 24bit per pixel image. If it was greyscale, e.g. one component, an 8 bit per component would be 8 bit per pixel.

A: BitsPerPixel = 3 * BitsPerComponent if the color is stored as RGB
BitsPerPixel = 4 * BitsPerComponent if the color is stored as RGB with an alpha channel (ARGB)
RGB is a random assumption ... this will hold for every color model using 3 components and may be a alpha chanel. It will be BitsPerPixel = BitsPerComponent if it is a gray scale image.

A: No, it translates into bits per color channel. When you have a grayscale image this is essentially bits per pixel as well.
When you have an RGB image with 16 bits per channel you have a total of 48 bits per pixel (or even 64 if you have an alpha channel, too).

A: There are already lots of tools out there which can convert PDFs to images. If you want to write your own, you are going to have to learn a huge spec and build a rasterizer. Why do you need to build a custom solution?


text:
Q: Fading image captions on hover in css I'm working on my portfolio and I did some fancy things to my image thumbnails. I now want my hover caption to fade in/out on hover.
This is my code so far;
HTML:

Fade Caption

Lorem ipsum dolor sit amet, consectetuer adipiscing elit,sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.

CSS:
    .mask {
    position:relative;
    height:180px;
    width:240px;
    -webkit-box-shadow:0 0 1px #000;
    border:5px solid #f6f6f6;
    overflow:hidden;
    float:left;
    margin:15px;
}
.mask img {
    position:absolute;
    height:300px;
    width:400px;
    -webkit-transform: rotate(15deg);
    -moz-transform:rotate(15deg);
    -o-transform:rotate(15deg);
    -ms-transform:rotate(15deg);
    transform:rotate(15deg);
    top:50%;
    left:50%;
    margin-top:-150px; /* half the height */
    margin-left:-200px; /*half the width */
}

.mask:last-child {
    margin-right:0px;
}

.mask .caption {
    background-color: rgba(222,169,188,0.9);
    position: absolute;
    color: #fff;
    z-index: 100;
    left: 0;
}

.mask .fade-caption {
    opacity: 0;
    width: 220px;
    height: 180px;
    text-align: left;
    padding: 4px 20px 4px 15px;
    display:none;
    font-size:0.8em;
}

.mask:hover .fade-caption {
    opacity: 1;
    display:inline;
      width: 220px;
        height: 180px;
-webkit-transition: all 300ms ease-out;
    -moz-transition: all 300ms ease-out;
    -o-transition: all 300ms ease-out;
    -ms-transition: all 300ms ease-out;
    transition: all 300ms ease-out;
    }

I thought I needed to add a fade-caption class and put the transitions on the :hover state, but apparently that's not right. I'm not so skilled with transitions yet and I'm hoping someone can help me with this since I couldn't find a tutorial that could help me with my problem.

A: You were pretty close. Check out this fiddle for a working example. Full CSS below:
.mask {
    position:relative;
    height:180px;
    width:240px;
    box-shadow:0 0 1px #000;
    border:5px solid #f6f6f6;
    overflow:hidden;
    float:left;
    margin:15px;
}
.mask img {
    position:absolute;
    height:300px;
    width:400px;
    top:50%;
    left:50%;
    margin-top:-150px; /* half the height */
    margin-left:-200px; /*half the width */
    -webkit-transform: rotate(15deg);
    -moz-transform:rotate(15deg);
    -o-transform:rotate(15deg);
    -ms-transform:rotate(15deg);
    transform:rotate(15deg);
}

.caption {
    background-color: rgba(222,169,188,0.9);
    position: absolute;
    color: #fff;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    padding: 4px 20px 4px 15px;
    font-size:0.8em;
    opacity: 0;
    -webkit-transition: all 300ms ease-out;
    -moz-transition: all 300ms ease-out;
    -o-transition: all 300ms ease-out;
    -ms-transition: all 300ms ease-out;
    transition: all 300ms ease-out;
}

.mask:hover .caption {
    opacity: 1;
}

Importantly, the transition styling is on the element itself, not just its :hover state. That way it will both fade in and out. If those style are just on :hover, the element will fade in but disappear immediately rather than fading out.
You can't transition between display: none and display: block/whatever. So, you need to let the opacity in this instance be what visually hides your caption. You could add the proprietary ms-filters to get old-IE support.
Other points to note:

*

*I consolidated your .caption and .fade-caption classes for the sake of simplicity.

*There's no need to re-declare things that are already set for the :hover state, you just need to state those things that need to change.

*There's no need for prefixes on box-shadow any more, just use the final version.

*You were getting a bit confused with positioning your caption, making it absolute but also setting a width and height. For simplicity's sake I have just set all four valules to 0.

*You don't need to declare the z-index here, just let the browser's normal stacking order sort it for you. If you need to place the caption before the image in the markup though, you would need to add this back in.

A: The reason that your transitions aren't current doing what you might expect is that the display properties (going from none to inline) on the caption is preventing the opacity from transitioning, and your transitions should also be applied to the element before you make any changes (i.e. before hover - in the regular state). Relying purely on the opacity to fade the caption in and out should work a treat:
.mask .fade-caption {
    opacity: 0;
    width: 220px;
    height: 180px;
    text-align: left;
    padding: 4px 20px 4px 15px;
    font-size:0.8em;
    -webkit-transition: all 300ms ease-out;
    -moz-transition: all 300ms ease-out;
    -o-transition: all 300ms ease-out;
    -ms-transition: all 300ms ease-out;
    transition: all 300ms ease-out;
}

.mask:hover .fade-caption {
    opacity: 1;
    width: 220px;
    height: 180px;
}

http://jsfiddle.net/g9NFV/
EDIT: Ninja'd, but I'll keep this answer here anyway for now.