text:
Q: Upgrade to MsTest V2 no longer sees my test projects I have several unit test projects, using the old built in Microsoft.VisualStudio.QualityTools.UnitTestFramework reference in my project.  recently I decided to remove that and install the MsTest V2 nuget package instead.  Everything compiles, but now none of my tests are recognized.  No other code changes were made.  I can see in my project the references:
<Import Project="..\packages\MSTest.TestAdapter.1.2.0\build\net45\MSTest.TestAdapter.props" Condition="Exists('..\packages\MSTest.TestAdapter.1.2.0\build\net45\MSTest.TestAdapter.props')" />

and
<Reference Include="Microsoft.VisualStudio.TestPlatform.TestFramework, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
      <HintPath>..\packages\MSTest.TestFramework.1.2.0\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
      <HintPath>..\packages\MSTest.TestFramework.1.2.0\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions.dll</HintPath>
    </Reference>

any ideas why this would happen/break?

A: Looks like you still have the old Test Adapter, you should have:
<Import Project="..\packages\MSTest.TestAdapter.**2.0.0**\build\net45\MSTest.TestAdapter.targets" Condition="Exists('..\packages\MSTest.TestAdapter.2.0.0\build\net45\MSTest.TestAdapter.targets')" />

You have 1.2. Make sure you added both the MSTest.TestFramework and MSTest.TestAdapter nuget packages to your test project


text:
Q: Is having the same part number enough for the LCD cable to be compatible? Laptop I've got is Acer 5551-a.
I need to replace the LCD cable, it appears to be broken in one place, screen displays distortions but stops displaying them if one bent part of the cable is moved. I want to get a new one instead of fixing the one I have.
LCD cable part number is DC020010L10 (written on the cable itself) . It also says Rev 2.0 after the name.
part #1 This one does not mention my laptop model or the revision number, and has "C7" added after the part number.
ACER ASPIRE 5742 5742Z 15.6" LED SCREEN VIDEO FLEX CABLE RIBBON DC020010L10 C7

part #2 This one does not mention my laptop model or the revision number.
Display Cable Acer - 50.R4F02.009 Compatible with Aspire 5250 | 5252 |
5253 | 5253G | 5333 | 5336 | 5342 | 5552 | 5552G |
5733 | 5733Z | 5736Z | 5741G | 5742 | 5742G | 5742Z | 5742ZG E Series
E442 | E443 | E529 | E642 | E642G | E644 | E644G | E729 | E729Z EasyNote
TK11 | TK11BZ | TK13 | TK13BZ | TK36 | TK37 | TK81 | TK83 | TK85 | TK87
and part # DC020010L10

Would any of these cables work with my laptop? They have the same part number, but different revision number. And these cables don't list my laptop model under compatible ones.
Thanks!

redpajama_set_name: RedPajamaStackExchange


text:
Q: "Missing or unspecified Language attribute" when importing snippets When importing a directory containing snippets in the Code Snippet Manager in VS2017 (v15.7.5), in the Output pane I get the warning
Missing or unspecified Language attribute
even though a language attribute is present. I even get this when importing Microsofts own snippets. The snippets are for C#.
How to import the snippets?

A: At the top of the Code Snippet Manager there is a dropdown where you have to select the language for which you're importing snippets; if a different language is selected you could get this warning.


text:
Q: column  does not exist (Django 1.8) I am trying to interact with the development server for my django project. However any page on the server returns the same error:
Exception Type: ProgrammingError

Exception Value: column myApp_verb.date does not exist

I had not recently added the field date to the model verb (it's been there for a while, and I'm not sure what caused this error to begin). My collaborators all have identical files on their local machines, and none of them are having any issues.
I have tried various things:
I have tried removing the date field (and all references to it). makemigrations did not detect any changes, and migrate failed with error:
django.db.utils.ProgrammingError: column "date" does not exist
I have tried renaming the field. Once again makemigrations did not detect any changes, and migrate failed with the same error as above.
I have tried deleting all of my migrations. This changed nothing.
I'm out of ideas at this point. Any help would be much appreciated.
Thanks in advance!
Edit: Here is the verb class, as requested. Its pretty simple:
class Verb(models.Model):
    english_gloss = models.CharField(max_length = 20)
    first_person = models.CharField(max_length = 20)
    second_person = models.CharField(max_length = 20)
    third_person = models.CharField(max_length = 20)
    fourth_person = models.CharField(max_length = 20)
    transitivity = models.BooleanField()
    classifier = models.CharField(max_length = 20)
    inner_lexical = models.CharField(max_length = 20)
    outer_lexical = models.CharField(max_length = 20)
    perfective = models.CharField(max_length = 20)
    imperfective = models.CharField(max_length = 20)
    date = models.DateTimeField(auto_now_add = True)

A: You can create a manual migration to fix the issue.
First comment out the coloumn(s) that are throwing the error.
Then write the manual migration. Usually something like this:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('my_field', 'last_migration_filename'), # no .py
    ]

    operations = [
        migrations.AddField(
            model_name='my_model',
            name='my_field',
            field=models.MyField(blank=True, null=True),
        ),
    ]

Then run python manage.py migrate. It will create that/those field(s).
Afterwards, uncomment the fields that cause the errors.
Worked for me like a charm.

A: I still have no idea why this error began, but it appears that there was some sort of corruption in my database. I deactivated the db and started a new one, and everything works perfectly again.

A: Had same problem. I wanted to add field "slug" to City model.
Error gone when I temporary commented line with select_related('city').
for location in Location.objects.filter().select_related('city'):
    cities[str(l.id)] = l.city.id

Stack trace pointed me on that peace of code:
File "/www/loorn/apps/users/widgets.py", line 69, in LocationSelect
    for location in Location.objects.filter().select_related('city'):

A: Fully agree with Özer S.
Yes, this is the only solution to overcome this problem. Dear Django developers, why when trying to add a field to an existing table, Django suddenly responds that such a field does not exist? Of course it does not exist, so I'm trying to add it!
The same solution is for my case - add a field with a multiple choice:

*

*This is what the added field in models.py looks like:
TEMPLATE = (
  ('list', 'List'), ('table', 'Table')
)
template = models.CharField(
    'View template',
    choices=TEMPLATE,
    max_length=7,
    default='list'
)

*Create manually a migration file with the number following the previous migration. I add the "template" field to the "blogcategory" table in the "blog" application and my migration file is called "0005_template".

*And this is the contents of the migration file (0005_template.py):
# -*- coding: utf-8 -*-
from django.db import migrations, models

class Migration(migrations.Migration):
dependencies = [
    ('blog', '0004_auto_20170628_1533'),
]

operations = [
    migrations.AddField(
        model_name='blogcategory',
        name='template',
        field=models.CharField(
            verbose_name='View template',
            choices=[('list', 'List'), ('table', 'Table')],
            max_length=7,
            default='list'
        ),
    ),
]

*Next, comment on these lines in the model:
TEMPLATE = (
  ('list', 'List'), ('table', 'Table')
)
template = models.CharField(
   'View template',
   choices=TEMPLATE,
   max_length=7,
   default='list'
)

*Then, do the application migration in the database:
python manage.py migrate blog

and get
Operations to perform:
    Apply all migrations: blog
Running migrations:
    Applying blog.0005_template... OK

As a result, the "template" field with the default "list" was added to all entries in the "blogcategory" table.
P.S. Do not forget to uncomment the field in the model.

A: I have had this problem. I fixed it by going to the Django migrations table in the database and locating the migration that was faulty. In my case, it was a fairly recent migration. I deleted that migration and the others following it. Then retried running python manage.py makemigrations and python manage.py migrate. This time both commands ran and the error went away.

A: You can usually get around this type of error by "tricking" django into thinking the column exists while generating the migration.

*

*create a new database column with the same name manually in your local db

*run python manage.py makemigrations to generate the correct migration

*delete the column you created earlier

*run python manage.py migrate 'appname' to create the new column


text:
Q: remove text followed by text "Edit" inside a tag
Edit Site Update Site Update

In the above code, how to remove text followed by "Edit" in em tag using jquery?
So that any text comes after text Edit in em tag, will be removed.

A: Why not
$('.pagetitle em').text('Edit')


