text:
Q: DWQA Plugin filters not working for logged in users I am using the DWQA plugin in my wordpress site : http://getlegal.co.in
But I am facing a problem. The filters in the plugin such as page navigation, category selection etc don't work for a logged in user whereas they function perfectly fine for a non logged in user.
I think there is some problem with the ajax calling.
Is there any code in wp-admin/admin-ajax.php and wp-admin/includes/ajax-functions.php which differentiates the way ajax calling is done for logged in and logged out users ?


text:
Q: How to add (css) classes to only one wp_nav_menu()? Edit
I removed the original Question as this Q has far above 1.000 views now - which means it's important to a lot of people - to show you something that works a) without a custom Walker & b) is easy. Note: I only removed to original Q, because it was pretty unspectacular.
The Task
Add css classes to all nav menu items inside a specific Nav Menu that was added via (admin UI) Appearance > Menu.
The function
function wpse4388_navmenu_classes( $items, $menu, $args )
{
    // prevent crashing the appearance > menu admin UI
    if ( is_admin() )
        return;

    # >>>> start editing

        // Nav menu name you entered in the admin-UI > Appearance > Menus (Add menu).
        $target['name'] = 'Topnav';

        // A targeted menu item that needs a special class - add the item number here
        $target['items'] = array( (int) 6 );

    # <<<< stop editing

    // filter for child themes: "filter_nav_menu_{nav menu name}"
    // the nav menu name looses all empty spaces and is set to lower
    // if you want to use the filter, hook your child theme function into 'after_setup_theme'
    $target = apply_filters( 'filter_nav_menu_'.strtolower( str_replace( " ", "", $target['name'] ), $target );

    // Abort if we're not with the named menu
    if ( $menu->name !== $target['name'] )
        return;

    foreach ( $items as $item )
    {
        // Add the class for each menu item
        $item->classes = 'classes for all items';

        // Append this class if we are in one of the targeted items
        if ( in_array( (int) $item->menu_order, $target['items'] ) )
            $item->classes .= ' only for a single item';
    }

    return $items;
}
add_filter( 'wp_get_nav_menu_items', 'wpse4388_navmenu_classes', 10, 3 );

Was it helpful? Don't forget to vote up! :)

A: I'm going to start by saying something similar to Horttcore..
Is there a reason you can't simply provide a differing container element for the given menu, it should provide enough specificity to style it uniquely.
Although, you could do something like this to conditionalise menu args based on the menu's location..
function my_wp_nav_menu_args( $args = '' ) {
    if( $args['theme_location'] == 'your-specific-location' )
        $args = array_merge( array(
            'container_class' => 'example',
            'menu_class' => 'example2'
        ), $args );
    return $args;
}
add_filter( 'wp_nav_menu_args', 'my_wp_nav_menu_args' );

Above code is based on the example given on the codex page for wp_nav_menu, and could easily be extended to do any number of things.
http://codex.wordpress.org/Function_Reference/wp_nav_menu
Hope that helps..

A: Maybe I got you wrong, but why don't you add the class in your theme?
Specify the class when you call the menu.
<?php wp_nav_menu( array( 'theme_location' => 'Top Nav', 'menu_class' => 'span-3' ) ); ?>

A: I had a very similar issue. I needed to target a specific wp_nav_menu() and replace the a links with a class. Here is my solution in reference to the OP:
function theme_add_menuclass( $classes, $args ) {
    if ( $args->theme_location == 'your-menu-location' ) {
        return preg_replace( '/<li /i', '<li class="your-class"', $classes );
    }
    return $classes;
}
add_filter( 'wp_nav_menu_items', 'theme_add_menuclass', 10, 2 );

You can use this to replace any piece in your nav menus. Hope this helps.

A: To add a CSS class to a menu item, go to Appearance > Menu > Screen Options (top right of screen) and ensure that CSS Classes is checked. This will allow you to add CSS classes to each menu item. For multiple class names, separate each item by a space, e.g.:
my-class-one my-class-two

redpajama_set_name: RedPajamaStackExchange


text:
Q: Where clause against multiple options Is there any "IN" keyword available in Linq to entities syntax ? I have a listbox where multiple items are added. I want to search for those items in db. My query looks like this:
 var result = context.data_vault
                      .Where(d => d.STATE == lstStates.SelectedItem.Text).OrderBy(d=>d.dv_id)
                      .Skip(e.NewPageIndex * GridView1.PageSize)
                      .Take(GridView1.PageSize)
                      .ToList();

I want d => d.STATE == lstStates.Items. How to change it?

A: The code:
string[] arr = listview.Items
                       .Cast<ListItem>()
                       .Select(i => i.Text) // or .Value
                       .ToArray();

db.Where(d => arr.Contains(d.STATE);

should be translated into the query:
... WHERE STATE IN ('your', 'array', 'items')

A: Try this:
var result = context.data_vault
                      .Where(d => lstStates.Items.Contains(d.STATE)).OrderBy(d=>d.dv_id)
                      .Skip(e.NewPageIndex * GridView1.PageSize)
                      .Take(GridView1.PageSize)
                      .ToList();

Here,
lstStates is List<string>

A: You can try .Any() or .Contains() syntax
example something like this:
select d from context.Data
Where ListofIdsFromUI.Any(d.Id)
select d


text:
Q: $(A^H . A).v = \lambda.v \Rightarrow \lambda\in \Bbb{R}$ and $\operatorname{tr}(A^H.A)\ge 0$ $\newcommand\dag\dagger$How to prove that for a $\lambda\in\Bbb{C}$ such that
$(1)$ $(A^\dag.A).v=\lambda.v$, $\bar{\lambda}=\lambda\Leftrightarrow \lambda\in\Bbb{R}$ and $(2)$ $\operatorname{tr}(A^\dag.A)\ge 0$?
For $(2)$, I put that as $(A^\dag.A)_{ii}=A^\dag_{ij}.A_{ji}=\bar{A}_{ji}.A_{ji} = \lVert A_{ji}\rVert^2_2\ge 0$ it is proved that $\operatorname{tr}(A^\dag.A)=\sum_i(A^\dag.A)_{ii}\ge 0$.
For $(1)$, how can I prove that $R^\dag.v=\bar{\lambda}.v$, such that, $\bar{\lambda}.v=R^\dag.v=(A^\dag.A)^\dag.v=A^\dag.A.v=R.v=\lambda.v\Rightarrow \bar{\lambda}=\lambda\Rightarrow\lambda\in \Bbb{R}$?

A: We Know that $A^HA$ is Hermitian positive, indeed :
$$∀x∈\mathbb R^n,\ <A^HAx,x>=<Ax,Ax>=\Vert Ax\Vert^2⩾0$$
For the fact that this matrix is hermitian is clear to show, therefore we have proved that all the eigenvalues of $A^HA$ are positives, so we have :
$$Tr(A^HA)=\sum_{\lambda∈Sp(A^HA)}\lambda ⩾0$$


text:
Q: Regular Expression block negation I want to find out a string in which a particular tag does not occur, such as:
<xyz>[\w]+<[^(unwanted)]></xyz>

where unwanted will be interpreted as a, d, e, n, t and u.  But what I want is a block string. How can I express it in regular expression?
I have tried negative lookahead, which doesn't work:
<xyz>.+(?!unwanted).+</xyz>

A: <xyz>(?:(?!unwanted).)+</xyz>

Matches all chars in <xyz>...</xyz>, but only as long as the expression unwanted doesn't start at any of them.


text:
Q: Push a ViewController not through Storyboard while working with Storyboard I searched the whole Internet for my question but obviously was to dumb to find anything.
In my app I'm working with a Storyboard and most of my ViewController are loaded in this style (I'm working with a navigation controller):
MyViewControllerClass *viewController = [storyboard instantiateViewControllerWithIdentifier:@"myViewController"];
[self.navigationController pushViewController:viewController animated:YES];

And now my question: Is it possible to push a VC in code without using storyboard for it? Like in the g'old times, but this does not work for me anymore:
MyViewControllerClass *viewController = [[MyViewControllerClass alloc] init];
[self.navigationController pushViewController:viewController animated:YES];

Please help me, I'm going crazy.
Thanks in advance.

A: Yes you can do it without using storyboard just you need to add navigation controller in app delegate like this, after that it will work fine
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
    navigationController = [[UINavigationController alloc] initWithRootViewController:self.viewController];

    self.window.rootViewController=navigationController;

    [self.window makeKeyAndVisible];

    return YES;

}

A: You can create xib file and push it. You can't push without visual.
ViewControllernew* vv = (ViewControllernew*)[[[NSBundle mainBundle] loadNibNamed:@"ViewControllernew" owner:self options:nil] objectAtIndex:0];
[self.navigationController pushViewController:vv animated:YES];

A: Can confirm it do work.
Push will act this way if viewController is nil. Does your alloc init creates actually an instance?


text:
Q: Proper way for MySQL to immediately return a newly-inserted row, for GraphQL use? When using GraphQL mutations to create records, it expects the full object in return, e.g.:
mutation {
  createPost(title: "Good morning") {
    id
    title
  }
}

How do I reliably get MySQL to return the newly inserted item? I'm currently doing this:
INSERT INTO posts(title) VALUES('Good morning');
SELECT * FROM posts WHERE id = LAST_INSERT_ID();

But I'm not sure if this is the best way. What if another user happens to perform an INSERT immediately after my own? Would LAST_INSERT_ID() refer to their primary key ID instead of mine?

A: That's the way we did it at my last job, and never had any problems. The docs say it is per connection, so you don't need to worry about another connection changing it.
One thing to be careful of is inserting multiple rows with one INSERT statement. In this case LAST_INSERT_ID() will return the first inserted ID.


text:
Q: close thread which is blocked while reading from inputStream here is code
private static class NgrokRunner implements Runnable {
    private InputStream inputStream;

    private boolean doStop = false;

    public NgrokRunner(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

        String line;

        try {
            while((line = reader.readLine()) != null) {
                System.out.println(line);

                if (keepRunning()) {
                    continue;
                } else {
                    System.out.println("break ----");
                    break;
                }
            }
        } catch (Exception e) {
            //TODO: handle exception
            System.out.println("Ngrok exception");
        }
    }

    public synchronized void doStop() {
        this.doStop = true;
    }

    private synchronized boolean keepRunning() {
        return this.doStop == false;
    }
}

and i started above thread like this
    ProcessBuilder processBuilder = new ProcessBuilder();
    processBuilder.command("ngrok", "http","8080", "--log=stdout");

    try {
        Process process = processBuilder.start();
        NgrokRunner runner = new NgrokRunner(process.getInputStream());
        Thread ngrokThread = new Thread(runner);
        ngrokThread.start();
        for (int i = 0; i < 4; i++) {
            System.out.println(i);
            Thread.sleep(10L * 100L);
        }
        //System.out.println("It works");
        runner.doStop();

    } catch (Exception e) {
        //TODO: handle exception                                                    System.out.println(e);
    }

But in while loop my child thread which is reading input from ngrok , blocking and even after calling doStop() it never reached at if condition where i am checking bool flag to exit from thread.
Well can anyone suggest me logic to achieve my ideal situation.
what i want is "Run ngrok server through binary file of ngrok in a thread and close the thread/ngrok whenever i want ( like when user wants through a pause/end button )"

A: ok so i solved it and here is final solution
run() code :
@Override
public void run() {
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        String line;
        try {
            while(!Thread.interrupted()) {
                if (!reader.ready()) {
                    try {
                        Thread.sleep(1000);
                        continue;
                    } catch (InterruptedException e) {
                        //TODO: handle exception
                        System.out.println("We got interrupted");
                        return;
                    }
                }

                line = reader.readLine();

                System.out.println(line);
            }
        } catch (IOException e) {
            //TODO: handle exception
            System.out.println("Ngrok exception" + e);
        }
    }

