Q: Why does setting focus in the OnNavigatedTo() event not set focus? I've got this code in a pages OnNavigatedTo() event:
if (string.IsNullOrWhiteSpace(textBoxGroupName.Text))
{
    textBoxGroupName.Focus(FocusState.Programmatic);
}

...but textBoxGroupName does not have focus when the page displays. Why not?

A: OnNavigatedTo happens to early in the page lifetime for setting the focus to work. You should call your code in the Loaded event:
private void MainPage_OnLoaded(object sender, RoutedEventArgs e)
{
    if (string.IsNullOrWhiteSpace(textBoxGroupName.Text))
    {
        textBoxGroupName.Focus(FocusState.Programmatic);
    }
}

Of course you need to setup the handler in your .xaml file (I've omitted the other attributes in the Page element:
<Page
    Loaded="MainPage_OnLoaded">

A: Only controls that are contained within the GroupBox control can be selected or receive focus. Seems like you are not using GroupBox correctly.
From MSDN

The complete GroupBox itself cannot be selected or receive focus. For more information about how this control responds to the Focus and Select methods, see the following Control members: CanFocus, CanSelect, Focused, ContainsFocus, Focus, Select.

Hint:
You maybe want to use the Controls property to access the child controls:
if (string.IsNullOrWhiteSpace(textBoxGroupName.Text))
{
    var child_TextBox = textBoxGroupName.Controls["myTextBox"]
    if(child_TextBox.CanFocus)
        child_TextBox.Focus(FocusState.Programmatic);
}


Q: How to handle very very large amount of data in Android? I have a database containing 2 500 000 row of 13-digits numbers (and on end a little bit more - 4 000 000)
The user has to find if a 13-digits number exists in this database, all this on his android phone, without any internet connexion. So what do you suggest to deal with this?
I thought about using SQLITE on Android.
What do you suggest?

A: SQLite will be the best storage option for large data sets on the device. Ensure that where possible you use the correct SQLite query to get the data you need rather then using a general query and doing processing in your own code.

A: This is a bit too much to add in the comments, so I'll add it here.
4,000,000 rows of integers is not that much. Assuming that the integers will use the maximum size of a signed int (8 bytes), your database will be:
4000000 * 8 / 1024 / 1024 = ~30.5mb
That is large, but not game breaking.
Now that also assumes you will need a full 8 bytes per number. We know that we want to store 13 digits per entry, so a 6 byte integer column would suffice:
4000000 * 6 / 1024 / 1024 = ~23mb

A: Hi d3cima may be too late answer but it's help other's. Myself Realm is the best option.
Realm
Realm’s developer-friendly platform makes it easy to build reactive apps, realtime collaborative features, and offline-first experiences.
Advantage's:

*

*faster than SQLite (up to 10x speed up over raw SQLite for normal
operations)

*easy to use

*object conversion handled for you

*convenient for creating and storing data on the fly
I used my project it's more than 10 x then Sqlite.


Q: Open an iOS app from a shared link on a Facebook post We need users to open our app from a "...shared a link" on Facebook, or re-direct to the iOS app download page.  Is there objective c code available to accomplish this?  Thanks.

A: Since you asked for objective-C code, I assume you want to open either the appstore or the app on a certain URL. However, objective-c code is the least of the efforts here since it's mostly configurations that are at work for this.
To open an app you need to provide it a custom URL scheme:
http://iosdevelopertips.com/cocoa/launching-your-own-application-via-a-custom-url-scheme.html
To detect if that app is installed, you can try that URL:
https://developer.apple.com/library/ios/documentation/uikit/reference/UIApplication_Class/index.html#//apple_ref/occ/instm/UIApplication/canOpenURL:
And if not, you can navigate to the appstore instead via a different URL:
How can I link to my app in the App Store (iTunes)?
After you have done all that, the only actual code you need takes something of the form:
NSString *customURL = @"yourscheme://";
NSString *storeURL = @"itms://url_to_your_app";

if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:customURL]])
{
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:customURL]];
}
else
{
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:storeURL]];
}

Opening the app via it's URL can be done from other apps and websites, but will be more difficult to choose whether or not to open the app or store from inside a browser.

A: Apple have documented the process for you. You can just implement it your way.
NSString *iTunesLink = @"https://itunes.apple.com/us/app/apple-store/id375380948?mt=8";

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:iTunesLink]]

You can refer to This document for more info


Q: Cannot update global state using Context.API Trying to use Context.API to create a global state and pass it to multiple components. The state will store a few properties including a TwilioToken, device type and a name. I have a component SignupForm that renders a button. When the button is clicked, this triggers a function handleSubmit that takes a username and passes the username as an argument to another function setupTwilio. This function sends the username to an end point that interacts with Twilio Programmable Voice API, sending back a TwilioToken and device type. I then want to update my global state with the Twilio Token and device type and then redirect the user to another page /rooms
Problem is I don't seem to be updating my global state at all, when I console.log(state.TwilioToken) in the component rendered after handleSubmit I get null
Here is my context provider:
const initialState = {
    nickname: '',
    selectedRoom: null,
    rooms: [],
    createdRoomTopic: '',
    twilioToken: '',
    device: null
};

const RoomContext = createContext(null);

export const RoomContextProvider = ({ children }) => {
    const[state, setState] = useState(initialState);
    return (
        <RoomContext.Provider value={[state, setState]}>{children}</RoomContext.Provider>
    )
};

export const useGlobalState = () => {
    const value = useContext(RoomContext)
    if(value === undefined) throw new Error('Please add RoomContextProvider');
    return value;
}

My signupform
import { useGlobalState } from '../../context/RoomContextProvider';
...
//without useState() I get the error Uncaught TypeError: object null is not iterable (cannot read property Symbol(Symbol.iterator))

const [state, setState] = useState(useGlobalState());
...
    const handleSubmit = e => {
        e.preventDefault();
        const nickname = user.username;
        setupTwilio(nickname);
        history.push('/rooms');
    }
    const setupTwilio = (nickname) => {
        console.log('inside setupTwilio function', nickname)
        fetch(`http://127.0.0.1:8000/voice_chat/token/${nickname}`)
        .then(response => response.json())
        .then(data => {
            const twilioToken = data.token;
            const device = new Device(twilioToken);
            device.updateOptions(twilioToken, {
                codecPreferences: ['opus', 'pcmu'],
                fakeLocalDTMF: true,
                maxAverageBitrate: 16000
            });
            device.on('error', (device) => {
                console.log("error: ", device)
            });
            setState((state) => {
                return {...state, device, twilioToken}
            });
        })
      ...
    };
    return (
       <button className="button button-primary button-wide-mobile button-sm"
               onClick={handleSubmit}> Start Coding
       </button>

    );

When I console.log my state in the component rendered I get null
import { useGlobalState } from '../../context/RoomContextProvider';
...
const [state, setState] = useState(useGlobalState());
console.log('global state token is', state.twilioToken)


Q: Windows 10 on my Dell 7410 keeps locking itself when im idle for a few minutes After about a minute, the screen dims, and another minute later the screen locks itself. This happens even while i am in a meeting or watching a video when im not moving my mouse. All while the laptop is charging and not in battery mode.
What ive tried:

*

*Disabling all power saving options

*Adding the registry key / grppolicy as described here

*Checking that dynamic lock is disabled - here windows tells me that some options are managed by my company

How can i make absolutely sure that windows will never, ever, lock itself on its own without me manually telling it to?


Q: Flash CS5.5 adds green background to bitmaps with alpha Recently, my Flash began to behave weirdly. I have imported PSD file, where were some layers with transparency. They imported successfully and are OK.
The problem is, when I want to edit them from library with PS. I always worked great, but now flash adds all pixels with alpha green background color (see picture below).
Left: Bitmap with alpha; Right: after clicking on "Edit with ..."
I went through all the settings I've found, but I can't find any solution. Did this happen to you too? Did you solve it?
Thank you for your answers.
EDIT: SOLUTION
I've resetted to the default settings. http://forums.adobe.com/thread/992810


Q: How can I get the string value of the name of a property in a dynamic type in Azure Log Analytics? I have a value of type dynamic, the JSON representation of which looks like:
{ "ReportName": { "Duration": 2347, "RowCount": 1167 } }
I would like to extract the string value "ReportName" from this, as I have many rows with a similar structure, but the name of the "root" property can differ for each one.
This seems like it should be easy, but I am struggling. I have arrived at this juncture by doing an mvexpand on a sub-property of a much larger JSON value/entity further up in my query, which has a variety of different property names inside it.
I have tried casting this to a string (using tostring()) and using jsonextract("$", value), plus several similar variants, but none of them seem to work (I get NULLs back).
Thanks!


Q: Design practice for container class with multiple collections which reference each other I'm trying to design a class structure with the following:

*

*Container class which holds all the items.

*Item collection class which is inside the Container, where each Item has a unique ID and some other data, including a reference to an ItemStyle.

*ItemStyle collection class which is inside the Container, where each ItemStyle represents a common style of items and also the relationship to other styles.

Relationships can be "Attaches To" where a style has a list of other styles it can attach to, and "Attachments" which is the inverse of that.  If a style can "Attach To" another style, then the other style should be able to produce the first style as one of its "Attachments".
The container manages the Items and the ItemStyles.  I use unique IDs for everything because I want to be able to serialize to and from XML.
However I keep running into logical problems such as I am trying to deserialize an ItemStyle from XML, but of course it can't generate references to the item IDs that it reads since only the Container itself has access to the other items.
Another issue is I want these classes to be independent to the point where if I have a reference to an Item, I can invoke a list of compatible items such as calling "Item.Attachments" or "Item.AttachesTo".  This of course all needs to be calculated by the Container since it is the only class to be able to access both the ItemStyles and the Item collections.
So I'm running into a solution where I am going to have to give each Item and ItemStyle a reference to the Container so they can perform their own lookups and determine their relationship with other items.  This seems like bad encapsulation and bad OOP practice, but I can't think of any other way.
I'm trying to compare my code to how a ListView works as an example.  A ListView has a ListViewItemCollection and ListViewItems.  In user code when you can create a new ListViewItem and when you add it to a ListViewItemCollection, it automatically now has a reference to its parent ListView.  When looking at the metadata it shows the ListView reference as only having a getter.  Can I assume that it uses an internal set?
Should following the ListView model of owner/item relationship work with my classes?

