Q:

Debugging Problem with Sharepoint Foundation 2010

I've installed Sharepoint 2010 Foundation on my WS2008R2 copy...
Whenever i lanch from Visual Studio some debug, the process couldn't attach to IIS and so every break point is skipped..
To male debugger work, i've gone to the folder
C:\inetpub\wwwroot\wss\VirtualDirectories\80

(The app I'm interested in is installed on the 80 port)
From that folder I change some parameters in the file web.config, as I found on the web:
 <customErrors mode="Off" />

 <compilation batch="false" debug="true" optimizeCompilations="true">

 <SafeMode MaxControls="200" CallStack="true" DirectFileDependencies="10" TotalFileDependencies="50" AllowPageLevelTrace="false">

With this config no breakpoint is considered, even if i run it with "F5 || Start Debugging"...
I don't know if this is important, but i'm trying to debug some methods that are on a Web Service (installed in my ISS on a couple of ASMX files)
Thank you very much!

A:

I have seen this behavior before when IIS is not cycled after VS builds and deploys to the GAC.  In those cases, it is using a cached copy of the code and thus the breakpoints do not line up.  An occasional IISReset will flush this through.
The other thing to try is manually attach to ALL W3WP.exe processes and see if it hits your breakpoints then.  If it does, it means the F5 is attaching to the wrong process.
The last suggestion is to make sure that you are in the local Administrators group on your dev machine and that you are running Visual Studio as Administrator.  Usually you will get other errors if either of these is not done but security is one of those gray areas where it never hurts to be sure.


Q:

Implementing IDisposable correctly to return TCP connection back to pool

I'm trying to implement TCP connection pooling and return a connection back to the pool using IDisposable. I'm wondering if my implementation is correct. It seems to be working but I think because the base class also implements IDisposable and finalize, my code might be leaky.
public class BaseClass : IDisposable
{
    internal bool IsDisposed { get; set; }
    private object someResource;

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    ~BaseClass()
    {
        Dispose(false);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (someResource != null)
        {
            // some clearn up
            return;
        }

        if (disposing)
        {
            //dispose un managed resources

        }
    }
}

public class ChildClass : BaseClass
{
    // adds some functionality
}

public class MyClass : ChildClass, IDisposable
{
    MyPoolManager manager = null;

    public MyClass(MyPoolManager manager)
    {
        this.manager = manager;

    }
    void IDisposable.Dispose()
    {
        manager.ReturnPooledConnection(this);
    }
}

public class MyPoolManager
{
    private static MyPoolManager instance = new MyPoolManager();
    private static object objLock = new object();

    private static Queue<MyClass> que = null;
    private string name;

    static MyPoolManager()
    {
        que = new Queue<MyClass>();
        // enqueue some instances of MyClass here
        MyClass client = new MyClass(instance);
        que.Enqueue(client);
    }

    private MyPoolManager() { }

    public MyPoolManager(string name)
    {
        this.name = name;
    }

    public MyClass GetPooledConnection()
    {
        lock (objLock)
        {
            while (que.Count == 0)
            {
                if (!Monitor.Wait(objLock, 1000))
                    throw new TimeoutException("Connection timeout");
            }
            return que.Dequeue();
        }
    }

    public void ReturnPooledConnection(MyClass client)
    {
        lock (objLock)
        {
            que.Enqueue(client);
            Monitor.Pulse(objLock);
        }
    }
}

Use it like this in your program:
MyPoolManager pool = new MyPoolManager();
using (var conn = pool.GetPooledConnection())
{
    // use the conn here
}

// when you reach here the conn should have returned back to the pool

A:

The days of using IDisposable for things like this only came about because of the lack of functional programming concepts in C#. Now that Action and Func<T> exist there's absolutely no reason to use IDisposable for this situation.
A pool of connections/resources can expose a much nicer and simpler interface that removes the need for the using statement altogether and as a result avoids the possibility of the caller "forgetting" to give the resource back to the pool. Just because something implements IDisposable it doesn't mean that the caller will dispose of it properly.
A few points on your implementation:

Your BaseClass is completely unnecessary and can be removed.
The manager class has a poor implementation of what's already in the .NET framework: ConcurrentQueue. It's not only a better option because you don't have to write it, but it's lock-free and much more efficient.
The manager class's lock forces serialised access to one thread at a time, even if there are plenty of resources available. If you have 30 connections, you should let 30 threads access your resource pool at once, not just 1. Use a Sempahore instead.

So with this in mind I'd like to make a couple of suggestions.

Generalise your resource pool. The resource pool shouldn't be coded to a specific type of thing. Anything of any type can be pooled.
Avoid the use of disposable and use higher order functions to wrap up the lifetime of the resource. The consumer can not possible forget to give the resource back to the pool because you're doing it all for them.
Use proper .NET collections to solve the problem, not your own implementation.
Avoid a straight lock which serialises access when you can instead use a semaphore.
Don't push the logic of resource creation into the pool. Pass in a function that can do the creation for you, then you can have something that can create objects of arbitrary complexity.

Here's a quick implementation I've just thrown together (haven't compiled it, it's for reference and for ideas only):
public class Pool<TResource>
{
  private const int PoolWaitTimeoutMs = 1000;

  private readonly BlockingCollection<TResource> _resources;

  public Pool(int size, Func<TResource> producer)
  {
    _resources = new BlockingCollection<TResource>();

    for(var i = 0; i < size; ++i)
    {
      _resources.Add(producer());
    }
  }

  public void Consume(Action<TResource> consumer)
  {
    // This is a helper for when consumers don't produce a result
    Consume(new Func<TResource, object>(res => { consumer(res); return null; }));
  }

  public TResult Consume(Func<TResource, TResult> consumer)
  {

    TResource res;

    try
    {
      // wait for a resource to become available
      if (!_resource.TryTake(out res, PoolWaitTimeoutMs))
      {
        throw new Exception("Unable to acquire resource");
      }

      // invoke the consumer function and return the result
      return consumer(res);
    }
    finally
    {
      // put it back in the queue if we managed to get one
      if(res != null)
      {
        _resources.Add(res);
      }
    }
  }
}

Using the pool them becomes as simple as this:
public class SomePooledResource
{
  public void DoStuff() { ... };
  public List<string> GetStuff() { ... };
  // other stuff
}

// create a pool of 10 resources
var pool = new Pool<SomePooledResource>(10, () => new SomePooledResource);

// use the resource without returning something
pool.Consume(res => res.DoStuff());

// use the resource returning a result
var results1 = pool.Consume(res => res.GetStuff());

// use the resource to do both
var results2 = pool.Consume(res =>
    {
      res.DoStuff();
      return res.GetStuff();
    });


Q:

jQuery and MVC3 Razor producing strange URL on Android browsers

I'm working on an MVC3 (with Razor) / jQuery Mobile application and am having trouble navigating back on many areas of my application when using an Android browser (or user agent).
The problem appears to be in the URL that gets created with the @Url.Action method. On iPhones and PC browsers the URL looks like this:

Customer Lookup

but on Android browsers or in Chrome using the Android user agent the URL looks like this:

Customer Lookup

When I click this link I get an error:
Uncaught Error: Syntax error, unrecognized expression: data-url='/(F(Kdqb5nTlCaTP52GkHZ76P50MXAvnUCexKHt0ucPisYJ0iubQ3jwKk6-tiqxAtGVdBmiOgq4mW1-ZF3XUZJc5Y9BHnXVa2fWeIyFE5BxUwmZRhPjbm4L8AWDeymlpAcYJ9ABEPfu5i5_JmvAFinX8y9Jnwj0YeQRnpx_NCVjGqEcuFB-0g5NYcOI_WAsixNP90])/CustomerLookup/Search?ep=Home&t=8cf20fb0b1db618')

I'm now unable to navigate back to the original page.
Any ideas?

A:

It looks like you have cookies disabled on your android and session is being thrown into your url.


Q:

Draw new sphere in front of the camera in 3D animation

With the use of Python and OpenGL, I created an optic flow animation, where a camera moves towards spheres (the circles displayed in the GIF).

I tried to create two conditions within the loop that updates the camera position frame by frame, and plays the animation :
near_z = -0.05;
far_z = -50.0;
nSpheres = 40;

for nframes in range(200):
   camera_z -= .7  # the camera moves with a speed of .7 on the z-axis.

1 - The first condition says that when the camera reaches the far clip plane (far_z), get the camera back to the near clip plane again (near_z). As you can see in the GIF, it is working.
camera_z = np.where(camera_z <= far_z, near_z, camera_z)

2- The second condition says that when a camera passes a sphere, redraw a new sphere in front of the camera, that way I would maintain the same number of spheres in the animation. So Every time a sphere disappears from the frame, redraw one. For some reason, it is not working. I tried to figure out why, but I am obviously failing.
if sphere.position.z >= camera_z: # if the sphere is behind the camera, so the sphere is not visible

           sphere.position.z = np.random.uniform(camera_z,far_z) # define a new position for the sphere in front of the camera.

Thanks in advance for your help!!

A:

near_z respectively far_z are no absolute coordinates. This are relative distances to the current z coordinate of the camera.
So it has to be:
sphere.position.z = np.random.uniform(camera_z+near_z, camera_z+far_z)

But be aware, if the camera is "reset", by

camera_z = np.where(camera_z <= far_z, near_z, camera_z)