Now from main thread
try {
       process = processBuilder.start();
       NgrokRunner runner = new NgrokRunner(process.getInputStream());
       ngrokThread = new Thread(runner);
       ngrokThread.start();

       for (int i = 0; i < 8; i++) {
           System.out.println(i);
           Thread.sleep(1000);
       }
       ngrokThread.interrupt();
} catch (Exception e) {
        //TODO: handle exception
        System.out.println(e);
}


text:
Q: Tikz positioning library has weird behavior with tkz-tab package in position of nodes \documentclass{standalone}

\usepackage{tkz-tab}
%\usetikzlibrary{positioning}

\begin{document}
    \begin{tikzpicture}
        \tkzTabInit[lgt=1.5, espcl=1.5]%
            {$x$/0.8, $f'(x)$/0.8, $f(x)$/1.6}{$-\infty$, $-\sqrt{3}$, $-1$}
        \tkzTabLine{,+,z,-,d}
        \tkzTabVar{-/$0$,+V+/,-DC-/$0$/$0$}
    \end{tikzpicture}
\end{document}

If the library is deactivate, the nodes (zeros) are fine, but if the library is activate, the nodes aren't aligned. How can this be fixed?

A: With positioning library, the syntax above left=1pt differs from the syntax above left=1pt and 1pt.
In the tkz-tab package, the styles of the node positions are defined as follows
\tikzset{low left/.style = {above left = \tkzTabDefaultSep}}

so if it changes to
\tikzset{low left/.style = {above left = \tkzTabDefaultSep and \tkzTabDefaultSep}}

then the problem with the alignment of the nodes is fixed.


text:
Q: $\sum \frac{\zeta(n) -1}{n} = 1- \gamma$ I read that it was known to Euler that $$\sum \frac{\zeta(n) -1}{n} = 1- \gamma$$, but I cannot find a proof of this and am curious how he obtained it. I first tried messing with the definition of $\gamma$, given as the limiting difference between the partial sums of the harmonic series and the natural log, but could not connect it to the zeta function. From whichever method is used to obtain the result, could we likewise obtain $\sum \frac{\zeta(2n) -1}{2n}$ or $\sum \frac{\zeta(2n+1) -1}{2n+1}$?
Could we somehow begin with the result that $\sum (\zeta(n) -1) = 1$?


text:
Q: Big Cartel - Add a description text in each of my categories I have a problem that I cannot solve on my BigCartel site for several weeks.
I would like to add a descriptive text for each of my categories. There is currently no block of text where I could enter a description in the page under the name of my category and I would like the text to be different for each of my categories.
I think in photo it will be simpler ... (here is a picture attached).

Thank you for help me :)
Best

A: So the first thing to do is to make sure you have the theme api imported
Second: This escape here will display your JSON array for all categories:
{{ categories.all }}

I placed this in the bottom of the layout html. Although I'm sure there are some other spots that would work just fine.
Using that array, loop through it to dynamically create an input box for each category and place it wherever you would like
The next question here, is how you would save and maintain the 'description' or whatever it is you want for that particular category to stay. As I assume you probably want a unique value for each category. Going to be working on just this thing tonight or tomorrow. So I'll check back and update my answer once I've got that part figured out.
On a side note, if your categories aren't going to be changing all the type, you could create just a series of your own variables that match the category and hard-code "write" the value for the text box as it pertains to that category.

A: I am not sure if it is different for different themes but I am using the "Roadie" theme and this is what I did:

*

*Go to the Advanced Settings

*Go to Products

*where to put the code
The code is:
{% if page.full_url contains 'your/permalink' %}
The category info you want
{% endif %}
If your page name is "Tops" your permalink is "/category/tops"
You can put multiples of these for each of your categories right under each other. So just copy and paste and change the info in it for the different categories.


text:
Q: switching SDK in eclipse I have installed the SDKs(1.5,1.6,2.1,2.2) from AVD manager, and created a new emulator device with version 1.5. However, I cannot find this device in run configuration target. It only displays the devices created with version 2.2.

A: What's the minimumSdkVersion/targetSdkVersion version in your XML ?

A: It looks like this is a bug. "Run Configurations"/"Debug Configurations" filter out all emulators that have API Level lower than what is specified in target property in default.properties file of Android project.
There is one workaround.

*

*In your "Run Configurations"/"Debug Configurations" select your configuration, go to "Target" tab and click on "Manual" radio button. This will show you list of running emulators when you want to start/debug you app.

*Start Android 1.5 emulator manually (from AVD Manager), wait until eclipse sees this emulator as "online" in "Devices" view.

*Start you application and select the Android 1.5 emulator to run on.


