text:
Q: How to print multi-level list in Spring I want to print a multi-level list like this using jslt in Spring, how to code the controller and jsp?

*

*News-cat-1

*

*News item1

*News item2

*News item3

*News-cat-2

*

*News item1

*News item2

*News item3

*News-cat-3

*

*News item1

*News item2

*News item3

Here is my controller code:
@RequestMapping(value = "/index.htm", method = RequestMethod.GET)
public String loadHomePage(ModelMap map) {

    List<NewsCategory> cat = newsService.getNewsCat();

    for(NewsCategory c : cat){
          List<News> list = newsService.getByCat(c.getId());

          map.put("list-" + c.getId(), list); // is this right?
    }

    map.put("newscat", cat);

    // And how to print these in the jsp page?

    return "index";
}

Thanks!

A: <c:forEach var="entry" items="${myMap}">
 List name: <c:out value="${entry.key}"/>
  <c:forEach items="${entry.value}" var="cat" varStatus="rowStatus">
                <c:forEach items="${cat.itemList}" var="item" varStatus="rowCount">
                    <div>...<c:out value="${item.description}"/></div>
                </c:forEach>
        </c:forEach>
</c:forEach>


text:
Q: C++: Multiple Sounds without Additional Headers or Libraries This is my first post here. I am trying to write a program that plays background music, while still allowing for playing sound effects (i.e. music with gunshots). I wish to play multiple sounds at once WITHOUT using any other libraries or header files. I don't want to use anything besides what comes with Windows XP and my compiler. I don't want links to other libraries, I need example code showing how to do this using vanilla Windows. I am using Windows.h. I have done research into this, and have yet to find an answer that meets my needs. I have heard that multiple threads might be an answer, but cannot get them to work. I am relatively new to coding.
Thanks in advance!

A: I know you've said you want to keep it simple, but it sounds like you want to use DirectSound. It provides one primary buffer (good for your background music) and a series of secondary buffers (good for your sound effects). Its very easy to work with, and doesn't require much more than linking dsound.lib
Also, completely unhelpful: You should be sure to upgrade to Windows 7 or 8 before April. Microsoft will no longer support it and you'll be a great risk for exploitation.

redpajama_set_name: RedPajamaStackExchange


text:
Q: heroku app on firefox won't load javascripts due to content security policy I have a new app deployed to heroku. On chrome it works as expected but in firefox I get the following error (and more like it) in the console:
Content Security Policy: The page's settings blocked the loading of a resource at inline ("script-src").
It's not just an annoyance - since it's blocking the javascripts from loading, the site is basically not usable on FF which is obviously quite problematic.  I can't modify the headers on heroku as my research has suggested.
What do?

A: You can configure your content security policy in your Rails app layer itself so no Heroku config changes are needed as follows:
# config/initializers/content_security_policy.rb

Rails.application.config.content_security_policy do |policy|
  policy.default_src :self, :https
  policy.font_src    :self, :https, :data
  policy.img_src     :self, :https, :data
  policy.object_src  :none
  policy.script_src  :self, :https
  policy.style_src   :self, :https, :unsafe_inline
  policy.report_uri  "/csp-violation-report-endpoint"
end

You can change this as needed. and more details can be found here


text:
Q: Is it possible to use JBoss SEAM on an application that is not a WEB application? I mean, is it possible to use seam in a back-end application that just offers functionality through remote EJBs or Webservices or MDBs or whatever? (ant therefore there is no http session or request).
Does it make sense to use Seam in such scenario?
If so, how is it launched? Since in a web context a listener is declared in the file "web.xml", in the described scenario, where is Seam launched?

A: No, SEAM is JSP-based, which requires a servlet/JSP engine and a web container.  It's neither possible nor desirable.
Creating a service-based back end that's independent of user interface is indeed a very good idea.  You can use EJBs or Hibernate to accomplish that.  But you don't need SEAM.

A: Seam is definitely not JSP based. It's arguably JSF centric, but you can use Wicket or GWT for your user interface as well.
A Seam based back-end only application is possible and, in my opinion, it makes perfectly sense if you plan to use some Seam features like Security, RESTEasy integration, the ability to use dependency injection in web services and the MDB facilities.
About the second question, that is how to launch it, in Seam2 you have to define a dummy war module with the filter needed for startup and shutdown. In Seam3, being based on CDI, you may be able to avoid it.

A: In EJB 3 world you already have good mechanisms of Dependency Injection, Transaction Management, EJB's have a clearly defined lifecycle. So I don't think Seam's extremely useful for EJB's, unless you wanna mix EJB with web technologies, like JSF, Wicket, etc -- in this case you benefit from the unified component model of Seam. You will have Seam's DI and resource management mechanisms, that abstracts differences between EJB's, Servlet's, JSF's aproaches to that.
Seam's main point is to seamlessly integrate different (mostly web) technologies.
That's why I think it doesn't make much sense if you are using EJB's alone.


text:
Q: Manage the menu permissions in EasyAdmin I'm using Symfony 4 and I would like to show / hide my entities in the menu depending on the roles, but it's impossible.
For example, I tried to override the menu.html.twig of EasyAdmin file but it didn't work.
It only works if I modify a loop directly in the EasyAdmin library but it's bad practice.

A: try the package alterphp/easyadmin-extension-bundle
it provides this functionality
https://packagist.org/packages/alterphp/easyadmin-extension-bundle
easy_admin:
        menu:
            - { label: 'Administrator', role: ROLE_SUPER_ADMIN } # Hidden if user is not granted ROLE_SUPER_ADMIN
            - { label: 'App action', route: 'app_action', role: ROLE_ADMIN } # Hidden if user is not granted ROLE_ADMIN

A: If you want to override an EasyAdmin template, create a directory ./templates/easy_admin and put your templates inside.
In your case, just create ./templates/easy_admin/menu.html.twig and this will override the default menu


text:
Q: mui datatable column width options is not available I am trying to set different column width for every column. But there is no option to set column width in mui datatable column options. I tried to override css properties also and that is also not working. Is there any other option to set column width .
MUIDataTableBodyCell: {
        root: {
          height: '30px',
           width: '200px'
        }
      },