A: Looking at a tight coupling between all classes involved, I don't think that having a reference to the parent (Container) would be a bad idea. There are many models that rely on having parent reference (typical reason could be to ensure a single parent but other reasons such as validations etc can be a cause) - one of the way to model is to have non-public constructor and construct objects via factory methods. Another way of modelling is to have public constructor but have internal setter to set the parent reference. Whenever child is added to the parent's collection object, the reference is set.
I would prefer the later approach. However, one of the thing that I would do is to avoid direct coupling with Container. Rather, I will introduce IContainer interface that will abstract look-ups needed in children and children (Item/ItemStyle) will know only about IContainer interface.
Yet another reasonable design would be to raise events from children when they want to do look-ups. These will be internal events that will be handled by container when the children are added to it.
Yet another approach would be to have a loose model. Essentially, Item can maintain its own ItemStyle references. Whenever needed, Container can build ItemStyle collection by implementing visitor pattern.


Q: Is it possible to put different datatypes in the same List<> Is it possible to put different datatypes in the same List<> in C#?
myList.Add("Joe");
myList.Add(25);

A: Assuming you are using Java, yes.  Everything is an Object in Java and Arrays take Objects.  Good luck getting them back out though.


Q: How do I fix my image not being pasted correctly? I am trying to crop a image into a circulor form (which works) and then pasting it to a white backround.
from PIL import Image,ImageFont,ImageDraw, ImageOps, ImageFilter
from io import BytesIO
import numpy as np

pfp = Image.open(avatar)

# cropping to circle
img=pfp.convert("RGB")
npImage=np.array(img)
h,w=img.size

alpha = Image.new('L', img.size,0)
draw = ImageDraw.Draw(alpha)
draw.pieslice([0,0,h,w],0,360,fill=255)
npAlpha=np.array(alpha)
npImage=np.dstack((npImage,npAlpha))
Image.fromarray(npImage).save('result.png')

background = Image.open('white2.png')

background.paste(Image.open('result.png'), (200, 200, h, w))
background.save('combined.png')

Heres what the cropped image looks like(It looks like it has a white background but that's it's transparent):
Cropped Image
But then when I paste it to the white background it changes to a square:
Pasted Image
Here is the original image I am working with:
Image

A: What you're doing is setting the Alpha of any pixel outside that circle to 0, so when you render it, it's gone, but that pixel data is still there. That's not a problem, but it important to know.
Problem
Your "white2.png" image does not have an alpha channel. Even if it's a PNG file, you have to add an alpha channel using your image editing tool. You can print("BGN:", background.getbands()), to see the channels it has. You'll see it says 'R','G','B', but no 'A'.
Solution 1
Replace your paste line with:
background.paste(pfp, (200, 200), alpha)
Here, we use the loaded in avatar as is, and the third argument is a mask which PIL figures out how to use to mask the image before pasting.
Solution 2
Give your white background image an alpha channel.
MS Paint doesn't do this. You have to use something else.
For GIMP, you simply right-click on the layer and click Add Alpha-channel.
Oh, and something worth noting.
Documentation for Paste.

See alpha_composite() if you want to combine images with respect to their alpha channels.


Q: tikz being mishandled by manuscriptcentral I'm submitting a paper through manuscriptcentral.  The paper uses tikz.  Here is the code for one of those figures:
%in preamble
\tikzset{box/.style={draw, minimum width = 1.cm, minimum height = 1.cm, text width=1cm, text centered, fill=white},
slantedbox/.style={draw,trapezium,trapezium left angle=70,trapezium right angle=-70, fill=colora!5, label={[shift={(-5ex,-3.5ex)}]top right corner:#1}}
}

%in main text

\begin{figure}
\begin{center}
\begin{tikzpicture}
\node [box] (phiQQ) at (0,0) {$\phi_{QQ}$};
\node [box] (phiQA) at (3,0) {$\phi_{QA}$};
\node [box] (phiQ*A) at (6,0) {$\phi_{Q^*A}$};
\node [box] (phiAA) at (4.5,-1.75) {$\phi_{AA}$};
\node [box] (phi*QA) at (3,-5) {$\phi^*_{QA}$};
\node [box] (phi*Q*A) at (6,-5) {$\phi^*_{Q^*A}$};
\node [box] (phi*AA) at (4.5,-6.75) {$\phi^*_{AA}$};
\node [box] (phi**AA) at (4.5,-10) {$\phi^{**}_{AA}$};
\path [->] (phiQQ) edge node {}(phiQA);
\path [->] (phiQA) edge [out=0,in=90] node {} (phiAA);
\path [->] (phiQA) edge node {} (phiQ*A);
\path [->] (phiQA) edge [out=270,in=180] node {} (phiAA);
\path [->] (phiQ*A) edge [out=270,in=0] node {} (phiAA);

\path [->, left] (phiQA) edge node[pos=0.7] {$\beta \phi_{QA}$} (phi*QA);
\path [->,right] (phiQ*A) edge node[pos=0.7]  {$\beta \phi_{Q^*A}$} (phi*Q*A);
\path [->,right] (phiAA) edge node[pos=0.3] {$2\beta\phi_{AA}$} (phi*AA);

\path [->] (phi*QA) edge [out=0,in=90] node {} (phi*AA);
\path [->] (phi*QA) edge node {} (phi*Q*A);
\path [->] (phi*QA) edge [out=270,in=180] node {} (phi*AA);
\path [->] (phi*Q*A) edge [out=270,in=0] node {} (phi*AA);

\path [->,right] (phi*AA) edge node[pos=0.35] {$\beta\phi^*_{AA}$} (phi**AA);

\begin{pgfonlayer}{background}
\node [slantedbox = $\xi$, fit = (phiQQ)(phiQA)(phiQ*A)(phiAA), minimum height = 3.4cm] at (3,-1) (xi) {};
\node [slantedbox = $\xi_*$, fit = (phi*QA)(phi*Q*A)(phi*AA), minimum height = 3.4cm] at (4,-5.75) (xi*) {};
\node [slantedbox = $\xi_{**}$, fit = (phi**AA), minimum height = 2.6cm] at (4.5,-10) (xi**) {};
\end{pgfonlayer}

After manuscriptcentral gets its hands on it and gives me the pdf to proof, here is what the corresponding page looks like:

It should be:

Any ideas what the problem is and a (low effort) method to fix it?


Q: How to get the meta value of the ACF field (wordpress)? I need to get the meta value of the ACF field.
ACF field called 'submitdate' (format => Date Time picker : Y-m-d H:i:s) already has data '2021-06-11 17:23:36'
I tried the following code, but it only shows correct $post->ID, it doesn't show $submitdate.
No error in console.
Would you please let me know how to echo the value of the field?
Query I tried:
$args = array(
'post_type'         => 'project',
'posts_per_page'    => -1,
'author'            => get_current_user_id(),
'name'              => get_the_title()
    );
$query = new WP_Query($args);

    if ($query->have_posts()) {
    global $post;
    while ($query->have_posts()) {
    $query->the_post();
    $submitdate = get_post_meta($post->ID, 'submitdate', true);
echo $post->ID;
echo $submitdate;
  }
}

I also tried, it shows current date and time, not the value in the field:
$submitdate = get_field("submitdate", $post->ID);

Thank you.

A: /* I had same issue before few days and resolved with below function */

/* please try this line of code */

  $args = array(
    'post_type'         => 'project',
    'posts_per_page'    => -1,
    'author'            => get_current_user_id(),
    'name'              => get_the_title()
   );
  $query = new WP_Query($args);

    if ($query->have_posts()) {
    global $post;

    while ($query->have_posts()) {
         $query->the_post();
         $submitdate = get_field('submitdate', $post->ID ); // if changed field name then update key in this query

          echo $post->ID;
          echo $submitdate;
     }
   }


Q: How to take data from mongodb atlas and add to table on website? the plan is to create a table on a website (link below) that users can add or remove data (a new row) to.
I have set up a form above the table (with POST) that takes data input into the form and then adds that data to a collection in my mongodDB atlas cloud.
This is fine so far, the problem is I dont know how to code to get that data to go from the db and append to the table (with GET)  adding a new row simultaneously.
eg. You add data to form and press submit.

*

*The data you submitted goes to database (set this up)

*At same time, data that was just submitted is taken from database and added to the table on the webpage (permanently until removed).

I can show you the page i created so you can see what Im trying to do.
https://epsl.herokuapp.com/transfer_list
I am using node, mongo, mongoose, express..to set  it up.
thanks.


Q: What does module refer to in context of the 4 concepts of Webpack? The 4 concepts of webpack are Entry, Output, Loaders, and Plugins.
I have been looking through the documentation to get an understanding of how my React configuration works.
Entry and Output make sense.  But why is loaders included under module.
In terms of the documentation modules are what webpack creates from files.
But in the code ( working ) it holds loaders.
I would have expected it to be a 3rd key.
Where is the documentation for Webpack-React?  I did an advance Google Search but nothing relevant came up except a React Proxy Loader,
I am trying to understand this code and need a starting point. Other than the 4 primary concepts.  I don't know how it works.
The form below does not even seem to be contained in more in depth documentation under loaders
module.exports = {
  entry: `${SRC_DIR}/index.jsx`,
  output: {
    filename: 'bundle.js',
    path: DIST_DIR
  },
  module: {
    loaders: [
      {
        test: /\.jsx?/,
        include: SRC_DIR,
        loader: 'babel-loader',
        query: {
          plugins: ["transform-object-rest-spread", "transform-class-properties"],
          presets: ['react', 'es2015']
        }
      }
    ]
  }
};

A: So one answer to your question is that you're not necessarily looking for documentation for Webpack and React, but Babel (or similar transpiler) and React. Babel-loader (which is the loader you're using above) transpiles React's JSX format into javascript the browser can read via Webpack. Here's the babel-loader documentation.
Here are a few other resources that may help:
1) Setup React.js with Npm, Babel 6 and Webpack in under 1 hour
2) Setup a React Environment Using webpack and Babel
3) React JSX transform
4) And if it is of interest to you: React without JSX


Q: How to get Names of Background Running Apps I'm making an app in which i need to show the names of apps running in background. I did R&D on it and came to know that we can know only about Apple's apps like Photos , Camera etc. But I couldn't know how. Please help me if you know how to get JUST NAMES OF BACKGROUND RUNNING APPS
For Background running processes I have used following Method
- (NSArray *)runningProcesses {

    int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0};
    size_t miblen = 4;

    size_t size;
    int st = sysctl(mib, miblen, NULL, &size, NULL, 0);

    struct kinfo_proc * process = NULL;
    struct kinfo_proc * newprocess = NULL;

    do {

        size += size / 10;
        newprocess = realloc(process, size);

        if (!newprocess){

            if (process){
                free(process);
            }
            return nil;
        }

        process = newprocess;
        st = sysctl(mib, miblen, process, &size, NULL, 0);

    } while (st == -1 && errno == ENOMEM);

    if (st == 0){

        if (size % sizeof(struct kinfo_proc) == 0){
            int nprocess = size / sizeof(struct kinfo_proc);

            if (nprocess){

                NSMutableArray * array = [[NSMutableArray alloc] init];

                for (int i = nprocess - 1; i >= 0; i--){

                    NSString * processID = [[NSString alloc] initWithFormat:@"%d", process[i].kp_proc.p_pid];
                    NSString * processName = [[NSString alloc] initWithFormat:@"%s", process[i].kp_proc.p_comm];

                    NSDictionary * dict = [[NSDictionary alloc] initWithObjects:[NSArray arrayWithObjects:processID, processName, nil]
                                                                        forKeys:[NSArray arrayWithObjects:@"ProcessID", @"ProcessName", nil]];
                    [processID release];
                    [processName release];
                    [array addObject:dict];
                    [dict release];
                }

                free(process);
                return [array autorelease];
            }
        }
    }

    return nil;
}

