text:
Q: How to create Toggle button with Ajax Helper on MVC I am adding this small functionality to favourite items on a MVC website and having some difficulties developing it on the UI side. I already have changed the processing and database side of the change.
It works as it is but I need to refresh the page to see the button changes to 'Add favourite' to 'Delete favourite' sort of icons.
My ugly code from the View goes here.
@{
    if(ViewBag.IsFavourited == true)
    {

    }
    else
    {

    }
}

    @Ajax.ActionLink("Unfavourite", "Delete", "Favourite", new { id = Model.BlogPostId },
            new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "deletefavourite", LoadingElementId = "addfavourite" }, new { @class = "deletefavourite" })

    @Ajax.ActionLink("Add to favourites", "Add", "Favourite", new { id = Model.BlogPostId },
            new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "addfavourite", LoadingElementId = "deletefavourite" }, new { @class = "addfavourite" })

Code from Controller if you may need to see this as well
public ActionResult Details(int id)
    {
        BlogPostViewModel blogpost = waclient.GetBlogPostById(id);

        Favourite favourite = blogpost.Favourites.SingleOrDefault(u => u.BlogPostBlogPostId == blogpost.BlogPostId && u.UserId == User.Identity.Name);

        if (favourite != null)
        {
            ViewBag.IsFavourited = true;
        }
        else
        {
            ViewBag.IsFavourited = false;
        }

        if (blogpost == null)
        {
            return HttpNotFound();
        }
        return View(blogpost);
    }

CSS to make the Links as Icons


text:
Q: how to append 4-5 spaces in jquery?
i am trying to append 4-5 apces by the below code but it's not
  working. new to Jquery,JS pls help.

$("#<%= lbl100.ClientID %>").text("Your search request is too broad and the first 100 results are displayed.Please refine your search if your result does not show.").append("            ");

Note:- I have also used &nbsp and adding space in the end(not worked) but they are printing as it is and space not coming

A: Use   with html()and make sure that id:- <%= lbl100.ClientID %> is correct and exists.
Example:-

$("#abc").html("Your search request is too broad and the first 100 results are displayed.Please refine your search if your result does not show.      ").append("     ");

Note:- if you try to select the text then you will see that spaces are also selected.
Another way to do it:-

$("#abc").html("Your search request is too broad and the first 100 results are displayed.Please refine your search if your result does not show.          see the space");

Note:- Make sure that jQuery library added before your script code otherwise it will not work and you will get $ is undefined error in your browser console.

A: That's how HTML works: white-space is collapsed into a single space. If you need hard-coded duplicate spaces you need to insert a literal U+00A0 NO-BREAK SPACE character. There're several ways to do it:

*

*Type it as-is (you may also use the clipboard)

*Insert a JavaScript entity

*Insert an HTML entity

Snippet illustrates #2 and #3 (the editor would convert the character to regular space):

$("div:nth-of-type(1)").text("One\u00A0\u00A0\u00A0\u00A0Two");
$("div:nth-of-type(2)").html("One    Two");

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to combine two array into a list which have a inner-list? I had two list:
a=[0,0,0,1,1,1,1,2,2]
b=[2,5,12,2,3,8,9,4,6]

And I wanted to get:
c=[[0,2,5,12],[1,2,3,8,9],[2,4,6]]

A and b correlated to each other, a[i] related to b[i], when the value in a change like 0 to 1, 12 end in the first inner-list of c.
I tried it with if else statement but it failed
How to get c in python?

A: This code produces c in a good enough way (provided a and b are always adjusted in the same way as in the example):
a=[0,0,0,1,1,1,1,2,2]
b=[2,5,12,2,3,8,9,4,6]

c = []

i = 0

while i < len(a):
  d = a.count(a[i])
  c.append([a[i]] + b[i:i + d])
  i += d

print(c) # ==> [[0, 2, 5, 12], [1, 2, 3, 8, 9], [2, 4, 6]]

A: We can zip the lists, group by first value from a, and make lists with the second:
from itertools import groupby
from operator import itemgetter

a=[0,0,0,1,1,1,1,2,2]
b=[2,5,12,2,3,8,9,4,6]

[list(map(itemgetter(1), group)) for _, group in groupby(zip(a, b), key=itemgetter(0))]

#[[2, 5, 12], [2, 3, 8, 9], [4, 6]]

A: Similar to @Thierry Lathuille's answer, but does actually prepend the keys to the sub lists as requested by OP:
import itertools as it

ib = iter(b)
[[k, *(next(ib) for _ in gr)] for k, gr in it.groupby(a)]
# [[0, 2, 5, 12], [1, 2, 3, 8, 9], [2, 4, 6]]

A: Here's my simple solution. Notice that you are splitting the list by by the counts of elemets in the list a. deque is used for popping elements in O(1) time from the left.
import itertools
from collections import Counter, deque

a = [0,0,0,1,1,1,1,2,2]
b = deque([2,5,12,2,3,8,9,4,6])
c = Counter(a)

new_list=[]
for x in c:
    new_list.append([x]+[b.popleft() for i in range(a[x])])


text:
Q: youtube-dl problems, can't download private videos I want to download all my private videos, but I when try it I get errors. This is the command line arguments that I'm using:
youtube-dl -u "Username" -p "Password" https://youtube.com/watch?v=58e_io9sIjE

And here is the output:
[youtube] Downloading login page
[youtube] Logging in
[youtube] 58e_io9sIjE: Downloading webpage
[youtube] 58e_io9sIjE: Extracting video information
[youtube] 58e_io9sIjE: Downloading DASH manifest
Traceback (most recent call last):
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 162, in _run_module_as_main
"__main__", fname, loader, pkg_name)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 72, in _run_code
exec code in run_globals
File "/usr/local/bin/youtube-dl/__main__.py", line 19, in <module>
File "/usr/local/bin/youtube-dl/youtube_dl/__init__.py", line 380, in main
File "/usr/local/bin/youtube-dl/youtube_dl/__init__.py", line 370, in _real_main
File "/usr/local/bin/youtube-dl/youtube_dl/YoutubeDL.py", line 1346, in download
File "/usr/local/bin/youtube-dl/youtube_dl/YoutubeDL.py", line 624, in extract_info
File "/usr/local/bin/youtube-dl/youtube_dl/YoutubeDL.py", line 670, in process_ie_result
File "/usr/local/bin/youtube-dl/youtube_dl/YoutubeDL.py", line 1016, in process_video_result
File "/usr/local/bin/youtube-dl/youtube_dl/YoutubeDL.py", line 910, in _calc_headers
File "/usr/local/bin/youtube-dl/youtube_dl/YoutubeDL.py", line 936, in _calc_cookies
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/cookielib.py", line 1324, in add_cookie_header
cookies = self._cookies_for_request(request)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/cookielib.py", line 1250, in _cookies_for_request
cookies.extend(self._cookies_for_domain(domain, request))
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/cookielib.py", line 1239, in _cookies_for_domain
if not self._policy.return_ok(cookie, request):
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/cookielib.py", line 1071, in return_ok
if not fn(cookie, request):
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/cookielib.py", line 1097, in return_ok_secure
if cookie.secure and request.get_type() != "https":
AttributeError: '_PseudoRequest' object has no attribute 'get_type'

Any idea how to fix this?

A: This has to do with some error in the newest update ( or other newer ). I used 2014.09.29.2 and it worked correctly.

A: Try using youtube-dl --no-part.


text:
Q: R xts and data.table and IDate This is an extension of this question R xts and data.table.
I see as.xts.data.table is a new addition to the data.table package.
When I set dates with IDate (integer dates), I then get errors when looking at the table after an xts conversion with this error message:

Error in index.xts(x[1, ]) :    unsupported 'indexClass' indexing
  type: IDate

CODE SNIPPET
library(data.table)
library(xts)

# I am setting dates as IDate here in example, but in my code
#   I get a subset from elsewhere
dt <- data.table(date = c(as.IDate("2014-12-31"),
                          as.IDate("2015-12-31"),
                          as.IDate("2016-12-31")),
                 nav = c(100,101,99),
                 key = "date")

str(dt)
# Classes 'data.table' and 'data.frame':    3 obs. of  2 variables:
#   $ date: IDate, format: "2014-12-31" "2015-12-31" ...
# $ nav : num  100 101 99
# - attr(*, "sorted")= chr "date"
# - attr(*, ".internal.selfref")=<externalptr>

#convert to xts for PerformanceAnalytics (IDate not supported)
dt.xts <- as.xts.data.table(dt) # seems to work okay but...

str(dt.xts) # gives indexing type error above

I understand IDate is still developing out - "Still experimental!". What is the best way to get rid of the IDate type to use xts in the interim? [I tried forcing the type to no avail - as.xts(as.Date(dt$date)) ]
Can a future as.xts.data.table fix the IDates?
R3.2.2. versions: xts: 0.9-7 zoo: 1/7-12 data.table: 1.9.6

A: Update on 2016-04-13:
This has just been fixed in recent development version of data.table. You don't need to handle conversion of IDate any more. Code from the question will work just fine.
Below outdated answer, useful for those on data.table 1.9.6 or lower.

You need to change your IDate field to Date before converting to xts. IDate and ITime types were not considered when as.xts method was developed.
Patch to support that can be made, there is already one bugfix related to xts waiting to be merged.
Solution to your problem:

library(data.table)
library(xts)
dt <- data.table(date = c(as.IDate("2014-12-31"),
                          as.IDate("2015-12-31"),
                          as.IDate("2016-12-31")),
                 nav = c(100,101,99),
                 key = "date")
dt[, date := as.Date(as.integer(date))]
dt.xts <- as.xts.data.table(dt)


text:
Q: How to set a checkbox to operate with anyc storage in react native I am putting together a check box that will push data to async storage in react native but am having trouble getting the data to stick. I've set up the function presumably to push data to storage when the box is checked and then when it is unchecked. Below is the code, it seems unchecking the box won't stick. When I open the app again the box is still checked, what might I be doing wrong here? Assume that as of right now the local item stored is true and I want to make it false when I uncheck. To confirm nothing is changing I have added a button to call data.
    const STORAGE_KEY = '@save_enableauto'
        state={
            enableAuto:false
        }

      _storeData = async enableAuto => {
            let x = enableAuto;
            console.log('setting auto messages to: ', !x);
            //send check box to state
            this.setState({ enableAuto: !x });

            try {

              if(x) {
                await AsyncStorage.setItem(STORAGE_KEY, 'true')
                alert('Data successfully saved!')
              } else {
                await AsyncStorage.setItem(STORAGE_KEY, 'false')
              }

            } catch (e) {
                console.log(e)
              alert('Failed to save name.')
            }
          }

        _retrieveData = async () => {
            try {
              const enableAuto = await AsyncStorage.getItem(STORAGE_KEY);
              if (enableAuto !== null) {
                // We have data!!
                console.log('receiving from local storage: ',enableAuto);
                this.setState({ enableAuto:eval(enableAuto) });
              }
            } catch (error) {
                alert('failed to load previous settings.')
              // Error retrieving data
            }
        };

        componentDidMount() {
            this._retrieveData()
          }

    ....

<Button title={'call Data'} onPress={() => this._retrieveData()}/>
    <CheckBox
                                    value={this.state.enableAuto}
                                    onValueChange={() => this._storeData(this.state.enableAuto)}
                                />

