Q:

check user security for modifying objects

I am thinking about security implementation for my python web app.
For example I have user and profiles.
Each user can edit his profile by sending POST at /profile/user_id
On every request i can get session user_id and compare it with profile.user_id if they not same - raise SecurityException().
But I also can do it another more common way:
generate for each profile
secret = hash(profile_data+secret_key)

and render for auth. users links like this:
/profile/4?key=secret

So idea is to generate secret key based on editable object data and check this key on server side. If user don't know secret key it can't get links to edit other profile, and so can't modify them.
How this method of protection called?
Has it any problems in comparsion with session based user_id check?

A:

/profile/4?key=secret

Practical issues:

it's generally a bad idea to put a secret in a URL. URLs leak easily through logs, history, referrers etc. Also it breaks navigation. It's better to put the secret in a cookie or POST data.
you would typically include a time limit in the signed data, so tokens aren't valid forever
you would typically include some kind of flag/counter/state on the user information and in the signed data, so that a user can update something (eg change password) to invalidate previously-issued tokens
you also have to ensure that the lifecycle of signed data can't be longer than that of the token, eg that you can't delete user 4 and create a new user 4 for whom the token is still valid
the hash you would use would be an HMAC using a server-side secret for the key

Signed authentication tokens are typically used as an alternative to database-backed session storage, for performance or operational reasons. It's certainly possible to do sessions securely with signed tokens, but if you're already using stored sessions for other purposes anyway you don't have a lot to gain.


Q:

Directory.GetDirectories with applied ExcusionsList with Linq

I have:
var folders = Directory.GetDirectories(path);

Decided to exclude some folders which they were listed in an array:
string[] ExcludingList;

And trying to achieve it via LINQ:
So was trying something similar to the line below, but yet the format is wrong:
var folders = Directory.GetDirectories(path)
    .Where(d => (! ExcludingList.Contains(d.Name)));

I know it is still wrong, maybe an extra initialization, a type change, conversion, or changing a bit of format be needed, can you help me with it?

A:

The code is good, but the issue is d represent the Name of sub directory, then you don't need to use d.Name, use just d, change little the code to :
var folders = Directory.GetDirectories(path)
    .Where(d => !ExcludingList.Contains(d))
    .ToList();

I hope you find this helpful.


Q:

Simplest way to render a 3D scene to an image file

I have a 3D scene (essentially a VRML file with one big IndexedFaceSet). I want to render the scene once into an image file. The image file will serve as a preview to the user, who will then be able to open the scene in a 3D viewer (X3DOM - it's a great library).
I know the camera position, direction and field-of-view angle necessary for the preview, as well as the lighting.
The preview image will be prepared offline on the server. Everything else on the server is written in Python, and I'd rather not introduce another language to the mix.
I tried Matplotlib, but couldn't figure out how to perform proper shading and lighting there. I don't want to start a browser instance on the server and let X3DOM do the heavy lifting. I guess I can use PyOpenGL to render the scene once and save it to a file, but I'm hoping there's an easier way.

A:

You could install blender, import and render through that but it is probably overkill.
OpenGLContext would probably provide all that you need: pyOpenGL it seems to be quite well documented and reasonable to use and seems to support the import of VRML.
If you need a higher resolution then you can make use of YaFaRay but I found it a lot harder to see if VRML import was supported directly or not.


Q:

Sorting dates in DataTables? (function override)

DataTables properly sort dates in YYYY-MM-DD format only. All other formats they sort as string.
As far as I'm not a fan of adding a library / plugin for every functionality into my projects I tried to solve it by myself.
DataTables are using Date.parse() function to "understand" the date and sort it. (according to https://datatables.net/blog/2014-12-18).
So I decided to override that function and modify it in the way it will "understand" also other date formats.
I added this JS into my code:
            let origFunction = Date.parse;

            Date.parse = function(str) {

                // I want to parse this date format: 27.01.2018
                if (str.indexOf('.') > 0) {
                    str = convertDateToISO(str); // my function translates date into 2018-01-27
                }
                return origFunction(str);
            };

When I test this in the browser console, Date.parse works perfectly fine with my date format, but DataTables keep sorting my european dates as strings.
Any idea what I'm doing wrong? Or is it possible to do it this way?
SOLVED:
After all it looks like really the easiest way is to include "Moment.js" plugin as described here: https://datatables.net/blog/2014-12-18#Operation
But while there was a "no plugin" requirement in my question, I'm accepting answer of @billynoah as a solution too.

A:

You probably want to take a look at orthogonal-data.  This allows you to define a custom value for sorting your column.  In this case, the most straightforward thing to do is use a timestamp for sorting and then you can display date in any format you want.  For data sourced from an object or ajax you can structure your column definition like:
{
    data: 'date',
    render: {
        _: 'display',
        sort: 'timestamp'
    }
}

For html source you can use the data-order attribute:
Sat, Dec 22nd 2018

(Disclaimer / Attribution: This is all more or less straight out of the manual linked above)


Q:

apache redirect misses /

I configured port 80 with:
Redirect permanent / https://www.scool.cool/

but if I enter for example: scool.cool/wp I got https://www.scool.coolwp.
How can I fix this? How can I add the miss slash?

A:

Try this in .htaccess or httpd.conf:
This will enable the Rewrite capabilities:
RewriteEngine On

This checks to make sure the connection is not already HTTPS:
RewriteCond %{HTTPS} !=on

This rule will redirect users from their original location, to the same location but using HTTPS:
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]

Full example:
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]

I hope to this help.


Q:

WordPress: Using custom field to define posts to display in loop

I'm trying to use a custom field in which I input the post ID numbers of the posts I want to show, seperated by commas. For some reason though, only the first post of the series of the post IDs are displaying. Can someone help? The value of $nlPostIds is (minus the quotes): "1542,1534,1546". Here's the code... the most important part is the 4th line 'post__in' => array($nlPostIds)
<?php
$nlPostIds = get_post_meta($post->ID, 'nlPostIds', true);
$args=array(
    'post__in' => array($nlPostIds)
   );
query_posts($args);
if ( $wp_query->have_posts() ) : while ( $wp_query->have_posts() ) : $wp_query->the_post(); ?>

            <div class="post" id="post-<?php the_ID(); ?>">

<a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?>

<?php the_time('F jS, Y') ?> | <?php comments_popup_link('No Comments', '1 Comment', '% Comments'); ?>  | Posted in <?php the_category(', ') ?>

                    <?php the_content('More »'); ?>

<?php the_tags('Tags: ', ', ', ' '); ?> <?php edit_post_link('Edit', '[ ', ' ]'); ?>

<?php endwhile; endif; ?>

Thanks!

A:

I think you need to also pass the argument 'posts_per_page' as -1 in your $args array (see the Codex on query_posts()).
UPDATE:
Apologies, I've just re-read your question and I think I know the problem. Pass $nlPostIds as the direct argument, without placing it an array. You only pass an array when each  element is an ID. In this care you're just passing a comma-separated string.
UPDATE:
Use;
$args = array('post__in' => @explode(',', $nlPostIds), 'posts_per_page' => -1);


Q:

Gathering Data For ClosedXML Using foreach Loop

My C# ASP.NET MVC5 application has a model named Ticket. I want to export all of the tickets in my database to an excel spreadsheet using ClosedXML. I have an Action just for exporting and downloading the data to the spreadsheet. Everything is working great, except when I open my newly downloaded spreadsheet I only have one ticket in there. I think I don't have something just right with my foreach loop. What am I doing wrong?
My action that is called when the user wants to download tickets:
public ActionResult DownloadTickets()
{
    string date = "";
    string title = "";
    string createdBy = "";
    bool isCallBack = true;

    using (var wb = new XLWorkbook())
    {
        var ticket = _context.Tickets.ToList();
        var dateForXcellSheet = DateTime.Now;
        var worksheet = wb.Worksheets.Add("Sample Sheet");

        foreach (var i in ticket)
        {
            date = i.DateCreated.ToString();
            title = i.Title;
            createdBy = i.CreatedBy;
            isCallBack = i.IsCallBack;
        }

        worksheet.Cell("A1").Value = date;
        worksheet.Cell("B1").Value = title;
        worksheet.Cell("C1").Value = createdBy;
        worksheet.Cell("D1").Value = isCallBack;

        // Add ClosedXML.Extensions in your using declarations

        return wb.Deliver("tickets-" + dateForXcellSheet + ".xlsx");
    }
}

A:

Change your code like below. Use for loop and use proper index to assign values to cell in spreadsheet.
 using (var wb = new XLWorkbook())
        {
            var ticketList = _context.Tickets.ToList();
            var dateForXcellSheet = DateTime.Now;
            var worksheet = wb.Worksheets.Add("Sample Sheet");

            for (int i= 0; i < ticketList.Count(); i++)
            {
                date = ticketList[i].DateCreated.ToString();
                title = ticketList[i].Title;
                createdBy = ticketList[i].CreatedBy;
                isCallBack = ticketList[i].IsCallBack;

            int index =  i + 1;
            worksheet.Cell("A" + index).Value = date;
            worksheet.Cell("B" + index).Value = title;
            worksheet.Cell("C" + index).Value = createdBy;
            worksheet.Cell("D" + index).Value = isCallBack;
            }

            // Add ClosedXML.Extensions in your using declarations

            return wb.Deliver("tickets-" + dateForXcellSheet + ".xlsx");
        }


