text:
Q: Check streetview exists when displaying it in infowindow following this example http://www.keypointpartners.com/test/mab/fromxml1.html and Google Maps API v3 documentation (https://developers.google.com/maps/documentation/javascript/streetview) I've put together a map that loads markers from an XML file and display a tabbed infowindow for each loaded marker. Wishing to check if a location actually has a streetview available, I've modified my createMarker to this:

    function createMarker(latlng, name, html) {
      //var contentString = html;

      var contentString = [
        '',
        '',
        name,
        '',
        '',
          '
*Località',
          '
*Struttura',
          '
*Voli',
          //'
*Opzioni',
          '
*Streetview',
        '',
        html,
        ''
      ].join('');

      // Create a marker
      var marker = new google.maps.Marker({
        position: latlng,
        title: name,
        map: inc_map
      });

      // Add a listener to the marker to populate and open the infowindow
      google.maps.event.addListener(marker, 'click', function() {
        infowindow.setContent(contentString);
        infowindow.open(inc_map, marker);
        google.maps.event.addListener(infowindow, 'domready', function() {
          inc_sv.getPanoramaByLocation(marker.position, 50, processSVData);
          //console.log("Adding tabs");
          $('#tabs').tabs();
        });

      });

Tha callback function used by getPanoramaByLocation is as follows:

    function processSVData(data, status) {
      if (status == google.maps.StreetViewStatus.OK) {
        google.maps.event.addListener(infowindow, 'domready', function() {
          $('#stv-lnk').click(function() {
            var panoramaOptions = {
              position: data.location.latLng,
              visible: true,
              linksControl: false,
              panControl: false,
              addressControl: false,
              zoomControlOptions: {
                style: google.maps.ZoomControlStyle.SMALL
              },
              enableCloseButton: false
            };
            var panorama = new google.maps.StreetViewPanorama(document.getElementById("stvpano"), panoramaOptions);
            inc_map.setStreetView(panorama);
          });
        });
        } else {
        google.maps.event.addListener(infowindow, 'domready', function() {
          $('#stv-lnk').click(function() {});
          document.getElementById("stvpano").innerHTML = "Streetview non è disponibile per questo luogo"
          });
          }
    }

Now, what happens is that first streetview tab doesn't show anything, while next clicked streetview tabs show previous tab's streetview. Comparing to the abovementioned example from API docs, I build a separate StreetViewPanorama object for each tab (while the example uses a global panorama var to hold it).
Is this my mistake? Or...?
Link at the actual page: http://turom-mice.it/condorincentive/incentive.html
Any help/suggestion greatly appreciated!
Cheers,
rash*
EDIT: ok, I solved one of the problems. I was nesting too many eventListener: I removed the ones inside function processSVData and each infowindow nows show the correct streetview. The code now looks like this:

    function processSVData(data, status) {
      if (status == google.maps.StreetViewStatus.OK) {
        $('#stv-lnk').click(function() {
          var panoramaOptions = {
            position: data.location.latLng,
            visible: true,
            linksControl: false,
            panControl: false,
            addressControl: true,
            zoomControlOptions: {
              style: google.maps.ZoomControlStyle.SMALL
            },
            enableCloseButton: false
          };
          var panorama = new google.maps.StreetViewPanorama(document.getElementById("stvpano"), panoramaOptions);
         inc_map.setStreetView(panorama);
        });
       } else {
        $('#stv-lnk').click(function() {
           inc_map.setStreetView(null);
           document.getElementById("stvpano").innerHTML = "Streetview non è disponibile per questo luogo"
        });
        }
    }

Now, the problem is that the 'else' branch seems doing nothing: when a location has no streetview available, you see last shown streetview, no matter I've set it to null and put some warning text inside the div (I should show a link to a substitute gallery page though). question is: is this correct? Or...?
As usual, any help/hint/suggestion...
Ciao,
rash*
EDIT 2: ok, solved completely. The else branch didn't manage the click event, so putting it back in place solved. The code just above has been edited to reflect the solution.
Thanks anyway, waiting for an answer made me re-think the whole thing. Hope this could be of some help to anybody.
rash*


text:
Q: UIViewController: view needs to redisplay once data is fetched I have TransactionViewController that looks like
@interface TransactionViewController : UIViewController<UITableViewDataSource, UITableViewDelegate>

@property(nonatomic, weak) IBOutlet UILabel *yearHeaderLabel;
@property(nonatomic, weak) IBOutlet UILabel *monthHeaderLabel;
@property(nonatomic, weak) IBOutlet UILabel *transactionsCountHeaderLabel;
@end

In implementation, the code looks like
    @interface TransactionViewController ()
    @property(nonatomic, strong) TransactionsModel *transactionsModel;
    @end

    @implementation TransactionViewController

    - (id)init {
        self = [super init];
        if (self) {
            [TransactionsAPI getTransactionsForYear:2014 AndMonth:9 completionHandler:^(NSDictionary *transactions) {
                self.transactionsModel = [[TransactionsModel alloc] initWithJson:transactions];
                NSLog(@"transactionsModelInViewController:%@", self.transactionsModel);
                [self viewWillAppear:YES];
            }];
        }
        return self;

    }

The data takes time to load from API server, the other methods don't wait since the call is asynchronous, they look like
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.transactionsModel.transactions.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    [tableView registerNib:[UINib nibWithNibName:@"TransactionCell" bundle:nil] forCellReuseIdentifier:CellIdentifier];

    TransactionCell *transactionCell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    if (transactionCell == nil) {
        transactionCell = [[TransactionCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }
    TransactionModel *transactionModel = self.transactionsModel.transactions[(NSUInteger) indexPath.row];
    [self setTransactionCell:transactionCell transactionModel:transactionModel];
        return transactionCell;
}

Now since self.transactionsModel was nil in first place, nothing is displayed, but eventually data is there, so I need to refresh the view. So I try
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.view setNeedsDisplay];
}

But this doesn't work and my view is still blank. What can I do to fix this issue? what am I missing?
Thanks

A: If you are using  a table view to display the data (Your code does not reflect that, see my comment), you can simply call
[self.tableView reloadData];

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get dynamically created UITextField (on top of UITableViewCell ) text value using tag? I have one UITableView and in that UITableViewCell am dynamically creating "n" number of UITextFields. How do i get the values i entered into UITextField by using the tag?.
This is how i create UITextField dynamcally
-(UITextField *)displayTextfield:(NSUInteger)index{

    textField= [[UITextField alloc] initWithFrame:CGRectMake(15,40,cell.frame.size.width-30,cell.frame.size.height)];
    textField.placeholder=@"Text here";
    textField.tag=index;
    textField.delegate=self;

    textField.keyboardType=UIKeyboardTypeNumbersAndPunctuation;
    textField.textAlignment=UITextAlignmentLeft;
    textField.font= [UIFont fontWithName:@"Helvetica-Neue Light" size:14];
    textField.textColor=[UIColor darkGrayColor];
    textField.backgroundColor=[UIColor colorWithRed:245.0/255.0 green:245.0/255.0 blue:245.0/255.0 alpha:1];
    return textField;
}

This is how i tried to access UITextField Value but its crashing.
 NSString *text = [(UITextField *)[cell.contentView viewWithTag:index] text];

Were index (tag) is getting from a for loop .
-[UITableViewCellContentView text]: unrecognized selector sent to instance 0x7fa8329d9360
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UITableViewCellContentView text]: unrecognized selector sent to instance 0x7fa8329d9360'

Please help me to fix this
displayTextfield() calling from here
- (UITableViewCell *)tableView:(UITableView *)tableView1 cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *MyIdentifier;
    if([[[selectedTabFields valueForKey:@"type"] objectAtIndex:indexPath.row] isEqualToString:@"VARCHAR"]){
        MyIdentifier = @"CharCell";

    }else{
        MyIdentifier = @"IntCell";
    }

    cell= [tableView1 dequeueReusableCellWithIdentifier:MyIdentifier];

    if (cell == nil)
    {
        cell = [[dynamicCell alloc] initWithStyle:UITableViewCellStyleDefault
                               reuseIdentifier:MyIdentifier];

        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.accessoryType = UITableViewCellAccessoryNone;

        [cell.contentView addSubview:[self displayTextfield:indexPath.row]];

    }

return cell;
}

A: Zeroth index in cell.contentView.subviews is already taken by a special view named UITableViewCellContentView so the following line doesn't return a UITextField when indexPath.row is 0:
>>> NSLog("%@", [cell.contentView viewWithTag:0])
<UITableViewCellContentView: 0x7fb7c2eb1cd0; frame = (0 0; 320 43.5); gestureRecognizers = <NSArray: 0x7fb7c2eb22a0>; layer = <CALayer: 0x7fb7c2eb1e40>

Change your tag value to something greater and this should fix the issue:
[cell.contentView addSubview:[self displayTextfield:indexPath.row + 1]];

so when you need to get the UITextField again:
NSString *text = [(UITextField *)[cell.contentView viewWithTag:indexPath.row + 1] text];

A: Fix your function's first line to be:
UITextField * textField= [[UITextField alloc] initWithFrame:CGRectMake(15,40,cell.frame.size.width-30,cell.frame.size.height)];

Secondly, assign tag +1 to the textfield so it will be non-zero:
[cell.contentView addSubview:[self displayTextfield:indexPath.row + 1]];

Lastly, before accessing the textfield text property, make sure it is actually a textfield and that the view exist:
NSString * textFieldText = nil;
UIView * view = [cell.contentView viewWithTag:index];
if(view && [view isKindOfClass:[UITextField class]]) {
    UITextField * textField = (UITextField *)view;
    textFieldText = [textField text];
}

if(textFieldText) {
    // Use text here...
}


text:
Q: Android Fragment Not Replacing Properly I am trying to build an app for 3.0 using fragments.  On the left side of the application there is a static fragment, and on the right side there is a dynamic one.  Each of my fragments in the dynamic portion have a title.  Whenever I go to replace the initial fragment, The title of the first is still shown above the title of the first.  Successive replacements replace the lower portion but the initial title is still shown (sorry I cannot post images yet).
Best I can do for image:
Initial Header
New Header
Content(displays fine)
main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >
    <fragment
        android:id="@+id/static_fragment"
        android:name="ruleout.android.History_Fragment"
        android:layout_width="500dp"
        android:layout_height="match_parent" />
    <fragment
        android:id="@+id/dynamic_fragment"
        android:name="ruleout.android.New_Screen_Fragment"
        android:layout_width="fill_parent"
        android:layout_height="match_parent" />
</LinearLayout>

Partial MainActivity used to change fragments
private void open(Fragment toShow)
{
    FragmentTransaction fragmentTransaction = FragMag.beginTransaction();
    fragmentTransaction.replace(R.id.dynamic_fragment, toShow);
    fragmentTransaction.addToBackStack(null);
    fragmentTransaction.commit();
}

Please let me know if you need any additional information and thanks in advance for your help.