text:
Q: Load BMP pixel data into array C I'm trying to read pixel data from a bitmap into an array of structured (which contains R, G and B ints, for the colours). I'm using a 12x12px image just for testing (because I believe that the bmp specification says that pixel data is padded with zeros at the end of each line to make it word-aligned. 12px width is automatically word aligned.
Here is the code I'm using. the INFOHEADER and FILEHEADER are parsed perfectly, and a 12x12 2D array of IMAGEs im is created. However printing the RGB data for each pixel prints rubbish.
typedef struct __attribute__((__packed__)) {
    unsigned char  b;
    unsigned char  g;
    unsigned char  r;
} IMAGE;

int main(void) {
    FILEHEADER fh;
    INFOHEADER ih;
    FILE *img = fopen("pic.bmp", "rb");
    fread(&fh, sizeof(unsigned char), sizeof(FILEHEADER), img);
    fread(&ih, sizeof(unsigned char), sizeof(INFOHEADER), img);

    IMAGE im[ih.width][ih.height];
    fseek(img, fh.imageDataOffset, 0);
    int i, j;
    for (i = ih.height-1; i >= 0; i--) {
        for (j = 0; j < ih.width; j++) {
            fread(&im[i][j], sizeof(unsigned char), sizeof(IMAGE), img);
            printf("%x%x%x ", im[i][j].r, im[i][j].g, im[i][j].b);
        }
        printf("\n");
    }
    printf("w = %d, h = %d\n", ih.width, ih.height);
}

However, for a 12x12px completely white bitmap, this outputs:
ffffff ffffff ffffff ffffff ffffff ffffff ffffff ffffff ffffff ffffff ffffff ffffff
ffffff ffffff ffffff ffffff ffffff ffffff ffffff ffffff ffffff ffffff ffffff ffffff
ffffff ffffff ffffff ffffff ffffff ffffff ffffff ffffff ffffff ffffff ffffff ffffff
ffffff ffffff ffffff ffffff ffffff ffffff ffffff ffffff ffffff ffffff ffffff ffffff
000 ca800 ff574b 007f 001 000 b000 574bc9 07fff 44c40 ff8690 007f
9077b0 7fff86 8000 574bca 07fff 0a00 ff7482 007f 4bc950 7fff57 2f00 86906d
07fff 60a50 ff8690 007f 4bc9d0 7fff57 ee00 87418 000 c9300 ff574b 007f
4bc8f0 7fff57 700 868b3c 07fff 400 000 000 820a0 7fff74 3000 574bc9
07fff 6000 1877 000 0100 000 000 004 000 1000 000 000
820a0 7fff74 000 0010 000 6000 1874 000 4bc8d0 7fff57 b300 868b31
000 38b30 051f9 000 000 000 000 000 000 010 000 000
745069 018 f700 ffffff 181a4 080 000 000 01f5 0140 000 000

Can anyone see what I'm doing wrong? Could it be an alignment issue?
Thanks
EDIT:
This is a screenshot of the bottom of the bitmap file. There seems to be 144 (12x12) white pixels (highlighted). The last two zeros are padding. It still doesn't make sense that my program doesn't parse this properly though.

A: Ok it turns out that I saved my blank bmp as 8bit instead of 24bit. 8bit uses a colour table, and each pixel references an entry in the colour table to get its data. 24bit bmp uses 3 bytes per pixel, and each byte represents an R, G and B value, so it doesn't need a colour table.


text:
Q: Removing white spaces and comments from asp.net site I have a Website project with a lot of aspx sites. I would like to find out is there any tool that will allow me to remove all white spaces and comments from the aspx files? I don't want to do it on run-time because it's not performance optimal. I would like to do it just before deployment.
Is there any ready tool, or should I write a simple console app, that would use REGEX to eliminate the unnecessary white spaces and comments?
Regards,
Adam

A: For what purpose? Obfuscation?
If you're just trying to reduce the size of HTTP responses to the end user, you are much better off telling the web server to use compression on your output. This zips the spaces away to nothing and gives much smaller results than 'minification'.
(Unless you are retaining loads of <!-- comments --> in which case you should simply change them to <%-- server-side comments --%>.)
Don't try to process ASP.NET with regex. Neither HTML nor aspx-templates are regular languages and together they are much, much more complicated than regex can handle. Naïve approaches like looking for spaces outside of <[^>]*> constructs are very likely to mess up your pages.

A: Yeah, there is no need to do it on run-time. Because it can be done on compile-time. Check this link out: http://omari-o.blogspot.com/2009/09/aspnet-white-space-cleaning-with-no.html


text:
Q: Magento Configurable Product Gallery Switch can somebody help me.
i have configurable products from simple and have 2 questions:
$galleryData = $_product->getData('media_gallery');

this way get all images from gallery for main product, how i can get all images for other options?
with this way i can get only image, small_image and thumbnail:
$mainprouct =  Mage::getModel('catalog/product')->loadByAttribute('sku', $_product->getSku())->getTypeInstance()->getUsedProducts();

how i can get all images for each option and reload media gallery on the fly?


text:
Q: Merging two groups with textbox and tablix together in SSRS 2008 I am facing formatting problem in generating SSRS report. I am having two groups in my report, one group is on list and other on tablix.
The first group with list contains only a textbox which display say AccountNo, while the other group has the entire table which displays the account details (AcctNo, AcctName, Type etc.).
I want to merge this two groups together, such that on each page I can see the both the groups, i.e., textbox the one with AcctNo and other with the table with acct details.
I am getting the first group on different page followed by the other group.
Can anyone suggests me how to merge these two group together on one page?

A: if possible in the table, the easiest way would be to create a parent group for the two groups, so both groups would have the same parent group


text:
Q: Limit of $\lim_{n\rightarrow \infty} \sum^{n}_{i=1} \frac{1}{\sqrt {n^2 +i} }$ Direct way leads to nowhere.
$$\lim_{n\rightarrow \infty} \sum^{n}_{i=1} \frac{1}{\sqrt {n^2 +i} } = \lim_{n\rightarrow \infty} \sum^{n}_{i=1} \frac{1}{n \sqrt {1 +\frac{i}{n^2}} } = $$
$$ = \lim_{n\rightarrow \infty} \frac{1}{n} \cdot \lim_{n\rightarrow \infty} \sum^{n}_{i=1} \frac{1}{\sqrt {1 +\frac{i}{n^2}} } = 0 \cdot \sum^{n}_{i=1} 1 = 0 \cdot n $$
So, I tried to apply squeeze theorem:
$$\lim_{n\rightarrow \infty} \sum^{n}_{i=1} \frac{1}{\sqrt {n^2 +i} } \leq \lim_{n\rightarrow \infty} \sum^{n}_{i=1} \frac{1}{n}  = 1$$
Could you help me to figure out the lower bound?

A: Notice that $$\frac{n}{\sqrt{n^2+n}} =\sum_{i=1}^n \frac{1}{\sqrt{n^2+n}}\leq \sum_{i=1}^n\frac{1}{\sqrt{n^2+i}}\leq \sum_{i=1}^n \frac{1}{n} =1$$ Since $\frac{n}{\sqrt{n^2+n}}=\frac{1}{\sqrt{1+\frac{1}{n}}}\to 1$, you get that $1$ as your limit by squeeze theorem.


text:
Q: Rails 4.2: Nested form that selects 2 objects from a different model I am currently building a tricky form. I am still a fairly young Rails developer so half the battle is grasping how to go about this.
I need to build a form that launches a Campaign. This Campaign will need to be named and commented. It also needs to choose a .zip file form a pre-populated dropdown box. Under that will be the ability to choose one of 5 .pdf files via a check box. Zip files and pdf files are a part of the same model Upload.
So far my Campaign model...
models/campaign.rb
class Campaign < ActiveRecord::Base
    has_many :uploads

    validates :name, presence: true,
                    uniqueness: true

    accepts_nested_attributes_for :uploads
end

The Uploads model represents the table that holds zip and pdf files..
models/uploads.rb
class Upload < ActiveRecord::Base
    has_one :campaign
end

Here is the Campaign controller..
controllers/campaigns_controller.rb
class CampaignsController < ApplicationController
      def index
        @campaigns = Campaign.all.order("created_at DESC")
      end

      def new
        @campaign = Campaign.new
      end

      def create
        @campaign = Campaign.new(campaign_params)

        if @campaign.save
            flash[:success] = "Campaign Successfully Launched!"
            redirect_to @campaign
        else
            flash[:error] = "There was a problem launching your Campaign."
            redirect_to new_campaign_path
        end
      end

      def show
        @campaign = Campaign.find(params[:id])
      end

  private

      def campaign_params
        params.require(:campaign).permit(:name, :comment)
      end
end

My form looks like this...
views/campaigns/_form.html.erb
<%= form_for @campaign, url: {action: "create"} do |f| %>

    <%= f.label :name %>
    <%= f.text_field :name %>

    <%= f.label :comment %>
    <%= f.text_area :comment %>

        #....this is where I lose it..

    <%= f.label :data_file %>

<% end %>

How should I got about this? Is this a case use for collection_select? Any advice or even tutorial links will be highly appreciated.


text:
Q: NextJS routing: why do there need to be different client and server routes? I'm somewhat new to React, but wholly new to NextJS, which I'm trying to teach myself.  I've been going through the NextJS 'getting started' tutorial, as well as looking at some other tutorials.  I don't understand why there is a need to distinguish between client routes and routes on the server, that is, why the client route given as an example uses a query, whereas the server route does not. I know that I am not seeing the forest for the trees, so if anyone can point me in the right direction of 'grokking' NextJS routes, I'd appreciate it.
From this tutorial, on the client side we might have
<Link href={`/blog?slug=${slug}`} as={`/blog/${slug}`} prefetch>
  ...
</Link>

which requires us (it would seem) to set up an Express server and handle the route
/blog/:slug

OK.  But why?  Why isn't the local link simply
<Link href={`/blog/${slug}`}  prefetch>
      ...
    </Link>

?  Or, alternatively, why doesn't NextJS handle server-side the route /blog?slug=${slug} ?
I can follow what the NextJS site 'getting started' tutorial (I input the code myself and test it) is doing, but as far as routing I am a bit lost as to what I'm doing and why. Clearly I am missing a crucial (and elementary) element here, and would appreciate clues as to the error of my ways.

A: If you look at the route
/blog/${slug}
Here slug can take different values as it a parameter. If you want NextJs to handle such routes you need to implement a route for each value that slug can take. For example.
/blog/slug1
/blog/slug2
/blog/slug3

And this number can grow very quickly. Hence we use an Express server so that we can intercept request to route /blog and pass slug as parameter to the blog page.

A: You do not need different client and server routes. That is not compulsory unless you are using client-side routing explained here, with dynamic routes.
If you do not want to use that you can switch for server-side routing with our old friend<a> which does not require separate links.
NextJS handles server-side route queries. Below is a simple example for that -
server.get("/dashboard", (req, res) => {
    const actualPage = '/dashboard';
    const queryParams = {
        username: req.query.username
    };
    app.render(req, res, actualPage, queryParams);
  });

In above example, when you open page - /dashboard?username=amit, you can get the value passed in URL query in your page which you can retrieve using - getInitialProps function.
To get data from URL query with server-side routing, you must create your page with getInitialProps function. Example is as below --
Dashboard.getInitialProps = async(ctx)  => {

    const query = ctx.query;

    const username = query.username;

    return {"username": username};

}

Above code sends data from url query as page props. Server returns that data to the page in req.
Now you must create _app page with getInitialProps function to make this work.


text:
Q: Curve fitting with variable number of Gaussian curve I have the data which appears like

And I decided to use three Gaussian curves to fit it.
(This code allows me to manipulate all three curves and put in best guesses for peak positions. Using these guesses, Mathematica will find a set of three gaussian curves that are the closest match if one clicks click find nearest solution.)
\[Lambda]min=340;
\[Lambda]max=380;
model = height + amp1*Exp[-(x - x01)^2/sigma1^2] + amp2*Exp[-(x - x02)^2/sigma2^2] + amp3*Exp[-(x - x03)^2/sigma3^2]

findBestFitFromValues[{amp1guess_, x01guess_, sigma1guess_,
amp2guess_, x02guess_, sigma2guess_, amp3guess_, x03guess_,
sigma3guess_, heightguess_}] :=
FindFit[
rowData(*change this*), {model, {sigma1 > 0, sigma2 > 0, sigma3 > 0}}, {{amp1,
  amp1guess}, {x01, x01guess}, {sigma1, sigma1guess}, {amp2,
 amp2guess}, {x02, x02guess}, {sigma2, sigma2guess}, {amp3,
 amp3guess}, {x03, x03guess}, {sigma3, sigma3guess}, {height,
 heightguess}}, x];
With[
 {
  localModel =
   model /.
    {
     amp1 -> amp1Var, amp2 -> amp2Var, amp3 -> amp3Var,
     sigma1 -> sigma1Var, sigma2 -> sigma2Var, sigma3 -> sigma3Var,
     x01 -> x01Var, x02 -> x02Var, x03 -> x03Var,
     height -> heightVar
     }},
 Manipulate[
  Column[{
    Style["Match to Data", 12, Bold],
    Show[rowDataPlot(*change this*),
     Plot[localModel, {x, 1240/\[Lambda]max, 1240/\[Lambda]min},
      PlotRange -> All, PlotStyle -> Black] ,Graphics[
     {
     Orange,Line[{{x01Var,0}, {x01Var,500}}],
     Blue,Line[{{x02Var,0}, {x02Var,500}}],
     Red,Line[{{x03Var,0}, {x03Var,500}}]
     }
     ]],
    Style["Chosen Curve", 12, Bold],
    Plot[localModel, {x, 1240/\[Lambda]max, 1240/\[Lambda]min},
     PlotRange -> All, PlotStyle -> Black, ImageSize -> 400]}
   ],
  Delimiter, Style["Peak 1", 12, Bold],
  {{amp1Var, 2000, Style["Amplitude 1", Orange]}, 0, 40000},
  {{x01Var,
    1240/\[Lambda]min - (1240/\[Lambda]min - 1240/\[Lambda]max) 1/5,
    Style["center 1", Orange]}, 1.95, 3.6},
  {{sigma1Var, 0.01, Style["sigma 1", Orange]}, 0.01, 0.3},
  Delimiter, Style["Peak 2", 12, Bold],
  {{amp2Var, 1660, Style["Amplitude 2", Blue]}, 0, 15000},
  {{x02Var,
    1240/\[Lambda]min - (1240/\[Lambda]min - 1240/\[Lambda]max) 2/5,
    Style["center 2", Blue]}, 1.95, 3.6},
  {{sigma2Var, 0.01, Style["sigma 2", Blue]}, 0.01, 0.3},
  Delimiter, Style["Peak 3", 12, Bold],
  {{amp3Var, 1445, Style["Amplitude 3", Red]}, 0, 10000},
  {{x03Var,
    1240/\[Lambda]min - (1240/\[Lambda]min - 1240/\[Lambda]max) 4/5,
    Style["center 3", Red]}, 1.95, 3.6},
  {{sigma3Var, 0.01, Style["sigma 3", Red]}, 0.01, 0.3},
  Delimiter, Style["Height", 12, Bold],
  {{heightVar, 15, Style["Height"]}, 0, 1000},
  Delimiter,
  Control[Button["click find nearest solution",
    vals =
     {amp1Var, x01Var, sigma1Var, amp2Var, x02Var, sigma2Var, amp3Var,
        x03Var, sigma3Var,
       heightVar} = {amp1, x01, sigma1, amp2, x02, sigma2, amp3, x03,
        sigma3, height} /.
       findBestFitFromValues[
        {amp1Var, x01Var, sigma1Var, amp2Var, x02Var, sigma2Var,
         amp3Var, x03Var, sigma3Var, heightVar}]]],
  SaveDefinitions -> True
  ]
 ]

If I want to fit another data with four or more Gaussian curves, how can I re-write my code to obtain the curve fitting that I can specify the number of Gaussian curves? Not the above one where I constrain the number to be three.
EDIT1
I mean, if I specify the number n to be 2, then we can have a two-Gaussian-curve fitting panel,

if I specify the number n to be 3, then we can have a three-Gaussian-curve fitting panel,

A: You can use the PDF of MixtureDistribution of NormalDistributions to specify your model:
ClearAll[model]
model[n_Integer] := Module[{m = Array[μ, n], s = Array[σ, n]/Sqrt[2], w = Array[ω, n]},
    ω[0] + FullSimplify[Sqrt[2 π]Total[w s]
  PDF[MixtureDistribution[w s, NormalDistribution @@@ Transpose[{m, s}]], x]]]

Examples:
model[3] // TeXForm

$\omega (1) e^{-\frac{(x-\mu (1))^2}{\sigma (1)^2}}+\omega (2) e^{-\frac{(x-\mu (2))^2}{\sigma
   (2)^2}}+\omega (3) e^{-\frac{(x-\mu (3))^2}{\sigma (3)^2}}+\omega (0)$

With the identification ω[0] = height, ω[1] = amp1, ω[2] = amp2,ω[3] = amp3, μ[i] = x0i and σ[i] = sigmai, this is the same as OP's model.
model[4] // TeXForm

$\omega (1) e^{-\frac{(x-\mu (1))^2}{\sigma (1)^2}}+\omega (2) e^{-\frac{(x-\mu (2))^2}{\sigma
   (2)^2}}+\omega (3) e^{-\frac{(x-\mu (3))^2}{\sigma (3)^2}}+\omega (4) e^{-\frac{(x-\mu (4))^2}{\sigma
   (4)^2}}+\omega (0)$

A: This is an extended comment.  (Well, two comments.)
(1) @Silvia 's and @rherman 's code (and code from any other expert programmer) requires good starting values.  That's just a fact of estimating curves.
(2) Rather than using triplets of sliders, how about using pairs of Locator's to define the individual Gaussian-shaped curves? A Locator at the peak of the curve could define the height and central value. A Locator on the "side" of the Gaussian curve could be restricted to move horizontally to vary the width. Sliders are good for when you have a "numerical" idea as to the values of the parameters. Here you want the user to set a "visual" idea as to the values of the parameters. This would also make the display less crowded (i.e., without any triplets of sliders).  Here's a crude example:
Manipulate[
 (* If no change in the mean/height locator, then update the standard deviation *)
 If[μ0 == p[[1]], σ = Abs[p2[[1]] - p[[1]]]];

 (* Update standard deviation locator *)
 p2 = {p[[1]] + σ, p[[2]] Exp[-1/2]};

 (* Record previous mean: this is so you can tell which locator was most recently moved *)
 μ0 = p[[1]];

 (* Plot associated Gaussian-shaped curve *)
 Plot[p[[2]] Exp[-(x - p[[1]])^2/(2 σ^2)], {x, -5, 5},
  PlotRange -> {All, {0, 5}}],

 {{p, {0, 0.4}}, Locator},
 {{p2, {1, 0.4 Exp[-1/2]}}, Locator},
 TrackedSymbols -> {p, p2},
 Initialization :> (μ0 = 0; σ = 1)]


text:
Q: Mac/LaCie Backup With Time Machine I have a MBP mid 2012, OS Catalina, with a Samsung 1TB SSD and want to get better about backups. I use backblaze but found it was not backing everything up when retrieving files. I bought a Lacie 2 TB HDD and did the first backup with Time Machine. Full backup is 616 GB. Other then taking two days it went fine. I ejected the HDD and did not reconnect until about a month later. Now when I reattach to backup the MBP shuts down sometime after 4hrs in, no crash report.  I thought it was overheating but moved to an open desk and still the MBP shut down. Any other thoughts?
Also, when I eject TM says "Encrypting" and stays this way, for more then an hour. Should this be expected. I'm planning on making the desk a more permanent home (bought an iPad Pro 2020 to try replacing the MBP with) but occasionally I will want to move it to connect with Ethernet instead of WIFI for faster speeds. (I live in an apt. and the tv is where the WIFI is leaving no space for the desk.) Will the eject process take more then an hour for encryption each time?


text:
Q: Binding for user controls embedded in page I have an ASP.NET page where I call this.DataBind() to bind the controls. I also have various user controls embedded. One has a drop down list, the bind statement gets called for it 2x but the sender the first time is not the drop down list.
Am I using the databind incorrectly? I use databind to get the properties of my page bound to a datasource so that I can use those properties in the declarative code.
In my DropDownList, I added if (sender == dropDownList) which solved the problem

A: Make sure that none of your user controls are themselves calling .DataBind()
.


text:
Q: How to fetch data from firebase datasnapshot? I have little experience with the firebase database. The following code doesn't work it as it doesn't retrieve the name of the user from the database. However, it shows the datasnapshot from the firebase. Here is the code.
databaseReference = FirebaseDatabase.getInstance().getReference().child("/userList/"+ FirebaseAuth.getInstance().getUid());
databaseReference.addChildEventListener(new ChildEventListener() {
    @Override
    public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
        Log.d(TAG, "onChildAdded: " + dataSnapshot.toString());
        for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()){
            Users users = dataSnapshot1.getValue(Users.class);
            String firstName = users.getFirstName();
            String lastName = users.getLastName();
            Log.d(TAG, "onChildAdded: " + firstName + " " + lastName);
        }
    }
}