If you think its impossible then kindly have a look to this app http://itunes.apple.com/us/app/sys-activity-manager-for-memory/id447374159?mt=8 . I have also got a solution but its not a proper way (I've mentioned in the last comment below this question).
Thanks.

A: I think in ios it not posible to get which apps are running in background, because in ios the which one is foreground this one the active running apps and other which one you are getting these all are background appps.
so, excluding your application name others are background apps.

A: I don't think it's ment to be possible, but others like you have been very involved in the same topic and come up with some workarounds. Read this blogpost for more info: http://www.amitay.us/blog/files/how_to_detect_installed_ios_apps.php


Q: Struggling with gesture dragging I am trying to implement dragging in my Android app. I am following the Android documentation sample listed here. Here is the code:
// The current viewport. This rectangle represents the currently visible
// chart domain and range.
private RectF mCurrentViewport =
        new RectF(AXIS_X_MIN, AXIS_Y_MIN, AXIS_X_MAX, AXIS_Y_MAX);

// The current destination rectangle (in pixel coordinates) into which the
// chart data should be drawn.
private Rect mContentRect;

private final GestureDetector.SimpleOnGestureListener mGestureListener
            = new GestureDetector.SimpleOnGestureListener() {
...

@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2,
            float distanceX, float distanceY) {
    // Scrolling uses math based on the viewport (as opposed to math using pixels).

    // Pixel offset is the offset in screen pixels, while viewport offset is the
    // offset within the current viewport.
    float viewportOffsetX = distanceX * mCurrentViewport.width()
            / mContentRect.width();
    float viewportOffsetY = -distanceY * mCurrentViewport.height()
            / mContentRect.height();
    ...
    // Updates the viewport, refreshes the display.
    setViewportBottomLeft(
            mCurrentViewport.left + viewportOffsetX,
            mCurrentViewport.bottom + viewportOffsetY);
    ...
    return true;
}

After the onScroll method executes, how do I update my View? Only the mCurrentViewport variable is updated in the sample.

A: There is quite some code going into using those Android tutorials that is not mentioned there. I suggest using the import sample from menu from Android Studio. This one is possibly what you need to play with:
https://github.com/googlesamples/android-BasicGestureDetect/
I have embedded that Android Tutorial code below in BasicGestureDetectFragment.java if you use the guthyb code above. In "moveLog" method you can do whathever you like with the dx values. I have also put a code under this that shows you how to creat an app dragging a picture. Just add "ic_launcher.png" to image folder under res folder so that you can have an image and move it. I suggest coding with Corona SDK that is a lot simpler than Android.
/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example.android.basicgesturedetect;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.MotionEventCompat;
import android.view.GestureDetector;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;

import com.example.android.common.logger.Log;
import com.example.android.common.logger.LogFragment;

import static android.view.MotionEvent.INVALID_POINTER_ID;

public class BasicGestureDetectFragment extends Fragment{
    private int mActivePointerId = INVALID_POINTER_ID;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        View gestureView = getActivity().findViewById(R.id.sample_output);

        gestureView.setFocusable(true);

        // BEGIN_INCLUDE(init_detector)

        // First create the GestureListener that will include all our callbacks.
        // Then create the GestureDetector, which takes that listener as an argument.
        GestureDetector.SimpleOnGestureListener gestureListener = new GestureListener();
        final GestureDetector gd = new GestureDetector(getActivity(), gestureListener);

        /* For the view where gestures will occur, create an onTouchListener that sends
         * all motion events to the gesture detector.  When the gesture detector
         * actually detects an event, it will use the callbacks you created in the
         * SimpleOnGestureListener to alert your application.
        */

        gestureView.setOnTouchListener(new View.OnTouchListener() {
            float mLastTouchX;
            float mLastTouchY;
            float mPosX;
            float mPosY;
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                gd.onTouchEvent(motionEvent);

                //**********
                final int action = MotionEventCompat.getActionMasked(motionEvent);
                switch (action) {
                    case MotionEvent.ACTION_DOWN: {
                        final int pointerIndex = MotionEventCompat.getActionIndex(motionEvent);
                        final float x = MotionEventCompat.getX(motionEvent, pointerIndex);
                        final float y = MotionEventCompat.getY(motionEvent, pointerIndex);

                        // Remember where we started (for dragging)
                        mLastTouchX = x;
                        mLastTouchY = y;
                        // Save the ID of this pointer (for dragging)
                        mActivePointerId = MotionEventCompat.getPointerId(motionEvent, 0);
                        break;
                    }
                    case MotionEvent.ACTION_MOVE: {
                        // Find the index of the active pointer and fetch its position
                        final int pointerIndex =
                                MotionEventCompat.findPointerIndex(motionEvent, mActivePointerId);

                        final float x = MotionEventCompat.getX(motionEvent, pointerIndex);
                        final float y = MotionEventCompat.getY(motionEvent, pointerIndex);

                        // Calculate the distance moved
                        final float dx = x - mLastTouchX;
                        final float dy = y - mLastTouchY;

                        mPosX += dx;
                        mPosY += dy;
                        moveLog(dx);

                        //invalidate();

                        // Remember this touch position for the next move event
                        mLastTouchX = x;
                        mLastTouchY = y;

                        break;
                    }

                    case MotionEvent.ACTION_UP: {
                        mActivePointerId = INVALID_POINTER_ID;
                        break;
                    }

                    case MotionEvent.ACTION_CANCEL: {
                        mActivePointerId = INVALID_POINTER_ID;
                        break;
                    }

                    case MotionEvent.ACTION_POINTER_UP: {

                        final int pointerIndex = MotionEventCompat.getActionIndex(motionEvent);
                        final int pointerId = MotionEventCompat.getPointerId(motionEvent, pointerIndex);

                        if (pointerId == mActivePointerId) {
                            // This was our active pointer going up. Choose a new
                            // active pointer and adjust accordingly.
                            final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
                            mLastTouchX = MotionEventCompat.getX(motionEvent, newPointerIndex);
                            mLastTouchY = MotionEventCompat.getY(motionEvent, newPointerIndex);
                            mActivePointerId = MotionEventCompat.getPointerId(motionEvent, newPointerIndex);
                        }
                        break;
                    }
                }

                //**********
                return false;
            }
        });
        // END_INCLUDE(init_detector)
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.sample_action) {
            clearLog();
        }
        return true;
    }

    public void clearLog() {
        LogFragment logFragment =  ((LogFragment) getActivity().getSupportFragmentManager()
                .findFragmentById(R.id.log_fragment));
        logFragment.getLogView().setText("");
    }
    public void moveLog(float x) {
        //do whatever you like
    }
}

*

*Image Drag App

Just start a blank app under Android Studio:
1 - Change activity_main.xml to this:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ImageView
        android:id="@+id/image"
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:contentDescription="@string/app_name"
        android:src="@drawable/ic_launcher" />

</RelativeLayout>

and MainActivity.java to this.
(Leave the package name as your own: package com.jorc.move.myapplication;)
package com.jorc.move.myapplication;

import android.annotation.SuppressLint;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private ViewGroup mainLayout;
    private ImageView image;

    private int xDelta;
    private int yDelta;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mainLayout = (RelativeLayout) findViewById(R.id.main);
        image = (ImageView) findViewById(R.id.image);

        image.setOnTouchListener(onTouchListener());
    }

    private View.OnTouchListener onTouchListener() {
        return new View.OnTouchListener() {

            @SuppressLint("ClickableViewAccessibility")
            @Override
            public boolean onTouch(View view, MotionEvent event) {

                final int x = (int) event.getRawX();
                final int y = (int) event.getRawY();

                switch (event.getAction() & MotionEvent.ACTION_MASK) {

                    case MotionEvent.ACTION_DOWN:
                        RelativeLayout.LayoutParams lParams = (RelativeLayout.LayoutParams)
                                view.getLayoutParams();

                        xDelta = x - lParams.leftMargin;
                        yDelta = y - lParams.topMargin;
                        break;

                    case MotionEvent.ACTION_UP:
                        Toast.makeText(MainActivity.this,
                                "thanks for new location!", Toast.LENGTH_SHORT)
                                .show();
                        break;

                    case MotionEvent.ACTION_MOVE:
                        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view
                                .getLayoutParams();
                        layoutParams.leftMargin = x - xDelta;
                        layoutParams.topMargin = y - yDelta;
                        layoutParams.rightMargin = 0;
                        layoutParams.bottomMargin = 0;
                        view.setLayoutParams(layoutParams);
                        break;
                }
                mainLayout.invalidate();
                return true;
            }
        };
    }
}


Q: Dynamic HREF in XSLT using attribute not working as expected I'm newer to XSLTs and I'm struggling a bit with getting this one to format correctly.  I want the output HTML to basically be rows that look like this:
1 : SO090040717 113657 XXX 56371444826

Where "SalesId" is a clickable URL that is formatted (in this example) as basically:
SO090040717
The error appears to be somewhere in the  text?
Sample XML:
<ELEMENT>
    <RECORD>
        <COUNTER>1</COUNTER>
        <DRILLDOWNGROUP>TEST</DRILLDOWNGROUP>
        <SalesId>SO090040717</SalesId>
        <PurchOrderFormNum>113657</PurchOrderFormNum>
        <dataAreaId>XXX</dataAreaId>
        <RecId>5637144826</RecId>
        <TableId>40276</TableId>
    </RECORD>
</ELEMENT>

My, non-working, XSLT:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html"/>
<xsl:template match="/">

<xsl:for-each select="ELEMENT">

<xsl:for-each select="RECORD">

        <xsl:value-of select="COUNTER"/>
        <xsl:text> : </xsl:text>

            <xsl:attribute name="href">
                <xsl:text>Dynamics://</xsl:text>
                <xsl:value-of select="DrillDownGroup"/>
                <xsl:text>?DrillDown_0?tableid=</xsl:text>
                <xsl:value-of select="TableId"/>
                <xsl:text>&field=RecId&value=</xsl:text>
                <xsl:value-of select="RecId"/>
                <xsl:text>&company=</xsl:text>
                <xsl:value-of select="DataAreaId"/>
            </xsl:attribute>
            <xsl:value-of select="SALESID"/>

        <xsl:text>   </xsl:text>
        <xsl:value-of select="PurchOrderFormNum"/>
        <xsl:text>   </xsl:text>
        <xsl:value-of select="dataAreaId"/>
        <xsl:text>   </xsl:text>
        <xsl:value-of select="RecId"/>