Q:

VS2012 project x86 target not running on 32 bit Windows XP

I wrote a WPF application using VS2012 on windows 8 computer (x86) and I want it to run on Windows XP x86. When I try to run the program I get error "... is not a valid windows 32 application." I've tried change Platform target to x86 and Any CPU,But have the same error. How can I fix it?

A:

Make sure you target .NET 4.0 (not 4.5). Also make sure both .NET 4.0 Runtime and Reliability Update 2 have been installed on your XP machine (it must be an XP SP3 machine).


Q:

What is the regular expression for the "root" of a website in django?

I'm using django and when users go to www.website.com/ I want to point them to the index view.
Right now I'm doing this:
(r'^$', 'ideas.idea.views.index'),

However, it's not working. I'm assuming my regular expression is wrong. Can anyone help me out? I've looked at python regular expressions but they didn't help me.

A:

What you have should work (it does for me).  Make sure it's in the top urls.py, and it should also be at the top of the list.


Q:

Print output in scripted curl - Python

need some help with this.
Already made an iterative script in Python to execute a curl at the same URL but with multiple PORTS, but I'm strugglin with the desired output.
I'm getting 1 of this for each PORT atm.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<TITLE>Length Required</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii">

Length Required

HTTP Error 411. The request must be chunked or have a content length.

What I need is to clean the output as much as possible as I'm only interested in printing the URL+PORT and HTTP_STATUS_CODE in each execution. Or Something close to this:

This is my current script
import subprocess
import os

port_list = [8080, 8090, 8091, 8092, 8093, 8094, 8095]
for i in port_list:
    i = str(i)
    subprocess.call(["curl", "-s", "-X", "POST", "http://www.isuckatpython/shootmyself.com:", i])

Hope I was clear enough.
Kind regards,
Alem.

A:

You can get the expected output in this way.
import subprocess

port_list = [8080, 8090, 8091, 8092, 8093, 8094, 8095]
host = "http://www.isuckatpython/shootmyself.com:"

for port in port_list:
    result = subprocess.Popen('curl -s -o /dev/null -w "%{http_code}" '+ host + str(port),
                              stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)
    output, error = result.communicate()
    output = output.decode('utf-8')
    if output != '000':
        # if curl:  Failed to connect to <url> port gives "000"
        print("CURL_AT="+host+str(port))
        print("HTTP_STATUS_CODE="+output)
    else:
        print("curl: Failed to connect to {0} port {1}: Connection ".format(host, port))


Q:

Trying to group quantities based off an ID

We have two columns one with ID and another with QTY. And the layout goes along the lines of:
ID        QTY
-------------
123       456
123       634
123      4235
234        67
234       735
234       666

What I am trying to do is add up all the numbers based off the ID so it would look like:
ID        QTY
-------------
123      5325
234      1468

I currently have the following SQL query:
SELECT CLIENT_ID, ID, QTY_ON_HAND,
SUM(QTY_ON_HAND)
FROM
(select CLIENT_ID, ID, QTY_ON_HAND
FROM INVENTORY
WHERE CLIENT_ID = '(CLIENT ID HERE)')
GROUP BY QTY_ON_HAND

It would be appreciated if anyone can tell me simple way on how to do this.

A:

I do not have a test DB at hand, but it should be this:
select
    ID,
    sum(QTY) as TOTAL
from
    YourTableName
group by
    ID;

YourTableName ... name of data table with two columns ID, QTY. Be aware of whole table name, it can be also something like dbo.yourtablename, etc.


Q:

Name value pair list, unable to increment name width number

I'm trying to create this using a for loop.
            slideArr.slide1 = 1;
            slideArr.slide2 = 2;
            slideArr.slide3 = 3;

So I get my total slides, loop over them like so
            for ( index = 0; index < totalSlides.length; ++index )
            {
                slideArr.slide = index;
            }

but I want the name value pair name in the case "slide" to increment as well.
            for ( index = 0; index < totalSlides.length; ++index )
            {
                slideArr.slide1 = 1;
            }

and on the second loop
            for ( index = 0; index < totalSlides.length; ++index )
            {
                slideArr.slide2 = 2;
            }

..etc..
is this possible?
I'm basically creating a name value pair list.

A:

I would highly advise against solutions recommending slideArr["slide"+index]. This is a Code Smell and in this case it suggests you're doing something wrong. Posting your full code would help others give you better, more precise answers.

First, slideArr, to me, implies you're using an Array datatype, but you're treating it more like an Object when you call
slideArr.slide1 = 1;

If it's actually an Array, this would be pretty bad
// Don't use arrays like this !
var slideArr = [];
slideArr.slide1 = 1;

Instead, if you have an Object containing an array of slides, that might be a little better
// Use an object with an array !
var myData = {slides: []};

// Add some slides
myData.slides.push(1);
myData.slides.push(2);
myData.slides.push(3);

Now you have an array of slides within myData
console.log(myData.slides);
// => [1, 2, 3]

You can loop through that quite easily
for (var i=0; i<myData.slides.length; i++) {
  console.log(myData.slides[i]);
}

Output
1
2
3

If you know the slides up front, you can define myData all in one go
var myData = {slides: [1, 2, 3]};

You can skip the .push calls above. Looping stays the same and you'll get identical output.


Q:

Error wrong number of arguments (0 for 1)

I have the form in index.erb.html file. (upload controller).
When i call localhost:3000/upload/ an error appeares wrong number of arguments (0 for 1) error
    <% form_for :picture, :html => { :multipart => true } do |form| %>

    First name::
    <%= form.text_field :first_name, :size => 20 %>

    Last name:
    <%= form.text_field :last_name, :size => 20 %>

    City:
    <%= form.select :city, Picture::CITIES, {}, :onchange => remote_function(:url => {:action => "update_universities"}, :with => "'picture[city]='+value") %>

    <%= render :partial => 'universities' %>

    Photo::
    <%= form.file_field :picture, :size => 20 %>

 <%= submit_tag "Upload" %>
<% end %>

So, I have a render function, because i use AJAX to update the second select field.
   University:
    <%= form.select :university, [] %>

What is the problem with my app? Please help me to fix that!

ArgumentError in Upload#index
Showing
  app/views/upload/_universities.html.erb
  where line #2 raised:
wrong number of arguments (0 for 1)
Extracted source (around line #2):
1: University:
  2: <%= form.select :university, [] %>
Trace of template inclusion:
  app/views/upload/index.html.erb
RAILS_ROOT: /home/user_admin/myapp
  Application Trace | Framework Trace |
  Full Trace
/home/user_admin/myapp/app/views/upload/_universities.html.erb:2:in
  form'
  /home/user_admin/myapp/app/views/upload/_universities.html.erb:2:in
  _run_erb_app47views47upload47_universities46html46erb_locals_object_universities'
  /home/user_admin/myapp/app/views/upload/index.html.erb:15:in
  _run_erb_app47views47upload47index46html46erb' /home/user_admin/myapp/app/views/upload/index.html.erb:1:in
  _run_erb_app47views47upload47index46html46erb'

A:

You need to pass the form variable through to your partial, so:
<%= render :partial => 'universities', :locals => {:form => form } %>

this should make the form object available to your partial.


Q:

Validating textbox when it was shown using jQuery form rules

I have a form which generates textbox when the user selects "others" in dropdown..
Dynamic textbox generation was done and I can able to get the value of "others" textbox.
But my Problem is
1) I want to validate the others textbox when it was shown..
How to do the validation any Suggesstions please..
<form name="f2" id="f2" method="post" action="" enctype="multipart/form-data">
    Type:
    <select name="type"  id="type" onchange='CheckColors(this.value);'>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="others">others</option>
    </select>
    <input type="text" name="others" id="others" style='display:none;'/>
    <input type="submit" name="submit"/>
</form>