A: If you want to dynamically change fragments, you can't declare them in your layout.  The Fragment documentation has an example of doing just what I think you are describing, where a layout has a static fragment declared in it along with a FrameLayout for holding a Fragment that will be dynamically added and replaced.


text:
Q: Rewrite rule and the_request How to rewrite search/2 from index.php?search="x"&&searc_by="y"&page_no=2?
If I am not wrong %REQUEST_URI is search/2, right? Also what is %THE_REQUEST in this case.
The page where search/2 link is located is rewritten as just home_page.

A: %{REQUEST_URI} and %{THE_REQUEST} are variables in mod_rewrite. These variables contain the following:

*

*%{REQUEST_URI} will contain everything behind the hostname and before the query string. In the url http://www.example.com/its/a/scary/polarbear?truth=false, %{REQUEST_URI} would contain /its/a/scary/polarbear. This variable updates after every rewrite.

*%{THE_REQUEST} is a variable that contains the entire request as it was made to the server. This is something in the form of GET /its/a/scary/polarbear?truth=false HTTP/1.1. Since the request that was made to the server is static in the lifespan of one such request, this variable does not change when a rewrite is made. It is therefore helpful in certain situations where you only want to rewrite if an external request contained something. It is often used to prevent infinite loops from happening.

A complete list of variables can be found here.

In your case you will have a link to search/2?search=x&search_by=y. You want to internally rewrite this to index.php?search=x&search_by=y&page_no=2. You can do this with the following rule:
RewriteRule ^search/([0-9]+)$ /index.php?page_no=$1 [QSA,L]

The first argument matches the external request that comes in. It is then rewritten to /index.php?page_no=2. The QSA (query string append) flag appends the existing query string to the rewritten query string. You end up with /index.php?search=x&search_by=y&page_no=2. The L flag stops this 'round' of rewriting. It's just an optimalization thing.


text:
Q: codeigniter live domain setup issue On local CI setup is working fine but when I uploaded on server it shows this error:

Your system folder path does not appear to be set correctly. Please open the following file and correct this: index.php

I have tried some of the changes like change the system folder path but nothing seems to work.

A: Instead of uploading all the files to server, first install ci on server, Check if you are able to view welcome page. Once you can see welcome page, upload other files


text:
Q: Is there a nice way to simulate Android's Fragment Pattern in iOS? We're using MvvmCross in our apps. In our Android app, we use the NavigationDrawer for our Menu. We load our HomeView which contains the NavigationDrawer and the ContentFrame.
<android.support.v4.widget.DrawerLayout >

    <!-- The main content view -->
    <FrameLayout android:id="@+id/content_frame" />

    <!-- The navigation drawer -->
    <ListView android:id="@+id/left_drawer" />

</android.support.v4.widget.DrawerLayout>

When the OnCreate() method is triggered, we load an AudioPlayerFragment into the content_frame based on a database query. In that same method we setup a listener that waits for the user to click one of the ListItem's in the navigation drawer.
protected override void OnCreate(Bundle bundle) {
   // do stuff to build the nav drawer
    _topDrawerList = FindViewById<MvxListView>(Resource.Id.left_drawer);
    _topDrawerList.ItemClick += (sender, args) = > SelectItem(args.Position, null);

    if(bundle == null)
        SelectItem(0, null);
}

private void SelectItem(int position, UserViewModel currentUser) {
    SupportFragmentManager.BeginTransaction()...
}

Our app is working great, and I like how the HomeView is the only View for the app. Everything else is a Fragment.
In our Core library, we have a ViewModel for the HomeView, and we also have a ViewModel for each Fragment in the app. Again, this is working well for us.

*

*PCL

*

*ViewModels

*

*HomeViewModel

*AudioPlayerViewModel  <-- vm for fragment

*LoginFragmentViewModel  <-- vm for fragment

*Droid.Ui

*

*Fragments

*

*AudioPlayerFragment

*LoginFragment

*Views

*

*HomeView  <-- Just a container View as the entry point to the app. Everything else is fragmented... AudioPlayerFragment is
  loaded instantly.

Now I'm trying to build a matching iOS app, but I can't figure out how to structure it. Essentially I'd like the exact same behavior where HomeView is the entry point and can contain both the SlidingPanel bits and some form of a ContentFrame that other "Views" can be loaded into.
Unfortunately, right now I've got this stupid MenuView to deal with, and a corresponding MenuViewModel... and I really don't want either.

*

*PCL

*

*ViewModels

*

*HomeViewModel

*AudioPlayerViewModel  <-- vm for fragment

*LoginFragmentViewModel  <-- vm for fragment

*Touch UI

*

*Views

*

*AudioPlayerView

*HomeView

*LoginView

*MenuView <-- UGLY!!!

*ViewModels

*

*MenuViewModel <-- UGLY!!!

I really don't want to create a custom View/ViewModel for the Menu. I'm using SlidingPanels for my iOS "version" of the Navigation Drawer, and the tutorials I'm seeing are requiring an additional View/ViewModel for the menu.
Is there any way to do this and keep continuity with regards to ViewModels so that they can all be reused in a PCL? Is there a nice (read Clean) way to build the layout structure in a similar way to Android?

A: There have been some attempts to provide unified User Interfaces driven by Portable code. Within MvvmCross, these have especially been driven by the MonoTouch.Dialog type approach to user interfaces. One such attempt/experiment is called "auto-views" - you can see it in action in:

*

*http://slodge.blogspot.co.uk/2013/02/recap-on-what-are-autoviews.html

*https://github.com/MvvmCross/MvvmCross-Tutorials/tree/master/AutoViewExamples
Beneath this autoviews layer, further View code can be shared quite readily within MvvmCross at the Dialog level - e.g. see https://github.com/MvvmCross/MvvmCross-Tutorials/tree/master/DialogExamples

However... with this said... most of the auto-views work to date has still focused on provide rapid prototyping rather than finished apps. For a full rich user interface, most developers still provide custom UIs.

I simply can't wrap my head around the iOS UI. It feels so very foreign to me in comparison to Android.

This isn't that unusual - most XAML developers take to AXML faster than they do to UIKit. However, if you take some time to build some UIViews and to build some user interfaces (pages) with UIViewControllers, then I think you'll get the hang of UIKit quite quickly. Further, I'm confident that once you start seeing the code-based power of things like UIKit animations then you'll even start to fall in love!

A: You will be able to reuse your View Models, but not your Views. Today, PCL doesn't provide access to the UI stack, so you can't have portable views. For more details, have a look at the blog post How to Make Portable Class Libraries Work for You that our tester wrote.

A: The approach I've settled on is to use the MvxViewController as my base entry point into the app.
public class HomeView: MvxViewController
{
    public override void ViewDidLoad()
    {
        base.ViewDidLoad();

        var myEntryFragement = new MyEntryFragment();
        Add(myEntryFragment);
    }
}

And then use MvxView's as "Fragments"
public class MyEntryFragment: MvxView // essentially a UIView
{

    private MyEntryViewModel _viewModel;
    public MyEntryFragment()
    {
        // manually construct the _viewModel (or alternatively inject it in the constructor)
        // setup all your UI controls in here
    }

}

Then I just load and unload my "Fragment's" as needed.


text:
Q: Why id Chrome extension popup closing on input autocomplete suggestion click? For a Chrome extension, I am using the popup as a login form with Angular.
But on OS X, when I click on the username autocomplete suggestion, the popup close itself like when you click outside of the popup. But it works well on Windows.
<!doctype html>

  <meta charset="utf-8">

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

  <link href="styles/main.css" rel="stylesheet">

You're logged in as:

{{user}}

      <button class="btn btn-danger" ng-click="logout()">Log out</button>
      Go to Cockpit

    <form ng-submit="login(username, password)">

        Email
        <input id="username" class="form-control" type="text" ng-model="username" required placeholder="Email">

        Password
        <input id="password" class="form-control" type="password" ng-model="password" required placeholder="Password">

{{error}}

        <button type="submit" class="btn btn-primary" ng-disabled="loading">Log in</button>

        Forgot your password?

    </form>

      Don't have an account? Get started

Any idea for a workaround?

A: It seems that OSX handles the click on the text popup as the click outside of the extension popover area, which causes it to close.
I've observed it on extensions for Safari and Chrome, but only on OSX.
Here's a related ticket in the Chromium bugtracker.
In some cases you can make a custom control which will use divs to display popup content, preventing this issue. For the autofill, I don't think the workaround exists. You can try to disable autofill completely in OSX browsers. Hardly a better solution, but might be appropriate for you.


text:
Q: Multiline cells in reStructuredText tables using csv-table directive I am trying to generate tables in reStructuredText. The content is the exported to pdf using rst2pdf. The content is coming from a database that I am parsing. As I don't know the column width in advance I am using the csv-table directive to facilite the table construction.
What I am currently struggling against is how to have cells which content can come on several lines. I tried the usual double quoted cells with a CR/LF but it does not work. Any idea ?
Here is my table with a not working two lines cell ("John, Junior" should come on two lines inside the cell):
.. csv-table:: a title
   :header: "name", "firstname", "age"
   :widths: 20, 20, 10

   "Smith", "John", 40
   "Smith", "John,
   Junior", 20

any idea on how to progress ?
There is a solution proposed when using Sphinx here: csv-table formatting in Python docstrings (Sphinx) - multiple lines in one cell , but I am using rst2pdf where, as far as I can tell, I cannot change the theme as proposed above.
Thanks for your help.


text: Q: How do I query local MongoDB from client side? I am trying to make a peer to peer application and I want to query my local MongoDB data from chrome and send a response back to whoever initiated the request. What are my options? I can't store the data on a server else there's no point of calling it peer to peer. Also the data is already available in DB so I don't need to update the data just read it.


text:
Q: Docker Swarm: difference between --swarm-discovery and cluster-store When creating a new swarm node we have something like the following code for the swarm master:
docker-machine create \
    -d digitalocean \
    --swarm \
    --swarm-master \
    --swarm-discovery="consul://${KV_IP}:8500" \
    --engine-opt="cluster-store=consul://${KV_IP}:8500" \
    --engine-opt="cluster-advertise=eth1:2376" \
    queenbee

What I don't understand is why we need both these lines?
--swarm-discovery="consul://${KV_IP}:8500" \
--engine-opt="cluster-store=consul://${KV_IP}:8500" \

What I have found so far is:

*