text:
Q: Sencha Touch 2: get dynamic url corresponding to clicked element in a list I am trying to dynamically retrieve the url after clicking on an item in a list.
The objective is to open the html page corresponding to clicked element.
Here is the code used:
Ext.define('FirstApp.view.Details',{
    extend:'Ext.Panel',
    xtype:'details',

    requires: ['Ext.Ajax'],

    config: {
        listeners: {
            activate: 'onActivate'
        },

        url: 'MyHtml.html' // Work fine if statically
        url: '{link}', // But this doesn't work dynamically

        tpl:'<h1>{link}</h1>' // However the desired data is displayed right here
    },

    onActivate: function(me, container) {
        Ext.Ajax.request({
            url: this.getUrl(),

            method: "GET",
            success: function(response, request) {
                me.setHtml(response.responseText);
            },
            failure: function(response, request) {
                me.setHtml("failed -- response: " + response.responseText);
            }
        });
    }

Do you have an idea?
Thanks in advance for your help.

A: {link} works in tpl because the tpl property handles the string like an XTemplate. Your (custom) url property is just handled like a string.
Where exactly is {link} coming from? Since you are using a standard panel, I can only assume you are setting the data property on the panel with this link value. If so, just set the url at the same time via setUrl. Otherwise add a listener on updatedata, so that whenever your template data changes the listener is called and you can update the url.


text:
Q: Can I call a method without triggering its event listeners? Is there any sort of flag or way to call a method without triggering any event handlers?
FOR EXAMPLE
I'm handling a controlTextDidChange method and checking to see if the character returned by a keystroke is valid. If it's not, I remove it; if it is, I append a word. The problem is that when I change the text while in controlTextDidChange, controlTextDidChange is called again and the program will loop indefinitely. I know I can use an instance variable to get around this, but is there any sort of flag or way to call a method without triggering any event handlers?

A: To expand the comment into a quick answer.
You have a method that issues a notification by design.  You want it to not issue that notification. You don't have an alternative available that does the same thing w/o the notification. If you want it to never issue that notification, and you have access to the code for the method, you could swizzle the method to a version where you've just commented out the notification.  Of course, if you had the code, you could just add another method, and call that one.   So you don't have the code, and all that's moot.
Can't you just bracket that invocation in code that removes the listener and then restores the listener?  In other words, psuedocode like this:
[self.controlThingy removeObserver:self]
[self.controlThingy myMethod]
[self.controlThingy addObserver:self]

You've then made self deaf to notifications for that one invocation of myMethod.  I've done similar things with bindings and KVO.


text:
Q: Loading React Sidebar in Parent Component when Child Component Loads In React, I'm trying to load a sidebar component in the parent component when a specific child component loads. The first issue I'm having is I keep receiving a TypeError that this is not defined. Secondly, cannot get <Sidebar/> to load when <NewPage/> is loaded. I'd like to also update the title in main, but I cannot even get to that point yet until I'm able to get the sidebar to show.
Below is a JSFiddle of the 3 classes I've put together to demonstrate the issue.
https://jsfiddle.net/pegues/9d31pah7/
Below is the main class component code:
class Main extends React.Component{

    constructor(props){
        super(props);

        this.titleHandler = this.titleHandler.bind(this);
        this.sidebarHandler = this.sidebarHandler.bind(this);

        this.state = {
            pageTitle: '',
            mounted: false,
            data: [],
            sidebar: false
        }
    }

    // Title Handler
    titleHandler(){
        console.log('Page Title Function Called');
        this.setState({ pageTitle: this.state.pageTitle });
    }

    // Sidebar Handler
    sidebarHandler(){
        console.log('Sidebar Function Called');
        this.setState({ sidebar: !state.sidebar });
    }

    // Load Dashboard
    loadDashboard(){
        ReactDOM.render(<Dashboard/>, document.querySelector('#main-content'));
    }

    // Load New Page
    loadNewPage(){
        ReactDOM.render(<NewPage action={this.sidebarHandler} />, document.querySelector('#main-content'));
    }

    // Render
    render(){
        return(

                <button onClick={this.loadDashboard}>Load Dashboard</button>
                <button onClick={this.loadNewPage}>Load New Page</button>

                {/* Content: Start */}

                    {/* Main: Start */}

{this.state.pageTitle}

                        {/* Main Content Container: Start */}

                        {/* Main Content Container: End */}

                    {/* Main: End */}

                    {this.state.sidebar ? <Sidebar/> : null}

                {/* Content: End */}

        );
    };
}

ReactDOM.render(,document.querySelector('#root'));

Below is the NewPage class component:
class NewPage extends React.Component{

    constructor(props){
        super(props);
        this.state = {
            pageTitle: 'New Page',
            sidebar: false
        };

        this.props.action.bind(this);
    }

    // Component Will Mount
    componentWillMount(){}

    // Component Did Mount
    componentDidMount(){}

    // Component Will Unmount
    componentWillUnmount(){}

    // Render
    render(){
        return(

                New Page Content...

        );
    }
}

A: Use arrow functions in class properties to avoid binding this.handleCardClick = this.handleCardClick.bind(this).
In your case, you forgot binding loadNewPage etc.
class Main extends Component {
  state = {
    pageTitle: "",
    mounted: false,
    data: [],
    sidebar: false
  };

  titleHandler = () => { ... }

  sidebarHandler = () => { ... }

  loadDashboard = () => { ... }

  loadNewPage = ()  => { ... }
...
}

Moreover, you are not referencing the state in sidebarHandler:
sidebarHandler = () => {
    console.log('Sidebar Function Called');
    this.setState({ sidebar: !this.state.sidebar }); // Not state.sidebar
}

There are many more mistakes in your code, like not using props.action that passed to NewPage and so on.
Use current sandbox with toggled Dashboard, NewPage and Sidebar to review your code.


text:
Q: Is it ok to be setting rejectUnauthorized to false in production PostgreSQL connections? We recently moved to Heroku and upon attempting to connect our apps to the DB, it kept rejecting our queries with the message "Self signed certificate". Passing in rejectUnauthorized solved for this but now I'm wondering, should we be doing this in production? If not, what is the appropriate way for us to be connecting to our Heroku PG Databases?
const pgp = require('pg-promise')(/*initOptions*/);
const {ConnectionString} = require('connection-string');

const cnObj = new ConnectionString(process.env.DATABASE_URL);

const cn = {
  host: cnObj.hostname,
  port: cnObj.port,
  database: cnObj.path?.[0],
  user: cnObj.user,
  password: cnObj.password,
  ssl: {
    rejectUnauthorized: false,
  },
};

const db = pgp(cn);

A: The risk you are running is that somebody gets between you and the Heroku server and impersonates the latter. They can then present their own certificate to you and negotiate a connection with you. The man in the middle can also pass the challenge from the server down to you and use your response to log into the database server in your stead.
All that assumes that the attacker has control over one of the network nodes between you and the Heroku server.
So I would say that while there is a residual risk, I wouldn't lose too much sleep over it, unless you are working with really sensitive data, in which case paranoia is a virtue.


text:
Q: Getting the type of Dynamic variable I am accessing a COM object and a method returns a dynamic variable. I do not have the implementation of the method that returns the dynamic variable and I need to cast it to the appropriate type so that I can use it in my class.
So I would like to know if there is a way to find the underlying type of a dynamic variable during runtime.
The dynamic variable is the value returning from a COM function so the UnWrap doesnt work and GetType() returns COMObject type.
thanks

A: If the object being returned can be one of many Types then you're best to keep using it as a dynamic and only trying to access methods and properties you know will exist (I'd expect the COM method to have some indication of how to use the dynamic it returns).
var canBeLiterallyAnything = ComMethod();
canbeLiterallyAnything.MethodDocsSayExists();
var propVal = canBeLiterallyAnything.SomeProperty;

Of course, if all of the possible Types all implement the same interface, you could cast to that interface.
var typeSafeReference = (ISharedInterface)canBeLiterallyAnything;

If you know that the COM method returns a specific Type but just don't know what that Type is then for the purpose of investigation you can call GetType() and either write it to console or set a breakpoint and inspect it.  This will let you then update your code to include a cast to that Type (which would minimise the impact of the use of dynamic, but also introduce the risk of a bad cast if other Types can be returned).
var type = canBeLiterallyAnything.GetType();

// e.g. If the above returns a Type of 'SpecificType', then you can update code to
var typeSafeReference = (SpecificType)canBeLiterallyAnything;

It should be noted that the COM method might not return a concrete Type, it might be returning an anonymous object, in which case there is no casting you can do so you'll have to just keep using it as a dynamic and only access properties/methods you know exist.


text:
Q: Intersection Of Topologies that contain a particular basis $Question:$
If $\mathscr A$ is a basis for a topology on $X$, then the topology generated by $\mathscr A$ equals the intersection of all the topologies that contain $\mathscr A$
$ My Approach:$
$\{ \mathscr T_\alpha\} $ be a class of topologies containing $\mathscr A$
From the given condition,
$\mathscr A \subseteq \mathscr T_\alpha$  $\forall \alpha$
$\Rightarrow$ $\mathscr T _ {\mathscr A}\subseteq \mathscr T_\alpha  $  $\forall \alpha $, where  $\mathscr T _ {\mathscr A}$ is the topology generated by $\mathscr A$
$\Rightarrow$
$\mathscr T _ {\mathscr A}\subseteq \bigcap \mathscr T_\alpha  $
Now how do I show
$\bigcap\mathscr T_\alpha\subseteq$ $\mathscr T _ {\mathscr A}$

A: Hint: $\mathscr{T}_{\mathscr{A}}$ is itself one of the $\mathscr{T}_\alpha$ in your collection.


text:
Q: How to Play Youtube Link Videos in My App? I want to play YouTube video in my Application. I written the code below but the video cant played please tell me how to play the video, Thanks in Advance
NSURL *url =[NSUrl UrlWithString: @"http://www.youtube.com/watch?v=2MSMJgpmVM8&feature=grec_index"];;
    NSString *embedHTML = @"\
\
<embed id=\"yt\" src=\"%@\" type=\"application/x-shockwave-flash\" \
width=\"%0.0f\" height=\"%0.0f\"></embed>\
";
videoView = [[UIWebView alloc] initWithFrame:CGRectMake(100, 100, 320.0, 412.0)];

[videoView setOpaque:NO];
NSString *html = [NSString stringWithFormat:embedHTML,url, videoView.frame.size.width, videoView.frame.size.height];
[videoView loadHTMLString:html baseURL:nil];

[self.view addSubview:videoView];

A: hey i dont think you will need to embed anything.you can simply shoot the webView with the appropriate URL...i had done dis a week back...it played the videos in Youtube..
Cheerzz..!!

A: Please follow this Link1 and Link2
Just Pass your URL in fileURL

A: I use the following function to get the HTML to place in a UIWebView
- (NSString *)YouTubeHTMLForURL:(NSString *)URLString;
{
  int w = streamWebView.frame.size.width;
  int h = streamWebView.frame.size.height;

    NSString *HTML = @"\
    \
    \
    \
    <embed id=\"yt\" src=\"%@\" type=\"application/x-shockwave-flash\" \
    width=\"%d\" height=\"%d\"></embed>\
    ";
    return [NSString stringWithFormat:HTML, w, h, URLString, w, h];
}

A: UIWebView  *wbView = (UIWebView *)[self.view viewWithTag:1];
NSString *embedHTML = @"\
    \
    \
    \
    <embed id=\"yt\" src=\"%@\" type=\"application/x-shockwave-flash\" \
    width=\"%0.0f\" height=\"%0.0f\"></embed>\
    ";

    NSString *html = [NSString stringWithFormat:embedHTML,url, 64.0, 64.0];
    [wbView loadHTMLString:html baseURL:nil];

  "url" is your video url

@Mike video plays only on device not on simulator

A: This below code should work -
But Please note that youtube only works in device are you checking this on device.
UIWebView  *wbView = (UIWebView *)[self.view viewWithTag:1];
NSString *embedHTML = @"\
    \
    \
    \
    <embed id=\"yt\" src=\"%@\" type=\"application/x-shockwave-flash\" \
    width=\"%0.0f\" height=\"%0.0f\"></embed>\
    ";

    NSString *html = [NSString stringWithFormat:embedHTML,url, 64.0, 64.0];
    [wbView loadHTMLString:html baseURL:nil];


text:
Q: Excel formula to extract string from text I'm using the following formula to extract a string from text in a cell by getting rid of -DCS.
The text contained in the cell: Q074-SARE_MANSONG-DCS
Formula:IF(ISNUMBER(SEARCH("DCS",H22)),LEFT(H22,FIND("@",SUBSTITUTE(H22,"-DCS","@",LEN(H22)-LEN(SUBSTITUTE(H22,"-",""))))-1),([@[<HELPER><SITE>]]))
Desired reslut: Q074-SARE_MANSONG
The problem is that it is not working for all cells. Can someone please tell me what it is that I'm doing wrong. Thanks.

A: Use one of these formulas instead (assuming your data is in A1)
=left(A1,len(A1)-4) or =SUBSTITUTE(A1,"-DCS","")

A: If "-DCS" is always at the end of the string:
=SUBSTITUTE(A1,"-DCS","")


text:
Q: Flash Actionscript 3 Bug? Using an int and negative numbers in a switch/case Running this code
var myValue1:int = 2;
switch (myValue1)
{
    case -3: trace(myValue1 + " == -3"); break;
    case -2: trace(myValue1 + " == -2"); break;
    case -1: trace(myValue1 + " == -1"); break;
    case 0:  trace(myValue1 + " == 0"); break;
    case 1:  trace(myValue1 + " == 1"); break;
    case 2:  trace(myValue1 + " == 2"); break;
    case 3:  trace(myValue1 + " == 3"); break;
    default: trace(myValue1 + " is unknown"); break;
}

var myValue2:int = -2;
switch (myValue2)
{
    case -3: trace(myValue2 + " == -3"); break;
    case -2: trace(myValue2 + " == -2"); break;
    case -1: trace(myValue2 + " == -1"); break;
    case 0:  trace(myValue2 + " == 0"); break;
    case 1:  trace(myValue2 + " == 1"); break;
    case 2:  trace(myValue2 + " == 2"); break;
    case 3:  trace(myValue2 + " == 3"); break;
    default: trace(myValue2 + " is unknown"); break;
}

gives this output:

2 == 0
-2 is unknown

(Compiled in Flash Builder 4.7.0.349722, running on Flash 11.5.502.149.  Running in Windows 7 SP1, Firefox 18.0.2)
The following changes all fix the above problem, giving the correct output:

*

*Changing the value-type to Number.

*Removing the negative-number case statements.

*Changing the case statements to use int-variables rather than literals... unless those variables are also const, in which case it stays broken!

Changing myValue2 = -1 gives the output -1 == -3, which is equally wtf-ish.

Clearly this is a bug, but... what causes it?  Is there some subtle nuance of using int  or negative numbers in case-statements that I don't understand?  Is my code somehow wrong?  Or is this simply an issue with the bytecode-compiler in Flash Builder?

A: I don't think you will find a concrete answer to this question.
What I can offer is a confirmation of the AS3 compiler bugginess.
I spent quite some time trying to resolve similar 'magical' errors and came up empty.
One such example is a For and While loops skipping the first or last item in an Array for no apparent reason while a Foreach looped worked just fine.
To me the most plausible reason for that is an error in memory management.
It might also be hardware related since the frequency of such things happening was higher on some machines that I or my colleagues worked on.
What I think is that some 'invisible' conditions are met e.g. order of performed operations ( you could try putting some dummy code in between the var declaration and the switch or maybe assigning the var value couple more times, just to 'jog the memory') that combined with the error-prone compiler mess up the memory addressing and your switch thinks its compering two integers while in reality it got a different value from the memory.

A: You can probably force the compiler's hand by converting the original value to a String and making your cases into String values.
switch( String(value) )
{
   case "-3": /*do something*/; break;
   case "-2": /*do something*/; break;
   case "-1": /*do something*/; break;
   case  "0": /*do something*/; break;
   case  "1": /*do something*/; break;
   case  "2": /*do something*/; break;
   case  "3": /*do something*/; break;
   default: break;
}

A: This is simply an issue with the bytecode-compiler in Flash Builder.
Clearly, your syntax is fine; there are literally hundreds of known issues with the compiler dating back to 2005 that are still open or unresolved.


text:
Q: ¿Por qué no puedo instanciar valores de mi provider? Verás lo que quiero es llamar a la variable de mi provider, que en este caso es:
Icon _hearticon = const Icon(
    Icons.favorite_border,
  );

y también el método que cambia la forma del icono cuando se presiona.
void changeHeart() {
    if (_hearticon.icon == Icons.favorite_border) {
      _hearticon = const Icon(
        Icons.favorite,
      );
    } else {
      _hearticon = const Icon(
        Icons.favorite_border,
      );
    }
    notifyListeners();
  }

aquí el provider completo
import 'package:flutter/material.dart';

class HeartIconState with ChangeNotifier {
  Icon _hearticon = const Icon(
    Icons.favorite_border,
  );
  void changeHeart() {
    if (_hearticon.icon == Icons.favorite_border) {
      _hearticon = const Icon(
        Icons.favorite,
      );
    } else {
      _hearticon = const Icon(
        Icons.favorite_border,
      );
    }
    notifyListeners();
  }

  Icon get hearticon => _hearticon;

  set hearticon(Icon value) {
    _hearticon = value;
    notifyListeners();
  }
}

y la forma en que los estoy llamando:
IconButton(
   icon: Heart.hearticon,
   color: Colors.red,
   iconSize: 25.0,
  onPressed: Heart.changeHeart,
           ),

Ya lo había hecho así cuando estaba manipulando el estado de un color para cambiar de negro a blanco y viceversa.
agrego aqui los errores. subi una fotografia porque son muchos.

A: He intentado replicar exactamente tú código y funciona correctamente.
Aségurate de haber inyectado el Provider HeartIconState correctamente antes de utilizarlo. ¿Puedes agregar el error?
Lo ejecuté de la siguiente forma:
#Clase provider
class HeartProvider extends ChangeNotifier {
  Icon _hearticon = const Icon(
    Icons.favorite_border,
  );
  Icon get hearticon => _hearticon;
 void changeHeart() {
    if (_hearticon.icon == Icons.favorite_border) {
      _hearticon = const Icon(
        Icons.favorite,
      );
    } else {
      _hearticon = const Icon(
        Icons.favorite_border,
      );
    }
    notifyListeners();
  }
}
#Clase main
void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(
          create: (_) => HeartProvider(),
        ),
      ],
      child: MaterialApp(
        debugShowCheckedModeBanner: false,
        title: 'SWAPI',
        initialRoute: 'login',
        routes: getApplicationRoutes(),
        theme: ThemeData(
          fontFamily: 'Orbitron',
          primaryColor: Color.fromRGBO(238, 219, 0, 1),
        ),
      ),
    );
  }
}
#Widget
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class MyWidget extends StatelessWidget {
  const MyWidget({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final _heartProvider = Provider.of<HeartProvider>(context);
    return IconButton(
              icon: _heartProvider.hearticon,
              color: Colors.red,
              iconSize: 25.0,
              onPressed: _heartProvider.changeHeart,
            );
  }
}


text:
Q: How do I open another activity from using androids 'Navigation Drawer' I am creating a new project with Eclipse's 'Navigation Drawer' template. I see no documentation or tutorials as far as how I would go about changing each item in the drawer's Listview to go to a new activity once clicked, rather then reuse the same one and change the top title text. Only tutorials I'm seeing is how to implement this Navigation Drawer, which looks like is useless now that Eclipse allows you to make a project with it. How would I make it so I can click on each item and have it go to a new activity?

A: Even though you claim you have looked at the Google tutorials on how to use a NavigationDrawer, it seems like you did absolutely no research whatsoever.
When reading the tutorial, you will come across this paragraph: https://developer.android.com/training/implementing-navigation/nav-drawer.html#ListItemClicks
It describes how to react to click events on the drawer.
The basic idea is that you creat a click-listener for callbacks when clicking the drawer. Inside the callback method, you start your desired Activity.
private class DrawerItemClickListener implements ListView.OnItemClickListener {
    @Override
    public void onItemClick(AdapterView parent, View view, int position, long id) {

         // start your activity here, depending on click position
    }
}

In the main-Activity, set the click-listener:
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());