The datasnapshot from firebase
onChildAdded: DataSnapshot {
    key = -Lt_5ltPuMx6CPSk5X8-,
    value = {
      firstName=firstname,
      lastName=lastname,
      email=firstname@gmail.com
    }
}

Here's how I store the firebase data.

A: The onChildAdded callback gets called for each child under /userList/$uid.  Each time it gets called, the snapshot contains one of the child nodes. In the callback you are looping over the children of that snapshot, which means that your dataSnapshot1 refers to the individual properties (email, firstName, lastName). And since those are not full user nodes, the dataSnapshot1.getValue(Users.class) fails to read a user from them.
In short: remove the loop, and you should be getting better results:
databaseReference = FirebaseDatabase.getInstance().getReference().child("/userList/"+ FirebaseAuth.getInstance().getUid());
databaseReference.addChildEventListener(new ChildEventListener() {
    @Override
    public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
        Log.d(TAG, "onChildAdded: " + dataSnapshot.toString());
        Users users = dataSnapshot.getValue(Users.class);
        String firstName = users.getFirstName();
        String lastName = users.getLastName();
        Log.d(TAG, "onChildAdded: " + firstName + " " + lastName);
    }
}

Also see these similar questions:

*

*childEventListener throws nullPointerException

*Object not getting From Datasnapshot using valueEventListerner but Working find but AddChildEventListern


text:
Q: Cannot Install Virtual Machine Manager 2008 R2 because Installation cannot start Server service I am attempting to install VMM 2008 R2 on my Windows 2008 R2 box. I had it going and after some issues had to uninstall and am now attempting to reinstall. Now I get the error:

Configuration of Virtual Machine Manager failed. For more information about configuration, see "Troubleshooting" in the Virtual Machine Manager Setup help.
  ID: 292. Details: The Server service is not started

From what I can tell it is not even installing the service. Does anyone have any ideas what could be going on?

A: The Server service is a core component of Windows and is not something that is installed with any other product, Microsoft or otherwise. If the Server service is missing it could be that you've uninstalled the File and Printer sharing component, which will uninstall the Server service so maybe that's what's going on.


text:
Q: Convert date to SQL datetime I'm somewhat new to T-SQL and despite reading a number of articles that indicate this should work, I'm having trouble converting October 1st of the current year to a datetime.
I've tried:
SELECT CAST(DATEPART(year, GETDATE()) + '1015' AS DATETIME)

SELECT CONVERT(datetime, 'Oct 15 ' + DATEPART(YEAR,GETDATE()),100)

And all kinds of variations.
Any ideas?  I need to set a datetime variable to whatever Oct 1st of the current year is.

A: What you're trying to is close, but DATEPART returns a number, so the "+" is doing addition, not concatenation.
Try it like this:
SELECT CAST(CAST(DATEPART(year, GETDATE()) AS VARCHAR(4)) + '1015' AS DATETIME)

edit -- Ed beat me to it, and the Concat function is better too.
But if you really wanted to knock it out of the park, try this...
SELECT DATEADD(month, 9, DATEADD(year, DATEDIFF(year, 0, getdate()), 0)) As October1CurrentYear

No casting required!

A: Your first query is very close. The problem is that the plus sign (+) for concatenation is actually giving you a numeric value, which you can't cast to a date.
To concatenate a year and '1015' and end up with a string, use the CONCAT function instead:
SELECT CAST(CONCAT(DATEPART(YEAR, GETDATE()), '1015') AS DATE)


text:
Q: how to use same column names with different data types in subquery in sqlserver I have a query:
select *
from proformaentry
where cast(tcmno as varchar) not in(
    select tcmno from contreceipt
)

I want to list all tcmno from proformaentry table which is not in the table contreceipt. In proformaentry table, tcmno is int datatype but in contreceipt, it is varchar type. So I used above query, but it is not returning any rows.
Actually there are some tcmno in proformaentry table which is not present in contreceipt.
Hope I can get the correct query to retrieve the rows from here.

A: I'm guessing contrecipt.tcmo is NULLABLE. NOT IN clause is the same as nested AND <> clauses. Example:
declare @tbl table(n int)
insert into @tbl values (1), (2), (3)

select * from @tbl where not n in(4, 5, 6, null)

The above query will not return any rows. If you transform the NOT IN, it'll be:
select * from @tbl where n <> 4 and n <> 5 and n <> 6 and n <> null

And since n <> null is FALSE, for the purpose of a WHERE clause, the NOT IN resulted to FALSE. In order to achieve the desired result, you can use NOT EXISTS:
select *
from proformaentry p
where not exists(
    select 1 from contreceipt where tcmno = cast(p.tcmno as varchar(20))
)


text:
Q: Error "Attempt to present xViewController on yViewController whose view is not in the window hierarchy!" iOS8 I have a view controller yViewController. I am adding it to the rootViewController as follows:
[self.window.rootViewController.view addSubView:yViewController.view]

I have a outlet UIButton on yViewController and on touch i am displaying a xViewCOntroller in a UIPopOverController using the following code to present it:
[popOver presentPopOverFromRect:button.frame inView:self.buttonContainerView permittedArrowDirections:UIPopOverArrowDirectionAny animated:NO]

It worked fine on iOS 7 however I am having the error on iOS 8:
Attempt to present xViewController on yViewController whose view is not in the window hierarchy!

Any advice?

A: Have you notified the view controller that is has moved to a parent one using will- and didMoveToParentViewController? https://developer.apple.com/library/ios/Documentation/UIKit/Reference/UIViewController_Class/index.html#//apple_ref/occ/instm/UIViewController/willMoveToParentViewController:


text:
Q: Angular async and event unexpectedly re-evaluating Observable My component utilises hot BehaviorSubject to observe a collection retrieved via http, but for simplicity I'll just create a basic BehaviorSubject driven list.
[snip]
This works exactly as expected.
Let's do something with the result, add an event to the list items (click, or mouseover etc.)
 <li
     *ngFor="let label of labels | async"
     (mouseover)="listMouseover()"
     >

      <span>{{convertString(label.title)}}</span>

  </li>

...
convertString(s:string) {

    console.log("evaluating string", s);
    return s + "!";

}

What you'll observe(!) is that the getter for the Observable is now hit every time any event is triggered, and (worse) the entire list is rebuilt. If this were expensive, this could be a problem, especially for something like mouseover.
[Edit - the async part is not relevant, happens with any list]
How do you mitigate this behavior, especially if reflow is expensive?
Thanks.  Plunkr here.

A: On your *ngFor use a trackBy.
https://angular.io/docs/ts/latest/guide/template-syntax.html (ctrl+F trackBy).
This will allow you to specify an identifier so that Angular won't tear down and recreate the DOM elements if the identifier is still present.
For the observable issue, you could create a simple cache so that it won't incur an expensive operation when the event is fired.
One such example is here:
http://www.syntaxsuccess.com/viewarticle/caching-with-rxjs-observables-in-angular-2.0


text:
Q: how to sort by Date related display the Records in visual force Page I display 20 Records in Visualforce Page, and Created SortBy: Date Button. Once Click the Date Button it should display selected Existing Records and Previous Records, in visualforce page using in Apex custom Controller.

A: In your soql querry add Order By createddate, that will work.


text:
Q: Electron js - Sub divs like dropdowns crops when parent window is smaller When I minimize the size of my application window and open a div (dropdown or any other menu), if the size of that div is bigger than the parent window, div is cropped.screenshot from intelliJ
In some applications like Intellij IDEA, they handle it well.screenshot from my app


text:
Q: Update notifications via Ajax I made a notification system. I wish I could, via Ajax, to call the function that allows me to display the number of unread notifications. There is the possibility, by browsing the website, you call the function every 10 seconds, for example, automatically. Thanks for your help.
  For now I have this code:
function notifications()
{
    $.get("//localhost/laravel/public/index.php/new_notifications",
    function(data)
    {
        data_parsed = JSON.parse(data);

        if(data_parsed.length > 0)
        {
            //code
        }
    });
}

A: if you want to call a function every few seconds, using javascript's set Interval should do:
window.setInterval(function(){
  /// call your function here
}, 5000);

Source
This function will loop/be called every 5 seconds.
setInterval is a standard JavaScript function, not part of jQuery. You call it with a function to execute and a period in milliseconds:
Here's how it might look:
setInterval(function(){
    $.ajax({ url: "server", success: function(data){
        //Update your dashboard gauge
        salesGauge.setValue(data.value);
    }, dataType: "json"});
}, 10000);

Source

A: Let's say you have a div somewhere that contains that information.