//Here is the script to validate the form..I want to validate the the other textbox when only it appears..How to do that?
<script type = "text/javascript">
$(document).ready(function () {
    $("#f2").validate({
        debug: false,
        rules: {
            type: {
                required: true
            },
            others: {
                required: true
            },
            messages: {
                //messages for required
            }
        });
    });
</script>

I tried the above process but it always shows the required filed two times side by side.

A:

Try with this
$(document).ready(function () {
  $("#f2").validate({
    debug: false,
    rules: {
      type: {
        required: true
      },
      messages: {
        //messages for required
      }
    }
  });
});

function CheckColors(value) {
  if(value=='others') {
    $('#others').show().attr('required','required');
  } else {
    $('#others').hide().removeAttr('required');
  }
}

Remove this line from validate function,then the validation works fine
others: {
   required: true
}

DEMO


Q:

PHP site developed using Laravel 5 is not getting rendered after Hosting

I developed a php site using Laravel 5 and tried hosting it in a LAN Server running UBUNTU 14. But when I navigated the page I'm just getting a Blank Page. No errors at all. I inserted a simple echo statement in index.php and I got the relevant echo.

A:

There can be many reason. If you are using Laravel 5.0, you will need at least PHP 5.4. For Laravel 5.1, you will need 5.5.9. But if you have installed PHP using sudo apt-get install php5 you are most likely to have PHP 5.5.9 or later. Because that is the default version for Ubuntu 14.04 LTS. try running php -v from terminal to check the version.
There can also be a Permission issue for storage folder.
From project root folder run following command,
sudo chmod 755 -R storage

Basically, laravel needs write access to storage folder to write a log in storage/log directory or to write a compiled view files in storage/framework/views etc. You can try 755 first. If that does not work try 777.


Q:

Why can not an Explicitly implemented member can not be public?

Possible Duplicate:
Why Explicit Implementation of a Interface can not be public?

I read this Question. Straight from the question
interface IRepository<T>
{
    void AddString();
}

interface IStringRepo : IRepository<string>
{
    List<string> GetStrings();
}

public class BLL : IStringRepo
{
    public List<string> FilterStrings()
    {
        return new List<string>() { "Hello", "World" };
    }

    public List<string> IStringRepo.GetStrings()
    {
        throw new NotImplementedException();
    }

    public void IRepository<string>.AddString()
    {
        throw new NotImplementedException();
    }
}

Why does making an explicitly referenced member public is an Error?

A:

Why does making an explicitly referenced member public is an Error

This is by design, just imagine one of the most popular reasons which forces a developer to implement an interface explicitly: memeber name ambiguity, so you have an existing class which already exposes public member with some name, and you can't change an existing class API since it is used by other systems also you cannot change interface API (member names/signatures), and both class and interface defines a member with the same name, so providing public acces modifier for an interface member does not make sense since member with the same name already declared in a class.
MSDN, 13.4.1 Explicit interface member implementations

It is not possible to access an explicit interface member
  implementation through its fully qualified name in a method
  invocation, property access, or indexer access. An explicit interface
  member implementation can only be accessed through an interface
  instance, and is in that case referenced simply by its member name.
It is a compile-time error for an explicit interface member
  implementation to include access modifiers, and it is a compile-time
  error to include the modifiers abstract, virtual, override, or static.


Q:

How to create text file and insert data to that file on Android

How can I create file.txt and insert data on file with content of some of variable on my code for example : population [][]; on Android, so there will be folder files on our package in file explorer (data/data/ourpackage/files/ourfiles.txt) Thank You

A:

Using this code you can write to a text file in the SDCard.
Along with it, you need to set a permission in the Android Manifest.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

This is the code :
public void generateNoteOnSD(Context context, String sFileName, String sBody) {
    try {
        File root = new File(Environment.getExternalStorageDirectory(), "Notes");
        if (!root.exists()) {
            root.mkdirs();
        }
        File gpxfile = new File(root, sFileName);
        FileWriter writer = new FileWriter(gpxfile);
        writer.append(sBody);
        writer.flush();
        writer.close();
        Toast.makeText(context, "Saved", Toast.LENGTH_SHORT).show();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Before writing files you must also check whether your SDCard is mounted & the external storage state is writable.
Environment.getExternalStorageState()

A:

Check the android documentation. It's in fact not much different than standard java io file handling so you could also check that documentation.
An example from the android documentation:
String FILENAME = "hello_file";
String string = "hello world!";

FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();

A:

If you want to create a file and write and append data to it many times, then use the below code, it will create file if not exits and will append data if it exists.
 SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MM_dd");
        Date now = new Date();
        String fileName = formatter.format(now) + ".txt";//like 2016_01_12.txt

         try
            {
                File root = new File(Environment.getExternalStorageDirectory()+File.separator+"Music_Folder", "Report Files");
                //File root = new File(Environment.getExternalStorageDirectory(), "Notes");
                if (!root.exists())
                {
                    root.mkdirs();
                }
                File gpxfile = new File(root, fileName);

                FileWriter writer = new FileWriter(gpxfile,true);
                writer.append(sBody+"\n\n");
                writer.flush();
                writer.close();
                Toast.makeText(this, "Data has been written to Report File", Toast.LENGTH_SHORT).show();
            }
            catch(IOException e)
            {
                 e.printStackTrace();

            }


Q:

javascript iterate through form elements to find input value

I've been looking through and haven't really found a solution yet, so I ask.
I have a shopping cart that needs to confirm that the item that is being added already exists and asks if user still wants to add.
The code I have tried does find and asks the question, however it still submits and adds the selected item.
// check if item exists
$(".add_to_order").on("click", function() {
    var current_id = $(this).data("id");
    return $(".order_list input").each(function() {
        if ( current_id == $(this).val() ) {
            return confirm('Item exists, still want to add?');
        }
    });
});

PHP (CodeIgniter) / HTML (Bootstrap)
<?php if ($products) {
    foreach($products as $product){ ?>
        <form action="/orders/add_to_order" method="get">
            <button class="add_to_order" type="submit" data-id="<?php echo $product->id; ?>">Add to Cart</button>
        </form>
<?php } } ?>

Cart
<form action="/orders/send" method="post" id="order">
    <?php foreach($order_products as $order_product) { ?>
        <input class="added_product" type="hidden" value="<?php echo $order_product->product_id; ?>" />
    <?php } ?>
    <button type="submit">Order</button>
</form>

I chose to make the product ID hidden.
Thank you.

A:

PROBLEM
AFAIK, jQuery's .each() function doesn't return a value.
When you are doing:
return $(".order_list input").each(function() {
    if ( current_id == $(this).val() ) {
        return confirm('Item exists, still want to add?');
    }
});

the inner return just returns to the .each(), but its value doesn't go to the return.

SOLUTION
I think the easiest way to solve this would be to set a variable confirmed and use it like so:
var confirmed = true;
return $(".order_list input").each(function() {
    if ( current_id == $(this).val() ) {
        confirmed = (!confirmed) ? false : confirm('Item exists, still want to add?');
    }
});
return confirmed;

This will start with confirmed as true, and if a single confirm() is pressed as false (if the user cancels), then confirmed will stay false.


Q:

CAST(NULL AS DATE)

I am trying to create a view in oracle which is already defined in DB2,in the DB2 view all date column having cast function , Below i have created a view by taking one date column from the view. Note:COBDATE column having number datatype as for the design. i am getting ORA-00936:missing expression error.
Create View MYVIEWV1 as (Select
A.COBDATE                   ,
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
 (case when (COBDATE = 0)
  then  CAST(NULL AS DATE)
  else
   date(SUBSTR(COBDATE,1,4) ||
   '-'||SUBSTR(COBDATE,5,2) ||
   '-'||SUBSTR(COBDATE,7,2))
       end )  as    COBDATE2
from MYTBLT1 A;

please suggest how i can convert this to oracle syntax?

A:

The cast isn't the issue, though it isn't really needed. The 'missing expression' error is reported against line 7 column 4, which is the call to the date() function - which doesn't exist in Oracle. It's expecting a date literal to follow the keyword date, not parentheses or function arguments.
You can use the to_date() function instead, with a format model matching the way you're constructing the first argument. You said cobdate is a number but you're treating it as a string so I'll continue to do that implicitly...
create table mytblt1 (cobdate number);
insert into mytblt1 values (20141225);
insert into mytblt1 values (0);

create view myviewv1 as
select cobdate,
  case when cobdate = 0
    then null -- or with unnecessary cast: cast(null as date)
  else
    to_date(substr(cobdate,1,4)
        ||'-'||substr(cobdate,5,2)
        ||'-'||substr(cobdate,7,2),
      'YYYY-MM-DD')
  end as cobdate2
from mytblt1;

select * from myviewv1;

   COBDATE COBDATE2
---------- -------------------
  20141225 2014-12-25 00:00:00
         0

desc myviewv1

Name     Null Type
-------- ---- ------
COBDATE       NUMBER
COBDATE2      DATE

With a cut-down date format model - so you don't have to worry about the - separators - you can simplify it further:
create view myviewv1 as
select cobdate,
  case when cobdate = 0
    then null -- cast(null as date)
  else
    to_date(cobdate, 'YYYYMMDD')
  end as cobdate2
from mytblt1;

Or you can move the case inside the function call:
create view myviewv1 as
select cobdate,
  to_date(case when cobdate = 0 then null else cobdate end, 'YYYYMMDD') as cobdate2
from mytblt1;


Q:

Rspec: before each on js:true specs only

For all my js:true feature specs
e.g.
scenario "test something", js: true do
end

I want to say run some arbitrary code
e.g
visit signin_path

I know I could do within spec_helper.rb
config.before(:each) do
 visit signin_path
end

But I only want to run this for specs with js:true
Is there a way to do this?

A:

Yes, just specify a separate before(:each, js: true) block in your spec_helper.rb
RSpec.configure do |config|
  config.before(:each, js: true)  do
    visit signin_path
  end
end


Q:

Calculate the coordinates with respect to the basis B given the coordenates of that vector with respect to another basis

first time I post. I can't solve an exercise that I know it's easy, It's so frustrating...
First of all:
Consider the basis $B_1 = $ {$u_1, u_2, u_3$} in $\mathbb R^3$.
1) Prove that the set $B_2 = $ {$v_1, v_2, v_3$} given by $v_1 = u_1 - u_2; v_2 = u_2 + u_3; v_3 = u_1 - u_3$ is another basis.
2) (Post title) If the vector $w_1$ has coordinates (2, 1, 1) with respect to the basis $B_1$, calculate the coordinates of $w_1$ with respect to the basis $B_2$.
Well, the answer of the question 1) I think is related with the definition of "basis of $R^3$, thus with the definition of linear independence.
But I can't figure up the answer smoothly.
The part 3) of the exercise is the inverse of 2) and I can solve it without any difficulty. (Or so I think)
Can you help me?
Thanks!