text:
Q: Could not load GORM service when configuring spring-security-core I have a grails 3.3.6 application configured with a REST profile using gorm version 6.1.10. When I added these dependencies, I began having issues with configuration. In my build.gradle file:
compile "org.grails.plugins:spring-security-core:3.2.0.M1"
compile "org.grails.plugins:spring-security-rest:2.0.0.M2"
compile "org.grails.plugins:spring-security-ui:3.1.2"

I have a users table titled 'App_User' and a role table titled 'Role'. I do not use the default user table name since it is a reserved word in Postgres. The spring-security tables were generated using the s2-quickstart script found here. Additionally, the rest plugin is found here.
It is confirmed that hibernate generates the correct tables and fields in my db. However, my app fails and gives the following relevant error:
2018-11-27 14:44:07.007 ERROR --- [           main] o.g.d.m.services.DefaultServiceRegistry  : Could not load GORM service: org.grails.datastore.mapping.services.Service: Provider charity.navigator.rest.$App_UserServiceImplementation not found

java.util.ServiceConfigurationError: org.grails.datastore.mapping.services.Service: Provider charity.navigator.rest.$App_UserServiceImplementation not found

I can provide an additional stack trace if needed.
I do not have an explicit service for the 'App_User' domain since I want to rely on spring-security to do all the work. If I need one, please provide a link to a working project that I can model.
For some context, I am loosely following this tutorial but with some necessary extensions.
Since I am also not sure what is precisely causing the error and because I do not want to publish the entire project, I am willing to provide some additional source code and context if needed.


text:
Q: Is there a Python equivalent for Swift's @dynamicMemberLookup? In Swift, you can define @dynamicMemberLookup (see documentation) to get direct access to properties that are nested inside another type. Is there a Python equivalent?
Example of what I want to achieve with Python
Let's say I have a class with members, e.g.:
c = OuterClass()
c.inner_class = ClassWithManyMembers()
c.inner_class.member1 = "1"
c.inner_class.member2 = "2"
c.inner_class.member3 = "3"

I would like to be able to get/set those members without having to type the inner_class every time:
print(c.member1)  # prints "1"
c.member1 = 3
print(c.member1)  # prints "3"

Example in Swift (Source):
Dynamic member lookup by member name
@dynamicMemberLookup
struct DynamicStruct {
    let dictionary = ["someDynamicMember": 325,
                      "someOtherMember": 787]
    subscript(dynamicMember member: String) -> Int {
        return dictionary[member] ?? 1054
    }
}
let s = DynamicStruct()

// Use dynamic member lookup.
let dynamic = s.someDynamicMember
print(dynamic)
// Prints "325"

Dynamic member lookup by key path
struct Point { var x, y: Int }

@dynamicMemberLookup
struct PassthroughWrapper<Value> {
    var value: Value
    subscript<T>(dynamicMember member: KeyPath<Value, T>) -> T {
        get { return value[keyPath: member] }
    }
}

let point = Point(x: 381, y: 431)
let wrapper = PassthroughWrapper(value: point)
print(wrapper.x)

My only idea in Python would be to monkey-patch all nested properties directly to the outer class.

A: I would advise against nesting classes in one another, but if you must do it, try this:
class MetaOuter(type):
    def __getattr__(cls, attr):
        for member in cls.__dict__.values():
            if hasattr(member, attr):
                return getattr(member, attr)
        raise AttributeError(attr)

    def __setattr__(cls, attr, value):
        for member in cls.__dict__.values():
            if hasattr(member, attr):
                setattr(member, attr, value)
                return
        super().__setattr__(attr, value)

class Outer(metaclass=MetaOuter):
    a = 0

    class Inner:
        x = 1
        y = 2

Now any attributes of a nested class inside Outer are available (and can be written to) as an attribute of Outer:
>>> Outer.x, Outer.y
(1, 2)
>>> Outer.a # Accessing regular attributes still works as usual
0
>>> Outer.x = True
>>> Outer.Inner.x
True

If you need to nest more than one level, use the same meta class for any inner encapsulating classes:
class Outer(metaclass=MetaOuter):
    a = 0

    class Inner(metaclass=MetaOuter):
        x = 1
        y = 2

        class Innerer:
            z = 42

>>> Outer.a, Outer.x, Outer.y, Outer.z
(0, 1, 2, 42)
>>> Outer.z = -1
>>> Outer.z
-1

Note: Be aware that if you're trying to access an attribute that is found in multiple nested classes, you can't be sure of which class the attribute will come from. A more predictable implementation in this case would be to handle some kind of key path that will be looked up, but that's essentially the same as what Python provides by default (e.g., Outer.Inner.Innerer.z).

A: Generally, you can just save a reference to the inner object when you want to make repeated accesses to it.
c = OuterClass()
c.inner_class = ClassWithManyMembers()

ic = c.inner_class
print(ic.member1)
print(ic.member2)
print(ic.member3)