A: After a lot of trial and error, I was able to find a solution that worked for me.  I am using mui-datatables 3.5.0.
I was able to set the column width by setting the cell props (setCellProps). Initially, I did this for both the cell and the header, but the header did not prove to be necessary.
    export const columns = [
    {
        name: "category",
        label: "Category",
        options: {
            setCellProps: () => ({ style: { minWidth: "800px", maxWidth: "800px" }}),
            customBodyRender: (data, type, row) => {return <pre>{data}</pre>}
      },
    },

A: You would have to provide your own columns which is an array of objects.
import { myCustomColumns } from "./my_custom_columns.js";

...

<MuiDataTable ... columns={myCustomColumns} />

Each object on the array is a column, and that is where you will set your own customHeadRender on the options property for the object. Take a look at the code snippet below.
// my_custom_columns.js

/*
   Since you are providing your own columns, the default column styling
   will be 'cleared'. The columnStyleWithWidth below will bring back the default
   styling with the width that you would like to define.
*/

const columnStyleWithWidth = {
   top: "0px",
   left: "0px",
   zIndex: "100",
   position: "sticky",
   backgroundColor: "#fff",
   width: "300px"
}

export const columns = [
{
   name: "category",
   label: "Category",
   options: {
     ...,
     customHeadRender: ({index, ...column}) {
        return (
          <TableCell key={index} style={columnStyleWithWidth}>
              <CustomColumn label={column.label} />
          </TableCell>
        )
     }
   }
},
...
]

Take note that TableCell is a component of Material-UI.


text:
Q: Google plus doesn't share description https://developers.google.com/+/web/snippet/
I refered this link..
When I tried to share the event title, image and description. I am unable to share event description.

*

*Schema.org microdata

*Open Graph protocol

*Title and meta "description" tags

I used above all three methods to share the event description. If any one knows please share the info..


text:
Q: Asymptotic equivalence with the Notable Limit of Natural Logarithm  I hope this is not too easy of a question
Basically I've been fiddling with Asymptotic Equivalences to solve limits in a faster and less prone to error way, and I am facing the limit:
$$
\lim_{x\to0}{\frac{e^x-\ln(e+x)}{x^3-2x}}
$$
The approach I wanted to use is that of substitution via Asymptotic Equivalence, aiming at substituting $e^x-1$ with $x$ and $\ln(e+x)$.
My idea was to add and subtract $1$ in the numerator in order to obtain the right situation to substitute $e^x-1$ with $x$; this decision probably isn't the best one to solve this limit in a definite manner since I'll remain with $\frac{1}{x^3-2x}$ that is of indefinite form but as I was trying out this path I started asking myself if it was possible to substitute $\ln{e+x}$ via Asymptotic Equivalences.
I was thinking that maybe
$$
\ln{\frac{1+f(x)}{f(x)}}=1\implies \ln{\frac{e+x}{x}}=e;
$$
am I completely wrong? If not can one of you point me to a resource (be it online or a book) in which I can delve deeper into Notable Limits and Asymptotic Equivalences?

A: Clearly, when $x\to 0$, we have $x^3=o(x)$, so we can consider only $2x$.
The definition of $o(...)$ or "little-o": let $f(x),\, g(x)$ two real functions. Let $x_0 \in \overline{\mathbb{R}}$ an accumulation point for $g(x)$ and such that $g(x) \neq 0\,\, \forall x \,\in \,I(x_0)$. We write $f(x)=o(g(x))$ when $x\to x_0$ if and only if:
$$\lim_{x\to x_0}\frac{f(x)}{g(x)}=0$$
In this case, let $f(x)=x^3$, $g(x)=2x$ and $x_0=0$. We have:
$$\lim_{x\to x_0}\frac{f(x)}{g(x)}=\lim_{x\to x_0}\frac{x^3}{2x}=\lim_{x\to x_0}\frac{1}{2}x^2=0$$
Or, when $x\to 0$, we have $2x>x^3$. Here, we have the graph (in red $y=2x$ and in blue $y=x^3$):

Also, we know from asymptotic relations (when $x\to 0$):
$$e^x-1\,\,\sim\,\,x$$
And:
$$\log(1+x)\,\,\sim\,\,x$$
Now, we can approach your limit:
$$\lim_{x\to0}{\frac{e^x-\ln(e+x)}{x^3-2x}}\,\,\sim\,\,\lim_{x\to0}\frac{e^x-1-\ln\left(1+\frac{x}{e}\right)}{-2x}\,\,\lim_{x\to 0}\frac{x-\frac{x}{e}}{-2x}=-\frac{1-\frac{1}{e}}{2}=\frac{1-e}{2e}$$

A: With a bit of algebraic manipulation
$$
\frac{e^x-\log(e+x)}{x^3-2x}=\frac{\log(e+x)-e^x}{2x}\frac{1}{1-(x^2/2)}
$$
so that
$$
\lim_{x\to0}\frac{e^x-\log(e+x)}{x^3-2x}=\left(\lim_{x\to0}\frac{\log(e+x)-e^x}{2x}\right)\left(\lim_{x\to0}(1-x^2/2)^{-1}\right)
=\lim_{x\to0}\frac{1}{2}\frac{\log(e+x)-e^x}{x}.
$$
Then note that $e^x=1+x+\mathcal O(x^2)$ and $\log(e+x)=1+x/e+\mathcal O(x^2)$ as $x\to 0$; hence,
$$
\frac{\log(e+x)-e^x}{x}=\frac{1}{e}-1+\mathcal O(x)
$$
and
$$
\lim_{x\to0}\frac{1}{2}\frac{\log(e+x)-e^x}{x}=\lim_{x\to0}\frac{1}{2}\left(\frac{1}{e}-1+\mathcal O(x)\right)=\frac{1}{2}\left(\frac{1}{e}-1\right).
$$


text:
Q: Is there anything in the Django / Python world equivalent to SimplePie Plugin for Wordpress? I know that SimplePie itself is derived from UFP, but the features I'm wondering about are the post-processing features that are available in SimplePie for WordPress plugin:
http://simplepie.org/wiki/plugins/wordpress/simplepie_plugin_for_wordpress/processing
Can I find something similar to this for my Django application?
Can this be accomplished using Django inclusion tags?

A: You are looking for the universal feed parser.

A: http://www.djangosnippets.org/tags/rss/


text:
Q: React & Redux, Update state, Error: A state mutation was detected between dispatches The problem I'm having is in my save data round trip.
The error: browser.js:34 Uncaught (in promise) Invariant Violation: A state mutation was detected between dispatches, in the path profile.user.alias.
I'm new to React & Redux but I think I've done everything by the book. What am I missing?

*

*I create a local state in the component and assign the object returned from mapStateToProps.

*I setState on onChange of text fields.

*On save click, I call the action defined in mapDispatchToProps passing it the local state. Note, the mapped action is a Thunk function since I use REST Api to save date on server.

*Server saves the data and returns the same object with new Ids etc. filled in.

*In fetch.then() I dispatch an action passing the object returned from the server.
The error is on the dispatch line.
export function setUserProfile (profile) {
    return function(dispatch) {
        return setProfile(profile)  <-- the API call
            .then(p => {
                dispatch(handleSetProfileSuccess(p));
            })
            .catch(error => {
                throw error;
            });
    };

I've been wrestling with this error since yesterday. I've tried all tricks I've found including changing to createReducer from Redux-Starter-Kit.
I've made sure that the exact same chain of objects, actions, reducers, etc. that I use in the 'set' are the same as in the 'get' action that works.
export function handleSetProfileSuccess (profile) {
    return { type: types.SET_USER_PROFILE_SUCCESS, profile };
}

export function setUserProfile (profile) {
    return function(dispatch) {
        return setProfile(profile)   <--- the api call with fetch
            .then(p => {
                dispatch(handleSetProfileSuccess(p));
            })
            .catch(error => {
                throw error;
            });
    };

// the action is never dispatched on save since the error is on the dispatch line above.
// the Redux way
export default function profileReducer(state = {}, action) {
    switch (action.type) {
        case types.GET_USER_PROFILE_SUCCESS:
            return { ...state, ...action.profile };
        case types.SET_USER_PROFILE_SUCCESS:
            return { ...state, ...action.profile };
        default:
            return state;
    }
}

// the redux-starter-kit way
const profileReducer=createReducer({}, {
    GET_USER_PROFILE_SUCCESS: (state, action) => state=action.profile,
    SET_USER_PROFILE_SUCCESS: (state,action) => state=action.profile
});

The whole round trip works. The new data is saved on the server and the returned object from the server is correct. The argument 'p' in the .then() call does contain the correct data. But it crashes on the call to
dispatch(handleSetProfileSuccess(p));

EDIT: Here's the code snippets from profile.js
// profile.js
state = { ...this.props.profile };

// on save click handler
setData = e => {
    e.preventDefault();

    // validate stuff here
    this.props.setProfile(this.state).then(() => {
        this.setState(prevState => ({
            ...prevState,
            ...this.props.profile
        }));
    });
};

export function mapStateToProps(state) {
    return {
        user: state.user,
        profile: state.profile
    };
}

const mapDispatchToProps = {
    getProfile: profileActions.getUserProfile,
    setProfile: profileActions.setUserProfile
};

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(Profile);

Please help. I'm all out of options.

A: it is likely that you are mutating a prop passed by react-redux.
Check all code where you are using props.profile or props.user, code like the following could be the culprit
props.profile.friends.splice(0, 1);

A: The state mutation error happens when you mutate the props received and dispatches an action with that mutated props. So to do such dispatches, copy the props to a local state while receiving it, make the changes to the state and dispatch the action with the state.
If the props received is a nested object do deep copying, using
JSON.parse(JSON.stringify());
So in your code, before making a dispatch copy the props to a state and make the dispatch with the state.


text:
Q: Uploaded .mov video plays out of sync After uploading the videos into the server, and you try to watch by clicking the play button the videos with the (.mp4) format plays well smoothly but the (.mov) video plays out of sync, like the voice delays, but if you download it, it plays normally with no problem. I don't know what could be the problem and the potential solution for it. I've tried Preloading but did not work.
My HTML the src is placed dynamically

    <video width="100%" controls autoplay id="talentVideo">
        <source src="" type="video/mp4">
        <source src="" type="video/qt">
    </video>

My Js code:


text:
Q: How to set two packages to sendIntent in android? I'm using sendIntent in my anroid project to send the user to whatsapp for sending the message. But i want both apps whatsapp and business whatsapp, so user can select according to there preference. Here is the code i tried :
Intent sendIntent = new Intent(Intent.ACTION_SENDTO,Uri.parse("smsto:" + toNumber));
sendIntent.setPackage("com.whatsapp","com.whatsapp.w4b");
startActivity(sendIntent);

This doesn't work. I also tried this code
Intent sendIntent = new Intent(Intent.ACTION_SENDTO,Uri.parse("smsto:" + toNumber));
sendIntent.setPackage("com.whatsapp");
sendIntent.setPackage("com.whatsapp.w4b");
startActivity(sendIntent);

This works but this code autmatically open businesswhatsapp.

A: The reason why the first code snippet you tried did not work is because setPackage method only takes one package name at a time, so you cannot specify multiple package names like you did.
The second code snippet you tried only specifies the second package name, so it will always open Business WhatsApp.
One way to allow the user to choose between WhatsApp and Business WhatsApp would be to present a chooser dialog that lets the user select which app to use. You can do this by using the Intent.createChooser() method, like this:
Intent sendIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + toNumber));
sendIntent.setPackage("com.whatsapp");
Intent businessSendIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + toNumber));
businessSendIntent.setPackage("com.whatsapp.w4b");
Intent chooserIntent = Intent.createChooser(sendIntent, "Choose app");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { businessSendIntent });
startActivity(chooserIntent);
In this code, we create two separate intents, one for WhatsApp and one for Business WhatsApp. Then, we create a chooser intent using Intent.createChooser(), which will display a dialog that allows the user to choose which app to use. We set the main intent (sendIntent) as the initial option, and add the businessSendIntent as an additional option using the EXTRA_INITIAL_INTENTS extra.
This way, the user can choose which app to use, and the selected app will be used to send the message.


text:
Q: Swift UIGestureRecognizer is not working / is not doing anything
I have a small issue that I couldn't fix for a few hours now! I have a simple ViewController with a label, which is linked to my ViewController class. I also set up an UIGestureRecognizer to change the text of the label when the label is clicked. But weirdly nothing happens at all.
The text of the label changes from whatever is set in the Storyboard to "Hello", so the setup is correct. But when I click the label, nothing happens.

Here's the entire ViewController class:
import UIKit

class PremiumViewController: UIViewController {

    // Views
    @IBOutlet weak var premiumLabel: UILabel!