*--swarm-discovery instructs the created Swarm worker container to look for the created key-value store using the specified address and protocol (consul:// here)

*--cluster-store tells the Docker daemon which KV store to use for libnetwork's needed coordination, similar to the --swarm-discovery option outlined above.

but their difference is still not clear to me.

A: You are basically correct.
The --swarm-discovery option is used to specify the key-value store that contains details of the Swarm nodes, and is used to manage the cluster service discovery. Note that this can even be a simple file with a list of nodes, or (not recommended) Docker Hub.
The --cluster-store option must be a libkv supported key-value store, however. This is used by Docker Engine to share details of containers, networks and volumes. This does not require Swarm, and it is perfectly possible to create a Docker cluster linked using Consul but that uses some alternative orchestration mechanism to Swarm. Generally, it is simplest for the Swarm and Docker cluster to share the same store, although it could also be possible to have different mechanisms for each.


text:
Q: Migrating to from glMatrix 1 to glMatrix 2 I haven't been able to update these functions from an old application using glMatrix 1.2 to glMatrix 2.7:
calculateNormal() {
    mat4.identity(this.normalMatrix);
    mat4.set(this.modelViewMatrix, this.normalMatrix);
    mat4.inverse(this.normalMatrix);
    mat4.transpose(this.normalMatrix);
}

And the following function of multiplying a matrix by a 4-component vector doesn't exist:
calculateOrientation() {
    mat4.multiplyVec4(this.matrix, [1, 0, 0, 0], this.right);
    mat4.multiplyVec4(this.matrix, [0, 1, 0, 0], this.up);
    mat4.multiplyVec4(this.matrix, [0, 0, 1, 0], this.normal);
}

A: In common the normal matrix is 3*3 matrix (mat3).
But anyway, glMatrix is well documented and according to the documentation of mat4 and vec4, your code can be ported like this:
calculateNormal() {
    this.normalMatrix = mat4.clone(this.modelViewMatrix);
    mat4.invert(this.normalMatrix, this.normalMatrix);
    mat4.transpose(this.normalMatrix, this.normalMatrix);
}

May be it is not necessary to create the vectors in the following, but I don't kow if the vectors are existing in your case:
calculateOrientation() {

    this.right = vec4.create();
    vec4.set( this.right, 1, 0, 0, 0 );
    vec4.transformMat4( this.right, this.right, this.matrix );

    this.up = vec4.create();
    vec4.set( this.up, 0, 1, 0, 0 );
    vec4.transformMat4( this.up, this.up, this.matrix );

    this.normal = vec4.create();
    vec4.set( this.normal, 0, 0, 1, 0 );
    vec4.transformMat4( this.normal, this.normal, this.matrix );
}


text:
Q: Duplicate values inside Array in Mongoose Schema What I am trying to do
I have a document with teamid as the unique identifier and name of the team. I have an array 'teamList' in my model which would hold the names of all the team members. When a new member is added, I only want names which are not existing to be added. So, if a name is already present it should not be added.
PROBLEM I would like to ensure that there are no repeats inside the teamList array. But right now, all objects in the names array are added to the teamList despite using $addToSet and turning off _id inside the array.
Here is my schema:
var teamSchema = new Schema({
  teamid: {
    type: String,
    required: true
  },
  created: {
    type: Date
  },
  lastUpdated: {
    type: Date,
    default: Date.now,
    required: true
  },
  teamList: [{
    name: {
      type: String,
      required: true,
      unique: true
    },
    dateAdded: {
      type: Date,
      default: Date.now
    },
    _id:false
  }]
});
module.exports = mongoose.model('teamModel', teamSchema);

This is my code:
var mongoose = require('mongoose');
teamModel = mongoose.model('teamModel');
var names = [{name:'Robert'},{name:'Alice'},{name:'Bob'}];
var teamName = 'ManU';
teamModel.update({
        teamid: teamName
      }, {
        $addToSet: {
          teamList: {
            $each: names
          }
        }
      }, {
        upsert: true
      },
      function (err, data) {
       console.log(data);
      });

My question is similar to - http://blog.open-tribute.org/2015/05/09/NodeJS-Mongoose-addToSet-duplicates-on-objects/ , Avoid duplicate entries on Mongoose array
But $addToSet does not work for me probably because I am passing in an array to be added to the teamList array and so I would have to use $each (which is not covered in the previous questions)

A: Your problem is that in the schema the teamList receive a name and a dateAdded, you are generating a new dateAdded for each update execution default: Date.now.
The statement $addToSet will check if the whole array object is duplicated or not.

{name
:
"Robert"
dateAdded
:
2018-07-14 14:06:09.749}
is different than:
{name
:
"Robert"
dateAdded
:
2018-07-14 14:06:12.473}
If you need to store the date when the new member is added you need to check it before the update.
One possible solution:
var teamPeople = [{name:'Robert'},{name:'Alice'},{name:'Bob'},,{name:'Ane'}];
  var teamName = 'ManU';
  var currentTeam = await TeamModel.findOne({teamid: teamName},{"teamList":1});
  for(var i=0;i < teamPeople.length;i++) {
    for (var j = 0; j < currentTeam.teamList.length; j++) {
      if (currentTeam.teamList[j].name === teamPeople[i].name) {
        //remove duplicate team member
        teamPeople.splice(teamPeople[j], 1);
      }
    }
  }
  console.log('New names:'+teamPeople);

  TeamModel.update({
      teamid: teamName
    }, {
      $addToSet: {
        teamList: {
          $each: teamPeople
        }
      }
    }, {
      upsert: true
    },
    function (err, data) {
      console.log(data);
    });


text:
Q: How do you bind Polymer elements to a Model in ASP.NET I have no problems displaying my model in a View using Polymer, for example:
        <paper-icon-item>
            <iron-icon icon="communication:phone" item-icon></iron-icon>
            <paper-item-body two-line>

@Model.PhoneNumber

Phone Number

            </paper-item-body>
        </paper-icon-item>

but I just do not get the bindings right for input
    //this does not work
    <paper-input label="Phone Number">@Model.PhoneNumber</paper-input>

    //nor this
    <paper-input is="iron-input" label="Phone Number">@Model.PhoneNumber</paper-input>

    //even when I try adding this...

...plus a myriad of other attempts.  The bindings are not working one or two way (I cannot display existing data or update data)
The controls look correct, they are very cool, animated, etc

A: You could bind to the value property of the paper input
<paper-input is="iron-input" label="Phone Number" value="@Model.PhoneNumber" name="PhoneNumber"></paper-input>
And also, for getting the value back to the server (if you are posting your form to the server), you might want to add the name attribute to your input, so that MVC will know how to bind your input to the model property.

A: You set the text of paper-input by using the value property. Try this
<paper-input label="Phone Number" value="@Model.PhoneNumber"></paper-input>
<paper-input is="iron-input" label="Phone Number" value="@Model.PhoneNumber"></paper-input>


text:
Q: How to include null values into grouping by date? I'd like to split number of emails added to the database by month and year.
My query:
    SELECT TOP 200 Monthh, Yearr, COUNT(Email) AS Amount
    FROM
    (SELECT Email, MONTH(Added_date) AS Monthh, YEAR(Added_date) AS Yearr
    FROM Contacts) a
    GROUP BY Monthh, Yearr
    ORDER BY CAST(Yearr AS INT), CAST(Monthh AS INT)

But let's say that my (very simplified) contact list looks like this:
|     Email       |   Added_date   |
| --------------- | -------------- |
| max@gmail.com   |  2021-10-01    |
| emma@gmail.com  |  2021-10-05    |
| tony@gmail.com  |  2021-12-06    |
| mark@gmail.com  |  2022-01-23    |
| lucy@gmail.com  |  2022-01-28    |
| chris@gmail.com |  2022-02-04    |

In this case, the result would look like this:
| Yearr | Monthh | Amount |
| ----- | ------ | ------ |
| 2021  |   10   |   2    |
| 2021  |   12   |   1    |
| 2022  |   01   |   2    |
| 2022  |   02   |   1    |

This works. However, there's a slight issue - November 2021 is not returned (which is of course highly logical), but I'd like to return it anyway in my result with null (0, zero etc.) value.
My dream result would be this:
| Yearr | Monthh | Amount |
| ----- | ------ | ------ |
| 2021  |   10   |   2    |
| 2021  |   11   |   0    |
| 2021  |   12   |   1    |
| 2022  |   01   |   2    |
| 2022  |   02   |   1    |

I can't seem to find an easy solution. And you can easily that the real split needs to be done back to year 2000.
Btw, I am running this query in SOQL and BigQuery if it's important.
Hope it's all clear and thank you for your help!

A: I think one of the easiest ways would be to create 2 auxiliar tables, one with the years you want to get info from (2000-current year), and another one with months (1-12), so you could perform an outer join with your actual table and get the number of mails created by year-month.
Let's say table years is called Years_Table with year_value column and Months', Months_table with month_value column, then you could do
SELECT TOP 200 month_value, year_value, COUNT(Email) AS Amount
FROM Contacts
RIGHT OUTER JOIN (SELECT year_value, month_value FROM Years_Table CROSS JOIN Months_Table) AS AUX_TABLE ON AUX_TABLE.year_value = YEAR(Added_Date) AND AUX_TABLE.month_value = MONTH(Added_Date)
GROUP BY month_value, year_value
ORDER BY year_value, month_value

Note: I ommited your CAST instruction since Year(added_date) should be a numeric, asuming your field added_date is a datetime field, on the contrary you should perform a different join.


text:
Q: Converting Lab Values to RGB values in opencv I am trying to convert the Lab values to its corresponding RGB values.I don't want to convert Lab image to RGB image but some values of L a and b.The function cvCvtColor only works for images.Can anybody tell me how to do this.
Thanks;
Code :
CvMat* rgb = cvCreateMat(centres->rows,centres->cols,centres->type);
cvCvtColor(centres,rgb,CV_Lab2BGR);

A: I don't know how to do it in OpenCV, but if something else is alright I've implemented it in C. See function color_Lab_to_LinearRGB and color_LinearRGB_to_RGB.
Here's the code:
double L, a, b;
double X, Y, Z;
double R, G, B;

// Lab -> normalized XYZ (X,Y,Z are all in 0...1)

Y = L * (1.0/116.0) + 16.0/116.0;
X = a * (1.0/500.0) + Y;
Z = b * (-1.0/200.0) + Y;

X = X > 6.0/29.0 ? X * X * X : X * (108.0/841.0) - 432.0/24389.0;
Y = L > 8.0 ? Y * Y * Y : L * (27.0/24389.0);
Z = Z > 6.0/29.0 ? Z * Z * Z : Z * (108.0/841.0) - 432.0/24389.0;

// normalized XYZ -> linear sRGB (in 0...1)

R = X * (1219569.0/395920.0)     + Y * (-608687.0/395920.0)    + Z * (-107481.0/197960.0);
G = X * (-80960619.0/87888100.0) + Y * (82435961.0/43944050.0) + Z * (3976797.0/87888100.0);
B = X * (93813.0/1774030.0)      + Y * (-180961.0/887015.0)    + Z * (107481.0/93370.0);

// linear sRGB -> gamma-compressed sRGB (in 0...1)

R = R > 0.0031308 ? pow(R, 1.0 / 2.4) * 1.055 - 0.055 : R * 12.92;
G = G > 0.0031308 ? pow(G, 1.0 / 2.4) * 1.055 - 0.055 : G * 12.92;
B = B > 0.0031308 ? pow(B, 1.0 / 2.4) * 1.055 - 0.055 : B * 12.92;

A: I think the only way to do what you want is:

*

*look at the OpenCV source code or documentation for cvCvtColor and implement the equations yourself (they're all explicitly given on that page)

*create a dummy image with the few Lab values you want to convert (say 1 by n by 3, where n is the number of values you want to convert) and use cvCvtColor around that.


text:
Q: Selection of Open GL2 ES image fragment I have a so library for render OpenGL image on GLSurfaceView. This library include a method that takes rectangle as argument. How i can do instrument for select fragment (portion) of OpenGL image ?
Code for render image using this library:
public void onDrawFrame(GL10 gl) {
    if (mLoaded != true && mWidth != 0 && mHeight != 0) {
        mContextCreated = true;
        CloudJNI.init();
        CloudJNI.open(mFile);
        CloudJNI.createRenderer(mWidth, mHeight);
        mLoaded = true;
    }
    if (mContextCreated == true) {
        if (!CloudJNI.renderFrame()) {

            GLES20.glClearColor(0.0f, 1.0f, 0.0f, 0.0f);
            GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
        }
    }
}


text:
Q: Area of curve given its tangent point.
Question : The area bounded by the curve $y = (x+1)^{2}$, its tangent at point $(1,4)$ and $x = -1$.

I began by finding the tangent to curve at points $(1,4)$
Differentiating the curve $w.r.t.x$ I got : $$y' = 2(x+1)$$
and substituting for $x = 1$, I got the slope of the tangent as : $$m = 4$$
Therefore the equation of the tangent of the curve is: $$y=4x$$
The tangent intersects the $x-axis$ at the origin. And the curve $y = (x+1)^{2}$ intercepts the $x-axis$ at point $-1$.
So to find the area between these 2 curves I integrated as follows:
$$\int_{-1}^{0} (x+1)^{2} - 4x \ =\frac{1}{3}x^{3} + x - x^{2} \ ; from \ x = -1  \ to \ x = 0 $$
$$ = \frac{7}{3} $$
Is this the correct method and solution?
EDIT As mentioned in the comments, integrating between $(-1,1)$ we get:
$$= \frac{8}{3}$$.

A: Yes your approach is correct but the upper bound of the integral is not correct. It should be $1$ and not $0$. The tangent to the curve is drawn at point $(1,4)$ and note the x-coordinate of the point is $1$. So the correct integral should be,
$ \displaystyle \int_{-1}^{\color {blue} 1} \left[(x+1)^{2} - 4x\right] ~ dx = \frac{8}{3}$

A:
$$\int\limits_{x=-1}^1 ((x+1)^2 - 4 x)\ dx = \frac{8}{3}$$


text:
Q: How can I access the value of a variable using it's JsonProperty attribute in a C# class? I have this class:
public class Configuration
{
   [JsonProperty("B_C.Parameter.fixtureHeight")]
   public string BCParameterfixtureHeight { get; set; }
}

I want to access the value of BCParameterfixtureHeight using its JsonProperty name of B_C.Parameter.fixtureHeight.
I've tried this which I think should work:
Configuration config = new Configuration();
config.BCParameterfixtureHeight = "1";

var a = [config].GetType().GetProperties().FirstOrDefault(p =>
p.GetCustomAttributes<JsonPropertyAttribute>().Any(at =>
at.PropertyName.Equals("B_C.Parameter.fixtureHeight")));

However, I'm getting a "Compiler Error CS1525" and a red line under the opening bracket in [config].  The compiler is saying

"Invalid expression term '['."

A: The brackets you put around config are the problem.
You should write:
var a = config.GetType() //...

EDIT:
As Chris Schaller mentionned in the comments, you can fix your initial errors by giving the expeted arguments to GetCustomAttributes.
     var a = config.GetType().GetProperties().FirstOrDefault(p =>
        p.GetCustomAttributes(typeof(JsonPropertyAttribute), false).Any(at => at is JsonPropertyAttribute && (at as JsonPropertyAttribute).PropertyName.Equals("B_C.Parameter.fixtureHeight"))
     );


text:
Q: How to get the Job Instance of Long Running Jobs in Quartz? I have created my own job class by extending the default class added couple of member variables and member methods. I saw the job gets triggered and is running for a very long time.
I just wanted to get the Job Instance not the JobDetail and wanted to invoke any member methods which has been defined by me or wanted to access the member variables.
Could you please let me know how we can achieve this?
Thanks,
Kathir

A: There is not such way, probably because quartz is meant to be compatible with a remote scheduling mode (i.e. cluster).
But if you are using it in a single server / application context, you could probably implement your own JobFactory (http://quartz-scheduler.org/api/2.1.5/org/quartz/simpl/SimpleJobFactory.html) that will just delegate to the super class the creation of the instance, and then register the instance somehow in a map or something else. Then you'll have to loop over the map keys to find the instance you are looking at.
Be careful of memory leaks with such a solution

Quick example:
In your spring configuration file:
<!-- quartz scheduler -->
<bean id="orchestration-api-quartz-factory" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
    <property name="configLocation" value="classpath:spring/quartz.properties"/>
    <property name="jobFactory">
        <bean class="service.scheduler.SpringServiceJobFactory"/>
    </property>
</bean>

And the basic implementation of your Factory:

/**
 * This job factory tries to locate the spring bean corresponding to the JobClass.
 *
 * @author Mathieu POUSSE
 */
public class SpringServiceJobFactory extends SpringBeanJobFactory implements JobFactory {

    @Autowired
    private ApplicationContext context;

    /**
     * {@inheritDoc}
     */
    @Override
    protected Object createJobInstance(final TriggerFiredBundle bundle)
                                       throws Exception {
        // create or get the bean instance
        Object bean = this.context.getBean(bundle.getJobDetail().getJobClass());

        // do what you want with the bean
        // but remeber what you did, otherwise if you forget to forget
        // you will have memory leaks !!!

        // myConcurrentMap.put("job.key", bean);

        return bean ;
    }

}

HIH


text:
Q: Java Encapsulation with arrays So I have two classes one is called bag the other is called TestBag. The goal is to ask the user what they want: to add or remove, and show what they have in the cart.
I'm kinda new to encapsulation, and I don't know how to get the user input and put it in the add method and get that to go the the cart string to show what the user has in the cart. This is what I have so far. I'm doing the add part first before the remove.
bag class:
import java.util.Arrays;

class bag {
    private String[] cart = new String[5];
    private int add;

    public String[] getcart(){
        return Arrays.copyOf(cart, getcart().length);
    }

    public int getAdd(){
        return add;
    }

    public void setAdd(int newValue){
        add = newValue;

    }

    public void setcart(String [] cart){
        cart = cart;
    }

}

TestBag:
import java.util.Scanner;

public class TestBag {

    public static void main(String[] args) {
         bag obj = new bag();

        System.out.println("Enter one of the following commands:");
        System.out.println("1 - add");
        System.out.println("2 - remove");
        System.out.println("3 - exit");
        Scanner input = new Scanner(System.in);
        System.out.println();
        System.out.println("Enter \"1\", \"2\" or \"3\"");
        int choice =input.nextInt();

        while (choice != 3) {
            if(choice == 1) {
                System.out.println("What do you want to add? ");

                for (int i = 0 ; i < obj.setAdd.length; i++ ) {
                 obj.setAdd[i] = input.nextInt();
                }
                System.out.println("Here's whats in your cart: ");
                printArray(obj.getcart());

            }
            else if(choice == 2) {
                //remove
            }
            else if(choice == 3) {
                //...exit program
            }
            else{

                System.out.println("Enter \"1\", \"2\", \"3\"");
                choice = input.nextInt();

            }

        }
    }

}

A: Thank you for sharing your code. Looking at your bag class, you're trying to achieve encapsulation through data hiding:

*

*Declare the variables of a class as private.

*Provide public setter and getter methods to modify and view the variables values.

However, declaring the getters and setters that way exposes the variables you declared as private in the first step. Well, the getters are just fine since one really has to see the contents of the cart and the number of items in  the cart. The setters are not fine. It's like declaring your variables as public since through the setters, you allow them to be modified at any time.
The main point of encapsulation through data hiding is to restrict access to the class's variables to selected methods. Here's how I'd go about it:
public class Bag{
    //Assuming that the bag has a dynamic size, a list would be appropriate here
    public List<String> items;

    public Bag(){
        items = new ArrayList<String>();
    }

    //This modifies the contents of the bag. The modification is restricted
    //through one of the methods (adding an item into the bag)
    //that are really part of the task.
    public void add(String item){
        items.add(item)
    }

    public List<String> getItems(){
        return new ArrayList<String>(items);
    }

    public int getNumberOfItems(){
        return items.size();
    }
}


text:
Q: Converting a String to json in Swift. for sending in a websocket I have a JS to send Json via websocket. as follows:
function senddata()
{
    var obj = {};
    var arrayOfRequests = [];
    arrayOfRequests.push({
        "id":22,
        "repeat":false,
    })
    obj.DataReq = arrayOfRequests;
    var stringToSend = JSON.stringify(obj);
    websocketConnection.send( stringToSend );
}

This code works as expected, and the server sends back the requested info.
I am trying to do the same thing in swift.
   func send(text: String) {
        let message = text
        guard let json = try? JSONEncoder().encode(message),
            let jsonString = String(data: json, encoding: .utf8)
        else {
            return
        }
        webSocketTask?.send(.string(jsonString)){ error in
            if let error = error {
                print("Error sending message", error)
            }
        }
    }
send(text: "{"DataReq":[{"id":22,"repeat":false}]}")

With this the server does not send any response.
If Connect both of these examples to a websocket echo server
the JS code sends {"DataReq":[{"id":22,"repeat":false}]}
while the Swift codes send "{"DataReq":[{"id":9,"repeat":false}]}".
any help is appreciated.

A: Encoding a JSON string to JSON is pointless. Remove the encoding part
func send(text: String) {
    webSocketTask?.send(.string(text)){ error in
        if let error = error {
            print("Error sending message", error)
        }
    }
}

And in the send line the double quotes are invalid. Use this syntax
send(text: #"{"DataReq":[{"id":22,"repeat":false}]}"#)


text:
Q: use tls1.2 with python 3.5 and mysql server I have successful made connection from my python app to mysql server following https://dev.mysql.com/doc/connector-python/en/connector-python-connectargs.html
The problem is that i use tls version 1.
But i want to use at least tls 1.2
On mysql server i have setup to use tls1.1 and 1.2 only.
When i try to connect to mysql python complains about wrong version.
mysql.connector.errors.InterfaceError: 2055:
Lost connection to MySQL server `at '192.168.99.100:3306',`
 system error: 1 [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1045)

print(ssl.OPENSSL_VERSION) shows me OpenSSL 1.0.2d 9 Jul 2015
What should i do to make python 3.5 use tls1.2
code that i use
from tkinter import *
import mysql.connector
from mysql.connector.constants import ClientFlag
from datetime import datetime
import ssl
print(ssl.OPENSSL_VERSION)
config = {
    'user': 'user',
    'password': 'password',
    'host': '192.168.99.100',
    'database' : "pizza",
    'client_flags': [ClientFlag.SSL],
    'ssl_ca': 'C:\\Users\\Linux\\PycharmProjects\\Kassa\\ca-cert.pem',
    'ssl_cert':'C:\\Users\\Linux\\PycharmProjects\\Kassa\\client-cert.pem',
    'ssl_key':'C:\\Users\\Linux\\PycharmProjects\\Kassa\\client-key.pem'
}
mydb = mysql.connector.connect(**config)
mycursor = mydb.cursor()

A: After wasting lots of hours i finally figured out the problem.
The problem is very simple.
I used pycharm and downloaded the wrong sql-connector which only had support for tls1.
By grabbing mysql-connector-python from mysql website i got the right version 8.0.12
So for future , check all version of software you use better .


text:
Q: Why can't different abi's be linked together? I see as a beginner that compilation units need to be the same ABI's in order to be able to be linked. I also read about how c++ commitee is hesitant to make ABI breaking changes to avoid making it hard to link against precompiled code with source unavailable. Is it not possible to somehow add some kind of translation code, or to alter old binaries somehow, such that they still link?

A: In C types such as floats, ints and chars etc, are always the same, just x number of bits in memory. Names are also not mangled in anyway so function names have to be completely different to be unique.
In C++ the classes and functions are mangled into symbols. How this mangling is done changes from compiler to compiler. So Microsoft Visual C++ might mangle a class with all the floats, then ints, and then chars, then methods. Let's call this method A.
But in GNU C++ it might work back to front compared to this. So methods, then chars, then ints and then floats. This will produce a different mangle to the Ms Compiler. Method B.
Let's say the exe is wrote in Ms Compiler and the DLL in GNU C++. You app is importing method A and expects that to be the data, but what it receives is method B and doesn't understand it and crashes.
That's what it means when the ABI's aren't standard.


text:
Q: How can I use MVC ideas without using classes? As of right now, I am still shaky on classes, so I don't want to use any classes for my site. I'm still practicing with classes.
But how can I implement the MVC idea without classes?

Would this work for a MVC?
index.php (the view)
index_controller.php
index_model.php

    Is this right for what a MVC should be?
View: show html, css, forms
Controller: get $_POST from forms and any data from the user, get info from db
Model: do all the functions, insert/delete in db, etc

Basically separate the HTML/css for the view, all the data collecting for the controller, and the logic for the model. And just connect them all using require_once.

A: Controller: Your index.php, accepting and directing requests. This can certainly be a 'classless' script. It would act as both controller and 'front controller'.
View(s): A collection of presentation scripts, specific script included by your controller. Essentially 'getting' data from the variable scope of the controller.
Model(s): A collection of functions that provide access to your data. The controller determines what to include for a request.
Sure, it can be done, but you loose a lot not using classes (OOP). Here's a quick example of what the controller might look like. Nothing amazing, just an idea. Showing the controller should shed some light on the model/view as well.
<?php
  $action = getAction(); //parse the request to find the action
  switch($action){
    case 'list':
      include('models/todolist.php'); //include the model
      $items = todolistGetItems(); //get the items using included function
      include('views/todolist/list.php'); //include the view
      break;
    case 'add':
      if(!empty($_POST['new'])){
        include('models/todolist.php'); //include the model
        todolistAddItem($_POST); //add the item
        $items = todolistGetItems(); //get the items using included function
        include('views/todolist/list.php'); //include the view
      } else {
        include('views/todolist/add.php'); //include the view
      }
  }


text:
Q: SonarQube 4.0 - LifeCycleException on startup with https port uncommented - reasons? I'm having trouble to get SonarQube running in combination with standalone HTTPS.
If I uncomment sonar.web.https.port= and set the rest of the necessary options Tomcat throws the following exception:
WrapperSimpleApp: Encountered an error running main: org.apache.catalina.LifecycleException: Failed to initialize component [StandardServer[-1]]
org.apache.catalina.LifecycleException: Failed to initialize component [StandardServer[-1]]
     at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:106)
     at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:139)
     at org.apache.catalina.startup.Tomcat.start(Tomcat.java:335)
     at org.sonar.application.EmbeddedTomcat.start(EmbeddedTomcat.java:71)
     at org.sonar.application.StartServer.start(StartServer.java:38)
     at org.sonar.application.StartServer.main(StartServer.java:50)
     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
     at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
     at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
     at java.lang.reflect.Method.invoke(Unknown Source)
     at org.tanukisoftware.wrapper.WrapperSimpleApp.run(WrapperSimpleApp.java:240)
     at java.lang.Thread.run(Unknown Source)
Caused by: org.apache.catalina.LifecycleException: Failed to initialize component [StandardService[Tomcat]]
     at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:106)
     at org.apache.catalina.core.StandardServer.initInternal(StandardServer.java:814)
     at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:102)
     ... 11 more