then suddenly all the spheres are out of the viewing frustum and clipped by the far plane.
In this case you've to translate all the spheres by the distance from the near plane to the far plane.
In this context near_z and far_z are "absoulte" coordinates (for a moment).
e.g. (instead of camera_z = np.where(camera_z <= far_z, near_z, camera_z):
if camera_z > far_z:
    offset_z = far_z - near_z
    camera_z -= offset_z
    for sphere in spheres:
        sphere.position.z -= offset_z


Q:

Which is the probability to a random line to be parallel to a specific other line?

In my perception, using the common sense, is less common, or less probable, to a random line be parallel that not to be, because to be parallel a line needs obey a restrictive rule. But anyone can, using simple probability, obtain that result:
specific line (r) = any line in R2 (e.g. y=0)
amount of random lines (u) = infinite (inf)
amount of parallel lines to r (s) = infinite (inf)
probability of s parallel to r = s / u = inf/inf = undefined

But there is another solution? Maybe using geometric probability, integrals or even empirical results?
[EDIT]
OK. I've understood the zero result and the "not impossible" thing. Thanks for answers and references.
But...

Is my initial perception wrong?
Is not easier to find a not parallel line instead a parallel?
Could someone prove or negate it?
If my perception is not wrong someone can calculate how easier is?
or maybe I really didnt understand the answers?

[NEW EDIT]
So, is it the final answer?
- Is my initial perception wrong?
- A: No, its correct.

Is not easier to find a not parallel line instead a parallel?
A: Yes, it is easier.
Could someone prove or negate it?
A: Yes: '''The probability of finding a parallel line is zero, so the probability of finding a non-parallel line is equal to one. Since 1>0, you have the answer to your question. – Rod Carvalho'''
If my perception is not wrong someone can calculate how easier is?
A: No, nobody can because it is undefined. (?)

[FINAL EDITION]
Now I realize that the question resumes to: which is the probability of a random real number be equal to a specific other. Thanks for help.

A:

Suppose that we have a line $\mathcal{L}_1$ defined by
$$\mathcal{L}_1 := \{ (x,y) \in \mathbb{R}^2 \mid y = a x + b \}$$
and another line, $\mathcal{L}_2$, defined by
$$\mathcal{L}_2 := \{ (x,y) \in \mathbb{R}^2 \mid y = \tan (\theta) x + c \}$$
where $\theta$ is an observation of a random variable $\Theta$ uniformly distributed over $[0, \pi]$. Lines $\mathcal{L}_1$ and $\mathcal{L}_2$ will be parallel if $\theta = \tan^{-1} (a)$. However, since $\Theta$ has a continuous distribution, we have that
$$\mathbb{P} \left( \Theta = \tan^{-1} (a) \right) = 0$$
In other words, the probability that a line whose slope is randomly chosen  is parallel to a given line is exactly equal to zero.


Q:

cannot change default rails error message

I have the following validation for my Profile model:
validates :category, presence: true,
  inclusion: {in: categories, message: "Please choose a category from the list."}

And the following in my en.yml file:
en:
  active_record:
    errors:
      models:
        profile:
          attributes:
            category:
              blank: "Category must be present."

Yet, for some reason, the error  message that is displayed is still the default:
can't be blank

how do I make the locale file work and change the error message?

A:

In your en.yml file you should be using activerecord, not active_record.


Q:

svn -- Time since last merge

I am in need of a "time since last merge" report. We have a single branch where changes from other branches are integrated. To keep everyone in sync, we encourage branch masters to perform a merge from integration line to their respective branches.
I am working on a post-commit hook that will send a report every time a commit is done on integration line that explains:

source branch
time since last merge between integration and other branches

svn mergeinfo is the starting point, but what other commands will help me get this info?

A:

svn log gives you the figure semi-straight.
If all merging is done on the highest possible directory level (as is best practice), then execute the following command:
svn log -g https://myrepos.tld/branches/single-private-feature-branch

you will get the usualy history plus revisions that were merged into this branch. Look for the string "Merged via: ". The first hit will be the last merge into this branch. You can optionally fetch the log entry of the revision given to make sure it is comming from the integration branch and was not merged from some other place.
All this can be done with simple shellscripting.
Hope it helps :)
C


Q:

AngularJS disable filter dyamically

I have a single page app built with angular with a filter that is responsible for substituting localized strings for reference keys.
Example:
{{'example.context.section.id'  | translate}}

I want to be able to disable the filter programmatically or overwrite it so that it just outputs the key. The point is to create a button on the mockups that allow the writers to view the translation keys their actual context.
angular.module('***').filter('translate', function() {
    return function(input){ return input; }
});

