text:
Q: MVVM Model with Entity Framework I have a Prototype using WPF + MVVM + PRISM + ENTITY FRAMEWORK
The problem is that im very confuse if i use the ENTITY FRAMEWORK Entities as the Model of the MVVM pattern. I have a Business Logic Layer, and i had problems using mappers on this layer, because im very unhappy on the conversion (Map problem).
What i can do to simplify the code, use a real Model not the Entitie object(for me use the Entitie as model is incorrect on the frontend), with the MVVM pattern on mind... and stay good for changes on the future, it will have 200+ entities on the final version...
Thats my layers...(Please forget about Mapping, since i taked it off putting the EF entities on the ViewModel, but the image represents the correct layers)
Im not using the repository too since i can add it on the end with changes only on the BLL.

VIEW MODEL:
    my current prototype do a getall, put it on a grid, and on selectchanged of the grid i put selected item on the textbox, and the save button update this changes to the database.
public class CadastroClienteViewModel : BindableBase, ICadastroClienteViewModel
{
    private readonly IClienteBLL _clienteService;

    #region Model
    //public Cliente ObCliente { get; private set; }

    public int ClienteID
    {
        get { return ((Cliente)cliItems.CurrentItem).ClienteID; }
        set
        {
            ((Cliente)cliItems.CurrentItem).ClienteID = value;
            OnPropertyChanged("ClienteID");
        }
    }

    public string Nome
    {
        get { return ((Cliente)cliItems.CurrentItem).Nome; }
        set
        {
            ((Cliente)cliItems.CurrentItem).Nome = value;
            OnPropertyChanged("Nome");
        }
    }

    #endregion

    public CadastroClienteViewModel(IClienteBLL ServiceCliente)
    {
        //ObCliente = new Cliente();
        _clienteService = ServiceCliente;

        this.SaveCommand = new DelegateCommand(ExecuteMethodSave);
        this.RefreshCommand = new DelegateCommand(ExecuteMethodRefresh, CanExecuteMethodRefresh);
        RefreshCommand.Execute(null);
    }

    private void ExecuteMethodSave()
    {
        _clienteService.ClienteBLL_Update(((Cliente)cliItems.CurrentItem));

        RefreshCommand.Execute(null);
    }

    private bool CanExecuteMethodRefresh()
    {
        return true;
    }

    private void ExecuteMethodRefresh()
    {
        var personViewModels = _clienteService.ClienteBLL_GetAll();

        //cliente = new ObservableCollection<Cliente>(personViewModels);

        cliItems = new ListCollectionView(personViewModels.ToList());
        cliItems.CurrentChanged += CliItemsOnCurrentChanged;

        //OnPropertyChanged("cliente");
        OnPropertyChanged("cliItems");
    }

    private void CliItemsOnCurrentChanged(object sender, EventArgs eventArgs)
    {
        //OnPropertyChanged("ObCliente");
    }

    public ICommand SaveCommand { get; private set; }
    public ICommand RefreshCommand { get; private set; }

    //public ObservableCollection<Cliente> cliente { get; private set; }
    public ICollectionView cliItems { get; private set; }
}

MODEL(Im not using it... but i would like):
public class MCliente
{
    public int ClienteID { get; set; }
    public string Nome { get; set; }
}

EF Entitie:
namespace Sistema.DataEntities.Models
{
public class Cliente
{
    public Cliente()
    {
    }

    public int ClienteID { get; set; }

    public string Nome { get; set; }
}

BLL:
public class ClienteBLL : IClienteBLL
{
    readonly ISistemaContext _context;
    public ClienteBLL(ISistemaContext context)
    {
        _context = context;
    }

    public IEnumerable<Cliente> ClienteBLL_GetAll()
    {
        return _context.Cliente.AsEnumerable();
    }

    public Cliente ClienteBLL_GetByID(int id)
    {
        return _context.Cliente.Find(id);
    }

    public bool ClienteBLL_Adicionar(Cliente Obcliente)
    {
        _context.Cliente.Add(Obcliente);
        return _context.SaveChanges() > 0;
    }

    public bool ClienteBLL_Update(Cliente Obcliente)
    {
        _context.Cliente.Attach(Obcliente);
        _context.Entry(Obcliente).State = EntityState.Modified;
        return _context.SaveChanges() > 0;
    }