Refresh that div in your ajax call.
function notifications()
{
    $.get("//localhost/laravel/public/index.php/new_notifications",
    function(data)
    {
        data_parsed = JSON.parse(data);

        if(data_parsed.length > 0)
        {
            //i don't know the structure of your data, but put the right thing here.
            $("#unreadNotification").text(data_parsed.unreadNotification);
        }
    });
}

Call that function every 10 seconds.
setInterval(notifications, 10000);


text:
Q: $watch on checkbox not working I am using angular-bootstrap-checkbox like below:
HTML
<checkbox class="checkbox" ng-model="manualPosition"></checkbox>

I want to watch the changes for the checkbox values.
JS
$scope.$watch('manualPosition', function(manualPosition) {
    console.log('here');
});

It doesn't work for me.

A: You have to add a watch for whatever the $scope variable
$scope.$watch('manualPosition', function (checkboxVal) {
    console.log(checkboxVal);
});

And your html should be like this,
<input type="checkbox"  ng-model="manualPosition"> CLICK</input>

DEMO


text:
Q: "has risen" and "rose" I'm really confused about tense:

The percentage of the employees has risen from 20 percent to 24 percent over the past five years.

The university's four-year graduation rate rose from 20 percent in 2013 to 70 percent in 2017.

The second sentence uses past tense not related with present, and the first sentence uses present perfect because the percentage now is 24 percent.

The percentage of people age 65 and older in the workforce has risen from 15.5 percent percent to 17 percent last year.

"Last year" here is the past, say 2022. Why does it uses present perfect tense?
[EDIT]
My question is that in the third sentence which is from a newspaper, why present perfect tense was used despite the clear referent to the past, "last year."
[EDIT END]

A: *

*'Rose' is the simple past tense.

*'Risen' is the past participle.

We use 'rose' when the rising has finished. That's why your example that refers to a specific period from 2013 to 2017 uses it. That entire period is in the past.
But when we speak about something rising during "the last 5 years" its reasonable to assume, unless otherwise stated, that it is continuing to rise, so it is correct to say it "has risen".

A: As the answer by Astralbee correctly points out, "rose" is the past tense of the verb "to rise", while "risen" is the past participle of that verb. The past participle is used in forming both the past perfect and present perfect constructions. The sentence

(1) The percentage of the employees has risen from 20 percent to 24 percent over the past five years.

uses the present perfect. This consists of the present tense of the verb "to have" plus the past participle of the main verb. (see This page on "Present Perfect" for details.)
As the EF page linked above puts it, the present perfect is often used for:

*

*An action or situation that started in the past and continues in the present.

*An action performed during a period that has not yet finished.

*A repeated action in an unspecified period between the past and now.

*An action that was completed in the very recent past, expressed by 'just'.

*An action when the time is not important.

However, an action that occurred at a specified time in the past that ended significantly before the present will not usually be described using the present perfect. It will most often be described using the simple past, although the past perfect or other constructions may sometimes be used.
Thus sentence (1) is proper and natural. This construction is often used for events during a period still in progress, or one very recently ended. This is true whether the rise may be assuemned to be continuing, or to have only recently halted. But an attempt to use this construction about a definite past period not ending at or near the present movement (or continuing beyond the present) would not be. For example:

(2) The percentage of the employees has risen from 20 percent to 24 percent during the 1990s.

is not a valid use of this construction. One might write either of:

*

*(3) The percentage of the employees had risen from 20 percent to 24 percent

*(4) The percentage of the employees rose from 20 percent to 24 percent during the 1990s. during the 1990s.

Sentence (3) would be likely to be used only if some other event, subsequent to the rise, had been or was about to be mentioned as well.
One might also write:

(5) The percentage of the employees has risen from 20 percent to 24 percent over the past five years, but that rise reversed dramatically last November.

This is a case where the rise has recently endued, but the present perfect may still be used.