I tried just executing the above filter replacement in the console but the translations still occur using the actual translate filter.
I also tried using $filterProvider in a config block after-the-fact but this also had no effect. I followed the guide on the (docs)[http://docs.angularjs.org/api/ng.$filterProvider] for this.
angular.module('ltAccountApp').config(['$filterProvider', function($filterProvider){
    $filterProvider.register('translate', function(translate) {
        return function(input) { return input; }
    });
}]);

Also this variation based on the docs:
angular.module('ltAccountApp').run(['$provide', '$filterProvider', function($provide, $filterProvider){
    $provide.value('translate', function(input){ return input; });
    $filterProvider.register('translate', function(translate) {
        return translate(input) || input;
    });
}]);

Maybe I could add the filter provider to the code and have it switch between the 2 options based on a rootscope variable?
Thanks for your help and suggestions!
Using AngularJS 1.08

A:

You can define a flag on $rootScope to control filter behavior.
angular.module('***')
.filter('translate', function($rootScope) {
  return function(input) {

    // define a `enableFilter` property in $rootScope to control filter behavior
    if ($rootScope.enableFilter) {
      // transform input here
      return transformedInput;
    } else {
      return input;
    }

  };
});


Q:

Javascript function hoisting inside of if statements

What's the deal with javascript function hoisting inside of if statements?  Does js just not do it?  The following code, when run in a browser works just fine.  It will alert "hey" after two seconds.
<script>
setTimeout(hey,2000)
function hey(){
    alert('hey')
}
</script>

But add a trival if statement around this:
<script>
if(true){
setTimeout(hey,2000)

function hey(){
    alert('hey')
}
}
</script>

and suddenly it complains that hey is not defined.
Now if you change the callback from hey to function(){hey()}, like this:
<script>
if(true){
setTimeout(function(){hey()},2000)

function hey(){
    alert('hey')
}
}
</script>

then it starts working again, even with the if statement.  So what's going on?

A:

Firefox doesn’t hoist function declarations in blocks, apparently. The behavior you're seeing is specific to Firefox, and documented nearly identically elsewhere.
To paraphrase:

Works:
if ( hasRequiredJQueryVersion ) {
   // Test data here
   // Library code here
}

Works everywhere except Firefox:
if ( true ) {
    testFunction();
    function testFunction() {
        alert(‘testFunction called’);
    }
}

This is behavior you should avoid, as it is specific to Firefox, even though Firefox's behavior may technically be correct.


Q:

Cannot start Azure Databricks cluster

I am new to the MS Azure. I am trying to download Microsoft Academic Graph for various analysis, and they don't offer bulk-downloading the structured dataset. External sources such as openacademicgraph weren't really useful, so I thought I could try downloading the data through Azure.
Luckily, there were manuals for just that - "Get Microsoft Academic Graph on Azure storage - docs.microsoft.com/en-us/academic-services/graph/get-started-setup-provisioning".
I followed the steps in the manual to create a Azure account for MAG, getting a following email from Academic Knowledge API -

Welcome to the Microsoft Academic Graph (MAG) Azure Storage (AS) Distribution preview. Please be advised that this distribution is in free preview stage. Pricing structure is subject to change.
Your Azure Storage is successfully setup to receive MAG update through Azure Data Factory. Each MAG dataset is provisioned to a separate container named "mag-yyyy-mm-dd". The 2020-02-14 dataset was pushed to your Azure Storage.
As MAG comes with ODC-BY license, you are granted the rights to add values and redistribute the derivatives based on the terms of the open data license, e.g., the attribution to MAG in your products, services or community events.
Each snapshot of MAG will show up in your Azure Storage as a distinct container. In Microsoft Academic Graph documentation, you could find a sample to extract knowledge from MAG for your application using Azure Databricks. Also there is a sample using U-SQL, a member of Azure Data Lake Analytic Framework.
We also put together great Analytics and visualization samples that we used for our WWW Conference Analytics blog post. We hope this can help accelerate your development process and spark imagination!

Next step was "Set up Azure Databricks for Microsoft Academic Graph - docs.microsoft.com/en-us/academic-services/graph/get-started-setup-databricks", which I followed. I was able to create an Azure Databricks for MAG (I have no idea what they are as I'm new to this), but now I cannot get it to run.
Following is the error message I get:

Message
Cluster terminated. Reason: Cloud Provider Launch Failure
A cloud provider error was encountered while launching worker nodes. See the Databricks guide for more information.
Azure error code: OperationNotAllowed
Azure error message: Operation could not be completed as it results in exceeding approved Total Regional Cores quota. Additional details - Deployment Model: Resource Manager, Location: centralus, Current Limit: 4, Current Usage: 4, Additional Required: 4, (Minimum) New Limit Required: 8. Submit a request for Quota increase at https://aka.ms/ProdportalCRP/?#create/Microsoft.Support/Parameters/~~~ by specifying parameters listed in the ‘Details’ section for deployment to succeed. Please read more about quota limits at https://docs.microsoft.com/en-us/azure/azure-supportability/regional-quota-requests.

I'm not sure what I'm supposed to do.
"Total Regional Cores quota" is exceeded, not my personal subscription etc. How would I ask to increase the quota for the whole region?
They say I need to apply for a larger quota, which cannot be done with the free trial account I created as per the manual. Does this mean that the manual is wrong, and I have to become Pay-As-You-Go?
"Current Usage: 4" but I am not using anything at the moment. All I have is an Azure storage and a Databrick cluster which aren't running.
I re-tried starting the cluster, and the second time it was successfully started, only to deactivated a couple of minutes later with the same error message.
I'm not going to do any complex querying and stuff - it's going to be pretty expensive. Being the poor research and such, all I am looking to get is the dataset following the MAG schema; I will run whatever analysis on them on my desktop which would be free, while slower. Any help would be really appreciated.

A:

To try Azure Databricks, you need to have “Pay-As-You-Go” subscription.
Azure Free Trail has a limit of 4 cores, and you cannot create Azure Databricks cluster using a Free Trial Subscription because to create a spark cluster which requires more than 4 cores.
If you have a free account, go to your profile and change your subscription to pay-as-you-go. Then, remove the spending limit, and request a quota increase for vCPUs in your region. When you create your Azure Databricks workspace, you can select the Trial (Premium - 14-Days Free DBUs) pricing tier to give the workspace access to free Premium Azure Databricks DBUs for 14 days.
For more details, refer "Sign up for a Free Azure Databricks Trial".


Q:

Getting the class name which triggered the event

I have a tag with below HTML :
Create Account
I am using a common click handler of the 3 button with Class create_account , member_login , product_service
Now inside the handler , I want the class name which triggered the click event, in best possible way (with minimal condition)
 $('.create_account , .member_login , .product_services').click(function(){

    console.log($(this).attr('class'));

    /**

      In case , user click on button with class `create_account` , I get in console

      `create_account singup  header-icon` , which is correct,

       **but I want `create_account` i.e is the class which triggered the Click event**

    */

 });

A:

I would just create a separate click handler for each class, like so:

// Define all the required classes in an array...
var selectors = ["create_account", "member_login", "product_services"];
// Iterate over the array
$.each(selectors, function(index, selector) {
    // Attach a new click handler per-class. This could be a shared function
    $("."+selector).click(function(e) {
        e.preventDefault();
        alert(selector); // Logs individual class
    });
});

Create
Login
Services

If you want you can abstract the shared logic out into another function, like this Fiddle


Q:

AppKit thread-safe or not?

Can you explain me is AppKit thread-safe or not? Where can I read about it? (Except Threaded Programming Guide because this documentation creates more question instead answers). For example can I validateVisibleItems of NSToolbar in separated thread? Or can I increment value of NSProgressIndicator in second thread?

A:

No, it is not in general.  You should not send messages to any UI objects except from the main thread.
In the specific example you give, you can use performSelectorOnMainThread:withObject:waitUntilDone: to get around the restriction:
[myToolbar performSelectorOnMainThread: @selector(validateVisibleItems)
                            withObject: nil
                         waitUntilDone: whatever];


Q:

How can I explain rainforests in a world with little, localized rain?

On the world I am building (Let's call it Bob for simplicity's sake), the days last 9 years. As a result of this, the living beings on Bob must migrate across the planet to avoid the encroaching night. Now, obviously if Bob had continents like Earth, this would be impossible for animals (like the ones that would evolve into sapient beings.). So to combat this, Bob lacks oceans, he instead has large lakes (like the Caspian Sea) scattered every couple thousand kilometers.
Now, without oceans, the weather becomes a bit messed up, specifically the precipitation cycle. Only areas within a few hundred miles (at best) of a lake would get rain, and rarely at that. So, how do I permit rain forests to appear on Bob?
On a world, were rain is rare and not widespread, how can rain dependent biomes like rainforests develop?

A:

Lakes + Mountains = Rainforest
Funny you should mention the Caspian Sea in your question. Look at the southern end of the Caspian Sea here:

Surrounded by dry desert on pretty much all sides, there is a dark green forested strip, covered with clouds. This is a result of northerly winds over the lake interacting with the Alborz mountains.
The result is heavy rainfall year round, although it is dryer in the summer. The mountain heights cause heavy snowfall on the high pastures in wintertime, and the melting snow inundates the lower forests all summer long. The result is cool, wet, mountain rainforest. No other ingredients required.

A:

It seems unlikely that quickly growing roots could circumnavigate the planet in 9 years. But I have a way you could do it. Hopefully I'm not too far off what you are trying to achieve.
Imagine a huge root system that goes around the planet in a belt, draws it's nourishment from whatever lakes are around. As night falls on part of it, it's basically autumn, the trees lose their leaves, the local roots draw in what they can and go dormant while the trees eventually die and fertilise the earth while the roots lie waiting below the frost for the next spring/day. Mushrooms spring up etc,.
With the areas that are just lighting up the roots feel the change and start putting out shoots and growing very fast for 9 years. So you have a moving rain forest in a belt around the entire planet where it's daytime and a bit of the night. Thickest and biggest at the trailing edge, and more sparse and younger trees at the leading edge.
The rain forest fauna would have to move with it, but I can imagine all sorts of specialists that might thrive in the leading and trailing edges and among the dying trees in the night.
They can do the things like throw seeds everywhere, have symbiotic relationships with animals etc, as well. It helps them spread and compete.
You could even have the rain forests only appear in suitable places, with pine type trees in suitable environments for them, all depends what roots are waiting for the sun to warm them.
This is probably the only way you could have specialist rain forest fauna. Otherwise they'd all die waiting 9 years in the dark for the seeds to sprout, if everything moves then they can evolve to move with it. The reason I use roots instead of seeds, is the water supply problem. Roots can store a lot, and with 9 years you can move water for a lot of km if you're imaginative about it.
If the different species had all evolved to share water for instance, you could basically have a suitable environment for all plants with water permeating through for hundreds of kilometres over time. So grasslands, wetlands, the whole deal.
Basically you're just transporting the water underground instead of in the clouds.


Q:

Change font of jTextfield in jDatePicker in Java

I have downloaded a jDatePicker library and embedded it into my application successfully. This is just a simple jdatepicker.jar file.
I have this simple code to add jDatePicker in my application
public JDatePickerImpl JDatePickerDemo()
{
        UtilDateModel model = new UtilDateModel();
        model.setDate(1990, 8, 24);
        model.setSelected(true);
        JDatePanelImpl datePanel = new JDatePanelImpl(model);
        JDatePickerImpl datePicker = new JDatePickerImpl(datePanel, new DateLabelFormatter());
        return datePicker;
}

this adds jDatePicker in my application

But the fonts in this above textField is very small, i want to increase its font size. How can I do?
I also have a class with it to format date in textfield, may be that can help but I don't know
public class DateLabelFormatter extends AbstractFormatter
{
    private String datePattern = "yyyy-MM-dd";
    private SimpleDateFormat dateFormatter = new SimpleDateFormat(datePattern);

    @Override
    public Object stringToValue(String text) throws ParseException {
        return dateFormatter.parseObject(text);
    }
}

A:

I have used sourceforge.net/projects/jdatepicker ...
If you unroll the jar from that site, you can inspect the classes and study their public API.  Upon doing this, you will see that there's a class called JDatePickerImpl. Somehwere I assume, you be instantiating this.
Upon creating an instance of this, you'll see that you have access to its internal text field, which is a JFormattedTextField. From there, you can change its font:
JDatePickerImpl datePicker = new JDatePickerImpl(...);
JFormattedTextField textField = datePicker.getJFormattedTextField();
textField.setFont(new Font("Some-Font-Name", Font.BOLD, 12));


Q:

cursor: pointer doesn't work on :after element?

I'm viewing the below example in Chrome and can't seem to get cursor: pointer to work on the :after element of li. Is there a way to get around this?
http://jsfiddle.net/qKMPQ/2/

A:

Instead of setting the cursor: pointer on the :after element, set it on the entire li and it will show up on both.
Edit:
For those of you trying to have different cursors on the li and its :after pseudo-element, you simply need to explicitly define the cursor property of the content inside the li. See this updated fiddle: http://jsfiddle.net/qKMPQ/20/

ul { list-style-type: none; }
li { cursor: pointer; }
a {
    background: red;
    float: left;
    width: 100px;
    height: 100px;
    cursor: help;
    display: block; }
li:after {
    content: "";
    background: yellow;
    float: left;
    width: 100px;
    height: 100px;
    display: block; }


Q:

write a file using FileSystem API

I am trying to create a file using the File system API..i googled and i get a code
function onFs(fs) {

  fs.root.getFile('log.txt', {create: true, exclusive: true},
      function(fileEntry) {
           fileEntry.getMetaData(function(md) {
            }, onError);

      },
      onError
  );
}

window.requestFileSystem(TEMPORARY, 1024*1024 /*1MB*/, onFs, onError);

can any one say what is the fs which is passed as function argument..
Please refer me a good example...

A:

fs is a javascript object that allows you to make "system-like" level calls to a virtual filesystem.
So for instance you can use the fs object to create/get a reference to a file in the virtual filesystem with fs.root.getFile(...). The third argument (in your case, the following lines of code from your above snippet) in the .getFile(...) method happens to be a callback for successful obtaining of a file reference.
function(fileEntry) {
       fileEntry.getMetaData(function(md) {
        }, onError);
}

That file reference (in your case it is called fileEntry) can have various methods called such as .createWriter(...) for writing to files, .file(...) for reading files and .remove(...) for removing files. Your method calls .getMetaData(...) which contains a file size and modification date.
For more specifics as well as some good examples on the html5 file-system api you may find the following article helpful Exploring the File-System API
The location of the files differs on the browser, operating system and storage type (persistent vs. temporary) but the following link has served to be quiet useful as well Chrome persistent storage locations


Q:

Centering a square qWidget in qt

I am trying to solve a graphics problem using the latest version of Qt. The image below shows what I managed to get so far and I will use it to explain the expected result.

I'm using a main vertical layout and within the biggest widget of the layout there is a horizontal layout with only one child: the square widget. The expected behavior would be of course to have the square widget centered horizontally and taking up the biggest space available. It is not required to use the same layout configuration, but the look of the interface should be the same.
The image above has been obtained by setting a QSizePolicy of minimumExpanding for both vertical and horizontal to the square widget and by forcing it to be square with the following code:
void SquareWidget::resizeEvent(QResizeEvent *event) {
    //This is an override to the QWidget method

    QSize s = size();

    if (s.height()<s.width()) {
        resize(s.height(), s.height());
    } else {
        resize(s.width(), s.width());
    }
    return;
}

While trying to solve this problem I went through the documentation some of the answers on this website and I couldn't find a clear answer about how to do two tasks.
First problem: how to make the widget square and keep its aspect ratio?
In this question
it is said that the method heightForWidth () doesn't work in newer versions of qt, and after a test it doesn't work for me either. The above override of resizeEvent, on the other hand, causes recursion because there are calls to resize() (and as far as I understand the layout should handle the resizing).
Second problem: how to center the square?
I tried using the layout alignment properties (center horizontally and vertically) but they cause the widget size to be immutable.
Maybe I am not understanding something about how Qt handles the widget placement. Any suggestion or clarification will be greatly appreciated.

A:

Rather than trying to get the widget to keep itself square and centred it might be simpler to reparent it and put the required logic in the parent widget type.
So, something like...
class keep_child_square_and_centred: public QWidget {
  using super = QWidget;
public:
  explicit keep_child_square_and_centred (QWidget *parent = nullptr)
    : super(parent)
    , m_widget(nullptr)
    {}
  virtual void set_widget (QWidget *widget)
    {
      if ((m_widget = widget))
        m_widget->setParent(this);
    }
  virtual QSize sizeHint () const override
    {
      return(m_widget ? m_widget->sizeHint() : super::sizeHint());
    }
protected:
  virtual void resizeEvent (QResizeEvent *event) override
    {
      super::resizeEvent(event);
      fixup();
    }
private:
  void fixup ()
    {
      if (m_widget) {
        QRect r(QPoint(), QSize(height(), height()));
        r.moveCenter(rect().center());
        m_widget->setGeometry(r);
      }
    }
  QWidget *m_widget;
};

Then use as...
keep_child_square_and_centred w;
SquareWidget sq;
w.set_widget(&sq);

You may still need to play around with a few settings if the parent is in a layout though.


Q:

How to specify html page globally in Jboss?

We have a filter that redirects user to error.html, if the user is not authorized. Right now, we are keeping error.html page inside the WAR, but is there any way to make the html file public so that every war file can access this error page? It would be still better, if we make this html page as a jar and keep it in server/default/lib.
Here is the sample that is used in filter.

 `reqDespacher = request.getRequestDispatcher("error.html")`

and the accessing url is
http://localhost/Context_root/error.html

Any help would be appreciated.

A:

In JBoss5 or JBoss6, you can copy and then define this custom error.html inside the /deployer/jbossweb.deployer/web.xml of the server instance that you are running. This will require a reboot of the JBoss instance. Example for error code 404:
<error-page>
            <error-code>404</error-code>
            <location><relative_path_to_error_html_file_under_jbossweb.deployer_folder></location>
</error-page>

Secondly, instead of re-directing request by specifying a page manually like you are doing currently, you should use the <error-page> and <error-code> deployment directive to define custom error pages. See specify-the-default-error-page-in-web-xml-in-servlet for a detailed example on how to add error-code directives on web.xml.
For JBoss AS7 global error page configuration take a look at how-to-customize-jboss-as7-404-page .


Q:

Only select text directly in node, not in child nodes

How does one retrieve the text in a node without selecting the text in the children?

Editor's Description

Last updated:

     Lorem ipsum dolor sit amet.

In other words, I want Lorem ipsum dolor sit amet. rather than Editor's DescriptionLast updated: Lorem ipsum dolor sit amet.

A:

In the provided XML document:

Editor's Description

Last updated:

      Lorem ipsum dolor sit amet.

the top element /div has 4 children nodes that are text nodes. The first three of these four text-node children are whitespace-only. The last of these 4 text-node children is the one that is wanted.
Use:
/div/text()[last()]

This is different from:
/div/text()

The latter may (depending on whether whitespace-only nodes are preserved by the XML parser) select all 4 text nodes, but you only want the last of them.
An alternative is (when you don't know exactly which text-node you want):
/div/text()[normalize-space()]

This selects all text-node-children of /div that are not whitespace-only text nodes.

A:

Just select text() instead of .:
div/text()

On the given XML fragment, this returns:
Lorem ipsum dolor sit amet.


Q:

Get item from list as a new copy (not as a reference to the original)

How can I get an item from a list as a new copy/instance, so I can use and change it later without changing the original object in the list?
Public Class entry
    Public val As String
     ' ... other fields ...
End Class

Dim MyList As New List(Of entry)
Dim newitem As New entry
newitem.val = "first"
MyList.Add(newitem)

Now if I try to get an item from this list and change it to something else, it changes the original item in the list as well (it is used as a reference not as a new instance).
Dim newitem2 As New entry
newitem2 = MyList.Item(0)
newitem2.val = "something else"

So now the MyList.item(0).val contains "something else", yet I wanted only the newitem2 to contain that new value for the given field and retain other values from the object in the list.
Is there a way to do this without reassigning all fields one by one?

A:

If entry is defined as a reference type (Class), then your only option is to explicitly create a new instance that has the same values as the originals. For example:
Public Partial Class Entry
    Public Function Clone() As Entry
        Return New Entry() With { .val = Me.val, … }
    End Function
End Class

(The .NET Framework Class Library defined a type ICloneable from early on for exactly this purpose. The type never really caught on for certain reasons.)
Be aware that you might have to do this recursively, that is, if your class contains fields that are of a reference type, you'll have to clone the objects stored in these fields as well.
Then, instead of doing this:
Dim newitem2 As New entry  ' (Btw.: `New` is superfluous here, since you are
newitem2 = MyList.Item(0)  '         going to throw away the created instance here.)

Do this:
Dim newitem2 As Entry = MyList.Item(0).Clone()

One alternative is to use value types (i.e. declare your item type as Structure). Value types are automatically copied when passed around. However, there are lots of caveats to observe, among them:

Do not do this if your type contains many fields. (Why? Many fields usually means that the type will occupy more bytes in memory, which makes frequent copying quite expensive if the objects get too large.)
Value types should be immutable types. (Why? See e.g. Why are mutable structs evil?)

These are just two guidelines. You can find more infornation about this topic here:

When should I use a struct instead of a class?
Choosing Between Class and Struct


Q:

SQL Schema setup

I am newer to SQL and a bit confused on how best to represent an Entity-Relationship diagram for the following:
Say we have a company. The company has employees. Employees have managers (Many employees to 1 manager). Managers are employees (but managers can't manage themselves). Each employee/manager can be on many projects (1 emp/manager to Many projects). Also, employees/managers have many roles at the company (1 emp/manager to Many roles).
I am most confused on how to take into account embedding managers within employees. Are there any constraints that I would need to include to ensure no manager manages themselves?
Here is my schema so far (PostgreSQL):
CREATE TABLE employees
(
    emp_id     INTEGER PRIMARY KEY,
    name       VARCHAR(120) NOT NULL,
    manager_id INTEGER REFERENCES managers (manager_id)
);

CREATE TABLE managers
(
    manager_id INTEGER PRIMARY KEY,
    name       VARCHAR(120) NOT NULL
);

CREATE TABLE projects
(
    project_id   INTEGER PRIMARY KEY,
    project_name VARCHAR(120) NOT NULL,
    emp_id       INTEGER REFERENCES employees (emp_id)
);

CREATE TABLE roles
(
    role_id   INTEGER PRIMARY KEY,
    role_name VARCHAR(120) NOT NULL,
    emp_id    INTEGER REFERENCES employees (emp_id)
);

Any thoughts and help is much appreciated!

A:

I'd make the following amendments to your schema:
CREATE TABLE employees
(
    emp_id     INTEGER PRIMARY KEY,
    name       VARCHAR(120) NOT NULL,
    -- instead of: manager_id INTEGER REFERENCES managers (manager_id)
    manager_id INTEGER REFERENCES employees (emp_id)
);

-- ...and remove:
--CREATE TABLE managers
--(
--    manager_id INTEGER PRIMARY KEY,
--    name       VARCHAR(120) NOT NULL
--);

If you really want to encode the "no manager manages themselves" rule as a DB constraint, you could add a CHECK constraint (emp_id <> manager_id).


Q:

What does the tongue do to discriminate sibilant vs. non-sibilant?

My native language is Korean. And including me, probably most Korean people often confuse /θ/ with /s/, and /ð/ with /d/. The problem is, I don't know enough how sibilant fricatives and non-sibilant fricatives are discriminated. I know that they are discriminated by whether the airflow goes between the teeth or not, but such difference are made by the tongue, isn't it? So how different is the tongue?
With enough practice to speak English, I can now speak /θ/ and /ð/ properly, but I still don't get /ɹ̝/, /t͜θ/, etc.

A:

In /s,z/ the sides of the tongue are slightly raised, creating an u-shaped channel or groove, known as sulcus. You probably already do that unconsciously when you say a Korean /s/ (unless you have a lisp). Sulcalization (grooving) concentrates the airflow, making it sound more strident as it hits the top front teeth.
In /θ,ð/ the tongue is comparatively flat, without sulcalization; this makes the airflow spread, resulting in a softer sound. An easy way to do that is to make the tongue tip peek out beyond the teeth. Many native speakers do that (if you pay attention, sometimes you can spot a tongue tip in a singer's /θ/ in a music video). Depending on the dialect and phonetic context, other speakers don't pop out the tongue at all; they can produce /θ,ð/ sounds with a flattish tongue entirely inside, tongue tip behind the top teeth.


Q:

VS2013 R3 NodeJS project slow loading

I have a NodeJS project in Visual Studio and it takes more than 2 min when it tries to load the solution and the project.
Looking other questions about performance issues I've disabled the source control, the visual experience and the synchronization:

Tools > Options > Source Control > Plug-in Selection

"Current source control plug-in": None

Tools > Options > Environment > General

"Automatically adjust visual experience based on client performance": Unchecked
"Enable rich client visual experience": Unchecked
"Use hardware graphics acceleration if available": Unchecked

Tools > Options > Environment > Synchronized Settings

"Enable synchronization for the following categories of settings": Unchecked

None of this actions improved the performance in project loading time.
How can I improve the project loading time? Are there any facts I should take in account to do not delay the loading time?
I'm using Visual Studio 2013 Update 3
Update
I have figured out what is going on (see accepted answer).
I will accept any other answer that tells me how to prevent folders to be loaded in the explorer tree because I will like to keep this folders there but not for visual studio proposes.
I have tested toggling "Show all files" option in the project explorer tree but it seems to do not affect to the loading time since the explorer tree still needs to process all the files in the directory (even if those are not going to be shown in the explorer tree).

A:

The Visual Studio explorer tree needs time to process all the files in the project folder.
I have tested it with a symbolic link to a folder that contains 184,615 Files and 15,012 Folders (13.7 GB) and the project never gets loaded (at least it does not look like it will become loaded before the next year), so I had to halt it.
Cleaning as much folders and files as possible from my project solved the problem and now the project loads in 3s.


Q:

Django, Display thumbs in Admin?

how ill show in the admin section the user picture?, i was looking the template of the admin and i can't see how...
i think that Django show the fields in the section code (change_list template), but jeje ..how? jeje
{% block result_list %}
          {% if action_form and actions_on_top and cl.full_result_count %}{% admin_actions %}{% endif %}
          {% result_list cl %}
          {% if action_form and actions_on_bottom and cl.full_result_count %}{% admin_actions %}{% endif %}
      {% endblock %}

Thanks guys :)

A:

We use Justin Driscoll's fabulous django-photologue.
If photologue is installed properly (recommend running python manage.py plinit as part of the installation) and the media is being served correctly the following should provide you with an easy-to-use admin_thumbnail() as follows:
models.py
from photologue.models import Photo

class Entry(models.Model):
    entry_photo = models.ForeignKey(Photo)
    ...

admin.py
def show_entry_thumbnail(item):
    return item.entry_photo.admin_thumbnail()
show_entry_thumbnail.short_description = _('Entry Photo')

class ItemAdmin(admin.ModelAdmin):
    list_display = (show_entry_thumbnail, ... )


Q:

Swift 5.2 tuple destructuring in closure has inconsistent behaviors

I ran into a weird tuple destructuring problem in Swift 5.2.
I thought tuple destructuring didn't work inside a closure parameter since some time ago.
And indeed, the following does not work:
let expected: ((Int, Int)) -> Void = { a, b in  // does not compile
    print(a, b)
}

However, I noticed that all of the below work:
func weird(closure: @escaping ((Int, Int)) -> Void) {
    closure((1, 3))
}

// I can understand this
weird { print($0.0 + $0.1) }
weird { a, b in print(a + b) }

// Surprise!
weird { print($0 + $1) }
weird { p in print(p.0 + p.1) }

Did the last two examples worked before Swift 5.2? Is this behavior documented somewhere?

A:

It is related to this proposal, which was once accepted in Swift 4.0.
SE-0110 Distinguish between single-tuple and multiple-argument function types
So, two of your examples (not last two though) caused error in a certain version of Swift, but Swift team found some unacceptable regression in this implementation.
Additional Commentary
And since a certain version of Swift (I do not remember the exact version, it might have been 4.0.x or 4.1), you can pass two argument closure to the parameter of function type taking a single tuple.
And recently, this exception is confirmed to be a part of SE-0110 and if some more modification is needed, a new proposal will be made and go through the usual Swift Evolution process.
Update on SE-0110 and SE-0155

the original proposal as reviewed did not include the special-case
  conversion from (T, U, ...) -> V to ((T, U, ...)) -> V for function
  arguments. In response to community feedback, this conversion was
  added as part of the Core Team's acceptance of the proposal.

The Swift book may not have clear explanation of this behavior, but it surely is documented.


Q:

How does MariaDB handle ENUM types used in FOREIGN KEY constraints?

Off the heels of this question,

How does MySQL handle joins on ENUMs?

How does MySQL work if the referencing table has more and less values in the ENUM than the table being referenced? Is it validating integrity based solely on the global ENUM textual key (symbol)? Or the underlying integer value?

A:

As demonstrated in the related question, JOINS on enums are "by-value". Constraints, on the other hand, is validated "by-position". This behaviour strikes me as rather counter-intuitive. Using a similar setup as Evan:
CREATE TABLE foo ( a ENUM ('A', 'B') not null primary key );
CREATE TABLE bar ( a ENUM ('X', 'Y', 'Z') not null primary key );
ALTER TABLE bar ADD CONSTRAINT fk_foo_bar
    FOREIGN KEY (a) REFERENCES foo (a);

insert into foo (a) values ('A'),('B');
insert into bar (a) values ('X'); -- OK
insert into bar (a) values ('Z');
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails ("test3"."bar", CONSTRAINT "fk_foo_bar" FOREIGN KEY ("a") REFERENCES "foo" ("a"))

So 'X' is valid according to the foreign key constraint. As Evan demonstrated, JOINs behave differently:
SELECT * FROM foo JOIN bar USING(a);
Empty set (0.00 sec)

So despite that, the row in bar is validated by the foreign key, the join between foo and bar is empty.
It may be tempting at first to use ENUM as a substitute for the lack of CHECK CONSTRAINTS in the MySQL family. However, the way FOREIGN KEYS work together with ENUMs can shoot you in the foot. A typical pattern for subtypes look like:
CREATE TABLE P
( p int not null primary key
, sub_type ENUM ('A','B')
,     constraint AK_P unique (p, sub_type));

CREATE TABLE A
( p int not null primary key
, sub_type ENUM ('A')
,     constraint aaa foreign key (p, sub_type)
                     references P (p, sub_type));

CREATE TABLE B
( p int not null primary key
, sub_type ENUM ('B')
,     constraint bbb foreign key (p, sub_type)
                     references P (p, sub_type));

insert into P (p,sub_type) values (1,'A'),(2,'B');
insert into A (p,sub_type) values (1,'A'); -- OK
insert into B (p,sub_type) values (1,'B'); -- OK, but should not be allowed since 1 is sub_type 'A' in parent
insert into B (p,sub_type) values (2,'B'); -- Fails, but should be OK

ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails ("test3"."B", CONSTRAINT "bbb" FOREIGN KEY ("p", "sub_type") REFERENCES "P" ("p", "sub_type"))

So the foreign key validates the position in the enum, not the value itself.
PostgreSQL does not allow foreign keys between different enums, so the situation is not possible to reproduce there:
CREATE type e1 as ENUM ('A', 'B');
CREATE type e2 as ENUM ('X', 'Y', 'Z');

CREATE TABLE foo ( a e1 not null primary key );
CREATE TABLE bar ( a e2 not null primary key );

ALTER TABLE bar ADD CONSTRAINT fk_foo_bar
    FOREIGN KEY (a) REFERENCES foo (a);
ERROR:  foreign key constraint "fk_foo_bar" cannot be implemented
DETAIL:  Key columns "a" and "a" are of incompatible types: e2 and e1.


Q:

mySQL query in C++

In the following code for retrieving data via a SQL query from the db, is there a way I can replace row[0] with fieldname. I am only enclosing the relevant part of the code
MYSQL_RES *resptr;
MYSQL_ROW row;

while ( ( row = mysql_fetch_row(resptr)) != NULL )
{
for (int i=0;i<8;i++)
string key = row[0];
 }

row[0] is the trans_date column. the code works fine as it is right now, but is there a way to assign key by using the fieldname vs. having to remember all the field numbers.
thanks!

A:

You can retrieve field names by doing
field = mysql_fetch_field(resptr);
std::cout << field->name;

(Put in a while loop to loop through all field)
But you can't call row[fieldName]. What you can do though is define variables to map column names and numbers
int id = 0;
int trans_date = 1;
// Code happening here
std::cout << row[id] << " " << row[trans_date];

UPDATE: You could always do something like this (using STL's map):
map<string, int> columns;
int i = 0;
while(field = mysql_fetch_field(resptr)){
  columns.insert(pair<string,int>(field->name, i++));
}

And then use row[columns["name"]];.


Q:

ASP.net The process cannot access the file because it is being used by another process

i have the following error:
  The process cannot access the file because it is being used by another process.

trying to save a file and then reading it, please can you help me to fix the code ?
 protected void Button1_Click(object sender, EventArgs e)
 {
    string path = "\\\\nasouts01\\CodiceDiRete\\temp\\";

    if (FileUpload1.HasFile)
    {
        string fileExt =
           System.IO.Path.GetExtension(FileUpload1.FileName);

        if (fileExt == ".csv")
        {
            try
            {

                FileUpload1.SaveAs(path + FileUpload1.FileName);

            }
            catch (Exception ex)
            {
                Label1.Text = "ERROR: " + ex.Message.ToString();
            }
            finally
            {
                FileUpload1.PostedFile.InputStream.Flush();
                FileUpload1.PostedFile.InputStream.Close();
                FileUpload1.FileContent.Dispose();
                //Release File from Memory after uploading
            }
        }
        else
        {
            Label1.Text = "Selezionare soltanto file .csv";
            gwreportpub.Visible = false;
            ButtonConferma.Visible = false;
            ButtonAnnulla.Visible = false;
            ButtonPulisci.Visible = false;
            return;
        }
    }
    else
    {
        Label1.Text = "Inserire un file ";
        gwreportpub.Visible = false;
        ButtonConferma.Visible = false;
        ButtonAnnulla.Visible = false;
        ButtonPulisci.Visible = false;
        return;
    }
    /*
    Validazione nel file , dopo visualizzazione dei dati nella tabella
    */
    int count  = 0;
    string line;

    // Read the file and display it line by line.
    using (System.IO.StreamReader file =
    new System.IO.StreamReader(path+FileUpload1.FileName))
    {
    while((line = file.ReadLine()) != null)
    {
       count = line.Split(',').Length;
       if(count != 12){

         Label1.Text = "Il file non contiene il numero esatto di campi che servono al caricamento";
         gwreportpub.Visible = false;
         ButtonConferma.Visible = false;
         ButtonAnnulla.Visible = false;
         ButtonPulisci.Visible = false;
         return;

       }
    }

    file.Close();
    }
    /*
    Prendo il valore della sequence
    */
    OracleCommand sequenceCmd = new OracleCommand("select ls_seq_batchrequest.nextval from dual",connection);
    OracleDataReader reader = sequenceCmd.ExecuteReader();
    int sequenceVal=0;
    while (reader.Read())
    {
        //dropdownlist1.Items.Insert(0, new ListItem(reader.GetString(0), reader.GetString(0)));
        sequenceVal = reader.GetInt32(0);
    }
    reader.Close();

    Session["sequenceVal"] = sequenceVal;

    /*
    Faccio l'inserimento a db dei dati e visualizzo la tabella
    */
    OracleTransaction myTrans = null;

    OracleCommand cmd = new OracleCommand("INSERT INTO ZTMP_SAM_TB_ELAB_PDR(facilityid,taxid,plantcode,ca_pdr, fullmeterkey_m1, corrmeterid_m1, " +
    "stopreading_m1, corrstopreading_m1,fullmeterkey_m2, corrmeterid_m2, " +
    "stopreading_m2, corrstopreading_m2, stopreadtime_m1,stopreadtime_m2,uidbatchrequest) " +
    "  VALUES (:1,:2,:3,:4,:5,:6,:7,:8,:9,:10,:11,:12,:13,:14,:15)", connection);
    //myTrans = connection.BeginTransaction();
    //cmd.Transaction = myTrans;
    /*
    ( :facilityid,:taxid,
    :plantcode,:capdr,:fullmetkeym2,
    :corrmetidm2,:stopreadingm2,
    :corrstopreadm2,:fullmetkeym1,
    :corrmetidm1,:stopreadingm1,:corrstopreadm1,
    :stopreadtimem2,:stopreadtimem1)
    */
    using (System.IO.StreamReader file2 =
    new System.IO.StreamReader(path+FileUpload1.FileName))
    {
    //System.IO.StreamReader file2 = new System.IO.StreamReader(path+FileUpload1.FileName);
    try
    {
    while((line = file2.ReadLine()) != null)
    {
       string[] split = line.Split(',');

       cmd.Parameters.Add("1", OracleType.VarChar, 64).Value = split[0];
       cmd.Parameters.Add("2", OracleType.VarChar, 64).Value = "";
       cmd.Parameters.Add("3", OracleType.VarChar, 64).Value = "";
       cmd.Parameters.Add("4", OracleType.Number).Value = Convert.ToInt32(split[1]);
       cmd.Parameters.Add("5", OracleType.VarChar, 64).Value = split[6];
       cmd.Parameters.Add("6", OracleType.VarChar, 64).Value = split[7];
       cmd.Parameters.Add("7", OracleType.Number).Value = Convert.ToInt32(split[8]);
       cmd.Parameters.Add("8", OracleType.Number).Value = Convert.ToInt32(split[9]);
       cmd.Parameters.Add("9", OracleType.VarChar, 80).Value = split[2];
       cmd.Parameters.Add("10", OracleType.VarChar, 80).Value = split[3];
       cmd.Parameters.Add("11", OracleType.Number).Value = Convert.ToInt32(split[4]);
       cmd.Parameters.Add("12", OracleType.Number).Value = Convert.ToInt32(split[5]);
       DateTime date1,date2;

       DateTime.TryParseExact(split[10], "dd/MM/yyyy", null, System.Globalization.DateTimeStyles.None, out date1);
       DateTime.TryParseExact(split[11], "dd/MM/yyyy", null, System.Globalization.DateTimeStyles.None, out date2);

       cmd.Parameters.Add("13", OracleType.DateTime).Value = date1;
       cmd.Parameters.Add("14", OracleType.DateTime).Value = date2;
       cmd.Parameters.Add("15", OracleType.Number).Value = sequenceVal;

       cmd.ExecuteNonQuery();

       /*Per ogni elemento esegui l'insert*/
    }
    //myTrans.Commit();
    }
    catch(Exception ex){

      //myTrans.Rollback();
      Label1.Text = ex.Message;
      return;
    //"Si e' verificato un errore nell'inserimento dei dati nella tabella ZTMP_SAM_TB_ELAB_PDR";
    }

    file2.Close();
    }

  }

A:

You can do two things to solve this

Save file with timestamp in name and work on that copy
Use File.ReadLine method if file is CSV.


Q:

Trying to implement a function to delete a struct in a linked list while assigning the struct before it to point to the struct after it

I understand that there are better ways to do what I'm attempting, but this is a question in a book that I'm using to learn C++ and it will help me grasp some of the fundamentals before I move on. Anyway, here is my code:
#include <iostream>

using namespace std;

struct EnemySpaceShip
{
    int weapon_power;
    int xcoord;
    int ycoord;
    EnemySpaceShip *nextEnemy;
};

EnemySpaceShip* getNewEnemy(EnemySpaceShip* p_enemies) // Creates a new EnemySpaceShip in linked list p_enemies
{
    EnemySpaceShip *p_ship = new EnemySpaceShip;
    p_ship->xcoord = 0;
    p_ship->ycoord = 0;
    p_ship->weapon_power = 10;
    p_ship->nextEnemy = p_enemies;
    p_enemies = p_ship;
    return p_ship;
}

EnemySpaceShip* findPreRemove(EnemySpaceShip* p_enemies, int x_attack, int y_attack) // finds the element that is before the ship to be removed or returns NULL
{
    EnemySpaceShip *p_current = p_enemies;
    EnemySpaceShip *initialShip = p_enemies;
    int i= 0;
    while (p_current != NULL)
    {
        i++;
        if (p_current->xcoord == x_attack && p_current->ycoord == y_attack)
        {
            if (i == 1)
            {
                delete initialShip;
                delete p_current;
                return NULL;
            }
            else
            {
                for (int j = 1; j < i - 1; j++)
                {
                    initialShip = initialShip->nextEnemy;
                }
                delete p_current;
                return initialShip;
            }
        }
        p_current = p_current->nextEnemy;
    }
    return NULL;
}

EnemySpaceShip* findRemove(EnemySpaceShip* p_enemies, int x_attack, int y_attack)
{
    EnemySpaceShip *p_current = p_enemies;
    while (p_current != NULL)
    {
        if (p_current->xcoord == x_attack && p_current->ycoord == y_attack)
        {
            return p_current;
        }
        p_current = p_current->nextEnemy;
    }
}

EnemySpaceShip* removeEnemyShip(EnemySpaceShip *p_ship) // deletes the ship parameter and returns the ship after it in the list
{
    EnemySpaceShip *enemyAfterRemove = new EnemySpaceShip;
    enemyAfterRemove = p_ship->nextEnemy;
    delete p_ship;
    return enemyAfterRemove;
}

int main()
{
    EnemySpaceShip *p_enemies = NULL;
    EnemySpaceShip *Ship1 = getNewEnemy(p_enemies);
    EnemySpaceShip *Ship2 = getNewEnemy(p_enemies);
    EnemySpaceShip *Ship3 = getNewEnemy(p_enemies);

    Ship3->xcoord = 5; //arbitrary numbers to test the code
    Ship3->ycoord = 5;

    EnemySpaceShip *ShipBeforeRemove = findPreRemove(p_enemies, 5, 5);
    EnemySpaceShip *ShipToRemove = findRemove(p_enemies, 5, 5);
    ShipBeforeRemove->nextEnemy = removeEnemyShip(ShipToRemove);
}

I'm using arbitrary values to test the program, I don't need to fully implement this as a functionality for the game that it is apparently being used for. Any help is much appreciated.

A:

I hope following is what you want.. Removing an element from a singly linked list..
EnemySpaceShip* removeFromList(EnemySpaceShip* p_enemies, int x_attack, int y_attack)
{
    if(p_enemies == NULL)
        return NULL;

    EnemySpaceShip *p1 = p_enemies;
    EnemySpaceShip *p2 = p1->next;

    if(p2 == NULL)
    {
        // Trivial case..

        if(p1->xcoord == x_attack && p1->ycoord == y_attack)
        {
            delete p_enemies;
            p_enemies = NULL;
        }

        return NULL;
    }

    while(p2 != NULL)
    {
         if(p2->xcoord == x_attack && p2->ycoord == y_attack)
         {
             // Element found, remove it and assign its previous pointer
             // as the next pointer of the deleted one..
             p1->next = p2->next;
             delete p2;
             return p1;
         }
         else
         {
             p1 = p2;
             p2 = p2->next;
         }
    }

    return NULL;

}


Q:

Is there a way for me to access the Account Class Objects from the List after comparison in Python3

I am using Python3 , I am planning to create a application that takes number of accounts from user and a bank. I am taking account name and number from user and storing it in a collection (List). How am i supposed to compare the attributes of that object or delete that object by taking account number from user?
This is my code:
class Account:

    def __init__(self):
        print("Enter the account name")
        self.account_name = input()
        print("Enter the account no")
        self.account_num = int(input())
        # print("Enter the balance")
        self.balance = 0

    def __str__(self):
        return f"{self.account_name,self.account_num,self.balance}"

class Bank:

    def __init__(self):
        print("Enter Bank Name")
        self.bname = input()
        print("Enter Bank Branch")
        self.branch = input()
        self.account_list = []
        # self.transfer_balance(13)

    def get_AccountList(self):
        print("Enter Account Details")
        self.account_list.append(Account())

    def delete_acccount(self, num):
        del self.account_list[num]

    def print_bank_details(self):
        print(f"Name of the Bank : {self.bname}")
        print(f"The name of the branch is : {self.branch}")

        for i in range(1, len(self.account_list)):
            print(f"Id : {i}---> {self.account_list[i]}")

def function():

    account_obj = []
    ans=True
    bank1 = Bank()
    while ans:
        print ("""
        1. Accept User Account INfo
        2. Print Account INfo
        3. Delete the account by Number
        4. Print Bank Info
        """)
        print("What would you like to do? ")

        ans=input()
        if ans == "1":
            print("\n Enter The Account Details")
            bank1.get_AccountList()
        elif ans == "2":
            print("\n Print Acccount info in the bank")
            bank1.print_bank_details()
        elif ans == "3":
            print("\n Enter the ID of the account to be deleted")
            num= int(input())
            bank1.delete_acccount(num)
        elif ans == "4":
            print("\n Goodbye")
        elif ans != "":
            print("\n Not Valid Choice Try again")

function()

A:

Comparing each object's account number is the only option. Go through the delete_account function, I have coded the solution. Also, there was a bug in print_bank_details function. It wasn't printing the first account details, I have fixed this one as well.
class Account:

    def __init__(self):
        print("Enter the account name")
        self.account_name = input()
        print("Enter the account no")
        self.account_num = int(input())
        # print("Enter the balance")
        self.balance = 0

    def __str__(self):
        return f"{self.account_name,self.account_num,self.balance}"

class Bank:

    def __init__(self):
        print("Enter Bank Name")
        self.bname = input()
        print("Enter Bank Branch")
        self.branch = input()
        self.account_list = []
        # self.transfer_balance(13)

    def get_AccountList(self):
        print("Enter Account Details")
        self.account_list.append(Account())

    def delete_acccount(self, num):
        for account in self.account_list:
          if account.account_num == num:
            self.account_list.remove(account)
            return True
        print("Account number was not found")

    def print_bank_details(self):
        print(f"Name of the Bank : {self.bname}")
        print(f"The name of the branch is : {self.branch}")

        for i in range(0, len(self.account_list)):
            print(f"Id : {i+1}---> {self.account_list[i]}")

def function():

    account_obj = []
    ans=True
    bank1 = Bank()
    while ans:
        print ("""
        1. Accept User Account INfo
        2. Print Account INfo
        3. Delete the account by Number
        4. Print Bank Info
        """)
        print("What would you like to do? ")

        ans=input()
        if ans == "1":
            print("\n Enter The Account Details")
            bank1.get_AccountList()
        elif ans == "2":
            print("\n Print Acccount info in the bank")
            bank1.print_bank_details()
        elif ans == "3":
            print("\n Enter the ID of the account to be deleted")
            num= int(input())
            bank1.delete_acccount(num)
        elif ans == "4":
            print("\n Goodbye")
        elif ans != "":
            print("\n Not Valid Choice Try again")

function()


Q:

java.net.InetSocketAddress and java.net.SocketAddress Support IPv6?

Do java.net.InetSocketAddress and java.net.SocketAddress support IPv6?
Because the two classes that i have research and try it couldnt able me to view ipv6 connection it only able to view ipv4 connection anyone there have try and able to do the editing of the code?

A:

A partial answer to your question, even though it may come too late to be of immediate use =).
I had the following lines of code attempt to connect to two different IP addresses:
// Defined port must be 13; that is NIST's default listening port.
SocketAddress socketAddress = new InetSocketAddress(currentIpAddress, 13);
socket = new Socket();
socket.connect(socketAddress, nistServerTimeoutInMilliseconds);

The first address works fine : '206.246.122.250'
The second address throws a 'java.net.SocketException: Protocol family unavailable' on the third line. That address is '2610:20:6F15:15::27'.
I thought at first that the problem was that IPv6 is not supported by InetSocketAddress in Java 1.7, but I found out that there are actually two classes that inherit from the InetAddress class in Java: Inet4Address and Inet6Address
http://docs.oracle.com/javase/6/docs/api/java/net/Inet4Address.html
http://docs.oracle.com/javase/7/docs/api/java/net/Inet6Address.html
This explains why my code, when trying to construct an Inet4Address using an IPv6 format was failing, and it may explain your issue as well.
Hope this helps =)
P.S. InetAddress and InetSocketAddress aren't the same class, but by testing for the kind of IP address you're dealing with, there may be a way to get around the problem.


Q:

Android: button with two background colors

I want to make a button style on Android with two background colors, such as the following image:
http://i.stack.imgur.com/ExKXl.png
Is it possible to make with drawable resources? I´ve being searching for a solution on http://developer.android.com/guide/topics/resources/drawable-resource.html but none of them can have two colors.
Is there a way?
[editing the answer]
The solution was to create a <layer-list> with items and each <item> has one <shape>. The code is bellow (the entire button has 32dp height so I used half-height for each color):
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

    <!-- Top color -->
    <item android:bottom="16dp">
        <shape android:shape="rectangle">
            <solid android:color="#FF0000" /> <!-- RED -->
        </shape>
    </item>

    <!-- Bottom color -->
    <item android:top="16dp">
        <shape android:shape="rectangle">
            <solid android:color="#00FF00" /> <!-- GREEN -->
        </shape>
    </item>
</layer-list>

But I had another issue, I was trying to put corners on each shape. I tried to put android:topLeftRadius and android:topRightRadius on the first shape and android:bottomLeftRadius and android:bottomRightRadius on the second shape but it didn´t show me the corners! So the solution was to use android:radius (all the 8 corners became rounded, dammit!) and put another two items to overcome the extra corners. At the end the XML has like that:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

    <!-- Top color with corner -->
    <item android:bottom="16dp">
        <shape android:shape="rectangle">
            <corners android:radius="5dp" /> <!-- It´s obligatory, It didn´t work only with android:topLeftRadius and android:topRightRadius -->
            <solid android:color="#FF0000" /> <!-- RED Color-->
        </shape>
    </item>

    <!-- Takes off the center corner -->
    <item android:top="8dp" android:bottom="8dp">
        <shape android:shape="rectangle">
            <solid android:color="#FF0000" /> <!-- RED Color-->
        </shape>
    </item>

    <!-- Bottom color with corner -->
    <item android:top="16dp">
        <shape android:shape="rectangle">
            <corners android:radius="5dp" /> <!-- It´s obligatory, It didn´t work only with android:bottomLeftRadius and android:bottomRightRadius -->
            <solid android:color="#00FF00" /> <!--  GREEN Color -->
        </shape>
    </item>

    <!-- Takes off the center corner -->
    <item android:top="16dp" android:bottom="8dp">
        <shape android:shape="rectangle">
            <solid android:color="#00FF00" /> <!--  GREEN Color -->
        </shape>
    </item>

</layer-list>

It is working now, thanks you all!

A:

Possible Duplicate: banded background with two colors?
In which a provided answer using Java:
Bitmap bmResult = Bitmap.createBitmap(buttonWidth, buttonHeight, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bmResult);
    Paint paint = new Paint();
    paint.setShader(new LinearGradient (0, 0, 0, bmResult.getHeight()/2, 0xFF284560, 0xFF284060, TileMode.MIRROR));
    canvas.drawPaint(paint);
    paint.setShader(new LinearGradient (0, 0, 0, bmResult.getHeight()/2, 0x55FFFFFF, 0x22FFFFFF, TileMode.CLAMP));
    paint.setMaskFilter(new BlurMaskFilter(3, BlurMaskFilter.Blur.NORMAL));
    canvas.drawRect(0, 0, bmResult.getWidth(), bmResult.getHeight()/2, paint)

was lifted from another SO post on the same topic: Gradients and shadows on buttons
And the accepted solution using an XML drawable:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:bottom="20dp">
        <shape android:shape="rectangle" >
            <size android:height="20dp" />
            <solid android:color="#ff0000" />
        </shape>
    </item>

    <item android:top="20dp">
        <shape android:shape="rectangle" >
            <size android:height="20dp" />
            <solid android:color="#0000ff" />
        </shape>
    </item>
</layer-list>

And as others have said:
You can create a 9patch image which would be the most resourceful.

A:

I think the easiest way is to create your background using a drawing software.


Q:

Change Android's spinner dialog background on 'dropdown' mode

HOw can I change it? The android:popupBackground property's doc says:

Background drawable to use for the dropdown in
   spinnerMode="dropdown". [reference, color]

But setting this property has no effect.

A:

Have you declared in the xml that android:spinnerMode = "dropdown" ?
If not, do it. Then try again to change android:popupBackground. :)
Links
http://developer.android.com/reference/android/widget/Spinner.html
http://developer.android.com/reference/android/widget/Spinner.html#attr_android:popupBackground


Q:

Ensure that ICommand implementation properly uses weak references

I am building an implementation of System.Windows.Input.ICommand that is like the commonly used RelayCommand, but doesn't keep a strong reference to targets of the delegates it uses. Such a structure is useful for when a control wants to expose some of its functionality as a command (which can be assigned to a ViewModel). Using a traditional RelayCommand would cause a memory leak, because the RelayCommand would contain strong references to the delegates that it runs, which in turn contain strong references to the control. Here is the code:
public class WeakRelayCommand : ICommand
{
    public WeakRelayCommand(Action<object> executeCallback, Func<object, bool> canExecuteCallback = null)
    {
        ExecuteTargetReference = new WeakReference<object>(executeCallback.Target);
        if (canExecuteCallback != null)
            CanExecuteTargetReference = new WeakReference<object>(canExecuteCallback.Target);
        ExecuteCallbackInfo = executeCallback.GetMethodInfo();
        CanExecuteCallbackInfo = canExecuteCallback?.GetMethodInfo();
    }

    private WeakReference<object> ExecuteTargetReference;
    private WeakReference<object> CanExecuteTargetReference;
    private MethodInfo ExecuteCallbackInfo;
    private MethodInfo CanExecuteCallbackInfo;

    public event EventHandler CanExecuteChanged;

    public bool CanExecute(object parameter)
    {
        if (CanExecuteCallbackInfo == null)
            return true;
        object canExecuteTarget = null;
        if (CanExecuteTargetReference?.TryGetTarget(out canExecuteTarget) ?? false)
        {
            return (bool)CanExecuteCallbackInfo.Invoke(canExecuteTarget, new[] { parameter });
        }
        else
            return false; //Target of the delegate for CanExecute has been garbage collected
    }

    public void Execute(object parameter)
    {
        object executeTarget = null;
        if (ExecuteTargetReference?.TryGetTarget(out executeTarget) ?? false)
        {
            ExecuteCallbackInfo.Invoke(executeTarget, new[] { parameter });
        }
        //Cannot execute the command if the target of the Execute delegate has been garbage collected
    }

    public void RaiseCanExecuteChanged()
    {
        CanExecuteChanged?.Invoke(this, EventArgs.Empty);
    }
}

The basic summary is that instead of holding strong references to delegates, which in turn hold strong references to the delegates' targets of invocation, it instead holds a reference to the MethodInfo associated with the actual method of the delegate, and holds a WeakReference to the targets of invocation separately from the method. This way, the targets of invocation are free to be garbage collected by the garbage collector.
I have tested this implementation and it works just fine as an implementation of ICommand, and it appears to properly use WeakReferences to achieve my objective. Can I get a verification that this is in fact the case?

A:

The implementation works fine if the passed delegate is an instance method, because that prevents the method from being garbage collected.
But that is not necessarily the case. Lambda expression, for instance, will be garbage collected sometime because they are not referenced somewhere else.
That may result in strange not reproducible bugs that are hard to debug.
The following code (with a simplified version of the WeakRelayCommand class) shows that the weak reference approach does not work for static methods and lambda expressions with closures.
void Main()
{
    var longLiveObject = new DummyObject();
    var commands = GetActions(longLiveObject);

    GC.Collect();
    GC.WaitForPendingFinalizers();

    foreach (var command in commands)
        Console.WriteLine(command.Name + "\t IsAlive:" + command.IsAlive);
}

private static WeakAction[] GetActions(DummyObject longLiveObject)
{
    var localObj = new DummyObject();
    return new []
    {
        new WeakAction("InstanceMethod (short living)", localObj.InstanceMethod),
        new WeakAction("InstanceMethod (long living)", longLiveObject.InstanceMethod),
        new WeakAction("StaticMethod", DummyObject.StaticMethod),
        new WeakAction("LamdaExpression (without closure)", o => { }),
        new WeakAction("LamdaExpression (with closure)", o => localObj.InstanceMethod(o)),
    };
}

// Define other methods and classes here
public class DummyObject
{
    public void InstanceMethod(object obj) { }
    public static void StaticMethod(object obj) {}
}

public class WeakAction
{
    private readonly WeakReference<object> _targetReference;
    private readonly MethodInfo _callbackInfo;

    public WeakAction(string name, Action<object> executeCallback)
    {
        Name = name;
        _targetReference = new WeakReference<object>(executeCallback.Target);
        _callbackInfo = executeCallback.GetMethodInfo();
    }

    public string Name { get; }
    public bool IsAlive
    {
        get
        {
            object obj;
            return _targetReference.TryGetTarget(out obj);
        }
    }
}

Output:
InstanceMethod (short living)        IsAlive:False
InstanceMethod (long living)         IsAlive:True
StaticMethod                        IsAlive:False
LamdaExpression (without closure)   IsAlive:True
LamdaExpression (with closure)      IsAlive:False


Q:

Choosing a size for a buffer

I'm confused, when allocating memory with malloc you have to provide a size, however, it sometimes happen that you don't know the size you need at that point so you either alloc a huge amount of memory (which doesn't sound too wise since you're probably not going to use it all) or you use realloc when the initial buffer size becomes too small. Are this two options valid? The second one sounds good, however, the docs say that realloc ...may move the memory block to a new location which sounds like a very bad idea/hard to handle situation (e.g. if you have multiple pointers pointing to the same address the moment you call realloc they all become invalid) I'm a beginner with C, can somebody explain me how to handle the situation in which you have a buffer that may or may not grow to occupy a lot of memory.

A:

it sometimes happen that you don't know the size you need at that point so you either alloc a huge amount of memory (which doesn't sound too wise since you're probably not going to use it all) or you use realloc when the initial buffer size becomes too small. Are this two options valid?

In principle yes. In practice, with modern OS kernels and default system configurations it doesn't matter how much you allocate with malloc. You see, malloc allocates address space, not memory. You can allocate as much address space as you want it will not actually consume memory; of course the OS will employ several sanity checks on the value, for example on a system with only 2GiB memory available (RAM + swap) you can't allocate 3GiB. The usual configuration is that the largest chunk of address space allocatable in a single chunk is 50% of the available system memory.
Only when you actually write something to it, the OS will reserve memory for it. So don't use calloc, because it initializes memory with, i.e. write something into it.
So if you don't know how much exactly you'll need, just malloc a big chunk of address space, for which you know, by the characteristics of the kind of data processed, that it will easily hold whatever you're expecting. Once you've got it in memory, you can use realloc to shrink the allocation. For all implemantations that matter realloc will never move data when shrinking an allocation.
One thing to be aware of is memory overcommitment: Say you got 5 processes running on a system with 4GiB RAM, each allocation 1GiB, but not immediately writing to it. The OS will give them this address space, i.e. it overcommits memory (just like airlines overcommit flight seats). Some time later the processes start writing to it. At some point the system runs out of memory and the OS has to do something about it: It will start killing processes until there's again room to "breathe".
You can switch off memory overcommitment though; strongly recommended on high reliability systems.

A:

You're right - those are pretty much your two choices.  You can work around the "multiple pointers" problem by abstracting a bit.  If instead of passing around the pointer returned by malloc directly, you stick it into another data structure:
struct malloc_wrapper
{
    void *p;
} wrapper;

wrapper.p = malloc(INITIAL_SIZE);

And pass pointers to that data structure around instead, you can change p at any time, and anybody who shares the pointer to your new structure will be updated accordingly:
void *tmp = realloc(somepointertowrapper->p, NEW_SIZE);

/* check tmp to ensure it's not NULL. That indicates a failure
 * to realloc and the original pointer passed into realloc
 * remains valid.
 */

somepointertowrapper->p = tmp;


Q:

asp.net membership login with alternate password

I am making an ASP.NET application and using ASP.NET membership controls for users to login. I want user can login using his normal password or a quick login (which allows user to create a 4 digit password similar to ATM PIN) for a quick login experience.  How do I achieve this?

A:

You need to extend the basic membership provider and use it. Here is a start point.
public class DoublePasswordProvider : SqlMembershipProvider
{
    public override bool ValidateUser(string username, string password)
    {
        if (checkPIN(username, password)) return true;
        return base.ValidateUser(username, password);
    }
}

Then edit we.config to use it:
<membership defaultProvider="DoublePasswordProvider">
      <providers>

        <add name="DoublePasswordProvider" type="YourNamespace.DoublePasswordProvider" connectionStringName="ApplicationServices"
             enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"
             maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"
             applicationName="/" />
      </providers>
    </membership>

Finally use standard asp.net controls (login, change password, bla bla)


Q:

InputStream is = App.class.getResourceAsStream("test.properties");

the returned InputStream is null. What will be the possible cause?

A:

App.class.getResourceAsStream(resource) searches for the resource in the same hierarchy as the class (so if your App class is in package com.yourcompany, this would search for the resource com/yourcompany/test.properties). In your situation you either have to prepend a slash or use the classloader instead of the class:
a)
App.class.getResourceAsStream("/test.properties")

b)
App.class.getClassLoader().getResourceAsStream("test.properties")