Caused by: org.apache.catalina.LifecycleException: Failed to initialize connector [Connector[HTTP/1.1-443]]
     at org.apache.catalina.core.StandardService.initInternal(StandardService.java:566)
     at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:102)
     ... 13 more
<-- Wrapper Stopped

Any ideas what I am missing? As soon as I disable the HTTPS port it starts up without a problem...

A: I had the same problem - turns out the port used for the webserver was already in use. Did you try changing the port number in sonarqube-4.4\conf\sonar.properties sonar.web.port=9001 ?


text:
Q: Restoring M1 Mac without (or with 100% worn) SSD I just wondered, in case you have 100% worn SSD is it possible to turn on your Mac and reinstall macOS to another drive?

A: Yes, you can boot the M1 Mac from an external Thunderbolt 3 drive.
Attach your Thunderbolt 3 drive to an M1 Mac, erase the drive and format as APFS with Disk Utility, and then run the macOS installer, selecting the external drive as the target, and install.
If you haven't got a working M1, you can use the M1 Mac that won't boot from the internal drive, by powering it up while pressing and holding (long press) the power button. When you get the startup menu, click the Options icon and "Disk Utility" in order to erase and format the external drive as APFS - and then from the Options menu select "Reinstall macOS" to install macOS.
After installation, you can use the external drive to boot the M1 Mac that hasn't got a SSD drive. When you power on the M1 Mac, you need to long press the power button until the display shows the startup menu. From here you can select the external drive to boot from.
Note that if you installed macOS on a different computer than the one you're trying to boot up, you will be required to enter various credentials (such as your user's password, your Apple-ID password, etc).