text:
Q: ToggleButton inside LIstView I have a problem with ToggleButton inside ListView.
I am using CursorAdapter to fill ListView. The problem is that when I click on some ToggleView inside, LogCat show different id.
public void bindView(View view, final Context context, final Cursor cursor) {

        ToggleButton toggle = (ToggleButton) view.findViewById(R.id.setalarm_item_switch);
        TextView id = (TextView) view.findViewById(R.id.setalarm_item_desc);

            id.setText(cursor.getString(ITEM_ID));

        toggle.setOnClickListener(new OnClickListener() {

            public void onClick(final View v) {

            Log.d("mojaapp", "Click on " + cursor.getINT(ITEM_ID));

            }
        });

    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {

        View view = LayoutInflater.from(context).inflate(R.layout.setalarm_item, null);
        return view;

    }

A: I think you are not reading the id correctly from cursor. Do it like this:
Log.d("mojaapp", "Click on " + cursor.getINT(cursor.getColumnIndex(ITEM_ID)));


text:
Q: Does Stack Exchange have an email notification option? Is there a feature on Stack Exchange that will allow me to receive an email notification when someone comments on my question or answer, or answers my question?

A: The email notifications option has been moved, from the multicollider to your profile. In order to reach it:

*

*Go to your profile by clicking on your username at the top of the page.

*Choose Preferences. You'll find it near your About me.

Check the blog post "Improved Global email notifications" by Jeff for more info.


text:
Q: Integral curves of height function's Hamiltonian vector field Consider in $\Bbb S^2$ the symplectic form $\omega \in \Omega^2(\Bbb S^2)$ given by $\omega_p(v,w) = \langle p, v \times w\rangle$. Fixed $z \in \Bbb R^3$, we define $h_z\colon \Bbb S^2 \to \Bbb R$ by $h_z(p) \doteq \langle p,z\rangle$. I computed the Hamiltonian vector field of $h_z$ as $X_{h_z}(p) = z \times p$.
I would like to find the integral curves of $X_{h_z}$. This means solving the system $\alpha'(t) = z \times \alpha(t)$. If $z = (a,b,c)$ and $$Z = \begin{pmatrix} 0 & -c & b \\ c & 0 & -a \\ -b & a & 0\end{pmatrix},$$we want to solve $\alpha'(t) = Z\alpha(t)$. Let's put the initial condition $\alpha(0) = p_0$ to ensure uniqueness of solution. Then $$\alpha(t) = \exp(tZ)p_0,$$and we use Rodrigues' rotation formula to get $$\alpha(t) = \left({\rm Id} + \frac{\sin \|tz\|}{\|tz\|}Z + \frac{1-\cos\|tz\|}{\|tz\|^2}Z^2\right)p_0.$$I'm having trouble visualizing this solution even in simple cases. We can assume that $p_0 = (0,0,1)$ since rotations are symplectomorphisms. If for example $z = (0,0,1)$, then $\alpha$ degenerates to a point. If $z = (0,1,0)$, then $\alpha(t)$ has the form $(\ast,0,\ast)$ and so is a pre-geodesic. What happens in the general case?

My sign convention is that if $(M,\omega)$ is a symplectic manifold and $f \in \mathcal{C}^\infty(M)$, then $X_f$ satisfies $\iota_{X_f}\omega = {\rm d}f$.

A: Let me present four easier points of view which are intertwined with visualization, but easily put into calculations.

*

*Using the beginning of your computation.
Your computation of the Hamiltonian vector field could be used directly to visualize it as in the second drawing which comes below ($z \times p$ is a vector of constant norm along the parallel passing through $p$ with respect to $z$, and it is tangent to said parallel. This gives an explicit solution: the parallel parametrized as such to have constant speed $\Vert z \times p\Vert$, and in the correct direction given by the sign conventions), but it may be a little ellusive to understand what is going on directly.

We can assume $z=(0,0,1)$ and $h$ is the height function after applying a rotation. This is not so important, but it is easier to present a drawing (which I will later on).

*

*Sphere and cylinder.
Since the north pole and the south pole clearly are stationary points since the height function has a maximum (resp. minimum) there, it suffices to analyse the rest. Therefore, we can use the fact that the horizontal projection of the
 cylinder on the sphere is a symplectomorphism (exercise!), and the pull-back of the height function under this map is obviously the height function on the cylinder. On the cylinder, it is clear (exercise!) that the integral curves are the horizontal circles. So the integral curves on the sphere will also be the horizontal circles (with different speeds corresponding to the fact that the speeds of the horizontal circles on the cylinder will transfer to slower speeds when sent via the symplectomorphism). The direction of those circles depends on the orientations you take.

*

*The almost-complex structure on the sphere.
The sphere $S^2$ has an obvious almost complex structure given by $J_px=p \times x$ (or $x \times p$, again orientation issues and sign conventions etc). This is just a rotation of $\pi/4$. It is easy to verify (exercise!) that $J$ is a compatible almost complex structure with the metric on the sphere, i.e.,
$$\omega(\cdot,J\cdot) =\langle \cdot, \cdot \rangle$$
and
$$\omega(J\cdot,J\cdot)=\omega(\cdot, \cdot).$$
Thus, the Hamiltonian vector field is given by $-J\nabla h$. And it is clear what that is, and what the orbits are:
Since $\nabla h$ is the vector field

it follows that $X_h$ is

PS: The drawing is a little off, as the vectors should be larger in the equator.

*

*Using the fact that the Hamiltonian is constant along the flows.
For a given integral path $\gamma$ of the Hamiltonian flow, $H \circ \gamma$ is constant. Thus, $\gamma$ must lie in a parallel of the sphere. Using a fragment of the other points of view, you can see that the speed must be constant on each integral path, thus the solutions are clear (computing the actual speed in terms of the height is easy).


text:
Q: why is the accuracy of my pretrained resnet-152 model so low? I am fairly new to deep learning and neural networks. I recently built a facial emotions recognition classifier using the FER-2013 dataset. I am using the pretrained resnet-152 model for classification, but the accuracy of my model is very low, both training and validation accuracies. I am getting an accuracy of around 36%, which is not good. I suppose that using transfer learning, the accuracies should be high, why is it that im getting such a low accuracy. should I change the hyperparameters? here is my code.
    model= models.resnet152(pretrained=True)

    for param in model.parameters():
      param.requires_grad= False

    print(model)
    from collections import OrderedDict

    classifier= nn.Sequential(OrderedDict([
                                           ('fc1',nn.Linear(2048, 512)),
                                           ('relu', nn.ReLU()),
                                           ('dropout1', nn. Dropout(p=0.5)),
                                           ('fc2', nn.Linear(512, 7)),
                                           ('output', nn.LogSoftmax(dim=1))
    ]))
    model.fc= classifier
    print(classifier)
    def train_model(model, criterion, optimizer, scheduler, num_epochs=10):
      since= time.time()

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

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

        for phase in ['train', 'validation']:
          if phase == 'train':
            scheduler.step()
            model.train()
          else:
            model.eval()

          running_loss= 0.0
          running_corrects=0

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

            optimizer.zero_grad()

            with torch.set_grad_enabled(phase== 'train'):
              outputs= model(inputs)
              loss= criterion(outputs, labels)
              _, preds= torch.max(outputs, 1)

              if phase == 'train':
                loss.backward()
                optimizer.step()

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

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

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

          if phase == 'validation' and epoch_acc > best_acc:
            best_acc= epoch_acc
            best_model_wts= copy.deepcopy(model.state_dict())

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

      model.load_state_dict(best_model_wts)
      return model

    use_gpu= torch.cuda.is_available()
    num_epochs= 10
    if use_gpu:
      print('Using GPU: '+ str(use_gpu))
      model= model.cuda()

    criterion= nn.NLLLoss()

    optimizer= optim.SGD(model.fc.parameters(), lr = .0006, momentum=0.9)
    exp_lr_scheduler = lr_scheduler.StepLR(optimizer, step_size=5, gamma=0.1)

    model_ft = train_model(model, criterion, optimizer, exp_lr_scheduler, num_epochs=10)

Can someone please guide me. I am a beginner at it, and I could really make use of some help in it.

A: *

*preprocess the dataset.

*Get more dataset as low accuracy could be a result of smaller dataset.

*Try data-augmentation if you have less data.


text:
Q: Asymptotic estimate for an integral involving the squared modulus of the Riemann zeta function For any fixed $\frac{1}{2} < \sigma < 1$, let
$$\int_0^T \frac{|\zeta(\sigma+it)|^2}{\sqrt{1+t^2}} \ dt = O(T^\theta), \qquad T \uparrow \infty. $$
It is clear that $\theta > 0$, since we have the classical asymtotic
$$\int_0^T \frac{|\zeta(\sigma+it)|^2}{T} \ dt \sim \zeta(2\sigma), \qquad T \uparrow \infty. $$
Is there more precise information about the value of  $\theta$?

A: Let us introduce the notation
$$M(T):=\int_0^T|\zeta(\sigma+it)|^2\,dt.$$
Then
$$\int_0^T \frac{|\zeta(\sigma+it)|^2}{\sqrt{1+t^2}} \,dt=\int_0^T\frac{dM(t)}{\sqrt{1+t^2}}=\frac{M(T)}{\sqrt{1+T^2}}+\int_0^T\frac{tM(t)}{(1+t^2)^{3/2}}\,dt$$
by writing this as a Riemann-Stieltjes integral and then integrating by parts. Using that $M(t)$ is asymptotically $\zeta(2\sigma)t$, we conclude that the left-hand side is asymptotically $\zeta(2\sigma)\log T$.


text:
Q: Borel set in $\mathbb{R}^3$ I want to show that $A$ is a Borel set, where: $$A=\{(x,y,z)\in\mathbb{R}^3 |0<x\le1,0<y^2+z^2\le x\} \subseteq \mathbb{R}^3$$
I know that we define the Borel $\sigma$-algebra by the $\sigma$-algebra generated by the open sets (lets call them O) of $\mathbb{R}^n$ - in this case $\mathbb{R}^3$ - and that the members of this Borel $\sigma$-algebra are called Borel sets.
I also know some different properties of the Borel $\sigma$-algebra, but I don't really know where to start.

A: One way to tackle this problem is to try to express this set as (countable) unions and intersections of (simpler) Borel sets. For example,
$A = \{(x,y,z)\in \mathbb{R}^3 \, | 0<x\leq 1\,\}\cap \{(x,y,z)\in \mathbb{R}^3 \, | 0<y^2+z^2\leq x\,\}$
and we can try to show that each of them is a Borel set.
Another useful tool to tackle these kind of problems is to use measurable functions $f:(X, \mathcal{F})\to (Y, \mathcal{G})$. For these functions, we will have that $f^{-1}(C)$ will be a $\mathcal{F}$-measurable set for every $\mathcal{G}$-measurable set $C$. It turns out that continuous functions $f:(\mathbb{R^d}, \beta(\mathbb{R^d}))\to (\mathbb{R}, \beta(\mathbb{R}))$ will be in particular measurable functions, so one can deduce that some sets are Borel from the fact that they are the pre-image of a measurable function. For example, the unit ball is Borel because $f(x,y,z)=x^2 + y^2 + z^2$ is a continuous function and then $f^{-1}([0,1))$ is a Borel set in $\mathbb{R}^3$ since $[0,1)$ is a Borel set in $\mathbb{R}$.
Recall that open intervals, closed intervals, and intervals in general, countable unions of intervals, open sets, closed sets, compact sets, G-$\delta$ sets and F-$\sigma$ sets are many examples of sets that live in the Borel $\sigma$-algebra over the reals, so there will be many (other) sets that can be expressed as the pre-image of an adequate Borel set in $\mathbb{R}$ by an adequate continuous (or, of course, a more general Borel-measurable) function.
Can you finish it from here?

A: Think about what this set is. If you look at the boundary, you'll see you have the points satisfying $x=y^2+z^2$ as part of it, which is the weird cone like thing that you might remember from the multivariates of the calculus.
Given this, you could visually see that $C = \{(x,y,z): 0 \leq x \leq 1, 0 \leq y^2 + z^2 = x\}$ is closed (which you still must prove rigorously). Also note $A = C \setminus \{(x,0,0) : 0\leq x \leq 1\}$. Since $C$ is closed, and the complement of the line is open, so the intersection is a Borel set (closed sets and open sets are Borel, so their intersection must be)

A: Your set $A$ is the intersection of the open set $\{(x,y,z):0<x\text{ and }0<y^2+z^2\}$ and the closed (i.e., complement of open) set $\{(x,y,z):x\leq1\text{ and }y^2+z^2\leq x\}$.


text:
Q: Match only Upper and Lowercase letters with Regex I am given a string (name) and it is supposed to check for the following:

*

*between 2 and 30 characters

*name can only contain alphabets and spaces

*First character of each work should be upper case

*Each word separated by space

*Name cannot start or end with space

*Special characters not allowed

here is my regex string: "[[[A-Z]{1}[a-zA-Z]*[\\s]?+]{2,30}[^\\s]"
"Roger Federer" should be valid, and this says it is
"Roger federer" should NOT be valid, but mine says it is
"Roger Federer $" should NOT be valid, but mine says it is
I'm curious if I'm enforcing these wrong, I am very new to regex

A: You can use
^(?=.{2,30}$)\p{Lu}\p{L}*(?:\s\p{Lu}\p{L}*)*$

If you want to allow one or more whitespaces between words, add + after \s.
See the regex demo.
In Java, the regex declaration will look like
s.matches("(?=.{2,30}$)\\p{Lu}\\p{L}*(?:\\s\\p{Lu}\\p{L}*)*")

The pattern matches

*

*^ - (implicit in matches) - start of string

*(?=.{2,30}$) - two to thirty chars required in the whole string

*\p{Lu}\p{L}* - an uppercase letter followed with zero or more letters

*(?:\s\p{Lu}\p{L}*)* - zero or more occurrences of a whitespace, then an uppercase letter and then zero or more letters

*$ - (implicit in matches) - end of string.

If you want to only match ASCII letters, replace \p{Lu} with [A-Z] and \p{L} with [A-Za-z].


text:
Q: How to select max date? My code is
function lister($a,$con){
    $queryq = " SELECT * FROM note WHERE date= MAX(date)  AND id='".$a."' AND admin='".$_SESSION['login_username']."' ";
    $resultq = mysqli_query($con,$queryq) or die('Error: ' . mysqli_error($con));
    $arrayq=mysqli_fetch_array($resultq,MYSQL_NUM); {
        echo $arrayq[4];
    }
}

There is an error:

Error: Invalid use of group function

What am I doing wrong?

A: try to split the query
         $queryA = "SELECT date FROM `note` WHERE id='".$a."' AND admin='".$_SESSION['login_username']."' ORDER BY date DESC LIMIT 1";
         $resultA = mysql_query($con, $queryA);
         $maxDatePerUser = mysql_fetch_array($resultA);
         $queryq = " SELECT * FROM note WHERE id='".$a."' AND admin='".$_SESSION['login_username']."' AND date='" . $maxDatePerUser["date"] ."'";
         $resultq = mysqli_query($con,$queryq) or die('Error: ' . mysqli_error($con));
         $arrayq=mysqli_fetch_array($resultq,MYSQL_NUM); {

A: The problem is caused by a circular reference of sorts.
SELECT * FROM note WHERE date= MAX(date)  AND id='".$a."' AND admin='".$_SESSION['login_username']."' "

You're asking the function to calculate something based on that same thing - a condition of the statement is MAX(date), but it can't calculate that until it knows what it is.
The best solution is to find MAX(date) separately:
SELECT max(date) FROM note

You can add additional restrictions, if necessary, if it is the max date WHERE, i.e.
SELECT max(date) FROM note WHERE id='".$a."' AND admin='".$_SESSION['login_username']."' "

Once you have this, you can pop it back in the query:
SELECT * FROM note
   WHERE date = (SELECT max(date)
                  FROM note
                  WHERE id = '" . $a . "'
                  AND admin = '" . $_SESSION['login_username'] . "')
   AND id = '" . $a . "'
   AND admin = '" . $_SESSION['login_username'] . "';

Hard to get the query 100% right without having the data to test on, but that should work.


text:
Q: update another column based on another, group by, left join, AND, sum and where I have one query without " WHERE expiry date is less than today " i am trying to explain is as far as possible by giving example of code, db structure, and expected results below
$query="UPDATE users c
LEFT JOIN (
  SELECT user_id, SUM(edexpf) as total
  FROM user_pages
  GROUP BY user_id
) x ON c.id = x.user_id
SET c.edexpn = COALESCE(x.total,0);
";

Here is Example results i am getting with db structure
users:
    id       edexpn
========== ===========
    1         0
    2         4

user_pages:
          expiry     user_id    edexpf         type
         ========== =========== ==========  ==========
2015-11-15 07:17:34      2          1         Static
2016-12-15 17:00:01      2          1         Dynamic
2016-12-15 17:00:01      2          1         New
2016-12-15 17:00:01      2          1         Dynamic

Now i am expecting results like this

users:
     id       edexpn
========== ===========
     2          2

Because one of page from user_pages: where user_id = 2 having 1
  passed date page and 2 up coming expiry date pages and type not like static, So, finally i don't want to get sum of expired date pages and if type like static And Like New

i think we can a add something like this
        // Where CURDATE() < DATE(expiry)
    AND type NOT LIKE '%Static%'
AND type NOT LIKE '%New%'

but not sure how


text:
Q: Can't get the text from pdf When i try to parse the pdf, i can't get the content of pdf but getting random symbols and characters. What is the reason behind it? This should give the proper text.
I have tried using PyPDF2 also still can not get the text.
filename = "test2.pdf"
with fitz.open(filename) as f:
    for p in f:
        print("\n\n")
        print(p.get_text(sort=True))

Result :
enter image description here
This type of result i get.


text:
Q: How to manage configurations across multiple computers and shells? I am a traveling technologist who does not always have a reliable connection to a home server. I tend to jump between zsh and bash on a few of my own machines.
What advice or recommendation would you have for normalizing my shell aliases and variables between shells?

A: The basic thing is to put your dot files under version control. When you use a new machine, check them out.
cd
git clone https://github.com/saterhater/home.git

In case the machine doesn't have your version control tool, you might want to at least download a read-only version. Github automates this; if you use different hosting that doesn't provide such a feature, make the generation of the zip file a commit hook.
cd
wget -O - https://github.com/saterhater/home/archive/master.zip | unzip -

As for the content of the files, you'll obviously need to make sure that they're portable. There's no magic recipe for that, just a few tips.

*

*Make sure to test your files under older versions of the shells, not just the ones you're using. I keep chroots with older Debian releases to get a range of versions of various software (my personal configuration should in principle work with bash 1.14 and zsh 2.5, though I haven't used versions that are that old in years).

*If you rely on any uncommon dependency, check it into your VCS, or write some automation to download it.

*If you want to make use of some feature when it's present, but keep a fallback if it's absent, test for the feature rather than testing the version number. It's more robust (some systems might have a nightly build, for example).

You can share some things between bash and zsh, mostly aliases and some functions. Key bindings and prompt settings aren't shareable. Bash completion functions can be used with non-ancient versions of zsh. If you have some code that makes use of the automatic splitting and globbing of unquoted variables that zsh doesn't perform, you can run emulate -L ksh to make zsh switch to ksh compatibility mode for the duration of a function; make emulate an alias to : if the shell isn't zsh (you can test the presence of the ZSH_VERSION variable).


text:
Q: JavaScript simulate Accesskey-Press I was wondering if there is a way to simulate pressing an accesskey with JavaScript. It should work with the following html:
<button accesskey="z">click</button>

Here is my approach with jQuery (pressing ALT+Z in Chrome):
var e = $.Event("keypress");
e.which = 90;
e.altKey = true;
$('button').trigger(e);

But it won't work so far. I want to test the accesskey specifically, just clicking the button via JavaScript is not the solution I'm looking for.

A: I think you are going to have to use something like Selenium to accomplish this. I have read all the literature I can find on the matter and experimented in jsFiddle. The browser treats an accesskey event exactly like a mouseclick. Even if you did manage to trigger it the event metadata all suggests the source was a mouse click so you can't definitively confirm it.
I have attempted to trigger the key combination on all levels of the DOM and with all key event types, this suggests to me that the accesskey functionality is on the browser level and not the API.
Selenium
[Edited answer, seems like different technology is needed]


text:
Q: jqChart candlestick chart : strange display I am using jqChart plugin for jQuery.
With the following code, candlestick chart is rendered correctly.
<script lang="javascript" type="text/javascript">
        $(document).ready(function () {
            $('#jqChart').jqChart({
                title: { text: 'CNDL CHRT' },
                series: [
                            {
                                type: 'candlestick',
                                data : [ ['Mon', 5375, 5325, 5340, 5330], ['Tue', 5322, 5250, 5290, 5270], ['Wed', 5375, 5325, 5340, 5330], ['Fri', 5322, 5250, 5290, 5270]]
                                                            }
                        ]
            });
        });
    </script>

All other things unchaged except for the JSON data as under, the chart is not rendered correctly.
Tooltips are displayed for only some of the bars.
All bars are without fill-color.
data : [["2012/07/02:0920", 5308.2, 5308.2, 5288.0, 5292.4], ["2012/07/02:0930", 5292.0, 5296.7, 5283.35, 5295.05], ["2012/07/02:0940", 5295.95, 5297.3, 5286.6, 5288.55], ["2012/07/02:0950", 5289.4, 5292.0, 5284.0, 5285.0]]

What may be wrong in the second "data" json object?
Thanks,
Vineet

A: The jqChart candlestick chart accepts data is in format HLOC. I believe you second data is in format OHLC.
You can convert it with something like:
    var data = [["2012/07/02:0920", 5308.2, 5308.2, 5288.0, 5292.4], ["2012/07/02:0930", 5292.0, 5296.7, 5283.35, 5295.05], ["2012/07/02:0940", 5295.95, 5297.3, 5286.6, 5288.55], ["2012/07/02:0950", 5289.4, 5292.0, 5284.0, 5285.0]];

    for (var i = 0; i < data.length; i++) {

        var item = data[i];

        data[i] = [item[0], item[2], item[3], item[1], item[4]];
    }

    $('#jqChart').jqChart({
        title: { text: 'CNDL CHRT' },
        series: [
                    {
                        type: 'candlestick',
                        data: data
                    }
                ]
    });


text:
Q: Stop My Footer From Sitting On The Bottom Of The Screen I'm having an issue with my footer where it is being stuck to the bottom of my screen and not sitting at the bottom of the page, can anyone help me sit at the bottom on the page not on the bottom of the screen?

footer {
  position: fixed;
  left: 0px;
  bottom: 0px;
  height: 70px;
  width: 100%;
  background: #2c2c2c;
}

#footer_container {
  max-width: 940px;
  height: 70px;
  margin: 0 auto;
  padding-top: 2%;
}