A:

The "actual dir" is in the folder/package your class is in. Correct usage:
InputStream is = App.class.getResourceAsStream(“../../test.properties”);

Or maybe:
InputStream is = App.class.getResourceAsStream(“/test.properties”);


Q:

Deploying a driver fails in VS 2019

Trying to experiment a bit with KMDF and the echo driver fails to deploy:
A[13:22:28:862]: An error occured while deploying files to the target machine for test "Driver Preparation": Could not find a part of the path 'C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Redist\MSVC\14.21.27702\debug_nonredist\X64\Microsoft.VC141.DebugCRT'..

Why does it try to find Microsoft.VC141.DebugCRT. I have Microsoft.VC142.DebugCRT installed with the newer toolset along with 10.0.18362.0 SDK.
I also installed the VS 2017 toolset and now the same error:
C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Redist\MSVC\14.21.27702\debug_nonredist\X64\Microsoft.VC141.DebugCRT missing.
But it should look into ...\14.16.27012.. instead.

A:

I've been getting the same error. I've tried uninstalling/reinstalling also tried 2017 as well. I uninstalled everything and reinstalled everything with no luck. I even tried installing VC141.
I acutally came to your post looking for an answer but on a whim I opened the installer, modified it to install the VC141 stuff which put the files into Community\VC\Redist\MSVC\14.16.27012\debug_nonredist\x64
VS still complained so i just copied * from Community\VC\Redist\MSVC\14.16.27012\debug_nonredist\x64 into Community\VC\Redist\MSVC\14.21.27702\debug_nonredist\x64 and "things seem to work". It's not much of an answer - but maybe it's good enough?