</xsl:for-each>

</xsl:for-each>

</xsl:template>
</xsl:stylesheet>

A: A few things:

*

*Case matters so be sure the paths in your select attributes are the same as the source XML.

*  The entity nbsp is not declared so use either a hex or decimal reference. You can create an entity declaration for nbsp if you want. In the example, I used the hex reference. Let me know if you want an example of the declaration for nbsp.

*You can't use literal & unless you're in a CDATA section. It's easier to use & instead. I used & in the example. If you want to use CDATA, do something like: <xsl:text><![CDATA[&company=]]></xsl:text>
XSLT 1.0
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="html"/>
    <xsl:template match="/">

                <xsl:for-each select="ELEMENT">

                        <xsl:for-each select="RECORD">

                                <xsl:value-of select="COUNTER"/>
                                <xsl:text> : </xsl:text>

                                    <xsl:attribute name="href">
                                        <xsl:text>dynamics://</xsl:text>
                                        <xsl:value-of select="DRILLDOWNGROUP"/>
                                        <xsl:text>?DrillDown_0?tableid=</xsl:text>
                                        <xsl:value-of select="TableId"/>
                                        <xsl:text>&field=RecId&value=</xsl:text>
                                        <xsl:value-of select="RecId"/>
                                        <xsl:text>&company=</xsl:text>
                                        <xsl:value-of select="dataAreaId"/>
                                    </xsl:attribute>
                                    <xsl:value-of select="SalesId"/>

                                <xsl:text>   </xsl:text>
                                <xsl:value-of select="PurchOrderFormNum"/>
                                <xsl:text>   </xsl:text>
                                <xsl:value-of select="dataAreaId"/>
                                <xsl:text>   </xsl:text>
                                <xsl:value-of select="RecId"/>

                        </xsl:for-each>

                </xsl:for-each>

    </xsl:template>
</xsl:stylesheet>

Output

1 : SO090040717   113657   XXX   5637144826


Q: Initialization of unique_ptr as a class member variable In C++, Is there a difference between using braces when initializing the unique_ptr and not using them in this code?
// MyClass.h
class MyClass()
{
public:
  MyClass();
private:
  std::unique_ptr<TT> tt{};
}

// MyClass.cpp
MyClass() {
}

Do I even need to initialize the unique_ptr?


Q: Import external js script into Angular app I was trying to implement this widget to my Angular app. For the second part I was able to create a custom js file in my assets folder, create a .d.ts file for it and successfully imported the function in my component.
But for the first part:
<script async src="https://telegram.org/js/telegram-widget.js?5" data-telegram-login="samplebot" data-size="large" data-onauth="onTelegramAuth(user)" data-request-access="write"></script>

If I do it with plain HTML and js, it will fetch from the website and generate a login button. Yet I tried simply pasting it into my component's HTML, it does not get rendered. As it is not a function nor a variable, I am not sure how can I place it into a specific div in the component.
Please help.


Q: Youtube Player fragments inside ViewPager I really need help with this situation. I can't manage to properly create YouTube fragments for each PagerView fragment.
Use case:
~ Let's say I have a PagerView with x fragments, and I want on each of it(in a part of it actually) to be able to play a different video using YouTube API.
This is my YoutubeFragment class which creates an instance of the player
    public class YoutubeFragment extends Fragment {
    private RelativeLayout layoutAbove;
YouTubePlayer mPlayer;
private static final String TAG = "YoutubeFragment";

private static final String API_KEY = DateUtils.getDeveloperKey();

// YouTube video ID
private static String VIDEO_ID;

private MyPlaybackEventListener myPlaybackEventListener = new MyPlaybackEventListener();

public void setVideoID(String id){
    VIDEO_ID = id;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.youtube_layout, container, false);
    YouTubePlayerSupportFragment youTubePlayerFragment = YouTubePlayerSupportFragment.newInstance();

    FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
    transaction.add(R.id.youtube_layout, youTubePlayerFragment).commit();

    youTubePlayerFragment.initialize(API_KEY, new OnInitializedListener() {

        @Override
        public void onInitializationSuccess(Provider provider, final YouTubePlayer player, boolean wasRestored) {

            if (!wasRestored) {
                mPlayer = player;
                mPlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
                mPlayer.setPlaybackEventListener(myPlaybackEventListener);
                mPlayer.cueVideo(VIDEO_ID);
            }
        }

        @Override
        public void onInitializationFailure(Provider provider, YouTubeInitializationResult error) {
            // YouTube error
            String errorMessage = error.toString();
            Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_LONG).show();
            Log.d("errorMessage:", errorMessage);
        }

    });

    return rootView;
}
}

And I use this in my adapter for the PagerView, replacing a view
if (images.size() == 0) {
            images.addAll(eventData.getVideos());
            youtubeFragment = new YoutubeFragment();
            if (views.getViewPager(R.id.vp_images) != null)
                views.getViewPager(R.id.vp_images).setVisibility(View.GONE);

            youtubeFragment.setVideoID(eventData.getYoutube_id());
            android.support.v4.app.FragmentManager fragmentManager = ((FragmentActivity) context).getSupportFragmentManager();
            fragmentManager.beginTransaction()
                    .replace(views.getFrameLayoutid(R.id.youtube_layout), youtubeFragment)
                    //.addToBackStack(null) // added to backstack of supportFragmentManager
                    .commit();
        }

I have to mention that I create the PagerView based on a list with items. I manage to create an instance of the video fragment, but only on the clicked item, but even like this, the video is not being played more than 1 sec. I was careful with padding & other views that might be over the player.
Also, on the next page (that is loaded by the PagerView) I can't event see the YouTube fragment.
Here is the XML file of PagerView fragment(at least the important snippet of it)
<RelativeLayout
    android:id="@+id/relativeProblematicLayout"
    android:contentDescription="@string/contentDescription"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <FrameLayout
            android:id="@+id/youtube_layout"
            android:layout_width="match_parent"
            android:layout_height="@dimen/event_image_height"
            android:visibility="visible" />

    </LinearLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/vp_images"
        android:layout_width="match_parent"
        android:layout_height="@dimen/event_image_height"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true">
    </android.support.v4.view.ViewPager>

    <RelativeLayout
        android:visibility="gone"
        android:id="@+id/viewPagerIndicator"
        android:layout_width="match_parent"
        android:layout_height="20dp"
        android:layout_marginTop="@dimen/standard_1_dp"
        android:layout_marginBottom="@dimen/standard_10_dp"
        android:layout_alignParentBottom="true"
        android:gravity="center">

        <LinearLayout
            android:id="@+id/viewPagerCountDots"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_centerHorizontal="true"
            android:gravity="center"
            android:orientation="horizontal" />
    </RelativeLayout>
</RelativeLayout>


Q: Jump to function definition How can I jump to a function definition using Vim? For example with Visual Assist, I can type Alt+g under a function and it opens a context menu listing the files with definitions.
How can I do something like this in vim?

A: To second Paul's response: yes, ctags (especially exuberant-ctags (http://ctags.sourceforge.net/)) is great.  I have also added this to my vimrc, so I can use one tags file for an entire project:
set tags=tags;/

A: Use gd or gD while placing the cursor on any variable in your program.

*

*gd will take you to the local declaration.

*gD will take you to the global declaration.

more navigation options can be found in here.
Use cscope for cross referencing large project such as the linux kernel.

A: TL;DR:
You can do this using internal VIM functionality but a modern (and much easier) way is to use COC for intellisense-like completion and one or more language servers (LS) for jump-to-definition (and way way more). For even more functionality (but it's not needed for jump-to-definition) you can install one or more debuggers and get a full blown IDE experience.
Best second is to use native VIM's functionality called define-search but it was invented for C preprocessor's #define directive and for most other languages requires extra configuration, for some isn't possible at all (also you miss on other IDE features). Finally, a fallback to that is ctags.
Quick-start:

*

*install vim-plug to manage your VIM plug-ins

*add COC and (optionally) Vimspector at the top of ~/.vimrc:
call plug#begin()
Plug 'neoclide/coc.nvim', {'branch': 'release'}
Plug 'puremourning/vimspector'
call plug#end()

" key mappings example
nmap <silent> gd <Plug>(coc-definition)
nmap <silent> gD <Plug>(coc-implementation)
nmap <silent> gr <Plug>(coc-references)
" there's way more, see `:help coc-key-mappings@en'

*call :source $MYVIMRC | PlugInstall to reload VIM config and download plug-ins

*restart vim and call :CocInstall coc-marketplace to get easy access to COC extensions

*call :CocList marketplace and search for language servers, e.g.:

*

*type python to find coc-jedi,

*type php to find coc-phpls, etc.

*(optionally) see :h VimspectorInstall to install additional debuggers, e.g.:

*

*:VimspectorInstall debugpy,

*:VimspectorInstall vscode-php-debug, etc.

Full story:
Language server (LS) is a separate standalone application (one for each programming language) that runs in the background and analyses your whole project in real time exposing extra capabilities to your editor (any editor, not only vim). You get things like:

*

*namespace aware tag completion

*jump to definition

*jump to next / previous error

*find all references to an object

*find all interface implementations

*rename across a whole project

*documentation on hover

*snippets, code actions, formatting, linting and more...

Communication with language servers takes place via Language Server Protocol (LSP). Both nvim and vim8 (or higher) support LSP through plug-ins, the most popular being Conquer of Completion (COC).
List of actively developed language servers and their capabilities is available on Lang Server website. Not all of those are provided by COC extensions. If you want to use one of those you can either write a COC extension yourself or install LS manually and use the combo of following VIM plug-ins as alternative to COC:

*

*LanguageClient - handles LSP

*deoplete - triggers completion as you type

Communication with debuggers takes place via Debug Adapter Protocol (DAP). The most popular DAP plug-in for VIM is Vimspector.
Language Server Protocol (LSP) was created by Microsoft for Visual Studio Code and released as an open source project with a permissive MIT license (standardized by collaboration with Red Hat and Codenvy). Later on Microsoft released Debug Adapter Protocol (DAP) as well. Any language supported by VSCode is supported in VIM.
I personally recommend using COC + language servers provided by COC extensions + ALE for extra linting (but with LSP support disabled to avoid conflicts with COC) + Vimspector + debuggers provided by Vimspector (called "gadgets") + following VIM plug-ins:
call plug#begin()
Plug 'neoclide/coc.nvim'
Plug 'dense-analysis/ale'
Plug 'puremourning/vimspector'
Plug 'scrooloose/nerdtree'
Plug 'scrooloose/nerdcommenter'
Plug 'sheerun/vim-polyglot'
Plug 'yggdroot/indentline'
Plug 'tpope/vim-surround'
Plug 'kana/vim-textobj-user'
  \| Plug 'glts/vim-textobj-comment'
Plug 'janko/vim-test'
Plug 'vim-scripts/vcscommand.vim'
Plug 'mhinz/vim-signify'
call plug#end()

You can google each to see what they do.
Native VIM jump to definition:
If you really don't want to use Language Server and still want a somewhat decent jump to definition with native VIM you should get familiar with :ij and :dj which stand for include-jump and definition-jump. These VIM commands let you jump to any file that's included by your project or jump to any defined symbol that's in any of the included files. For that to work, however, VIM has to know how lines that include files or define symbols look like in any given language. You can set it up per language in ~/.vim/ftplugin/$file_type.vim with set include=$regex and set define=$regex patterns as described in :h include-search, although, coming up with those patterns is a bit of an art and sometimes not possible at all, e.g. for languages where symbol definition or file import can span over multiple lines (e.g. Golang). If that's your case the usual fallback is ctags as described in other answers.

A: Use ctags.  Generate a tags file, and tell vim where it is using the :tags command.  Then you can just jump to the function definition using Ctrl-]
There are more tags tricks and tips in this question.