ic.member1 = "5"


text:
Q: MVC5 add new folder and new class. Namespace does now show on other pages This is mind blowing for me.
1) I start a new MVC5 project
2) I add a new folder named "Extensions"
3) I add a Extensions.CS file inside that folder and give it a namespace Application1.Extensions
4) I go to any other page and try to access that newly created namespace but it never shows nor allows me to compile.
What's wrong with my process??

A: You have to check if the, with a right click on the Extensions.cs file then properties if the "Build Action" has the "Compile"


text:
Q: Query PFObject with full PFUser info Im my object "car" i have a column called "owner" in which i save the PFUser object to.  When I query this "car" object and try to get the owner's name, I have to call owner.fetchIfNeeded() in order to get the PFUser's custom columns such as "firstname".  How can my original query make sure to include all extra columns on PFUsers so I do not have to call fetchIfNeeded()?

A: You can use the includeKey method to fetch the PFUser object with the original query.
PFQuery *query = [PFQuery queryWithClassName:@"car"];
[query includeKey:@"owner"];

You can also use multi-level includes using dot notation to retrieve relational data on the user object. e.g.
[query includeKey:@"owner.profilePicture"];

References:

*

*https://parse.com/docs/ios/api/Classes/PFQuery.html#//api/name/includeKey:

*https://parse.com/docs/ios_guide#queries-relational/iOS


text:
Q: Angular 2 Service not functioning as Singleton in Child Component (possible duplicate) SECOND UPDATE
My issue was in the service itself, changing the methods to arrow functions solved the problem.