Q:

How to hide JSON data by creating a div

In order to hide the JSON data (so that it can be faded in later), I modified the a1.start function by creating div called "loading," but in the Javascript Console in Chrome, there is

Uncaught SyntaxError: Unexpected token ILLEGAL

in the HTML:  a1.start($("#cakeHook"),"a1data.json");
<!doctype html>

    <title>Cake Baby Bakery</title>

    <link href="css/bootstrap.css" rel="stylesheet"/>
    <link href="css/basica1.css" rel="stylesheet"/>

a1.start
a1.start = function(hookElementSelection, dataurlForJsonFile) {

jQuery('
', {
id: 'loading',
text: 'Loading...'
}).appendTo('hookElementSelection');

$('hookElementSelection).hide();

    a1.products = {};
    a1.recipes = {};
    a1.suppliers = {};
    a1.bakedRecipes = [];

    //make an ajax call and wait for success
    $.ajax({url:dataurlForJsonFile}).success(function(data) {

        //get the recipe data
        parseJSONData(data);

        //put the recipes on the page
        $.each(a1.recipes, function(i, recipe) {
            recipe.render(hookElementSelection);
        });
        renderCalculator(hookElementSelection); //add in the final calculation logic
    });
};

A:

When you try to use the variable, you are using a string instead:
.appendTo('hookElementSelection')