text:
Q: Issue with invalid syntax error in python 2.7.3 I am trying to run a script (see below) to read in a fasta file and output a taxonomy file (printing only the sequence header without the '>' character) but I keep getting a syntax error which I have not been able to resolve. As a result the script creates the cleanseqs.tax file but the file is blank. Could anyone help?
Thank you!
>>> Fasta = open("testseqs.fasta", "r")
>>> Tax = open("cleanseqs.tax", "w")
>>> while 1:
...     SequenceHeader= Fasta.readline()
...     Sequence= Fasta.readline()
...     if SequenceHeader == '':
...             break
...     Tax.write(SequenceHeader.replace('>', ''))
... Fasta.close()
  File "<stdin>", line 7
    Fasta.close()
        ^
SyntaxError: invalid syntax
>>> Tax.close()

A: Add in an extra line, as ... Fasta.close() isn't necessarily the end of the while loop. It could take in another keyword, like else. Adding another line implies the end of the while loop.
Or did you mean to indent Fasta.close()?

A: The interpreter thinks you are trying to put the Fasta.close() call inside the while-loop, but the line is improperly indented. Just press enter when you want to end the while block.
Also it would be ideal here to use the with-statement so you can get rid of the close()-calls entirely.

A: A file object is a context manager, so you can use the with statement to automatically close the files:
with open("testseqs.fasta", "r") as fasta, open("cleanseqs.tax", "w") as tax:
    while True:
        ...

A: As you requested, here are a couple of examples with existing FASTA parsers:
Example file:
$ cat test.fasta
>header1 description1
SEQUENCE
>header2 description2
SEQUENCESEQUENCE

*

*With BioPython.SeqIO:
from Bio import SeqIO
reader = SeqIO.parse('test.fasta', 'fasta')
with open('biopython.tax', 'w') as out:
    for prot in reader:
        out.write(prot.description + '\n')
reader.close()

Output:
$ cat biopython.tax
header1 description1
header2 description2

*With pyteomics.fasta (pyteomics is a library developed by me and my colleagues):
from pyteomics import fasta
with open('pyteomics.tax', 'w') as out, fasta.read('test.fasta') as reader:
    for prot in reader:
        out.write(prot.description + '\n')

Output:
$ cat pyteomics.tax
header1 description1
header2 description2

A: I had the same problem, my program would write in a file but file turned out to be empty.
Correct your indent and then close the file, content will be present in file after closing it in python.


text:
Q: WSO2 Business Activity Monitor supported payment gateway I have configured APIs via the WSO2 API Manager and connected the API Manager to the Business Activity Monitor. I now need to charge for API usage.
Does WSO2 Business Activity Monitor support any payment gateway out-of-the-box? Is there any reference manual or use case about connecting BAM to a payment gateway?
If BAM doesn't support processing payment via integration with 3rd party payment gateways, what should be the best practice to process payments? (e.g. like StratosLive does?)
I can't seem to find any guide about this topic.

A: Please refer to [1] for more details for billing and metering. In BAM there is no way to connecting to a payment gateway.
[1] http://docs.wso2.org/wiki/display/AM140/Monitoring%2C+Statistics+and++Billing


text:
Q: Admin login should ask credentiols while loging in Please anybody could help me to find the solution for following,
.  Login with admin
    - Copy a link from the browser
    - Close the browser without logging out
    - Open a browser and paste the link
Expected:
  It should prompt to enter credentials.
  Actual:
  Its logging in without prompting for credentials

A: Browser remember that you are logged because cookies. These cookies have expiration date. Cookies will be not deleted when you close the browser (only privacy tabs clear cookies). Try to sign out if you want to log out.


text:
Q: Как передать в функцию лямбда выражение, если она захватывает внешние переменные Есть такой код:
#include <iostream>
using namespace std;

bool f(double f_(int), int k) {
    if (f_(k) < 1) {
        return 0;
    }
    else {
        return 1;
    }
}
int main() {
    int m = 3;
    auto g = [&m](int k)->double {return (double)k / 3; };
    cout << f(g, 2) << endl;
    cout << f(g, 5) << endl;
    return 1;
}

И он не компилится пишет:
Ошибка (активно)    E0413   не существует подходящей функции преобразования из "lambda []double (int k)->double" в "double (*)(int)"

Если написать так то всё работает (квадратные скобки пустые)
auto g = [](int k)->double {return (double)k / 3; };

Что я делаю не так подскажите пожалуйста.

A: У вас лямбда с захватом - не совсем функция, а функциональный объект... Чтобы исправить ситуацию - проще всего воспользоваться шаблонами:
template<typename Func>
bool f(Func f_, int k) {
    if (f_(k) < 1) {
        return 0;
    }
    else {
        return 1;
    }
}