This might be a repeat, but I have done exhaustive research on Angular DI and it's clear that injecting services at the root level make them available as the same instance to all components in an app.
Underneath my AppComponent I have three children Screenshot, Confirm and Preview. I call a service from the Screenshot component and save some data on that service, then try to access that data later on from the Preview component but it seems I am accessing a new instance of that service.
app.module
@NgModule({
  declarations: [
    AppComponent,
    Screenshot,
    Confirm,
    Preview,
  ],
  entryComponents: [
    Preview
  ],
  imports: [
    CommonModule,
    BrowserModule
  ],
  providers: [
    MessageService,
    ScreenshotService
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component
@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit, OnChanges, OnDestroy {
    @ViewChild(Preview) preview: Preview;

    title: string;
    confirmed: boolean;
    constructor(
        private screenshotService: ScreenshotService,
        private messageService: MessageService,
    ) {
        this.title = 'Media Radar';
        this.confirmed = false;
    }

    onNotify(confirm): void {
        this.confirmed = confirm;
        if(this.confirmed) {
            this.preview.showPreview();
        }
    }
    ...
}

app.component.html

{{ title }}

    <screenshot [hidden]="confirmed" (showConfirm)='onNotify($event)'></screenshot>
    <confirm [hidden]="!confirmed" (hideConfirm)='onNotify($event)'></confirm>
    <preview [hidden]="!confirmed"></preview>

preview.component
import { ScreenshotService } from './screenshot.service';
@Component({
    selector: 'preview',
    template: `<canvas #preview></canvas>`
})

export class Preview {
    @ViewChild('preview') preview: ElementRef;
    private canvas: HTMLCanvasElement;
    constructor(
        private screenshotService: ScreenshotService,
        private renderer: Renderer2
    ) {}

    showPreview() {
        console.log(this.screenshotService) // shows a new instance with no data
    ...
    }
}

To avoid getting too lengthy with code, I'll leave out the service and the other child component which calls it first but can post if needed.
UPDATE
screenshot.service
import { Injectable } from '@angular/core';

@Injectable()
export class ScreenshotService {
    public imageURL: string = '';
    public title: string  = '';
    public height: number = 0;
    public width: number = 0;

    constructor() {
    }
    convertToBlob(): Promise<any> {
        console.log(this); // returns all the initial values above when called from the Preview component the second time despite being previously assigned values when a different method was called from a different service
    }
    ...
}

A: My problem was in the service methods. I changed them to arrow functions and it solved everything.


text:
Q: how could I download file in mobile require:I need to download files from server in mobile.
question:
In pc:

    click me to download

and

botn works well,but it can't work well in mobile,how can I realize it?


text:
Q: Why do Networkx and Igraph return different values for the Mincut function? I am testing out the minimum cut functions for both Networkx and Igraph, but I've run into a situation where they are returning different values for their respective mincut functions given exactly the same graph.
G = nx.Graph()
graph = ig.Graph()
#LINES[1 - 3] are just src dest weights from a file. I did not include the parsing code for clarity purposes.
G.add_edge(lines[1], lines[2], weight=int(lines[3]))
graph.add_vertex(lines[1])
graph.add_vertex(lines[2])
graph.add_edge(lines[1], lines[2], weight=int(lines[3]), capacity=int(lines[3]))
ans = nx.stoer_wagner(G)
print("MinCut Val: ", ans[0])
print(graph.mincut())

My command line output is as follows:
 MinCut Val:  744
 Graph cut (0 edges, 1024 vs 31232 vertices, value=0.0000)

Is there any reason for the disparity? How is it even possible for the mincut to be 0 for one, and 744 for the other?
Thanks!


text:
Q: What kind of data preprocessing is required before running a clustering algorithm? I have a dataset that consists of 87 observations or rows of data. My variables are a mix of different kinds - continuous, categorical and some count. Examples are variables which are percentage types, variables whose values are numbers and some counts.
My objective is to find natural groupings among the 87 observations. I have been tasked to choose one method among k-means, k-medians or hierarchical types.
I have tried doing the following:

*

*Started with hierarchical clustering. Used only the continuous variables in the dataset to try and get clusters; but that did not work as I keep/kept getting the following error: "Invalid (dis)similarity option".

*Tried standardizing the variables since they are on different scales and then running hierarchical clustering. Still the same error as above.

*I have used linkage methods like wardslinkage, centroidlinkage, medianlinkage etc... but I am getting the same error

I am of the opinion that variables which have values as whole numbers or percentages are continuous variables. But, please let me know if I might be wrong?
There is clear guidance available in literature as to what linkage method is appropriate when certain kinds of variables are present. However, for some reason, none of my linkage methods within hierarchical clustering seem to be running properly.

A: "Invalid (dis)similarity option"
is not an error caused by preprocessing, but a programming error in your code (which is why it does not go away if you change your data)
Could even be a typo.


text:
Q: Why cannot $2^x=m^n+1$? $x,n,m >1$ and $x,n,m \in \mathbb{Z}$
I've tried to solve it myself, but I'm getting nowhere, so apologies if it's an irritatingly basic question.
Whilst I'm on it, is it true that $y^x \ne m^n+1$ ($y>1, y \in \mathbb{Z}$)? There's probably a glaringly obvious counterexample I'm overlooking.

A: The Diophantine equation is $$2^x = 1 + m^n.$$

*

*Since the left hand side is even $m$ must be odd, let $m = 2r+1$.

*Since $m^n + 1$ factors into $(m+1)(\cdots)$ when $n$ is odd, $n$ must be even, let $n = 2u$.

Putting these two facts together and applying the binomial theorem gives $$m^n = (2r+1)^{2u} = (4r(r+1)+1)^u = \sum_{k=0}^u \binom{u}{k} [4r(r+1)]^k$$
Plugging this into our original equation, and pulling out the first term of the sum we have
$$\begin{array}{rcl}
2^x
&=& 1 + \binom{u}{0} [4r(r+1)]^0 + 4 \sum_{k=1}^u \binom{u}{k} 4^{k-1}[r(r+1)]^k \\
&=& 2 + 4 M \\
\end{array}$$ for some $M$, this is impossible unless $M=0$, then $x=1$ and $u=0$ and $m$ can be anything.


text:
Q: Making Periodic URL Requests from an Activity I have an activity which makes periodic requests (once every 15 seconds to get a json data feed).  The requests I am passing off to a AsyncTask so its not on the main UI thread.  So far so good.  But lets say that I request the feed and it takes 20 seconds to respond.  I really don't want to kick off another thread until say 30 seconds are up.  So ....
Is there a way to prevent the AsyncTask from running if there first one has not yet finished?
Also is there a way to timebox the AsyncTask to take no more than 30 seconds? reguardless of the Http timeout?
Thanks,
Steve

A: You can use a mutex variable to enforce this. Say, We call the variable update. This will be a boolean variable with initial value true.
Before running an Async task, Check the value of update, If it is true run the async task and set update to false.
After the end of the async task, in the onPostExecute() method, set update to true again.
So another async task will not be launched while one hasn't finished, thus ensuring exclusivity.


text:
Q: Find depth of each children of body in an HTML document In the below code sample, Body has two children. I would like to know the max depth of each child
Body element has two children nodes, how do I find each child's max depth.
Here in this case:
Child 1 depth: 3
Child 2 depth: 5

List 1

Heading 1

A: If you use jQuery it is quite straight forward although your question isn't clear.
$('.child-2').parents().length

or this If you use calcDepth your question isn't clear.
var calcDepth = function ( root ) {
    var $children = $( root ).children();
    var depth = 0;

    while ( $children.length > 0 ) {
        $children = $children.children();
        depth += 1;
    }

    return depth;
};
var result = calcDepth( document.getElementById('parent-1') );


text:
Q: Putting two links and a text string into a cell? I would like a cell like this:

Change
20:25
to
20:30

where the two different times (20:25, 20:30) are sourced from two different cells. I would like to preserve the line breaks.
How might I achieve this?

A: I'm not sure I completely understand. The issue here is having the line breaks in a single cell? If so, you can use ALT+Enter to put in line breaks for Excel. http://help.isu.edu/index.php?action=knowledgebase&catid=38&subcatid=66&docid=1022
Edit: This may work with what you're trying to do:
="Change " & TEXT(A1,"h:mm") & " to " & TEXT(A2,"h:mm")
The TEXT function may be needed if Excel is trying to convert your date to a number.

A: Assuming the layout as in the image, please try:
=A1 & CHAR(10) & B1 &CHAR(10) & C1 & CHAR(10) &D1

Alternatively:
="Change" & CHAR(10) & B1 & CHAR(10) & "to" & CHAR(10) & D1


text:
Q: Is it possible to add CSS in a component that does not include @Type I would like to make a table that alternating two different colours.
How can I make the table coloured?
const StickyTable = require("react-sticky-table").StickyTable;
const Row = require("react-sticky-table").Row;
const Cell = require("react-sticky-table").Cell;

export const BasicExample = () => {
  return (
    <React.Fragment>
      <Paper>

          <StickyTable>
            <Row>
              <Cell>Header 1</Cell>
              <Cell>Header 2</Cell>
            </Row>
            <Row>
              <Cell>Cell 1</Cell>
              <Cell>Cell 2</Cell>
            </Row>
          </StickyTable>

      </Paper>
    </React.Fragment>
  );
};

A: You should be able to use style attribute on color. For example:

If that doesn't work try putting a div around your row tag and style that because right now you are editing the entire table. Meaning your div is on the entire table. Put it inside the table tags on each specific row for alternating colors. Give the different div styles different colors. So instead of this:
<StickyTable>
Do this <StickyTable>

I hope it works:)

A: If sticky table internally uses the html table element in its jsx, you could use the even and odd css rules to apply colors to the table cells.
tr:nth-child(even) {background: #CCC}
tr:nth-child(odd) {background: #FFF}


text:
Q: How to Switch Between NavBar Tabs with a Button R Shiny I need the user to click a button and be taken to a different tabPanel of a navbarPage. Here is a simple app where this could be implemented. How can I achieve this?
ui <- shinyUI(
 navbarPage('Test App',
  tabPanel('Page 1',
   p('This is the first tab'), br(),
   actionButton('jumpToP2', 'Jump to Second Tab')
  ),

  tabPanel('Page 2',
   p('This is the second tab'),
   actionButton('jumpToP1', 'Jump to First Tab')
  )
 )
)

server <- shinyServer(function(input, output){
  observeEvent(input$jumpToP2,{
    ## Switch active tab to 'Page 2'
  })

  observeEvent(input$jumpToP1,{
    ## Switch active tab to 'Page 1'
  })
})

shinyApp(ui, server)

A: You can use updateTabsetPanel to switch between different tabPanels. See the documentation and example codes at https://shiny.rstudio.com/reference/shiny/latest/updateTabsetPanel.html. The code below should fulfill your requirements.
ui <- navbarPage('Test App',id = "inTabset",
                 tabPanel(title = "Panel 1", value = "panel1",
                          actionButton('jumpToP2', 'Jump to Second Tab')),
                 tabPanel(title = "Panel 2", value = "panel2",
                          actionButton('jumpToP1', 'Jump to First Tab'))
        )

server <- function(input, output, session) {
    observeEvent(input$jumpToP2, {
        updateTabsetPanel(session, "inTabset",
                          selected = "panel2")
    })

    observeEvent(input$jumpToP1, {
        updateTabsetPanel(session, "inTabset",
                          selected = "panel1")
    })

}

shinyApp(ui, server)

A: I'm not so sure that this really the best way for you to design your U... Do you know that tabPanel() will act pretty much the same way as an actionButton() will in this case?
ui <- navbarPage('Test App',id = "inTabset",
             tabPanel(title = "Panel 1", uiOutput("panel1")),
             tabPanel(title = "Panel 2", uiOutput("panel2"))
                      )
server <- function(input, output, session) {
    output$panel1 <- renderUI({
    #your UI data
    })
    output$panel2 <- renderUI({
    #your UI data
    })
}
shinyApp(ui, server)


text:
Q: How can you use css to style all  elements in a table when one of the  elements has a certain class? I need to highlight an entire row of in a table when one of the  elements contains a certain class.  Example:

.whole-row-red-background {
  background-color: red;
}

  </tbody

In the example above, only the first cell (the first td) of the second row in the table is set with a red background.  Under this scenario (first  in the row has this class) I need all  elements in the row to have a red background.

A: You could use the general sibling selector.
More info here: https://developer.mozilla.org/en-US/docs/Web/CSS/General_sibling_combinator
Here is your updated snippet:

.whole-row-red-background {
  background-color: red;
}

.whole-row-red-background ~ td {
  background-color: red;
}

  </tbody

A:

let td = document.getElementsByClassName("whole-row-red-background")[0]
let tr = td.closest("tr")
tr.style.backgroundColor='red'
.whole-row-red-background {
  background-color: red;
}

      x
      y
      z

      a
      b
      c


text:
Q: Hibernate CRUD à la Ruby on Rails' Scaffolding Do you know of any tool that would do like Ruby on Rails' Scaffolding (create simple CRUD pages for any particular class to allow quickly populating a database with dummy data), only which used Java classes with Hibernate for database access, and JSP/JSF for the pages?
It is a drag when you are programming one part of an application, but need data that can only be added with another part that is not ready yet, or very cumbersomely by directly inserting it into the DB.

A: Grails is a very nice Rails-like framework built on top of Spring MVC.  For persistence, they use GORM, which is basically an ActiveRecord-like framework built on top of Hibernate.  Pretty slick.
If you already have Hibernate entities, they can actually be used immediately in Grails with no additional work.

A: You can try Telosys Tools, an Eclipse plugin for
code generation (scaffolding) working from an existing database
with customizable Velocity templates.
It's very simple and easy to use.
The tutorial for code generation with Spring MVC and Spring Data is here : https://sites.google.com/site/telosystutorial/
See also : http://tools.telosys.org/
Eclipse Marketplace : http://marketplace.eclipse.org/content/telosys-tools

A: I'm a little late on this one but it popped up in the "Related" links →
JBoss Seam and it's Seam Gen tasks are exactly what you are looking for (Hibernate + JSF). You can generate an entire web app from a Hibernate fronted database in seconds.

A: you can use grails. Grails tries to be Groovy on Rails -- uses Rails behind the scene for scaffolding, etc. Since you can pretty much write full scale java code in a groovy class, you can have the CAKE and EAT IT too.

A: Grails is somewhat different from Rails, even though it was based on Rails and has a similar feel. Grails uses spring to help wire your services together. The environment is not only dynamic (with Groovy) but also allows you to use Java (static environment) as well. It is really cool, especially if you're coming from a java environment. The Grails folks took the Rails idea and expanded it using the Domain Driven Model. Rails is still data model centric where you have to deal a lot with the database to create your objects (which is called a model), where as Grails allows you to design applications using the true domain object model where you deal with objects from the domain class' perspective instead of the database.

A: There is a good tutorial here on how to do this in Netbeans. I've used this wizard before with good results. Out of the box you can select which persistance framework to use and the JSF pages it produces are quite nice and clean.

A: Spring + AspectJ + Hibernate + CLI = Spring Roo RAD framework.
Give it a try.


text:
Q: Meta-model of the field function OpenTurns 1.16rc1 After updating Openturns from 1.15 to 1.16rc1 I have the following issue with building the meta-model of the field function:
to reduce the computational burden:
ot.ResourceMap.SetAsUnsignedInteger("FittingTest-KolmogorovSamplingSize", 1)
algo = ot.FunctionalChaosAlgorithm(sample_X, outputSampleChaos)
algo.run()
metaModel = ot.PointToFieldConnection(postProcessing, algo.getResult().getMetaModel())

The "FittingTest-KolmogorovSamplingSize" was removed from OpenTurns 1.16rc1 and when I try to replace the fitting test with:
ot.ResourceMap.SetAsUnsignedInteger("FittingTest-LillieforsMaximumSamplingSize", 10)

Or with
ot.ResourceMap.SetAsUnsignedInteger("FittingTest-LillieforsMinimumSamplingSize", 1)

The code is freezing. Is there any solution for this?

A: The solution is to use:
degree = 1
dimension_xi_X = 3
dimension_xi_Y = 450
enumerateFunction = ot.LinearEnumerateFunction(dimension_xi_X)
basis = ot.OrthogonalProductPolynomialFactory(
    [ot.HermiteFactory()] * dimension_xi_X, enumerateFunction)
basisSize =450 #enumerateFunction.getStrataCumulatedCardinal(degree)
adaptive = ot.FixedStrategy(basis, basisSize)
projection = ot.LeastSquaresStrategy(
    ot.LeastSquaresMetaModelSelectionFactory(ot.LARS(), ot.CorrectedLeaveOneOut()))
ot.ResourceMap.SetAsScalar("LeastSquaresMetaModelSelection-ErrorThreshold", 1.0e-7)
algo_chaos = ot.FunctionalChaosAlgorithm(sample_X,
outputSampleChaos,basis.getMeasure(), adaptive, projection)
algo_chaos.run()
result_chaos = algo_chaos.getResult()
meta_model = result_chaos.getMetaModel()
metaModel1 = ot.PointToFieldConnection(postProcessing,
algo_chaos.getResult().getMetaModel())

A: The proposed solution is simply to use another distribution to model your data. You could have used any other multivariate continuous distribution of proper dimension. IMO it is not a valid answer as the distribution has no link to your data.
After inspection, it appears that the problem has nothing to do with Lilliefors's test. In OT 1.15 we were using this test (under the wrong name of Kolmogorov) to select automatically a distribution suited to the input sample, but we switched to a more sophisticated selection algorithm (see MetaModelAlgorithm::BuildDistribution). It is based on a first pass using the raw Kolomgorov test (thus ignoring the fact that parameters have been estimated) then an information-based criterion is used to select the most relevant model (AIC, AICC, BIC depending on the value of the "MetaModelAlgorithm-ModelSelectionCriterion" key in ResourceMap. The problem is caused by the TrapezoidalFactory class during the Kolmogorov phase. I will provide a fix ASAP in OpenTURNS master. In the mean time, I have adapted the proposed solution to something more adapted to your data:
degree = 6
dimension_xi_X = 3
dimension_xi_Y = 450
enumerateFunction = ot.HyperbolicAnisotropicEnumerateFunction(dimension_xi_X, 0.8)
basis = ot.OrthogonalProductPolynomialFactory(
    [ot.StandardDistributionPolynomialFactory(ot.HistogramFactory().build(sample_X[:,i])) for i in range(dimension_xi_X)], enumerateFunction)
basisSize = enumerateFunction.getStrataCumulatedCardinal(degree)
#basis = ot.OrthogonalProductPolynomialFactory(
#    [ot.HermiteFactory()] * dimension_xi_X, enumerateFunction)
#basisSize = 450#enumerateFunction.getStrataCumulatedCardinal(degree)
adaptive = ot.FixedStrategy(basis, basisSize)
projection = ot.LeastSquaresStrategy(
    ot.LeastSquaresMetaModelSelectionFactory(ot.LARS(), ot.CorrectedLeaveOneOut()))
ot.ResourceMap.SetAsScalar("LeastSquaresMetaModelSelection-ErrorThreshold", 1.0e-7)
algo_chaos = ot.FunctionalChaosAlgorithm(sample_X,
outputSampleChaos,basis.getMeasure(), adaptive, projection)
algo_chaos.run()
result_chaos = algo_chaos.getResult()
meta_model = result_chaos.getMetaModel()
metaModel = ot.PointToFieldConnection(postProcessing,
algo_chaos.getResult().getMetaModel())

I also implemented a quick and dirty estimator of the L2-error:
# Meta_model validation
iMax = 5
# Input values
sample_X_validation = ot.Sample(np.array(month_1_parameters_MSE.iloc[:iMax,0:3]))
print("sample size=", sample_X_validation.getSize())
# sample_X = ot.Sample(month_1_parameters_MSE[['Rseries','Rsh','Isc']])

# output values
#month_1_simulated.iloc[0:1].transpose()
Field = ot.Field(mesh,np.array(month_1_simulated.iloc[0:1]).transpose())
sample_Y_validation = ot.ProcessSample(1,Field)
for k in range(1,iMax):
    sample_Y_validation.add( np.array(month_1_simulated.iloc[k:k+1]).transpose() )

# In[18]:

graph = sample_Y_validation.drawMarginal(0)
graph.setColors(['red'])
drawables = graph.getDrawables()
graph2 = metaModel(sample_X_validation).drawMarginal(0)
graph2.setColors(['blue'])
drawables = graph2.getDrawables()
graph.add(graph2)
graph.setTitle('Model/Metamodel Validation')
graph.setXTitle(r'$t$')
graph.setYTitle(r'$z$')
drawables = graph.getDrawables()
L2_error = 0.0
for i in range(iMax):
    L2_error = (drawables[i].getData()[:,1]-drawables[iMax+i].getData()[:,1]).computeRawMoment(2)[0]
print("L2_error=", L2_error)

You get an error of 79.488 with the previous answer and 1.3994 with the new proposal. Here is a graphical comparison.
Comparison between test data & previous answer
Comparison between test data & new proposal


text:
Q: Symfony2 - How to remove the Doctrine Bundle? I am currently working on a project using Symfony2 and I have no need for the Doctrine Bundle. I have tried to remove it on numerous occasions but I keep getting errors that break the install.
I have grep'ed for all instances of 'Doctrine' within the app directory and have commented out any reference to Doctrine in the following files:

*

*app/config/config.yml

*app/AppKernel.php

*app/autoload.php

I then cleared the cache (currently working in dev mode, so removed the cache/dev directory).
The Error I am currently getting is:

Fatal error: Class 'Doctrine\Common\Annotations\FileCacheReader' not
found in
/path/to/application/app/cache/dev/appDevDebugProjectContainer.php on
line 45

This refers to this block of code in the cache
/**
 * Gets the 'annotation_reader' service.
 *
 * This service is shared.
 * This method always returns the same instance of the service.
 *
 * @return Doctrine\Common\Annotations\FileCacheReader A Doctrine\Common\Annotations\FileCacheReader instance.
 */
protected function getAnnotationReaderService()
{
    return $this->services['annotation_reader'] = new \Doctrine\Common\Annotations\FileCacheReader(new \Doctrine\Common\Annotations\AnnotationReader(), '/path/to/application/app/cache/dev/annotations', true);
}

but I cannot find a way to stop this from being added to the cache, as I cannot find any settings relating to the annotation_reader.

A: Symfony uses Doctrine's annotation library. You don't need Doctrine's ORM or DBAL and you can remove them. But you need annotation reader if you use annotations anywhere in your project.
EDIT: You'll have to test it on your own. I never tried it myself.
These bundles seem to use annotation reader:

*

*DoctrineBundle

*DoctrineAbstractBundle

*SecurityExtraBundle

*FrameworkExtraBundle

*FrameworkBundle

Note that it's probably not worth the effort. If you're not using given services they're not created.

A: You might wanna have a look at:
http://fabien.potencier.org/article/50/create-your-own-framework-on-top-of-the-symfony2-components-part-1
and
http://silex.sensiolabs.org/
;)


text:
Q: Acrobat Javascript - How to make user only use 3 out 4 text fields (no matter which 3)? I have a group of 4 text fields but only want to allow user to fill in 3 of them (at user's choice) and if user tries to fill in the fourth, don't allow.
Thanks in advance

A: Without exact field names, I can't give you exact code but here's how to achieve what you want. For each of the 4 fields, in the "On Blur" event, check the value of each field, if three fields have a non-blank value, set the 4th to read-only.
By performing the calculation in "On Blur" you'll be checking the value of the fields after a new value has been entered.


text:
Q: Problems with multiple one-way ANOVAs Could you please help me how I can conclude if I would like to know the difference between Treatment 1 and Treatment 2:
I have three groups. Treatment 1, Treatment 2 and Control.
I used multiple one-way ANOVAs to compare each pair of groups. The results are:
Treatment 1 = Control, Treatment 2 > Control, Treatment 1 = Treatment 2
If I look at the first two analyses. My conclusion would be that Treatment 2 is more effective than Treatment 1. But if I look at the last analysis I will say that Treatment 1 is the same as Treatment 2 in terms of effectiveness. This is conflicting.
How could I conclude in this case?
Thank you.

A: First, PLEASE don't ever say that one treatment is equal to another. You have not shown they are equal, you have only failed to show that they are unequal.
Second, statistical tests do not have the transitivity property. Imagine a situation where you have samples of sizes 20, 2000, and 2, and the observed means go in the order 1st < 2nd < 3rd. Because of the larger sample sizes, you might well find a significant difference between the first two. And because of the small sample sizes, you might also NOT find a significant difference between the 1st and 3rd. Statistical testing is all about what you can prove with reasonable certainty, and what you cannot establish because of too much uncertainty.


text:
Q: Ember change queryParameters from an action in a controller I have a filter list component which is supposed to update the data on the page.  Depending on which filters are clicked in this component, I am trying to update my query parameters with it.
Right now, I have the filters working and logging out with correct parameters, but this.transitionToRoute() is incorrect/not working.  I think the version of this is not what I'm expecting.
actions: {
  updateQuery: function() {
    //do stuff to get my newParams
    console.log(newParams); //This echoes out nicely
    this.transitionToRoute({queryParams: newParams}); //this returns "not a function"
    return false;
  }
}

The output for newParams is:
{status: "KNOWN_TO_FAIL", owner: "spople,kuher,dwoods"}
so I know the params are correct, I just don't know how to change the URL parameters and update the data.
Another note which may be another question is that I need this to update only a specific div on the page and not the entire page.  Am I barking up the wrong tree?

A: Components do not have a transitionToRoute method. Your updateQuery action would work fine if it were in a Controller, which does have a transitionToRoute method. You need to pass your action back up to the Controller to trigger the transition.
Without more info, it's hard to judge whether you're barking up the wrong tree or not. Depending on how you have your query params configured in the route (do you have refreshModel set to true?), you're likely to see the the page reload.


text:
Q: tkinter window will not pop up I am doing a project with tkinter. I've recently switched to linux Mint on my computer. The program runs fine with no errors, the gui just won't come up. I'm using pycharm.
import sys
from tkinter import *

THEME_COLOR = "#375362"

class QuizInterface:
    def __int__(self):
        self.window = Tk()
        self.window.title("Quizzler")
        self.window.config(padx=30, pady=30)

        self.card = Canvas(width=300, height=250)
        self.card.create_text(text="Question goes here", font=("arial", 20, "italic"))
        self.card.grid(row=1, column=0, columnspan=2)

        self.score = Label(text="Score: ", font=("arial", 13, "bold"))
        self.score.grid(row=0, column=1)

        true_image = PhotoImage(file="images/true.png")
        self.true_button = Button(image=true_image, highlightthickness=0)

        false_image = PhotoImage(file="images/false.png")
        self.f_button = Button(image=false_image, highlightthickness=0)

        self.window.mainloop()

A: One of the function that gets called when a class is intitialized is __init__, but you are defining def __int__(self):, so:
class QuizInterface:
    def __init__(self):
        ...


text:
Q: How to loop and push objects values to array? I have a json like:
data: (46) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
Province/State: "Anhui"
Country/Region: "Mainland China"
Lat: 31.8257
Long: 117.2264

Now data has
data: Array(46)
0: {date: "1/22/20", Recovered: 0, Deaths: 0, Confirmed: 1}
1: {date: "1/23/20", Recovered: 0, Deaths: 0, Confirmed: 9}
2: {date: "1/24/20", Recovered: 0, Deaths: 0, Confirmed: 15}
3: {date: "1/25/20", Recovered: 0, Deaths: 0, Confirmed: 39}
4: {date: "1/26/20", Recovered: 0, Deaths: 0, Confirmed: 60}
5: {date: "1/27/20", Recovered: 0, Deaths: 0, Confirmed: 70}
6: {date: "1/28/20", Recovered: 0, Deaths: 0, Confirmed: 106}

And I have plenty objects in the json, I loop and push coordinates like this:
let coords = [];

getVirusData();

function getVirusData() {
  getAvailableDatasets()
    .then(combineDatasets)
    .then(data => { // It's asynchronous
      coords.push.apply(coords, data.map(item => item.Lat + "," + item.Long));
    }).then(function(entry) {
      for (var a = 0; a < coords.length; a++) {
        var pin = coords[a].split(',');
        var latLng = new google.maps.LatLng(pin[0], pin[1]);
        var marker = new google.maps.Marker({
          position: latLng,
          map: map
        });
      }
    });
  }

That works but I need to also push each date for each object into an array, should be i believe an associative array tho since the dates are related to those particular coordinates and do so for each object and also "confirmed", "Recovered" and "Deaths" should go to their own array but related to each object
Desired output would be an array like
obj = ["31.8257,117.2264"]["22/02/20", "24/02720"]["recovered 1", "recovered 3"]
But I don't understand how I could do that for each object

A: Here is a working fiddle for filtering your inputs based on dates from the slider and date attribute on the input data:
https://jsfiddle.net/ku16vapg/5

let virusData;
let virusDataCopy;
getVirusData();

function getVirusData() {
  getAvailableDatasets()
    .then(combineDatasets)
    .then((r) => {
      try {
        virusData = JSON.Parse(r);
      } catch (e) {
        virusData = r;
      }
      initUI(virusData);
    })
}

function initUI(initialDataSet) {
  function dateToTS(date) {
    return date.valueOf();
  }

  function tsToDate(ts) {
    var d = new Date(ts);
    return d.toLocaleDateString(lang, {
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    });
  }

  let dataSetCopy = [];
  initialDataSet.forEach(ds => {
    ds.data.forEach(obj => {
      dataSetCopy.push(obj.date)
    })
  })
  dataSetCopy.sort((a, b) => Date.parse(a) - Date.parse(b));
  console.log(dataSetCopy)

  let lang = "en-US";

  $("#demo_4").ionRangeSlider({
    skin: "big",
    type: "double",
    grid: true,
    min: dateToTS(new Date(dataSetCopy[0])),
    max: dateToTS(new Date(dataSetCopy[dataSetCopy.length - 1])),
    from: dateToTS(new Date(dataSetCopy[3000])),
    to: dateToTS(new Date(dataSetCopy[7000])),
    prettify: tsToDate,
    onFinish: function(data) {
      let filtererdData = virusData.map(vd => {
        return { ...vd,
          data: vd.data.filter(obj => {
            objDataTS = Date.parse(obj.date);
            return (objDataTS < data.to) && (objDataTS > data.from)
          })
        }
      })
      updateUI(filtererdData)
    },
  });
  updateUI(initialDataSet)
}

function updateUI(dataSet) {
  document.querySelector("pre").textContent = JSON.stringify(dataSet, null, 2)
};

function getAvailableDatasets() {
  return $.getJSON('https://api.github.com/repos/CSSEGISandData/COVID-19/contents/csse_covid_19_data/csse_covid_19_time_series')
    .then((files) => {
      return Promise.all(
        files.filter(file => /^time_series_19-covid-.+\.csv$/.test(file.name))
        .map(file => getDataset(file.download_url))
      );
    })
    .catch(function(err) {
      console.log(err);
    })
}

function getDataset(url) {
  return $.ajax(url)
    .then(csv => {
      const output = Papa.parse(csv, {
        header: true, // Convert rows to Objects using headers as properties
        dynamicTyping: true, // Convert some fields to Numbers automatically
      });
      if (output.data) {
        const labelMatches = url.match(/time_series_19-covid-(.+)\.csv$/);
        const label = labelMatches ? labelMatches[1] : "Untitled";

        const formatted = output.data.map(area => {
          const obj = {};

          Object.keys(area).forEach(key => {
            if (/^\d+\/\d+\/\d+$/.test(key)) {
              obj[key] = {
                date: key,
                [label]: area[key]
              };
            } else {
              obj[key] = area[key];
            }
          });

          return obj;
        });

        return formatted;
      } else {
        console.log(output.errors);
      }
    });
}

function combineDatasets(datasets) {
  if (datasets.length) {
    const combined = datasets.reduce((result, dataset, i) => {
      if (i === 0) {
        return result;
      }
      dataset.forEach(area => {
        // Look for area with same coordinates
        let existingArea = result.find(a => a.Lat === area.Lat && a.Long === area.Long);
        if (!existingArea) {
          result.push(area);
        } else {
          const dates = Object.keys(area).filter(key => /^\d+\/\d+\/\d+$/.test(key));
          dates.forEach(date => existingArea[date] = Object.assign(area[date], existingArea[date]));
        }
      });
      return result;
    }, datasets[0]);

    return combined.map(area => {
      const obj = {
        data: []
      };

      Object.keys(area).forEach(key => {
        if (/^\d+\/\d+\/\d+$/.test(key)) {
          obj.data.push(area[key]);
        } else {
          obj[key] = area[key];
        }
      });

      return obj;
    });
  } else {
    throw "No datasets were found";
  }
}

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ion-rangeslider/2.3.1/css/ion.rangeSlider.min.css" />

<input id="demo_4" />


text:
Q: WebBrowser не открывает некоторые сайты Некоторые сайты не открываются с помощью контрола webbrowser. Проверил версию webbrowser свойством version, версия полностью совпадает с установленным IE на компе. Установленный на компе IE 11 версии открывает все те сайты, которые я не могу открыть с помощью webbrowser в программе.  Можно ли как-нибудь решить проблему или нужно использовать что-то другое?
перехожу стандартным образом
webBrowser.Navigate("example_link");

Добавил свойство для отключения ошибок js, не помогло
webBrowser.ScriptErrorSuppresed = true;


text:
Q: What loop/logic do I need to print out 5 separate lines of a single array element? I am extremely new to coding and I am currently working on iterating over arrays. I am not sure why I am having trouble with this logic as I can already do a bunch of other stuff with arrays. I think I am forgetting some of the basics.
I am wanting to be able to print one of these array elements multiple times, either as a 'spam' e.g. printing out "Wave 1" 5 times in a row, or having a function that takes in a (num) and then spams it (num) times.
Here is the array:

const friendlyEmotes = ["Wave 1", "Wave 2", "Flirt 1", "Flirt 2", "Dance 1", "Dance 2", "High-five", "Laugh"]

And this is my code:
const spamWave = function(num){
   for (let i = 0; i < num; i++){
   return friendlyEmotes[0];
   }
}

I realize I am not using 'i' in the return statement and therefore am not utilizing the loop, but that is where I am missing the logic or syntax in order to use 'i' to print out the element multiple times.
I tried indexOf with using [i] without success:
const spamWave = function(num){
   for (let i = 0; i < num; i++){
   return friendlyEmotes.indexOf(0)[i];
   }
}

// spamWave(5) returns 'undefined'

I hope I was able to make my question clear and concise.
Any advice would be much appreciated.

A: You are returning the array element instead of logging it to the console. This should work for you: it's a function which takes an array, an index of the item in the array to log, and the number of times to log the element at the index:

const friendlyEmotes = ["Wave 1", "Wave 2", "Flirt 1", "Flirt 2", "Dance 1", "Dance 2", "High-five", "Laugh"];

function logArrayElementAtIndex (arr, index, logCount) {
  for (let i = 0; i < logCount; i += 1) {
    console.log(arr[index]);
  }
}

logArrayElementAtIndex(friendlyEmotes, 0, 5);


text:
Q: d3.js force layout on non-svg elements Can d3.js layout.force be used to (re)position non-svg elements like div's?
If div's have position: absolute; maybe left and top could be used as a equivalent for the x1 and y1 attributes as used for the svg elements?
The goal is to have some force effects on images and menu items with IE8 support. I'm aware of the fact that svg nodes can be images but as I need to support IE8 this is not an option.
If not possible, is using svgweb together with d3.js a stable option for this purpose?
Thanks!
**Update**
D3 is cool!! I'm starting to get the hang of it and it sure is possible to use "the force" on regular html elements like divs as d3.layout.force() essentially gives you x and y coordinates for every "tick" (or frame) which you can use however you want.
ie:
force.nodes(data)
     .on("tick", tick)
     .start();

function tick() {
     div.style("left", function(d) {return d.x+"px"})
        .style("top", function(d) {return d.y+"px"});
}

works just fine!
dragging with .call(force.drag); does give you problems (as expected).
firebug:
(container.ownerSVGElement || container).createSVGPoint is not a function
d3_svg_mousePoint()d3.js (line 3718)
container = div#nav
e = mousemove clientX=607, clientY=200
mouse()d3.js (line 3711)
container = div#nav
d3_behavior_dragPoint()d3.js (line 4481)
d3_behavior_dragDispatch()d3.js (line 4453)
type = "drag"
d3_behavior_dragMove()d3.js (line 4491)
l()d3.js (line 1871)
e = mousemove clientX=607, clientY=200
[Break On This Error]

var point = (container.ownerSVGElement || container).createSVGPoint();

Should be fixable though.

A: Here is an example showing svg, canvas and div elements all sharing the same force-directed layout: http://bl.ocks.org/4491174

A: In principle there is nothing SVG-specific in D3. You will have to see if it works in practice for your particular application, but it certainly sounds feasible. Have a look in particular at the documentation for force.layout.on, which has an example showing how to update node and link positions. If you change that code to modify the relevant position attributes of the div, it should work.


text:
Q: InvalidCastException in returning most recently added column I want to return the last column of most recently inserted record from a database table. I keep getting this error:

A first chance exception of type 'System.InvalidCastException' occurred in SchoolManagement.exe
Additional information: Specified cast is not valid.
If there is a handler for this exception, the program may be safely continued

Code:
public int A()
{
    string _connection = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
    string stmt = "SELECT TOP 1 RegistrationNumber FROM tblStudentBiodata ORDER BY RegistrationNumber DESC";

    int count = 0;

    using (SqlConnection thisConnection = new SqlConnection(_connection))
    {
        using(SqlCommand cmdCount = new SqlCommand(stmt, thisConnection))
        {
            thisConnection.Open();
            count = (int)cmdCount.ExecuteScalar();
        }
    }
    return count;
}

A: Your cast to int is throwing the exception:
count = (int)cmdCount.ExecuteScalar();

Your conversion is not safe, and you are certainly not getting back an integer from the ExecuteScalar method. In fact, the ExecuteScalar method will return the result wrapped (boxed) into an Object so be aware that the object could contain any type (e.g. float, decimal, int etc.).
Also make sure you are not casting from a null value, since that would be returned if there are no records in the table. So make sure to add a check if the object is null before attempting to cast.
Per my explanation, check the type of RegistrationNumber column in SQL server and make sure to cast to the correct type in your C# code.
Here is a list of the type mappings between SQL Server and C#:
http://msdn.microsoft.com/en-us/library/cc716729%28v=vs.110%29.aspx

A: As already pointed in another answer, below line is causing the exception and fir sure RegistrationNumber column is not INT type. I doubt it would be SQL CHAR or VARCHAR column.
count = (int)cmdCount.ExecuteScalar();

In this case, instead of doing a direct casting, try casting it indirectly using AS operator and declare your count variable as nullable Int like
int? count = 0;
count = cmdCount.ExecuteScalar() as int?;

Then check and use it
if (count != null)
{
   //Do something with it
}


text:
Q: Is that a good idea to keep CommunicationManager framework in my iOS project I have an old iOS app where it is using Communication Manager framework to communicate with my server. Since communication framework library files architectures are 32bit and I can not change the app architecture to 64bit because of these lib files. So I removed the communication manager framework totally and added AFNetworking for this app.
In my other old app, it is also using communication manager framework but that app is not using those 32bit lib files directly. Project is finding these lib files by library search path, but it's not included in the project 'Linked Framework and Libraries' section. Somehow communication framework is using AFNetworking framework, which is also used in this 2nd project. And this project architecture is 64bit.
NOW, is that a good idea to remove the communication manager framework totally from my 2nd project as well and use AFNetworking or just keep it as it is since it is not causing any problem now and app architecture is 64bit. I know from next iOS release Apple is going to support 64bit architecture app only.
Note: I didn't develop any of these apps from scratch.


text:
Q: python how to collect a specific file from a list of folders and save I have many folders in a master folder as given below. Each folder contains a .JPG file. I would like to extract all these files and store them in this master folder.

Inside each folder

My present code:
import os
import glob

os.chdir('Master folder')
extension = 'JPG'
jpg_files= [i for i in glob.glob('*.{}'.format(extension))]

This did not work.

A: To find the images in your tree, I would use os.walk.  Below you can find a complete example to 'find and move' function that move all the files to your given path, and create a new filename for duplicate filenames.
The simple 'find and replace' function will also check with function add_index_to_filepath whether or not the file already exists, add an index (n) to the path.  For example:  if image.jpg would exists, it turns the next one into turn into image (1).jpg and the following one into image (2).jpg and so on.
import os
import re
import shutil

def add_index_to_filepath(path):
    '''
    Check if a file exists, and append '(n)' if true.
    '''
    # If the past exists, go adjust it
    if os.path.exists(path):
        # pull apart your path and filenames
        folder, file = os.path.split(path)
        filename, extension = os.path.splitext(file)

        # discover the current index, and correct filename
        try:
            regex = re.compile(r'\(([0-9]*)\)$')
            findex = regex.findall(filename)[0]
            filename = regex.sub('({})'.format(int(findex) + 1), filename)
        except IndexError:
            filename = filename + ' (1)'

        # Glue your path back together.
        new_path = os.path.join(folder, '{}{}'.format(filename, extension))

        # Recursivly call your function, go keep verifying if it exists.
        return add_index_to_filepath(new_path)

    return path

def find_and_move_files(path, extension_list):
    '''
    Walk through a given path and move the files from the sub-dir to the path.
    Upper-and lower-case are ignored.  Duplicates get a new filename.
    '''
    files_moved = []

    # First walk through the path, to list all files.
    for root, dirs, files in os.walk(path, topdown=False):
        for file in files:
            # Is your extension wanted?
            extension = os.path.splitext(file)[-1].lower()
            if extension in extension_list:
                # Perpare your old an new path, and move
                old_path = os.path.join(root, file)
                new_path = add_index_to_filepath(os.path.join(path, file))

                if new_path in files_moved:
                    shutil.move(old_path, new_path)

                # Lets keep track of what we moved to return it in the end
                files_moved.append(new_path)

    return files_moved

path = '.'  # your filepath for the  master-folder
extensions = ['.jpg', '.jpeg']  # There are some variations of a jpeg-file extension.
found_files = find_and_move_files(path, extensions)


text:
Q: 404 Error using Flash Builder 4 BlazeDS wizard My issue this time around is trying to use the new DCD BlazeDS wizard in Flash Builder 4. If I set my project up as a combined Java/Flex app I am unable to connect to the RDS servlet using the wizard. I get a 404 error every time.
I'm certain the service is set up correctly since my app can access the exposed java classes and BlazeMonster can see the exposed services.
Is anyone else having this issue and if so has anyone found a work-around? I'd very much like to use the code generation features of the wizard for my project.
Thanks as always,
Codeflayer

A: You also need to make sure you have the RDSDispatchServlet setup in the web.xml config file.


text:
Q: Changing Menu Fonts Design I am using the 2011 theme and I would like to make the font that appears on the primary menu bigger and more stylish, is it possible for me to achieve this and if so, how to I go about it.

A: Your question is really a pure CSS and HTML question and not specifically WordPress.
It's best to learn to use Firebug with Firefox, or use the developer tools in Chrome or Safari or IE to view and work with the CSS and HTML in your theme and then make those changes to theme files, such as style.css.


text:
Q: waste and wastage what is difference between waste and wastage:
-The report is critical of the department's waste/wastage of resources
-This new technology will cut energy wastage/waste

A: When in doubt, just use waste. Wastage isn't super commonly used.


text:
Q: Connect Prototype Cells to View Controller [Swift 4] I am new to programming and currently working on a newsfeed like app. I had a normal Table view up and running fine, but want to try it now with a costume cell type. So I created one and thought connecting the labels the usual way would be perfectly fine, but I was wrong. So I am wondering how I can let my Text label connect to my view controller, so I can use my custom cell.
class ViewController: BaseViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet var newsfeedTableView: UITableView!

var ref: DatabaseReference!

var posts = [String]()

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return (posts.count)
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: "cell")

//here is where I need the custom label to get the posts
    cell.textLabel?.text = posts[indexPath.row]
    cell.textLabel?.font = UIFont.boldSystemFont(ofSize: 18.0)

    return cell
 }
}

A: Create subclass of UITableViewCell and connect IBOutlets to this class
class YourCell: UITableViewCell {
    @IBOutlet weak var customLabel: UILabel!
    ...
}

don't forget to set class of your prototype cell in storyboard:

then in cellForRowAt data source method downcast your dequeued cell as YourCell
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! YourCell

then you have access to YourCell outlets
cell.customLabel.text = "SomeText"
...

A: I'm assuming that you are using Storyboard.
First of all, you should understand that there is little difference when you use own custom table cell. In that case, in the method "cellForRowAtIndexPath", after dequeue your cell, you just have to typecast table cell like 'as! YourCustomTableCellClass'. After this line, you can access each property of this class.
First, design your table cell on Storyboard whatever you want.
Now, make a subclass of UITableViewCell and assign this class to your prototype custom cell which you have designed on Storyboard. Also, don't forget to set "reuse identifier in Storyboard table cell.
Then connect your outlets with custom cell class from Storyboard.
Now you can use code like this:
 class YourTableCellClass: UITableViewCell {

// I'm using these outlets as a sample, but you have to connect them from Storyboard.
var leftTextLabel: UILabel!
var rightTextLabel: UILabel!
}

class YourTableController: UITableViewController {

override func viewDidLoad() {
    super.viewDidLoad()
}

// MARK: - TableView Delegate & DataSource
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 1 // return your number of rows here...
}

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 100 // return the height for the row here.....or you can set height from Storyboard if you have fix height of all rows.
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "CellIdentifier", for: indexPath) as! YourTableCellClass
    cell.leftTextLabel.text = "Text" // Set text here....
    cell.rightTextLabel.text = "Text" // Set text here....
    return cell
}
}