should be:
.appendTo(hookElementSelection)

Then you have an unterminated string when you try to use the variable again:
$('hookElementSelection).hide();

should be:
hookElementSelection.hide();


Q:

Prevent alert tone when scanning / identifying an NFC intent

Perhaps I'm missing something but when I scan an NFC tag via a galaxy nexus, the phone always makes the default alert tone.
Is there a way of programmatically switching this off ? I have scoured the menus / preferences and can't find a way of doing this. The next step ... ICS source code :-/

A:

with android-19 you can:
as described in:
http://developer.android.com/reference/android/nfc/NfcAdapter.html#FLAG_READER_NO_PLATFORM_SOUNDS
By using NfcAdapter.enableReaderMode() and the flag FLAG_READER_NO_PLATFORM_SOUNDS instead of NfcAdapter.enableForegroundDispatch()

A:

Here is a simple example of how to silence/change nfc sounds
public class MainActivity extends Activity implements ReaderCallback{
private NfcAdapter mNfcAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
}

@Override
public void onResume() {
    super.onResume();
    // This example works using using simple mifare ultralight tags. Set any necessary flags for other tags
    mNfcAdapter.enableReaderMode(this, this, NfcAdapter.FLAG_READER_NFC_A | NfcAdapter.FLAG_READER_NO_PLATFORM_SOUNDS, null);
}

@Override
public void onPause() {
    super.onPause();
    mNfcAdapter.disableReaderMode(this);
}

@Override
public void onTagDiscovered(Tag tag) {
    // Play your own sound here

    // Then handle your tag
}

}