A: If everything is contained in one file, there's the command gd (as in 'goto definition'), which will take you to the first occurrence in the file of the word under the cursor, which is often the definition.

A: As Paul Tomblin mentioned you have to use ctags.
You could also consider using plugins to select appropriate one or to preview the definition of the function under cursor.
Without plugins you will have a headache trying to select one of the hundreds overloaded 'doAction' methods as built in ctags support doesn't take in account the context - just a name.
Also you can use cscope and its 'find global symbol' function. But your vim have to be compiled with +cscope support which isn't default one option of build.
If you know that the function is defined in the current file, you can use 'gD' keystrokes in a normal mode to jump to definition of the symbol under cursor.
Here is the most downloaded plugin for navigation
http://www.vim.org/scripts/script.php?script_id=273
Here is one I've written to select context while jump to tag
http://www.vim.org/scripts/script.php?script_id=2507

A: Another common technique is to place the function name in the first column. This allows the definition to be found with a simple search.
int
main(int argc, char *argv[])
{
    ...
}

The above function could then be found with /^main inside the file or with :grep -r '^main' *.c in a directory. As long as code is properly indented the only time the identifier will occur at the beginning of a line is at the function definition.
Of course, if you aren't using ctags from this point on you should be ashamed of yourself! However, I find this coding standard a helpful addition as well.

A: 1- install exuberant ctags. If you're using osx, this article shows a little trick:
http://www.runtime-era.com/2012/05/exuberant-ctags-in-osx-107.html
2- If you only wish to include the ctags for the files in your directory only, run this command in your directory:
ctags -R

This will create a "tags" file for you.
3- If you're using Ruby and wish to include the ctags for your gems (this has been really helpful for me with RubyMotion and local gems that I have developed), do the following:
ctags --exclude=.git --exclude='*.log' -R * `bundle show --paths`

credit: https://coderwall.com/p/lv1qww
(Note that I omitted the -e option which generates tags for emacs instead of vim)
4- Add the following line to your ~/.vimrc
set autochdir
set tags+=./tags;