Еще вариант - использовать function<>:
bool f(function<double(int)> f_, int k) {
    if (f_(k) < 1) {
        return 0;
    }
    else {
        return 1;
    }
}


text:
Q: DocuSign Bulk Send w/ CSV User Portal The current goal is to be able to send multiple files to multiple recipients through the user portal on our website. We want to make this process as efficient as possible because we will have lots of files to sign. Lastly, I would need a way to track and save all the users.
From what I know about docusign, I am able to send a file to multiple recipients in bulk using bulk send using just the website and not having to use the API at all. Is it possible to send multiple files to multiple recipients through the same CSV? Or would it be better to just send each file separately to multiple clients and do that for each file? Also, I'm wondering if it's possible to do that in the API as well. Previously, I achieved sorting clients ID & envelope ID using the docusign api with PHP and connected it to a database. Let me know which method seems optimal for my solution.

A: Steven, you can use the API to use Bulk Send.
In fact, with the DocuSign eSignature API v2.1 this functionality is much improved and allows you to do all of the above.
See here for more details: https://www.docusign.com/blog/dsdev-deep-dive-discussions-bulk-send-with-esignature-api-v2-1/


text:
Q: Back navigation from an alert view button I'm having some problems with back navigation to previous view controller (in the stack of my navigation controller) when user taps the custom "back" button that is shown in an alert view.
I've tried several ways to do it, but I haven't been able to do it. When that button is tapped, the application simply goes back to the controller that popped the alert (as if the user press the "cancelButton").
Hope you can understand me with this sample code:
In viewDidLoad, I pop up the alert with:
UIAlertView *alert = [[UIAlertView alloc]
        initWithTitle:@"XXXXXX"
        message:@""
        delegate:self
        cancelButtonTitle:@"OK"
        otherButtonTitles:@"Back", nil];
    [alert show];
    [alert release];

Then, inside the code of the view controller I call next action to try to navigate back:
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex == 1)
{
    [self.navigationController popViewControllerAnimated:YES];
}}

The whole code is executed and it has no debug errors.
If I haven't explained my trouble properly, please tell me and I'll try to do it better! (I'm Spanish and my English is not the best).
Thanks in advance.

I'll try to explain it better, in order to show you that my problem could be harder to resolve...
I have a navigation controller, that in a determinate moment, shows a view with a tab bar. You may know that there is not way to implement a tab bar controller inside a navigation controller, so I've used a "custom controller" that inserts that tab bar.
Then, from that view with the tab bar, (inside which I have already added some subviews) I want to navigate back (clicking the alert button) to the view without tab bar, that I supose to be the previous view in the stack of the navigation, as I can see when I push the back button in the navigation bar...
I don't know if now it's clearer or I have confused you more...
I could try to make you a diagram of controllers, if you want so.
Thanks for your help!

A: trying in a separate thread.
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex == 1)
{
   [self performSelectorInBackground:@selector(newThreadMethod) withObject:nil];
}
}
-(void)newThreadMethod{
     [self performSelectorOnMainThread:@selector(go) withObject:nil waitUntilDone:NO];
 }
-(void)go{
       [self.navigationController popViewControllerAnimated:YES];
  }

but this is not a right way of doing. but for time being it will help you.

A: for the part of the tab bar, I had successfully merged navControllers with a tabController. The tab bar controller has to be at the top of the diagram, and instead of view controller for each tab bar item, use navControllers, specially in the first tab bar item; just hide the tab bar in the first viewDidLoad and unhide it when you need it.


text:
Q: Why "that of" in these sentences?
"I have anxiously awaited the arrival of those such as yourselves. My names Megumin! My calling is that of an arch wizard, one who controls explosion magic, the strongest of all offensive magic! Do you, too, desire my forbidden strength, which is so almighty, I've been ostracized by the entire world?" – Megumin

*

*My calling is that of an arch wizard (in bold above)

*My name is that of Michael. No god am I, but one who serves.

*A Barons title is that of a lord, but he may opt to be referred to as Baron (or Baroness) versus lord.

*My job title is that of Head of Commercial Operations, however most of the team call me the Director.

In all of these sentences, why they use that of instead of just saying "A is B", such as "my calling is arch wizard"?

A: This is an effect of "heightened language". It is a deliberately fancy way of expressing something to mark the language of a strange character.
Here, the plain form would be "I am a wizard."  You can raise the language a little by using the rare meaning of "calling"="job", to give "My calling is being a wizard." Then you can raise the language further to say "My calling is the calling of a wizard", but then avoid the repetition of "calling" by saying "My calling is that of a wizard".
Raised language is possible in most of the world languages, and Japanese has a particularly complex system of plain and raised language. This may be the translator's attempt to represent a complex and fancy expression of Japanese in English.

A: I'm not sure all of those are correct in everyday, terrestrial, non-fantasy English.
Both 2 and 4 sound much better with just a simple "is" instead of "is that of". Number 2 sounds particularly non-idiomatic. It should be "My name is Michael." Period.
4, also, should be "My job title is [perhaps in quotation marks or even italicized] "Head of Commercial Operations." because "Head of Commercial Operations" literally is his job title.
"That of" could be used to avoid saying plain "is" for some reason. Perhaps because the words following "is" aren't the literal completion of the statement.
For example:

"My name is that of my father and his father before him." You wouldn't say "My name is my father."

or

"My job title is that of the highest authority in the organization." because that isn't the exact wording of his job title.

Someone might also use "is that of" instead of just "is" in an effort to sound very formal, legalistic, or just plain pompous. Adding extra unnecessary words to your statements can help with that. It sounds to me like that might be the situation in example 1, where the author is trying to convey the personality type and social station of the speaker, Megumin.

A: The use of that of is correct in all instances quoted, except in the sentence, My name is that if Michael.  I think poetic licence is being used here, meaning that in literature it is acceptable to deviate from the accepted use of the language, for effect.


text:
Q: In SVG, why the stroke are blurry in some specific positions I just use SVG to draw rectangles, but I found the stroke were blurry when the position 'x' is an integer while others were not when the position 'x' is an integer plus 0.5
It can be reproduced both in Chrome and IE, has someone met this before?

<svg type="svg-chart" style="height: 100%; width: 100%; padding: 0px;">
    <g>
        <rect x="2" y="2" width="17" height="81" style="fill:rgb(31,119,180);fill-opacity:0.7019607843137254;stroke-width:1;stroke:rgb(255,0,0);stroke-opacity:1" class="gm-shape-grid-bar" type="shape" subtype="gbar" status="normal"></rect>
        <rect x="23" y="2" width="17.5" height="81" style="fill:rgb(31,119,180);fill-opacity:0.7019607843137254;stroke-width:1;stroke:rgb(255,0,0);stroke-opacity:1" class="gm-shape-grid-bar" type="shape" subtype="gbar" status="normal"></rect>
        <rect x="43.5" y="2" width="19.5" height="81" style="fill:rgb(31,119,180);fill-opacity:0.7019607843137254;stroke-width:1;stroke:rgb(255,0,0);stroke-opacity:1" class="gm-shape-grid-bar" type="shape" subtype="gbar"></rect>
    </g>
</svg>


text:
Q: Google Script Limit Wanted to know whether there is any limit imposed by Google for script execution, like i am having a Google sheet with lengthy code with having multiple user accessing the sheet. I am having Workspace account and not Consumer account.
Question is, whether there any numbers of execution per day limit imposed by google?

A: See Quotas for Google Services.
To improve script performance, see Apps Script best practices.


text:
Q: passing arrays (&) to functions c++, runtime error #include <iostream>
#include <cmath>
using namespace std;

void input(int(&x)[10]);
int copy(int (&x)[10], int(&y)[10]);
void read(int(&x)[10], int b);

int main()
{
    int m[10], v[10], c;
    input((&m)[10]);
    read((&m)[10], 10);
    c = copy((&m)[10], (&v)[10]);
    read((&v)[c],c);
    system("PAUSE");
    return 0;
}

void input(int(&x)[10])
{
    for(int i=0; i < 10; i++)
    {
        cout<<"enter number "<<i+1<<": ";
        cin>>x[i];
    }
}

void read(int(&x)[10], int b)
{
    for(int i=0; i < b; i++)
    {
        cout<<"number("<<i+1<<"): "<<x[i];
    }
}

int copy(int(&x)[10], int(&y)[10])
{
    int c = 0;
    for(int i = 0; i < 10; i++)
    {
        if(x[i] % 3 == 0)
        {
            y[c]=x[i];
            c++;
        }
    }
    return c;
}

I get a runtime error when i input the first number, any help will be appreciated
I think the problem is in the way i pass the arrays to the functions but I am not really sure
the aim of the program is to get input for 10 int-s in the array m, than transfer those divisible by 3 to v, and output both

A: input((&m)[10]);

This doesn't do what you think it does; &m is a pointer to an array, so (&m)[10] is a reference to the 10th element of an array of arrays; in other words, to an invalid block of memory some distance off the end of m.
You want input(m); to pass a reference to m.

A: The syntax of passing an array is not correct (though it compiles). It should be as simple as,
input(m);
read(m, 10);
c = copy(m, v);
read(v, c);

int(&x)[10] should be used for the function prototype where you are receiving an array of size 10 by reference. While calling the function simply pass the name of the variable.

A:
void input(int(&x)[10])

In this function signature:

*

*x is the argument name

*int(&)[10] is the argument type (reference to an array of 10 ints).

Now consider how you've called this function, presumably by copy/paste:

input((&m)[10]);

With any function call, you write just the name of a variable, not its type; so, when you're passing the array to the function, you should just write:
input(m);

(At present you're passing something else that does not exist in memory, because of &'s triple meaning.)
Same goes for the other places where you pass [references to] arrays.

A: You are passing pointers to the functions, not references.
input((&m)[10]);

In the line above, the & is getting the address of m, and making it into a pointer.
The functions are not expecting pointers. Skip the & in the calls, and it should work.
Also, I suggest you try to find a tutorial describing the difference between a pointer and a reference. A quick Google search turned up this question here on Stack Overflow, with some good answers.

A: It does not work to pass arrays into c++. This will result in a run time error unless you use pointers or create a class that contains an array and pass that.

A: Expanding on the answer above: m[10] is past the last element in the array so what happens is you are reading memory outside your variables which is generally considered to be bad form.


text:
Q: Upload image from laravel api to core php project folder I have made Laravel API, which works with Android. This project is integrated to php web project. Both project are hosted in same hosting, but are in different folder.
In web project, image is uploaded in web project folder, and from laravel api image is uploaded to it's project folder only. Now I want to upload image from laravel api to the other project's upload directory.
Image upload code:
                $imageName = $rand . $image . $userid . "." . $ext;

             $request->file('image_name')->move(
                 'http://corephp/webProject/upload/' . $year . "/" . $month , $imageName

            );