A:

There isn't a way to pro grammatically turn this sound off or to override the Touch to Beam UI.


Q:

Email Alerts/Logs when Azure Container Instance Succeeds/Fails

Is there any way to setup email alerts for when individual Azure Container Instances succeed or fail (or basically change state)? I have some run-once containers I kick off periodically, and would like to be notified when they complete and the status of the completion. Bonus if the email can include logs from the container, as well. Is this possible using the built-in alerts?
So far I haven't been able to make it work with the provided signals.

A:

Dont believe there is an automatic way so what I did was created a small timer based function that runs every 5 minutes and gets a list of all containers and checks the status. If any are in say a failed state it then uses SendGrid to sent an alert email.
UPDATE for Dan
I use Managed Service Identity in my function so I have a container tasks class like the below, can't remember exactly where I got the help to generate the GetAzure function as obviously when doing local debug you can't use the MSI credentials and the local account on Visual Studio that is meant to work doesn't appear to. However I think it might have been here - https://github.com/Azure/azure-sdk-for-net/issues/4968
public static class ContainerTasks
{
    private static readonly IAzure azure = GetAzure();

    private static IAzure GetAzure()
    {
        var tenantId = Environment.GetEnvironmentVariable("DevLocalDbgTenantId");
        var clientId = Environment.GetEnvironmentVariable("DevLocalDbgClientId");
        var clientSecret = Environment.GetEnvironmentVariable("DevLocalDbgClientSecret");
        AzureCredentials credentials;

        if (!string.IsNullOrEmpty(tenantId) &&
            !string.IsNullOrEmpty(clientId) &&
            !string.IsNullOrEmpty(clientSecret))
        {
            var sp = new ServicePrincipalLoginInformation
            {
                ClientId = clientId,
                ClientSecret = clientSecret
            };
            credentials = new AzureCredentials(sp, tenantId, AzureEnvironment.AzureGlobalCloud);
        }
        else
        {
            credentials = SdkContext
                .AzureCredentialsFactory
                .FromMSI(new MSILoginInformation(MSIResourceType.AppService), AzureEnvironment.AzureGlobalCloud);
        }
        var authenticatedAzure = Azure
            .Configure()
            .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
            .Authenticate(credentials);
        var subscriptionId = Environment.GetEnvironmentVariable("DevLocalDbgSubscriptionId");
        if (!string.IsNullOrEmpty(subscriptionId))
            return authenticatedAzure.WithSubscription(subscriptionId);
        return authenticatedAzure.WithDefaultSubscription();
    }