(Why the semi colon: http://vim.wikia.com/wiki/Single_tags_file_for_a_source_tree )
5- Go to the word you'd like to follow and hit ctrl + ] ; if you'd like to go back, use ctrl+o (source: https://stackoverflow.com/a/53929/226255)

A: g* does a decent job without ctags being set up.
That is, type g,* (or just * - see below) to search for the word under the cursor (in this case, the function name). Then press n to go to the next (or Shift-n for previous) occurrence.
It doesn't jump directly to the definition, given that this command just searches for the word under the cursor, but if you don't want to deal with setting up ctags at the moment, you can at least save yourself from having to re-type the function name to search for its definition.
--Edit--
Although I've been using g* for a long time, I've recently discovered two shortcuts for these shortcuts!
(a) * will jump to the next occurrence of the word under the cursor. (No need to type the g, the 'goto' command in vi).
(b) # goes to the previous occurrence, in similar fashion.
N and n still work, but '#' is often very useful to start the search initially in the reverse direction, for example, when looking for the declaration of a variable under the cursor.

A: Install cscope. It works very much like ctags but more powerful. To go to definition, instead of Ctrl + ], do Ctrl + \ + g. Of course you may use both concurrently. But with a big project (say Linux kernel), cscope is miles ahead.

A: After generating ctags, you can also use the following in vim:
:tag <f_name>

Above will take you to function definition.


Q: .htaccess redirect url with controller name for MVC application i am trying to build a mvc like application and i cant figure out the right .htaccess i need.
I want something like:
RewriteRule ^(.*)/(.*)/(.*)$ $1.php?action=$2&n=$3 [L]

so  i can access the file that contains the proper controller and two get variables from the url. The code above doesnt work, i have been around this for 2 days now and i cant find anything like what i need anywhere.What happens there is that the 3 variables are required at the url in order to work, and thats not what i want. Sugestions?

A: Most frameworks use a Front-Controller instead of mod_rewrite. This controller splits apart the URL and routes accordingly.
While not the only solution, this is more flexible. Consider when you have the URL plugin/controller/view/id or controller/view/param1/param2.
If you want to adopt the Front-Controller architecture, I'd recommend using FallbackResource to keep your htaccess file trim.
FallbackResource /front-controller.php

From there it should be fairly straightforward to split apart the url with functions like parse_url().

A: use this:
RewriteRule ^([^\./]*)$ index.php?route=$1 [L,NC,QSA]

then
$route = explode('/', $_GET['route']);
$id = array_pop();
$controller = array_shift($route);
$method = implode('_', $route);

$controller = new $controller;
$controller->$method();


Q: springMVC+mybatis+mysql can't insert blob I use the mybatis and springMVC,and the database is the MySql,I know the configuration of the SpringMVC and mybatis are right ,but when I want to write a demo of the blob ,it does't work,this is the code.
FileMapper.java
public interface FileMapper {
    //插入文件
    int insert(ContractFile file);
    //读取文件
    ContractFile selectByFileName(String fileName);
}

FileMapper.xml
<insert id="insert" parameterType="com.beebank.test.model.ContractFile">
    insert into t_base_file
    (fileId, fileName, fileContent)
    values
    (#{fileId,jdbcType=INTEGER},
    #{fileName,jdbcType=VARCHAR},
    #{fileContent,jdbcType=BLOB})
</insert>

ContractFile.java
public class ContractFile {
    private Integer fileId;
    private String fileName;
    private byte[] fileContent;
    // getter() and setter()...
}

TestFile.java(the main code)
String fileName = input.nextLine();
File file = new File(fileUrl + fileName);
FileInputStream fis = new FileInputStream(file);
byte[] fileContent = new byte[(int)file.length()];
fis.read(fileContent);
ContractFile contractFile=new ContractFile();
contractFile.setFileId(1);
contractFile.setFileName(fileName);
contractFile.setFileContent(fileContent);
mapper.insert(contractFile);
fis.close();

This is my first time to ask and my English is not good, so Hope we learn from each other。


Q: Checking for missing values in CSV I have a CSV file that counts the data in a timestamp every 15 min.
I need tried to figure out how to see, if there is missing any of the 15 min in the file. But i cant get the code to work 100%.
hope you can help!
First i geathered the data from csv and set it in timestamp. The format is yyyy-mm-dd-hh:mm.
lst = list()

with open("CHFJPY15.csv", "r") as f:
    f_r = f.read()

sline = f_r.split()

for line in sline:
    parts = line.split(',')
    date = parts[0]
    time = parts[1]
    closeingtime = parts[5]

    timestamp = date + ' ' + time + ' ' + closeingtime
    lst.append(timestamp)

print(lst, "liste")

(All credits to BillBell for the code below)
Here try creating a consistently formatted list of data items.
from datetime import timedelta
interval = timedelta(minutes=15)
from datetime import datetime
current_time = datetime(2015,12,9,19,30)
data = []
omits = [3,5,9,11,17]
for i in range(20):
    current_time += interval

    if i in omits:
        continue
    data.append(current_time.strftime('%y.%m.%d.%H:%M')+' 123.456')

Now I read through the dates subtracting each from it predecessor. I set the first 'predecessor', which I call previous to now because that's bound to differ from the other dates.
I split each datum from the list into two, ignoring the second piece. Using strptime I turn strings into dates. Dates can be subtracted and the differences compared.
previous = datetime.now().strftime('%y.%m.%d.%H:%M')
first = True
for d in data:
    date_part, other = d.split(' ')
    if datetime.strptime(date_part, '%y.%m.%d.%H:%M') - datetime.strptime(previous, '%y.%m.%d.%H:%M') != interval:
        if not first:
            'unacceptable gap prior to ', date_part
        else:
            first = False
    previous = date_part

Hope you can see the problem.


Q: Can I show an image with BIOS interrupts or assembly? I am trying write a simple bootloader, and I want to show an image when my bootloader starts. How can I do this?
I am using assembly with nasm assembler.

A: Depends on what kind of video mode you want use and what to do with the picture. But I think the resources below by almost 100% to answer your questions and create new ones).
PC Games Programmers Encyclopedia book: archive Zip
PC Games Programmers Encyclopedia part source code
File Description PCGPE
Good Luck!


Q: shader storage block length returns zero or less I am getting zero or less when I try to get the length of an indeterminate-length array in a shader storage block.
Setting up the storage:
geometryBuffer = ByteBuffer.allocateDirect(12* 4)
    .order(ByteOrder.nativeOrder());

geometryBuffer.putFloat(1f);
geometryBuffer.putFloat(0.25f);
geometryBuffer.putFloat(0.5f);
geometryBuffer.putFloat(0.75f);
geometryBuffer.putFloat(1.1f);
geometryBuffer.putFloat(0.35f);
geometryBuffer.putFloat(0.6f);
geometryBuffer.putFloat(0.85f);
geometryBuffer.putFloat(1.2f);
geometryBuffer.putFloat(0.45f);
geometryBuffer.putFloat(0.7f);
geometryBuffer.putFloat(0.95f);

geometryBuffer.flip();

geometryBufferId = GL15.glGenBuffers();
GL15.glBindBuffer(GL43.GL_SHADER_STORAGE_BUFFER, geometryBufferId);
System.out.println("bb" + GL11.glGetError());
GL15.glBufferData(GL43.GL_SHADER_STORAGE_BUFFER, geometryBuffer, GL15.GL_STATIC_DRAW);
System.out.println("bd" + GL11.glGetError());
GL30.glBindBufferRange(GL43.GL_SHADER_STORAGE_BUFFER, 0, geometryBufferId, 0, 36);
System.out.println("br" + GL11.glGetError());
GL15.glBindBuffer(GL43.GL_SHADER_STORAGE_BUFFER, 0);

The frag shader:
#version 430

out vec4 outColour;

layout(std430, binding=0) buffer Geometry {
    vec4 a;
    vec4 myVec[];
} ;

void main() {
    // if (myVec[0].y == 0.35) {
    if (myVec.length() == -1) {
        outColour = vec4 (1,0,0,1);
    } else {
        outColour = vec4(0,0,1,1);
    }
}

I expect length to be 2 but the length returned in this example is -1. I can retrieve the values in the array as the test if (myVec[0].y == 0.35) also returns red.
According to https://www.opengl.org/wiki/Interface_Block_(GLSL) and the GLSL spec v4.5 section 4.1.9, the size is calculated at runtime from the size of the buffer or range, minus all the sized components in the block and then divided by the size of an individual array entry. What I seem to be getting is zero minus the number of vec4 units before the indeterminate storage in the block.
An alternative would be to pass a uniform with the array size, but why doesn't length() return the correct value? I'm running on a GTX660M

A: I cant claim the credit for this as it was provided by someone on a GL forum, but to close this question out, the answer is that referencing myVec.length() is not enough, you have to actually reference the array so this works :
if (myVec.length() == 2 && myVec[0].y == 0.35) {
...

Without actually referencing an array entry in the shader, the compiler presumably optimizes it out, thus returning a length of zero at runtime.


Q: __attribute__((OS_main)) results in strange behaviour in AVR I don't know how to precisely described the error I am seeing. If I set up my port register in main() everything works as intended. However if I try to do it in a function, the program halts.
main.c:
__attribute__((OS_main)) int main(void);
int main(void) {
    DDRD = 0xF0;
    PORTD = 0xF0;
    led( LED_GREEN, true );
    while( true );
}

This turns on the green LED. However if I move the port setup to a seperate function nothing happens, like so:
__attribute__((OS_main)) int main(void);
int main(void) {
    hwInit();
    led( LED_GREEN, true );
    while( true );
}

The culprit seems to be the attribute line because if I comment it out the second example works as expected. My problem is understanding why, since as I understand it the OS_main attribute should only tell the compiler that it should not store any registers upon entry or exit to the function. Is this not correct?

A: The following was compiled with avr-gcc 4.8.0 under ArchLinux. The distribution should be irrelevant to the situation, compiler and compiler version however, may produce different outputs. The code:
#include <avr/io.h>

#define LED_GREEN PD7
#define led(p, s) { if(s) PORTD |= _BV(p); \
                else PORTD  &= _BV(p); }

__attribute__((OS_main)) int main(void);
__attribute__((noinline)) void hwInit(void);

void hwInit(void){
    DDRD = 0xF0;
}

int main(void){

    hwInit();
    led(LED_GREEN, 1);

    while(1);
}

Generates:
000000a4 <hwInit>:
  a4:   80 ef           ldi r24, 0xF0   ; 240
  a6:   8a b9           out 0x0a, r24   ; 10
  a8:   08 95           ret

000000aa <main>:
  aa:   0e 94 52 00     call    0xa4    ; 0xa4 <hwInit>
  ae:   5f 9a           sbi 0x0b, 7 ; 11
  b0:   ff cf           rjmp    .-2         ; 0xb0 <main+0x6>

when compiled with
avr-gcc -Wall -Os -fpack-struct -fshort-enums -std=gnu99 -funsigned-char -funsigned-bitfields -mmcu=atmega168 -DF_CPU=1000000UL -MMD -MP -MF"core.d" -MT"core.d" -c -o "core.o" "../core.c" and linked accordingly.
Commenting __attribute__((OS_main)) int main(void); from the above sources has no effect on the generated assembly. Curiously, however, removing the noinline directive from hwInit() has the effect of the compiler inlining the function into main, as expected, but the function itself still exists as part of the final binary, even when compiled with -Os.
This leads me to believe that your compiler version/arguments to the compiler are generating some assembly which is not correct. If possible, can you post the disassembly for the relevant areas for further examination?
Edited late to add two contributions, second of which resolves the problem at hand:
Hanno Binder states: "In order to remove those 'unused' functions from the binary you would also need -ffunction-sections -Wl,--gc-sections."
Asker adds [paraphrased]: "I followed a tutorial which neglected to mention the avr-objcopy step to create the hex file. I assumed that compiling and linking the project for the correct target was sufficient (which it for some reason was for basic functionality). After having added an avr-objcopy step to generate the file everything works."


Q: Performance: list all keys from hdf5 file with pandas Is it normal that that it takes so long to obtain all present keys in a hdf5 file?
Code Sample:
start = time.time()
store = pd.HDFStore(filepath)
print(time.time() - start)
0.0

start = time.time()
a = store.keys()
print(time.time() - start)
23.874846696853638

len(a)
80

start = time.time()
store.select(key="/data/table1") # the next table would be /data/table2
print(time.time() - start)

0.062399864196777344

All keys are 'tables' (i.e. not fixed).
There are about 80 keys present in the file.
The entire size of the  .h5 file is 348 MB. Each table has approx. the same size (after loading to a pandas.DataFrame) of 2.6 MB.
pandas v.0.20.1
tables v.3.2.2.
I am wondering if the key hierarchy is an issue: all in data/table[X] instead of directly into table[X]?

A: I have the same issue.  It appears the cause is related to the way tables checks every single node value to create a list of keys.  I've raised this to pandas dev.
If you want to check whether a key is in the store then
store.__contains__(key)

will do the job and is much faster.
https://github.com/pandas-dev/pandas/issues/17593


Q: Iterating Properties I've been doing some research on iterating properties, and have come up with a basic solution that seems to work, but doesn't quite do what I'm looking for. I'm calling a WebService method which returns an PeopleSoft object with a large amount of properties. Each one of these properties returns some obscure type of object that would take too much time to typecast individually. My code works and it iterates the properties, but it doesn't display the values. Here is the auto generated code visual studio makes for one of the properties.
public SETIDTypeShape5 SETID {
        get {
            return this.sETIDField;
        }
        set {
            this.sETIDField = value;
        }
    }

I'm guessing that the SETIDTypeShape5 doesn't have a proper ToString() method, because when it gets printed, all it shows is SETIDTypeShape5. I know it has a Value property associated with it, but is there any way to access that value? This is the code I have so far, and what some of the output looks like.
                Type getType = idResponseTypeShape.GetType();

            foreach (PropertyInfo info in getType.GetProperties(BindingFlags.Instance | BindingFlags.Public))
            {
                String name = info.Name;
                object value = info.GetValue(idResponseTypeShape, null);
                Debug.WriteLine("{0} = {1}", name, value);
            }

SETID = VendorMod.edu.clcillinois.fs3.SETIDTypeShape5
VENDOR_ID = VendorMod.edu.clcillinois.fs3.VENDOR_IDTypeShape5
VENDOR_NAME_SHORT = VendorMod.edu.clcillinois.fs3.VENDOR_NAME_SHORTTypeShape3
VNDR_NAME_SHRT_USR = VendorMod.edu.clcillinois.fs3.VNDR_NAME_SHRT_USRTypeShape1
VNDR_NAME_SEQ_NUM = VendorMod.edu.clcillinois.fs3.VNDR_NAME_SEQ_NUMTypeShape1
NAME1 = VendorMod.edu.clcillinois.fs3.NAME1TypeShape3
NAME2 = VendorMod.edu.clcillinois.fs3.NAME2TypeShape1
VENDOR_STATUS = VendorMod.edu.clcillinois.fs3.VENDOR_STATUSTypeShape1

I'm not sure if I'm explaining it thoroughly, but I'm basically looking for a way to get the Value of each one of those TypeShapes, without manually casting each one to the correct object explicitly. Is this even possible?


Q: How to set a specific function to every widget while using loops in tkinter from Python 3? I'm exploring tkinter from Python 3 and I have a problem with using loops to create widgets containing functions. I have this code:
from tkinter import *

def test(no, button_name, event=None):
    def callback():
        print(button_name)
    return callback

root = Tk()
list_of_buttons = 'Button 1, Button 2, Button 3, Button 4, Button 5'.split(', ')
for no, i in enumerate(list_of_buttons):
    list_of_buttons[no] = Button(root, text=i, command=test(no=no, button_name=i))
    list_of_buttons[no].grid(row=no, column=0)
root.mainloop()

This code Works good, and the result is when you press each button, it prints its's own name. But, I think buttons are ugly, even with ttk, so I am planning to make some customized screen, with labels and images instead of buttons. Then I tried to change the Button widget to a Label, in this way:
list_of_buttons[no] = Label(root, text=i)
list_of_buttons[no].bind('<Button-1>', test(no=no, button_name=i))

Then an error appears:

TypeError: callback() takes 0 positional arguments but 1 was given

I tired to fixed using lambda but when i use it, when I press the label it just doesn't work:
list_of_buttons[no].bind('<Button-1>', lambda event: test(no=no, button_name=i))

I also tried calling the callback function like this:
return callback()

But this only print 'Button 5'. Is there any way to do the same with the labels that needs event bindings?

A: Modify your callback def to:
def callback(event=None):
    print(button_name)

This is because the callback that tkinter calls is actually the callback function, not the test function. Test function does not need event=None.


Q: Apache or Varnish reverse proxy to subfolder I have a domain, site.example.com and I would like to reverse-proxy a web app in site2.example.com/subfolder. Users should access that app by using site.example.com/subfolder. Is it possible? I would like to use Apache or even better varnish (without hitting Apache) to do the redirect.
Thank you

A: I would use Apache unless there you have a high traffic site. This can be done using mod_proxy with ProxyPass and ProxyPassReverse.
It will end up being something like on the site.example.com server:
ProxyRequests On
ProxyVia On
ProxyPass /subfolder http://site2.example.com/subfolder
ProxyPassReverse /subfolder http://site2.example.com/subfolder


Q: Laravel eloquent is very slow when joining two models There is a model Invoice which equals to a purchase basket and model InvoiceItem which stores items inside a specific invoice. The model invoice has status field, if its value is 2999 and someone has verified it, it is successful. I need to get invoice items which are sold. Here is codes:
class Invoice extends Model
{

    protected $fillable = [];
    protected $table = 'payment_invoices';

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    public function scopeSuccessful($query)
    {
        return $query->where('status', 2999)->where('verified_at', '<>', null);
    }
}

and
class InvoiceItem extends Model
{

    protected $fillable = [];
    protected $table = 'payment_invoice_items';

    public function invoice()
    {
        return $this->belongsTo(Invoice::class, 'invoice_id');
    }

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    public function vendor()
    {
        return $this->belongsTo(Vendor::class, 'vendor_id');
    }

    public function scopeNotDeleted($query)
    {
        return $query->where('deleted_at', null);
    }

    public function scopeSold($query)
    {
        return $query->notDeleted()->whereHas('invoice', function ($q) {
            $q->successful();
        });
    }
}

The following statement

InvoiceItem::sold()->take(10)->get()

returns 10 sold items but it is very slow. it takes about 4 seconds to retrieve the information while the query
select *
from laravel.payment_invoice_items pii
join laravel.payment_invoices pi
    on pi.id = pii.invoice_id
    and pii.deleted_at isnull
    and pi.status=2999
    and pi.verified_at notnull
limit 10

takes about 800 milliseconds. Eloquent is very inefficient. Is there any solution to use the eloquent and get the same efficiency here?


Q: How to remove StartMenu shortcut using C# How can I remove a shortcut folder from Startmenu in Windows using C#, I know how to do that using this code:
    private void RemoveShortCutFolder(string folder)
    {
        folder = folder.Replace("\"  ", "");
        folder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.StartMenu), folder);
        try
        {
            if (System.IO.Directory.Exists(folder))
            {
                System.IO.Directory.Delete(folder, true);
            }
            else
            {
            }
        }
        catch (Exception)
        {
        }
    }