    public bool ClienteBLL_Delete(int id)
    {
        var clubMember = _context.Cliente.Find(id);
        _context.Cliente.Remove(clubMember);
        return _context.SaveChanges() > 0;
    }

A: I'm adding this as an answer (not a comment) even if it's not a final answer to your question (cause it's opinion-based) but it doesn't fit as a comment. That's just what I would do for a WPF application that requires a database.
I would entirely drop the idea of directly connecting your WPF application to your database. I would build a 3-tiers architecture, i.e. I would create a stateless webservice that does all the stuff on server side.
So you would have:

*

*the database

*the webservice (using WCF), that is connected to the database, that does all the data stuff for you (I would even make it responsible of the business stuff too)

*the WPF application, that is connected to the webservice:

*

*the View layer is your XAML + your code-behind

*the ViewModel layer is, well, your ViewModels (out of scope of your question, but feel free to ask if you have any question about that layer). The ViewModels asynchronously call the webservice

*the Model is the client WCF proxy
Some benefits of this approach:

*

*depending on the hardware/network harchitecture, could be a huge performance benefit to only make ONE call to the server instead of N calls (assuming the latency between the DB and the webservice (both on "server side") is lower than the one between the WPF application and the database)

*more scalable

*all benefits of the stateless approach: one Entity Framework context instantiation per webservice requests, so much easier to deal with concurrency issues (in case you have N WPF instances running concurrently)

*easier to maintain (loose coupling between tiers)

*easier to test (assuming you actually build tests)

*better security (no need to expose a direct access to the database over the network)


text: Q: control music player from other ios app which will receive control events from BLE device I want control music player like play, pause, play previous/next song from ios app which is responsible for receive control events from BLE device. Can you guys give me quick solution.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Convert Region to Path Does anybody know if there is a way to convert org.eclipse.swt.graphics.Region object to org.eclipse.swt.graphics.Path one?
I have a method that is returning Regions (different shapes) and I need to draw them in a Canvas.
Do you have any suggestions?


text:
Q: Python - Checks beginning of a list, until finds the correct item but I showed it which position to start with?     AccountU = ['Cam', 'Copper']
    AccountP = ['Pop1234', 'What?']

    def LoginA():
        print ("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=")
        print ("A few clicks away from your selection!")
        UserE = input("Username: ")
        if UserE in AccountU:
            for position, UserE in enumerate(AccountU):
                PasswordF = AccountP[position]
                PassE = input("Password: ")
                if PasswordF == PassE:
                    Menu()
        else:
            print ("Your account is not working.")
            LoginA()

In this code, I have tried to make it so that it will enter the username and then find out the position. This should allow it to crosscheck with the password, as they would've been entered at an identical time. However, instead it crosschecks from the beginning until it checks the right location.
For example, if I entered 'Copper' for my username then it would ask the password twice even though I entered 'What?' exactly. I think it could be to do with the 'for position, UserE in enumerate(AccountU):' in particular but I am very confused on what with.
Proof of requiring to enter the password twice.

A: You don't need to loop over every entry in AccountU - you know which username you are looking up, you just want the corresponding password. If you use the .index() method you can find the index of the username in the AccountU list. Then, assuming AccountP is directly matched to AccountU you can find the correct password at the same index, like so:
AccountU = ['Cam', 'Copper']
AccountP = ['Pop1234', 'What?']

def LoginA():
    print ("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=")
    print ("A few clicks away from your selection!")
    UserE = input("Username: ")
    if UserE in AccountU:
        PasswordF = AccountP[AccountU.index(UserE)]
        PassE = input("Password: ")
        if PasswordF == PassE:
            Menu()
        else:
            print ("Incorrect Password")
    else:
        print ("Your account is not working.")
        LoginA()

However, you would be better using a dictionary to store your usernames and passwords. This will ensure that the correct user is matched up to the correct password. Here's an example of how that might work:
accounts = {'Cam': 'Pop1234',
            'Copper': 'What?'}

def LoginA():
    print ("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=")
    print ("A few clicks away from your selection!")
    UserE = input("Username: ")
    if UserE in accounts.keys():
        PassE = input("Password: ")
        if accounts[UserE] == PassE:
            Menu()
        else:
            print ("Incorrect Password")
    else:
        print ("Your account is not working.")
        LoginA()

A: Problem is with
           for position, UserE in enumerate(AccountU):
                PasswordF = AccountP[position]

*

*you are overwriting UserE

*Your are asking password for every user.

Make if condition and check password for user entered.
           for position, User in enumerate(AccountU):
                if UserE == User:
                    PasswordF = AccountP[position]
                    .... your code ......

Using Dictionary is better choice.


text:
Q: CSS webkit-animation scroll top I'm not very good in CSS.
Following CSS continuously scroll the background image.
But I need to do is scroll top and stop the animation of the background image. Could you please help me on this matter.
body {
     background-image: url(<?php echo get_template_directory_uri().'/img /sas-sport-bg.jpg'; ?>);

    -webkit-animation:400s scroll  linear;
    -moz-animation:400s scroll  linear;
    -o-animation:400s scroll  linear;
    -ms-animation:400s scroll  linear;
    animation:400s scroll  linear;
}
 @-webkit-keyframes scroll{
    0%{
        background-position:0px 0px;
    }
}
@-moz-keyframes scroll{
    20%{
        background-position:0px -1000px;
    }
}
@-o-keyframes scroll{
    40%{
        background-position:0px -1000px;
    }
}
@-ms-keyframes scroll{
    80%{
        background-position:0px -1000px;
    }
}
@keyframes scroll{
    100%{
        background-position:0px -1000px;
    }
}

A: You can set the animation-fill-mode to forwards in your animation to stop the animation at the last state.
check the code below:
body {
         background-image: url(<?php echo get_template_directory_uri().'/img /sas-sport-bg.jpg'; ?>);

        -webkit-animation:400s scroll  linear forwards;
        -moz-animation:400s scroll  linear forwards;
        -o-animation:400s scroll  linear forwards;
        -ms-animation:400s scroll  linear forwards;
        animation:400s scroll  linear forwards;
    }
     @-webkit-keyframes scroll{
        100%{
            background-position:0px -1000px;
        }
    }
    @-moz-keyframes scroll{
        100%{
            background-position:0px -1000px;
        }
    }
    @-o-keyframes scroll{
        100%{
            background-position:0px -1000px;
        }
    }
    @-ms-keyframes scroll{
        100%{
            background-position:0px -1000px;
        }
    }
    @keyframes scroll{
        100%{
            background-position:0px -1000px;
        }
    }


text:
Q: Not self invoking anonymous functions Bootstrap css uses the following:
!function( $ ) {
}( window.jQuery )

That's different than the self-invoking anonymous function call that I originally learned:
(function($) {
})(jQuery);

Q: Is that just preference you think? I mean the not symbol instead of enclosing it in parenthesis.

A:
"Q: Is that just preference you think?"

Yes, but using a unary ! operator, you can avoid a few bugs when you forget a semicolon before the IIFE, which can cause the () to be interpreted as a function call.
alert('foo')  // alerts 'foo'

(function() {  // TypeError: undefined is not a function
    alert('bar');
})()

Here the outer () is interpreted as a function call. It's trying to call whatever was returned from the alert() function, which of course returns undefined, which isn't a function.

alert('foo')  // alerts 'foo'

!function() {
    alert('bar');  // alerts 'bar'
}()

No troubles with this one, since the ! is a unary operator that only evaluates the operand  to its right.

A: A statement starting with the function keyword is treated as a function declaration and must be followed by a name that is a valid identifier.
An anonymous function expression starts with the word function, but since there is no name, it can't be used where it might be confused with a function declaration. In most cases, the grouping operator is used to indicate a function expression:
(function() {
  /...
}());

or
(function() {
  /...
})();

You can also do:
var foo = function() {
}();

In all of the above, the function keyword isn't at the start of the statement so it's treated as the start of a function epxression. A name isn't required and the function can be immediately called.
It's the same with !function.... The parser sees the ! and says "what follows is an expression". When it gets to function it knows it's the start of a function expression.
Using !function… instead of (function…) saves a single character, and possibly creates a bit of confusion as it's a less common way to write a function expression.


text:
Q: facebook session cookie problem I'm using the php sdk on my canvas app in facebook.
i have 3 pages: index.php play.php & register.php
in both index & play i check if there is a session in this manner:
$session = $facebook->getSession();

$me = null;
// Session based API call.
if ($session) {
  try {
    $uid = $facebook->getUser();
    $me = $facebook->api('/me');
  } catch (FacebookApiException $e) {
    error_log($e);
  }
}

// login or logout url will be needed depending on current user state.
if ($me) {
  $logoutUrl = $facebook->getLogoutUrl();
} else {
  $loginUrl = $facebook->getLoginUrl(array('canvas' => 1,
                                          'fbconnect' => 0,
                                          'req_perms' => 'publish_stream,email',
                                          'next' => 'register.php',
                                          'cancel_url' => 'http://www.facebook.com/apps/application.php?id=MYAPPID&perms' ));
}

if (!$me){ print("");
print("");
print("Please wait..."); exit(); }

So that if i don't know who the user is and his new to my app, direct him to register.php and put his uid in my DB.
The problem i have is that some users can see correctly the entry page index.php but when navigating to play.php they get redirected to the register page. After that the same thing happens every time they try to enter the play page.
Something is terribly wrong here. i've tried clearing cookies but nothing seem to work.

A: I'd probably think that $facebook->api(...) can return values that are negative positives (ie. returns a value that evaluates to TRUE, but is really not, as in a string 'UNAUTHORIZED', or an empty array). Relying on just the not operator ('!') is probably not all that reliable, and I would check for return types (although I don't know the API and can't tell you what it is)
Best thing to do is a var_dump ( $facebook->api('/me') ) ; to see what it actually returns. Also you could try a proper test instead of just the not operator and the imperative, so instead of ;
if ( $me ) { ... }

Try ;
if ( is_object ( $me ) ) { ... }
if ( is_array ( $me ) ) { ... }
if ( ! empty ( $me ) ) { ... }

Or any of the other things that you could test for through $facebook->api('/me'), or even something specific like ;
if ( $me !=== NULL ) { ... }

Anyway, I'm sure your problem lies within the business logic of how to test for your return data.


text:
Q: Single quote character and wildcard in an SQLite query cases SQLiteException I have a search function in my app:
String selection = DatabaseContract.DbEntry.COLUMN_NAME + " like '%" + searchQuery + "%'";

When a user searches for ' like I'm, the app crashes raising an android.database.sqlite.SQLiteException.
What I want is the capability of the searching for that ' in the user input?
Is there a way to achieve that?

A: As with any externally supplied values, use variables in SQL:
String selection = DatabaseContract.DbEntry.COLUMN_NAME + " like '%' || ? || '%'";

with searchQuery in selectionArgs as value to be bound.


text:
Q: Why do "Properties" and df command return different used disk space? So I just formatted two SSDs to EXT4 and when I right-click and select Properties in file manager, I get a window that says 50 GB (!) of disk space is already used on the 1 TB disk and 100 GB (!!) is used on the 2 TB disk.
The df command hower indicates only 77 MiB are used on each.
Anyone know the reason for this discrepancy and how to determine the real values of available space?
Many thanks

A: Awesome, thanks Andrew. I reduced the space reserved for superuser to 2% using
sudo tune2fs -m2 /dev/sdc1


text:
Q: Sublime Text 2 autocompletion for python I have installed both SublimeCodeIntel and SublimeJEDI, but I am not getting the autocompletion from imported library.
What do I need to do to get available methods from imported library, say MySQLdb in Sublime Text 2? In Pycharm, if I import a library, I get all the available methods from that library as suggestion like from Google search. But this is not the case in Sublime Text. Is there any other plugin I have to install to get this feature?

A: My best advice would be to upgrade to Sublime Text 3 and use Anaconda for code completion. ST3 has a number of new features over ST2, and behind the scenes, the API has a bunch of changes that make writing and supporting plugins very easy - unfortunately, some of the changes are backwards-incompatible. ST2 includes Python 2.6 internally, while ST3 includes Python 3.3, so developers essentially either need to support two separate codebases, or have a lot of ugly if ST2: do this; else: do that type of constructs. The result of this is that a lot of plugin authors have chosen to only support ST3, meaning there are many more packages available for ST3 than ST2, and this includes Anaconda. The "beta" version of ST3 (currently build 3065) is just as stable as ST2. If you're a registered user (and you should be!), you have access to the bleeding-edge development builds (build 3081 was just released some hours ago), which have a ton of new features, but are sometimes less stable. I've been using ST3 exclusively (unless I need to test something on ST2) for well over a year now, and haven't had any issues at all.
As far as Anaconda goes (it has no relation whatsoever with the Anaconda Python distribution), I just love it. I used to use SublimeCodeIntel, but it was a little tough to configure, took a long time to index files, and oftentimes just didn't work well, if at all. Anaconda uses static analysis to figure out the type of your variables, and provides the appropriate methods and attributes via autocomplete. All you need to do is specify where Python lives on your machine, and it will automatically configure itself to use the standard lib for that version, as well as any 3rd-party modules you may have installed. It can be configured independently via .sublime-project files, so you can use different interpreter versions depending on the project you're working on - it also works with virtualenvs. Finally, it provides built-in linting via PEP8, PyLint, and/or PEP257, if you are so inclined (I just turn it off, as I think it's annoying, but it can be very helpful for novice coders). Aside from the fact that it just works, Anaconda's best feature is that it's entirely asynchronous, so it won't slow down ST3 or crash it if it has an unrecoverable error. I've never had it crash on me, through, another reason I like it.
Finally, just in case you were wondering, I have no connection to the Anaconda project at all, other than a single pull request that removed one character - I'm just a very satisfied user.


text:
Q: Whole home folder under git repo Recently installed oh-my-zsh. i noticed that in all my folders under home  directory there was a master from git plug in appearing.
    On branch master

Initial commit

Untracked files:
  (use "git add <file>..." to include in what will be committed)
    .AndroidStudio2.1/
    .CFUserTextEncoding
    .DS_Store
    .PyCharm40/
    .Xauthority
    .android/
    .atom/
    ...(list of all my folders)
nothing added to commit but untracked files present (use "git add" to track)

Should i git ignore my home folder? Any ideas?

A: Actually there was a .git folder inside my ~ directory and everything under it was mentioned as git repository. after deleting it the (master) word from git plug in dissapeared


text:
Q: Is there a more efficient way of looping a countdown timer using the turtle module? Hey I'm trying to make a simple countdown timer that counts down until my exams. It technically works but the way I've coded the "days" number being written is really inefficient. I had to do it this way though because when I had two texts being written (see code snippet below), the latter one would always blink.
text.write(str(delta), align="center", font=("Arial", 50, "normal"))
text2.write(str(delta_time), align="center", font=("Arial", 35, "normal"))

Here's the full code:
from turtle import Screen, Pen, Turtle
import datetime as dt

wn = Screen()
wn.title("Countdown until Mock Exams")
wn.tracer(0)
wn.colormode(255)
# wn.setup(width=300, height=200)

text = Turtle()
text.ht()
text2 = Turtle()
text2.ht()
text2.goto(0, -55)
zzz = 0
date_exams = dt.date(2022, 2, 14)

while True:
    print(zzz)
    # text.clear()
    text2.clear()
    date_now = dt.date.today()
    # print(dt.datetime())

    delta = date_exams-date_now
    delta = str(delta).split(",")
    del delta[-1]
    delta = delta[0]

    x = dt.datetime.today().strftime("%H:%M:%S")
    y = "23:59:59"
    format = "%H:%M:%S"

    delta_time = dt.datetime.strptime(y, format) - dt.datetime.strptime(x, format)
    text2.write(str(delta_time), align="center", font=("Arial", 35, "normal"))

    if zzz == 100 or zzz == 0: # this technically works but PC has to do more work (ie. fans start blowing)
        text.clear()
        text.write(str(delta), align="center", font=("Arial", 50, "normal"))
        zzz = 0
    zzz += 1

Any help is greatly appreciated!

A: You can use time.sleep(1.0) rather than counting the zzz.
from turtle import Screen, Pen, Turtle
import datetime as dt
import time

wn = Screen()
wn.title("Countdown until Mock Exams")
wn.tracer(0)
wn.colormode(255)
# wn.setup(width=300, height=200)

text = Turtle()
text.ht()
text2 = Turtle()
text2.ht()
text2.goto(0, -55)
date_exams = dt.date(2022, 2, 14)

while True:
    text2.clear()
    date_now = dt.date.today()
    # print(dt.datetime())

    delta = date_exams - date_now
    delta = str(delta).split(",")
    del delta[-1]
    delta = delta[0]

    x = dt.datetime.today().strftime("%H:%M:%S")
    y = "23:59:59"
    format = "%H:%M:%S"

    delta_time = dt.datetime.strptime(y, format) - dt.datetime.strptime(x,
                                                                        format)
    text2.write(str(delta_time), align="center", font=("Arial", 35, "normal"))

    text.write(str(delta), align="center", font=("Arial", 50, "normal"))
    time.sleep(1.0)


text:
Q: grabbing individual document in meteor template helper I am trying to access the individual document within a #each in Meteor so that I can mark it. Basically if the user clicks on the content I want to run some logic on that document. Example:
{{#each document}}
<div>
  {{text}}
  {{did_i_read_the_doc}}
</div>
{{/each}}

and I want the {{did_i_read_the_doc}} to show "yes" or "no" depending on whether it is marked in the collection. So in my template helper I want something like
Template.documents.helpers({
  did_i_read_the_doc: function() {
    //what goes here?
    if (thisIndividualDocument.contains(Meteor.userId() in "readBy")
      show "yes" in html
    else
      show "no" in html
  }

I'm not sure how to access the individual mongo document in the helpers wrapped in an each block. I'm used to the logic of returning all of the documents in a helper
    documents: function() {
      return Documents.find({})
    }
but how would I define a helper function that gets the individual document? In the final run of things I want to be able to click a document and mark it as read, like a notification, and have something that shows up saying "already read" or "unread" depending.

A: I figured this out right after I posted.
In the helper method you can use
my: function() {
  if(this.field)
    //do something

so 'this' grabs the individual document.
EDIT: just for example to solve my specific case
did_i_read_the_doc: function() {
  if(this.read) {
    return "yes"
  }
  else {
    return "no"
  }
}


text:
Q: .htaccess rewrite rule puzzle Because I need to password protect a subdirectory using cPanel, I modified Wordpress's .htaccess rule as instructed here: https://wordpress.org/support/topic/password-protect-a-directory-with-htaccess
This is my current wordpress rewrite block:
# BEGIN WordPress
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.php$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ./ /index.php [L]
</IfModule>

# END WordPress

Notice particularly this line:
RewriteRule ./ /index.php [L]

The normal wordpress Rewrite Rule is this:
RewriteRule . /index.php [L]

It works perfectly for the password-protected directory. But I seem to have lost the rewrite for when a page gets loaded without the trailing slash.
Before I changed this, Wordpress would look at a url like this:
http://example.com/about-us and load it up as http://example.com/about-us/ (with a trailing slash).
Now it simply goes to a Not Found page. It's not even loading the theme's 404 page.
Any ideas how to fix this without mucking up my password-protected directory?

A: You can use question mark:
RewriteRule ./?$ /index.php [L]


text:
Q: Generic ForEach Method that accepts a List and Value of same Type and Changes List Member Properties I have multiple classes with the same property. I want to create a single method that would serve the same purpose for each individual class.
Example:
 private void RefreshSelection<T>(ObservableCollection<T> itemList, T selectedItem)
    {
        foreach (var item in itemList)
        {
            item.IsSelected = selectedItem.Equals(item);
        }
    }

As expected, I recieve this error:
'T' does not contain a definition for 'IsSelected' and no extension method 'IsSelected' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?)

I have tried to find a useful answer but can only find examples of retrieving the property value, not changing it. Any advice is greatly appreciated.

A: You could use an Interface and decorate your classes that support IsSelected
public interface ISelectable
{
    bool IsSelected { get; set; }
}

public class MyAwesomeClass : ISelectable
{
    public bool IsSelected { get; set; }

    // Blah
}

private void RefreshSelection<T>(ObservableCollection<ISelectable> itemList, T selectedItem)
    where T : class, ISelectable
{
    foreach (var item in itemList)
    {
        item.IsSelected = selectedItem.Equals(item);
    }
}

A: Create an interface called IIsSelected
public interface IIsSelected
{
   bool IsSelected { get; set; }
}

Then implement this interface on your classes which has the IsSelectedproperty:
public class MySelectableClass : IIsSelected
{
    public bool IsSelected { get; set; }
}

Update your method to:
private void RefreshSelection<T>(ObservableCollection<T> itemList, T selectedItem)
where T: IIsSelected
{
    foreach (var item in itemList)
    {
        item.IsSelected = selectedItem.Equals(item);
    }
}

The method will only except any type which implements the IIsSelected interface and the compiler won't throw an error.

A: The other answers are great, but occasionally there are situations where you cannot decorate existing classes with an interface. For example,

*

*the class definitions are in 3rd-party DLLs,

*you do not have permission from the team leader.

For these situations, move the property-set outside your function, passing it in as a lambda function instead:
private void RefreshSelection<T>(ObservableCollection<T> itemList, T selectedItem,
                                 Action<T, bool> setSelected)
{
    foreach (T item in itemList)
    {
        setSelected(item, selectedItem.Equals(item));
    }
}

and call it this way:
RefreshSelection(itemList, selectedItem, (i, newValue) =>
{
    i.IsSelected = newValue;
});

This is a standard technique for reusing code - extensively used by Linq and jQuery.


text:
Q: subversion not working with pycharm In pycharm, there is an option to upload changes to a remote svn repository.
However, it does not ask for password. How do I provide it?

A:
it does not ask for password.

Maybe because of caching:
you can disable credential caching. To disable caching for a single command, pass the --no-auth-cache option:
$ svn commit -F log_msg.txt --no-auth-cache
Authentication realm: <svn://host.example.com:3690> example realm
Username:  mark
Password for 'mark':

Adding         newfile
Transmitting file data .
Committed revision 2324.

# password was not cached, so a second commit still prompts us

$ svn delete newfile
$ svn commit -F new_msg.txt
Authentication realm: <svn://host.example.com:3690> example realm
Username:  mark
[...]

Or, if you want to disable credential caching permanently, you can edit your runtime config file (located next to the auth/ directory). Simply set store-auth-creds to no, and no credentials will be cached on disk, ever.
[auth]
store-auth-creds = no

As source you can make use of this Link.

A: From the PyCharm documentation regarding authenticating to Subversion:

Subversion server does not require user authentication on every
  request. When you use the Subversion integration from within PyCharm,
  you only need to answer the authentication challenge of the server, if
  it is required by the authentication and authorization policies. The
  successful authentication results in saving your credentials on disk,
  in ~/.subversion/auth/ on Unix systems or <USER HOME>/.subversion_IDEA
  on Windows and OS X.
When an authentication challenge comes from the server, the
  credentials are sought for in the disk cache; if the appropriate
  credentials are not found, or fail to authenticate, the users is
  prompted to specify the login name and password.
If necessary, you can opt to delete all credentials stored in cache,
  for http, svn and ssh+svn protocols.


text:
Q: Как определить прокси / не прокси Как узнать, юзер зашел под прокси или нет? Точно знаю, что есть способ)
Можно и php и .htaccess - без разницы.
A: Точного способа нет. Есть Элитные (High-Anonymous ka HIA) прокси, которые нигде не оставляют пыли за собой.
Но вообще можете сравнивать переменные
$_SERVER['REMOTE_ADDR']
$_SERVER['HTTP_X_REAL_IP']
$_SERVER['HTTP_X_FORWARDED_FOR']

И если там разные адреса - это почти наверняка был прокси (хреновый, но таки прокси))
После socks-проксей вообще грустно определять, там все заголовки ручками пишутся.
Вариант для извращенцев - отправить на $_SERVER['REMOTE_ADDR'].$_SERVER['REMOTE_PORT'] запрос по протоколам CONNECT, SOCKS4, SOCKS5, так вы точно спалите все прокси без авторизации) Только предупрежу, что эти три запроса могут идти ок.10 сек в зависимости от таймаутов/отклика/нагрузки на сервер, потому для каждого юзера это делать нелогично совсем.
Еще почитайте вот эту штуку , есть несколько нетривиальных способов. Однако упор сделан на яву и куки, первое часто отключено, второе часто чистят. А вот проверка IP в списках - неплохой способ.
Добавлено
$ip1 = @$_SERVER['REMOTE_ADDR'];
$ip2 = @$_SERVER['HTTP_X_REAL_IP'];
$ip3 = @$_SERVER['HTTP_X_FORWARDED_FOR'];
if ( (!!$ip2 && ($ip1 != $ip2)) || (!!$ip3 && ($ip1 != $ip3)) )
  die('No proxy, please.');

Добавлено с покаянием
Прошу прощения, но заинтересовало и понял, что задачу я сильно усложнил =(
На самом деле факт того, что переменная $_SERVER['HTTP_VIA'] не пуста, равен факту использования прокси. А код выше скорее предназначен для определения истинного IP. Элитные от анонимок отличает то, что их таким образом не пропалить. Но элита на то и элита, что их очень мало и найти трудно.
Итого, ваш код:
if (!empty($_SERVER['HTTP_VIA']))
  die('No proxy, please.');


text:
Q: fullpage.js setAllowScrolling I have tried to disable the scrolling down on section 4 into section 5.
Does not seem to respond to this:
        if(anchorLink == 'support-contact' && slideIndex == 0) {
        $.fn.fullpage.setAllowScrolling(false, 'down');
        $.fn.fullpage.setKeyboardScrolling(false, 'down');
        }

support-contact is set here (section 5 not set as it is hidden section):
$(document).ready(function() {
initialize(false);
function initialize(hasScrollBar){
$('#fullPage').fullpage({
    anchors: ['home', 'livingwell', 'happybuy', 'support-contact'],
    loopHorizontal: false,
    controlArrows: true,
    menu: '#menu',

A: Please provide an isolated reproduction in jsfiddle or codepen. It is working as expected as can be seen here https://jsfiddle.net/1kyuL4em/42/
But notice the afterSlideLoad or onSlideLeave callbacks won't get fired when landing in the section as a result of a vertical movement.
Only horizontal movements will fire them.
So you probably want to also make use of the afterLoad or onLeave callbacks and calculate the index of the current slide within the horizontal slider by using something like the following:
$('.fp-section.active).find('.fp-slide').index();

A: Sorry to re-open, but I have the same issue with a fullpage.js based website.
I have 8 sections, each one with only 2 slides.
The first slide is full screen, but the second is a long scrolling page.
I want that when on the 2nd, it is not possible to scroll up or down to the next or previous section, but that we can only use the "previous" arrow to go back to the first slides.
I have tried both functions below, but none is working.
afterLoad: function(anchorLink, index, slideIndex, direction, nextSlideIndex){
var thisSlide = $('.fp-section.active').find('.fp-slide').index();
if(thisSlide === 1){
$.fn.fullpage.setAllowScrolling(false, 'up, down');
}
},

afterLoad: function(slideIndex){
if(slideIndex === 1){
$.fn.fullpage.setAllowScrolling(false, 'up, down');
}
},

If I simply use this function :
afterLoad: function(){
$.fn.fullpage.setAllowScrolling(false, 'up, down');
},

It works, but the vertical scrolling is also disabled on the first slides, which is not what I intend to do.
If anyone has an idea, thanks!

A: I dont know if this was the best way to solve the issue but i worked for me in then end. Hope it helps you. If you get stuck shout me.I have hit the wall so many times i have a few work around for things. im a crap programmer but i try. There is better guys out here but silent.
So i target the sections and give each one an instruction so it does not carry the instruction from the previous slide:
afterLoad: function(anchorLink, index){
if(index == 3 && anchorLink == 'golden-visa'){
    $('body.fp-viewing-slidefree').find('.fp-section').index();
        $.fn.fullpage.setAllowScrolling(true, 'all');
        $.fn.fullpage.setKeyboardScrolling(true, 'all');
}
if(index == 4 && anchorLink == 'ahimsa-investments'){
    $('body.fp-viewing-ahimsa-investments').find('.fp-section').index();
        $.fn.fullpage.setAllowScrolling(false, 'down');
        $.fn.fullpage.setKeyboardScrolling(false, 'down');
}
if(index == 5 && anchorLink == 'investment-information'){
    $('body.fp-viewing-investment-information').find('.fp-section').index();
        $.fn.fullpage.setAllowScrolling(false, 'all');
        $.fn.fullpage.setKeyboardScrolling(false, 'all');
        }
},

I have another similar issue which i posted here but it seems no one gets back to me. A shame... This is certainly an issue maybe a bug but cant get around it and stuck with a product that should work:
Fullpage.js disable vertical scroll on section


text:
Q: Can't find 'Convert to Android system permissions' and 'Infer Annotations' under Analyse menu I want to use the new tools android-studio 2.2 has to offer :

*

*Convert to Android system permissions

*Infer Annotations

However, i can't see those tools in the menu.
I've tried restart, selecting other files, selecting the whole project, but - no luck so far - i still not able to see those entries in the menu.
I'm using Android Studio 2.2 Preview 1
Build #AI-145.2878421, built on May 17, 2016
I've been folowing the guide on the official site : http://android-developers.blogspot.co.il/
and the i/o guide (the tools are described at around the time 21:00)

A: Convert to android system permission
At 21:45 he says "This is still a work in progress". The feature is not done yet, therefore you cannot find it in the IDE.
Infer annotations
At 21:10 he says that this functionality is behind "a flag". It is unclear which flag, or how to enable it.
It is also discussed here on reddit, but no conclusive results yet.
The experimental thing they mention there is not related to these
features.

I waited for the release of 2.2 preview 2, but they are not in there either.
It can be safely assumed that both these features will be released with future versions of android studio.


text:
Q: Is there an easy way in VBA to shift the Range("B2:B5, FB2:OR5") over 1 each time you click a button? Essential, the goal is to update a graph by shifting the range by 1 with a button click.
i.e. Worksheets("Sheet1").Range("B2:B5, FB2:OR5") to
Worksheets("Sheet1").Range("B2:B5, FC2:OS5")
next click would change the range to .Range("B2:B5, FD2:OT5")...
Going with @BigBen's idea
    Dim Range1 as Range
    Last_col = Worksheets("Sheet1").Range("ZZ216").End(xlToLeft).Column
    First_col = Last_col - 251
    Set Range1 = Worksheets("Sheet1").Range(Worksheets("Sheet1").Cells(216, First_col), _
        Worksheets("Sheet1").Cells(219, Last_col))

Now that I have this, how do I concatenate it back into this format .Range("B2:B5, FC2:OS5")?

A: Using @BigBen's approach
 Dim Range0 as Range
 Dim Range1 as Range
 Dim Range2 as Range

 Set Range0 = Worksheets("Sheet1").Range("B2:B5")

 Last_col = Worksheets("Sheet1").Range("ZZ216").End(xlToLeft).Column
 First_col = Last_col - 250
 Set Range1 = Worksheets("Sheet1").Range(Worksheets("Sheet1").Cells(216, First_col), _
    Worksheets("Sheet1").Cells(219, Last_col))

 Set Range2 = Union(Range0, Range1)

 Worksheets("Sheet 2").ChartObjects("Chart 1").Activate
 ActiveChart.SetSourceData Source:=Range2


text:
Q: What's the difference between look towards the road and look off towards the road? What does 'off' imply here? Would the meaning change if we took it out?

*

*McVries spoke absently, still looking off towards the road. (from a novel)

*McVries spoke absently, still looking towards the road. (a made up example)

A: "off" here means "away from the focus of attention" or "without any focus".
(To avoid unclear pronouns, I'm going to pretend McVries is a woman)
So the first sentence implies that McVries isn't looking at the person or thing that she normally ought to in her current situation. I imagine she's having a conversation with someone and not meeting their gaze, or there's something she's trying to avoid looking at, like a dead body.
The second sentence suggests McVries was focusing her attention on the road because there's something interesting there.


text:
Q: ASP.NET MVC view - get data from dynamic expando object showing Id's not names from another table EF class I populated my view with dynamic expando using Entity Framework classes. I have two tables tribe and Asserah.
Tribe has Id and tribeName columns where as Asserah has Id , Asserahname and Tribeid. Both tables have primary key on column Id but no FK.
My controller is passing data to the view like this:
public ActionResult ViewAll()
{
    dynamic dy = new ExpandoObject();
    dy.asserah = GetAllAsserash();
    dy.tribe = GetAllTribes();
    return View(dy);
}

View is like this:
@foreach (Asserah item in Model.asserah) {

            @Html.DisplayFor(modelItem => item.AsserahName)

            @Html.DisplayFor(modelItem => item.TribeId)
            *@Html.DisplayFor(modelItem => item.TribeName)@*

            @Html.ActionLink("Edit", "Edit", new { id=item.AsserahId }) |
            @Html.ActionLink("Details", "Details", new { id=item.AsserahId }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.AsserahId })

}

I actually add
[NotMapped]
public Tribe TribeName { get; set; }

to Asserah EF class to display it in view but it is not showing any value
Can anyone help me out to get TribeName instead of TribeId?
BR


text:
Q: How to make mat-checkbox like a radio button I have a mat-checkbox in the angular project. How to make a mat-checkbox can only be selected one. (No more than one). Here's the code I have:
<mat-checkbox>Pre Order</mat-checkbox>
<mat-checkbox>Order</mat-checkbox>

Can anyone help? I want the mat-checkbox to behave like a mat-radio-button.

A: Just to get the correct answer:

*

*Use the mat-radio-button

*Set border-radius: 0%; for .mat-radio-outer-circle css class

And that's it!
Cheers!


text:
Q: iOS event bound using addEventListener is not triggering I'm trying to bind a click event to document. Click bound using addEventListener is not triggering. Click is only triggered when clicked on an element having v-on:click event.
This is happening in iOS.
Fiddle
Please try clicking on the orange and grey areas in the fiddle on iOS Safari.
Please help!


text:
Q: awk add string to each line except last blank line I have file with blank line at the end. I need to add suffix to each line except last blank line.
I use:
awk '$0=$0"suffix"' | sed 's/^suffix$//'
But maybe it can be done without sed?
UPDATE:
I want to skip all lines which contain only '\n' symbol.
EXAMPLE:
I have file test.tsv:
a\tb\t1\n
\t\t\n
c\td\t2\n
\n

I run cat test.tsv | awk '$0=$0"\t2"' | sed 's/^\t2$//':
a\tb\t1\t2\n
\t\t\t2\n
c\td\t2\t2\n
\n

A: It sounds like this is what you need:
awk 'NR>1{print prev "suffix"} {prev=$0} END{ if (NR) print prev (prev == "" ? "" : "suffix") }' file

The test for NR in the END is to avoid printing a blank line given an empty input file. It's untested, of course, since you didn't provide any sample input/output in your question.
To treat all empty lines the same:
awk '{print $0 (/./ ? "suffix" : "")}' file

A: this will skip all blank lines
awk 'NF{$0=$0 "suffix"}1' file

to only skip the last line if blank
 awk 'NR>1{print p "suffix"} {p=$0} END{print p (NF?"suffix":"") }' file

A: @try:
awk 'NF{print $0 "suffix"}' Input_file

A: If perl is okay:
$ cat ip.txt
a   b   1

c   d   2

$ perl -lpe '$_ .= "\t 2" if !(eof && /^$/)' ip.txt
a   b   1    2
             2
c   d   2    2

$ # no blank line for empty file as well
$ printf '' | perl -lpe '$_ .= "\t 2" if !(eof && /^$/)'
$

*

*-l strips newline from input, adds back when line is printed at end of code due to -p option

*eof to check end of file

*/^$/ blank line

*$_ .= "\t 2" append to input line

A: Try this -
$ cat f ###Blank line only in the end of file
-11.2
hello

$ awk '{print (/./?$0"suffix":"")}' f
-11.2suffix
hellosuffix

$

OR
$ cat f  ####blank line in middle and end of file
-11.2

hello

$ awk -v val=$(wc -l < f) '{print (/./ || NR!=val?$0"suffix":"")}' f
-11.2suffix
suffix
hellosuffix

$


text:
Q: Django executes the view functions many times when client has submitted a form just only once I need to upload user's image to server for django(1.8) to process it.
I'm sure the client only submits the form only once. Howerver, the backend executed the related view function many times and return 504 when I submitted a little large image(about 2M).
Here is my html:

 <form action="/test/" method="POST" id="upload_form" enctype="multipart/form-data">
      {% csrf_token %}

      <input id="choose_btn" class="btn" name="user_image"  type="file">
 </form>
 <button type="button" id="upload_btn" class="btn btn-danger " data-loading-text="uploading..." autocomplete="off"> Upload!</button>

Here is my js(insure there is only one submit , inspired from https://stackoverflow.com/a/4473801/1902843):

$('#upload_btn').click( function () {
        var $btn = $(this).button('loading');
        $('#upload_form').submit(function(e){
            console.log("start submit");
            var $form = $(this);
            if ($form.data('submitted') === true) {
                // Previously submitted - don't submit again
                console.log("has submitted!");
                e.preventDefault();
            } else {
                console.log("first submitted");
                // Mark it so that the next submit can be ignored
                $form.data('submitted', true);
            }
        });
        $('#upload_form').submit();
    });

and my back-end view function is:
model

class UserImage(models.Model):
    image = models.ImageField(upload_to='./user_image/%Y%m/%d', storage=ImageStorage(), blank=False)
    detect_result = models.TextField(max_length=1000, blank=True)

view

@csrf_exempt
def test(request):
    # if use form's is_valid() function, it always return false.
    # very weird, thus i annotate it
    # if request.method == 'POST':
    #     form = UploadFileForm(request.POST, request.FILES)
    #     if form.is_valid():
    user_image = request.FILES['user_image']
    im = UserImage(image=user_image)
    im.save() #after looking for log, it saved many times depending on image size?
    img_path = settings.MEDIA_URL + str(im.image)
    ...
    processing image
    ...

    return render_to_response('open.html', result_data)

A: I would personally start by placing your submit button within the form.
<form action="/test/" method="POST" id="upload_form" enctype="multipart/form-data">
    {% csrf_token %}

    <input id="choose_btn" class="btn" name="user_image"  type="file">
    <button type="button" id="upload_btn" class="btn btn-danger " data-loading-text="uploading..." autocomplete="off"> Upload!</button>
</form>

And then use an event listener on the #upload_btn instead of triggering a click.  Also, only call $('#upload_form').submit() once
$('#upload_btn').on('click', function (e) {  // Attach a click event listener
    // Check the form, display loading icon, etc
    // and when ready to submit the form ...
    $('#upload_form').submit();
});


text:
Q: Delphi multi color value in TStringGrid I want the currency values in the TStringGrid table to have different color decimals. How can do that?

A: You need to draw the cells yourself by implementing an OnDrawCell handler.
Something like this:
procedure TForm1.StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer;
  Rect: TRect; State: TGridDrawState);
var
  Grid: TStringGrid;
  S: string;
  Val: Double;
  FracVal, IntVal: Integer;
  FracStr, IntStr: string;
  IntW, FracW, W, H: Integer;
  Padding: Integer;
const
  PowersOfTen: array[0..8] of Integer =
    (
      1,
      10,
      100,
      1000,
      10000,
      100000,
      1000000,
      10000000,
      100000000
    );
  Decimals = 2;
  BgColor = clWhite;
  IntColor = clBlack;
  FracColor = clRed;
begin

  Grid := Sender as TStringGrid;

  if (ACol < Grid.FixedCols) or (ARow < Grid.FixedRows) then
    Exit;

  Grid.Canvas.Brush.Color := BgColor;
  Grid.Canvas.FillRect(Rect);

  S := Grid.Cells[ACol, ARow];
  Padding := Grid.Canvas.TextWidth('0') div 2;

  if not TryStrToFloat(S, Val) or not InRange(Val, Integer.MinValue, Integer.MaxValue) then
  begin
    Grid.Canvas.TextRect(Rect, S, [tfSingleLine, tfVerticalCenter, tfLeft]);
    Exit;
  end;

  IntVal := Trunc(Val);
  IntStr := IntVal.ToString;
  if Decimals > 0 then
    IntStr := IntStr + FormatSettings.DecimalSeparator;
  IntW := Grid.Canvas.TextWidth(IntStr);
  FracVal := Round(Frac(Abs(Val)) * PowersOfTen[Decimals]);
  FracStr := FracVal.ToString.PadRight(Decimals, '0');
  if Decimals = 0 then
    FracStr := '';
  FracW := Grid.Canvas.TextWidth(FracStr);
  W := IntW + FracW;
  H := Grid.Canvas.TextHeight(IntStr);

  if W >= Grid.ColWidths[ACol] - 2*Padding then
  begin
    S := '###';
    Grid.Canvas.TextRect(Rect, S, [tfSingleLine, tfVerticalCenter, tfRight]);
  end
  else
  begin
    Grid.Canvas.Font.Color := IntColor;
    Grid.Canvas.TextOut(Rect.Right - Padding - W,
      Rect.Top + Rect.Height div 2 - H div 2, IntStr);
    Grid.Canvas.Font.Color := FracColor;
    Grid.Canvas.TextOut(Rect.Right - Padding - FracW,
      Rect.Top + Rect.Height div 2 - H div 2, FracStr);
  end;

end;

This code will write non-numeric data left-aligned as is. For numeric data, it will draw the values with a fixed number of decimals. You can choose the decimals (0..8), as well as the colours of the integral and fractional parts. If the number doesn't fit in its cell, ### will be displayed instead.

I haven't fully tested the code. I'll leave that to you as an exercise.
Update: Sorry, I forgot you are using Delphi 7. This means that you need to replace IntVal.ToString with IntToStr(IntVal) and so on.


text:
Q: JPA/HIBERNATE Handle non POJO entity I have three classes. ClassA and ClassB are classical POJO entity mapped in database. I want a third ClassC to perform a specific and complex query in database (not mapped with any table) using HQL. Is that possible to add @Entity annotation on ClassC and persist it for reading only?
I am going through the documentation to figure out a way to map the following (sample) sql statement:
select
 a.id, b.name, c.city
from
 emp a, identity b, address c
where
 a.id = b.id and a.id = c.id

I don't want to create domain objects and mapping for emp, identity and address.
All I want is to have one object, mapped to the output of the sql statement.
public class Data {
 private int id;
 private String name;
 private String city;
 // ... and other details ...
}

Technically, this should be the job of a stored procedure or a view. Unfortunately, I cannot change the database.
Any help / pointers would be appreciated.

A: You can create your very complex SQL query as a view and map your entity to that. Basically, a view is just a read-only table (you can make it as a read-write in Oracle but that is another story :) ) so any hibernate mapping would work fine as a read-only entity. I've done that before but years ago using plain Hibernate and hbm files. I have never tried using JPA or annotations but I can't see why it wouldn't work.


text:
Q: How do I put both PCA and a keras classifier into an sklearn pipeline and do a grid search CV? I am trying to do a grid search CV operation on a keras NN with PCA beforehand. To this end, I have constructed a pipeline consisting of the PCA step then the keras estimator using the sklearn wrapper. However, one of the things I want to search through is n_components of the PCA, which means that the input size of the neural net needs to be variable and dependent on the number of features selected in a previous piepline step.
Below is my code to create a NN which I have put into a keras wrapper
def create_model(learning_rate=0.01, activation='relu',Input_Vector_Size=34,
                 neuron_number=10,dropout_prob=0.1):
    # Create an Adam optimizer with the given learning rate
    opt=Adam(lr=learning_rate)

    # Create your binary classification model
    model=Sequential()
    model.add(Dense(neuron_number,input_shape=(Input_Vector_Size,),
                    activation=activation))
    model.add(Dropout(dropout_prob))
    model.add(Dense(1,activation='sigmoid')) #output layer

    # Compile model with your optimizer, loss, and metrics
    model.compile(optimizer=opt,loss='binary_crossentropy',
                  metrics=['accuracy'])

    return model

Which I put into a pipline using
#%% Create a Pipeline with the Keras_Classifier and PCA
pca=PCA(n_components=0.9)
NN=KerasClassifier(build_fn=create_model,verbose=0)
# Define the parameters to try out
pipeline=Pipeline([('pca',pca),('NN',NN)])
params = {'pca__n_components':[0.8,0.85,0.9,0.95],
          'NN__activation': ['relu', 'tanh'],
          'NN__neuron_number': [10, 15, 20],
          'NN__dropout_prob':[0.05,0.1,0.2,0.3],
          'NN__learning_rate': [0.1, 0.01, 0.001]}

However I'm a bit stuck on what to set as the param for Input_Vector_Size as this will be dependent on how many features PCA has selected.
So, is it possible to make a pipeline parameter (here, the Input_Vector_Size) that is dependent on a parameter in a previous step of the pipeline (here, the number of features selected by PCA)?
(Note: I realize that one option around this is to just have an autoencoder in my NN and vary the compression, however I was hoping to do PCA specifically)


text:
Q: not able to install a python package I am trying to install a module in python but it is throwing me below error. I dont understand. I am also not able to find wheel file for this module.
Anyone else imported this module ?
Module Name :generatengrams
pip install generatengrams
from generatengrams import ngrammatch

Getting below error:
Could not find a version that satisfies the requirement generatengrams (from versions: )
No matching distribution found for generatengrams

A: pip install ngram

Check Python ngram. PyPI


text:
Q: How Do I Use WkHtmlToXSharp in C# I've read a lot about WkHtmlToXSharp (wrapper for wkhtmltopdf) so I downloaded it.  The one page that appears to be the only documentation states you only need the wkhtmltosharp.dll, but I can't find it in the file I downloaded.  It appears to be several projects, and the thing that looks like a DLL in the Libs/Win64 folder won't load into my project.
I'd GREATLY appreciate it if someone could point me to some instructions, and maybe some basic samples.
I need to know where the .DLL is, what namespace to use, and general usage syntax to convert a HTML file to PDF.
THANK YOU!!

A: public static string ConvertHTMLtoPDF(string htmlFullPath, string pageSize, string orientation)
{
   string pdfUrl = htmlFullPath.Replace(".html", ".pdf");

   try
   {
       #region USING WkHtmlToXSharp.dll
       //IHtmlToPdfConverter converter = new WkHtmlToPdfConverter();
       IHtmlToPdfConverter converter = new MultiplexingConverter();

       converter.GlobalSettings.Margin.Top = "0cm";
       converter.GlobalSettings.Margin.Bottom = "0cm";
       converter.GlobalSettings.Margin.Left = "0cm";
       converter.GlobalSettings.Margin.Right = "0cm";
       converter.GlobalSettings.Orientation = (PdfOrientation)Enum.Parse(typeof(PdfOrientation), orientation);
       if (!string.IsNullOrEmpty(pageSize))
           converter.GlobalSettings.Size.PageSize = (PdfPageSize)Enum.Parse(typeof(PdfPageSize), pageSize);

       converter.ObjectSettings.Page = htmlFullPath;
       converter.ObjectSettings.Web.EnablePlugins = true;
       converter.ObjectSettings.Web.EnableJavascript = true;
       converter.ObjectSettings.Web.Background = true;
       converter.ObjectSettings.Web.LoadImages = true;
       converter.ObjectSettings.Load.LoadErrorHandling = LoadErrorHandlingType.ignore;

       Byte[] bufferPDF = converter.Convert();

       System.IO.File.WriteAllBytes(pdfUrl, bufferPDF);

       converter.Dispose();

       #endregion
   }
   catch (Exception ex)
   {
       throw new Exception(ex.Message, ex);
   }

   return pdfUrl;
}

A: WkHtmlToXSharp does not have a 64bit version at this stage, you need to use the 32bit version.
You should find WkHtmlToXSharp.dll somewhere in the package.
using WkHtmlToXSharp;
IHtmlToPdfConverter htmlToPdfConverter = new MultiplexingConverter();
htmlToPdfConverter.ObjectSettings.Load.LoadErrorHandling = LoadErrorHandlingType.ignore;
htmlToPdfConverter.Convert(viewHtml);


text:
Q: Make a view appear and disappear in a button I want to make a view appear out of a button (slide up and zoom) on click and then on tap again disappear in same fashion into that button. I have achieved a view coming out of a button with this code. But reverse is not working. any help
- (IBAction) arrowBtnClick{

    _arrowUpBtn.enabled=false;
    if (_isSliderMenuPresent) {
        [UIView animateWithDuration:.5f delay:0.0f options:UIViewAnimationOptionCurveEaseOut animations:^{
            _sliderView.frame = CGRectMake(_sliderView.frame.origin.x, 440.0f, _sliderView.frame.size.width, 200 );
        } completion:^(BOOL finished)
         {
             _isSliderMenuPresent = false;
             _sliderView.hidden = true;
             _arrowUpBtn.enabled=true;
             [_arrowUpBtn setBackgroundImage:[UIImage imageNamed:@"arrow_up.png"] forState:UIControlStateNormal];
         }];
    }
    else{
        _sliderView.hidden = false;
        _sliderView.transform = CGAffineTransformMakeScale(0.00, 0.00);
        [UIView animateWithDuration:.5f delay:0.0f options:UIViewAnimationOptionCurveEaseIn animations:^{
            _sliderView.transform = CGAffineTransformIdentity;
            _sliderView.frame = CGRectMake(_sliderView.frame.origin.x,_sliderView.frame.origin.y-150, _sliderView.frame.size.width, 200 );
        } completion:^(BOOL finished)
         {
             _isSliderMenuPresent = true;
             _arrowUpBtn.enabled=true;
             [_arrowUpBtn setBackgroundImage:[UIImage imageNamed:@"close_button.png"] forState:UIControlStateNormal];
         }];
    }
}


text:
Q: 90th Percentile of the Number of Balls in the Fullest Box This is a simplified version of an applied probability modeling problem.
I believe I solved it, but I'm wondering if there is a more elegant approach than mine:
There are 10 boxes and 200 balls. At each trial exactly four boxes are selected
at random and exactly one ball is placed into each. Thus there are 50 trials in the game. The
boxes have equal capacity. What must that capacity be so that in 90% of the
50-trial games no box overflows?
Answer: Obviously more than 20; using binomial, 28 seems to suffice.

A: The filling process of any one box can be modeled as a random walk starting at $n = 0$, where at each step $n$ either increases by 1 with probability $p = 0.4$ (since the probability of any one box being chosen in a given trial is 4 out of 10) or $n$ stays the same with probability $1 - p = 0.6$.  The probability of ending up with $n$ balls in any given box at the end of 50 trials is then
$$
P(n) = { 50 \choose n } p^n (1 - p)^{50 - n},
$$
and the probability of having more than $n$ balls in a box is
$$
P_o(n) = \sum_{m = n+1}^{50} { 50 \choose m } p^m (1 - p)^{50 - m}.
$$
Now, we want to find the value of $n$ for which there is at least a 90% chance that none of the 10 boxes overflows.  Since the probability of a box of capacity $n$ overflowing is $P_o(n)$, the probability of none of the ten boxes overflowing is*
$$
(\text{prob. of no overflows}) = (1 - P_o(n))^{10} \geq \frac{9}{10} \qquad P_o(n) \leq 1 - \sqrt[10]{\frac{9}{10}} = 0.0104807...
$$
From here, one can plug various choices of $n$ into Wolfram Alpha and find that $P_o(27) \approx 0.016$ and $P_o(28) \approx 0.007$.  So the answer does appear to be 28.
Alternately, one can approximate the binomial distribution by a normal distribution.  Each trial adds a mean of of $\bar{\mu} = 0.4$ balls to each bin, with a variance of $\bar{\sigma}^2 = 0.24$.  This means that after $N = 50$ trials, the distribution of the number of balls $n$ in a given bin will be
$$
P(n) \, dn = \frac{1}{\sqrt{2 \pi N \bar{\sigma}^2}} \exp \left[ - \frac{(n - N \bar{\mu})^2}{ 2 N \bar{\sigma}^2} \right] dn
$$
This is a normal distribution with a mean of $N \bar{\mu} = 20$, a variance of $N \bar{\sigma}^2 = 12$, and a standard deviation of $\sigma = \sqrt{12}$.  By the above logic, we want to know the argument of the error function $\text{erf}(x)$ such that
$$
\frac{1}{2} + \frac{1}{2}\text{erf}(x) = \sqrt[10]{\frac{9}{10}} \approx 0.989519...
$$
which can be found to be $x = 1.6325...$ (thanks again to Wolfram Alpha.)  Thus, according to this approximation, there is a 90% chance of no overflows if the size of the boxes is greater than $20 + 1.6325 \sigma = 26.55...$.  I think that the continuity correction bumps this up to 27.05, which implies that you really need a box size of 28, but it's been a while since I've used this;  in any event, this is only an approximation, and it obviously comes pretty close to the exact result from the binomial distribution.
(The advantage of this sort of calculation is that it only requires one lookup of values in a table of values for the error function, rather than a series of calculations of a sum involving binomial coefficients;  so it might be better for a quick-and-dirty answer, and would certainly be easier if I didn't have a computer handy.)

*The one caveat here is that I'm not 100% sure that the probability of one box overflowing is independent of the probability of any of the other boxes overflowing.  It seems plausible to me, but I haven't come up with a rigorous argument.

A: Extended and corrected comment. For the Problem as stated above
independence is more important than I intended. (To simplify the
posted problem, I reduced the number of
boxes and the number of trials from the original applied problem,
with unanticipated results.)
Assuming that boxes are
independent does indeed give 28 as the 99th percentile for the maximum number $W$ of balls in the fullest box. However, a simulation of the actual situation
described, shows that the 99th percentile of $W$ is 31, and that the
correlation of the numbers of balls in two different boxes is about $r = -0.11.$
In the simulation below using R statistical software, the game is "played" 10,000 times. For each play
of the game, the matrix MAT has $50$ rows (trials) and $10$ columns (boxes).
Each element of the matrix is 1 or 0 according as the box received a ball
on the relevant trial, or not. All rows add to 4.
set.seed(1776)  # change seed for different simulation
games = 10000;  w = r =  numeric(games)
for (k in 1:games)
{
 trials=50;  boxes=10
 MAT=matrix(rep(0, trials*boxes), nrow=trials)
 for (i in 1:trials) {
   MAT[i,] = sample(c(1,1,1,1,0,0,0,0,0,0), boxes) }
 w[k] = max(colSums(MAT))
 r[k] = cor(MAT[,1],MAT[,2])
}
quantile(w, .99)
## 99%
##  31
mean(r)
## -0.1139328

Repeated simulations gave exactly 31 for the 99th percentile of $W,$
and very nearly an average correlation of -0.11 between the contents
of the first and second columns. The figure below shows the simulated
distribution of $W.$

Thanks to @MichaelSiefert and @RossMillikan for helpful discussions
of this problem.


text:
Q: duvida na criação de dataframe pandas Estou com uma duvida na criação de um dataframe como exemplo
dicionario = {'pais': 'brasil', 'capital': 'brasilia', 'clima': 'tropical'}
pd.DataFrame(dicionario)
volta erro de index
mas se coloca algum valor em lista
dicionario = {'pais': ['brasil'], 'capital': 'brasilia', 'clima': 'tropical'}
pd.DataFrame(dicionario)
Volta um pandas dataframe perfeito com index e colunas

A: A solução é simples
use:
df = pd.DataFrame([dicionario])

Entretanto, isso é porque tem apenas uma linha. Normalmente você criaria o DataFrame conforme o exemplo abaixo:
>>> dicionario = {'pais': ['brasil', 'argentina', 'australia'],
                  'capital': ['brasilia', 'buenos aires', 'canberra'],
                  'clima': ['tropical', 'temperado', 'tropical']}
>>> df = pd.DataFrame(dicionario)
>>> df
        pais       capital      clima
0     brasil      brasilia   tropical
1  argentina  buenos aires  temperado
2  australia      canberra   tropical
>>>

Espero que ajude

A: Esse seu problema pode ser feito de duas formas:
import pandas as pd

dicionario = {'pais': 'brasil', 'capital': 'brasilia', 'clima': 'tropical'}

pd.DataFrame([dicionario])

print(dicionario)

Alternativamente:
import pandas as pd

dicionario = {'pais': 'brasil', 'capital': 'brasilia', 'clima': 'tropical'}

pd.DataFrame(dicionario, index=[0])

print(dicionario)


text:
Q: My Ag-grid display is getting messed up when I scroll I have an ag-grid display with about 1000 rows and 3 columns ... initially the display looks fine ... but as I scroll, somewhere around the 150th column.. my grid display gets messed up .. I stop seeing the border, scroll bar, header of the grid and left and right columns disappear ... below is an image of what I see. if I scroll further down, I will stop seeing the left and right columns and the header completely..

Any help on this would be greatly appreciated.. I don't even know where to look.
(Note: please ignore the black lines in the left column. I had to cover the text before I can post the image here.)
thank you
Vij

A: I had the same problem, when i used Internet Explorer.
I'm not so sure, that in your case it is the same, but my problem was solved with the lagging.
When you initialize your ag-gird add this to it:
suppressScrollLag: true
I hope this solves your problem.

A: One other option, even though it's not the most elegant one, is to increase the number of rows that get rendered outside the viewable content:
gridOptions.rowBuffer = 100;

The default is set to 20 rows.


text:
Q: Parsing XML from a stream, C# / SoapUI I'm trying to get the value of "payload" from the following piece of XML that's sent with SoapUI:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:loc="localhost">
   <soapenv:Header/>
   <soapenv:Body>
      <loc:HTTPWebService>
         <!--Optional:-->
         <loc:input>Test</loc:input>
         <payload>Data</payload>
      </loc:HTTPWebService>
   </soapenv:Body>
</soapenv:Envelope>

Here's the C# bit:
string xmlPayload = "";

XmlDocument xmlSoapRequest = new XmlDocument();

using (Stream receiveStream = HttpContext.Current.Request.InputStream)
{
    receiveStream.Position = 0;

    using (StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8))
    {
        xmlSoapRequest.Load(readStream);
        xmlPayload = xmlSoapRequest.SelectSingleNode("/payload/@value").Value;
    }
}
return xmlPayload;

The problem is that currently "xmlPayload" ends up with the value of null and the request fails. The XML is properly loaded but for some reason "XmlPayload" is empty and SoapUi responds with "System.NullReferenceException: Object reference not set to an instance of an object." How can I get parse the "Data" value from "payload" properly?

A: You are selecting value of "value" attribute that clearly not present in your XML. Also it is not at root of the DOM.
It looks like you want
  xmlPayload = xmlSoapRequest.SelectSingleNode("//payload").InnerText;

(Notice "//" which means "any node starting from root" and lack of "@value" which means - attribute with name "value")

A: Alexei had it - except use "InnerText" instead of "Value" to get your "Data":
xmlPayload = xmlSoapRequest.SelectSingleNode("//payload").InnerText;

A: If the node is null, you will need to check that before you assign the variable.
Try this:
xmlPayload = xmlSoapRequest.SelectSingleNode("/payload/@value") != null ? xmlSoapRequest.SelectSingleNode("/payload/@value").Value : "value not available";

However, I believe a better way would be using InnerText
xmlPayload = xmlSoapRequest.GetElementByTagName("payload") != null ? xmlSoapRequest.GetElementByTagName("payload").InnerText : "value not available";

The format is like this:
var variable = condition ? A : B;

It's basically saying that if condition is true, variable equals A, otherwise variable equals B.

A: This code works fine and you should be able to incorporate it back in to your original program:
string xmlPayloadText = @"<soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:loc=""localhost"">
<soapenv:Header/>
<soapenv:Body>
    <loc:HTTPWebService>
        <!--Optional:-->
        <loc:input>Test</loc:input>
        <payload>Data</payload>
    </loc:HTTPWebService>
</soapenv:Body>
</soapenv:Envelope>";

        XmlDocument xmlSoapRequest = new XmlDocument();
        xmlSoapRequest.LoadXml(xmlPayloadText);
        var xmlPayload = xmlSoapRequest.SelectSingleNode("//payload");
        Console.WriteLine(xmlPayload.InnerText);


text:
Q: How Do you create an Linked lists of linked lists I am new to this and I am just looking for feedback.
I have currently created a struct as follows
struct node{
    int value;
    int power;
    struct node *link;
};

and from this I created a linked list, to represent 1 quadratic. However the bit that I am having a problem with is that I am struggling to make lists of these lists to represent an indefinite amount of quadratic.

A: You'll need a second structure, maybe like this:
struct node_list
{
    struct node *equation;
    struct node_list *next;
};

The equation member hold a pointer to an equation (quadratic, list of struct node), while next points to the next struct node_list.


text:
Q: First and last value aggregate functions in postgresql that work correctly with NULL values I know there are aggregate functions for getting last and first value of rows in postgresql
My problem is, that they do not work as i need. And i could use the help of one postgresql wizard. I'm using postgresql 9.2 - in case the version makes offering solution easyer.
Query
select v.id, v.active, v.reg_no, p.install_date, p.remove_date
from vehicle v
    left join period p on (v.id = p.car_id)
where v.id = 1
order by v.id, p.install_date asc

Returns 6 rows:
id, active, reg_no, install_date, remove_date
1, TRUE, something, 2008-08-02 11:13:39, 2009-02-09 10:32:32
....
1, TRUE, something, 2010-08-15 21:16:40, 2012-08-25 07:44:30
1, TRUE, something, 2012-09-10 17:05:12, NULL

But when i use aggregating query:
select max(id) as id, last(active) as active, first(install_date) as install_date, last(remove_date) as remove_date
from (
    select v.id, v.active, v.reg_no, p.install_date, p.remove_date
    from vehicle v
      left join period p on (v.id = p.car_id)
    where v.id = 1
    order by v.id, p.install_date asc
) as bar
group by id

Then i get
id, active, install_date, remove_date
1, TRUE, 2008-08-02 11:13:39, 2012-08-25 07:44:30

not
id, active, install_date, remove_date
1, TRUE, 2008-08-02 11:13:39, NULL

as i expected
Is it possible to change the aggregate functions somehow to yield NULL if the value of last row is null, not last existing value?
EDIT1
Roman Pekar offered alternative solution to my problem, but that does not fit my needs. The reason is - i simplified the original query. But the query i run is more complex. I realise that there might be alternative solutions to my problem - this why is update the post to include the original, more complex, query. Which is:
select partner_id, sum(active) as active, sum(installed) as installed, sum(removed) as removed
from (
    select
    pc.partner_id as partner_id,
    v.id,
    CASE WHEN v.active = TRUE THEN 1 ELSE 0 END as active,
    CASE WHEN first(p.install_date) BETWEEN '2013-12-01' AND '2014-01-01' THEN 1 ELSE 0 END as installed,
    CASE WHEN last(p.remove_date) BETWEEN '2013-12-01' AND '2014-01-01' THEN 1 ELSE 0 END as removed
    from vehicle v
        left join period p on (v.id = p.car_id)
        left join partner_clients pc on (pc.account_id = v.client_id)
    group by pc.partner_id, v.id, v.active
) as foo group by partner_id

As you can see, i actually need to get first and last value of several vehicles not one and in the end aggregate the counts of those vehicles by the owners of those vehicles.
/EDIT1

A: You could use window functions lead() and lag() to check first and last record, for example:
select
    max(a.id) as id,
    max(a.first) as first,
    max(a.last) as last
from (
    select
         v.id,
         case when lag(v.id) over(order by v.id, p.install_date) is null then p.install_date end as first,
         case when lead(v.id) over(order by v.id, p.install_date) is null then p.remove_date end as last
    from vehicle v
       left join period p on (v.id = p.car_id)
    where v.id = 1
) as a

sql fiddle demo

A: Thanks to Damien i went reading postgresql documentation about creating functions (source) and fiddled with the function changing it from:
CREATE OR REPLACE FUNCTION public.last_agg ( anyelement, anyelement )
RETURNS anyelement LANGUAGE sql IMMUTABLE STRICT AS $$
        SELECT $2;
$$;

CREATE AGGREGATE public.last (
        sfunc    = public.last_agg,
        basetype = anyelement,
        stype    = anyelement
);

to:
CREATE OR REPLACE FUNCTION public.last_agg ( anyelement, anyelement )
RETURNS anyelement LANGUAGE sql IMMUTABLE CALLED ON NULL INPUT AS $$
        SELECT $2;
$$;

CREATE AGGREGATE public.last (
        sfunc    = public.last_agg,
        basetype = anyelement,
        stype    = anyelement
);

and it seems to have fixed my troubles.
Thanks for reading.


text:
Q: MAMP: How to add AMF PHP extension? How can I add a PHP extension called "AMF" to my MAMP setup in Mac OSX?
Thanks in advance :)
Cheers,
Mark

A: I think I did it. Here are the tutorial links that I have followed :)
http://developerkarma.com/blog/andrew-m-riley/quick-and-dirty-pecl-mamp-os-x
Other reference link:
http://www.lullabot.com/articles/setup-memcached-mamp-sandbox-environment
Syntax I used:
./pecl i amfext-0.9.2

The links above worked with the newly compiled amf.so in my extensions folder but the AMFEXT php extension did not appear in the phpinfo.php.
I will try to use this link I just found:
http://www.phpbuilder.com/board/showthread.php?t=10363479&page=3
I will update this answer tomorrow if the phpbuilder link worked.
Cheers! :D

A: amfext is long outdated and unstable. Check this extension out - http://neoxic.me/php-amf3/
No problem building and integrating into MAMP!


text:
Q: Source Multiple R Scripts With Delay In Between I'm trying to source multiple R scripts with a short delay in between each one.  The 15 R scripts to be 'sourced' all collect data from GA API, transform/clean/analyze the data, then finally push the into their own worksheets within a single Google Sheet. So I'd like to set a wait of 1 minute between each script to make sure I'm not overloading the Google Sheet file.
How can I turn the code (below) into a mini-function where there is a wait time between each source() command?
    source("/code/processed/script1.R")
    source("/code/processed/script1.R")
    source("/code/processed/script1.R")
    ...
    source("/code/processed/script15.R")

Thanks in advance for your help! :)
PS - For context, please note I have my working directory organized in the following hierarchy:
 |-project
    |-code
      |-processed
      |-raw
    |-data
      |-processed
      |-raw

A: As suggested in my comment I would use sys.sleep(), either by manually adding it netwerk every source command:
source(...)
sys.sleep(60)
source(...)

Or by storing all scripts in a vector and looping over them.


text:
Q: Monotouch binding for ABPersonCopyImageDataWithFormat In Monotouch the only way you can get the Image from an ABPerson instance is using the Image property which returns the image in its original size.
In Objective-C there is a function called ABPersonCopyImageDataWithFormat (http://developer.apple.com/library/ios/#documentation/AddressBook/Reference/ABPersonRef_iPhoneOS/Reference/reference.html#//apple_ref/c/func/ABPersonCopyImageDataWithFormat), which can return the thumbnailed image from the contact,
but Monotouch does not provide a binding for this.
Does any body know how to call this function in Monotouch or how to create its binding?
Thanks,
Danny

A: Just found the solution (by disassemling the monotouch.dll and look carefully at the internal code)
[DllImport("/System/Library/Frameworks/AddressBook.framework/AddressBook")]
private static extern IntPtr ABPersonCopyImageDataWithFormat(IntPtr handle, ABPersonImageFormat format);

ABPersonImageFormat format = ABPersonImageFormat.Thumbnail;
NSData data = new NSData(ABPersonCopyImageDataWithFormat(person.Handle, format));
UIImage imgThumb = UIImage.LoadFromData(data);

Good luck with it !!!

A: It's bound as MonoTouch.AddressBook.ABPerson.CopyImage (ABPersonImageFormat format);


text:
Q: how to authorize scripts that trigger on events like on form submit? My understanding is, the only way to authorize a script is to execute it and then it'll do all of the authorizations it needs. How do we do this for functions that are used in conjunction with an even trigger like on form submit?
Say I have a function like this:
function onFormSubmit(e){ ... }

If this function triggers on form submit then e will have the event details. But if I just execute it normally then e will be undefined.
And if my function needs e to do other things, like send an e-mail using MailApp then the script will have to be authorized to send e-mail using MailApp.
So how to get the script authorized for everything that needs authorization?

A: Add an innocuous function like
/**
 *
 * The purpose of this function is to trigger the script authorization dialog without
 * throwing any errors.
 */
function doNothing(){}

Then run it. Even if it do nothing it will trigger the script authorization dialog.

From https://developers.google.com/apps-script/guides/services/authorization

Granting access rights
Apps Script determines the authorization scopes (like access your
  Google Sheets files or Gmail) automatically, based on a scan of the
  code. Code that is commented out can still generate an authorization
  request. If a script needs authorization, you'll see one of the
  authorization dialogs shown here when it is run.


text:
Q: Unable to bind phpseclib to specific source IP It looks like the SSH / SCP code for phpseclib does not support binding to a source IP.  Unfortunately, this breaks our use case.
Is there a way to add this support?

A: phpseclib uses fsockopen to do SSH, which doesn't support binding. You could probably rewrite it to do socket_create / socket_bind. I guess I could do it if you paypal me some money!


text:
Q: array of object string convert to array of object only javascript I have a string that contains an array of object '[{letter: a, number: 1}, {letter: b, number: 2}]' I'm trying to make it literally a array of object using JSON.parse() but I'm getting an error saying
`SyntaxError: Unexpected token l in JSON at position 2`

My code
let a = '[{letter: \'a\', number: 1}, {letter: \'b\', number: 2}]'

let b = JSON.parse(a)

console.log(b)

I can't even use a.split(',') because I have a , inside the object
my expected output was
[{letter: 'a', number: 1}, {letter: 'b', number: 2}]

how can I fix it?

A: In JSON keys must be strings, so you have to reformat your JSON string like this:
[{"letter": "a", "number": 1}, {"letter": "b", number: 2}]

More info, see this article


text:
Q: Trim HTML string up to certain limit in java Given an HTML string such as this :

Q. What is the basic difference between Bachelor of Technology and Bachelor of Engineering?

How can I modify the string so that only first n characters from clean text are returned in same HTML format? Also how to avoid intra word breakgage?
For eg: for n=20, the above string should get transformed to

Q. What is the basic

A: Assuming you are using Jsoup (question tagged jsoup) something like below:
public static void main(String[] args) {
    String html = "
Q. What is the basic difference between Bachelor of Technology and "
            + "Bachelor of Engineering?
";

    //get the p tag and strong tag and content
    Element paragraph = Jsoup.parseBodyFragment(html).selectFirst("p");
    Element strong = paragraph.selectFirst("p strong");
    String content = strong.text();

    // use regex to get the first 20 chars while maintaining word boundaries
    Pattern p = Pattern.compile("\\G\\s*(.{1,20})(?=\\s|$)");
    Matcher m = p.matcher(content);
    m.find();

    // replace the text of strong element with the first 20 chars of original content
    strong.text(m.group(1));

    System.out.println(paragraph);
}


text:
Q: My eclipse keep saying "The value of the field is not used" ı have a (boolean)hasDriverLicence variable in my Person class . I created getter and setter methods and ı used hasDriverLicence in the person constructor but my eclipse saying "The value of the field  Person.hasDriverLicence is not used."  Here is the code :
public Person(int id, String firstName, String lastName, String gender, Calendar birthDate, String maritalStatus,
        String hasDriverLicence) throws Exception {

    this.id = id;
    this.firstName = firstName;
    this.lastName = lastName;
    this.birthDate = birthDate;

    setGender(gender);
    setMaritalStatus(maritalStatus);
    setHasDriverLicence(hasDriverLicence);

and here is the getter and setter :
public void setHasDriverLicence(String hasDriverLicence) throws Exception {

    if (!(hasDriverLicence.equalsIgnoreCase("Yes")) && !(hasDriverLicence.equalsIgnoreCase("No")))

        throw new Exception("Wrong input, please type Yes or No");

    if (hasDriverLicence.equalsIgnoreCase("Yes")) {

        this.hasDriverLicence = true;

    }

    else if (hasDriverLicence.equalsIgnoreCase("No")) {

        this.hasDriverLicence = false;

    }
}

public String getHasDriverLicence() {

    if (this.hasDriverLicence = true)

        return "Yes";

    if (this.hasDriverLicence = false)

        return "No";

    else

        return "";
}

A: You have a typo in the getter.
Your if conditions actually set the value of the instance field, instead of checking for it:
if (this.hasDriverLicence = true)

This should be:
if (this.hasDriverLicence == true)

Or better simply:
if (this.hasDriverLicence) {
    // ...
// no need for a separate if statement for the opposite condition,
// and you can only have two states here
else {

    // ...
}

The variable is therefore assigned but never used in your code.
Elaboration
The reason why the single = compiles, but the IDE gives you a warning claiming the variable is never used, is because the assignment operator returns the assigned value.
For instance, the statement:
myVariable = 1

... returns 1.
Therefore, when you are incorrectly checking for an assignment (=) rather than primitive equality (==), you will always check for the value of your assignment (in your case, true in the first condition which will always fulfill, false in the second, which will therefore never fulfill).

A: May be you can try rebuilding your workspace. I am not able to see the issue with the above mentioned code.


text:
Q: JSON, PHP & SQL implementation error I'm trying to work out how to use JSON, php and SQL (initially MSSQL) to populate a type-ahead field of names and, once the name is selected, to also populate a job title and department.  This is my first time to use JSON, so I'm starting a bit from scratch here.
I got a partial solution from Experts Exchange (see Fiddle) using static data, but I'm having trouble converting the data I'm pulling from the database to what is being shown in the fiddle.
The code for the fiddle is:-
<!DOCTYPE html>

        <title>Autocomplete Textbox Demo | PHP | jQuery</title>

        <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">

        Department Name

        <input id="empName" type="text" size="50" />

        <input id="empTitle" type="text" size="50" />

I'm stuck now on implementing the results returned from the database query to work with the fiddle.  I believe I've to the data correctly formatted but it's wrong somewhere and I'm not sure where that is.
I'm getting the data from an SQL table with a separate php page called fetchEmpName.php:-
<?php
    require('i_PDOConnection.php');
    $query = "SELECT empFName + ' ' + empLName as [empName], empTitle, empDept FROM tbl_CouncilStaff WHERE active = 1 AND display = 1 AND (empFName LIKE '%".$search."%' OR empLName LIKE '%".$search."%') ORDER BY empLName";
    $stmt = $dbh->prepare($query);
    $stmt->execute();
    $data = $stmt->fetchAll();
    $return_arr = array();
    $return_arr['contacts'] = array();
    foreach ($data as $row) {
        $dataArray['empName'] = $row['empName'];
        $dataArray['empTitle'] = $row['empTitle'];
        array_push($return_arr['contacts'],$dataArray);
    }
    echo json_encode($return_arr);
?>

Which (according to the Chrome console log, produces an array like:
{empName: "Bob Smith", empTitle: "Chief Cook and Bottle Washer"}

Which works properly when I replace the fiddle data with the generated data but fails once the static data is replaced by the sql code.  So that tells me that the problem lies in the script.  At this point, the page has morphed into:
<!DOCTYPE html>

    <title>Autocomplete Textbox Demo | PHP | jQuery</title>

    <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">

Department Name

<input id="empName" type="text" size="50" />

<input id="empTitle" type="text" size="50" />

When I run the page, the jquery library throws an error saying

jquery-ui.min.js:8 Uncaught TypeError: Cannot read property 'label' of undefined"

I hope this is enough for someone to sort out where I'm off track - or if there is a better way to solving the problem of filling additional fields from a type-ahead field.
Thanks in advance - any assistance offered would be greatly appreciated.


text:
Q: Kendo UI Uploader: Angular directive doesn't post files I am working with Angular and Kendo together, and I'm trying to implement the upload widget using the angular-kendo directives written by Kendo Labs.
I have a controller, called "EditWorkspace".  In that controller I defined the kendo-upload directive's options as
 $scope.uploadOptions

The callback functions for the uploader are defined inside the controller.  From the documentation, I was led to believe that this is what the directive expects.  These options are used across multiple elements.  I don't seem to have a problem until I actually try to post the files to a server, at which point ALL arrays are empty ($_POST, $_FILES, $_GET, $_REQUEST, etc) which I know because I dumped all the arrays out to see what was in them.
I've tried switching all configuration to my own directive in which I invoke
$(element).kendoUpload()

But I get the same result.  Files get inside the form just fine and send a message off to the server, but they post empty arrays.
Has anybody had a similar experience with either Kendo or Angular and can you shed some light on it?  I could post all kinds of code but I don't think it would help to explain.


text: Q: privateid Private Identity is a biometric recognition solution (API, SaaS, PaaS) powered by TensorFlow that provides verification, identity and search for face, face+mask, voice and fingerprint using fully homomorphic encryption (FHE). Use this tag with a language or IAM specific tag ([okta], [html], [python], [javascript], etc.) for questions about using the API or general use. Specify the application area such as [face-detection] as well.


text:
Q: Find values that are not in every row I have a spreadsheet that contains users in each column. Below each user lists groups that they are in.
I want to highlight values that are not in every column.

*

*If a user is part of a group that everyone is a part of, that group would not be highlighted.

*If there was even one person who wasn't part of that group as well, that group would be highlighted.

Example.
Say there are 3 columns: A, B, C.

*

*Column A has values 1, 2, 3, 4, 5 listed below it.  Each number in a different row

*Column B has values 1, 2 ,4, 5 listed below it.

*Column C has values 1, 2, 4, 6, 7 listed below it.
In this example

*

*In Column A, 3 and 5 would be highlighted.

*In Column B, 5 would be highlighted.

*In Column C, 6 and 7 would be highlighted.
Because each of those numbers are not listed every column.

A: So, you can do this using Conditional Formatting using the following logic:
Just for the sake of example, suppose your data is in the range A1:H20 with, as you said, each column being a new user and the first row A1:H1 being user names.
What this tells us:
COUNTA($A$1:$H$1) = Number of users
COUNTIF($A$1:$H$20,A2) = Number of times the value in A2 appears in your dataset
Therefore if COUNTIF($A$1:$H$20,A2) < COUNTA($A$1:$H$1), that means the value in A2 does not appear in each column (otherwise they woud be equal). (Also note that this is based on the assumption that you can't have a value appearing twice in a given column!).
At this point, it's a simple conditional formula.
Hope this explains it well enough.


text:
Q: Inconsistent behavior of "scrollWidth" between Webkit and Firefox I have a set of header divs that need to match the width of the content divs below them. In general, the content divs are thinner than the header divs, and they can vary in size.
So, what I do is set the width of the header div to match the width of the content div. Then, because I want the header and content to be wide enough to not cut off any words, I check each header's "scrollWidth" property to see if it's larger than its "offsetWidth" property, and then set the content and header widths the header's scrollWidth.
header.style.width = tableCell.offsetWidth + "px";
if (header.scrollWidth > header.offsetWidth) {
    content.style.width = header.scrollWidth + "px";
    header.style.width = header.scrollWidth + "px";
}

This works great with Safari and Chrome, but doesn't work at all in FireFox. With Firefox, "scrollWidth" returns the same value as the header's set width.
"Sounds like a great time to use tables" you say, but I can't. The header needs to remain static on the top of the page.
So, how can I get Firefox to return an equivalent value to scrollWidth under these conditions? I've tried setting the overflow of the header divs to "hidden" and "scroll," but that didn't effect anything.

A: Firefox seems to include the border width, Chrome doesn't. I had to subtract the border width when I was in Firefox. Hacky, but it worked.

A: I answered a similar question on stackoverflow: Why scrollWidth doesn't work in this case in Firefox?
The problem is that Firefox returns for scrollWidth the clientWidth value, when the overflow is visible.
The workaround I found for Firefox is to set the overflow to hidden, get the correct scrollWidth and revert the overflow to visible. More details and code in the link.


text:
Q: Pandas: Assigning multiple *new* columns simultaneously I have a DataFrame df with a column containing labels for each row (in addition to some relevant data for each row).  I have a dictionary labeldict with keys equal to the possible labels and values equal to 2-tuples of information related to that label.  I'd like to tack two new columns onto my frame, one for each part of the 2-tuple corresponding to the label for each row.
Here is the setup:
import pandas as pd
import numpy as np

np.random.seed(1)
n = 10

labels = list('abcdef')
colors = ['red', 'green', 'blue']
sizes = ['small', 'medium', 'large']

labeldict = {c: (np.random.choice(colors), np.random.choice(sizes)) for c in labels}

df = pd.DataFrame({'label': np.random.choice(labels, n),
                   'somedata': np.random.randn(n)})

I can get what I want by running:
df['color'], df['size'] = zip(*df['label'].map(labeldict))
print df

  label  somedata  color    size
0     b  0.196643    red  medium
1     c -1.545214  green   small
2     a -0.088104  green   small
3     c  0.852239  green   small
4     b  0.677234    red  medium
5     c -0.106878  green   small
6     a  0.725274  green   small
7     d  0.934889    red  medium
8     a  1.118297  green   small
9     c  0.055613  green   small

But how can I do this if I don't want to manually type out the two columns on the left side of the assignment?  I.e. how can I create multiple new columns on the fly.  For example, if I had 10-tuples in labeldict instead of 2-tuples, this would be a real pain as currently written.  Here are a couple things that don't work:
# set up attrlist for later use
attrlist = ['color', 'size']

# non-working idea 1)
df[attrlist] = zip(*df['label'].map(labeldict))

# non-working idea 2)
df.loc[:, attrlist] = zip(*df['label'].map(labeldict))

This does work, but seems like a hack:
for a in attrlist:
    df[a] = 0
df[attrlist] = zip(*df['label'].map(labeldict))

Better solutions?

A: Instead of doing what you're doing with labeldict, you could make that information into a DataFrame and then join it with your original one:
>>> labeldf = pandas.DataFrame([(np.random.choice(colors), np.random.choice(sizes)) for c in labels], columns=['color', 'size'], index=labels)
>>> df.join(labeldf, on='label')
  label  somedata  color    size
0     a -1.709973    red  medium
1     b  0.099109   blue  medium
2     a -0.427323    red  medium
3     b  0.474995   blue  medium
4     b -2.819208   blue  medium
5     d -0.998888    red   small
6     b  0.713357   blue  medium
7     d  0.331989    red   small
8     e -0.906240  green   large
9     c -0.501916   blue   large

A: Just use result_type='expand' in pandas apply
df
Out[78]:
   a  b
0  0  1
1  2  3
2  4  5
3  6  7
4  8  9

df[['mean', 'std', 'max']]=df[['a','b']].apply(mathOperationsTuple, axis=1, result_type='expand')

df
Out[80]:
   a  b  mean  std  max
0  0  1   0.5  0.5  1.0
1  2  3   2.5  0.5  3.0
2  4  5   4.5  0.5  5.0
3  6  7   6.5  0.5  7.0
4  8  9   8.5  0.5  9.0

and here some copy paste code
import pandas as pd
import numpy as np

df = pd.DataFrame(np.arange(10).reshape(5,2), columns=['a','b'])
print('df',df, sep='\n')
print()
def mathOperationsTuple(arr):
    return np.mean(arr), np.std(arr), np.amax(arr)

df[['mean', 'std', 'max']]=df[['a','b']].apply(mathOperationsTuple, axis=1, result_type='expand')
print('df',df, sep='\n')

A: If you want to add multiple columns to a DataFrame as part of a method chain, you can use apply. The first step is to create a function that will transform a row represented as a Series into the form you want. Then you can call apply to use this function on each row.
def append_label_attributes(row: pd.Series, labelmap: dict) -> pd.Series:
    result = row.copy()
    result['color'] = labelmap[result['label']][0]
    result['size'] = labelmap[result['label']][1]
    return result

df = (
    pd.DataFrame(
    {
        'label': np.random.choice(labels, n),
        'somedata': np.random.randn(n)}
    )
    .apply(append_label_attributes, axis='columns', labelmap=labeldict)
)

A: You can use merge instead:
>>> ld = pd.DataFrame(labeldict).T
>>> ld.columns = ['color', 'size']
>>> ld.index.name = 'label'
>>> df.merge(ld.reset_index(), on='label')
  label  somedata  color    size
0     b  1.462108    red  medium
1     c -2.060141  green   small
2     c  1.133769  green   small
3     c  0.042214  green   small
4     e -0.322417    red  medium
5     e -1.099891    red  medium
6     e -0.877858    red  medium
7     e  0.582815    red  medium
8     f -0.384054    red   large
9     d -0.172428    red  medium

A: This should work:
df[['color','size']] = list(df['label'].apply(labeldict))


text:
Q: Passing a two-dimensional array in C function I am trying to return a two-dimensional array from a function, but something goes wrong. arr2 on the main function is getting an error,

CXX0030: Error: expression cannot be evaluated

Code
int** file2array(char* filename) {

    FILE *fp = NULL;
    char c;
    int i = 0;
    int arr[9][9];

    if ((fp = fopen(filename, "r")) == NULL)
    {
        printf("File could not be opened\n");
    }
    else
    {
        while (!feof(fp))
        {
            c = fgetc(fp);

            if (c == '.') {
                arr[i/9][i%9] = 0;
                i++;
            }

            if (c>= '1' && c<='9') {
                arr[i/9][i%9] = c - 48;
                i++;
            }
        }
        fclose (fp);
    }

    return arr;
}

int main(){
    int** arr2 = file2array("SolverInput.txt");
}

A: A 2D array int arr[9][9] and a pointer to pointer int **arr are not interchangeable, use a pointer to an array int (*arr2)[9]:
void *file2array(char* filename){
    ...
    int arr[9][9];
    ...
    return arr;
}

int (*arr2)[9] = file2array("SolverInput.txt");

But note that arr is a local variable (his lifetime ends whith the function), use malloc:
void *file2array(char* filename){
    ...
    int (*arr)[9] = malloc(sizeof *arr * 9);
    ...
    return arr;
}

int (*arr2)[9] = file2array("SolverInput.txt");
...
free(arr2);

If you don't know the number of elements before-hand (an arbitrary number instead of 9) you can use a variable-length-array (VLA)
void *file2array(char* filename, int dim){
    ...
    int (*arr)[dim] = malloc(sizeof *arr * dim);
    ...
    return arr;
}

int dim = 9;
int (*arr2)[dim] = file2array("SolverInput.txt", dim);
...
free(arr2);

Also, fgetc() returns an int (not a char)
Change
char c;

to
int c;

A: Arrays behave weirdly when then are passed as function parameters. That's how it is in C. Just don't do it.
Instead, you should embed the array in a struct.
typedef struct {
    int cell[9][9];
} sudoku;

You can then pass a sudoku * instead of an int ** to the function. This has the immediate benefit of telling the reader of your code what it does. An int ** can mean pretty much anything, but a sudoku * cannot.
int read_sudoku(const char *filename, sudoku *sud) {

    if (some error happens)
        return -1;

    sud->cell[3][8] = 5;
    return 0;
}

int main() {
    sudoku sud;

    if (read_sudoku("sudoku001.txt", &sud) == -1) {
        fprintf(stderr, "cannot read sudoku\n");
        return EXIT_FAILURE;
    }

    ...
}

This is the simplest it can get. No malloc, no free, just some code that does the actual work.


text:
Q: ResourceBundle can't find resources in target/test-classes My problem is that when resource bundle tries to get resources during JUnit test I get MissingResourceException, but all files that located in src/test/resources are compiled into target/test-classes and I even can reach them using
 ClassLoader classLoader = getClass().getClassLoader();
        File file = new File(classLoader.getResource("someFile.properties").getFile());
        System.out.println(file.getAbsolutePath());

What should I do?

A: 'classLoader.getResource()' may be causing the issue. Try getting it through ResourceAsStream which returns InputStream. for example:-
InputStream is = this.getClass().getClassLoader().getResourceAsStream("filename");

A: I checked File's code. I found there is no such constructor that construct a File object with a file object.
If you do maven test does copy resource file to test-classes.
try this
// this will show your resoure root.
File file = new File(getClass().getResource("/").getPath());

// debug you may find your file here.
File[] resoureces = file.listFiles();

or just use
File file = new File(getClass().getResource("/").getPath() + "someFile.properties");