text:
Q: Logstash kibana geoip filter conflict I have been trying to make Geo Filter working for logs. No luck yet.
I keep recreating my Logstash Index in ES, recreating GeoIP field with with Default type, double, and float, but Kibana keep complaining that my geoip.location property has Conflict.
Any suggestion would be appreciated.
geoip {
  source => "[headers][x-forwarded-for]"
  target => "geoip"
  database => "/etc/logstash/GeoLiteCity.dat"
  add_field => [ "[geoip][coordinates]", "%{[geoip][longitude]}" ]
  add_field => [ "[geoip][coordinates]", "%{[geoip][latitude]}"  ]
}
mutate {
  convert => [ "[geoip][coordinates]", "float"]
}

A: Resolved the issue by specifying default Mapping template, and recreating index now has "geo_point" data type for geoip.location.


text:
Q: Is it possible to flush rsyslog? I'm using the unix logger command to send a log to syslog. But it takes way too long on some machines to get to file. Is it possible to flush rsyslog so that it writes to disk faster.

A: /bin/kill -HUP `cat /var/run/syslogd.pid`

According to the man page for rsyslogd, this makes rsyslogd close all open files. So it will flush its log output to disk.


text:
Q: A field in a React Hook Form does not update the form state unless that field get the focus I am using React Hook Form. I have this simple form:
A simple form
When I enter values in the "quantity "and "price" fields, the third field, "total" shows the result of multiplying them. So far, all fine.  But I have noticed that when I click the submit button the value in the "total" field does not update the data form, unless that previously it get the focus by clicking on it.
This is what I get when I don't click the "total" field:
Showing the state form in the console
As you can see in the last image, the value of the "total" field is not reflected in the form state.
This is my code:
import { useForm } from "react-hook-form"