But the problem that I need to remove one shortcut folder in ALL USERS folder, not the current logged user. Environment.SpecialFolder.StartMenu gives me the current user not all users folder.
Any idea,
Thanks,

A: If you don't mind a little Win32, you can use SHGetSpecialFolderPath.
[DllImport("shell32.dll")]
static extern bool SHGetSpecialFolderPath(IntPtr hwndOwner, StringBuilder lpszPath, CSIDL nFolder, bool fCreate);

enum CSIDL
{
  COMMON_STARTMENU = 0x0016,
  COMMON_PROGRAMS = 0x0017
}

static void Main(string[] args)
{
  StringBuilder allUsersStartMenu = new StringBuilder(255);
  SHGetSpecialFolderPath(IntPtr.Zero, allUsersStartMenu, CSIDL.COMMON_PROGRAMS, false);
  Console.WriteLine("All Users' Start Menu is in {0}", allUsersStartMenu.ToString());
}

A: Use Environment.SpecialFolder.CommonStartMenu instead of StartMenu.

A: Thanks guys, I found the answer:
    private void RemoveShortCutFolder(string folder)
    {
        folder = folder.Replace("\"  ", "");
        folder = Path.Combine(Path.Combine(Path.Combine(Environment.GetEnvironmentVariable("ALLUSERSPROFILE"), "Start Menu"), "Programs"), folder);
        try
        {
            if (System.IO.Directory.Exists(folder))
            {
                System.IO.Directory.Delete(folder, true);
            }
            else
            {
            }
        }
        catch (Exception)
        {
        }
    }


Q: Qt Reources - Add and Read JSON file I need a JSON file to save some info about my app and read it sometimes. And because my app runs in Ubuntu and Windows, I added it to Qt Resources...
To access the JSON file I tried:
QFile file(":/files/files/my_settings.json");
qDebug() << "settings file: " << endl << file.readAll();

A: First you need to call QFile::open() before calling readAll().
Second point, you can not write to file in Qt Resources.
If you want a cross platform way to save settings and such for your software take a look at QStandardPaths::writableLocation() and QSettings.
Note that QSettings won't handle JSON out of the box, but it will handle all the read/write to file for you (and the file format and location for you if you took car of setting QCoreApplication::applicationName and QCoreApplication::organizationName).


Q: Defining self-referential structs in a C header file (.h)? I'm trying to create a struct used in two .c source files to make a simple linked list structure. I thought it would save time to create a struct in the header file, however, I get a 'parse error before *' error.
This is the code I'm using:
/*
 * Structures.h
 *
 *  Created on: Dec 17, 2011
 *      Author: timgreene
 */

#ifndef STRUCTURES_H_
#define STRUCTURES_H_

typedef struct list_struct {
    int data;
    struct list_struct* next;
    struct list_struct* prev;
} list;

#endif /* STRUCTURES_H_ */

Edit: I did originally omit a detail that is, I'm actually compiling with xcc from the XMOS toolchain. I still don't understand that there would be a difference in .h file syntax.
Could it be a compilation flag I'm using?
Here's the console printout:
xcc -O0 -g -Wall -c -MMD -MP -MF"filter.d" -MT"filter.d filter.o " -target=XC-1A -o filter.o "../filter.xc"
In file included from ../filter.xc:15:
Structures.h:13: error: parse error before '*' token
Structures.h:14: error: parse error before '*' token
Structures.h:15: error: parse error before '}' token

A: Looking around in some of the XMOS documentation, it seems the problem is that XC is not C, it's just a C-like language.  From the "XC Programming Guide":

XC provides many of the same capabilities as C, the main omission being support
  for pointers.

...which explains why it doesn't accept the next and prev pointers in your structure.
Apparently xcc lets you mix C and XC sources, though, so if you were to limit your use of the structure to C code it should work.  From the "XCC Command-Line Manual", it appears that anything with a .xc extension (as in the command line you used above) is treated as XC, rather than C, source code by default.  This can be overridden by placing the option -xc before the C sources on the command line and -x afterward (or just rename the files with a .c extension).
If you must use XC rather than C, you may need to find another way of doing things (arrays, maybe?).

A: Try using a forward declaration of struct list_struct:
struct list_struct;
typedef struct list_struct {
    int data;
    struct list_struct* next;
    struct list_struct* prev;
} list;

Perhaps your compiler doesn't recognize the identifier in the middle of its own definition, I'm not sure what the standards say about that (if anything).
For those that don't already know, this is also the way to deal with circular dependencies in struct definitions:
struct a;
struct b;

struct a {
    int x;
    struct b *y;
};

struct b {
    int x;
    struct a *y;
};


Q: What is the DataGrid MappingName for a non DataTable DataSource? I am able to Bind my DataGrid in .NET 3.5 CF to a List() but I am unable to format the columns by specifying their width. Below is the code that looks like it should work but does not.  I am pretty sure that I am not setting the MappingName correctly as all tutorials tell you to set it to the name of your DataTable but I am not binding to a DataTable so I am not quiet sure what to do.
            grdBatch.DataSource = InventoryItems;

        DataGridTableStyle tableStyle = new DataGridTableStyle();
        tableStyle.MappingName = InventoryItems.ToString();
        DataGridTextBoxColumn tbcName = new DataGridTextBoxColumn();
        tbcName.Width = 400;
        tbcName.MappingName = "SERIAL_ID";
        tbcName.HeaderText = "SERIAL_ID";
        tableStyle.GridColumnStyles.Add(tbcName);
        grdBatch.TableStyles.Clear();
        grdBatch.TableStyles.Add(tableStyle);