    public static IEnumerable<IContainerGroup> ListTaskContainers(string resourceGroupName, ILogger log)
    {
        log.LogInformation($"Getting a list of all container groups in Resource Group '{resourceGroupName}'");

        return azure.ContainerGroups.ListByResourceGroup(resourceGroupName);
    }
}

Then my monitor function is simply
public static class MonitorACIs
{
    [FunctionName("MonitorACIs")]
    public static void Run([TimerTrigger("%TimerSchedule%")]TimerInfo myTimer, ILogger log)
    {
        log.LogInformation($"MonitorACIs Timer trigger function executed at: {DateTime.Now}");
        foreach(var containerGroup in ContainerTasks.ListTaskContainers(Environment.GetEnvironmentVariable("ResourceGroupName"), log))
        {
            if(String.Equals(containerGroup.State, "Failed"))
            {
                log.LogInformation($"Container Group {containerGroup.Name} has failed please investigate");
                Notifications.FailedTaskACI(containerGroup.Name, log);
            }
        }
    }
}

Notifications.FailedTaskACI is just a class method that sends an email to one of our Teams channels
It's not perfect but it does the job for now!


Q:

regex for finding date dir

i am looking to search for  in dir ...
a2010-02-10
how to search the ls all dir in with date format
ls -d *(\d+)-(\d+)-(\d+)

its not working like perl
what is the right format

A:

Your regex appears to be correct, but bash doesn't support full regular expressions.  It supports wildcards, which can't always work the same way.  Try this:
ls -d | grep -E '(\d+)-(\d+)-(\d+)$'

And really, the (\d+) groups could be replaced with just \d+.
If you prefer a pure-bash solution, try this:
ls -d *[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]

You can simplify that to be less exact if desired:
ls -d *[0-9]*-[0-9]*-[0-9]*

But I'd go for using grep because it is a lot clearer what you want.  You could make it even clearer:
ls -d | grep -E '\d{4}-\d{2}-\d{2}$'


Q:

What will parse do to the deleted PFFile?

I uploaded a PFFile to Parse.com, and saved the url of the PFFile. Then I deleted the PFFile, and tried using the saved url to download the PFFile. It's success!
So my question is: What will Parse.com do to the deleted PFFile? Is the PFFile being saved permanently or will be deleted in some time?

A:

According to this question/answer there is no way to permanently delete these files without doing it manually or through the REST API: https://www.parse.com/questions/deleting-pffiles
The 2 ways you can do it are:

Go to the "Clean up Files" (Settings/Clean up Files) button on your app's dashboard to delete all of the files.
Use the REST API:
curl -X DELETE \
        -H "X-Parse-Application-Id: " \
        -H "X-Parse-Master-Key: " \
        https://api.parse.com/1/files/

The last option is only good for deleting one file, so the first choice looks like the best here. It's unfortunate that you cannot do this using the SDK, but it is a good security measure as Files do not have ACLs.


Q:

How to uninstall program, which was installed via ./

I'm using 14.04 LTS.
Installed programm is truecrypt-6.3a-setup-ubuntu-x86
I installed via following command
sudo ./truecrypt-6.3a-setup-ubuntu-x86

Ubuntu software center doesn't show me installed truecrypt
None of
sudo apt-get remove truecrypt
sudo dkpg --remove truecrypt

works.
It shows me that truecrypt doesn't installed.
apt-cache pkgnames | grep true

returns none of either truecrypt or something similar
Well, it probably should go, but I cannot find /usr/bin/truecrypt-uninstall.sh as well as usr/share/truecrypt-uninstall.shsearchmonkey returns zero of truecrypt except truecrypt.mod and downloaded files
What can I do?

A:

Open the terminal and type:
which truecrypt

The results will be something like:
/usr/bin/truecrypt

If you see the above results run the following commands to uninstall TrueCrypt manually:
sudo -i
rm -f /usr/bin/truecrypt
rm -f /usr/share/truecrypt/doc/License.txt
rm -f '/usr/share/truecrypt/doc/TrueCrypt User Guide.pdf'
rm -f /usr/share/applications/truecrypt.desktop
rm -f /usr/share/pixmaps/truecrypt.xpm
rm -rf /usr/share/truecrypt/doc /usr/share/truecrypt
rm -f /usr/bin/truecrypt-uninstall.sh