A:

1) If $B_1=\{\mathbf{u}_1,\mathbf{u}_2,\mathbf{u}_3\}$ is a basis for $\mathbb{R}^3$, then that means the equation $\mathbf{0}=c_1\mathbf{u}_1+c_2\mathbf{u}_2+c_3\mathbf{u}_3$ has only the solution $c_1=c_2=c_3=0$.
Now, to show that $B_2=\{\mathbf{v}_1,\mathbf{v}_2,\mathbf{v}_3\}$ is a basis for $\mathbb{R}^3$, we can show that the equation $\mathbf{0}=k_1\mathbf{v}_1+k_2\mathbf{v}_2+k_3\mathbf{u}_3$ has only the trivial solution.
We have
$\mathbf{0}=k_1\mathbf{v}_1+k_2\mathbf{v}_2+k_3\mathbf{k}_3=k_1(\mathbf{u}_1-\mathbf{u}_2)+k_2(\mathbf{u}_2+\mathbf{u}_3)+k_3(\mathbf{u}_1-\mathbf{u}_3)$
$=(k_1+k_3)\mathbf{u}_1+(k_2-k_1)\mathbf{u}_2+(k_2-k_3)\mathbf{u}_3$
Since we know $(k_1+k_3)\mathbf{u}_1+(k_2-k_1)\mathbf{u}_2+(k_2-k_3)\mathbf{u}_3=\mathbf{0}$ has only the trivial solution, we know that $k_1+k_3=k_2-k_1=k_2-k_3=0$ must hold.
Thus, $k_1=-k_3$, $k_2=k_1$, and $k_2=k_3$ must hold.
Since $k_2=k_1$ and $k_2=k_3$, then $k_1=k_3$. But we also have that $k_1=-k_3$. We know that $k_1=k_3=-k_3$ will only hold if $k_3=0$. Then we have $k_1=k_2=k_3$, thus $k_1=k_2=k_3=0$.
Since, this is the only solution that works, that tells us that $B_2=\{\mathbf{v}_1,\mathbf{v}_2,\mathbf{v}_3\}$ is a linearly independent subset of $\mathbb{R}^3$ containing $3$ elements (which implies $\dim B_2 = 3$). Thus, $B_2$ is also a basis for $\mathbb{R}^3$.
2) If $\mathbf{w}_1$ has coordinates $(2,1,1)$ with respect to the basis $B_1$, that means that we can write $\mathbf{w}_1$ as a linear combination of the elements of $B_1$ in exactly one way:
$\mathbf{w}_1=2\mathbf{u}_1+\mathbf{u}_2+\mathbf{u}_3$
One can see by inspection that $u_1=\frac{1}{2}(\mathbf{v}_1+\mathbf{v}_2+\mathbf{v}_3)$
Then from our original equations:
$\mathbf{v}_1=\mathbf{u}_1-\mathbf{u}_2$
$\mathbf{v}_2=\mathbf{u}_2+\mathbf{u}_3$
$\mathbf{v}_3=\mathbf{u}_1-\mathbf{u}_3$
We have $\mathbf{u}_3=\mathbf{u}_1-\mathbf{v}_3=\frac{1}{2}(\mathbf{v}_1+\mathbf{v}_2-\mathbf{v}_3)$
and $\mathbf{u}_2=\mathbf{v}_2-\mathbf{u}_3=\mathbf{v}_2-\frac{1}{2}(\mathbf{v}_1+\mathbf{v}_2-\mathbf{v}_3)=\frac{1}{2}(-\mathbf{v}_1+\mathbf{v}_2+\mathbf{v}_3)$
Then we can substitute:
$\mathbf{w}_1=2(\frac{1}{2}(\mathbf{v}_1+\mathbf{v}_2+\mathbf{v}_3))+(\frac{1}{2}(-\mathbf{v}_1+\mathbf{v}_2+\mathbf{v}_3))+(\frac{1}{2}(\mathbf{v}_1+\mathbf{v}_2-\mathbf{v}_3))=\mathbf{v}_1+2\mathbf{v}_2+\mathbf{v}_3$
Thus, the coordinates with respect to $B_2$ are $(1,2,1)$
(There are various other ways to do this).


Q:

Reading .txt file to list Android / FileNotFound

I'm attempting to read a .txt file and appending it to an ArrayList. It seems to fail at the Scanner line with 'java.io.FileNotFoundException: /raw/words.txt: open failed: (No such file or directory)'. I've tried BufferReader method and changing the location of the file with little success. Why is it not recognizing the file?
public void openFile (){
    File file = new File("raw/words.txt");
    ArrayList<String> names = new ArrayList<String>();
    try{
    Scanner in = new Scanner (file);
    while (in.hasNextLine()){
        names.add(in.nextLine());
    }
    }
    catch (Exception e){
    e.printStackTrace();
    }
    Collections.sort(names);
    for(int i=0; i<names.size(); ++i){
        System.out.println(names.get(i));
    }
}

A:

Yes, you can't specific by just raw/words.txt like that, the android doesn't store path as same as desktop pc
you need to get their resources and read it
for example copy from here
// to call this method
// String answer = readRawTextFile(mContext, R.raw.words);

public static String readRawTextFile(Context ctx, int resId)
     {
          InputStream inputStream = ctx.getResources().openRawResource(resId);

             InputStreamReader inputreader = new InputStreamReader(inputStream);
             BufferedReader buffreader = new BufferedReader(inputreader);
              String line;
              StringBuilder text = new StringBuilder();

              try {
                while (( line = buffreader.readLine()) != null) {
                    text.append(line);
                    text.append('\n');
                  }
            } catch (IOException e) {
                return null;
            }
              return text.toString();
     }


Q:

How shall I understand "." in filename expansion?

In Bash's Manual, for filename expansion:

When a pattern is used for filename expansion, the character . at
  the start of a filename or immediately following a slash must be
  matched explicitly, unless the shell option dotglob is set.
When matching a filename, the slash character must always be matched
  explicitly.
In other cases, the . character is not treated specially.

Can you give some examples to explain the cases in the quote?
How shall I distinguish the usage of . in filename expansion from its unrelated usage of hardlink .?

A:

There is no usage of . in filename expansion. If you use filename expansion, filenames which start with . are usually excluded, unless you explicitly asked for those, using something like .* or .?. / is not a valid character in a filename, so * doesn't match /.
$ touch foo .foo; echo *; echo .*; echo ./*; echo; ./.*
foo
.foo
./foo
./.foo

Note how * and ./* excluded .foo - yet the first echo command had no usage of ., and the third echo command used ./, so the wildcard is separated from the . by a /. To match filenames starting with ., you must explicitly specify the leading . - .*, ./.*. However, in this case the role of . is no different from, say, the role of a in a*.
This exception can be disabled by using shopt -s dotglob.
Since there is no special usage of . in filename expansion, there is nothing to distinguish. The only special characters in filename expansion are *, ?, [...].


Q:

Generate tibbles with different column names with map2()

I have a character vector of names and a list of numeric vectors. I would like to create tibbles with one column each where the column names come from the character vector and the should be populated with the values from the numeric vectors.
Here is a minimal example of what I tried:
names <- c("col1", "col2")

cols <- list(1:10, 11:20)

map2(.x = !!!rlang::syms(names), .y = cols, ~tibble::tibble(.x = .y))

When I run this, I get an invalid argument type error. From what I understand (and what I tried), I cannot simply use names as .x. Then the column names would be .x instead of col1 or col2. By using syms and unquoting the expression I tried to convert the character elements from names into names which I was thinking were needed.
EDIT: Benchmark on suggested solutions:
Both suggested solutions work well and are easy to read. Thus, I conducted a small benchmark to help me choose which solution to accept. The (accepted) solution using !! is faster and a little shorter.
Unit: microseconds
      expr      min        lq      mean    median       uq      max neval
 set_names 1148.635 1163.1985 1210.2218 1168.8840 1201.048 3950.820   100
        !!  701.961  713.5295  729.4239  721.2395  734.779 1102.086   100

A:

map2() is a regular function so does not support !!. Since it is tibble() that does the quoting here, that's where you should unquote:
map2(names, cols, function(n, x) tibble::tibble(!!n := x))

Note that you don't need sym() to unquote names on the LHS because both symbols and strings are supported (this is standard in R, you can always supply names as strings or symbols, e.g. list("str" = 1, sym = 2)).


Q:

just flip effect actual flip should not happend

I have a div that has a background image.  When I click on the div, I  want it to flip and then change the URL of the image to show a different image.  The problem that is happening is the "flipped" image is showing as a mirror image. How can I avoid this?
CSS
.imgnew
{
 -webkit-transform-style:preserve-3d;
 -webkit-transition:all 1.0s linear;
 transform-style:preserve-3d;
 transition:all 1.0s linear

}

.transition
{
 -webkit-transform:rotateY(180deg);
 transform:rotateY(180deg);

}

JavaScript
$('div').add('')

Note:
I have a div element and no other element can be added to the div or wrapped around it.
I am adding these two classes for the flip.

A:

Try something like this
$(".imgnew").on('click', function() {
   $(".imgnew").addClass("transition");
    setTimeout(function(){
       $(".imgnew").removeClass("transition");
    }, 500);
});

That will add the class, and then halfway through the transition, remove it. The effect should not be noticeable, it will just look like a flip, but the resulting div will still be unmirrored.
Here is a simple JSFiddle showing this effect


Q:

.NET CQRS Frameworks nCQRS vs Lokad.CQRS

For the last couple of weeks I've been reading up and watching any resources I can find on CQRS. I really like the concept and am keen to start delving deeper. I have only found 2 major .NET frameworks for CQRS and I am trying to evaluate the differences between them.
I am looking to implement CQRS on a noSql db, most likely RavenDB.
Lokad seems very focused on windows Azure, not sure if it supports Raven. It has extensive documentation but not a lot of activity in the community. nCQRS has a lot of activety and supports Raven.
I was wondering if anyone has any experience working with these two frameworks and what the major differences are between them.

A:

Besides "CQRS" solutions, what's often applied is an ESB (Enterprise Service Bus). CQRS is all around messaging and these types of frameworks exist around messaging.

MassTransit http://masstransit-project.com/, https://github.com/MassTransit/MassTransit
NServiceBus http://www.nservicebus.com/, https://github.com/NServiceBus/NServiceBus
Eh, BizTalk, sorta.

MassTransit is Apache2 licensed. NServiceBus is LGPL/Commercial for the latest releases, I think you can get older under a more permissive license. BizTalk isn't a great solution and it's whatever Microsoft charges for it.
Some of the info from http://cqrsinfo.com/documents/cqrs-introduction/ might be of use in developing solutions around this as well.
http://twitter.com/#!/ackenpacken has a in process message dispatcher he uses. I'm not sure if it's out there anywhere but I've seen it :) For fun his latest example I saw had the consumers implementing ICanHaz<T>.


Q:

Mingw x64 Windows: plugin needed to handle lto object

When I'm trying to compile my project with 64-bit mingw (x86_64-5.1.0-posix-seh-rt_v4-rev0) I got messages:
BFD: my/project/dir/filename.cpp.obj: plugin needed to handle lto object

for each source file. Yet when I compile with 32-bit mingw(i686-5.1.0-posix-dwarf-rt_v4-rev0), everething is OK.
My flags are:
CXX_FLAGS "-fno-exceptions -fno-rtti -std=c++14 -O3 -fstrict-aliasing -flto -fomit-frame-pointer -march=native -ffast-math -funroll-loops"
LINKER_FLAGS "-O1 -s"

I tried to add -fuse-linker-plugin and -fno-use-linker-plugin, but it didn't help.
My OS is 64-bit Windows 10. I use CLion and CMake if it matters, though it shouldn't.
How can I fix it?

A:

Put the LTO plugin into the bfd-plugins directory:
mkdir mingw64\lib\bfd-plugins
cp mingw64\libexec\gcc\x86_64-w64-mingw32\5.1.0\liblto_plugin-0.dll mingw64\lib\bfd-plugins\liblto_plugin-0.dll


Q:

2 params in C# not compiling

I'm trying to do this:
public void CustomMethod(params int[] number,params string[] names)
{
...
}

If i delete one of them , there is no problems , any idea of why i can't do this?
I have tried putting a normal parametre in the middle of both.

A:

Only the last parameter can have params. See the documentation.

No additional parameters are permitted after the params keyword in a method declaration, and only one params keyword is permitted in a method declaration.

The reason is that allowing multiple params would give ambiguity. For example, what would this mean?
public void CustomMethod(params int[] foo, params int[] bar)
{
    ...
}

// ...

CustomMethod(1, 2);

A:

This is simply not supported. The compiler can't know when one parameter list ends and the next begins.


Q:

magento product list.phtml

If I click on a product from my product overview on the left side, the shop does not load with the list.phtml. As soon as I swap view to grid or list, it swaps to the list.phtml file and everything is fine. But as I said, if I click on the products on the sidebar, it doesnt work (it's not even affected by list.phtml at all). I removed all the code inside it and it still showed (a bit different, that's why I want to change it) the products, but as soon as I swapped mode, everything disappeared -- as it should. Do you know where I can change that?
Thank you.

A:

It should use list.phtml file. In that file it is defined for both list mode and grid mode.
 <?php echo $this->getToolbarHtml() ?>
    <?php // List mode ?>
    <?php if($this->getMode()!='grid'): ?>
    <?php $_iterator = 0; ?>

And
<?php else: ?>
<?php // Grid Mode ?>
<?php $_collectionSize = $_productCollection->count() ?>

You can see something like above code in your list.phtml file,one is for list mode and another for grid mode. This is the default case unless you haven't changed the layout or template code.
If you want to know the file location than you can always enable template path hint. If you don't know how to do that you can follow this.
After knowing from which file it is rendering you can fix it.
Hope this will help.


Q:

scala how to access to element in tuple in list

I have a list where two element are tuple.
How can I access to the elements of the tuple?
package prova_package

object prova_worksheet {
  println("Welcome to the Scala worksheet")       //> Welcome to the Scala worksheet
  var l = List((1,'a'),(2,'b'),3,4)               //> l  : List[Any] = List((1,a), (2,b), 3, 4)
    var u = (1,'a')                           //> u  : (Int, Char) = (1,a)
    u._1                                      //> res0: Int = 1
 //l(1)._1  //this does not work. Why?  How can I access to the value 'b' ?

}

I want the value 'b'

A:

Scala is a static language.
Your code does not work because you've mixed different types for elements. That's why the compiler infers a type List[Any] for your list. Your code would have worked fine if the list had a type List[(Int, Char)].
While there is a way to work around your issue using casting I want to outline boldly that it is unidiomatic:
l(1).asInstanceOf[(Int, Char)]._1

An idiomatic approach is to have monomorphic lists, i.e., the ones containing elements of the same type.


Q:

Reflector will not be free anymore. Any alternatives?

Possible Duplicate:
Open Source Alternatives to Reflector?

Since March, this tool is no longer free even for all its old versions. Any alternatives?

A:

Check ILSpy, Development started after Red Gate announced that the free version of .NET Reflector would cease to exist by end of February 2011.
Also read their blog posts here

A:

The last thing i heard was that JetBrains will ship a disassembler with resharper and also as standalone.
[Edit]
See http://blogs.jetbrains.com/dotnet/tag/resharper-6/


Q:

It's still crashing, where am I going wrong?

(Edited to add this bit) I'm writing a program where it reads in a string of characters, then counts the frequency of each letter in the string and outputs the number of times each letter or non-letter occurs.
I was using tolower() but this was creating a problem.
I've changed it so I'm now using a loop to lower the case. Unfortunately the program is still crashing on me and I can't spot the problem.
I've run through each function to make sure I don't have anything loose. I've got the new line element being removed but when I run it through, I type in something as simple as "hello" and it crashes out.
#include <stdio.h>
#include <string.h>

void read(char letterfreq[], int STRSIZE)
{
    printf("The capacity of the string array is %d\n", STRSIZE-1);

    printf("Please enter your string:\n");

    letterfreq[strlen(letterfreq) - 1] = '\0';

    return;
}

void lowerCase(char letterfreq[], int STRSIZE)
{
    }

}

void countFreq(int counter[], int COUNT, char letterfreq[], int STRSIZE)
{
    int c = 0;
    int i;

    for(i = 0; i < STRSIZE; i++)

            }
            else
                if((letterfreq[i] < 'a') || (letterfreq[i] > 'z'))
                {
                    counter[COUNT-1]++;
                }
        }
    }

    return;
}

void printFreq(int counter[], int COUNT)
{
    int c;

    printf("Here is the letter frequency of your string:\n");

    for(c = 0; c < COUNT; c++)

    printf("There were also %d special characters in the string.\n", counter[26]);

    return;
}

char promptReset(char reset)
{
    printf("Would you like to calculate the letter frequency of another string? (Y/N)\n");
    scanf("%c%*c", &reset);

    do
    {
        readString(letterfreq, STRSIZE);

        lowerCase(letterfreq, STRSIZE);

        countFreq(counter, COUNT, letterfreq, STRSIZE);

        printFreq(counter, COUNT);

        reset = promptReset(reset);

    }while(reset == 'y' || 'Y');

    return(0);
}

A:

Here(in function lowerCase):
letterfreq[i] = letterfreq[i] - 32;

you need to add 32 to convert the character into uppercase. Look at the ASCII table to know why.
Here(in function countFreq):
for(i = 0; i < STRSIZE; i++)
{
    while(letterfreq[i] != '\0')
    {
        if(letterfreq[i] >= 'a' && letterfreq[i] <= 'z')
        {
            counter[c]++;
            c++;
        }
        else
            if((letterfreq[i] < 'a') || (letterfreq[i] > 'z'))
            {
                counter[COUNT-1]++;
            }
    }
}

the for loop doesn't make any sense. Remove it. Then, the while loop never ends as you don't increment i. You need i++; at the end of the while loop.
Here:
        if(letterfreq[i] >= 'a' && letterfreq[i] <= 'z')
        {
            counter[c]++;
            c++;
        }

counter[c]++ won't count the frequency of each character. You need
counter[letterfreq[i]-'a']++;

for that. c is not needed. Remove it from the function.

Also, as @iharob has mentioned in a comment,
 }while(reset == 'y' || 'Y');

should be
 }while(reset == 'y' || reset == 'Y');

Fixed program:
#include <stdio.h>
#include <string.h>

const int COUNT = 27;
const int STRSIZE = 100;

void readString(char letterfreq[], int STRSIZE)
{
    printf("The capacity of the string array is %d\n", STRSIZE-1);

    printf("Please enter your string:\n");
    fgets(letterfreq, STRSIZE, stdin);

    letterfreq[strlen(letterfreq) - 1] = '\0';

    //return; Not required
}

void lowerCase(char letterfreq[], int STRSIZE)
{
    int i;

    for(i = 0; i < STRSIZE; i++)
    {
        if(letterfreq[i] >= 'A' && letterfreq[i] <= 'Z')
        {
            letterfreq[i] = letterfreq[i] + 32; //Add instead of subtract
        }
        //i++; You already increment i from the loop
    }

}

void countFreq(int counter[], int COUNT, char letterfreq[], int STRSIZE)
{
    int i=0; // You forgot to initialize i with 0

    while(letterfreq[i] != '\0')
    {
        if(letterfreq[i] >= 'a' && letterfreq[i] <= 'z')
        {
            counter[letterfreq[i]-'a']++;
        }
        else if((letterfreq[i] < 'a') || (letterfreq[i] > 'z')) //is always true; Use `else`
        {
            counter[COUNT-1]++;
        }

        i++; //You forgot this
    }

    //return; Not required
}

void printFreq(int counter[], int COUNT)
{
    int c;

    printf("Here is the letter frequency of your string:\n");

    for(c = 0; c < COUNT-1; c++) //See change here too
    {
        printf("%c \t %d \n", c + 'a', counter[c]);
    }

    printf("There were also %d special characters in the string.\n", counter[26]);

    //return; Not required
}

char promptReset(char reset)
{
    printf("Would you like to calculate the letter frequency of another string? (Y/N)\n");
    scanf("%c%*c", &reset);

    return(reset);
}

int main()
{
    char letterfreq[STRSIZE];
    char reset = '\0'; //Always initialize variables to prevent unexpected behavior
    int counter[COUNT];

    printf("Welcome to the Letter Frequency program\n");

    do
    {
        memset(counter,0,sizeof(counter)); //Initializing counter with zeros
        memset(letterfreq,'\0',sizeof(letterfreq)); //Do the same for letterfreq

        readString(letterfreq, STRSIZE);

        lowerCase(letterfreq, STRSIZE);

        countFreq(counter, COUNT, letterfreq, STRSIZE);

        printFreq(counter, COUNT);

        reset = promptReset(reset);

    }while(reset == 'y' || reset == 'Y'); //Changed

    return(0);
}


Q:

How do I use backgroundworker in this instance?

I've a question on how the backgroundworker would actually work. I'm not too sure how it would work with different methods.
So for example I have the following code (adapted from http://broadcast.oreilly.com/2010/06/understanding-c-using-backgrou.html for illustration purposes):
private void getDateTime()
{
    DateTime startTime = DateTime.Now;
    double value = Math.E;
    while (DateTime.Now < startTime.AddMilliseconds(100))
    {
      value /= Math.PI;
      value *= Math.Sqrt(2);
    }
}

private backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    for(int i=0; i <= 100; i++)
    {
        getDateTime();
        backgroundWorker1.ReportProgress(i);
    }
}

This would continually calculate the DateTime using the backgroundworker thread. Now I'm assuming that the for-loop within the backgroundworker's DoWork method would run the calculation, report the progress, and then reiterate the loop (please do correct me if I've misunderstood).
Now assuming I have another method, which parses a (presumably large) DataTable and returns another DataTable, using it in the backgroundworker would mean I'd be parsing the DataTable over and over (theoretically. again, correct me if I'm wrong)? If this is how the program would flow, is there a more efficient method to achieve the DataTable parsing without having to reiterate the loop, but still being able to use backgroundworker?
This is intended for a Windows Form, and the UI tends to freeze up when I parse the DataTable(s). I've heard that backgroundworker could help me get around the freezing of the UI, but I find it highly inefficient to have to re-parse the entire DataTable over, and over. However I'm not sure of any other way I can report progress without a for-loop either.
EDIT:
I've figured out a temporary solution. It works, but I still have no way of reporting progress.
    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        int rows = (int)e.Argument;
        int count = 0;
        t3 = runComparison();
        for (int i = 0; i <= rows; i++)
        {
            count++;
            int current = count / rows;
            backgroundWorker1.ReportProgress(current * 100);
        }
        e.Result = t3;
    }

    private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        progressBar1.Value = e.ProgressPercentage;
    }

    private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        if (e.Error != null)
        {
            MessageBox.Show("An unexpected error has occurred. Please try again later.", "ERROR!", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        else
        {
            dataGridView1.DataSource = e.Result;
        }
    }

I'm aware my for-loop doesn't do anything. However, the "runComparison" already consumes a lot of time. As such, progress doesn't get reported until an entire run-through if it's in the for-loop. Alternatively, maybe I could use a label or messagebox instead of the progress bar. Not too sure how I'm supposed to achieve this.

A:

I've come up with a rather inelegant solution. But it satisfies the requirement for user-friendliness so... Whatever works :P
Thanks for all the feedback, I appreciate it.
Anyway, here's the code:
    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        backgroundWorker1.ReportProgress(1); //to invoke ProgressChanged
        t3 = runComparison(); //run intensive method
        e.Result = t3; //return DataTable
    }

    private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        progressBar1.Visible = true; //display a label
        textBoxProgress.Visible = true; //display the progress bar
        //change the progress bar style
        //the Marquee style is constantly running, so it could show users the process is working
        //not too sure how to explain it, you'll have to try it out.
        progressBar1.Style = ProgressBarStyle.Marquee;
    }

    private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        if (e.Error != null)
        {
            MessageBox.Show("An unexpected error has occurred. Please try again later.", "ERROR!", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        else
        {
            //reset the display and update the DataGridView
            progressBar1.Visible = false;
            textBoxProgress.Visible = false;
            progressBar1.Style = ProgressBarStyle.Blocks;
            dataGridView1.DataSource = e.Result;
        }
    }


Q:

Anchor link not working when clicked

Sooo.. I've got this navigation on the frontpage. I'm trying make it link to an anchor on another page.
www.oddfuse.com
This is the anchor link:

As you can see, it does not redirect to the specified page.
However it does work when typed directly into the address bar:
www.oddfuse.com/page#skills
This also works:

But with the hash, I get no response whatsoever.
Any ideas on how I fix this?

A:

Okay, so it turned out that it was the jQuery Mobile somehow messing with the anchor tags.
I needed to put data-ajax="false" in the link, and it now works perfectly. TMYK.
Found the solution here


Q:

Online form/survey creation service

Looking for a simple drag/drop interface to create an online questionnaire. Able to spend up to $200(USD) per month.
Requirements:

Versioned. Or at least allow respondent can make changes to their previous answers
File upload
Authenticated Respondents (must create account, or be invited to
respond i.e. private)
Simple logic - show question if respondent gives selected answer
Export data
Branding - logo and colors

Nice to Have:

Admin only view. Admin can make notes on responses that are not visible to respondent - It would be nice to have 2 views of the data, one public and the other admin only.
Reports. Don't want the data to be cumulative - each respondent should have their own report.

So far I am checking out these services (in order of best match):

http://www.wufoo.com/features/
http://www.orbeon.com/
Google Forms

None of them seem to meet all the requirements, so I am looking for recommendations here

A:

Survey Monkey may be a good option for you. It does not hit all of your requirements, see below.  Feature/Pricing Chart

Versioned. Or at least allow respondent can make changes to their previous answers  I don't know that it can do this once the survey has been submitted, most surveys are not accessible once they have been submitted by design.
File upload  Does not specifically mention this, and I have not used the paid features to test this.
Authenticated Respondents (must create account, or be invited to respond i.e. private)  Yes
Simple logic - show question if respondent gives selected answer  Yes, more advanced logic available as well
Export data  Yes
Branding - logo and colors Yes


Q:

Vertical Axis labels set to middle in Google Visualization Chart

I am using Google's visualization bubble chart. I need to align the labels in the vertical axis to middle. See the image below please. Something like this. These month names needs to be in between the major gridlines.

Here is the options I added for this bubble chart, but it does show next to axis line only.
var options = {
        sizeAxis: {
            maxSize: 7,
            minSize: 1
        },
        animation: {
            duration: 1500,
            easing: 'in',
            startup: true
        },

        fontSize: 10,
        legend: 'none',
        height: 230,
        chartArea: { left: "20%", right: 0, top: 0, width: "70%", height: "200px" },

        bubble: { stroke: '#ffca18', opacity: 1 },
        colors: ['#ffca18', '#ffca18'],
        tooltip: {
            trigger: 'none'
        },
        hAxis: {
            ticks: [
                { v: 2015, f: '2015' },
                { v: 2016, f: '2016' },
                { v: 2017, f: '2017' },
                { v: 2018, f: '2018' },
                { v: 2019, f: '2019' },
                { v: 2019, f: '2020' }
            ],

            gridlines: { color: '#dedede' },
            minorGridlines: { color: '#f7f7f7', count: 3 },
            textStyle: { color: '#5f5f5f' }
        },
        vAxis: {
            ticks: [
                { v: 1, f: 'May' },
                { v: 2, f: 'April' },
                { v: 3, f: 'March' },
                { v: 4, f: 'February' },
                { v: 5, f: 'January' }
            ],
            gridlines: { color: '#dedede' },
            textStyle: { color: '#5f5f5f' },
            viewWindowMode: 'explicit',
            viewWindow: {
                min: 1,
                max: 7
            }
        }
    };

A:

we can move the labels manually, on the chart's 'ready' event,
or in this case, the 'animationfinish' event, or both.
the chart has a method for getChartLayoutInterface()
this returns an object we can use to get the placement of various chart elements.
we can get the placement of the gridlines,
and move the labels in between.
function moveYAxisLabels() {
  var chartLayout = chart.getChartLayoutInterface();
  var labels = chart.getContainer().getElementsByTagName('text');
  var labelIndex = -1;
  Array.prototype.forEach.call(labels, function(label) {
    if (label.getAttribute('text-anchor') === 'end') {
      labelIndex++;
      labelHeight = chartLayout.getBoundingBox('vAxis#0#label#' + labelIndex).height;
      labelBottom = chartLayout.getBoundingBox('vAxis#0#gridline#' + labelIndex).top;
      labelTop = chartLayout.getBoundingBox('vAxis#0#gridline#' + (labelIndex + 1)).top;
      label.setAttribute('y', labelBottom - ((labelBottom - labelTop) / 2) + Math.floor(labelHeight / 2));
    }
  });
}

see following working snippet...

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {
  var data = new google.visualization.DataTable({
    "cols": [
      {"label": "id", "type": "string"},
      {"label": "x", "type": "number"},
      {"label": "y", "type": "number"}
    ],
    "rows": [
      {"c":[{"v": ""}, {"v": 2015}, {"v": 1}]},
      {"c":[{"v": ""}, {"v": 2016}, {"v": 2}]},
      {"c":[{"v": ""}, {"v": 2017}, {"v": 3}]},
      {"c":[{"v": ""}, {"v": 2018}, {"v": 4}]},
      {"c":[{"v": ""}, {"v": 2019}, {"v": 5}]},
      {"c":[{"v": ""}, {"v": 2020}, {"v": 6}]}
    ]
  });

  var chart = new google.visualization.BubbleChart(document.getElementById('chart_div'));

  google.visualization.events.addListener(chart, 'ready', moveYAxisLabels);
  google.visualization.events.addListener(chart, 'animationfinish', moveYAxisLabels);

  function moveYAxisLabels() {
    var chartLayout = chart.getChartLayoutInterface();
    var labels = chart.getContainer().getElementsByTagName('text');
    var labelIndex = -1;
    Array.prototype.forEach.call(labels, function(label) {
      if (label.getAttribute('text-anchor') === 'end') {
        labelIndex++;
        labelHeight = chartLayout.getBoundingBox('vAxis#0#label#' + labelIndex).height;
        labelBottom = chartLayout.getBoundingBox('vAxis#0#gridline#' + labelIndex).top;
        labelTop = chartLayout.getBoundingBox('vAxis#0#gridline#' + (labelIndex + 1)).top;
        label.setAttribute('y', labelBottom - ((labelBottom - labelTop) / 2) + Math.floor(labelHeight / 2));
      }
    });
  }

  var options = {
    sizeAxis: {
      maxSize: 7,
      minSize: 1
    },
    animation: {
      duration: 1500,
      easing: 'in',
      startup: true
    },
    fontSize: 10,
    legend: 'none',
    height: 230,
    chartArea: {
      bottom: 48,
      left: 200,
      right: 18,
      top: 18,
      width: '100%',
      height: '100%'
    },
    bubble: { stroke: '#ffca18', opacity: 1 },
    colors: ['#ffca18', '#ffca18'],
    tooltip: {
      trigger: 'none'
    },
    hAxis: {
      ticks: [
        { v: 2015, f: '2015' },
        { v: 2016, f: '2016' },
        { v: 2017, f: '2017' },
        { v: 2018, f: '2018' },
        { v: 2019, f: '2019' },
        { v: 2020, f: '2020' }
      ],
      gridlines: { color: '#dedede' },
      minorGridlines: { color: '#f7f7f7', count: 3 },
      textStyle: { color: '#5f5f5f' }
    },
    vAxis: {
      ticks: [
        { v: 1, f: 'JUNE' },
        { v: 2, f: 'MAY' },
        { v: 3, f: 'APRIL' },
        { v: 4, f: 'MARCH' },
        { v: 5, f: 'FEBRUARY' },
        { v: 6, f: 'JANUARY' },
        { v: 7, f: '' }
      ],
      gridlines: { color: '#dedede' },
      textStyle: { color: '#5f5f5f' },
      viewWindowMode: 'explicit',
      viewWindow: {
        min: 1,
        max: 7
      }
    }
  };

  chart.draw(data, options);
});

the only issue here is the animation,
the chart will move the labels on 'ready',
then we move them back on 'animationfinish',
so they appear to jump.
you may re-think using animation...


Q:

Is Stripe Checkout leaking memory?

The issue I'm seeing is that when you load Stripe Checkout into a page using their canonical "Custom" guide, configure it, and then open and close it a few times, the browser memory usage continually jumps. It sometimes, sorta gets released a little, but the residual always grows. And on a long lived page/SPA, eventually things crawl.

Start Google Chrome with --enable-precise-memory-info flag (issue happens with or without this flag)
Copy the "Custom" example on their site: https://stripe.com/docs/checkout#integration-custom (or use your own setup, the results are the same).
Click the 'Purchase' button (or trigger your stripeInstance.open(cfg)), fiddle with the popup, close.
Repeat step 3, watch memory gradually

You can watch memory with memory-stats.js or just by running in (Chrome) console:
performance.memory.usedJSHeapSize

I'm convinced this has to be "me" and not Stripe. No way they'd leak so bad on open and close events right?

Edit: Here's a JS fiddle that literally copies their demo code: https://jsfiddle.net/p1Lfuewt/
And a 5 second interval screen shot of memory with basically just opening and closing their widget by clicking "purchase" (no idea what that promise error is, that's them):

A:

Short answer, yes.
The longer answer is, it sure seems like it. The attached JSFiddle example replicates the Stripe canonical docs, and it's trivial to replicate the issue of memory blowing out on the simple act of opening and closing Stripe's widget.
handler.open({
  name: 'Stripe.com',
  description: '2 widgets',
  zipCode: true,
  amount: 2000
})
// Repeat for

A (terrible) workaround we implemented was tracking the number of opens+closes events and forcing a hard reload after X events for edge cases reaching those levels.


Q:

Performance: better to inizialize variable or just fill it?

Let's say i have a function that is called 10 times a second, something like:
void RxData(System::Byte *Data){}

in this function i want to fill a struct with *Data, where the struct is like:
Struct datastr{
float first;
float second;
}

in term of performances and memory use is better to declare a extern variable datastr str1 and then doing:
void RxData(System::Byte *Data){str1=*reinterpret_cast<datastr*>(Data);}

or reinizializing every time the struct, like:
void RxData(System::Byte *Data){datastr str1; str1=*reinterpret_cast<datastr*>(Data);}

can someone explain what are the differencies in term of memory management? i tend to think that the second option is more "clean" but i cannot realy argue why.

A:

In terms of memory management, the data will obviously be located in different places in memory. A global variable is placed in a static segment, while a local variable lives on the stack. Is it created every time? Yes. Does it affect performance? It depends. If datastr really looks like what you show here, then no.
It might have a slightly better performance even, because is very likely to be present in cache at the moment your function executes. A global variable might me there too, probably will, but its in a different memory location, so could mean the prefetcher will have more work to do.
Option 2 is clearly better in terms of style. Reader will have everything at hand while seeing the function and won't have to jump around to decipher the data flow.


Q:

What is the scancode of "Pause/Break" key?

I download "SharpKeys.exe" from here. It works well. But I want to change "Pause/Break" to another, this app cannot recognize this key correctly. Does any one know the scancode? Thx

A:

Pause is a very special non-typematic key with an unusual scan code (E1 1D 45 E1 9D C5). This is too long to be remapped using SharpKeys (or any program that uses the registry to do scan code remappings, since this feature is limited to 2-byte scancodes). If you try to remap it, you'll get only the first two bytes, and end up remapping the Num Lock key instead. This breaks in all sorts of hilarious ways.
You will need to use another program to do the remapping, perhaps something like AutoHotKey. But I'm not sure this will actually work, given how special this key is.
It is not clear why a programmer would ever want to remap Pause/Break. This is a very useful key, one that is often painfully missing from laptop keyboards where your only option is to remap another key to Ctrl+Break (scan code E0 46). This gives you back at least part of the function of a real Pause/Break key.


Q:

How can we encourage more discussion when voting to close, or why is it not happening already?

I feel like I've become more aware of a trend, in that it seems that when a question ends up in the review queue, it tends to snowball into getting closed regardless of what editing efforts are made to salvage the post.
The most recent example I can find of this is New friend put us in awkward position. I originally had voted to close, but saw that the OP had provided us with her desired course of action in the comments. After editing this in, I retracted my close vote, leaving the total close votes at 2. Since these edits there has been no additional feedback on the post, but there are still close votes coming in.
My proposition is a curiosity in wondering if there's anything we can do to encourage individuals who are still casting close votes to at least leave reason for why they're doing so.  If nothing else, can we at least have a discussion or some acknowledgement of this topic, and maybe that could even help encourage more feedback on posts that are being voted closed?
My fear is that an eagerness to participate in the review queue is leading to hurried votes, either not voting appropriately or not having/taking the time to provide feedback to make the post suitable for IPS.  If we want to grow, either of these things could become problematic (as it discourages new users).

A:

You are bringing two separate issues:

How to get users to communicate to the OP what is wrong with the question and if possible how to fix the question
Getting users to retract close votes after the question is edited

As long as new close votes aren't cast there isn't much problem with close votes aging out instead of being retracted. Since people don't get notified when questions they've voted to close get edited they'd have to keep revisiting questions to retract votes after edits have been made. I don't remember the exact number but after enough people vote keep open the question gets removed from the review queue. Even if enough votes are cast to close the question after it's been edited, you can just nominate the question for reopening. The turn around on reopening questions on this site isn't that long so I don't really see this as being much of a problem.
To get people to leave meaningful messages when voting to close questions you need to change the culture of the site. You do this by setting a good example and encouraging other users to do so as well. There isn't a requirement of posting a comment when you VTC and I don't think that adding such a requirement would work out well.


Q:

Json empty return

$alfa = file_get_contents("http://api.steampowered.com/ISteamUserStats   /GetUserStatsForGame/v0002/?appid=730&key=$key&steamid=$steamid");
$beta =  json_decode($alfa);

Sometimes, $steamid (actualy the user with that steamid) don't have that Game (710) and array it's empty ... and i don't know how to make a verification if that array it's empty or not...
You can check this with $steamid = 76561198010791116 and key from here http://steamcommunity.com/dev/apikey
What's the function for this ?

A:

Give the empty() function a try: http://php.net/manual/function.empty.php
if(empty($beta)) {
   // array $beta is empty
}


Q:

Preventing duplicate entries in ListBox

I got problem here with my C# code..
What I want to do with this code is, that when I type something from textbox with the same symbols (the same name), it shows, that I can't add it in the listbox two or more times.
So I made this code:
void Btn_addClick(object sender, EventArgs e)
{
    string thelist = listBox1.Text;
    string text = textBox1.Text;

    if(text == thelist)
    {
        MessageBox.Show("This name already exists!");
    }
    else
    {
        listBox1.Items.Add(textBox1.Text);
        textBox1.Text = "";
    }
}

But the problem is, that it shows the MessageBox only if I select the name from the list and compare it from text box. If I don't select anything or other word, it adds the same word without telling that it already exists.

A:

You are trying to compare your TextBox.Text to the entire ListBox.  You probably want to find out if the ListBox contains the text you are entering.
The following will achieve the results you want very easily:
void Btn_addClick(object sender, EventArgs e)
{
    if(listBox1.Items.Contains(textBox1.Text))
    {
        MessageBox.Show("This name already exists!");
    }
    else
    {
        listBox1.Items.Add(textBox1.Text);
        textBox1.Text = "";
    }
}


Q:

Codeigniter - reverse data in table

I'm look for a way to display data in reverse order using the table library along with pagination in Codeigniter.  From
public function pagination(){

    $this->load->library("pagination");
    $this->load->library("table");

    $this->table->set_heading("ID", "Name", "Address");

    $config["base_url"] = site_url('site/pagination');
    $config["total_rows"] = $this->db->get("mail")->num_rows();
    $config["per_page"] = 10;
    $config["num_links"] = 10;
    $config['page_query_string'] = TRUE;

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

    $data["records"] = $this->db->get("mail", $config["per_page"], $this->input->get('per_page', TRUE));
    $data['pagination'] = $this->pagination->create_links();

    $this->load->view("site_header");
    $this->load->view("site_nav");
    $this->load->view("content_about", $data);
    $this->load->view("site_footer");

}

The table is working just fine but i can't figure out a way to display the data in reverse order. I would like to make the table start with the latest entries (ID, Name, Address) from the database and not the first.
I suppose their i something wrong with how i query the database:
$data["records"] = $this->db->get("mail", $config["per_page"], $this->input->get('per_page', TRUE));

A:

Change :
$data["records"] = $this->db->get("mail", $config["per_page"], $this->input->get('per_page', TRUE));

to :
$data["records"] = $this->db->select("ID, Name, Address")->from("mail")->order_by("ID DESC")->limit($config["per_page"], $offset)->result_array();


Q:

With jfeinstein10's slidingmenu,how to create slide up menu

I would like to use the sliding menu library to create a slide up menu which shows up in the bottom of the screen as you pull the bottom title bar up. Something like this..

I am new to Android. Any idea how I could reuse the library to do this? Which class/function should be modified?
Any help is appreciated.

A:

I believe modifying jfeinstein10's lib might take some time.
Consider the following well documented lib that fits your needs:
Android Sliding Up Panel


Q:

React how to update another component's state?

I am pretty new to react, trying to make some components work. I have
    ObjectA:React.createClass({
        propTypes: {
           ...

        },

        getInitialState: function() {
            return {
                myState: null
            }
        },

        updateMyState: function(value) {
           this.setState({
               myState: value
           })
        }

        render: function() {
            return (
'hello' +{this.state.myState}
);
          }
    });

    ObjectB:React.createClass({
            propTypes: {
               ...

            },

            render: function() {
                return (
<ObjectA / >

);
            }
        });

I'd like to update ObjectA's state from ObjectB. How could I in ObjectB call ObjectA's updateMyState method?
Thanks!

A:

The basic idea of React is the unidirectional data flow. That means that data is only shared downwards from an ancestor component to its children via the child's properties. We leave Flux like architectures and event emitters out of the equation for this simple example as it's not necessary at all.
The ONLY way then to change a component's state from the outside is changing the props it receives in the parent's render method. so myState would actually live in ObjectB and be given to ObjectA as property. In your example that would look like this:
ObjectA:React.createClass({
    propTypes: {
       ...

    },

    render: function() {
        return (
'hello' +{ this.props.name }
);
      }
});

ObjectB:React.createClass({
    propTypes: {
       ...

    },

    getInitialState: function() {
        return {
            name: null
        }
    },

    onNameChange: function(newName) {
        this.setState({ name: newName })
    },

    render: function() {
        return (

                <ObjectA name={ this.state.name } />

        );
    }
});


Q:

Stripping Left and Right of character

What would be the best way to strip left and right of characters in php? I have it stripping right but cant figure out left. I tried ltrim but it doesnt seem to work well.
$rawsubject = 'RE: [#4152] - Registration Issues';
$casenumber_param="]";
$casenumber_strip = strpos($rawsubject,$casenumber_param);
$casenumber = substr($rawsubject,0,$casenumber_strip);

output currently is: RE: [#4152
I need to strip everything left of [# so all I am left with is 4152.

A:

There are a few ways you could do this, but it's probably best if you go with a regular expression. This one behaves exactly like your current code: find the closing square bracket and isolate all consecutive digits that come just before it.
if (preg_match('/\d+(?=\])/', $rawsubject, $matches)) {
    $casenumber = $matches[0];
}

It's very probable that you would prefer something more direct, such as "grab the digits between the square brackets":
if (preg_match('/\[#(\d+)\]/', $rawsubject, $matches)) {
    $casenumber = $matches[1];
}

See it in action.


Q:

#1093 - You can't specify target table 'windUpdates' for update in FROM clause

I'm trying to delete the most lower 60 rows but its not working.
I tried some other posts in stackoverflow but non of them worked for me.
DELETE FROM windUpdates
WHERE INDEX <= (
                  ( SELECT MAX(  INDEX )  FROM windUpdates )  - 60
               )

Thanks.

A:

you need to create temporary table for the result of your subquery,
DELETE FROM tablename
WHERE `Index` NOT IN
(
  SELECT `Index`
  FROM
    (
      SELECT `Index`
      FROM tablename
      ORDER BY `Index` DESC
      LIMIT 60
    ) x
)

PS: Be sure to backup your database first.