when tried to upload, the problem says: Unable to create the directory .
but this works for laravel directory only:
  $request->file('image_name')->move(
                base_path() . '/public/uploads/' . $year . "/" . $month, $imageName
            );

A: Change
'http://corephp/webProject/upload/' . $year . "/" . $month
To
base_path("../../corephp/webProject/upload/$year/$month")


text:
Q: Building FFmpeg.NET .dll I need to use some FFmpeg functions in C# (to be precise, in GTK#). So I downloaded wrapper FFmpeg.NET. After that I try to build FFmpeg.NET.2008.sln(reference: I will build dll in Visual Studio 2008, but will use in GTK#), then get the following errors:

Error 1   error PRJ0019: A tool returned an error code from "Performing
  Makefile project actions" FFMpeg.NET
  Error 2   The referenced assembly
  "C:\Users\Zhenya\Documents\ffmpegdotnet-94877\bin
  (debug shared)\ffmpeg.net.dll" was not found. If this assembly is
  produced by another one of your projects, please make sure to build
  that project before building this one.

How to fix these issues?
Or how to correctly build this wrapper to get .dll?

A: FFmpeg for .NET includes very old version ffmpeg. I use ffmpeg.exe directly. For example
    void RunFfmpeg()
    {
        ffmpegProcess = new Process
            {
                EnableRaisingEvents = true,
                StartInfo =
                    {
                        FileName = GetFfmpegPath(),
                        Arguments = ffmpegParams.ToString(),
                        UseShellExecute = false,
                    },
            };
        ffmpegProcess.Start();
        ffmpegProcess.BeginOutputReadLine();
        ffmpegProcess.WaitForExit();
    }


text:
Q: elasticsearch-php create index returns \BadRequest400Exception I have a fresh installation of elasticsearch 5.0.0 and elasticsearch-php . I am trying to create an index.
I run the code from this index management documentation:
$client = ClientBuilder::create()->build();
$params = [
    'index' => 'my_index'
];

// Create the index
$response = $client->indices()->create($params);

and it works. I create an index successfully.
I try the next code snippet:
$client = ClientBuilder::create()->build();
$params = [
    'index' => 'my_index',
    'body' => [
        'settings' => [
            'number_of_shards' => 3,
            'number_of_replicas' => 2
        ],
        'mappings' => [
            'my_type' => [
                '_source' => [
                    'enabled' => true
                ],
                'properties' => [
                    'first_name' => [
                        'type' => 'string',
                        'analyzer' => 'standard'
                    ],
                    'age' => [
                        'type' => 'integer'
                    ]
                ]
            ]
        ]
    ]
];

// Create the index with mappings and settings now
$response = $client->indices()->create($params);

and I get:
Elasticsearch\Common\Exceptions\BadRequest400Exception with message 'No handler found for uri [/my_index] and method [POST]'

any ideas why?
This code used to work when I used elasticsearch 2.0
EDIT: I found this question so either it is a problem with elasticsearch-php or I need to update it I guess
I am using elasticquent which I have just realized requires elasticsearch-php version <2.2 so this is what is causing the problem

A: Looking at the error message:
No handler found for uri [/my_index] and method [POST]

This means that your create index call is using an HTTP POST method under the hood. In previous versions (i.e. pre 5.0), the elasticsearch-php client used to create indices with an HTTP POST but since ES 5.0 only HTTP PUT is accepted to create a new index.
This change back in september made this create call compatible with ES 5.0 again.
The only possible explanation is that you have ES 5.0 installed but you don't have the 5.0 version of the elasticsearch-php client installed.
Since you're running Elasticquent which doesn't yet support ES 5, you can temporarily go around this issue by modifying the Endpoints/Indices/Create.getMethod() method to always return PUT instead of POST and your call will work again, but you might run into other incompatibilities.


text:
Q: no operator ">>" matches these operands -- operand types are: std::istream >> const double My Code
#include <iostream>
#include <stdlib.h>
#define Pi 3.14159

using namespace std;

class Rectangle
{
    public:
        friend ostream &operator<<(ostream &output,const Rectangle &D)
        {
            output<<"length:"<<D.length<<endl<<"height:"<<D.height<<endl;
            return output;
        }
        friend istream &operator>>(istream &input,const Rectangle &D)
        {
            input >> D.length >> D.height;
            return input;
        }
    private:
        double length;
        double height;
};

The error is in [17,19]:no operator ">>" matches these operands -- operand types are: std::istream >> const double
I am searching for a long time on net. But no use. Please help or try to give some ideas how to achieve this.
Thank you very much for answering.

A: Ask yourself, can you read into a const variable? Reading to a variable changes the variable, so the answer is obviously no.
Try this
friend istream &operator>>(istream &input,Rectangle &D)


text:
Q: Hibernate entity does not update in application, it does in database I'm asking for your kind answer to the following: What would be the reason for an entity state not getting updated in the Application BUT it does in the database.
A simple example.
System.print.out.println(patio.getName()); // = "HisYard"
patio.setName("MyYard");
session.saveOrUpdate(patio);
session.persists(patio);
session.flush();
session.commit();
session.disconnect();

------MySql Database-------
id_patio = 3
name = "MyYard"
------Database-------

Later on the same application...

Session session = HibernateUtil.getSessionFactory().openSession();
int niceNeigborhood = 3;
Neighborhood neighborhood = (Neighborhood)session.load(Neighborhood.class, niceNeigborhood);
session.refresh(neighborhood);
String whosYardIsThis = neighborhood.getHouse().getPatio().getName();
System.print.out.println(whosYardIsThis); // = "HisYard" !!!!!!!

As you can see, nothing, flush, commit, refresh, save, nothing works. BUT my database IS updated, the entity is NOT.
Help, please.

A: After a whole day of reading blogs and posts, I could find solution to this problem. Basically, the problem is this: When you want to obtain an updated instance of a given entity with all its properties "properly" updated, and to do so your business logic requires to traverse objects to reach  the given entity, you need to set lazy="false" in the collection mapping tag of the intermediate objects. My example:
String whosYardIsThis = neighborhood.getHouse().getPatio().getName();

To obtain a Patio object with its properties really updated (previously in other part of your project), you need to map House's Collection of Neighbors to
<set name="neighborhood" inverse="true" cascade="all-delete-orphan" lazy="false">

so as the data be always up-to-date, fetched from the very database and not from the troublesome cache.
For better explanation than mine, check the experts: 6.2. Collection mappings.


text:
Q: kids' book from the 1950s/early '60s about a boy who built a spaceship out of a box and took his dog into space Children's book, likely written in later '50s or early '60s featuring a young boy builds space ship in yard ( garage?) from cardboard box.

*

*His dog may talk, may be an alien.

*He takes his dog into space.

*Likely black/white illustrations.

A: This could be Rusty's Space Ship By Evelyn Shipley Lampman, 1957.
Two kids, Rusty and Susan, build a play spaceship out of junk.  But a mysterious person wants their ship, who turns out of be a lizard shaped alien named Tiphia.
Anyway, most of the plot involves, Tiphia, the kids, and their dog travelling around the solar system in Rusty's play spaceship powered by Tiphia's own spaceship.
It is mentioned in other answers:
https://scifi.stackexchange.com/questions/235351/childs-science-fiction-book-about-kids-in-space-with-a-metal-disk-and-an-alien/235355#235355[1]
https://scifi.stackexchange.com/questions/202126/kids-book-about-boys-finding-a-disc-from-a-planet-called-eyopee/202129#202129[2]
https://scifi.stackexchange.com/questions/214382/60s-book-about-a-boy-who-builds-a-spaceship-from-cardboard-in-garage/214384#214384[3]
https://scifi.stackexchange.com/questions/66578/childrens-novel-three-children-plus-dog-travel-to-the-moon-in-pretend-space/145518#145518[4]
And my answer to this question about interstellar navigation wonders whether Tripetha ever managed to find his home world.
https://worldbuilding.stackexchange.com/questions/180161/finding-earth-on-a-star-map/180214#180214%5B1%5D[5]


text:
Q: vaadin - delay execution while modal dialog window is open I have a grid layout in which I want to show a pop up when the user tries to replace a component which is already present in the grid.
For e.g. the grid layout has a Label (wrapped in a DragAndDropWrapper) which is present at 0,0 position.
If the user tries to add a new component at the same position(0,0 position), then it should show a pop up (confirmation dialog box) asking the user to confirm if the user wishes the replace the existing component or not.
Now, my issue is that the current thread does not wait for the execution to complete. It keeps going ahead after showing the pop up box. Thus, there is a lot of problem in updating the UI after the input is taken from the dialog box for the user's answer.
Can someone show how to do this? Note that I need to do this in a DragAndDropHandler's drop method call as I need to show the dialog box only when the user tries to drop a new component on an existing component of the grid layout.
A working example would be a great help.
Thanks in advance.

A: So I followed the comment by André Schild and it did work for me.
I just remember which component and location was used for replacing the component. Then, I ask for a confirmation and if the user says Yes, then I just go ahead and replace it.
Thanks again Andre


text:
Q: If I upload a text file via one form, is it possible to read it on other form that is showing record of a particular entries from database? I don't want to read file using tmp_name. Is there any other possible methods to read file from a folder with its original name that I stored in databases?
Also, I am trying to access contents of that file in second form.

A: All else being equal: No.
A file was uploaded and it was saved to a temporary place with a generated filename and your PHP program was told what filename the client said it should have. The two filenames are not the same.
You can't access it using its original file name because that isn't the file name it has on the computer running the PHP.
The script handling the upload could use move_uploaded_file to move the file to somewhere else and change its name so it is the same as the one the client told you it originally had. Then you would be able to use that name. You would, of course, have to be careful to avoid collisions. Two different files with the same name could be uploaded.


text:
Q: database context insert and delete bug I am trying to insert some entity into the databse context and delete it.
The trouble I have right now is when I try to delete it , it gives me this error.
System.InvalidOperationException : The object cannot be deleted because it was not found in the ObjectStateManager.

So I googled and people tell me to call .attach() to the entity, after I did that I got
System.InvalidOperationException : An object with the same key already exists in the
ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same
key.

So either way , its not working - -
Some Code:
    public void delete(WebPointOrderHead item)
    {
        WebDataEntities3 dbcDelete = this.dbc;
        WebPointOrderHead deleteItem = dbcDelete.WebPointOrderHeads.Where(p => (p.OrderID == item.OrderID)).First();
        dbcDelete.WebPointOrderHeads.Remove(item) ;
        dbcDelete.SaveChanges();
    }

    public void insert(WebPointOrderHead item)
    {

        WebDataEntities3 dbcinsert = this.dbc;
        WebPointOrderHead itemToAdd = BusinessLogic.calculatePoints(item, dbcinsert);
        var IDs = from id in dbcinsert.WEBIDs
                  where id.TableName.Equals("PointOrder_ID")
                  select id;
        IDs.First().NextID++;
        var highestID = (from c in dbcinsert.WebPointOrderHeads
                         select c.OrderID).Max();
        itemToAdd.OrderID = highestID + 1;
        dbcinsert.WebPointOrderHeads.Add(itemToAdd);
        dbcinsert.SaveChanges();
    }