.social {
  list-style-type: none;
}

.social li a {
  position: absolute;
  bottom: 0;
  right: 0;
  display: inline;
  float: right;
  padding: 10px;
  text-decoration: none;
  color: #FFFFFF;
  font-weight: bolder;
}

.social>li>a:hover {
  color: #D9D9D9
}

.copyright_text {
  position: absolute;
  bottom: -10px;
  left: 0;
  padding-top: 2%;
  float: left;
  text-transform: uppercase;
  font-size: 0.30cm;
  color: #fff;
  margin-left: 20px;
}

.logo_footer {
  display: flex;
  align-items: center;
  position: fixed;
  left: 0px;
  bottom: 15px;
  height: 50px;
  width: 100%;
  margin-left: 20px;
  margin-bottom: 5px;
}

© Copyright 2017 AccountPARADISE

TWITTER

A: If you use position:fixed; then your element will be casted to the location depended on your screen, not your page.
If you want to trow it down you can do multiple things. You can have a parent container with position relative en put absolute bottom:0.
Or just place it display block and put it below your other html containers.
This way it will be aligned behind the rest and at the bottom of your page.

A: Just don't use position: fixed - erase that from the CSS rule for the footer, then it will simply be below all other elements above it. (The left and bottom parameters can also be erased in this case, they are only relevant for "positioned" elements)


text:
Q: Sending string through queue in Freertos I want to create a task with push button and the task sends a string to a queue and creates another task (this can also be separate task with lower priority) which reads the queue and blink led if its variable is same with the string in the queue. Otherwise system should stay in the idle mode. Im quite new with freertos and Led doesnot blink with below codes eventhough there is no compilation error. I also want to replace the datatype from char to string if it is possible. (select and zyRxBuff come from different sources, it is written as below for simplicity)
#include "main.h"
#include "FreeRTOS.h"
#include "task.h"
#include "timers.h"
#include "queue.h"

void SystemClock_Config(void);
static void MX_GPIO_Init(void);

The handlers ;
QueueHandle_t myQueue = NULL;
TaskHandle_t QTASK1 = NULL;
TaskHandle_t QTASK2 = NULL;

Prototypes ;
void Qsender(void* p);
void Qreceiver(void* p);

Main block;
int main(void)
{

 HAL_Init();
 SystemClock_Config();
 MX_GPIO_Init();

if (HAL_GPIO_ReadPin(GPIOC, GPIO_PIN_13) == GPIO_PIN_SET)
{
     xTaskCreate(Qsender, "SendingTask", 200, NULL, 1, &QTASK1);
     vTaskStartScheduler();
}
 while (1) {};
}

Sender Function;
void Qsender(void* p)
{
  char select[10]= "BlinkLed";
    myQueue = xQueueCreate(1, sizeof(select));
    xQueueSend(myQueue, (void*) &select, (TickType_t)10);

    if (myQueue != 0)
    {
        xTaskCreate(Qreceiver, "ReceivingTask", 200, NULL, 1, &QTASK2);
    }

}

Receiver Function;
void Qreceiver(void* p)
{
    char myRxBuff[10];
    char zyRxBuff[10]="BlinkLed";
    xQueueReceive(myQueue, &myRxBuff, (TickType_t)50);

    if ( myRxBuff == zyRxBuff)
    {
            HAL_GPIO_TogglePin(GPIOB, GPIO_PIN_0);
            HAL_Delay(500);
    }
}

Idle function;
void vApplicationIdleHook(void){__WFI();};

A: Nothing is happening because the program is likely executing too quickly for things to work. When your program starts it initializes everything in a fraction of a second, and if the button is not pressed then nothing happens. Then your main loop does nothing. At a minimum, you should put the button watching in a task, and that task should have a while or for loop that doesn't end.
Create a more simple system first - like, two tasks, a button-reader, and a light-emitter. The button-reader task simply checks if the button is pressed and inserts an item into the queue. The light-emitter check if there is something in the queue.
It should also be noted, that all RTOS really don't like creating and ending tasks all the time. If you're going to do so, you should read up on how tasks are created and destroyed. (https://www.freertos.org/a00125.html) Letting a task go out of context doesn't automatically clean it up, you need to use vTaskDelete - With your current functions, you'll need to clean up the QReceiver with your QSender task, which is a violation of the SOLID principals. Additionally, your QReceiver will  need to send a message back that it's done. If you can get them statically working first, it will be a lot easier to get them dynamically working later.
I also noticed that you're comparing strings by address and not by content.
Qsender is sending BlinkLed
void Qsender(void* p){
    char select[10]= "BlinkLed";
    myQueue = xQueueCreate(1, sizeof(select));
    xQueueSend(myQueue, (void*) &select, (TickType_t)10);

    if (myQueue){
        xTaskCreate(Qreceiver, "ReceivingTask", 200, NULL, 1, &QTASK2);
    }
}

However in Qreceiver you're comparing the address of myRxBuff and zyRxBuff, when you should be doing a string-compare
void Qreceiver(void* p){
    char myRxBuff[10];
    char zyRxBuff[10]="BlinkLed";
    xQueueReceive(myQueue, &myRxBuff, (TickType_t)50);
    if ( myRxBuff == zyRxBuff){ // Offending Line
            HAL_GPIO_TogglePin(GPIOB, GPIO_PIN_0);
            HAL_Delay(500);
    }
}

void Qreceiver(void* p){
    char myRxBuff[10];
    char zyRxBuff[10]="BlinkLed";
    xQueueReceive(myQueue, &myRxBuff, (TickType_t)50);
    if ( strcmp(myRxBuff, zyRxBuff) == 0){ // Should compare content now
            HAL_GPIO_TogglePin(GPIOB, GPIO_PIN_0);
            HAL_Delay(500);
    }
}


text:
Q: Running a java program at the command line, what am I doing wrong? Note
I'm running windows, the path just looks like it's linus because I typed it manually and thats how I think of paths.
I'm trying to run a java class That I have built to diagnose my connection to a databse, it references the oracle jdbc adaptor.
When I just run it without a class path:
%> java DBDiagnostics <connectionString>

I get an exception when it reaches the following line of code:
Class.forName("oracle.jdbc.pool.OracleDataSource").newInstance();

with the following exception:
java.lang.ClassNotFoundException: oracle.jdbc.pool.OracleDataSource
        at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
        at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
        at java.lang.Class.forName0(Native Method)
        at java.lang.Class.forName(Class.java:169)
        at DBDiagnostics.GetConnection(DBDiagnostics.java:43)
        at DBDiagnostics.runDiagnostic(DBDiagnostics.java:29)
        at DBDiagnostics.main(DBDiagnostics.java:18)
Creating connection.
java.sql.SQLException: No suitable driver found for lskd
        at java.sql.DriverManager.getConnection(DriverManager.java:602)
        at java.sql.DriverManager.getConnection(DriverManager.java:207)
        at DBDiagnostics.GetConnection(DBDiagnostics.java:55)
        at DBDiagnostics.runDiagnostic(DBDiagnostics.java:29)
        at DBDiagnostics.main(DBDiagnostics.java:18)
Veryfying connectivity to Database
Exception in thread "main" java.lang.NullPointerException
        at DBDiagnostics.verifyTable(DBDiagnostics.java:86)
        at DBDiagnostics.verifyTable(DBDiagnostics.java:76)
        at DBDiagnostics.verifyDatabseConnectivity(DBDiagnostics.java:68)
        at DBDiagnostics.runDiagnostic(DBDiagnostics.java:36)
        at DBDiagnostics.main(DBDiagnostics.java:18)

I assume that this is because I need to include it in the classpath.
So, I tried adding it to the classpath like this:
%> java -classpath .:ojdbc6.jar DBDiagnostics <connectionString>

The VM just says it cant find the class:
Exception in thread "main" java.lang.NoClassDefFoundError: DBDiagnostics
Caused by: java.lang.ClassNotFoundException: DBDiagnostics
        at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
        at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
Could not find the main class: DBDiagnostics.  Program will exit.

I know this is a question I should just know the answer to, but what am I doing wrong?

A: Replace the colon with a semicolon:
java -classpath .;ojdbc6.jar DBDiagnostics <connectionString>

A: is there a typo:
%> java -classpath .:ojdbc6.jar DBDiagnostics <connectionString>

maybe it would work if you type this:
%> java -classpath ./ojdbc6.jar DBDiagnostics <connectionString>

A: Does the DBDiagnostics.class file appear in the directory from which you're launching Java?  If not, the class loader won't find it.
Does the DBDiagnostics class have a package?  If it does, you have to refer to the fully resolved class name, and the root of the package hierarchy has to appear in the directory from which you launch Java.

A: Mike Sickler's answer looks right for a Windows platform.  The path separator for Windows is ";", but ":" for Unix and Linux, so make sure you always use the right one!

A: Long shot, but is this Unix or Windows? If on Windows the class path separator should be a semi colon:-
%> java -classpath .;ojdbc6.jar DBDiagnostics <connectionString>

And of course you need to have the ojdbc6.jar file in the current directory if you don't specify any path to it. (And possibly it's dependencies as well...)