A: update _storeData call to:
<CheckBox value={this.state.enableAuto}
               onValueChange={() => this._storeData(!this.state.enableAuto)}
     />

and your function body to :
_storeData = async enableAuto => {
        let x = enableAuto;
        console.log('setting auto messages to: ', x);
        //send check box to state
        this.setState({ enableAuto: x });
        ...
    }


text:
Q: c# check in which TabPage is TextBox I don't even know who to explain this using my English :) but I'll try...
I have TabControl1 with 3 TabPages (for ex. page1, page2, page3)
I did foreach loop for check what textboxs are enabled:
foreach (TabPage tp in tabControl1.TabPages)
       {
           foreach (Control textboxy in tp.Controls)
           {
               if (textboxy is TextBox)
               {

                   if (textboxy.Enabled)
                   {

                       if (!string.IsNullOrWhiteSpace(textboxy.Text))
                       { ...

Now, I need to know in which TabPage is my enabled textbox to send report:
                           // ------ report ---------//

                           string userID = LoginForm.UserID;
                           string name;
                           string computerName = textboxy.Name;
                           string computer = computerName;

                       }

                          string whichTabPage = ...? ;  <- HERE

                          (there is connectionstring)

                    ...}
               ..}

Now, i must know in what TabPage is enabled textbox and store it in variable for ex.:
            string whichTabPage = ?;

Report have to include: TabPage Name, Enabled TextBox Name and text in TextBox.

A: Something ike this...
string whichTabPage=String.Empty;
foreach (TabPage tp in tabControl1.TabPages)
  if (textboxy.Enabled)
  {
    whichTabPage = tp.Name;
  }
next

You could also use tp.Text instead of tp.Name if preferred


text:
Q: 3D sphere vs sphere collision resolve problem I have been watching OneLoneCoder video about circle collision resolve
 and use the code from git.
But the code is for 2D case, i.e. circles, and I need a solution for spheres. So I tried to add Z-component to equations but getting failures.
So I am testing the next way: I create two spheres, one above other. Lower is situated a heavy sphere, upper a tiny. The higher sphere is falling. In reality tiny should bounce up, but it just stuck, and they are falling as a single body for a while, but then the higher sphere is bouncing up. Also the sphere per each jump gets higher(see gif):

Here is the code:
/*
vertex - VERTEX **vertex=new VERTEX*[100];
vc - vertex count (how many vertices are currently created)
*/

void Update()
{
auto DoCirclesOverlap = [](float x1, float y1, float z1, float r1, float x2, float y2, float z2, float r2)
 {
  return ((x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2) + (z1 - z2)*(z1 - z2)) <= (r1 + r2)*(r1 + r2);
 };
 vector<pair<VERTEX*, VERTEX*>> vecCollidingPairs;
 // Update vertex[i] Positions
 for (int i = 0;i < vc;i++)
 {
  // Update vertex[i] physics

  vertex[i]->x += vertex[i]->vx * TIME_QUANT_CONSTANT;
  vertex[i]->y += vertex[i]->vy * TIME_QUANT_CONSTANT;
  vertex[i]->z += vertex[i]->vz * TIME_QUANT_CONSTANT;
 }
 // Static collisions, i.e. overlap

 for (int i(0);i < vc;i++)
 {

  for(int j(0);j < vc;j++)
  {
   if (vertex[i]->index != vertex[j]->index)
   {
    if (DoCirclesOverlap(vertex[i]->x, vertex[i]->y, vertex[i]->z, vertex[i]->size, vertex[j]->x, vertex[j]->y, vertex[j]->z, vertex[j]->size))
    {
     // Collision has occured
     vecCollidingPairs.push_back({ vertex[i], vertex[j] });

      // Distance between vertex[i] centers
      float fDistance = sqrtf((vertex[i]->x - vertex[j]->x)*(vertex[i]->x - vertex[j]->x) + (vertex[i]->y - vertex[j]->y)*(vertex[i]->y - vertex[j]->y) + (vertex[i]->y - vertex[j]->y)*(vertex[i]->y - vertex[j]->y));
      // Calculate displacement required
      float fOverlap = 0.5f * (fDistance - vertex[i]->size - vertex[j]->size);
      // Displace Current vertex[i] away from collision

       vertex[i]->x -= fOverlap * (vertex[i]->x - vertex[j]->x) / fDistance;
       vertex[i]->y -= fOverlap * (vertex[i]->y - vertex[j]->y) / fDistance;
       vertex[i]->z -= fOverlap * (vertex[i]->z - vertex[j]->z) / fDistance;
       // Displace vertex[j] vertex[i] away from collision
       vertex[j]->x += fOverlap * (vertex[i]->x - vertex[j]->x) / fDistance;
       vertex[j]->y += fOverlap * (vertex[i]->y - vertex[j]->y) / fDistance;
       vertex[j]->z += fOverlap * (vertex[i]->z - vertex[j]->z) / fDistance;

    }
   }
  }
 }
 // Now work out dynamic collisions
 for (auto c : vecCollidingPairs)
 {
  VERTEX *b1 = c.first;
  VERTEX *b2 = c.second;
  // Distance between vertex[i]s
  float fDistance = sqrtf((b1->x - b2->x)*(b1->x - b2->x) + (b1->y - b2->y)*(b1->y - b2->y) + (b1->z - b2->z)*(b1->z - b2->z));
  // Normal
  float nx = (b2->x - b1->x) / fDistance;
  float ny = (b2->y - b1->y) / fDistance;
  float nz = (b2->z - b1->z) / fDistance;
  // Tangent
  float tx = -ny;
  float ty = nx;
  float tz = nz;
  // Dot Product Tangent
  float dpTan1 = b1->vx * tx + b1->vy * ty + b1->vz * tz;
  float dpTan2 = b2->vx * tx + b2->vy * ty + b2->vz * tz;
  // Dot Product Normal
  float dpNorm1 = b1->vx * nx + b1->vy * ny + b1->vz * nz;
  float dpNorm2 = b2->vx * nx + b2->vy * ny + b2->vz * nz;
  // Conservation of momentum in 1D
  float m1 = (dpNorm1 * (b1->mass - b2->mass) + 2.0f * b2->mass * dpNorm2) / (b1->mass + b2->mass);
  float m2 = (dpNorm2 * (b2->mass - b1->mass) + 2.0f * b1->mass * dpNorm1) / (b1->mass + b2->mass);
  // Update ball velocities
  b1->vx = tx * dpTan1 + nx * m1;
  b1->vy = ty * dpTan1 + ny * m1;
  b1->vz = tz * dpTan1 + nz * m1;
  b2->vx = tx * dpTan2 + nx * m2;
  b2->vy = ty * dpTan2 + ny * m2;
  b2->vz = tz * dpTan2 + nz * m2;
 }
 }

What is the problem?

A: Thanks for @Tyyppi_77 from Stack GameDev, where I posted the same question, that pointed that the issue was on line
float fDistance = sqrtf((vertex[i]->x - vertex[j]->x)*(vertex[i]->x - vertex[j]->x) + (vertex[i]->y - vertex[j]->y)*(vertex[i]->y - vertex[j]->y) + (vertex[i]->y - vertex[j]->y)*(vertex[i]->y - vertex[j]->y));

And the correct one is
float fDistance = sqrtf((vertex[i]->x - vertex[j]->x)*(vertex[i]->x - vertex[j]->x) + (vertex[i]->y - vertex[j]->y)*(vertex[i]->y - vertex[j]->y) + (vertex[i]->z - vertex[j]->z)*(vertex[i]->z - vertex[j]->z));

It just solved almost all of issues. The only terrible thing is, because of static collision, the lower and much more heavier sphere is a little bit shifts down while it is hit by the sphere above. Do You know how it can be solved?


text:
Q: Animated view transitions. How to defer removing or inserting element? I try to make some animated transitions between connecting different outlets. I know there are methods like willInsertElement , didInsertElement or willDestroyElement on View class which you can override, but you can not defer appending or especially removing an element. I was trying to override other methods but view class is to complicated to understand how it works. I came up with some idea:
jsfiddle example
    AnimationHelper = Ember.Object.extend({
        isPreviousViewFadedOut:false,
        nextViewToFadeIn:null,
        triggerManually: true,
        setNextViewToFadeIn:function (view) {
            if (this.nextViewToFadeIn) {
                if (this.hasObserverFor('isPreviousViewFadedOut')) {
                    this.removeObserver('isPreviousViewFadedOut', this.nextViewToFadeIn, 'fadeInCallback');
                }
            }
            this.nextViewToFadeIn = view;
            this.addObserver('isPreviousViewFadedOut', this.nextViewToFadeIn, 'fadeInCallback');
        }
    });

    AnimatedView = Ember.View.extend({
        didInsertElement:function () {
            this.$().hide();

            if (AnimatedView.aHelper.get('triggerManually')) {
                AnimatedView.aHelper.set('isPreviousViewFadedOut', true);
                this.fadeInCallback();

                //next time we don't want call fadeInCallback manually
                AnimatedView.aHelper.set('triggerManually', false);
            } else {
                AnimatedView.aHelper.setNextViewToFadeIn(this);
            }
        },

        fadeInCallback:function () {
            if (AnimatedView.aHelper.get('isPreviousViewFadedOut')) {
                this.$().fadeIn(1000);
            }
        },

        willDestroyElement:function () {
            AnimatedView.aHelper.set('isPreviousViewFadedOut', false);
            var clone = this.$().clone();
            this.$().replaceWith(clone);

            var that = this;
            clone.fadeOut(1000, function () {
                $(this).remove();
                if (AnimatedView.aHelper.nextViewToFadeIn == that) {
                    AnimatedView.aHelper.removeObserver('isPreviousViewFadedOut',
                        AnimatedView.aHelper.nextViewToFadeIn, 'fadeInCallback');
                } else {
                    AnimatedView.aHelper.set('isPreviousViewFadedOut', true);
                }
            });
        }
    })

    AnimatedView.reopenClass({
        aHelper:new AnimationHelper()
    })

It seems to work fine, but this is probably very bad design. Is there any better way to achieve similar effect? or maybe I'm completely wrong and should look at problem from very different perspective? for example do animations inside View which wraps another View etc.?

A: There was a pull request a little while back that was merged into master that added some extra hooks to Em.ContainerView that would have allowed an async transitionary period between two views in an outlet, but that change was reverted soon after due to it causing errors and not really being a well-discussed approach for allowing for transitions between two outlet views.
The Ember core team's lately been focusing on making it really easy to tie your application's views to the Router by way of one-view-at-a-time outlets, and such a system doesn't really make it easy to do what you're trying to do. Almost certainly, if those transitions are valuable to you, you'll want to not use outlets at all and instead manually create/append/animate the views yourself as you enter and exit states. Perhaps Ember core will take another look at this problem at some point, but I wouldn't expect it before the upcoming v 1.0 release.
I do believe that the recently published Yapp app built in Ember took the approach of having a state for every single transition between every "landing" state, and didn't make use of outlets at all. The app's built by some smart people and is doing quite well, so it definitely seems like advice to stand by.

A: Also these might help a lot:
http://discuss.emberjs.com/t/animation-support-in-ember-1-1/1977
https://github.com/billysbilling/ember-animated-outlet
If you could select an answer that'd be really helpful to reducing the number of unanswered Stack Overflow questions on Ember.


text:
Q: How to Join a Collection to a Document using Mongocxx I have a single document (or collection, whichever would work best to get to the solution) named "main":
{
    "field1":"value1",
    "objects":[ {"key":1}, {"key":2} ]
}

I have another collection named "foreign" with the following three documents:
//document 1
{
    "foreignKey":1,
    "name": "Mike"
}
//document 2     {
    "foreignKey":2,
    "name": "Michael"
}
//document 3
{
    "foreignKey":3,
    "name": "Mick"
}

I want the joined results to be:
//results
{
    "field1":"value1",
    "objects":[
        {
            "foreignKey":1,
            "name": "Mike"
        },
        {
            "foreignKey":2,
            "name": "Michael"
        }
    ]
}

I've only found examples in MongoDB that almost accomplishes this but it's example only has an array of values; but I have an array of objects.
I don't know how to translate this to Mongo-cxx.
I copied the following example from the MongoDB site for convenience
------------------------------------------------
//Consider a collection orders with the following //document:
({ "_id" : 1, "item" : "MON1003", "price" : 350, "quantity" : 2, "specs" :
[ "27 inch", "Retina display", "1920x1080" ], "type" : "Monitor" }

//Another collection inventory contains the following //documents:
{ "_id" : 1, "sku" : "MON1003", "type" : "Monitor", "instock" : 120,
"size" : "27 inch", "resolution" : "1920x1080" }
{ "_id" : 2, "sku" : "MON1012", "type" : "Monitor", "instock" : 85,
"size" : "23 inch", "resolution" : "1280x800" }
{ "_id" : 3, "sku" : "MON1031", "type" : "Monitor", "instock" : 60,
"size" : "23 inch", "display_type" : "LED" }
(
//The following aggregation operation performs a join //on documents in the orders collection which match a //particular element of the specs array to the size //field in the inventory collection.
db.orders.aggregate([
   //stage
   {
      $unwind: "$specs"
   },
   //stage
   {
      $lookup:
         {
            from: "inventory",
            localField: "specs",
            foreignField: "size",
            as: "inventory_docs"
        }
   },
   //stage
   {
      $match: { "inventory_docs": { $ne: [] } }
   }
])

//The operation returns the following document:
{
   "_id" : 1,
   "item" : "MON1003",
   "price" : 350,
   "quantity" : 2,
   "specs" : "27 inch",
   "type" : "Monitor",
   "inventory_docs" : [
      {
         "_id" : 1,
         "sku" : "MON1003",
         "type" : "Monitor",
         "instock" : 120,
         "size" : "27 inch",
         "resolution" : "1920x1080"
      }
   ]
}

A: Using the example you linked from MongoDB's $lookup with an array, and based on aggregation_examples.cpp and test/collection.cpp, the following code implements an aggregation operation with $unwind, $lookup and $match that returns the same document as in the example:
#include <iostream>

#include <bsoncxx/json.hpp>

#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/uri.hpp>

using bsoncxx::builder::basic::kvp;
using bsoncxx::builder::basic::make_document;
using bsoncxx::builder::basic::array;

int main(int, char**)
{
    std::cout << "Start program" << std::endl;

    mongocxx::instance instance{};
    mongocxx::client client{ mongocxx::uri{} };

    mongocxx::database db = client["stack"];
    mongocxx::collection colInventory = db["inventory"];

    // Pipeline stages: $unwind, $lookup and $match
    mongocxx::pipeline pipe{};
    pipe.unwind("$specs");
    pipe.lookup(
        make_document(
            kvp("from",         colInventory.name()),
            kvp("localField",   "specs"),
            kvp("foreignField", "size"),
            kvp("as",           "inventory_docs")
        )
    );
    pipe.match(
        make_document(
            kvp("inventory_docs", make_document(kvp("$ne", array{})))
        )
    );

    auto cursor = db["orders"].aggregate(pipe, mongocxx::options::aggregate{});

    for (auto doc : cursor) {
        std::cout << bsoncxx::to_json(doc) << std::endl;
    }

    std::cout << "End program" << std::endl;
}

Output:
Start program
{ "_id" : 1.0, "item" : "MON1003", "price" : 350.0, "quantity" : 2.0, "specs" : "27 inch", "type" : "Monitor", "inventory_docs" : [ { "_id" : 1.0, "sku" : "MON1003", "type" : "Monitor", "instock" : 120.0, "size" : "27 inch", "resolution" : "1920x1080" } ] }
End program

Pretty print:
{
    "_id": 1.0,
    "item": "MON1003",
    "price": 350.0,
    "quantity": 2.0,
    "specs": "27 inch",
    "type": "Monitor",
    "inventory_docs": [
        {
            "_id": 1.0,
            "sku": "MON1003",
            "type": "Monitor",
            "instock": 120.0,
            "size": "27 inch",
            "resolution": "1920x1080"
        }
    ]
}


text:
Q: How to restrict special characters in input field in React js by using setValue method of react form hook there is one input field inside **useFieldArray **getting data from **API **in editable mode so i want to restrict special characters and numbers in that editable input field. I am using **setValue **function on **OnChange **but it's not working.
I tried to replace the numbers and special characters and fetch the value on console the value is coming correct but in the frontend, value is not updated by **setValue **function.
So, I want to restrict special characters from that input field, and data is coming from an **API **
`
const handleWarningName = (name, value, index) => {
    if (name === `warning.${index}.name`)
    {
      console.log("-----",value,"index" ,index)
      setValue(`warning.${index}.name`, value);
    }
  };

`
this is the function of handling the value
your text


text:
Q: nginx multisite reverproxy using path variable I have multisite settings on single instance, I mean using site id, I'm switching content, logo theme colors etc and I have different domain names for each site.
Paths
http://localhost:3000/{{site_id}}/
http://localhost:3000/{{site_id}}/about-us/
http://localhost:3000/{{site_id}}/product/1232/slug

etc...

For Example
http://localhost:3000/1 => site-a.local
http://localhost:3000/2 => site-b.local
http://localhost:3000/3 => site-c.local

I'm using nginx, reverse proxy from port 80 to 3000. How can I forward the site id in the nginx
server {

   listen 80;
   listen [::]:80;

   server_name site-a.local;

   location ~ /(.*) {

        proxy_pass http://localhost:3000/1;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;

    }

}

server {

   listen 80;
   listen [::]:80;

   server_name site-b.local;

   location ~ /(.*) {

        proxy_pass http://localhost:3000/2;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;

    }

}

The above idea is not working for some reason can someone help me?

A: upstream node {
  server 127.0.0.1:3000;
  keepalive 32;
}

server {
  server_name site-a.local;
  listen 80;
  location / {
    proxy_pass http://node/1/;
    proxy_set_header Host $host;
  }
}

server {
  server_name site-b.local;
  listen 80;
  location / {
    proxy_pass http://node/2/;
    proxy_set_header Host $host;

  }
}

server {
  listen 3000;
  location /1/ { return 200 "Hello from 1 with URL $uri"; }
  location /2/ { return 200 "Hello from 2 with URL $uri"; }
}

With this you are proxying to your node backend, listening on port 3000.
$:/etc/nginx/conf.d# curl -H "Host: site-a.local" 127.1/test/location/
Hello from a with URL /a/test/location/

$:/etc/nginx/conf.d# curl -H "Host: site-b.local" 127.1/test/location/
Hello from b with URL /b/test/location/


text:
Q: Tastypie Nested Resources - cached_obj_get() takes exactly 2 arguments (1 given) I'm trying to use the example here: http://django-tastypie.readthedocs.org/en/latest/cookbook.html#nested-resources
for some reason i get:

cached_obj_get() takes exactly 2 arguments (1 given)

even though i clearly call it with 2 arguments (exactly like in the aforementioned example.
this is my code:
def prepend_urls(self):
    return [
        url(r"^(?P<resource_name>%s)/(?P<pk>\w[\w/-]*)/feed%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('get_feed'), name="api_get_feed"),
]

def get_feed(self, request, **kwargs):
    try:
        obj = self.cached_obj_get(request=request, **self.remove_api_resource_names(kwargs))
    except ObjectDoesNotExist:
        return HttpGone()
    except MultipleObjectsReturned:
        return HttpMultipleChoices("More than one resource is found at this URI.")

    feed_resource = FeedItemResource()
    return feed_resource.get_list(request, p_id=obj.id)

A: Sorry for the confusion - there was an API change to improve authorization which changed the signature for cached_obj_get from:
def cached_obj_get(self, request=None, **kwargs):

to
def cached_obj_get(self, bundle, **kwargs):

This change is consistent going forward – and if you needed the request object, it's available as bundle.request – but obviously the documentation needs to be updated.
You can build a bundle object with:
basic_bundle = self.build_bundle(request=request)

then use it as an argument to cached_obj_get (see Resource.get_detail source code as an example):
obj = self.cached_obj_get(bundle=basic_bundle, **self.remove_api_resource_names(kwargs))

The other confusing aspect if you're not familiar with Python's object model is that methods always receive at least one argument because the first positional argument is always the object instance or self and keyword arguments aren't included in that count so "1 given" means that the method only received the self positional argument when it was expecting self and bundle.


text:
Q: iptables not logging to /var/log/messages on centos 7 I am trying to set up IP Tables on CentOS 7 which I've done in the past but for some reason I can't get it to log the dropped packets like I'd expect.
In the ip tables config I have the following
*filter
-A INPUT -i lo -j ACCEPT
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A OUTPUT -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited

# Log and drop packets that don't match the above rules
-N LOGGING
-A INPUT -j LOGGING
-A OUTPUT -j LOGGING
-A LOGGING -j LOG --log-prefix "IPTables-Dropped: " --log-level 6
-A LOGGING -j REJECT
-A INPUT -j REJECT
-A OUTPUT -j REJECT
COMMIT

As you can see I only have port 22 (SSH) open so I would expect if I try and do an HTTP request, because this isn't allowed in the firewall, it would block the request (which it does) but I should also see in /var/log/messages the log line IPTables-Dropped which I don't.
I've also tried updating /etc/rsyslog.conf and added kern.warn /var/log/messages but doesn't make any difference (I did restart rsyslog service).

A: Order of rules does matter.
This rule:
-A INPUT -j REJECT --reject-with icmp-host-prohibited

precedes this rule:
-A INPUT -j LOGGING

preventing it to ever be executed: no logging.
Same for other chains.
Just use iptables-save to output a "refreshed" version of your rules, and edit their order accordingly.
Also read this link about the (very rarely happening) problem of using REJECT without first DROP-ing INVALID states.


text:
Q: speedata Publisher - how to insert a full size image I use the speedata Publisher (the LuaTeX based database publishing software) and I'd like to insert a pdf file that covers the whole page. I have found the Image tag, but this gives me a margin at the top and the left and a blank page.
This is what I have now:
<Layout xmlns="urn:speedata.de:2009/publisher/en">

  <Record element="data">
    <PlaceObject>
      <Image width="210mm" file="mypdf.pdf"/>
    </PlaceObject>
  </Record>

</Layout>

(I cannot create a new tag speedatapublisher and there is none yet here)

A: You should specify the position of the image in absolute terms (0mm):
<Layout xmlns="urn:speedata.de:2009/publisher/en">

  <Record element="data">
    <PlaceObject column="0mm" row="0mm">
      <Image width="210mm" file="mypdf.pdf"/>
    </PlaceObject>
  </Record>

</Layout>

Hope this helps!


text:
Q: Daily update on PHP logic There is a case that if the employee that already worked for a year since the join_date, he will be given 12 leave_balance, but how to determine for the next year ? Because it can't be multiplied by difference in year. For example

*

*join_date 15 Jan 2015, today date is 15 Jan 2016, then update leave_balance = leave_balance + 12;

*but then, between 15 Jan 2016 - 15 Jan 2017 he use his vacation for 5 days, so his leave_balance will be 8,

*on 15 Jan 2017, he will receive another leave balance quota 12, so leave_balance must update 8 + 12 = 20.

what I have thought is only like this
if(join_date  = same date this year)
then update leave_balance
please help
table needed is very simple, status_employee,join_date and leave_balance
$q = "select * from employee";
$r = mysql-query($q);
while($result = mysql_fetch_array($r))
{
    $datetime1 = new DateTime($result['join_date']);
    $interval = $datetime1->diff(new DateTime());
    $year= $interval->y;

       if($year > 0 && status_employee = 'Permanent Staff')
       {
             $leave_balance = $result['leave_balance'] + (12 * $year);
       }
}

for ilustration
UPDATE

$q = "SELECT * FROM employee WHERE employee_type = 'Permanent' && DATEDIFF(.join_date , CURDATE()) >= 365";

$r = mysql_query($q);
while($res = mysql_fetch_array($r))
{
    $q = "SELECT * FROM holiday_transaction WHERE id_employee='".$res['id_employee']."'";
    $r = mysql_query($r);
    $res = mysql_fetch_array($r);
    $check = mysql_num_rows($r);

$id_employee = $res['id_employee'];
if($check > 0) //employee is on the transaction_table
{
    //check latest renewal date
    $q = "SELECT * FROM holiday_transaction WHERE id_employee = '$id_employee' && transaction_type='Renewal' && DATEDIFF(CURDATE() ,trn_date) >= 365";
    $r = mysql_query($q);
    $check = mysql_num_rows($r);

    if($check == 0) //0 means he qualify with conditions above that his latest renewal is already more than a year
    {
        $q = "INSERT INTO holiday_transaction(id_employee,holiday,transaction_type) VALUES('$id_employee','12','Renewal')";
        mysql_query($q)
    }
    else
    {
        //don't insert because it is not yet 365days since his latest renewal
    }

}
else //never been on the table and give 12 quota
{
    $q = "INSERT INTO holiday_transaction(id_employee,holiday,transaction_type) VALUES('$id_employee','12','Renewal')";
    mysql_query($q)
}

}

A: You do not need a cron job.  You can just run a stored procedure on mysql or just some php code when someone next logs on.  JUst do it before presenting them with a page.

A: The answer to your second question. If I was doing it I would have a transaction table.  This would ensure that even if the code ran twice it would not double things up.  It also gives you an exact trace in case of disputes by employees.  Like this:
table employee_holidays
employee_ref (index into employee table)
trn_date (the date that these holidays were added or taken)
holidays (integer)

Then

*

*You apply your annual holidays of 12 any time after the end of the year and use the year-end as the date.  If the entry is already there for that date then you don't add it.

*Every time an employee takes a holiday, you add a negative entry for that date.

*To find out how many holidays they have left, you sum them up.
If you really want a ready total then I would have a totals table (or use the employee_table.leave_balance).  BUT I would use a trigger in the transaction table to update this figure.
I think that once you have this together and can't get something working then you should ask a new question.


text:
Q: For loop to read data from excel sheet in selenium using python from openpyxl import load_workbook

def Email_ID(row_Num, cell_Num, sheet):
    wb = load_workbook('/Users/Umesh/Downloads/Test_Read.xlsx')
    sheet = wb.get_sheet_by_name(sheet)
    email = sheet.cell(row=row_Num, column=cell_Num).value

    if email is not None:
        return email
    else:
        return ''

Using the above code I am able to get a single emailid from the excel sheet and register it in the application, but I need to read all the email ids from the excel sheet one by one by using FOR loop.
can any one help.

A: I noticed there is not a main entry point to your python script so I incorporated a more abstract version of your code. Besides that I do not understand why you passed in a sheet to def Email_ID when you instantiated one(sheet = wb.get_sheet_by_name(sheet)) inside your function.
I am assuming you mean to get all emails from first column, if not a small change can be made to grab emails vertically.
Besides that, I have tested this code and it works on Mojave MacOS. This python script will get all values from first column dynamically:
from openpyxl import load_workbook

def main():
    curr_sheet = get_sheet()
    for i in range(1, curr_sheet.max_row + 1):
        print(email_id(i, 1, curr_sheet))

# get email from each row based on parameters passed
def email_id(row_Num, cell_Num, sheet):
    email = sheet.cell(row=row_Num, column=cell_Num).value

    if email is not None:
        return email
    else:
        return ''

# setup our sheet to be easily passed through various functions
def get_sheet():
    wb = load_workbook('/Users/sudoxx2/Downloads/test_sheet.xlsx')
    sheet = wb.active
    return sheet

# main entry point to our python script(universal entry point in most python scripts)
if __name__ == "__main__":
    main()

Please let me know if you have any questions.


text:
Q: Combine 3 single-dimensional arrays into one multi-dimensional array by key So I have 3 arrays. One which contains user's first names, the second one containing user's last names, and the third one containing their last names.
The arrays have one thing in common, the keys.... So user_first[0] belongs to user_last[0] and it also matches with email[0] and so on.
So I want a new array to look like:
Array
(
  [0] => Array
  (
    [first_name] => John
    [last_name] => Doe
    [email] => john.doe@domain.com
  )

  [1] => Array
  (
    [first_name] => Jane
    [last_name] => Doe
    [email] => jane.doe@domain.com
  )

)

Instead of the original, which would be this:
Array
(
  [0] => John
  [1] => Jane
)
Array
(
  [0] => Doe
  [1] => Doe
)
Array
(
  [0] => john.doe@domain.com
  [1] => jane.doe@domain.com
)

A: $combinedArray = array();

foreach($first_names as $key => $first_name)
{
  $combinedArray[$key] = array(
    "first_name" = $first_name,
    "last_name" = $last_names[$key],
    "email" = $emails[$key]
  );
}

A: Simply use array within array like
    $a = array();
    $a[] = array("first_name"=>"John","last_name" => "Doe", "email" => "john.doe@domain.com");
$a[] = array("first_name"=>"Jane","last_name" => "Doe", "email" => "jane.doe@domain.com");

which is exactly what you want i.e
array(2) {
  [0]=>
  array(3) {
    ["first_name"]=>
    string(4) "John"
    ["last_name"]=>
    string(3) "Doe"
    ["email"]=>
    string(19) "john.doe@domain.com"
  }
  [1]=>
  array(3) {
    ["first_name"]=>
    string(4) "Jane"
    ["last_name"]=>
    string(3) "Doe"
    ["email"]=>
    string(19) "jane.doe@domain.com"
  }
}

A: try with the below code
<?php
$arr1 = array(
              0 => "John",
              1 => "Jane");

$arr2 = array
(
  0 => "Doe",
  1 =>  "Doe"
);
$arr3 =array
(
  0 => "john.doe@domain.com",
  1 => "jane.doe@domain.com"
);
$new_arr=[];
foreach ($arr1 as $key => $value) {
    # code...
    //echo $arr2[$key]."<br>";

    $new_arr[$key]["first_name"]= $value;
    $new_arr[$key]["last_name"]= $arr2[$key];
    $new_arr[$key]["email"]= $arr3[$key];
}

echo "<pre>";
print_r($new_arr);

check demo here : demo


text:
Q: How to create a csv file with labels from a list of images i have multiple folders in a directory and in each of the folder are hundred of images(.jpg).
Now i try to create a csv file, which includes the name of the image, a comma and then the label of it.
So my folders are
dog
cat
mouse
elephant
and in these are images titled dog1.jpg, dog2.jpg, ... cat1.jpg, and so on.
I have already tried to list all the names of the pictures with the following code:
import os

path = '/content../'

files = []
for  r, d, f in os.walk(path):
    for file in f:
        if '.jpg' in file:
          print(file)

This prints me the list of my images.
My thoughts are that i create something like
import csv

# csv file name
with open('test.csv')
category []
if filename == 'dog' then append 0
if filename == 'cat' then append 1 ...

But I am getting nowhere.
At the end the csv file should look like:
dog1.jpg,0
dog2.jpg,0
cat1.jpg,1
mouse2.jpg,2
elepant.jpg,3

I hope you can help me, Thank you very much!

A: Here is my take on it
File with explanation:
https://hastebin.com/hopeneluhi.py
Please note I didnt test this. Let me know if there are any issues :)


text:
Q: SIP library for iOS with non-GPL license Are there any non-GPL SIP libraries/SDKs that'll let me implement SIP for iOS?

A: These are the ones I know about:
Proprietary:

*

*vaxvoip
Open source: GPL/LGPL

*

*sofia-sip

*linphone

*exosip

A: oSIP is LGPL and therefore can be used (as a library) in commercial and closed-source projects. It compiles easily for arm. It is the SIP library used by linphone for iPhone; however, linphone is GPL.

A: These days SIP over WebRTC is getting popularity. It uses SIP Signaling and WebRTC as Media which is provided by google.
Following options are also very good if you to avoid getting into SIP level complexities.
https://alqatech.com/services/webrtc-sdk-android/
https://alqatech.com/services/webrtc-sdk-ios/


text:
Q: Highcharts: overlapped columns in exported chart The live chart looks fine, however, when exported to PNG, JPEG or PDF, the columns overlap.
The code: http://jsfiddle.net/strawberry/1s27pjed/

exporting:{
                chartOptions:{
                    legend:{
                        enabled:true,
                        style: {fontFamily: "Arial"}
                    },

                }
            },

In addition, is there an option to change the font and size of the legend text in the export? I was able to change the title and axis fonts, but not the legend.

A: The legend.style option is Deprecated in new versions and maybe that's why it doesn't work. You can use legend.itemStyle instead:
legend: {
    enabled:true,
    itemStyle: {fontFamily: "Arial", fontSize: '8px'}
}

Here's the DEMO.


text:
Q: Using custom created components in tapestry I recently started learning about the Tapestry framework. I was following a book example about creating a custom component and using it in code. For some reason the text from the component is not showing (I only see the hello world text). Here is the .java and tml files:
public class Index
{
  public Index() {

  }

    public String getHello()
    {
        return "Hello world!";
    }
}

Index tml :
<html xmlns:t="http://tapestry.apache.org/schema/
tapestry_5_3.xsd">
<head>
<title>Tapestry 5 Book</title>
</head>
<body>
<t:MyComponent/>

<h1> ${hello} </h1>

</body>
</html>

MyComponent.java
public class MyComponent {

    public String getStuff()
    {
        return "Random stuff";
    }
}

MyComponent.tml
<span> ${stuff} </span>

I would also like to say that the .java files are in their corresponding packages (pages and components in main/java...) and .tml files are in their corresponding packages in resources. My question is, why is the component text not showing ?

A: Everything looks OK to me, so it's really just a case of absolutely verifying that the MyComponent.tml is in the right place, and visible on the classpath at runtime.  This could be an issue with IDE configuration, for example.
For component class org.example.MyComponent, the typical place is src/main/resources/org/example/MyComponent.tml, but you have to make sure your IDE is exporting files inside src/main/resources.


text:
Q: Twilio Conversation: Handling of old messages when a new conversation is created out of Closed Conversation In twilio conversation documentation, it says-
If new message comes into closed Conversation, a new Conversation will be auto-created with
the Participant who initiated the Conversation. At this point, there is no automatic addition
 of other Participants, so you should add them to the newly created Conversation.

https://www.twilio.com/docs/conversations/states-timers#closed-conversations
In this case what happens to the old messages, do they get copied to the new conversation. If not, what is the recommended way to do so?

A: Twilio developer evangelist here.
A new conversation will not get the messages from the old closed conversation. If you do want to add the messages to that conversation, then you'd need to fetch them from the API and create new messages using the REST API.


text:
Q: Ensure that all NEW instances of a class implements ALL fields or properties Lets say I have a class
class Car
{
    string color;
    bool fourDoor;
    int numberOfTires;
}

And I create a new instance
Car myCar = new Car();
myCar.color = "green";
myCar.fourDoor = true;

I haven't assigned anything to numberOfTires so how do I make it throw a compile warning/error?

A: That isn't something  supported by the  compiler as it is not required to assign something to all properties. You could write an analyzer for it, but in non-trivial cases it will quickly become "halting problem" complex.
Note that  if Car was a struct then that can be checked via a very specific syntax (only if you don't initialize the value first), but: that  is so nuanced that  it won't help you, and it wouldn't  be good advice (and that is before we discuss the issue of mutable structs).
In your case, your best bet would be to use the constructor  to declare what things you require. Then it becomes:
 Car myCar = new Car(color: "green", fourDoor: true, numberOfTires: 42);

My explicit usag of parameter names is purely for visibility; it would work just  as well as:
Car myCar = new Car("green", true, 42);

This would  map to something like:
class Car
{
    public string Color {get;}
    public bool FourDoor {get;}
    public int NumberOfTires {get;}
    public Car(string color, bool fourDoor, int numberOfTires)
    {
        Color = color;
        FourDoor = fourDoor;
        NumberOfTires = numberOfTires;
    }
}

A: For such case, you should use constructor with arguments. Take a look here: https://msdn.microsoft.com/en-us/library/k6sa6h87.aspx.

A: Jason gives a good option for your problem: https://stackoverflow.com/a/10720455/3836632
"I think that your configuration parameters should be readonly (and arguably private but accessible via a property). Then, set warnings to be marked as errors. Then, when you fail to initialize one of these variables, you'll get a compile-time error

The field CalculatorConfig.param1 is never assigned to, and will always have its default value.

Now you've caught the issue at compile time."

A: *

*List item

You can set the properties that need to initialised in the argument of the constructor. This way u can force the user to pass value during the object creation.
public class Car
    {
        public Car(string color, bool fourDoor, int numberOfTires)
        {
            this.Color = color;
            this.FourDoor = fourDoor;
            this.NumberOfTires = numberOfTires;
        }
    public string Color { get; set; }
    public bool FourDoor { get; set; }
    public int NumberOfTires { get; set; }
}


text:
Q: inputView and inputAccessoryView prior to 3.2? I'm trying to add support for 3.1.3, as it's the last version on the first generation iPods. I
was wondering how to simulate the inputView and inputAccessoryView for a UITextField prior to 3.2, as those have been added only in 3.2 afaik.

A: Take a look at this tutorial, might be helpful.
http://www.randomsequence.com/articles/adding-a-toolbar-with-next-previous-above-uitextfield-keyboard-iphone/
I have used this to create a toolbar with NEXT and PREVIOUS buttons and support iOS 3.1.3 as well.


text:
Q: How to define a hierarchal table using EF core In the application I am working on, we have a users table, TblUser. Users within this table may belong to a single, parent user. A parent user may have multiple child users.
This relationship is maintained within a table called TblUserMapping with two columns, ParentUserId and ChildUserId corresponding with the parent's and child's TblUser.Id value. TblUser.Id is an auto-incrementing value.
How can I define this within EF Core, and would it be possible to Insert a ChildUser into TblUser and use the auto-generated Id value to also create a TblUserMapping record?
Right now I have:
[Table("TblUser")]
public class TblUser
{
    public TblUser()
    {
        ChildUsers            = new List<TblUserMapping>();
    }

    public int Id { get; set; }
    public string UserName { get; set; }

    public virtual ICollection<TblUserMapping> ChildUsers { get; set; }
    public virtual TblUserMapping ParentUser { get; set; }
}

[Table("TblUserMapping")]
public class TblUserMapping
{
    public TblUserMapping()
    {
    }

    public int ChildUserId { get; set; }
    public int ParentUserId { get; set; }

    public virtual TblUser ChildUser { get; set; }
    public virtual TblUser ParentUser { get; set; }
}

public class TblUserMapping : IEntityTypeConfiguration<TblUser>
{
    public void Configure(EntityTypeBuilder<TblUser> entity)
    {
        entity.Property(e => e.Id).ValueGeneratedOnAdd();
        entity.Property(e => e.UserName)
            .IsRequired()
            .IsUnicode(false);
    }
}

public class TblUserMappingMapping : IEntityTypeConfiguration<Entities.TblUserMapping>
{
    public void Configure(EntityTypeBuilder<Entities.TblUserMapping> entity)
    {
        entity.HasKey(e => e.ChildUserId);
        entity.Property(e => e.ChildUserId)
            .IsRequired();
        entity.Property(e => e.ParentUserId)
            .IsRequired();

        entity.HasOne(e => e.ParentUser)
            .WithMany(e => e.ChildUsers)
            .HasForeignKey(e => e.ParentUserId);

        entity.HasOne(e => e.ChildUser)
            .WithOne(e => e.ParentUser)
            .HasForeignKey<TblUser>(e => e.Id);
    }
}

But this isn't working as I had hoped when I do:
var userInformation = await _context
    .Users
    .Include(entity => entity.ChildUsers)
    .ThenInclude(entity => entity.ChildUser)
    .Where(s => s.UserName == userName)
    .FirstOrDefaultAsync();

var ChildUser = new TblUser
{
    UserName = userModel.UserName,
    ParentUser = new TblUserMapping()
    {
        ParentUser = userInfo
    }
};

_context.Users.Add(ChildUser);
await _context.SaveChangesAsync();

A: You can attach navigation properties, and Entity Framework will populate the ids automatically when it creates them. The example you have given should work, you might need to show us how you are getting userInfo before we can see what's going on.
That being said, instead of keeping a separate mapping table, I would have each child user refer directly to their parent:
[Table("TblUser")]
public class TblUser
{
    public int Id { get; set; }
    public string UserName { get; set; }

    public int? ParentId { get; set; }
    public TblUser Parent { get; set; }

    // Lazy-loading is not enabled by default in EF Core, so you don't need the 'virtual' keyword
    // Also, if the initialization of a member does not depend on constructor arguments, I
    // prefer this syntax instead of doing it in the constructor
    public ICollection<TblUser> Children { get; set; } = new List<TblUser>();
}

A: You can use InverseProperty attribute in your model:
[Table("TblUser")]
public class TblUser
{
public TblUser()
{
    ChildUsers            = new List<TblUserMapping>();
}

public int Id { get; set; }
public string UserName { get; set; }

[InverseProperty("ChildUser")]
public virtual ICollection<TblUserMapping> ChildUsers { get; set; }

[InverseProperty("ParentUser")]
public virtual TblUserMapping ParentUser { get; set; }
}

And in other model:
[Table("TblUserMapping")]
public class TblUserMapping
{
public TblUserMapping()
{
}

public int ChildUserId { get; set; }
public int ParentUserId { get; set; }

[ForeignKey("ChildUserId")]
public virtual TblUser ChildUser { get; set; }

[ForeignKey("ParentUserId")]
public virtual TblUser ParentUser { get; set; }
 }

As you see I defined these relations with attributes that means no need to came in your configuration.


text:
Q: trying to run a cronjob and even the very simple one wont work i am trying to to run this:
* * * * * lynx http://www.domain.com/cron/updatetest.php
That should be simple but still it wont work.  now that's really weird because this should work. when i put the address in the browser(the real one) it works perfectly.
Any clue ?

A: Problems with cron are usually environment problems. In this case it might be, that lynx doesn't have a terminal to work with. Since you want to just request the page, try
* * * * * lynx -dump http://www.domain.com/cron/updatetest.php >/dev/null 2>&1

If you want to save the requested page instead, use something like
* * * * * lynx -dump http://www.domain.com/cron/updatetest.php >/path/to/file.txt

See also man lynx


text:
Q: React components in existing application I started adding React components to an existing website. I currently have a simple component that looks like this.
'use strict';

const element = React.createElement

class CourseForm extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      someObject: ''
    }
  }

  changeObject() {
    //this value will change on various events
    this.setState({ someObject: {key: value} })
  }

  render() {
    return (

        This is a react form!

    )
  }
}

const domContainer = document.querySelector('#react-course-form')
ReactDOM.render(element(CourseForm), domContainer)

An html element is used to show the component.

What I would like to do is include another componen, and send it data on events from this component.
render() {
    return (

    This is a react form!
    <button onClick={this.changeObject}>change</button>

)
}

So I basically want the child components to be aware of what someObject is because they will be displaying data from that object.

A: You can create another component and import in in your CourseForm component. Then you can just use it in your render method and send it the props as you do now in your example. You're using regular divs no though so it won't work.
example:
<AnotherComponent sendObject={this.state.someObject} />

When the state updates in your CourseForm component the child components will rerender automatically with the new data to it as props.
First create your new component:
class AnotherComponent extends Component {
  // Your code goes in here. You can access the object data you send
  // in by props by grabbing it from this.props.someObject
}

Then import it as a component in your CourseForm component:
import AnotherComponent from '.. your filepath here';

And use AnotherComponent in your render method in CourseForm:
<AnotherComponent sendObject={this.state.someObject} />


text:
Q: MFC: CToolTipCtrl causes ASSERT I have implemented tool tips seemingly successfully in an app which is MFC based and uses CPropertyPage.  However after adding a button to open a dialog box called IDC_USERMSG which contains a single CEdit control on one of the CPropety pages an Assert is thrown when the IDC_USERMSG dialog is dismissed.
_AFXWIN_INLINE CWnd* CWnd::GetParent() const
{
    ASSERT(::IsWindow(m_hWnd)); // Asserts here.
    return CWnd::FromHandle(::GetParent(m_hWnd));
}

I belive this is because the IDC_USERMSG dialog no longer exsists at this stage because it has been closed.
Button/Tooltips implimented as follows.
BEGIN_MESSAGE_MAP(CUserData, CPropertyPage)
    // Displays dialog when button pressed
    ON_BN_CLICKED(IDC_USERMSG, &CUserData::OnBnClickedUsermsgbtn)
END_MESSAGE_MAP()

BOOL CUserData::OnInitDialog()
{
    EnableToolTips(TRUE);
    static CString ToolTip;
    CTTCtrl.Create(this); // CToolTipCtrl CTTCtrl is a global
    CTTCtrl.SetDelayTime(TTDT_AUTOPOP, 8000);
    CTTCtrl.SetMaxTipWidth(ToolTipWidth);

    ToolTip.LoadStringW(TT_REN);
    CTTCtrl.AddTool( GetDlgItem( IDC_TT_REN), ToolTip );

    return 0;
}

BOOL CUserData::PreTranslateMessage(MSG* pMsg)
{
    CTTCtrl.RelayEvent( pMsg );
    CDialog::PreTranslateMessage(pMsg);

    // think I need some sort of filter here.

    return CDialog::PreTranslateMessage(pMsg);
}

Call Stack
mfc90ud.dll!CWnd::GetParent()  Line 297 + 0x2d bytes    C++
mfc90ud.dll!CWnd::FilterToolTipMessage(tagMSG * pMsg=0x00155570)  Line 392 + 0x8 bytes  C++
mfc90ud.dll!CWnd::_FilterToolTipMessage(tagMSG * pMsg=0x00155570, CWnd * pWnd=0x0012fa78)  Line 374 C++
mfc90ud.dll!CWnd::PreTranslateMessage(tagMSG * pMsg=0x00155570)  Line 1070  C++
mfc90ud.dll!CDialog::PreTranslateMessage(tagMSG * pMsg=0x00155570)  Line 56 + 0xc bytes C++
MyApp.exe!CUserData::PreTranslateMessage(tagMSG * pMsg=0x00155570)  Line 495    C++

A: You are calling CDialog::PreTranslateMessag twice, remove the second call.


text:
Q: When Install spacy it show failed to install builed dependencies When i try to install spacy it show error failed to  install build dependencies.I have tried on all things but cannot solve it .
I donwload from following website but no help https://www.lfd.uci.edu/~gohlke/pythonlibs/
Please help me.i am in huge trouble

A: The best way to install spaCy is to just run pip install -U spacy, or, if you're using conda, run conda install -c conda-forge spacy. Alternatively, you can compile it from source by cloning the repo, but usually that isn't necessary. More info can be found here.


text:
Q: Android UI - What Layout to be used to draw many ImageView horizontally i have some images, let's say 4 to 10 images.
i want them to draw horizontally and dynamically resize if more image added.
for example in below script, i have 4 images. but the fourth image not drawed (only 3 images visible) :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:orientation="vertical"
    android:gravity="center">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ball_1"
            />

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ball_1a"
            />

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ball_1b"
            />

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ball_1c"
            />
    </LinearLayout>
</LinearLayout>

design screenshot :

any idea to solve ?
thanks in advance

A: You can use horizontal RecyclerView
Here is how to setup:
LinearLayoutManager layoutManager
    = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
recyclerView.setLayoutManager(layoutManager);

Check this example: Link


text:
Q: Excessive Datastore Writes when creating Hi asked a question on this yesterday and have now simplified the problem to see if it makes it easier to solve / diagnose.
I am trying to bulk create 500 JDO entities, each entity has a "Key" as primary key, two indexed Strings and one unindexed String.
When I create the 500 entities it uses 6% of the datastore write quoto (from a quoto of 500000) which is 30000 write operations which equates to 60 writes per entity. On the development server the "write ops" is 6 which agrees with the various comments made about datastore writes. There is no searching and no composite indexes, I'm just creating 500 entities.
So why do my entities take 60? The JDO Entity is as below:
import javax.jdo.annotations.Extension;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import com.google.appengine.api.datastore.Key;

@PersistenceCapable
public class Product {

    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private Key key;
    @Persistent
    private String productId;
    @Persistent
    private String productName;

    @Persistent
    @Extension(vendorName="datanucleus", key="gae.unindexed", value="true")
    private String merchantProductId;

      .
      .// getters and setters here but not included in post
      .
}

The 500 entities are created in the loop:
private void createBulkProducts(PrintWriter out){
    int cnt = 0;
    Product tmpProd = null;
    PersistenceManager pm = PMF.get().getPersistenceManager();
    ArrayList<Product> products = new ArrayList<Product>();
    for(cnt = 0; cnt < 500; cnt++){
        tmpProd = createBulkProduct(new Integer(cnt).toString());
        products.add(tmpProd);
    }
    if(products.isEmpty() == false){
        pm.makePersistentAll(products);
        out.println(products.size() + " bulk products committed to database");
    }
    pm.close();
    out.println(cnt + " bulk products inserted");
}

private Product createBulkProduct(String cnt){
    Product product = new Product();
    product.setMerchantProductId("mid" + cnt);
    product.setProductId("pid" + cnt);
    product.setProductName("the quick brown fox jumps over the lazy dog " + cnt);
    return product;
}

I am running on GAE 1.6.1
All help / suggestions greatly appreciated
Craig

A: Daily quota for free apps is 50k write operations not 500k. See your Dashboard where it should say n.nn of 0.05 Million Ops.
Taken this into account all calculations are OK.


text:
Q: Wrong Office version and Operating system in vba Excel I am running this code in VBA Excel 365 using Windows 11
Sub test()
Dim sBuild As String, sOP As String, sVersion As String

sBuild = Application.Build
sOP = Application.OperatingSystem
sVersion = Application.Version
MsgBox "Operating System " & sOP & " with Office version " & sVersion & " Build " & sBuild

End Sub

However, I get this message "Operating System Windows (64-bit) NT 10.00 with Office version 16.0 Build 15028"
The properties Application.Version and Application.OperatingSystem shows the same results as if I was running in Excel 2016 and using Windows 10.
Any suggestion to get the real Office and Windows version?
Thank you.
Manuel

A: This link in the comment above works fine for Office (Check the application version in modern office).
I use this for Windows:
Function GetWindowsInfo() As String
  Dim oShell As Object
  Set oShell = CreateObject("WScript.Shell")
  Dim RegKeyProduct As String
  RegKeyProduct = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProductName"
  Dim ProductName As String
  ProductName = oShell.RegRead(RegKeyProduct)
  Dim VersionBuildNumbers(1 To 4) As Variant
  Dim RegKeyMajor As String
  RegKeyMajor = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\CurrentMajorVersionNumber"
  VersionBuildNumbers(1) = oShell.RegRead(RegKeyMajor)
  Dim RegKeyMinor As String
  RegKeyMinor = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\CurrentMinorVersionNumber"
  VersionBuildNumbers(2) = oShell.RegRead(RegKeyMinor)
  Dim RegKeyBuild As String
  RegKeyBuild = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\CurrentBuildNumber"
  VersionBuildNumbers(3) = oShell.RegRead(RegKeyBuild)
  If VersionBuildNumbers(3) >= 22000 Then
    ProductName = Replace(ProductName, "10", "11")
  End If
  Dim RegKeyUBR As String
  RegKeyUBR = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\UBR"
  VersionBuildNumbers(4) = oShell.RegRead(RegKeyUBR)
  Dim BuildNumber As String
  BuildNumber = oShell.RegRead(RegKeyBuild) & "." & oShell.RegRead(RegKeyUBR)
  Dim Bitness As String
  Bitness = "32-bit"
  If Len(Environ("PROGRAMFILES(x86)")) Then Bitness = "64-bit"
  GetWindowsInfo = "Microsoft " & ProductName & " (" & Join(VersionBuildNumbers, ".") & ") " & Bitness
End Function


text:
Q: Can you access previous /var files from new compiles of the same app? Our app downloads a bunch of video files and allows the user to view them. We've noticed that we can download and play the files with no issues at all. But then if an update is pushed or we use Xcode to push a new app over the old one (same version) it will report that the video cannot be found. This is despite the the fact that we can see the video there, in the same folder and folder ID we're looking for has not changed. Is there something happening behind the scenes with local storage for iOS app files that makes them inaccessible after an update?
Example:
/var/mobile/containers/data/application/{same id}/documents/


text:
Q: SuperCollider -- Synthdef with mix of variable amount of SinOsc's This code returns an error, but it works if I remove "arg" from line 4.  What can I do to make n an argument and not get an error?
(
SynthDef("test",
    {
        arg n=8;

        f=Mix.fill(n, {
            arg index;
            var freq, amp;
            freq=440*((7/6)**index);
            //freq.postln;
            amp=(1-(index / n)) / (n*(n+1) / (2*n));
            SinOsc.ar(freq,0,0.2*amp)
        });
        //f=SinOsc.ar(440,0,0.2);
        Out.ar(0,f)
    }).add;
)

A: SynthDefs always have fixed "wiring", so you cannot vary the number of SinOscs. That is a hard constraint which you cannot avoid.
What you can do is procedurally generate synthdefs for each cardinality:
(
(2..10).do{|num|

    SynthDef("wiggler%".format(num), {|freq=440, amp=0.1|
        var oscs;
        oscs = Mix.fill(num, {|index|
            SinOsc.ar(freq * index)
        });
        Out.ar(0, oscs * amp);
    }).add;

}
)

x = Synth("wiggler2")

x.free

x = Synth("wiggler10")

x.free

A: In case you have a an upper bound for n (let's say n<=16), then you can create a continuous cutoff array with which you multiply the harmonics.
(
SynthDef("test",
    {
        arg n=8;

        var cutoff = tanh( (1..16)-n-0.5 *100 ) * -1 / 2 + 0.5; // this

        f=Mix.fill(16, { // run it through the upper bound
            arg index;
            var freq, amp;
            freq=440*((7/6)**index);
            //freq.postln;
            amp=(1-(index / n)) / (n*(n+1) / (2*n));
            cutoff[index] * SinOsc.ar(freq,0,0.2*amp) // multiply with cutoff
        });
        //f=SinOsc.ar(440,0,0.2);
        Out.ar(0,f)
    }).add;
)

The cutoff array has values 1 if index<n, and zeros after that. Lets say n=3, then cutoff==[1,1,1,0,0,0,...].


text:
Q: Laravel Nova: Build Components First post.
I'm currently building a Laravel Nova application. I'm making changes to the dashboard component - more specifically the file within the "resources/js/views/Dashboard.vue".
I'm struggling to build the component - does anyone know how to build the component? I have some code which runs webpack.mix to build my JS and SCSS files, but I'm pretty sure it doesn't include the files within the Laravel Nova instance.
Any help will be great.
EXTRA:
I've already tried run the webpack command to build from inside the Laravel Nova instance but it errors out.

A: UPDATE
I found renaming my webpack.mix.js.dist to webpack.mix.js, running npm run dev whilst within the ./nova directory worked... but only after running php artisan nova:publish
I've wrote a command to compile all these steps but do I have to run php artisan nova:publish everytime, just seems...tedious?

A: By default, Nova's JavaScript is compiled for production. As such, you will not be able to access the Vue DevTools out of the box without compiling Nova's JavaScript for development. To accomplish this, you may use the following terminal commands from the root of your Nova project:
cd ./vendor/laravel/nova
mv webpack.mix.js.dist webpack.mix.js
npm install
npm run dev
rm -rf node_modules
cd -
php artisan nova:publish

Details: https://nova.laravel.com/docs/2.0/customization/frontend.html#vue-devtools


text:
Q: Check randomness of XID field in DHCP request I want to test my UUT by sending DHCP request from it and check if the xid the request packet is random.
Also I need to test if my UUT drops response that have invalid xid field. is there any tool available for it?
I used nmap to run dhcp discover. but not sure how to send invalid xid inorder to check if UUT drops it.

A: In nmap you should use a script to this.
You may use the example broadcast-dhcp-discover script and customize to change the xid
https://github.com/nmap/nmap/blob/master/scripts/broadcast-dhcp-discover.nse
Then you will run it with the command
nmap --script script-name -e $INTERFACE


text:
Q: Understanding gdalwarp reprojection My file is
Driver: GTiff/GeoTIFF
Files: 0001.TIF
Size is 8512, 8622
Coordinate System is:
PROJCS["WGS 84 / UTM zone 31N",
    GEOGCS["WGS 84",
        DATUM["WGS_1984",
            SPHEROID["WGS 84",6378137,298.257223563,
                AUTHORITY["EPSG","7030"]],
            AUTHORITY["EPSG","6326"]],
        PRIMEM["Greenwich",0],
        UNIT["degree",0.0174532925199433],
        AUTHORITY["EPSG","4326"]],
    PROJECTION["Transverse_Mercator"],
    PARAMETER["latitude_of_origin",0],
    PARAMETER["central_meridian",3],
    PARAMETER["scale_factor",0.9996],
    PARAMETER["false_easting",500000],
    PARAMETER["false_northing",0],
    UNIT["metre",1,
        AUTHORITY["EPSG","9001"]],
    AUTHORITY["EPSG","32631"]]
Origin = (837903.261500865686685,5877808.477226150222123)
Pixel Size = (30.079329235631686,-30.079329235631686)
Metadata:
  AREA_OR_POINT=Point
Image Structure Metadata:
  INTERLEAVE=BAND
Corner Coordinates:
Upper Left  (  837903.262, 5877808.477) (  8d 1'48.79"E, 52d56'35.71"N)
Lower Left  (  837903.262, 5618464.501) (  7d46'39.67"E, 50d37'11.83"N)
Upper Right ( 1093938.512, 5877808.477) ( 11d48'11.42"E, 52d43'20.22"N)
Lower Right ( 1093938.512, 5618464.501) ( 11d21'56.03"E, 50d24'59.35"N)
Center      (  965920.887, 5748136.489) (  9d44'38.52"E, 51d41'24.52"N)
Band 1 Block=8512x1 Type=UInt16, ColorInterp=Gray

After reprojecting it to EPSG:32632 by
gdalwarp -t_srs epsg:32632  0001.TIF 0001_.TIF
I got
Driver: GTiff/GeoTIFF
Files: 0001_.TIF
Size is 9192, 9293
Coordinate System is:
PROJCS["WGS 84 / UTM zone 32N",
    GEOGCS["WGS 84",
        DATUM["WGS_1984",
            SPHEROID["WGS 84",6378137,298.257223563,
                AUTHORITY["EPSG","7030"]],
            AUTHORITY["EPSG","6326"]],
        PRIMEM["Greenwich",0],
        UNIT["degree",0.0174532925199433],
        AUTHORITY["EPSG","4326"]],
    PROJECTION["Transverse_Mercator"],
    PARAMETER["latitude_of_origin",0],
    PARAMETER["central_meridian",9],
    PARAMETER["scale_factor",0.9996],
    PARAMETER["false_easting",500000],
    PARAMETER["false_northing",0],
    UNIT["metre",1,
        AUTHORITY["EPSG","9001"]],
    AUTHORITY["EPSG","32632"]]
Origin = (413533.214507141499780,5866398.182513756677508)
Pixel Size = (29.999953551392952,-29.999953551392952)
Metadata:
  AREA_OR_POINT=Point
Image Structure Metadata:
  INTERLEAVE=BAND
Corner Coordinates:
Upper Left  (  413533.215, 5866398.183) (  7d42'47.95"E, 52d56'24.88"N)
Lower Left  (  413533.215, 5587608.614) (  7d46'56.92"E, 50d26' 2.84"N)
Upper Right (  689292.788, 5866398.183) ( 11d48'55.18"E, 52d54'49.85"N)
Lower Right (  689292.788, 5587608.614) ( 11d39'51.06"E, 50d24'35.94"N)
Center      (  551413.001, 5727003.398) (  9d44'37.73"E, 51d41'29.87"N)
Band 1 Block=9192x1 Type=UInt16, ColorInterp=Gray

I calculated myself (using Java GeoTools) that

413533.215, 5608276.425 EPSG:32632 =
837903.262, 5618484.501 EPSG:32631

why I get such a big difference: 5587608.614 instead of 5608276.425?
How does gdalwarp determine the pixel size and the extents?
EDIT:
The accepted answer shed light on my confusion. After I reprojected the lower right corner of the source raster instead of the lower left one, I got almost the same numbers:
x: 1093938.5119545625
y: 5618464.500556534
[668055.0297114132, 5587613.552738925]

x and y are the original coordinates in EPSG:32631

A: Just display your raster in a GIS software in UTM 32N:

You see that the raster is rotated in the new CRS, and the former Lower Left point is not the most southward point anymore.
Since gdalwarp always produces a rectangle parallel to the axes of the new projection, the new corner points are different from the UTM31N corner points.


text:
Q: Spring oauth2 add additional fieldp After login /uaa/oauth/token spring send that fields:
{
  "access_token": "eyJhbG",
  "token_type": "bearer",
  "refresh_token": "asfasfda"
  "expires_in": 86399,
  "scope": "events",
  "jti": "a4e4584c-ed38-4a26-b778-1748b27046ae",
  "key" : "my own field"
}

But how can i add my own custom fields, for example key?

A:  @Configuration
    @EnableResourceServer
    protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

        @Override
        public void configure(ResourceServerSecurityConfigurer resources) {
            resources.resourceId(Constants.RESOURCE_ID);
        }

        @Override
        public void configure(HttpSecurity http) throws Exception {
           http
            .addFilter(new AuthTokenRequestFilter())
           .....
        }
}


text:
Q: Significance of @Produces, @GET, @Path and @QueryParam before function definition I am new to java. I was looking the below code.
@Produces("text/xml")
@GET
@Path("/xml/search")
public Object searchXML(@QueryParam("query") String query,
        @QueryParam("granularity") String granularity) {
    return search(query, granularity);
}

I couldn't understand the uses of @Produces, @GET, @Path and @QueryParam before function definition in above code.
Can anybody put some light on this.
Thanks

A: Those anotations are defined by JAX-RS, a Standard for RESTful Web Services.
In the example above, it mean the method will handle a:

*

*GET request

*on path "/xml/search"

*and map the query argument "query" to String query argument,

*as well as the "granularity" to granularity

*the resulting content-type will be "text/xml"
(and it will probably call a custom marshaller for this)
(see this page for a reference)

A: A producer method is a method that generates an object that can then be injected.Link
When you want to inject an object that is not itself a bean
When the concrete type of the object to be injected may vary at runtime
When the object requires some custom initialization that the bean constructor does not perform
@GET: Transmits a representation of the resource identified by the URI to the client. The format might be HTML, plain text, JPEG, and so on. See How to Transmit a Representation of the Resource (@GET). Link
@Path(param) : @PathParam is a parameter annotation which allows you to map variable URI path fragments into your method call. Link
can use @QueryParam annotation to inject URI query parameter into Java method Link

A: @Produces annotation is to specify the MIME media types of representations a resource can produce and send back to the client.here mediatype is an text rather xml can be recieved,
@GET is an HTTP Methods like  @PUT, @POST, @DELETE
@Path annotation's value is a relative URI path .In this the function call will be from service is through the path as /xml/search/ to the function with the params.
@QueryParam is to extract query parameters from the Query component of the request URL, in this receives the param as strings from the URL .
Document Reference more info


text:
Q: Mongodb c# driver FindAll with setFields and AsQueryable Using MongoDB C# driver, seems that I'm unable to get the data by AsQueryable with setFields and Where condition only by mongo query. I fetched documents by this code
var query = _collection.FindAll().SetFields(fields.MongoFieldsBuilder).AsQueryable();
var query1 = query.Where(d=>d.Name="Ken").ToList();
var query2 = query.Where(d=>d.Age>=2).ToList();

So, when query1 or query2 executed, c# driver fetches all documents from mongo and then filters it in memory. But I expected that Where condition will be converted to mongo query with fields.
Can anyone please explain how to do it correctly?

A: You using  .AsQueryable() from System.Linq, because of this it filter everything on a client side.
But you need to use .AsQueryable() from MongoCollection to filter data in a database. This extension method creates MongoQueryable<T>.
I believe that following should work:
//or you could use your projection class instead of BsonDocument
var query = Items.AsQueryable<BsonDocument>()
                 .Select(x=> new {id = x["_id"].AsObjectId, Name=x["Name"].AsString});
var query1 = query.Where(d=>d.Name == "Ken").ToList();

Update:
If you want use SetFields you have to use old query syntax:
_col.Find(Query<UserDocument>.EQ(x=> x.Name, "Ken")).SetFields(..).

Also you could use SetFields without magic strings as follow:
cursor.SetFields(Fields<UserDocument>.Include(x=> x.Name, x=> x.Age))

With linq SetFields is done via Select.
Hope this helps.


text:
Q: Arrays multiplication in python3 I am getting the error message "'Float' object is not
subscriptable"
import stdio

import stdarray

n = 3

x = [0.30, 0.60, 0.10]

y = [0.40, 0.10, 0.50]

c = stdarray.create2D(n, n, 0.0)

for i in range(n):

    for j in range(n):

        c[i][j] += x[i][j] * y[i][j]

        stdio.writeln(c)

A: Since arrays x and y are 1d arrays, you can index them as if they are 2d arrays.
I think you wanted to index x by i and y by j.
Try
import stdio

import stdarray

n = 3

x = [0.30, 0.60, 0.10]

y = [0.40, 0.10, 0.50]

c = stdarray.create2D(n, n, 0.0)

for i in range(n):

    for j in range(n):

        c[i][j] += x[i] * y[j]

        stdio.writeln(c)


text:
Q: if statment not working with 3rd condition having 2 OR options I want to get result only when all 3 conditions are fullfilled, code works good when 3rd has only one option ex "smith" but taking only 1 condition if 3rd has 2 or more ex "smith"||"Smith"
#include <iostream>
using namespace std;

int main()
{
    int age;
    string name;
    string lastname;
    cout << "Podaj swoje imie" << endl;
    cin >> name;
    cout << "Podaj swoje nazwisko" << endl;
    cin >> lastname;
    cout << "Wprowadz swoj wiek" << endl;
    cin >> age;
    cout << "Imie: ";
    cout << name << endl;
    cout << "Nazwisko: ";
    cout << lastname << endl;
    cout << "Wiek: ";
    cout << age << endl;
    if (age < 18)
    {
        cout << "you're too young";
    }
    else
    {
        cout << "you can drink" << endl;
    }
    if ((age == 27)
            && (name == "katarzyna" || "kasia" || "Katarzyna" || "Kasia")
            && (lastname == "smith" || "Smith"))
    {
        cout << "BOOM" << endl;
        cout << "BOOM";
    }
}

A: lastname == "smith" || "Smith" doesn't do what you think it does.
It is true if lastname == "smith" is true, or if "Smith" is true.
"Smith" always evaluates to a non-NULL pointer, so it is always true.
You want lastname == "smith" || lastname == "Smith", and similarly for the second part with name.

A: I would do the if in this way:
if ((age == 27) && (name == "katarzyna" || name == "kasia" || name == "Katarzyna" || name == "Kasia") && (lastname == "smith" || lastname == "Smith")) {


text:
Q: Prevent keyup event from firing when input box selected I have an event that I want to fire whenever R or SPACE is pressed, with the exception of when in an input field.
Specifically, I'm worried about <input id='nameInput' type='text'> that I dynamically create when I click in a div and remove onchange/onblur. That's why I tried checking if( !$('#nameInput') ), but $('#nameInput') is a jQuery object, so its boolean value is always true (and hence !$('#nameInput') == false).
$(window).bind('keyup',
  function(e) {
    var code = (e.keyCode ? e.keyCode : e.which);
    if(code == 32 || code == 82){
      if( !$('#nameInput') ){
        roll();
      }
    }
  }
);

I have a solution that utilizes a global boolean variable getting set in onfocus of the input field, but I'd like a solution that doesn't require a global variable if it's possible.
Is there a way to determine what element currently has focus?

A: You can use document.activeElement to know wich element currently has focus.
if (!$(document.activeElement).is('input, textarea')) {
    roll();
}

You could also make use of the :focus selector.
if (!$(':focus').is('input, textarea')) {
    roll();
}


text:
Q: Why does mysql server rpm size become smaller after 8.0.29?

A 10 times size change and why?
ref: https://downloads.mysql.com/archives/community/

A: They've moved lots of non-required stuff to a new "Debug Information" package (mysql-community-debuginfo-8.0.29-1.el7.x86_64.rpm). That package isn't available for 8.0.28 and takes 425.3 MB.
It's mentioned in the MySQL 8.0.29 release notes:

Implemented standard package policy to ship separate debuginfo RPMs for the following platforms: SLES/openSUSE, and community EL6 and EL7. Commercial versions of EL6 and EL7 are now built with the RelWithDebInfo build type instead of Debug, which greatly decreases their size. (Bug #33663811, Bug #33684418, Bug #33664929)


text:
Q: LIst of lists in R into a data.frame - inconsistent variable names I have a list of lists and I want to convert it into a dataframe. The challenge is that there are missing variables names in lists (not NA's but the variable is missing completely).
To illustrate on example: from
my_list <- list()
my_list[[1]] <- list(a = 1, b = 2, c = 3)
my_list[[2]] <- list(a = 4, c = 6)

I would like to get
     a  b c
[1,] 1  2 3
[2,] 4 NA 6

A: Another option is
library(reshape2)
as.data.frame(acast(melt(my_list), L1~L2, value.var='value'))
#  a  b c
#1 1  2 3
#2 4 NA 6

Or as @David Arenburg suggested a wrapper for melt/dcast would be recast
recast(my_list, L1 ~ L2, value.var = 'value')[, -1]
#  a  b c
#1 1  2 3
#2 4 NA 6

A: You can use the bind_rows function from the dplyr package :
my_list <- list()
my_list[[1]] <- list(a = 1, b = 2, c = 3)
my_list[[2]] <- list(a = 4, c = 6)
dplyr::bind_rows(lapply(my_list, as.data.frame))

This outputs:
Source: local data frame [2 x 3]
  a  b c
1 1  2 3
2 4 NA 6

A: Another answer, this requires to change the class of the arguments to data.frames:
 library(plyr)
 lista <- list(a=1, b=2, c =3)
 listb <- list(a=4, c=6)
 lista <- as.data.frame(lista)
 listb <- as.data.frame(listb)
 my_list <- list(lista, listb)
 my_list <- do.call(rbind.fill, my_list)
 my_list
   a  b c
 1 1  2 3
 2 4 NA 6


text:
Q: Laptop won't boot after bad overclock attempt I have an ASUS G750JX laptop running Windows 8.1 that's recently been experiencing difficulty booting. The hard disk light flickers off after a few seconds and the computer just sits on a black screen until it's turned off.
Previously, holding the F2 button would cause the hard disk light to flicker weakly for a while, and the next attempt at turning it on would be successful, but now that won't even work. The hard disk light is on, and shutting down requires holding the button down longer, but the screen stays black.
A bad overclock attempt which caused a crash alongside severe graphical glitching occurred immediately before the problem started.


text:
Q: mysql select between or what? I'm learning about MySQL and I have a case, I have some table like this:
id, level,        minpost, maxpost
 1, 'Newbie',           0,      99
 2, 'Enthusiast',     100,     499
 3, 'Activist',       500,     749
 4, 'Socialite',      750,     999

So how do I know which "level" if I have 80 posts?
Should I use select between or maybe you have any suggest for my problem?
ps. I cant post image :(

A: SELECT level FROM <table> WHERE <myLevel> BETWEEN minpost AND maxpost

The BETWEEN operator will do the following:
expr BETWEEN min AND max

Equals:
(min <= expr AND expr <= max)

A: select *
from the_table
where 80 between minpost AND maxpost

P.S.: don't bother posting images, SQL code (that can be copied) is much better

A: Yes you can use BETWEEN.
It's nothing but the short form of value>=minvalue AND value<=maxvalue
The query will look like:
select * from `tableName`
   where <valueToCheck> between minpost AND maxpost;

A: select id,level from <table> where minpost >= <minpost> and maxpost <= <maxpost>


text:
Q: Convert PG_query to PDO statement I'm a bit lost with this statement. I am trying to convert this PG_query script into PDO. The Idea is that I can then use this example, to pull other values from the database and display in a form.I can populate a dropdown with the PDO but wasn't sure what to do so I can grab row values and fill form items. So this example I just want to grab rivername.
$result = pg_query("SELECT * FROM rivers_tbl WHERE river_id  = '$river_id'");
$test = pg_fetch_array($result);
  if (!$result)
    {
    die("Error: Data not found..");
    }
    $rivername = $test['rivername'];

I have a DB connection working and this part of my query in PDO
 $stmt2 = $conn->prepare("SELECT * FROM rivers_tbl WHERE river_id  = '$river_id'");
   if ($stmt2->execute()) {
       $stmt2->setFetchMode(PDO::FETCH_ASSOC);
       }

A: $sql = "SELECT * FROM rivers_tbl WHERE river_id  = :river_id";
    $sth = $conn -> prepare($sql);
    $sth -> bindValue(':river_id', $river_id, PDO::PARAM_INT);
    $sth -> execute();

    $row = $sth->fetch(PDO::FETCH_ASSOC);

  if (!$sth) {
    die("Error: ..");
    }
    $rivername = $row['rivername'];

In this example I use Error executing the query, but for something like records not found use:
if ($count = $sth->rowCount() == 0) {
    echo "No records Found!";
}else{
    $rivername = $row['rivername'];
}


text:
Q: Inspect dynamic drop down menu I need to automate drop down which is populated dynamically.
When I try to inspect it; it gets closed.
How to interact with this kind of dynamic drop down to find its elements and click one of them.

A: I got it working as below

*

*driver.getPageSource() to fetch all the page elements when drop down is opened post clicking on element

*note put break point after selenium script which does click on dynamic drop down & later fetches pagesource immediately

*

*click action

*getPageSource action to save into temp string

*break point to look into string

*copy this and paste into https://codebeautify.org/xmlviewer > Beautify/Format

*Goto full screen mode, clicking inside the window and search for drop down option name https://codebeautify.org/xmlviewer#

*Also keep the console open to check the element which gets created dynamically post clicking drop down element. Now search this in xml tree.

*This way one can locate element for this kind of unique constraints.

A: *

*Right-click on the dropdown, click Inspect Element, and find it in the devtools.

*Left-click on the dropdown to open it.

*Right-click on an option in the open dropdown but do NOT click Inspect Element.

*Press Escape to close the context menu.

Now you can scroll through the HTML and find the options in the devtools.


text:
Q: Show result from a post request in alert dialog box and send the details to another composable I am doing a post request, show the value in an alert dialog box and pass that information to another composable.
I don't know how to show the result in an alert dialog box and pass the information to another composable.
Here is what I have done so far.
@Composable
fun Lookup() {

        val number = remember {
            mutableStateOf(TextFieldValue())
        }
        val name = remember {
            mutableStateOf(TextFieldValue())
        }
        val response = remember {
            mutableStateOf("")
        }

    var showDialog by remember { mutableStateOf(false) }

    if (showDialog) {
        LookupDialog()
    }

    val openDialog by viewModel.open.observeAsState(false)

    if (openDialog){
        DialogBoxLoading()
    }
    Column(
        modifier = Modifier.padding(20.dp),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {

        Spacer(modifier = Modifier.height(20.dp))
        TextField(
            label = { Text(text = "Number") },
            value = number.value,
            onValueChange = { number.value = it })

        Spacer(modifier = Modifier.height(20.dp))

        Box(modifier = Modifier.padding(40.dp, 0.dp, 40.dp, 0.dp)) {
            Button(
                onClick = {
                    postDataUsingRetrofit("fjsjsdf")
                    LookupDialog
                },
                shape = RoundedCornerShape(50.dp),
                modifier = Modifier
                    .fillMaxWidth()
                    .height(50.dp)
            ) {
                Text(text = "Search Number")
            }
        }

    }
}

fun postDataUsingRetrofit(number: String) {

    val url = "https://baseurl/slookup"
    val postBody = String.format(
            """{
            "number": "%1${"$"}s",
            "name": "%2${"$"}s"
        }""", number, name
    )
    val requestBody = postBody.toRequestBody()

    val okHttpClient = OkHttpClient()

    val retrofit = Request.Builder()
        .method("POST", requestBody)
        .url(url)
        .build()
    okHttpClient.newCall(retrofit).enqueue(object : okhttp3.Callback {
        override fun onFailure(call: okhttp3.Call, e: IOException) {
            Log.d("itfailed", e.toString())
        }

        override fun onResponse(call: okhttp3.Call, response: okhttp3.Response) {
            val json = JSONObject(response.body?.string())
            val responseStatus = json.getString("status")
            val responseDesc = json.getString("desc")
        }
    })

}

@Composable
fun LookupDialog(title: String = "",
                        isSuccessful: Boolean = false,
                        content: (@Composable () -> Unit)? = null,
                        clicked: () -> Unit = {}) {
    AlertDialog(
        onDismissRequest = { },
        confirmButton = {
            TextButton(onClick = {
            //Move to a new composable(page)
            })
            { Text(text = "OK") }
        },
        dismissButton = {
            TextButton(onClick = {})
            { Text(text = "Cancel") }
        },
        title = { Text(text = "This should contain information responseStatus from postDataUsingRetrofit ") },
        text = { Text(text = "This should contain information responseDesc from postDataUsingRetrofit ") }
    )
}

@Composable
fun NewComposable(action: (Result?) -> Unit) {

Column(
            modifier = Modifier.padding(20.dp),
            verticalArrangement = Arrangement.Center,
            horizontalAlignment = Alignment.CenterHorizontally
        ) {

            Spacer(modifier = Modifier.height(20.dp))
            TextField(
                label = { Text(text = "This should contain information responseStatus from postDataUsingRetrofit ") },
                keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
                value = number.value,
                onValueChange = { number.value = it })

            Spacer(modifier = Modifier.height(20.dp))

            TextField(
                label = { Text(text = "This should contain information responseDesc from postDataUsingRetrofit ") },
                keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
                value = msisdn.value,
                onValueChange = { name.value = it })
}
}

After postDataUsingRetrofit is done, the information shows in LookupDialog, that information passed to NewComposable.