A:    public void delete(WebPointOrderHead item)
{
    WebDataEntities3 dbcDelete = this.dbc;
    WebPointOrderHead deleteItem = dbcDelete.WebPointOrderHeads.Where(p => (p.OrderID == item.OrderID)).First();
    dbcDelete.WebPointOrderHeads.Remove(item) ;
    dbcDelete.SaveChanges();
}

A few things here about this snippet.
1) You can clean up your LINQ to be like this:
    WebPointOrderHead deleteItem = dbcDelete.WebPointOrderHeads.First(x=>x.OrderID == item.OrderID);

My prefered method of choice would look more like this:
WebPointOrderHead deleteItem = dbcDelete.WebPointOrderHeads.FirstOrDefault(x=>x.OrderID == item.OrderID);
if(deleteItem == null)return;

This way you have a little cleaner LINQ and only try to remove the record if it was found in the context.
2) You are querying the context for the entity, but then trying to remove the detached entity. You need to change .Remove(item) to .Remove(deleteItem); The context has no idea what item is.
3) Addressing your Insert/Update logic. When you are working with detatched entities, you need to check the ID. If the ID is > 0 then you need to use .Attach(), if the ID is 0 you need to use .Add()
4) I'm confused by your insert block of code, it looks to me like you are trying to control the IDs of your entities yourself. This has many issues: Not Thread Safe, Not Needed, Bad, etc... If you Add() an entity to a context that does not have an ID it will be inserted, and your identity will be assigned assuming you have an Identity column. If you Attach() an entity with an existing ID, then EF will generate an Update statement.


text:
Q: Retrieving PayPal email address after payment? When you are setting up a PayPal Buy Now Button, you can take customers to the URL when they finish checkout.
Is there a way to retrieve their PayPal email immediately after PayPal checkout using $_GET?
Does PayPal append some kind of ?email=email@address.com at the end of your thankyou page?
Or is there any variable I could add at the end of my thankyou page when typing a success URL inside the PayPal?
Basically I want to store their PayPal email address that they used on deposit, so that when they would cash out, the same PayPal email address will be used.
Just wanted to let you know why I'm interested in storing their real PayPal email address in the first place.
Any help from someone who have knowledge in this would be appreciated.

A: With a legacy HTML Buy Now button that redirects away from your page, there is never any guarantee the payer will return to your site after a successful transaction. With such an old integration, the only reliable way to get the email address of the payer and record this information in your database is to implement the old IPN service.

Instead, you should do a server-side integration of the current Standard Checkout.
Follow the Set up standard payments guide and make 2 routes on your server, one for 'Create Order' and one for 'Capture Order', documented here. Both routes should return only JSON data (no HTML or text). Inside the 2nd route, when the capture API is successful you should store its resulting payment details in your database (particularly purchase_units[0].payments.captures[0].id, which is the PayPal transaction ID -- as well as the payer object's email address, in your case) and perform any necessary business logic (such as sending confirmation emails or reserving product) immediately before forwarding your return JSON to the frontend caller.
Pair those 2 routes with the frontend approval flow: https://developer.paypal.com/demo/checkout/#/pattern/server


text:
Q: ScrollView acting weired (Xcode 11 GM seed - SwiftUI) I was trying to make a custom list. And its acting weired if we add Encapsulated VStack in scrollView and try to add new row from that VStack. But we have to encapsulate because in Xcode will give "complex view complier error". I am providing full code for better understanding. Please try to run it. New element is not added as expected and its pushing everything upward.
struct RowView: View {

var body: some View {
    VStack{
          HStack{
              Spacer()

              .foregroundColor(Color.black)
              Spacer()
          }

      }
      .background(Color.white)
      .cornerRadius(13)
      .padding()
}}

struct cView:View {
@State var array: [String] = []

@State var height: CGFloat = 60
var body: some View {
    VStack{
        Button(action: {
            self.array.append("Test")
        }, label: {
            Text("Add")
        })

        VStack{

            ForEach(array, id: \.self){_ in
                 RowView()
            }
        }
        .background(Color.red)
        .cornerRadius(13)
        .padding()

    }

}}

struct ContentView : View {

@State var array: [String] = []

var body: some View {

        ScrollView{

            VStack{

                Text("d")
                    .frame(height: 90)
                VStack{
                       cView()
                }

            }
        }
        .navigationBarTitle("Test", displayMode: .automatic)

}}

A: When I reformatted and removed unused stuff I got:
struct RowView: View {
    let text: String

    var body: some View {
        VStack{
            HStack{
                Spacer()
                Text(text).foregroundColor(Color.black)
                Spacer()
            }
        }
        .background(Color.white)
        .cornerRadius(13)
        .padding()
    }
}

struct cView:View {
    @State var array: [String] = []

    @State var height: CGFloat = 60
    var body: some View {
        VStack{
            Button(
                action: { self.array.append("Test") },
                label: { Text("Add") }
            )
            ForEach(array, id: \.self){text in
                RowView(text: text)
            }
            .background(Color.red)
            .cornerRadius(13)
            .padding()
        }
    }
}

struct ContentView : View {
    var body: some View {
        List {
            VStack{
                Text("d")
                cView()
            }
        }
    }
}

ScrollView is a real PITA and it hates Text which is why I replaced it with a List. RowView was missing a Text IMHO so I put one in. The array in ContentView was never used so I removed it, similarly a navigatinBarTitle needs a NavigationView.
This isn't really an answer as it uses List instead of ScrollView but it does point to where your problems lie. It is also very strange as every thing is in a single List row but I tried to change as little as possible.
You might like to try running SwiftLint on your code. I often swear at it, especially when it complains about the cyclomatic complexity of my enum switches but it does improve my code.

A: Most likely a bug, but I did not need to encapsulate. And if I don't, the code works as expected:
struct RowView: View {
    var body: some View {
        VStack{
            HStack{
                Spacer()
                    .foregroundColor(Color.black)
                Spacer()
            }

        }
        .background(Color.white)
        .cornerRadius(13)
        .padding()
    }
}

struct ContentView : View {
    @State var array: [String] = []
    @State var height: CGFloat = 60

    var body: some View {
        ScrollView{
            VStack{
                Text("d")
                    .frame(height: 90)

                VStack{
                    Button(action: {
                        self.array.append("Test")
                    }, label: {
                        Text("Add")
                    })

                    VStack{
                        ForEach(array, id: \.self){_ in
                            RowView()
                        }
                    }
                    .background(Color.red)
                    .cornerRadius(13)
                    .padding()
                }
            }
        }
        .navigationBarTitle("Test", displayMode: .automatic)
    }
}


text:
Q: PHPStorm Built in Terminal - How do I backspace words? I love PHPStorm's built in terminal, all my zsh aliases work properly and it's super convenient.
The only thing it's missing is the ability to backspace by words (like I can in OSX's default terminal, with the option + backspace keys).
Is there any way to get that functionality in PHPStorm's built in terminal?

A: By default the zle (zsh command line editor) command to backspace whole words - backward-kill-word (or vi-backward-kill-word if you are using viins keymap) - is also bound to Ctrl+W.
Should this not be the case for you, you can set this with
bindkey '^W' backward-kill-word

in your configuration.

A: Isn't currently possible. Please vote for IDEA-113214


text:
Q: Capturing of "session cookies" while on unencrypted wifi
Possible Duplicate:
On unencrypted public wifi, what kind of real danger am I in?

Looking for info about having session cookies captured when connected to unencrypted wifi.
What can be done with them, etc?
Please give info on the question and avoid responses like "use vpn" or "don't connect to unencrypted wifi".
Thanks.
Update:  Edited for better scope definition.
Update2: For future searchers, I found these very interesting articles.  They have good info on the subject.
http://blogs.computerworld.com/17338/some_thoughts_on_blacksheep_and_firesheep
http://www.pcworld.com/businesscenter/article/210028/secure_your_pc_and_website_from_firesheep_session_hijacking.html

A: 1) Unencrypted wifi typically means an "open" connection such as what is used in Mcdonalds and many locations. When Wifi is open, typically, it is possible for everyone to see what everyone else does. When you login to websites, the website remembers you typically by saving a cookie on your machine.
So, capturing the session cookie basically means stealing the cookie and putting it in to an active session elsewhere to trick the server in to thinking that you are the person who logged in.
2) Ins and outs? :S - well, I think I covered it in the first part - Unsecure wifi is convenient, but by its nature, it is unsecure.
You say filter out answers about use VPN, but that is honestly the solution - an encrypted tunnel to a trusted network. Many wifi hotspots fully support VPN clients and even give you configuation files for free (example - BT Openzone VPN client for the UK).
WPA2 based networks do a better job at isolating connections from each other, but it still has it's problems and is hackable by someone who knows what they are doing.
The only truly (IMHO) secure option is certificate based wifi networks, but other than in large enterprises with the infrastructure to support it, you just don't see it every day.

A: To answer your second question, a solution can be a proxy server that uses SSL.
Another solution is a Firefox plugin called HTTPS Everywhere that attempts to force SSL connections.
If you're not looking to change traffic, you could try using Blacksheep. It's a plugin that detects HTTP session cookie capturing, but doesn't prevent it.

A: Rent-a-VPN.  Seriously.  Your profile doesn't say where you are, but in the US there are a few subscription VPN services that will do exactly what you need without your having to deploy your own server.  PublicVPN is one I'm familiar with and a happy customer of.  $7/month, month-at-a-time, and no requirement to renew.

A: Another option would be to use the good-ol' SOCKS + ssh trick. (Hopefully nobody will spam that page again like it was when I found it from google -- there was some wierd div obscuring the actual content, but I fixed it by getting an account on that wiki, appending ?action=history to the URL, going to the previous revision, clicking "edit", and saving that old version as a new version.)


text:
Q: Generic way to sort a linked list with considering 3 parameters in C i have simple linked list with this struct:
typedef struct exam {
    char name[100];
    int credits;
    int grade;
    struct exam* next;
} Exam;

I want to sort it in lexicographical way considering: The name sorted in alphabetic way, the credits and the grade sorted in a crescent way
Both credits and grade are positive and can assume any dsired number.
How would you do that?
Thank you!

A: You need to compare each field in priority order and assign an ordering based on that.  For example:
int cmp_examp(Exam *e1, Exam *e2)
{
    if (strcmp(e1->name, e2->name) < 0) {
        return -1;
    } else if (strcmp(e1->name, e2->name) > 0) {
        return 1;
    } else if (e1->credits < e2->credits) {
        return -1;
    } else if (e1->credits > e2->credits) {
        return 1;
    } else if (e1->grade < e2->grade) {
        return -1;
    } else if (e1->grade > e2->grade) {
        return 1;
    } else {
        return 0;
    }
}

This orders exams first by name, then by credits, then by grade.