text:
Q: using RESTlet, XStream annotations seem to have no effect Using @XStreamOmitField in my POJO seems to have no effect whatsoever. the annotated field still gets exposed in the xml or json representation.
@XStreamAlias("Pojo")
@Entity
public class Pojo {
    private String name;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long key;

    @XStreamOmitField
    private String hidden;

    public Pojo(String name, String hidden) {
        this.name = name;
        this.hidden = hidden;
    }
}

and in the ServerResource
@Get
public Pojo test() {
    Pojo pj= new Pojo("hansi","hinter");
    return pj;
}

gets me
<com.myComp.ORMTest.Pojo>
  <name>hansi</name>
  <hidden>hinter</hidden>
</com.myComp.ORMTest.Pojo>

Any ideas why the annotations are ignored?

A: Two things come to mind:
1.) Did you tell XStream to parse the annotations?
2.) Does your web framework maybe use proxies to access the pojos and those don't delegate the annotations? (happened to a friend with Apache Tapestry)

A: You have to tell XStream to explicitly process annotations:
XStream xstream = new XStream();
xstream.processAnnotations(MyClass.class);

Or, you should add this code to tell XStream to process all annotations:
xstream.autodetectAnnotations(true);


text:
Q: Is the length of the proof of propositional tautology a PA-total function? Suppose we have fix some interpretation of propositional (not first-order!) logic inside PA, and say $f(n) = $ {the maximum length of a proof of a tautology with $n$ propositional primitives}
Questions:
1) Is this PA-definable? I think so, because all of the deduction rules of propositional logic are codeable as PA relations.
2) Does PA prove that this function is total a priori? We know there is some sort of exponential bound (convert everything into CNF, and then inspect the result), but can we prove that this function is PA-computable without knowing there exists a bound necessarily?
Motivation: I want to bound the length of proofs of tautologies of length $n$. While one can do this by considering carefully the proof of Completeness for propositional logic, this is quite tedious, and I was wondering whether we can justifiably bound this function by, say, the Goodstein function (or some other similarly fast-growing function).

A: Yes, $PA$ can prove that the "propositional busy beaver" is total. In fact, the bound you cite is provable in $PA$ - the standard proof doesn't use anything beyond $PA$!


text:
Q: Bloomberg API DVD_HIST request with DVD_START_DT & DVD_END_DT override First let me apologize for my bad english.
I'm writing a Java servlet, HistoricalDataRequest (BDH Excel Add-In function) & ReferenceDataRequest (BDP Excel Add-In function) work fine.
And now I'm trying to request a DVD_HIST (BDS Excel  Add-In function), but when I set the override for DVD_START_DT & DVD_END_DT I get this exception:

com.bloomberglp.blpapi.NotFoundException: Element: DVD_START_DT not
  found in: ReferenceDataRequest

I'm using this command:
request.set("DVD_START_DT", "20151101");

request.set("DVD_END_DT", "20151231");

Anybody found this problem before?
Some ideas?

A: The correct way to set overrides on a Historical/Reference request is:
Element overrides = request.GetElement("overrides");
Element override1 = overrides.AppendElement();
override1.SetElement("fieldId", "DVD_START_DT");
override1.SetElement("value", "20151101");
Element override2 = overrides.AppendElement();
override2.SetElement("fieldId", "DVD_END_DT");
override2.SetElement("value", "20151231");


text:
Q: Python: next in for loop I want to use next to skip one or more items returned from a generator. Here is a simplified example designed to skip one item per loop (in actual use, I'd test n and depending on the result, may repeat the next() and the generator is from a package I don't control):
def gen():
for i in range(10):
    yield i

for g in gen():
   n = next(gen())
   print(g, n)

I expected the result to be
0 1
2 3

etc.
Instead I got
0 0
1 0

etc.
What am I doing wrong?

A: You're making a new generator each time you call gen(). Each new generator starts from 0.
Instead, you can call it once and capture the return value.
def gen():
    for i in range(10):
        yield i

x = gen()
for g in x:
    n = next(x)
    print(g, n)


text:
Q: Create a New Hard Drive Partition in Windows 8 I got a dell inspiron laptop with 500 GB Hard Drive with Windows 8 pre installed. There is only one partition (C). OS installed on this partition.
I want to partition C drive. What is the best way to partition it ?

A: The best way is the Disk Management applet. Right click on 'My Computer' and click 'Manage', then on the left hand side, storage > Disk Management.

Right click on the C:\ Partition, and select 'Shrink Volume...' - Reduce the partition down to the size that you want your new partition, and click 'Shrink.'
Now, in the new unallocated space, right click and format it however you'd like!


text:
Q: How do I set the table cell widths to minimum except last column? I have a table with 100% width. If I put s in it, they get spread out with equal length columns. However, I want all the columns except last to have as small a width as possible, without wrapping text.
What I did first was that I set width="1px" in all s except last (although deprecated, but the style="width:1px" didn't have any effect), which worked fine until I had multi-word data in the column. In that case, to keep the length as small as possible, it wrapped my text.
Let me demonstrate. Imagine this table:
---------------------------------------------------------------------------------
element1 | data      | junk here   | last column
---------------------------------------------------------------------------------
elem     | more data | other stuff | again, last column
---------------------------------------------------------------------------------
more     | of        | these       | rows
---------------------------------------------------------------------------------

No matter what I try, what I keep getting is either this:
---------------------------------------------------------------------------------
element1         | data             | junk here        | last column
---------------------------------------------------------------------------------
elem             | more data        | other stuff      | again, last column
---------------------------------------------------------------------------------
more             | of               | these            | rows
---------------------------------------------------------------------------------

or (even though I set style="whitespace-wrap:nowrap") this:
---------------------------------------------------------------------------------
         |      | junk  | last
element1 | data |       |
         |      | here  | column
---------------------------------------------------------------------------------
         | more | other | again,
elem     |      |       | last
         | data | stuff | column
---------------------------------------------------------------------------------
more     | of   | these | rows
---------------------------------------------------------------------------------

I want to get the table I presented first. How do I achieve this? (I'd rather stick to standard and using CSS. I honestly don't care if IE hasn't implemented part of the standard either)
More explanation: What I need is to keep the columns as short as possible without wrapping words (last column should be as large as it needs to make the table width actually reach 100%). If you know LaTeX, what I want is how tables naturally appear in LaTeX when you set their width to 100%.
Note: I found this but it still gives me the same as last table.

A: whitespace-wrap: nowrap is not valid css. It's white-space: nowrap you're looking for.

A: td:not(:last-child){
    white-space: nowrap;
}

td:last-child{
    width: 100%;
}

By using the code above, the last table-cell will try to be as big as possible, and you will prevent the ones before that from wrapping. This does the same as the other answers given, but way more efficient.

A: You can set fix width by placing div tag inside td

table {
    border: 1px solid green;
    border-collapse: collapse;
    width:100%;
}

table td {
    border: 1px solid green;
}

table td:nth-child(1) {
  width: 1%;
}

table td:nth-child(1) div {
  width: 300px;
}

element1 element1 element1 element1 element1 element1

        data
        junk here
        last column

element2

        data
        junk here
        last column

element3

        data
        junk here
        last column

https://jsfiddle.net/8bf17o1v/

A: Slightly different topic but maybe it helps someone who stumbles on this question like me.
(I just saw the comment by Campbeln who suggests exactly this after writing my answer below, so this is basically a detailed explanation of his comment)
I had the problem the other way around: I wanted to set one table column to the minimum width possible without breaking it on white space (last column in the following example) but the other's width should be dynamic (including line breaks):
-----------------------------------------------------------------------------------
element1 | data      | junk here which can   | last column, minimum width, one line
                       span multiple lines
-----------------------------------------------------------------------------------
elem     | more data | other stuff           | again, last column
-----------------------------------------------------------------------------------
more     | of        | these                 | rows
-----------------------------------------------------------------------------------

Simple solution:
HTML

    element1
    data
    junk here which can span multiple lines
    last column, minimum width, one line

    elem
    more data
    other stuff
    again, last column

    more
    of
    these
    rows

CSS
td.shrink {
  white-space: nowrap;
  width: 1px;
}

Columns with class shrink only expand to the minimum width but others stay dynamic. This works because width of td is automatically expanded to fit whole content.
Example Snippet

table {
  width: 100%;
}

td {
  padding: 10px;
}

td.shrink {
  white-space: nowrap;
  width: 1px;
}

    element1
    data
    junk here which can span multiple lines
    last column, minimum width, one line

    elem
    more data
    other stuff
    again, last column

    more
    of
    these
    rows

A: This works in Google Chrome, at least. (jsFiddle)

table {
  border: 1px solid green;
  border-collapse: collapse;
  width: 100%;
}

table td {
  border: 1px solid green;
}

table td.shrink {
  white-space: nowrap
}

table td.expand {
  width: 99%
}

    element1
    data
    junk here
    last column

    elem
    more data
    other stuff
    again, last column

    more
    of
    these
    rows

A: If you need multiple text lines in table cell.
Do not use white-space: nowrap use white-space: pre; instead.
In table cell avoid any code format like new lines and indention (white-space) and use
 to set a new text line/row. Like this:
element1
second row

Demo on CodePen

A: A combination of either white-space: nowrap or white-space: pre with min-width: <size> will do the job. width: <size> on itself is not enough to hold the table from squeezing.


text:
Q: Add an IntegerField to a Datefield in a Django template I'm trying to display the expiry date of a bonus from within a Django template. At the moment the opening_date is stored as a datefield and we store the bonus term as an integerfield. Unfortunately just trying to add the bonus term to the opening date fails and the furthest I have got so far is:
{{product_form.instance.opening_date|add:product_form.instance.bonus_term}}

I have tried just adding it to the month but unfortunately I need the whole date returned to display.
For a better idea of what I want is say the opening date was 01/01/2012 and the bonus term was 12, I want to display the expiry date of 01/01/2013. I realise this is probably better off being in the database but due to the way it has been previously set up there is a large amount of existing data that wouldn't have it.
Thanks.

A: I think that, for your scenario, the most elegant solution is to create a model method in your model that calcule expire date, then call the method in template:
In model:
class product(models.Model):
    opening_date = ...
    bonus_term = ...
    def expire_date( self ):
         return self.opening_date + timedelta( days = self.bonus_term )

In template:
{{product_form.instance.expire_date}}

I'm sure that you will call this method in more other lines of your code.