grdBatch is a DataGrid and InventoryItems is a List of POCOS(Plain old C# Objects).

A: Change:
 tableStyle.MappingName = InventoryItems.ToString();

to
tableStyle.MappingName = InventoryItems.GetType().Name;


Q: debugging a rails controller making too many queries I have a rails application that about 3 years old, and I'm having a problem with my pages making too many queries. Every page that loads has several lines that look like this:
ReqTdsLink Columns (1.0ms)   SHOW FIELDS FROM `req_tds_links`

what sort of method call would cause this output in the log? I can't find any before filters, or anything else in the application controller that could be causing this, but I have yet to check all the views (which are astronomical in number) I'd like to have something specific to look for before i start manually scanning each file for something that might cause this.
thanks,
-C

A: Are you running in development or production mode?
SHOW FIELDS FROM foo is done by your model, as you noted, so it knows which accessor methods to generate.
In development mode, this is done every request so you don't need to reload your webserver so often, but in production mode this information should be cached, even if you're running a three year old version of Rails.

A: This is called by ActiveRecord reading the attributes of a model from your database.  It won't happen multiple times in production, but in development mode, Rails queries the table each time to pick up on any changes that may have occurred.

A: If you have this kind of problem again and need to track down how a query is being called I would suggest the Query Trace plugin: http://github.com/ntalbott/query_trace/tree/master.  It adds a stack trace to the log for every SQL query.  Very handy.

A: This line actually comes from calling the model, i had an array in the application controller that looked like [Model1, Model2, Model3] and I changed it to look like ['Model1','Model2', 'Model3'] and that fixed all the extra calls.


Q: Рекурсивные вызовы в qucksort Не понимаю, как происходят рекурсивные вызовы для сортировки подмассивов
Происходит ли это так ? : вызывается рекурсивная функция и она остается не доделанной , и вызывается следующая до тех пор , пока эти вызовы не закончатся , а потом возвращаемся на предыдущие уровни рекурсии доделывать предыдущие вызовы ?
Так ли это ? Если нет, то в каких случаях подобное происходит. И как тогда работает рекурсия в qsort ?
  Вот код , где рекурсивная функция , про которую спросил выше
template<class T>
void quickSortR(T* a, long N) {
// На входе - массив a[], a[N] - его последний элемент.

  long i = 0, j = N-1;      // поставить указатели на исходные места
  T temp, p;

  p = a[ N>>1 ];        // центральный элемент

  // процедура разделения
  do {
    while ( a[i] < p ) i++;
    while ( a[j] > p ) j--;

    if (i <= j) {
      temp = a[i]; a[i] = a[j]; a[j] = temp;
      i++; j--;
    }
  } while ( i<=j );

  // рекурсивные вызовы, если есть, что сортировать
  if ( j > 0 ) quickSortR(a, j);
  if ( N > i ) quickSortR(a+i, N-i);
}


Q: PHP file read not working On a server I have the file some.php. I try to read the contents using file_get_content and fread. Both these don't read my content.
If I try some other URL like yahoo.com, these functions are reading the contents. Why does this happen?
$my_conetn =  file_get_contents("http://example.com");
echo $my_conetn;

The above snippet is not working.
$handle = fopen($filename, "r");
$contents = fread($handle, 20);
echo $contents;
fclose($handle);

Also the above snippet is not working.
How to check my server? Is there any file read operation locked or not?
edit: I am not sure, but it is only my server file that can't be read. I can read the other server links. So I contact my hosting provider, then I get back to you guys/gals.

A: When using file functions to access remote files (paths starting with http:// and similar protocols) it only works if the php.ini setting allow_url_fopen is enabled.
Additionally, you have no influence on the request sent. Using CURL is suggested when dealing with remote files.
If it's a local file, ensure that you have access to the file - you can check that with is_readable($filename) - and that it's within your open_basedir restriction if one is set (usually to your document root in shared hosting environments).
Additionally, enable errors when debugging problems:
ini_set('display_errors', 'on');
error_reporting(E_ALL);


Q: How to rewrite CSS Grid declaration w/ grid areas for IE11 I have a handy Container component that defines a grid that wraps all children within the middle column, which serves as a max-width container. This component has the option of specifying the child item to break that max-width container and start at the first column and end at the last column.
See this blog post for further explanation: https://cloudfour.com/thinks/breaking-out-with-css-grid-layout/
See this Codepen for example:
https://codepen.io/tylersticka/full/wdmymG/
I was confident that'd the old IE 10 and IE 11 spec would have properties to cover the newer spec's properties but I haven't had any luck with in when testing in IE 11. What syntax am I missing or do I need to modify to replicate grid-areas in IE 11?
.grid-container {
  display: -ms-grid;
  display: grid;

  -ms-grid-columns: [full-start] minmax(0, 1fr) [main-start] minmax(0, 1120px) [main-end] minmax(0, 1fr)
[full-end];

  grid-template-columns:
    [full-start] minmax(0, 1fr) [main-start] minmax(0, 1120px) [main-end] minmax(0, 1fr) [full-end];

  > * {
    grid-column: main;
    padding: 0 16px;
  }
}

.full-width {
  grid-column: full;
}

Sources:
https://css-tricks.com/css-grid-in-ie-debunking-common-ie-grid-misconceptions/
https://css-tricks.com/css-grid-in-ie-css-grid-and-the-new-autoprefixer/
https://autoprefixer.github.io/


Q: React Router v4 Group of Router I want to create a Route Group to validate each route with the first Component. But it may not be possible. Because React read just the first group, I also tried it with React.Fragment, but the same thing happens
I created a Group of Routes:
import React from 'react';
import {Route} from 'react-router-dom';
import _ from 'lodash';

export const PathGroup = (pathGroup, sadas) => {
    const Template = pathGroup.template;

    return (
        { _.map(pathGroup.children, (pathRoute, key) => {
            const { component, path, exact, ...another } = pathRoute.props;
            return (
                <Route
                    exact
                    path={path}
                    key={key}
                    render={ (route) => <Template
                        component={component}
                        route={route}
                        {...another}
                    />}
                />
            )
        }) }
    );
};

export const Path = (path) => {
    return <React.Fragment/>
};

To print the routes by group in this way:
render() {
    const user = this.props.user;
    if (!user.verified) { return(
Loading...
); }
    return (
        <BrowserRouter>
            <Switch>
                <PathGroup template={PublicLayout} >
                    <Path exact path='/contact' component={Contact}  user={user}/>
                    <Path exact path='/' component={Home}  user={user} />
                </PathGroup>
                <PathGroup template={PrivateLayout} verify={this.props.user.logged}  redirectFalse="/projects" >
                    <Path exact path='/profile' component={Profile}  user={user} />
                    <Path exact path='/posts' component={Posts}  user={user} />
                    <Path exact path='/posts/:idPost' component={Post}  user={user} />
                </PathGroup>
                <PathGroup template={Login} verify={this.props.user.logged} redirectTrue="/projects"  >
                    <Path exact path='/login' component={Login} />
                </PathGroup>
                <Route component={ NotFound } />
            </Switch>
        </BrowserRouter>
    );
}

But when I run the app it shows just the first group

Also I tried with React.Fragment, but happens the same.

A: I don't know if this is the answer you want, but if you want to have a fallback page for each base route, the easiest way is to use nested switch.

import React, { Component } from "react";
import { render } from "react-dom";
import { Route, Switch, BrowserRouter } from "react-router-dom";

const Home = props => (

    <Switch>
      <Route path={props.match.url + "/1"} exact render={() =>
Home 1
} />
      <Route path={props.match.url + "/2"} exact render={() =>
Home 2
} />
      <Route render={() =>
Home 404
} />
    </Switch>

);

const Post = props => (

    <Switch>
      <Route path={props.match.url + "/1"} exact render={() =>
Post 1
} />
      <Route path={props.match.url + "/2"} exact render={() =>
Post 2
} />
      <Route render={() =>
Post 404
} />
    </Switch>

);

class App extends Component {
  render() {
    return (
      <BrowserRouter>

        <Switch>
          <Route path="/home" component={Home} />
          <Route path="/post" component={Post} />
          <Route render={() =>
404
} />
        </Switch>

      </BrowserRouter>
    );
  }
}

*

*The authentication can be done in each root route component, and then redirect to login page.

*Query parameter also can be used, so the same route can handle multiple ids.
Eg: <Route path={this.props.match.url + '/:id'} exact component={Post} /> and then, in Post component, using const { id } = this.props.match.params to get the id.
There is the CodeSandbox demo.


Q: Java - Sorting a 2D Array by Row Sum Trying to write a method that swaps the rows of a 2D array in order of increasing row sum.
For example, if I have the following 2d array:
int [][] array = {4,5,6},{3,4,5},{2,3,4};

I would want it to output an array as so:
{2 3 4}, {3 4 5}, {4 5 6}

Methodology:
a.) take the sums of each row and make a 1D array of the sums
b.) do a bubble sort on rowSum array
c.) swap the rows of the original array based on the bubble sort swaps made
d.) then print the newly row sorted array.
Here's my code so far:
      public void sortedArrayByRowTot() {
        int [][] tempArray2 = new int [salaryArray.length [salaryArray[0].length];

        for (int i = 0; i < tempArray2.length; i++) {
          for (int j = 0; j < tempArray2[i].length; j++) {
            tempArray2[i][j] = salaryArray[i][j];
          }
        }

        int [] rowSums = new int [tempArray2.length];
        int sum = 0;
        for (int i = 0; i < tempArray2.length; i++) {
          for (int j = 0; j < tempArray2[i].length; j++) {
            sum += tempArray2[i][j];
          }
          rowSums[i] = sum;
          sum = 0;
        }

        int temp;
        int i = -1;
        for(int j = rowSums.length; j > 0; j--){
          boolean isSwap = false;
          for (i = 1; i < j; i++) {
            if(rowSums[i-1] > rowSums[i]) {
              temp = rowSums[i-1];
              rowSums[i-1] = rowSums[i];
              rowSums[i] = temp;
              isSwap = true;
            }
          }

          if(!isSwap){
            break;
          }
        }

        for (int k = 0; k < tempArray2.length; k++) {
          temp = tempArray2[i-1][k];
          tempArray2[i-1][k] = tempArray2[i][k];
          tempArray2[i][k] = temp;
        }

        for (int b = 0; b < tempArray2.length; b++) {
          for (int c = 0; c < tempArray2[b].length; c++) {
            System.out.print(tempArray2[b][c] + " ");
          }
        }
      }
    }

Not sure if I am doing part c of my methodology correctly?
It keeps saying "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2"

A: As @shmosel said, you can do it like this:
public static void sortedArrayByRowTot() {
    int [][] array = {{4,5,6},{3,4,5},{2,3,4}};
    Arrays.sort(array, Comparator.comparingInt(a -> IntStream.of(a).sum()));
}

A: I was able to solve my question. Thanks.
    public void sortedArrayByRowTot() {
      //Creates tempArray2 to copy salaryArray into
      int [][] tempArray2 = new int [salaryArray.length][salaryArray[0].length];

      //Copies salaryArray into tempArray2
      for (int i = 0; i < salaryArray.length; i++) {
        for (int j = 0; j < salaryArray[i].length; j++) {
          tempArray2[i][j] = salaryArray[i][j];
        }
      }

      //Creates rowSum array to store sum of each row
      int [] rowSums = new int [tempArray2.length];
      for (int i = 0; i < tempArray2.length; i++) {
        for (int j = 0; j < tempArray2[0].length; j++) {
          rowSums[i] += tempArray2[i][j];
        }
      }

      //Modified Bubble Sort of rowSum array (highest to lowest values)
      int temp;
      int i = 0;
      for(int j = rowSums.length; j > 0; j--){
        boolean isSwap = false;
        for (i = 1; i < j; i++) {
          if(rowSums[i-1] < rowSums[i]) {
            temp = rowSums[i-1];
            rowSums[i-1] = rowSums[i];
            rowSums[i] = temp;
            isSwap = true;
            //swaps rows in corresponding tempArray2
            int [] temp2 = tempArray2[i-1];
            tempArray2[i-1] = tempArray2[i];
            tempArray2[i] = temp2;
          }
        }

        if(!isSwap){
          break;
        }
      }

      //Prints sorted array
      System.out.println("Sorted array: ");
      for (i = 0; i < tempArray2.length; i++) {
        for (int j = 0; j < tempArray2[i].length; j++) {
          System.out.print("$"+ tempArray2[i][j] + " ");
        }
        System.out.println();
      }
    }

A: You may try this way. That I have solved.
 public class Solution{
          public static void sortedArrayByRowTot() {
            int [][] salaryArray = { {4,5,6},{3,4,5},{2,3,4} };
            int [][] tempArray2 = new int [salaryArray.length][salaryArray[0].length];

            for (int i = 0; i < salaryArray.length; i++) {
              for (int j = 0; j < salaryArray[i].length; j++) {
                tempArray2[i][j] = salaryArray[i][j];
              }
            }

            // Buble Sort to store rowSums
            int [] rowSums = new int [tempArray2.length];
            for (int i = 0; i < tempArray2.length; i++) {
              for (int j = 0; j < tempArray2[0].length; j++) {
                rowSums[i] += tempArray2[i][j];
              }
            }

            //Buble Sort by Rows Sum (Lowest Value to Highest)
            int temp;
            int i = 0;
            for(int j = rowSums.length; j > 0; j--){
              boolean isSwap = false;
              for (i = 1; i < j; i++) {
                if(rowSums[i-1] > rowSums[i]) {
                  temp = rowSums[i-1];
                  rowSums[i-1] = rowSums[i];
                  rowSums[i] = temp;
                  isSwap = true;
                  //swaps rows in corresponding tempArray2
                  int [] temp2 = tempArray2[i-1];
                  tempArray2[i-1] = tempArray2[i];
                  tempArray2[i] = temp2;
                }
              }

              if(!isSwap){
                break;
              }
            }
            /** No Need.
            for (int k = 0; k < tempArray2.length; k++) {
            temp = tempArray2[i-1][k];
            tempArray2[i-1][k] = tempArray2[i][k];
            tempArray2[i][k] = temp;
          }
          */

            for (int b = 0; b < tempArray2.length; b++) {
            for (int c = 0; c < tempArray2[b].length; c++) {
              System.out.print(tempArray2[b][c] + " ");
            }
          }
          }

        public static void main(String[] args) {
            sortedArrayByRowTot();
        }
      }