function App() {

  const { register, handleSubmit, watch } = useForm({
    defaultValues: {
      price: 0,
      quantity: 0,
      total: 0
    }
  });

  const onSubmit = data => console.log(data)

  return (

      <form onSubmit={handleSubmit(onSubmit)}>

          Quantity:
          <input type="number"
            {...register("quantity")}
          />

          Price:
          <input type="number"
            {...register("price")}
          />

        {
          /** 'total' is the result of multiplying the two previous fields.
          *   It only updates the form data when it get the focus.
          */
         }

          Total:
          <input type="number"
            {...register("total")}
            value={watch('price') * watch('quantity')}
            readOnly
          />

        <input type="submit" value='Submit' />
      </form>

  )
}

export default App

I was expecting the form state to update regardless of whether or not the "total" field got focus.
Thanks in advance everyone for your help.

A: Solved. Thank you @Anurag Srivastava (sorry I'm not allowed to vote yet).  This is the final code:
import { useEffect } from "react";
import { useForm } from "react-hook-form"

function App() {

  const { register, handleSubmit, setValue, watch } = useForm({
    defaultValues: {
      price: 0,
      quantity: 0,
      total: 0
    }
  });

  // I had to add these two lines
  const price = watch("price")
  const quantity = watch("quantity")

  useEffect( ()=> {
    setValue('total', price * quantity)
  }, [price, quantity, setValue])

  const onSubmit = data => console.log(data)

  return (

      <form onSubmit={handleSubmit(onSubmit)}>

          Quantity:
          <input type="number"
            {...register("quantity")}
          />

          Price:
          <input type="number"
            {...register("price")}
          />

        {
          /** 'total' is the result of multiplying the two previous fields.
          *   It only updates the form data when it get the focus.
          */
         }

          Total:
          <input type="number"
            {...register("total")}
            //value={watch('price') * watch('quantity')}
            readOnly
          />

        <input type="submit" value='Submit' />
      </form>

  )
}

export default App

A: Edit: You would need to watch the fields as well, to get their values in the app:
const price = watch("price")
const quantity = watch("quantity")

It might be easier for you to use setValue combined with useEffect:
const { register, handleSubmit, watch, setValue } = useForm({
  defaultValues: { price: 0, quantity: 0, total: 0 }
});

...

useEffect(() => {
  setValue('total', quantity * price)
}, [quantity, price])

...

  <input type="number"
    {...register("total")} // No need to watch
    readOnly
  />


text:
Q: How can I get OData DELETE to work? I've created an OData service (WCF Data Service), and a consumer to test it.
Previously, when I attempted to delete, I got the WebDAV 405 error message, "Method Not Allowed".
So I googled and found:
http://nikhilthaker86.wordpress.com/2010/03/27/issue-hosting-restful-services-on-iis-7/
I followed the instructions and removed the WebDav module from my website (service) in IIS 7.
Now I get this error message instead:
"HTTP Error 500.21 - Internal Server Error
Handler "WebDAV" has a bad module "WebDAVModule" in its module list
Module: IIS Web Core
Notification: ExecuteRequestHandler"
If you have a solution that will make this problem go away, I would really appreciate it... otherwise, if you're an IIS guru, and you're thinking "This guy has no idea what he's doing", please point me in the direction of some useful online reading material.
Thanks in advance.

A: The WebDAV module will block both the DELETE and PUT (update) verbs for IIS.  You can either uninstall WebDAV (recommended) or simply remove it from the Handlers of the site.  More details can be found here: http://forums.iis.net/t/1166025.aspx
One way to do this is to add the following remove lines to your site's web.config:
<system.webServer>
    <modules>
        <remove name="WebDAVModule" />
    </modules>
    <handlers>
        <remove name="WebDAV" />
    </handlers>
</system.webServer>


text:
Q: JavaScript - loop in button in forEach loop Can anyone Please help me. Im stuck in this code for about weeks now.
What I'm trying to do is have an image slider with buttons on the bottom of the image that will display corresponding information of the image in a modal.

<c:forEach var = "tempCustomer" items = "${customers}">

<button class="buttonImg myBtn" type="button" style="z-index:-1">Click Me!</button>

×

${tempCustomer.description}

</c:forEach>

Here is the JavaScript

Edited
Please can anybody please help me. Im stuck in this code forever.
Image is here
Image 2

A:
the problem is that only the first button works on the carousel, that
  is to open up the modal with the images's description, and the rest
  doest not work

The reason is because of this line
var btn = document.getElementsByClassName("buttonImg myBtn")[0];

btn.onclick = function() {
modal.style.display = "block";
}

document.getElementsByClassName("buttonImg myBtn")[0] will only give the first element,So no way the events is attached to the other buttons.
Use document.querySelectorAll('.buttonImg').
This will give a collection(simmilar to arraylist). Loop over that arrayList and attach cick event to all the event

A: Maybe this is something that is helpful to you as a starting point?
I tried to emulate your row of pictures since there is no Spring MVC on stackoverflow. Please forgive me for not formatting things properly. This is only meant as a principle sketch. I eliminated the ids from your elements as these would not be unique any more inside the loop.
The actual jquery part is very simple: I bind a click event to all buttons of class="myBtn" and inside the event function I handle the action:

*

*make all modals invisible

*make the current modal visible again (.show())

$(function(){
 $('.myBtn').click(function(){
   $('.modal').hide();      // first: hide *all* modals
   // $(this).next().show() // then: show the one next to the button
   // or in a general case, when div.modal can not
   // be guaranteed to be "next" to the button:
   $('.modal',this.parentNode).show()
 })
})
.sideways {vertical-align:top;display:inline-block;}
.modal {display:none}

 <button class="buttonImg myBtn" type="button" style="z-index:-1">Click Me!</button>

   ×

description 1

 <button class="buttonImg myBtn" type="button" style="z-index:-1">Click Me!</button>

   ×

description 2

 <button class="buttonImg myBtn" type="button" style="z-index:-1">Click Me!</button>

   ×

description 3