    // View Did Load
    override func viewDidLoad() {
        super.viewDidLoad()

        premiumLabel.text = "Hello"

        // Tap listener
        let tap = UIGestureRecognizer(target: self, action: #selector(PremiumViewController.clicked))
        premiumLabel.isUserInteractionEnabled = true
        premiumLabel.addGestureRecognizer(tap)
    }

    @objc func clicked() {
        premiumLabel.text = "You clicked me"
    }

}

A: Use UITapGestureRecognizer instead of UIGestureRecognizer
change from
let tap = UIGestureRecognizer(target: self, action: #selector(PremiumViewController.clicked))

to
let tap = UITapGestureRecognizer(target: self, action: #selector(PremiumViewController.clicked))


text:
Q: How to import file into sqlite? On a Mac, I have a txt file with two columns, one being an autoincrement in an sqlite table:
, "mytext1"
, "mytext2"
, "mytext3"

When I try to import this file, I get a datatype mismatch error:
.separator ","
.import mytextfile.txt mytable

How should the txt file be structured so that it uses the autoincrement?
Also, how do I enter in text that will have line breaks?  For example:
"this is a description of the code below.
The text might have some line breaks and indents.  Here's
the related code sample:

foreach (int i = 0; i < 5; i++){

  //do some stuff here

}

this is a little more follow up text."

I need the above inserted into one row.  Is there anything special I need to do to the formatting?
For one particular table, I want each of my rows as a file and import them that way.  I'm guessing it is a matter of creating some sort of batch file that runs multiple imports.
Edit
That's exactly the syntax I posted, minus a tab since I'm using a comma. The missing line break in my post didn't make it as apparent. Anyways, that gives the mismatch error.

A: I was looking on the same problem. Looks like I've found an answer on the first part of your question — about importing a file into a table with ID field.
So yes, create a temporary table without ID, import your file into it, then do insert..select to copy its data into your target table. (Remove leading commas from mytextfile.txt).
-- assuming your table is called Strings and
-- was created like this:
-- create table Strings( ID integer primary key, Code text )

create table StringsImport( Code text );
.import mytextfile.txt StringsImport
insert into Strings ( Code ) select * from StringsImport;
drop table StringsImport;

Do not know what to do with newlines. I've read some mentions that importing in CSV mode will do the trick (.mode csv), but when I tried it did not seem to work.

A: I'm in the process of moving data containing long text fields with various punctuation marks (they are actually articles on coding) into SQLite and I've been experimenting with various text imports.
I created a database in SQLite with a table:
CREATE TABLE test (id PRIMARY KEY AUTOINCREMENT, textfield TEXT);

then do a backup with .dump.
I then add the text below the "CREATE TABLE" line manually in the resulting .dump file as such:
INSERT INTO test textfield VALUES (1,'Is''t it great to have
                     really long text with various punctaution marks and
          newlines');

Change any single quotes to two single quotes (change ' to ''). Note that an index number needs to be added manually (I'm sure there is an AWK/SED command to do it automatically). Change the auto increment number in the "sequence" line in the dump file to one above the last index number you added (I don't have SQLite in front of me to give you the exact line, but it should be obvious).
   With the new file, I can then do a restore onto the database

A: In case anyone is still having issues with this you can download an SQLLite manager.
There are several that allow importing from a CSV file.
Here is one but a google search should reveal a few: http://sqlitemanager.en.softonic.com/


text:
Q: How to define a value in a multiArray This is my first question and I'll try to be clear.
I need to assign a value in positions. I have a two-dimensional array of 7 rows ( for example).
Depending on the value someone give me, I have to change value positions.
Example
If someone give me: 3. I must put these 3, in the following order.
1 * * * * * * * * *
2 * * * * * * * * *
3 * * * * * * * * O
4 * * * * * * * * O
5 * * * * * * * * O
6 * * * * * * * * *
7 * * * * * * * * *

If some one give me: 2
1 * * * * * * * * *
2 * * * * * * * * *
3 * * * * * * * * O
4 * * * * * * * * O
5 * * * * * * * * *
6 * * * * * * * * *
7 * * * * * * * * *

I define de some start point in the "middle" of the array. These i do OK.
start point in the middle. S = Start point
1    * * * * * * * * *
2    * * * * * * * * *
3    * * * * * * * * *
4    S * * * * * * * *
5    * * * * * * * * *
6    * * * * * * * * *
7    * * * * * * * * *

The problem is when i must put '0' in the final of the array, because the number of '0' is variable and must be centered
I have these code:
var height = 7;
var width = 9;
var exit = 3; // or can be 2, or 4, 5 etc.

var matrix = new Array(height);
for (var i=0; i<height; i++) {
    matrix[i] = new Array(width);
    for (var j = 0; j<width; j++) {
        matrix[i][j] = *;
    }
}

function startPoint(height, matrix){
    // Se define el punto de partida
    var startPoint = Math.round(height/2) -1;
    document.write("el punto de partida es: "+startPoint)
    matrix[startPoint][0] = 'S';
    return matrix
}

function finishPoint(exit, matrix){
    // punto de salida.

    return matrix
}

I'm learning JavaScript and I found a problem that I can not resolv. I'm trying and I can not have a clear idea.

A: To center an array of k values in a space of s values (where s >= k) you can use the formula
 var x = Math.floor((s - k) / 2);

and store the k values in x, x+1, ... , x+k-1.
The idea of the formula is

*

*Compute how many free places are remaining (i.e. s - k)

*Split these in two to give half of them to each side

of course if the number of free places ends up being odd you cannot split them exactly in half, and one side will get more than the other. Using Math.floor takes care of this adjustment giving the first side one element less.

A: You just need to find the center (height/2) and subtract HALF the height of the "exit". so if the exit is 4 tall, then 2 should be on one side and 2 on the other, so you subtract 2 from the center.

var height = 7;
var width = 9;
var exit = 3; // or can be 2, or 4, 5 etc.

var matrix = new Array(height);
for (var i=0; i<height; i++) {
    matrix[i] = new Array(width);
    for (var j = 0; j<width; j++) {
        matrix[i][j] = '*';
    }
}

function startPoint(height, matrix){
    // Se define el punto de partida
    var startPoint = Math.round(height/2)-1 ;
    document.body.innerHTML+=("el punto de partida es: "+startPoint+'
')
    matrix[startPoint][0] = 'S';
    return matrix
}

function finishPoint(exit, matrix){
    // punto de salida.
    var startPoint=Math.round(height/2-(exit/2))
    for(var i=0;i<exit;i++)
      matrix[startPoint+i][width-1]='0'
    return matrix
}

matrix=startPoint(height,matrix)
matrix=finishPoint(exit,matrix)

for(var i=0;i<height;i++){
  for(var j=0;j<width;j++)
     document.body.innerHTML+=matrix[i][j]
  document.body.innerHTML+='
'
}

document.body.innerHTML+='la salida es de altura: '+exit+ ' entonces buscamos el centro ('+(height/2)+') y restamos mitad de la altura ('+exit/2+')'


text:
Q: RSpec: should_receive as thing being spec-ed I'd like to use should_receive as the subject of a spec in RSpec. In other words, instead of testing a should ==, I'd like to test that another class receives a method call.
What I'd like to write is something like:
describe '#methodOne' do

  subject { ClassTwo }

  it { should_receive(:methodTwo) }

  ClassOne.methodOne

end

Is this possible?

A: There are ways you can contort RSpec to do things like this but it's not using RSpec how it's intended.  should_receive sets up a mock expectation that a method will be called.  It doesn't make sense for the one liner it syntax.
I recommend you start with the basic describe/it structure and only refactor to the more advanced constructs (subject, one-line it) when you've got duplication.

A: So here's how I did it:
describe "#methodOne" do

  it "calls the appropriate method" do

    ClassTwo.should_receive(:methodTwo)
    ClassOne.methodOne

  end

end

This works beautifully

A: I would use the subject in its instance variable form:
@subject.should_receive(:methodTwo)


text:
Q: javascript two events one function How can I listen for click and mouseover events when one of events are detected run a function?

//show image by color
function showImage(imgPath, imgText, mainImgId, element) {
  let thumb = document.getElementsByClassName("colors-li");
  for (let i = 0; i < thumb.length; i++) {
    thumb[i].classList.remove("active");
  }
  element.classList.add("active");

  let curImage = document.getElementById(mainImgId);
  curImage.src = imgPath;
  curImage.alt = imgText;
  curImage.title = imgText;
}

Please help me reduce one of these:
    onclick="showImage('img/products/product-red.jpg','red', 3, this);"
    onmouseover="showImage('img/products/product-red.jpg','red', 3, this);"

A: I will do that this way:
withUsing data attributes
const cColorLi_list = document.querySelectorAll('li.colors-li')
  ;
function showImage(elmLI)
  {
  elmLI.closest('ul')
    .querySelectorAll('li.colors-li')
    .forEach(eLI => eLI.classList.toggle('active',(elmLI===eLI)))
  let curImage = document.getElementById(elmLI.dataset.ref)
  curImage.src = elmLI.dataset.img
  curImage.alt = curImage.title = elmLI.querySelector('img').alt
  }
cColorLi_list.forEach(cLi=>
  {
  cLi.onclick=()=> showImage(cLi)
  cLi.onmouseover=()=> showImage(cLi)
  })


text:
Q: SQL query for MySQL that will fetch usernames and their last comments from the database (one comment per user) Write a SQL query to MySQL, which will select usernames and their last comments from the database (one comment for each user), with the following table structure (SQL query should also display users who have no comments):
CREATE TABLE `db_user` (
  `db_user_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `balance` decimal(10,2) NOT NULL,
  PRIMARY KEY (`db_user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;

CREATE TABLE `db_comment` (
  `db_comment_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `db_user_id` int(10) unsigned NOT NULL,
  `text` text NOT NULL,
  PRIMARY KEY (`db_comment_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;

Created 2 tables and entered some values into them:
CREATE TABLE db_user (
db_user_id int(10) unsigned NOT NULL AUTO_INCREMENT,
name varchar(255) NOT NULL,
balance decimal(10,2) NOT NULL,
PRIMARY KEY (db_user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
INSERT INTO db_user (db_user_id, name, balance) VALUES ('1', 'Pavel', '5,5');
INSERT INTO db_user (db_user_id, name, balance) VALUES ('2', 'Alex', '6,7');
INSERT INTO db_user (db_user_id, name, balance) VALUES ('3', 'Maria', '7,8');
INSERT INTO db_user (db_user_id, name, balance) VALUES ('4', 'Mike', '4,3');
CREATE TABLE db_comment (
db_comment_id int(10) unsigned NOT NULL AUTO_INCREMENT,
db_user_id int(10) unsigned NOT NULL,
text text NOT NULL,
PRIMARY KEY (db_comment_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
INSERT INTO db_comment (db_user_id, db_comment_id, text) VALUES ('3', '1', 'Hello!');
INSERT INTO db_comment (db_user_id, db_comment_id, text) VALUES ('2', '2', 'Beatiful!');
INSERT INTO db_comment (db_user_id, db_comment_id, text) VALUES ('1', '3', 'What?');
INSERT INTO db_comment (db_user_id, db_comment_id, text) VALUES ('3', '4', 'Amazing!');
INSERT INTO db_comment (db_user_id, db_comment_id, text) VALUES ('2', '5', 'Nice!');
INSERT INTO db_comment (db_user_id, db_comment_id, text) VALUES ('1', '6', 'Cool!');
INSERT INTO db_comment (db_user_id, db_comment_id, text) VALUES ('3', '7', 'Great!');
INSERT INTO db_comment (db_user_id, db_comment_id, text) VALUES ('2', '8', 'OMG!');
INSERT INTO db_comment (db_user_id, db_comment_id, text) VALUES ('1', '9', 'Really?');
INSERT INTO db_comment (db_user_id, db_comment_id, text) VALUES ('4', '', '');
Then I tried to write a SQL query:
SELECT
u.name,
c.text
FROM db_user u
LEFT JOIN(
SELECT
Db_comment.db_user_id,
MAX(Db_comment.db_comment_id) as last_cid,
FROM db_comment
GROUP BY db_comment.db_user_id
)uc ON u.db_user_id=uc.db_user_id
LEFT JOIN db_comment c
ON c.db_comment_id=uc.last_cid
But there are many errors.
I'm a beginner in writing SQL queries, please tell me how to make such a query more correctly and easier.
Approximate result:
1 Pavel - Really?
2 Alex - OMG!
3 Maria - Great!
4 Mike -        , (or post a line "No comments")

A: trying to answer but still have some issues, work in progress, interested by support too ^^

db_comment_id    db_user_id    text
1                1             Hello
2                2             Great
3                3             Awesome
4                1             NextStage
5                2             Crazy
6                1             Horrible`

________________________________________________________________________________

db_user_id    name    balance
1             joe     200.00
2             jane    350.00
3             bill    80.00

________________________________________________________________________________

select last_comment.*, name
    FROM db_comment last_comment

LEFT JOIN db_user ON db_user.db_user_id=last_comment.db_comment_id
LEFT JOIN db_comment new_comment
    ON last_comment.db_user_id = new_comment.db_user_id
    AND last_comment.db_comment_id<new_comment.db_comment_id
WHERE new_comment.db_user_id IS NULL
ORDER BY last_comment.db_user_id DESC LIMIT 3

________________________________________________________________________________

OUTPUT
db_comment_id    db_user_id    text        name
3                3             Awesome     bill
5                2             Crazy       null
6                1             Horrible    null


text:
Q: How can I make Google Chrome tabs sharper? Picture about my chrome I've Ubuntu 16.04 and my problem is in Google Chrome (not chromium) the tabs fonts are blur.
I tried change antialiasing in unity tweak, so my fonts are sharper in ubuntu, expect google chrome. Disturb my eyes.
Also tried go to chrome://flags/#disable-direct-write and was looking for "DirectWrite" but i didn't find. So how can I get sharper fonts?

A: Use:
--disable-directwrite-for-ui


text:
Q: AWK: how to sort column in awk script as part of a for loop I have the following awk script:
#!/usr/bin/env bash

awk '
        BEGIN{
        FS=OFS="\t";
        printf "\n\n%33-s\t%20-s",
        "Description", "Amount"
        printf "\n-------------------------------------------------- \n";
        }
        {
        if ($3 > 0) {
                a[$7] += $3;
                sa += $3;
        }
        else {
                b[$7] += $3;
                sb += $3;
        }
        }
        END{
        print "INCOME" "\n";
        for (i in a) {
                printf "%-33s\t%-20 .2f\n", i, a[i];
        }
        printf "%-33s\t%-20 .2f\n", "\nTOTAL INCOME", sa;
        print "\n""\n" "EXPENSES" "\n";
        for (j in b) {
                printf "%-33s\t%-20 .2f\n", j, b[j];
        }
        printf "%-33s\t%-20 .2f\n", "\nTOTAL EXPENSES", sb;
        }
' "${@:--}"

This prints the following as expected after running ./report out.txt:
Description                         Amount
--------------------------------------------------
INCOME

Client Income                        65855.52
Other Income                         33496.21
Refunds                              24072.49
Transfers                            66445.38
Rental Income                        74505.46
Tax Refunds                          2200.16
Salaries & Wages                     234198.04
Interest                             4.07

TOTAL INCOME                         500777.33

EXPENSES

Business - Miscellaneous            -473.55
Government                          -985.83
Personal Expenditures               -89212.40
Hiring & Rentals                    -3271.20
Travel                              -24148.74
Accounting & Legal                  -3091.20
Bank – Charges                      -1106.87
Motor Vehicle – Miscellaneous       -153.59
Vehicle Miscellaneous               -70.00
Capex                               -18186.76
Food - Fast Food                    -3004.19
Christian to Edorne                 -1018.88
Business – Miscellaneous            -63.09
Bank – Withdrawals                  -5720.00
IT – Subscriptions                  -1077.95
Property – Rent                     -60100.00
Food – Groceries                    -65760.27
Equipment Hiring                    -3325.00
Property – Maintenance              -13956.72
Transfers Overseas                  -27638.31
Property – Bond                     -1800.00
Business – Repairs & Maintenance    -1362.25
Weed Spray Chemicals                -133.17
Transport                           -218.40
Motor Vehicle Expenses              -862.52
Business – ACC                      -206.04
Education                           -1515.04
Office & Stationary                 -323.34
Food – Liquor                       -405.55
Petrol - Vehicle                    -10341.62
Petrol - Equipment                  -823.12
Transfers                           -211239.22
Property - Maintenance              -10762.56
Business – Storage                  -1659.50
Motor Vehicle – Parking             -39.90
Motor Vehicle – WOF                 -264.05
IT – ISP                            -14706.36
Tax                                 -11783.08
Food – Fast Food                    -4410.23
Electricity                         -6980.73
Christian to Crewcut                -20.95
Healthcare                          -7250.95
Vehicle – Maintenance               -302.00
Food – Eating Out                   -6209.95
Business Services – Mail            -400.00
Household                           -2190.58
Edorne to Christian                 -4961.30
Salaries & Wages                    -55634.21
Miscellaneous                       -1788.81
Insurance                           -2623.96
Motor Vehicle – Maintenance         -4711.62
Property – Body Corporate           -26736.16
Principal & Interest                -12605.61
Property – Rates                    -16336.82

TOTAL EXPENSES                      -743974.15

My question is how can I sort the income and expense items in alphabetical order (first column)? I have tried to sort the first column by changing the for loop lines to
printf "%-33s\t%-20 .2f\n", i, a[i] | "sort -u";
printf "%-33s\t%-20 .2f\n", j, b[j] | "sort -u";

which does not work.
I am not really able to provide source data for security reasons and due to the vast amount of data. My hope is that someone can help me with this anyway as my question is rather general in nature.

A: With GNU awk you can control array scanning via PROCINFO["sorted_in"] to sort arrays (by index or data) so that for (index in array) processes the array in the desired order.
Adding this to your END block processing would look like:
    END{

    PROCINFO["sorted_in"]="@ind_str_asc"                 # sort array by index based on "string" data and in "ascending" order

    print "INCOME" "\n"
    for (j in a) {
            printf "%-33s\t%-20 .2f\n", i, a[i];
    }
    printf "%-33s\t%-20 .2f\n", "\nTOTAL INCOME", sa;
    print "\n""\n" "EXPENSES" "\n"
    for (j in b) {
            printf "%-33s\t%-20 .2f\n", j, b[j];
    }
    printf "%-33s\t%-20 .2f\n", "\nTOTAL EXPENSES", sb
    }

NOTE: once set the PROCINFO["sorted_in"] applies to all array references until either the end of the awk script or until a new PROCINFO["sorted_in"] is applied

A: I think that you will find it easier to sort the date before running this script. You don't tell us where it's coming from but either specify sort column or pipe it through awk '{ print $3 $7}' | sort


text:
Q: Joomla 3.2.1 Module Layout Override: Need to move category title subheading above grouped article titles I'm trying to create a mod_articles_category layout override for a Joomla 3.2.1 site.
I have 1 parent article category and about 10 child categories under it.
The default is to display the category title in parentheses beneath each article title, which looks crowded and repetitive.
What I'd like to do is display each category title subheading once above each child group of article titles.
So far, I've got it to display the category title (see comment below) but for some strange reason, it is displaying underneath the group of articles it relates to, instead of above it. How can I get it to move above each child group of article titles?
Thanks in advance for any tips.
======================
<ul class="category-module<?php echo $moduleclass_sfx; ?>">
<?php if ($grouped) : ?>
<?php foreach ($list as $group_name => $group) : ?>

<?php if ($item->displayCategoryTitle) :?>

<?php echo $item->displayCategoryTitle; ?>

<?php endif; ?>

<?php foreach ($group as $item) : ?>

<?php if ($params->get('link_titles') == 1) : ?>
<a class="mod-articles-category-title <?php echo $item->active; ?>" href="<?php echo $item->link; ?>">
<?php echo $item->title; ?>

<?php else : ?>
<?php echo $item->title; ?>
<?php endif; ?>

<?php if ($item->displayHits) : ?>

(<?php echo $item->displayHits; ?>)

<?php endif; ?>

<?php if ($params->get('show_author')) :?>

<?php echo $item->displayAuthorName; ?>

<?php endif;?>

<?php if ($item->displayDate) : ?>
<?php echo $item->displayDate; ?>
<?php endif; ?>

<?php if ($params->get('show_introtext')) :?>

<?php echo $item->displayIntrotext; ?>

<?php endif; ?>

<?php if ($params->get('show_readmore')) :?>

<a class="mod-articles-category-title <?php echo $item->active; ?>" href="<?php echo $item->link; ?>">
<?php if ($item->params->get('access-view') == false) :
echo JText::_('MOD_ARTICLES_CATEGORY_REGISTER_TO_READ_MORE');
elseif ($readmore = $item->alternative_readmore) :
echo $readmore;
echo JHtml::_('string.truncate', $item->title, $params->get('readmore_limit'));
if ($params->get('show_readmore_title', 0) != 0) :
echo JHtml::_('string.truncate', ($this->item->title), $params->get('readmore_limit'));
endif;
elseif ($params->get('show_readmore_title', 0) == 0) :
echo JText::sprintf('MOD_ARTICLES_CATEGORY_READ_MORE_TITLE');
else :
echo JText::_('MOD_ARTICLES_CATEGORY_READ_MORE');
echo JHtml::_('string.truncate', ($item->title), $params->get('readmore_limit'));
endif; ?>

<?php endif; ?>

<?php endforeach; ?>

<?php endforeach; ?>

A: Change
<?php if ($item->displayCategoryTitle) :?>

<?php echo $item->displayCategoryTitle; ?>

<?php endif; ?>

to

<?php echo $group_name; ?>


text:
Q: How do I write a rewrite rule for a virtual host in Apache? I have a subversion server that is working fine; however, I bought a tool that requires that the project have a "branches" subdirectory an is case sensitive. The entire repository already has projects with a "Branches" folder so I'm trying to write in a rewrite to the httpd.conf file. I've got the LoadModule uncommented and turned the RewriteEngine on, Apache starts but I don't get my desired result.
RewriteRule ^/Root/(.+)/branches(.*)  /Root/$1/Branches$2

If I use a RedirectMatch it works in the browser but still doesn't work in tool.
RedirectMatch ^/Root/(.+)/branches(.*)  /Root/$1/Branches$2

I understand that Rewrite typically for rewriting to a file or physical location but I've seen some similar example when trying to solve mine. I am open to other approaches, I've looked into the < If > but it is beyond me.

A: Finally figured it out
    RewriteRule ^/Root/(.+)/branches(.*)  http://svn/Root/$1/Branches$2 [P]

Since it is virtual I needed to include the absolute web URL. Without the [P] flag (proxy) it was returning a 302 redirect, with the flag the server only handles the request and the client is simply returned the correct page from the single request.


text:
Q: Dispatch isn't called when I use bindActionCreators I'm able to get an input to update my redux store onChange if I explicitly write out the dispatch function. Why does it stop working when I try to use bindActionCreators()?
not using bindActionCreators (this works)
@connect(
  state => ({}),
  dispatch => {
    return {
      onSearchChange: (term) => {
        dispatch(search(term));
      }
    };
  }
)

export default class SearchForm extends Component {
  render() {
    return (
      <input type="text" onChange={(event) => onSearchChange(event.target.value)} />
    );
  }
}

using bindActionCreators (this does not work. It never dispatches the action)
@connect(
  state => ({ categories: state.categories.data }),
  dispatch => bindActionCreators({search}, dispatch)
);

export default class SearchForm extends Component {
  render() {
    return (
      <input type="text" onChange={(event) => search(event.target.value)} />
    );
  }
}

A: There are a couple issues here that seem to be syntactical and unrelated to Redux; they could be copy-paste errors, or actual issues:

*

*Your second example contains a syntax error; there should not be a semicolon at the end of the decorator:

repl: Leading decorators must be attached to a class declaration (4:1)
  2 |   state => ({ categories: state.categories.data }),
  3 |   dispatch => bindActionCreators({search}, dispatch)
  4 | );
    |  ^

*The functions you're calling in the event handler (in both examples) don't seem to be defined; for them to work as written, you'd need to extract the function from this.props:
export default class SearchForm extends Component {
  render() {
    const { search } = this.props;
    return (
      <input type="text" onChange={(event) => search(event.target.value)} />
    );
  }
}

If the examples are as written here in your code, I would expect the first example to fail unless there was an onSearchChange function declared in scope.
As a shortcut, connect can accept a simple object as a second argument, and it will assume each value on the object is an action creator for it to bind to:
@connect(
  state => ({ categories: state.categories.data }),
  { search }
)
export default class SearchForm extends Component {

[Edit]
Since you import search via
import {search} from 'redux/modules/repo-search';

you can import it instead with an alias
import { search as searchActionCreator } from 'redux/modules/repo-search';

If you do this, then connect needs to know the value you really want to use for the prop:
@connect(
  state => ({ categories: state.categories.data }),
  {search: searchActionCreator}
)
export default class SearchForm extends Component {
  render() {
    const { search } = this.props;
    return (
      <input type="text" onChange={(event) => search(event.target.value)} />
    );
  }
}

Alternatively, simply use a different variable name, or the path to the function in this.props, inside render:
return (
  <input type="text" onChange={(event) => this.props.search(event.target.value)} />
);


text:
Q: Kentico dynamic content Context:
Using kentico 5.5 R2.
We have 6 product types (workshops, under those types there are several workshops which are unique by date and location). They each share the same registration process but on the last step the content changes depending on the product chosen. In the CMS they share the first 2 steps of the registration and they are pages, the last page is a blank page, and the unique content pieces are sub pages in a folder.
Somehow the devs loaded the dynamic content in the final page (called Register-Step-Done), and I can't seem to find any logic or anything in the CMS that makes this work. i.e. something that says Product Type A uses Content A.
We are trying to add a 7th product type, I've added the unique content piece just like the others (as a sub page in the same folder with the same naming convention), but when it hits the final step for this new 7th product it's just blank (Register-Step-Done) and not loading that unique content in.

A: Well turns out the original devs put a custom case statement in a file in \App_Code\Util\ and hardcoded some CMS page names to get it all working.... Very frustrating experience.


text:
Q: VB asp.net detect if the pdf has a hand written signature We have a document that requires two hand written signatures.
We email or fax the document to person A.
Person A signs it and fax/emails it back to us.
We need to then upload the signed pdf into our web app we developed and we need to have the system auto check if there is a signature in the area for Person A.  We could put an identifier next to where they should sign so it know to look for pixels in that area or how else can we tell it to look for a signature or more than X amount of pixels next to an identifier.
We then take the document signed by person A and send it to person B  They sign it and send it back to us and we need the same process to happen.  Look to the designated area where B signs  so we can auto mark that document as B signature.


text:
Q: How long does a Pokémon stay in one location? If a friend encounters a Pokémon, it doesn't disappear directly. So I should be able to catch it, as well.
My question is, how long does it stay there? Can I still expect to find it there a few hours later, or even a day later?

A: Pokemon do not "move" in GO. Once they spawn in a location, they tend to stay there until despawn.
Pokemon have an attribute which controls spawn behavior (likely TimeTillHiddenMs and ExpirationTimeMs in the protobuf files), which determines their spawn length. For the most part, Pokemon will despawn either 15, 30, or 45 minutes after initially spawning, although some outliers do exist as this is a server-side variable.

A: Once a Pokemon spawns in an area, they do not move in that area until they despawn. So generally they will be in the same spot for 15 minutes.
What's not clear is when they despawn, there does seem to be a better than random chance they will respawn in an adjacent area. I'm not sure how big a game area is, but it is at least several city blocks.

A: I'm not convinced of the answer above. All the 'good' Pokemon I come across seem to move around frequently, and quickly until they show up on the screen. One moment it'll appear, and it'll be gone just a couple minutes into the search, or the foot-prints for a single Pokemon will increase or decrease without my even moving.

A: According to the Silph Road, on 2016/11/05, Niantic updated a pokemon's spawn timer mechanics such that pokemon spawn in one place for 30 minutes and then despawn.
I have looked at pokemon, refreshed the game every minute, and a pokemon despawns after 30 minutes or occasionally 1 hour. There is a Silph Road thread with more discussion.

A: I agree that pokemon move around and usually quickly.  I don't know if they respawn in the same are or not. I was with someone who caught a Pikachu.  We haven't returned to see if another spawned in that area.
But pokemon do move and disappear from a certain territory.  Our thought is they don't respawn in the same area but I havent found any proof either way.

A: I have spawns over by the next door neighbors and two, two houses down that I can reach from the edge of my property. They spawn random pokemon on the hour in the exact same spots. One spawns exactly on the hour and the other two, 10 minutes later. They despawn after 15 minutes. The last half hour, there is nothing to get. My guess is the spawn areas marked by the ruffling leaves flying up as you look around have different clockwork spawn and despawn times. There seems to be as I can tell 3 spawns per spawn location. There could be more and my radar doesn't quite reach the a far spawn in the location two houses down, approximately 150 feet from the edge of my property line.


text:
Q: MySQL Connector C++ build from source in Visual Studio 2013 I am trying to build the mySQL Connector C++ from source in Visual Studio 2013 Running CMake produces a project file, but that project file doesn't compile because of a big list errors and an even bigger list of warnings.
Building Custom Rule C:/mysql-connector-c++-1.1.3/test/framework/CMakeLists.txt
  CMake does not need to re-run because C:\mysql-connector-c++-1.1.3\test\framework\CMakeFiles\generate.stamp is up-to-date.
  test_suite.cpp
C:\mysql-connector-c++-1.1.3\cppconn/exception.h(61): warning C4251: sql::SQLException::sql_state: class "std::basic_string<char,std::char_traits<char>,std::allocator<char>>" needs to have dll-interface to be used class "sql::SQLException"
  test_factory.cpp
C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\stdlib.h(546): error C2146: syntax error : missing ")" before identifier "_Str"
C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\stdlib.h(546): error C2065: _Str: undeclared identifier
C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\stdlib.h(546): warning C4229: anachronism used : modifiers on data are ignored
C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\stdlib.h(546): error C2365: _strtoi64: redefinition; previous definition was 'function'

C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\cstdlib(39): error C2039: strtoll: is not a member of '`global namespace''
C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\cstdlib(39): error C2873: strtoll: symbol cannot be used in a using-declaration

Could some one please list all the steps in successfully compiling the C++ Connector?


text:
Q: Como ordenar los valores en un diccionario de python tengo un problema con el desarrollo de un algoritmo de ordenamiento de diccionarios en python. Se me da un diccionario y se me pide que, mediante merge sort(no esta permitido usar built-in functions) ordene este diccionario de tal manera que el value vaya en orden ascendete. Todo esto debe lograrse en aproximadamente 1 segundo, me dicen que el problema esta en doble loop for del final, que eso es lo que causa la demora. como puedo solucionar ese inconveniente del doble loop for? aqui esta la parte importante del codigo:
    def orden(lista):
        if len(lista) > 1:
            mid = len(lista) // 2
            lefthalf = lista[:mid]
            righthalf = lista[mid:]

            orden(lefthalf)
            orden(righthalf)

            i = 0
            j = 0
            k = 0
            while i < len(lefthalf) and j < len(righthalf):
                if lefthalf[i] <= righthalf[j]:
                    lista[k] = lefthalf[i]
                    i = i + 1
                else:
                    lista[k] = righthalf[j]
                    j = j + 1
                k = k + 1

            while i < len(lefthalf):
                lista[k] = lefthalf[i]
                i = i + 1
                k = k + 1

            while j < len(righthalf):
                lista[k] = righthalf[j]
                j = j + 1
                k = k + 1
        return lista

    lista = list(self.futbol.values())

    orden(lista)
    diccionario = {}

    for i in lista:
       for j in self.futbol.keys():
           if self.futbol[j] == i:
               diccionario[j] = self.futbol[j]
               break

A: Aviso
Lo primero comentar un defecto del propio enunciado del problema, y es el concepto de "ordenar un diccionario". Los diccionarios no tienen orden interno, por lo que dependiendo de la versión de python que uses es posible que, pese a todo el trabajo que te tomas en ordenar el diccionario, al llegar al final e imprimir el resultado lo veas "desordenado", ya que en versiones anteriores a Python 3.7 los diccionarios no garantizaban el orden de inserción.
Esto quiere decir que aunque tú primero hagas diccionario["a"] = 1 y después diccionario["b"] = 0, cuando muestres el diccionario perfectamente podrías encontrarte {'b': 0, 'a': 1} en vez de {'a': 1, 'b': 0} como podrías esperar. Y lo mismo si iteras por el diccionario, diccionario.items() puede retornarte las claves en cualquier orden impredecible.
Esto cambió en Python 3.7 y ahora, a partir de esa versión, sí se garantiza el orden de inserción. Es decir, que las claves serán retornadas en el mismo orden en que fueron insertadas en el diccionario.
Solución
Dicho lo anterior, y suponiendo que trabajas con Python 3.7 o superior, sí sería posible crear un diccionario "ordenado" en el sentido en que se pide en el enunciado.
La solución puede ser muy simple si te das cuenta de que la función orden() que has programado funciona para cualquier lista que le pases, sea cual sea el contenido de esa lista, con tal de que los elementos de la misma se puedan comparar entre sí. Lo mismo te sirve para ordenar listas de números (que es para lo que la has usado), que listas de cadenas, por ejemplo, ya que las cadenas también se pueden comparar entre sí, y toda la clave de la ordenación descansa en la comparación lefthalf[i] <= righthalf[j] que simplemente compara dos elementos de la lista.
En particular, también funciona para ordenar listas de tuplas. Si la lista que le pasas en vez de contener números contiene parejas de datos, se ordenará correctamente porque python permite comparar una tupla con otra. Por ejemplo, esta comparación sería cierta:
  (1, "Pepe") <= (3, "Juan")

Pues para comparar tuplas python compara antes sus primeros elementos y en este caso es cierto que 1 <= 3.
Gracias a esto puedes construir una lista que, en vez de tener los valores del diccionario futbol, tenga parejas (valor, clave). La lista quedará ordenada por valores, pero cada valor llevará asociada una clave, que permitirá reconstruir el diccionario.
Tal lista puedes obtenerla así:
lista = [ (valor, clave) for clave, valor in self.futbol.items() ]

Después se la pasas a tu función:
orden(lista)

Y tu función te ordenará las tuplas por su primer elemento, es decir, por los valores del diccionario original. En base a esta lista puedes construir el diccionario ordenado:
diccionario = { clave: valor for valor, clave in lista }

Si no conoces esta sintaxis (comprensión de diccionarios) puedes hacer un bucle normal:
diccionario = {}
for valor, clave in lista:
  diccionario[clave] = valor


text:
Q: Howto Uninstall spree_auth_devise gem I have an existing Rails 5.1 application which already contains a custom user controller.
As I was following the instructions to install Spree, I installed the spree_auth_devise gem and ran the migrations and other install commands as advised on the readme page. As I began working with the gem I found that there was an issue with my User class, and this - of course - was because I had installed the devise gem when I am not using devise.
I have attempted to follow the instructions on how to set up a custom user model when not using devise, but after following these instructions and removing the spree_auth_devise I am unable to launch the site.
When I run the site with the gem installed, my custom routes for "login" etc, do not work. They point to the path where spree is installed and not that defined in my routes.rb.
I'm not sure what to do to remove the gem and get my user model working with spree. Any help is appreciated. I'm not sure what details or code to provide other than this as there are many files affected by this. I will post anything you feel may help.
UPDATE: Per the comment below, here are the spree-relevant portions of my routes.rb. Let me know if you need anything else:
mount Spree::Core::Engine, at: '/store'

get 'login'                                 =>  'sessions#new'
get 'signup'                                =>  'users#new'
delete  'logout'                            =>  'sessions#destroy'
post 'login'                                =>  'sessions#create'

UPDATE 2 I get this error when I try to launch the server or run rake db:migrate...
Exiting
/Users/user/sites/site/app/controllers/application_controller.rb:8:in `<class:ApplicationController>': uninitialized constant Spree::AuthenticationHelpers (NameError)
    from /Users/user/sites/site/app/controllers/application_controller.rb:1:in `<top (required)>'

A: Based on your information, try this:
Remove config/initializers/devise.rb if you haven't done it
remove any devise related code from your routes.rb
Might look similar to this:
devise_for :users, controllers: {
    confirmations: 'users/confirmations',
    passwords: 'users/passwords',
    registrations: 'users/registrations',
    sessions: 'users/sessions',
    unlocks: 'users/unlocks'
}

Check if there are is any code related to devise/spree_auth_devise
Might look like this in your User model:
devise :database_authenticatable, :registerable

Or in your ApplicationController or any other controller (git grep it):
before_action :authenticate_user!

Rollback your database changes (set STEP and RAILS_ENV appropirately):
rake db:rollback STEP=1 RAILS_ENV=development

If nothing helps, try a git revert or git reset
Regarding your error uninitialized constant Spree::AuthenticationHelpers
This module is defined in the spree_auth_gem here and also gets included to your ApplicationController in the engine.
If you did setup spree by this guide remove include Spree::AuthenticationHelpers from your ApplicationController.
Thes includes below might also be unnecessary. I would remove them 1 by 1 and see if your app still works:
include Spree::Core::ControllerHelpers::Auth
include Spree::Core::ControllerHelpers::Common
include Spree::Core::ControllerHelpers::Order
include Spree::Core::ControllerHelpers::Store
helper 'spree/base'


text:
Q: Unable to register user using Hyperledger membersrvc I have Hyperledger setup in Ubuntu using docker images for fabric-peer and membersrvc and I am trying to setup CA as per https://github.com/hyperledger/fabric/blob/master/docs/Setup/ca-setup.md
I started the docker containers using docker-compose up command but getting the following error when trying to login using POST /registrar API, with the following payload:
    {
  "enrollId": "test_vp0",
  "enrollSecret": "MwYpmSRjupbT"
}

But getting the following errors:
vp0_1         | 04:40:24.157 [rest] Register -> INFO 04c REST client login...
vp0_1         | 04:40:24.158 [rest] Register -> INFO 04d Local data store for client loginToken: /var/hyperledger/production/client/
vp0_1         | 04:40:24.158 [rest] Register -> INFO 04e Logging in user 'test_vp0' on REST interface...
vp0_1         | 04:40:24.158 [crypto] RegisterClient -> INFO 04f Registering client [test_vp0] with name [test_vp0]...
vp0_1         | 04:40:24.159 [crypto] Debugf -> DEBU 050 [client.test_vp0] Data will be stored at [/var/hyperledger/production/crypto/client/test_vp0]
vp0_1         | 04:40:24.159 [crypto] Debugf -> DEBU 051 [client.test_vp0] Keystore path [/var/hyperledger/production/crypto/client/test_vp0/ks] missing [true]: [<clean>]
vp0_1         | 04:40:24.159 [crypto] Debugf -> DEBU 052 [client.test_vp0] Creating Keystore at [/var/hyperledger/production/crypto/client/test_vp0/ks]...
vp0_1         | 04:40:24.160 [crypto] Debug -> DEBU 053 [client.test_vp0]  Open Keystore DB...
vp0_1         | 04:40:24.160 [crypto] Debug -> DEBU 054 [client.test_vp0]  Ping Keystore DB...
vp0_1         | 04:40:24.160 [crypto] Debugf -> DEBU 055 [client.test_vp0] Keystore created at [/var/hyperledger/production/crypto/client/test_vp0/ks].
vp0_1         | 04:40:24.160 [crypto] Debugf -> DEBU 056 [client.test_vp0] Keystore opened at [/var/hyperledger/production/crypto/client/test_vp0/ks]...done
vp0_1         | 04:40:24.160 [crypto] Debug -> DEBU 057 [client.test_vp0]  Registering node crypto engine...
vp0_1         | 04:40:24.160 [crypto] Debug -> DEBU 058 [client.test_vp0]  Initiliazing TLS...
vp0_1         | 04:40:24.161 [crypto] Debug -> DEBU 059 [client.test_vp0]  Initiliazing TLS...Disabled!!!
vp0_1         | 04:40:24.161 [crypto] Debug -> DEBU 05a [client.test_vp0]  Getting ECA client...
vp0_1         | 04:40:24.161 [crypto] Debugf -> DEBU 05b [client.test_vp0] Dial to addr:[localhost:7054], with serverName:[tlsca]...
vp0_1         | 04:40:24.161 [crypto] Debug -> DEBU 05c [client.test_vp0]  TLS disabled...
vp0_1         | 04:40:24.161 [crypto] Debug -> DEBU 05d [client.test_vp0]  Getting ECA client...done
**vp0_1         | 04:40:24.162 [crypto] Errorf -> ERRO 05e [client.test_vp0] Failed requesting read certificate [rpc error: code = 14 desc = grpc: RPC failed fast due to transport failure].
vp0_1         | 04:40:24.162 [crypto] Errorf -> ERRO 05f [client.test_vp0] Failed requesting ECA certificate [rpc error: code = 14 desc = grpc: RPC failed fast due to transport failure].
vp0_1         | 04:40:24.162 [crypto] Errorf -> ERRO 060 [client.test_vp0] Failed getting ECA certificate [rpc error: code = 14 desc = grpc: RPC failed fast due to transport failure].
vp0_1         | 04:40:24.162 [crypto] Errorf -> ERRO 061 [client.test_vp0] Failed retrieving ECA certs chain [rpc error: code = 14 desc = grpc: RPC failed fast due to transport failure].
vp0_1         | 04:40:24.163 [crypto] Errorf -> ERRO 062 [client.test_vp0] Failed registering node crypto engine [rpc error: code = 14 desc = grpc: RPC failed fast due to transport failure].
vp0_1         | 04:40:24.163 [crypto] Errorf -> ERRO 063 [client.test_vp0] Failed registering client [test_vp0]: [rpc error: code = 14 desc = grpc: RPC failed fast due to transport failure]
vp0_1         | 04:40:24.163 [crypto] RegisterClient -> ERRO 064 Failed registering client [test_vp0] with name [test_vp0] [rpc error: code = 14 desc = grpc: RPC failed fast due to transport failure].
vp0_1         | 04:40:24.163 [rest] Register -> ERRO 065 Error on client login: rpc error: code = 14 desc = grpc: RPC failed fast due to transport failure
vp0_1         | 2016/10/13 04:40:24 grpc: addrConn.resetTransport failed to create client transport: connection error: desc = "transport: dial tcp [::1]:7054: getsockopt: connection refused"; Reconnecting to {"localhost:7054" <nil>}
vp0_1         | 2016/10/13 04:40:24 Failed to dial localhost:7054: grpc: the connection is closing; please retry.**

So how to resolve this issue?

A: Create a file called docker-compose.yml with the following content,
membersrvc:

  image: hyperledger/fabric-membersrvc:latest
  restart: unless-stopped
  expose:
    - "7054"
  volumes:
    - /var/run/docker.sock:/var/run/docker.sock
  command: membersrvc
    vp0:
      extends:
        file: peer-noops.yml
        service: vp
      hostname: vp0
      environment:
        - CORE_PEER_ID=vp0
        - CORE_SECURITY_ENABLED=true
        - CORE_SECURITY_ENROLLID=test_vp0
        - CORE_SECURITY_ENROLLSECRET=MwYpmSRjupbT
        - CORE_PEER_PKI_ECA_PADDR=membersrvc:7054
        - CORE_PEER_PKI_TCA_PADDR=membersrvc:7054
        - CORE_PEER_PKI_TLSCA_PADDR=membersrvc:7054
      ports:
        - "7050:7050"
        - "7051:7051"
      links:
        - membersrvc
      command: sh -c "sleep 5; peer node start"

create another file in the same directory and name it peer-noops.yml,
vp:
  image: hyperledger/fabric-peer:latest
  restart: unless-stopped
  environment:
    - CORE_PEER_ADDRESSAUTODETECT=true
    - CORE_PEER_NETWORKID=dev
    - CORE_LOGGING_LEVEL=info  #critical, error, warning, notice, info, debug
    # The following section enables pbft consensus
    - CORE_PEER_VALIDATOR_CONSENSUS_PLUGIN=noops  # noops, pbft
    - CORE_NOOPS_BLOCK_TIMEOUT=2s
    - CORE_NOOPS_BLOCK_WAIT=2s
  expose:
    - "7051"
    - "7052"
    - "7053"
  volumes:
    - /var/run/docker.sock:/var/run/docker.sock
  command: peer node start

run docker-compose up from the same directory.
Please read this for more details.


text:
Q: How to iterate from multidimention json array How do I iterate through a JSON return via jQuery and return the index of each object?
Examples of some of my code below:
 foreach ( x = somevalue  ; x < length of array ; x +++
{
            that x must be the index
         [0] => Array

          $('#actual_'+x).text(data.actual+" hrs.");
          $('#total_'+x).text(data.total+" hrs.");
          $('#regular_'+x).text(data.regular+" hrs.");

}

  (
[0] => Array
    (
        [actual] => 9
        [total] => 10
        [regular] => 0
        [over] => 11
        [total_h] => 11
        [eng_pay] => 148.5
        [rate] => 9
    )

[1] => Array
    (
        [actual] => -1
        [total] => 0
        [regular] => -1
        [over] => 2
        [total_h] => 1
        [eng_pay] => 18
        [rate] => 9
    )

)
I would like to iterate through this jQuery ajax widget's success function:
  $.ajax({
  type:'POST',
  url: 'cal_grid.php',
  dataType: 'json',
     cache: false,

      data:$('#grid_frm').serialize(),
      success: function(data)

      {

        alert(data);

      }  // response call back ends

    });//ajax call ends

A: untested, but should do the trick. throw this into your success function.
$.each($(data), function(i, obj){
   console.log(i); //spits out your index into console
});


text:
Q: phpseclib SSH2: Why won't my commands run? I'm trying to make a web interface for managing my Ubuntu hosted Minecraft server. I use screen in order to make the console re-accessible. I don't get why the following code does not work:

    $ssh->read('quadrplax@quadrplax-laptop:~$');
    $ssh->write("screen -rd\n");
    $ssh->write("stop\n");

Now, don't ask me why, but if I add in this useless code:

    $randid=rand(0, 1000000);
    $consolemsg=strval($randid);

    $ssh->read('quadrplax@quadrplax-laptop:~$');
    $ssh->write("screen -rd\n"); // note the "\n"
    $ssh->write("say Stopping server - ID:".$consolemsg."\n");
    echo $ssh->read(" [INFO] [Minecraft-Server] [Server] Stopping server - ID:".$consolemsg);
    $ssh->write("stop\n");

Then it will be able to get the screen session disconnected, but the page will then load for minutes before timing out. Sorry for how stupid this is, I can't find any good guides for phpseclib, they all are copies of the same guide and don't give any long examples. I have been able to get some things to work, for example my suspend code somehow works:

    $ssh->read('quadrplax@quadrplax-laptop:~$');
    $ssh->write("sudo pm-suspend\n");
    $ssh->setTimeout(5);
    $output = $ssh->read('#[pP]assword[^:]*:|quadrplax@quadrplax-computer:~\$#', NET_SSH2_READ_REGEX);
    $ssh->write("FAKEPASSWORD\n");

Sorry for formatting errors or anything, first time here. I had a hard time getting this post to submit. Can someone help me out with this?
Edit: Fixed a copy-paste error


text:
Q: Livereload snippet throwing error I'm using the livereload plugin with SublimeText3 and when I open SublimeText get this error:

Error parsing snippet xml: expected > in filePackages/User/livereload.sublime-snippet on line:6

Here's the code:
<snippet>
    <content>
<script>document.write('<script src="http://'
    + (location.host || 'localhost').split(':')[0]
    + ':35729/livereload.js?snipver=1"></'
    + 'script>')</script>
    </content>
    <!-- Optional: Set a tabTrigger to define how to trigger the snippet -->
    <tabTrigger>livereload</tabTrigger>
    <!-- Optional: Set a scope to limit where the snippet will trigger -->
    <!-- <scope>source.html</scope> -->
</snippet>

It's highlighting the < here: ...snipver=1"></'.
Note that it doesn't seem to affect it working, because LiveReload is indeed working but it's annoying every time I open SublimeText I get that error and can't determine why.

A: Your snippet is not valid XML, you should enclose your content in CDATA:
<snippet>
    <content><![CDATA[
<script>document.write('<script src="http://'
    + (location.host || 'localhost').split(':')[0]
    + ':35729/livereload.js?snipver=1"></'
    + 'script>')</script>
    ]]></content>
    <!-- Optional: Set a tabTrigger to define how to trigger the snippet -->
    <tabTrigger>livereload</tabTrigger>
    <!-- Optional: Set a scope to limit where the snippet will trigger -->
    <!-- <scope>source.html</scope> -->
</snippet>


text:
Q: Passing a CMake variable to C++ source code First of all, I already read How to read a CMake Variable in C++ source code, and I don't really know if it can help me.
Second, my question. Top level CMakeLists.txt says SET( MY_VAR /some/path ) and in top level source.cpp I need to achieve somehow a std::string containing /some/path/to/files naturally using MY_VAR value.

A: add_executable(myexe main.cpp)
if (MY_VAR)
    target_compile_definitions(myexe PRIVATE MY_VAR=${MY_VAR})
endif()

A: You can use the configure_file(filename output_file) command. It replaces something like ${VARIABLE} or @VARIABLE@ in file filename with the actual value of cmake variable VARIABLE and writes the result to output_file.
So, you can write something like
// in C++ code
std::string my_var = "@MY_VAR@";

# in CMakeLists.txt
configure_file(filename.h.in filename.h)

Also, I think it is a good idea for the output file to be generated somewhere inside build directory (and its' containing directory added to include paths).
configure_file in cmake documentation

A: The only way to pass in values during compilation is by passing a macro. E.g., if CMake sets a macro called $(MY_VAR) (as make(1) does):
g++ -DMY_VAR=$(MY_VAR) .... xxx.cc

and xxx.cc uses MY_VAR as it wishes.


text:
Q: Scanner object has a class attribute instead of in code initialisation Today, I have encounter a problem with Scanner object while programming a server/client application. I have solved the problem but I don't understand why my solution solved the problem.
At first, in my application I had some memory leak warning when compiling the project (JAVA 8, eclipse)
 because I was using Scanner to ask input from the user but didn't close it. When I try to close the scanner my other class where throwing exception like java.util.NoSuchElementException. I learned that I had a similar problem to : Cannot use multiple Scanner objects in Java but between classes. When I was closing a scanner in a class the other class (thread) scanner couldn't execute.  (java.util.NoSuchElementException)
The solution I found to solve this problem was to put a Scanner function as a class function member:
public class ClientThread extends Thread {

    private Scanner scanner;

   /*some code*/

}

When doing so I lost my memory leak warning.
Why having the scanner as a class member solved the warning ? Is it because of the class destructor ?

A: Usually, when you create a Scanner, you need to close it once you no longer need it.
The Scanner class has several, overloaded constructors where each one takes a different type of argument. There is a constructor that takes a File argument. There is a constructor that takes a Path argument. And there is a constructor that takes a InputStream argument. In order for your Java program to accept input from the user, via the computer keyboard, you use the constructor that takes an InputStream like so:
Scanner scanner = new Scanner(System.in);

This is because the static member in of class java.lang.System has type InputStream. You should think of System.in as encapsulating the keyboard on your computer. If you close System.in, it's like closing your keyboard and that is something you shouldn't do.
Now the Eclipse IDE is not smart enough to realize that your code is creating a Scanner that essentially encapsulates the computer keyboard (and therefore should not be closed). Eclipse only knows that any Scanner that you create should eventually be closed and since your code does not close the Scanner you created, Eclipse displays a warning that you haven't closed a Scanner that you created. In the displayed warning you are offered three suggestions on how to get rid of the warning. The first two refer to an annotation that you can add, namely
@SuppressWarnings("resource")

The third suggestion requires you to change the Eclipse configuration. You do this by selecting the Preferences item of the Window menu that appears at the top of the Eclipse IDE. In the Preferenes window, select Java > Compiler > Errors/Warnings and change the Resource leak setting to Ignore as shown in the following screen capture:

Note however, that this configuration setting applies to all resources, not just Scanner, so if you open a regular file in your java code and don't close it, Eclipse will not warn you.
Personally, I simply ignore the warning since I know that I should not close a Scanner created with System.in or I add an annotation.

A: Although Java usually auto-release the memory when you leave the scope some classes require special treatment.
Generally these are classes who has something to do with files and connections (to db or just sockets).
The latter is required  because the underlying OS requires those resource to be explicitly released (in general).
In the Java 8 there was introduced Autoclosable and it solves some of the problems but ultimately you need to be careful.
Here is an example for Scanner with autoclosable:
File file = new File("filename here");
try (Scanner in = new Scanner(file)) {
    // do something here, note you dont need close as it is autoclosable
}


text:
Q: UISearchBar in control segments I have a search bar that can be used to search for any item in the control segments ( all the shops ). And the control segment to filter the shop.
So :
the search is for all shops
the segments is to filter the shops
Here is how I saved the selected index
s.valueChange = { index in
            switch index {
            case 0 :
                self.selectedIndex = 0
                self.tableView.reloadData()
            case 1 :
                self.selectedIndex = 1
                self.tableView.reloadData()
            case 2 :
                self.selectedIndex = 2
                self.tableView.reloadData()
            case 3 :
                self.selectedIndex = 3
                self.tableView.reloadData()
            default:
                self.selectedIndex = 0
                self.tableView.reloadData()
            }

And this is number of rows in section
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if searchActive {
            return auxiliar.count
        } else {

        switch selectedIndex {
        case 0:
            return  allShops.count
        case 1:
            return self.coffee.count
        case 2:
            return self.restuarnt.count
        case 3:
            return self.pharmacy.count

        default:
            return   allShops.count
        }

        }
    }

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if searchActive

    {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! ShopTableViewCell
        let entry1 = auxiliar[indexPath.row]
        cell.shopName.text = entry1.shopname

        return cell
    } else {
    switch selectedIndex {
    case 0:
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! ShopTableViewCell
        let entry = shops[indexPath.row]
        cell.shopName.text = entry.shopname

        return cell

    case 1 :
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! ShopTableViewCell
        let entry = coffee[indexPath.row]
        cell.shopName.text = entry.shopname
        return cell

    case 2 :
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! ShopTableViewCell
        let entry = restuarnt[indexPath.row]
        cell.shopName.text = entry.shopname
        return cell

    case 3 :
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! ShopTableViewCell
        let entry = pharmacy[indexPath.row]
        cell.shopName.text = entry.shopname
        return cell

    default:
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! ShopTableViewCell
        let entry = shops[indexPath.row]
        cell.shopName.text = entry.shopname
        return cell
    }
    }
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)

        if searchActive {

            guard (auxiliar.count) > indexPath.row else {
                print("Index out of range")
                return
            }
            let meal1 = auxiliar[indexPath.row]
            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            var viewController = storyboard.instantiateViewController(withIdentifier: "viewControllerIdentifer") as! MealsDetailsController
            viewController.passedValue = (meal1.familiy_id)
            viewController.name = (meal1.shopname)
            print("\(meal1.familiy_id) im the search ")
            view.animateRandom()
            self.present(viewController, animated: true , completion: nil)

        } else {
        switch selectedIndex {
        case 0  :
            let meal1 =  shops[indexPath.row]
            guard (shops.count) > indexPath.row else {
                print("Index out of range")
                return
            }
            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            var viewController = storyboard.instantiateViewController(withIdentifier: "viewControllerIdentifer") as! MealsDetailsController
            viewController.passedValue = (meal1.familiy_id)
            viewController.name = (meal1.shopname)
            print("\(meal1.familiy_id) im the search ")
            view.animateRandom()
            self.present(viewController, animated: true , completion: nil)

        case 1 :
            let meal1 =  coffee[indexPath.row]

            guard (coffee.count) > indexPath.row else {
                print("Index out of range")
                return
            }

... the rest of the cases

And finally the  textDidChange
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        auxiliar = shops.filter { $0.shopname.range(of: searchText, options: .caseInsensitive, range: nil, locale: nil) != nil}
        if searchText == "" || searchBar.text == nil {
            auxiliar = shops
        }
        tableView.reloadData()
    }

  func searchBarTextDidBeginEditing(_ searchBar: UISearchBar)
    {
        self.searchActive = true
    }

    func searchBarTextDidEndEditing(_ searchBar: UISearchBar)
    {
        self.searchActive = true
    }

    func searchBarCancelButtonClicked(_ searchBar: UISearchBar)
    {
        self.searchActive = false
    }

    func searchBarSearchButtonClicked(_ searchBar: UISearchBar)
    {
        self.searchActive = false
    }

    func searchBarBookmarkButtonClicked(_ searchBar: UISearchBar) {
        self.searchActive = false

    }

The Problem
When I search for a shop the results are coming fine in all the segments. But when I end the search and change the segments all the segments after search has the rows of segment 0 ( selectedIndex = 0 ) and never change again
Also when I click on the X button inside search bar the app crashes
What I want :
After ending search and search bar is "" or nill, I want to click on any segment and the shops belong to that segment appear.


text:
Q: create your own swing component A software component is required which allows to find a given word in a given passage, whenever the component find the desired word in the passage the components will invoke all the listener that are attached to it that it has find the desired word.
This component must be used from a Swing UI based application showing user a text field to take a word and a text area for passage. There must be a label which will update its value showing count that how many times the given word has been found within the given passage.
this is my code it's displya gui but count field is not changed or set.
import java.awt.EventQueue;

public class compomentex implements ActionListener{

private JFrame frame;
private JTextField textField;
private JTextField textField_1;
private JTextArea textArea;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                compomentex window = new compomentex();
                window.frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

public interface wordsearcherinterface
{
    public void wordsearch();
}
public class wordsearcher implements wordsearcherinterface
{
    public String word;
    public String paragraph;

    public void addwordsearch(wordsearcherinterface obj)
    {
        obj.wordsearch();
    }

    public void wordsearch()
    {
        //if(event.getSource()==Check)
        String word;
        String Words;
        String [] Words2;
        int disp=0;
         word=textField.getText();

        Words=textArea.getText();
        Words2=Words.split(" ");

        for(int i=0;i<Words2.length;i++)
        {
            if(Words2[i].equals(word))
            {
                    disp++;

            }
        }

        String show;
        show=disp+"";
        textField_1.setText(show);
        if(disp==0)
        {
            JOptionPane.showMessageDialog(null, "The Word is not present int Passage");
        }

    }

}

 * Create the application.
public compomentex() {
    initialize();

}

/**
 * Initialize the contents of the frame.
 */
private void initialize() {
    frame = new JFrame();
    frame.setBounds(100, 100, 450, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);

    JLabel lblWord = new JLabel("WORD");
    lblWord.setBounds(29, 81, 46, 14);
    frame.getContentPane().add(lblWord);

    textField = new JTextField();
    textField.setBounds(121, 78, 86, 20);
    frame.getContentPane().add(textField);
    textField.setColumns(10);

    JLabel lblPassage = new JLabel("PASSAGE");
    lblPassage.setBounds(29, 143, 46, 14);
    frame.getContentPane().add(lblPassage);

    JTextArea textArea = new JTextArea();
    textArea.setBounds(97, 161, 196, 90);
    frame.getContentPane().add(textArea);

    JButton btnCheck = new JButton("CHECK");
    btnCheck.setBounds(326, 213, 98, 23);
    frame.getContentPane().add(btnCheck);

    JLabel lblSeeker = new JLabel("SEEKER");
    lblSeeker.setBounds(161, 11, 46, 14);
    frame.getContentPane().add(lblSeeker);

    JLabel lblCount = new JLabel("COUNT");
    lblCount.setBounds(349, 81, 46, 14);
    frame.getContentPane().add(lblCount);

    textField_1 = new JTextField();
    textField_1.setBounds(325, 106, 86, 20);
    frame.getContentPane().add(textField_1);
    textField_1.setColumns(10);

}

@Override
public void actionPerformed(ActionEvent arg0) {
    // TODO Auto-generated method stub

}
}

Thanks in advance

A: There are lots of issues in your code. I have mentioned corrected code below. Please correct.
First - actionPerformed method is empty.
@Override
public void actionPerformed(ActionEvent arg0) {
    new wordsearcher().wordsearch();
}

Second - instance variable textArea is not initialized.
textArea = new JTextArea();

Third - ActionListener is not added on button btnCheck
btnCheck.addActionListener(this);


text:
Q: Trouble with parsing, target contains a hyphen I'm trying to get some information from an RSS feed, more specifically the data contained in the "filing-type" section. However the section contains a hyphen and so when i run the code:
import feedparser
BEGIN_URL = "https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&CIK="
FINISH_URL = "&type=&dateb=&owner=include&start=0&count=40&output=atom"
def check_sec_rss(ticker):
    TARGET_URL = BEGIN_URL+ticker+FINISH_URL
    feed = feedparser.parse(TARGET_URL)
    for post in feed.entries:
        print(post.filing-type)

check_sec_rss("AAPL")

I get an error:
Traceback (most recent call last):
  File "D:/icsusV0.1/test3.py", line 10, in <module>
    check_sec_rss("APDN")
  File "D:/icsusV0.1/test3.py", line 8, in check_sec_rss
    print(post.filing-type)
  File "C:\Users\domin\AppData\Local\Programs\Python\Python38-32\lib\site-packages\feedparser.py", line 400, in __getattr__
    raise AttributeError("object has no attribute '%s'" % key)
AttributeError: object has no attribute 'filing'

Can someone point me in the right direction?

A: Managed it through trial and error...
print(post['filing-type'])


text:
Q: What is the purpose of 'i' in this css rule : input[type="color" i]? What does the "i" stand for in this css rule defined by the user-agent default stylesheet (chromium 81)?
input[type="color" i] { /* user agent stylesheet */
    ...
    padding: 1px 2px;
}

And can I define my own rule to unset the padding?

A: See an answer in What does "i" mean in a CSS attribute selector?.
For unset the padding, you can create your own input[type="color"]. If the order is not okay, add !important after padding (eg. padding: 1px 2px !important;).


text:
Q: Show $\lim_{n\to\infty}\frac{\int_X|f|^{n+1}d\mu}{\int_X|f|^nd\mu}=\|f\|_\infty$. Suppose $\mu$ is a positive measure on $X$, $\mu(X)<\infty$, $f\in L^\infty(\mu)$, $\|f\|_\infty>0$, and
$$\alpha_n=\int_X|f|^nd\mu\quad(n=1,2,3,\ldots).$$
How to show that
$$\lim_{n\to\infty}\frac{\alpha_{n+1}}{\alpha_n}=\|f\|_\infty?$$

A: Hint:  Show
$$\|f\|_\infty \leqslant \liminf_{n\to\infty}\frac{\alpha_{n+1}}{\alpha_n} \leqslant \limsup_{n\to\infty}\frac{\alpha_{n+1}}{\alpha_n}\leqslant \|f\|_\infty$$
First Inequality
Using Holder's Inequality with $1/p = n/(n+1)$ and $1/q = 1/(n+1)$:
$$\int_X|f|^{n}\,\mathrm{d}\mu \leqslant \left(\int_X|f|^{n+1}\,\mathrm{d}\mu\right)^{n/(n+1)}\left(\int_X\,\mathrm{d}\mu\right)^{1/(n+1)} = \left(\int_X|f|^{n+1}\,\mathrm{d}\mu\right)^{n/(n+1)}\left[\mu(X)\right]^{1/(n+1)}.$$
Then,
$$\frac{\int_X|f|^{n+1}\,\mathrm{d}\mu}{\int_X|f|^{n}\,\mathrm{d}\mu} \geqslant \left(\int_X|f|^{n+1}\,\mathrm{d}\mu\right)^{1/(n+1)}\left[\mu(X)\right]^{-1/(n+1)},$$
and
$$\liminf_{n\to\infty} \frac{\int_X|f|^{n+1}\,\mathrm{d}\mu}{\int_X|f|^{n}\,\mathrm{d}\mu} \geqslant \lim_{n\to\infty}\left(\int_X|f|^{n+1}\,\mathrm{d}\mu\right)^{1/(n+1)}\lim_{n\to\infty}\left[\mu(X)^{-1}\right]^{1/(n+1)}$$
Can you find the limits on the RHS?
Proving the second inequality is straightforward.


text:
Q: Can see MOSS 2007 image as admin, but not as user - cannot figure out I'm hoping someone can help me figure this out. First, to help you understand what we use here, we have MOSS 2007. We have three different site collections set up. From each site collection, I create sites and sub-sites. A mock-up of the path would be:
//site-collectionsp.com/site/sub-site
I'm having problems getting the logo to display for people who have access only to the sub-site and not to the site collection nor upper-level site. For this particular issue, the path of this sub-site is (all paths in this message - except links to images - are mock-ups and not real):
//site-collectionsp.com/site/sub-site
I created a logo and and, using SP Designer, placed the logo onto the sub-site's server. The URL would be:
//site-collectionsp.com/site/sub-site/test-logo.jpg
I closed Designer and typed the full URL in the browser window, copied it, then, under title, description, and icon, I placed the direct URL for the logo URL.

Since I am the admin, I went to the sub-site and the logo displays like it should. See image below:

I logged out and then logged into the site as someone else (Lisa). This other person ONLY has access to the sub-site and not the site-collection nor site. When I logged in as her, the logo does not display. See image below:

So I then went back into Designer. I opened up the master page and looked at the code; I'm looking at the path of the logo and for some odd reason, there is some other logo, a GIF image, as the logo and not the one I placed on the server. See image below:

Furthermore, in Designer, I cannot see the _layouts folder on the server (maybe because I am do not have top admin rights; I'm not sure why). So as a work-around to see if I can get this logo to appear for Lisa, I made a duplicate of the master page. I named it default2.master, opened it up in Designer, and looked at the logo code.
Because the logo is already on the server, with the path being "https://site-collectionsp.com/site/sub-site/test-logo.jpg" I changed the master2 code to simply "test-logo.jpg" and to further make sure that this new master page is working throughout the sub-site, I changed the header of it from Logo Test Site to Master 2. I then made this master page the new default of the sub-site. To see this code in Designer, look at image below:

To make sure all works, I logged in as admin and went to Lisa's library to see if logo still displays for me (the admin) and if header changed - it does. See image below:

At this point, you would think that if I log out as admin, then log back in as Lisa, and keeping in mind that I changed the logo path to recognize the one on the sub-site and not in the _layouts folder, you'd think the logo would display for Lisa. Does it? No, it does not. See image below:

Then, for one final good measure, I simply right-clicked on the browser displaying this library to view the source code. As you'll see below, the code is pointing to the correct logo! Then, if it is, why isn't it displaying when Lisa views her library? See below:

So, that's where I'm at and I'm hoping someone knows why this is and what I need to do to fix it.
Thanks.

A: Ok, first and foremost, check to see if that image is checked out. If it's checked out, you'll need to check it in, and probably publish it, for non-administrators to be able to see the image.
If it's not checked out, take a look at the security around the library where that image is stored and make sure that your normal users can view the items in that library; if they don't have access to the library and its contents, the image will be trimmed out by SharePoint's security model.

A: In the past we have added a site logo to the /TEMPLATE/LAYOUTS directory in the 12 Hive.
This way every site will have access to the logo using: /_layouts/logo.jpg and site permissions will not get in the way.
Alternatively, you create an admin site, giving all authenticated users read access to the site and library.


text:
Q: How to use collect and include for multidimensional array I have:
array1 = [[1,2,3,4,5],[7,8,9,10],[11,12,13,14]]
@student_ids = [1,2,3]

I want to replace elements in array1 that are included in @student_ids with 'X'. I want to see:
[['X','X','X',4,5],[7,8,9,10],[11,12,13,14]]

I have code that is intended to do this:
array1.collect! do |i|
  if i.include?(@student_ids) #
    i[i.index(@student_ids)] = 'X'; i # I want to replace all with X
  else
    i
  end
end

If @student_ids is 1, then it works, but if @student_ids has more than one element such as 1,2,3, it raises errors. Any help?

A: It's faster to use a hash or a set than to repeatedly test  [1,2,3].include?(n).
arr = [[1,2,3,4,5],[7,8,9,10],[11,12,13,14]]
ids = [1,2,3]

Use a hash
h = ids.product(["X"]).to_h
  #=> {1=>"X", 2=>"X", 3=>"X"}
arr.map { |a| a.map { |n| h.fetch(n, n) } }
  #=> [["X", "X", "X", 4, 5], [7, 8, 9, 10], [11, 12, 13, 14]]

See Hash#fetch.
Use a set
require 'set'

ids = ids.to_set
  #=> #<Set: {1, 2, 3}>
arr.map { |a| a.map { |n| ids.include?(n) ? "X" : n } }
  #=> [["X", "X", "X", 4, 5], [7, 8, 9, 10], [11, 12, 13, 14]]

Replace both maps with map! if the array is to be modified in place (mutated).

A: You can use each_with_index and replace the item you want:
array1 = [[1,2,3,4,5],[7,8,9,10],[11,12,13,14]]
@student_ids = [1,2,3]

array1.each_with_index do |sub_array, index|
  sub_array.each_with_index do |item, index2|
    array1[index][index2] = 'X' if @student_ids.include?(item)
  end
end

A: Try following, (taking @student_ids = [1, 2, 3])
array1.inject([]) { |m,a| m << a.map { |x| @student_ids.include?(x) ? 'X' : x } }

# => [["X", "X", "X", 4, 5], [7, 8, 9, 10], [11, 12, 13, 14]]

A: You can do the following:
def remove_student_ids(arr)
  arr.each_with_index do |value, index|
   arr[index] = 'X' if @student_ids.include?(value) }
  end
end

array1.map{ |sub_arr| remove_student_ids(sub_arr)}


text:
Q: Cocoapods error for one project target while others are working fine I have create 3 project target (Development, Production and Staging).Expect Production other working fine after pull the changes of others while building the production target xcode giving the error :

gone through some of the available solution but no success!!!

A: If you change something the conflict will be occur, do like remove your WorkSpace once and again install or update your Pods,it will Work

Run pod   install or pod update your CocoaPods installation.

For additional Information see this1
Choice-2

there's a problem with Cocoapods in your project.  Sometimes cocoapods can get out of sync and you need to re-initiate cocoapods. You should be able to resolve this error by:

*

*Deleting the Podfile.lock file in your project folder

*Deleting the Pods folder in your project folder

*Execute pod install in your project folder

*Do a Clean in Xcode

*Rebuild your project

Conclusion: don't run pod install while project opened in the Xcode.

Update answer
I. Project Cleanup

*

*In the project navigator, select your project

*Select your target

*Remove all libPods*.a in Linked Frameworks and Libraries
II. Update CocoaPods

*

*Launch Terminal and go to your project directory.

*Update CocoaPods using the command pod install

A: I have solved my problem by this way :
After implementing lot many solution i got this error :

By removing Check pods manifest.lock, Copy pods resources and Embed pods frameworks from Build Phases of Tests project target(xxxTests) i solved the issue.
NOTE: If any one still getting any issue related to pods, then try to remove libpods-xxx.a from Link Binary with libraries and again add it.


text:
Q: NavigationController not working ios 7 but works ios 8 and ios 6 I have ran into a problem. I have updated my code in my xcode project and now on ios 7 the navigationController no longer is working but on ios 8 and ios 6 everything is fine.
When app starts I initialize the navigationController with the HomeView
    UIViewController *viewController = [storyBoard instantiateViewControllerWithIdentifier:@"homeController"];
    navigationController  = [[UINavigationController alloc] initWithRootViewController:viewController];
    self.window.rootViewController = navigationController;

When i try to segue to another View in ios 7 the View segues but there is no navigation bar on the top nor any way to go back.
EditProfileController* profile = segue.destinationViewController;
profile.firstName = self.firstName;

When i try to push to a View in ios 7 nothing happens
ViewController* view = (ViewController *)[storyboard instantiateViewControllerWithIdentifier:@"viewController"];
[self.navigationController pushViewController:view animated:YES];

I have no idea what I have changed in my code that could of caused this problem. The only things i can think back that i changed and could of effected this was:

*

*Storyboard Constraints

*Screen Orientation

*Push Notification

*Added Google Analytics

*Added Crashlytics and Instabug

But i have no idea where with bug came from. I pulled up an older version of my project everything works fine on that version. So it must of been something I changed. Any advice is appreciated. Thanks guys!