text:
Q: How can I add another TextView in my Listview? I've made a ListView by following a tutorial on the web. It works great and exactly like I want it to. Now I'm trying to create another ListView in another activity but this time I need two TextViews, not one.
Here's my Adapter:
public class CustomListTwo extends ArrayAdapter<String> {

private final Activity context;
private final String[] web;
// private final String[] hex; <-- was trying to add this one but it gave me an error :(
private final Integer[] imageId;

public CustomListTwo(Activity context,
                     String[] web, Integer[] imageId) {
    super(context, R.layout.color_item_layout, web);
    this.context = context;
    this.web = web;
    this.imageId = imageId;
}

@Override
public View getView(int position, View view, ViewGroup parent) {
    LayoutInflater inflater = context.getLayoutInflater();

    View rowView= inflater.inflate(R.layout.color_item_layout, null, true);
    TextView txtTitle = (TextView) rowView.findViewById(R.id.item_value);
    ImageView imageView = (ImageView) rowView.findViewById(R.id.item_color);

    txtTitle.setText(web[position]);
    imageView.setImageResource(imageId[position]);

    return rowView;

    }
}

I'm trying to add "String[] hex;" but it gives me an error saying that the "variable may not be initialized". My idea was to duplicate everything that was written about the web variable and replace it with the hex variable and change the values.
Here's my activity:
public class ColorRed extends Activity {

ListView list;
String[] web;
Integer[] imageId = {
        R.color.red_50,
        R.color.red_100,
        R.color.red_200,
        R.color.red_300,
        R.color.red_400,
        R.color.red_500,
        R.color.red_600,
        R.color.red_700,
        R.color.red_800,
        R.color.red_900,
        R.color.red_A100,
        R.color.red_A200,
        R.color.red_A400,
        R.color.red_A700,
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_color_red);

    web = getResources().getStringArray(R.array.values);

    CustomListTwo adapter = new
            CustomListTwo(ColorRed.this, web, imageId);
    list=(ListView)findViewById(R.id.list_red);
    list.setAdapter(adapter);
    list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {
            switch (position){
                case 0: r50(view);
                    break;
                case 1: r50(view);
                    break;
                default:
                    r50(view);
                    break;
            }

          }
       });
    }

Here's my ListView item:
   <?xml version="1.0" encoding="utf-8"?>
   <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="72dp"
   android:background="?android:attr/selectableItemBackground">

   <ImageView
    android:background="?android:attr/selectableItemBackground"
    android:layout_width="match_parent"
    android:layout_height="72dp"
    android:id="@+id/item_color"
    android:src="@drawable/myrect" />

    <TextView
    android:id="@+id/item_hex"
    android:layout_width="wrap_content"
    android:layout_height="72dp"
    android:textColor="#de000000"
    android:textAllCaps="true"
    android:textSize="18sp"
    android:text="List Item"
    android:paddingRight="16dp"
    android:gravity="center_vertical"
    android:layout_centerVertical="true"
    android:layout_alignParentTop="true"
    android:layout_alignParentEnd="true" />

   <TextView
    android:layout_width="wrap_content"
    android:layout_height="72dp"
    android:text="New Text"
    android:textColor="#de000000"
    android:textSize="18sp"
    android:id="@+id/item_value"
    android:layout_centerVertical="true"
    android:layout_alignParentTop="true"
    android:layout_alignParentStart="true"
    android:paddingLeft="16dp"
    android:gravity="center_vertical"/>

    </RelativeLayout>

So basicly, my question is how do I add a new TextView and load it with an array from strings.xml just like I do with the current TextView? I want the TextView "hex" to be populated with text from an array which I declare in strings.xml.
EDIT: My updated adapter:
    public class CustomListTwo extends ArrayAdapter<String> {

    private final Activity context;
    private final String[] web;
    private final String[] hex;
    private final Integer[] imageId;

    public CustomListTwo(Activity context, String[] web, String[] hex, Integer[] imageId) {
        super(context, R.layout.color_item_layout, web, hex);
        this.context = context;
        this.web = web;
        this.hex = hex;
        this.imageId = imageId;
    }

    @Override
    public View getView(int position, View view, ViewGroup parent) {
        LayoutInflater inflater = context.getLayoutInflater();

        View rowView= inflater.inflate(R.layout.color_item_layout, null, true);
        TextView txtTitle = (TextView) rowView.findViewById(R.id.item_value);
        ImageView imageView = (ImageView) rowView.findViewById(R.id.item_color);

        TextView txtHex = (TextView) rowView.findViewById(R.id.item_hex);
        txtHex.setText(hex[position]);

        txtTitle.setText(web[position]);
        imageView.setImageResource(imageId[position]);

        return rowView;
    }
}

Updated activity:
public class ColorRed extends Activity {

    ListView list;
    String[] web;
    String[] hex;
    Integer[] imageId = {
            R.color.red_50,
            R.color.red_100,
            R.color.red_200,
            R.color.red_300,
            R.color.red_400,
            R.color.red_500,
            R.color.red_600,
            R.color.red_700,
            R.color.red_800,
            R.color.red_900,
            R.color.red_A100,
            R.color.red_A200,
            R.color.red_A400,
            R.color.red_A700,
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_color_red);

        web = getResources().getStringArray(R.array.values);
        hex = getResources().getStringArray(R.array.hex_red);

        CustomListTwo adapter = new
                CustomListTwo(ColorRed.this, web, hex, imageId);
        list=(ListView)findViewById(R.id.list_red);
        list.setAdapter(adapter);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                switch (position){
                    case 0: r50(view);
                        break;
                    case 1: r50(view);
                        break;
                    default:
                        r50(view);
                        break;
                }

            }
        });
    }

Now I get an error in this code:
super(context, R.layout.color_item_layout, web, hex);

"Cannot resolve method"

A: You can't declare a final variable and not initialize it anywhere.
Pass the hex array in your adapter constructor, assign it to the hex[] in the adapter and use it in getView(..).


text:
Q: WPF: StringFormat on double value does not recognize custom windows region setting In my application I bind labels, textblocks etc. to double values in the view model.
<Label Content="{Binding DoubleValue}" ContentStringFormat="{}{0:0.00}">
<TextBlock Text="{Binding DoubleValue, StringFormat='\{0:f2\}'}"

In my "code behind" I set the language property of the MainWindow:
TheMainWindow.Language = XmlLanguage.GetLanguage(CultureInfo.CurrentUICulture.Name);

This works like a charm. When german culture is selected, all double values use the comma as decimal symbol and when english culture is selected, all double values use the point as decimal symbol.
The problem is when you customize the windows region settings, e.g. I configure the german reagion setting to have a point as decimal separator.
The StringFormat method does not recognize this custom setting! It still formats the double values with a comma as decimal symbol.
If I create a string property in the view model like this
public string FormattedDoubleValue
{
        get { return DoubleValue.ToString("0.00"); }
}

and bind to this property, this does recognize the custom region setting!
Is there any way to make the StringFormat method recognize the custom region settings?

A: I found a solution here:
CurrentUICulture ignores Region and Language settings
Using the answer of MSkuta works without having to change all my xaml files :)

redpajama_set_name: RedPajamaStackExchange


text:
Q: pipenv/pip install from git commit/revision id I would like to install a package from a git repository specifying a commit id using pipenv (I belive it should be very similar If I would use pip)
so far I tried:
pipenv install "git+ssh://git@bitbucket.org/<username>/<repository>.git/<commit_id>#egg=mypackage"
which is apending the following line to the Pipfile & provides no errors
<package-name> = {git = "ssh://git@bitbucket.org/<username>/<repository>.git/<commit_id>"}
If I import the package import mypackage it detects it but its dependencies are missing.
The setup.py of mypackage looks like;
import setuptools

with open("README.md", "r") as readme:
    long_description = readme.read()
with open("./requirements.txt", "r") as fh:
requirements = fh.readlines()

setuptools.setup(
    name='mypackage',
    url='https://bitbucket.org/<username>/<repositroy>',
    packages=setuptools.find_packages(),
    install_requires=[req for req in requirements if req[0] not in ["#", "-"]],

)

A: Just figured it out by reading this that the revision id should be specified after a @
pipenv install  "git+ssh://git@bitbucket.org/<username>/<repository>.git@<commit_id>#egg=<package_name>"


text:
Q: How are Flash files without class definitions compiled? Let's use the code from the first section of this website. I don't see a class declaration, and my program cannot be built in FlashDevelop. I receive the following error message:
Error: A file found in a source-path must have an externally visible definition. If a definition in the file is meant to be externally visible, please put the definition in a package.
Build halted with errors (fcsh).

What should I do in order to be able to build & run it?

A: If you're using flash develop and pure AS3 (no flex) then everything has to be in a class and package.
Simply wrap that code in a custom class to use it in flashDevelop.  If you create a new project in flash develop most templates create a Main.as file - which is the root class that runs when you're project loads, just dump the code inside the Main class defined in that .AS file (except for the imports, they'll need to be inbetween the package and class declarations).
package {

    //imports here

    public class Main extends MovieClip {
       //put any vars that aren't in functions here  (eg. var mFileReference:FileReference)
       public function Main():void {
           //put anything not contained in a function here
       }

       //put the functions here

    }

}


text:
Q: IMAP server responds with "BAD..." error to "LIST..." after similar "LIST" command completes successfully I'm getting a BAD... error when running a LIST command against an IMAP server that I'm not understanding and could use some help with.  I run almost an identical command just prior to it to list the root mailboxes and have no problem, but then as I begin to iterate over those mailboxes and try to list their child mailboxes, I get the error.  The odd thing is that even though the first returned line from the IMAP server is the BAD... response, it still fulfills the rest of the query as if nothing was wrong?!?!
To start off, you'll need to know the namespace details of the server in question...
NAMESPACE

Array
(
    [0] => * NAMESPACE (("" ".")) NIL NIL
)

This server uses an empty root namespace, and a period (.) for the mailbox delimiter.
Here's the command I'm using for the root list...
LIST "" "%" RETURN (SUBSCRIBED CHILDREN SPECIAL-USE STATUS (MESSAGES UNSEEN))

For which I get the expected response...
Array
(
    [0] => * LIST (\Subscribed \HasChildren) "." Archives
    [1] => * STATUS Archives (MESSAGES 0 UNSEEN 0)
    ...
)

I should mention that all of the RETURN meta capabilities were established from an earlier CAPABILITIES request.
So based on the results, I begin to iterate over them to get the child mailboxes, with the first one being Archives.  The syntax I'm using is based almost identically to that outlined in the RFC 3501 #6.3.8 examples under LIST...
LIST "Archives." "%" RETURN (SUBSCRIBED CHILDREN SPECIAL-USE STATUS (MESSAGES UNSEEN))

I would expect it to list all of the child mailboxes relative to the Archives mailbox, which it does, however it first lists a BAD... response...
Array
(
    [0] => * BAD Error in IMAP command : Unknown command (0.000 + 0.000 secs).
    [1] => * LIST (\Subscribed \HasNoChildren) "." Archives.2017
    [2] => * STATUS Archives.2017 (MESSAGES 0 UNSEEN 0)
    [3] => * LIST (\Subscribed \HasNoChildren) "." Archives.2016
    [4] => * STATUS Archives.2016 (MESSAGES 192 UNSEEN 0)
    [5] => * LIST (\Subscribed \HasNoChildren) "." Archives.2019
    [6] => * STATUS Archives.2019 (MESSAGES 1 UNSEEN 0)
)

First, I don't understand what I've done wrong, and further, the BAD... error is not referencing a specific command like it should, so I really don't have anything to go on here.  Second, if it's failing, then why is it still completing the rest of the request?
Could really use some help, thanks!

EDIT 1: I'm getting this same unexplained error from two different IMAP servers I'm testing against, and they're both exhibiting the same behaviour... returning the correct records, but not before including a BAD... error first.  So it must be something in the syntax of my LIST... requests, but I feel like I'm using the same examples that the RFC defines, so I'm at a loss.


text:
Q: Javascript bug "e.preventDefault();" is not a function It's been an hour since I can not find where is my mistake. Moreover, I'm sure it's a stupid one. Anyway, here it's my javascript code :
var deleteRefsButton = document.getElementsByClassName('refs--item--delete');

var deleteRefs = function(e, i){
    e.preventDefault();
    e.parentNode.classList.add('deleted');
    document.getElementById('deletedInput'.i).value = true;
}

for (var i=0;i<deleteRefsButton.length;i++){
    var button = deleteRefsButton[i];
    button.addEventListener('click', deleteRefs(button,i), false);
}

And here my html scheme :

        content

    <input type="hidden" name="deleted1" value="false">
    Delete this refs

        content

    <input type="hidden" name="deleted2" value="false">
    Delete this refs

...

So, as you can see, my goal is to listen the click event on links (a.refs--item--delete), prevent the top scrolling, then add a "deleted" class to its parentNode and finally add the value true to the good hidden input.
But with this present code, nothing work, the console says :
 Uncaught TypeError: e.preventDefault is not a function

So maybe you saw my mistake.
Thank you in advance

A: There are a couple things wrong that have to do with the fundamentals of javascript.
When using addEventListener you pass in the instance of the function you wish to trigger you don't execute it.
button.addEventListener('click', deleteRefs, false);

Then when the listener is triggered the event will be passed in as the first argument. That will solve preventDefault being undefined.
Second you are trying to do getElementById('deletedInput'.i) you are trying to call i on a String. That is not valid javascript. What you would do is:
getElementById('deletedInput' + i);

However i will be undefined because you cannot execute the function like you are doing in addEventListener.
I also want to note that doing this document.getElementById('deletedInput'.i) will not work because you have no elements with an ID prefixed with deletedInput. You can solve this with querySelector. I have added this to my example.
Finally I want to note that your for loop starts at 0. You have no elements with 0. You will need to add 1 to i when passing i your handler.
I have edited your code you could do something like this. If you have questions you can reference developer.mozilla.org. You could copy and paste this and it will work.
var deleteRefsButton = document.getElementsByClassName('refs--item--delete');
var deleteRefs = function(){

    // The arguments object is an Array-like object corresponding to the arguments passed to a function.
    var i = arguments[0];
    var e = arguments[1];
    e.preventDefault();
    e.currentTarget.parentNode.classList.add('deleted');
    document.querySelector('[name="deleted' + i + '"]').value = true;
}

for (var i=0; i < deleteRefsButton.length; i++){

    var button = deleteRefsButton[i];

    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
    // .bind will prepend i the the list of arguments passed to deleteRefs
    button.addEventListener('click', deleteRefs.bind(this, i + 1), false);
}


text:
Q: How to use for loop for single entity in input xml file I have to insert for loop in a input xml file but eclipse gives an eroor
+ "<FolderName></FolderName>"
+"<RootFolderPath>" + Helper.cabinetName + "/ABC/"+odfolder+"/";
for(int $i=5;$i<FilepathArr.length;$i++)
+subproduct[$i]+
"</RootFolderPath>"
+ "<DocumentName>" + fname[0] + "</DocumentName>"

the operator +is  deifned for argument type string.


text:
Q: What is causing an Unhandled Promise Rejection: undefined is not an object (evalutating '_context.t0.response.data')? I keep getting an Unhandled Promise Rejection: TypeError: undefined is not an object (evaluating '_context.t0.response.data'). After doing some digging, it seems like my error is coming from this part of my code. It's the authUser function specifically that seems to be causing the problem
import { addError, removeError } from './error';
import { SET_CURRENT_USER } from '../actionTypes';
import api from '../../services/api';

export const setCurrentUser = user => ({
    type: SET_CURRENT_USER,
    user
});

export const setToken = token => {
    api.setToken(token);
};

export const authUser = (path, data) =>
{
    return async dispatch => {
        try {
            const {token, ...user} = await api.call('post', `auth/${path}`, data);
            AsyncStorage.setItem('jwtToken', token);
            api.setToken(token);
            dispatch(setCurrentUser(user));
            dispatch(removeError());
        } catch (err) {
            const error = err.response.data;
            dispatch(addError(error.message));
        }
    }
};

actionTypes.js
export const SET_CURRENT_USER = 'SET_CURRENT_USER'

api.js
import axios from 'axios';

const host = 'http://localhost:4000/api';

export const setToken = token => {
    if (token) {
        axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
    } else {
        delete axios.defaults.headers.common['Authorization'];
    }
};

export const call = async (method, path, data) => {
    const response = await axios[method](`${host}/${path}`, data);
    return response.data;
};

export default { setToken, call };

error.js
import {ADD_ERROR, REMOVE_ERROR} from '../actionTypes';

export const addError = error => ({
    type: ADD_ERROR,
    error
});

export const removeError = () => ({
    type: REMOVE_ERROR
});

Error:
Possible Unhandled Promise Rejection (id: 4):
TypeError: undefined is not an object (evaluating '_context.t0.response.data')
_callee$@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:107239:43
tryCatch@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:26927:23
invoke@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:27103:32
tryCatch@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:26927:23
invoke@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:27003:30
http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:27015:21
tryCallOne@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:28865:16
http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:28966:27
_callTimer@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:32405:17
_callImmediatesPass@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:32441:19
callImmediates@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:32659:33
callImmediates@[native code]
__callImmediates@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:2719:35
http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:2505:34
__guard@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:2702:15
flushedQueue@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:2504:21
flushedQueue@[native code]
callFunctionReturnFlushedQueue@[native code]

Also if it helps, I followed the localhost link and the function that is breaking there, tho I did not write this and cannot change it.

  var authUser = function authUser(path, data) {
    return function _callee(dispatch) {
      var _await$api$call, token, user, error;

      return _regenerator.default.async(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              _context.prev = 0;
              _context.next = 3;
              return _regenerator.default.awrap(_api.default.call('post', "auth/" + path, data));

            case 3:
              _await$api$call = _context.sent;
              token = _await$api$call.token;
              user = (0, _objectWithoutProperties2.default)(_await$api$call, ["token"]);
              AsyncStorage.setItem('jwtToken', token);

              _api.default.setToken(token);

              dispatch(setCurrentUser(user));
              dispatch((0, _error.removeError)());
              _context.next = 16;
              break;

            case 12:
              _context.prev = 12;
              _context.t0 = _context["catch"](0);
              error = _context.t0.response.data;
              dispatch((0, _error.addError)(error.message));

            case 16:
            case "end":
              return _context.stop();
          }
        }
      }, null, null, [[0, 12]], Promise);
    };
  };

A: The error is coming from the catch block of the authUser function:
export const authUser = (path, data) =>
{
    return async dispatch => {
        try {
           // ... Other existing codes
        } catch (err) {
            const error = err.response.data;
            dispatch(addError(error.message));
        }
    }
};

For errors thrown by axios, err.response won't always be available, at times when there is no response from the server or there was a problem making the request in the first place, err.response would be undefined. In such cases, you need to handle other sources of errors. You should update the catch logic to handle the possible error cases, the code should be something like this:
catch (err) {
    if (err.response) {
        // There is an error response from the server
        // You can anticipate error.response.data here
        const error = err.response.data;
        dispatch(addError(error.message));
    } else if (err.request) {
        // The request was made but no response was received
        // Error details are stored in err.reqeust
        console.log(err.request);
    } else {
        // Some other errors
        console.log('Error', err.message);
    }
}

More details on handling axios error here.


text:
Q: Prediction of linear classifier using Sparse Matrices I am using sparse matrices to train the logistic regression estimator
using OnevsRestClassifier.. The feature set is quite large
(~1.6million).
When the classifier has to predict, it raises an exception saying
number of features in test data and train data are not equal.
I fail to understand how it can expect the number of features to be
equal when it comes to sparse matrix representation. For instance,
here is the snippet of my rudimentary code:
classifier = OneVsRestClassifier(LogisticRegression())
classifier = classifier.fit(X_train, y_train)
predicted = classifier.predict(X_test)

Here the shape of X_train and X_test are obviously different.
print X_train.shape
(11, 1617899)
print X_test.shape
(3, 83715)

So an exception is raised:
ValueError: X has 83715 features per sample; expecting 1617899

(Little source code probing says me that linear_model/base.py does
this comparison in decision_function())
How can I fix this?


text:
Q: Application.ScreenUpdating toggle I'm looking for the simplest way to toggle ScreenUpdating via call.
Can you please advise if this solution could have any adverse effects?
Sub Toggle_Screen_Updating()
With Application
   .ScreenUpdating = IIf(.ScreenUpdating, False, True)
End with
End Sub

A: This will toggle it.
Application.ScreenUpdating = Not Application.ScreenUpdating

I recommend not to use toggleing because you never clearly know the state after running this line. You only know that is is the opposite that it was before.
I recommend to explicitly run Application.ScreenUpdating = False whenever you want to turn it off and Application.ScreenUpdating = True whenever you want to turn it on.
I see no advantage in using a toggle instead.


text:
Q: XML to flat file via XSLT trying to convert an XML file of the following sort to a flat file or csv. I am able to generate XSLT files for other XML formats, but I don't really understand how to work with trees structure in this format. Any thoughts? I've experimented a bit, but I'm just not familiar with XSLT enough.
  <observations
        realtime_start="2013-02-08"
        realtime_end="2013-02-08"
        observation_start="1776-07-04"
        observation_end="9999-12-31" units="lin"
        output_type="2"
        file_type="xml"
        order_by="observation_date"
        sort_order="asc"
        count="792" offset="0"
        limit="100000">
    <observation date="1947-01-01" CPIAUCSL_20130208="21.48"/>
    <observation date="1947-02-01" CPIAUCSL_20130208="21.62"/>
    <observation date="1947-03-01" CPIAUCSL_20130208="22.0"/>
  </observations>

A: Will this example suffice?
T:\ftemp>type obs.xml
<?xml version="1.0" encoding="UTF-8"?>
  <observations realtime_start="2013-02-08" realtime_end="2013-02-08"
  observation_start="1776-07-04" observation_end="9999-12-31" units="lin"
  output_type="2" file_type="xml" order_by="observation_date" sort_order="asc"
  count="792" offset="0"        limit="100000">
  <observation date="1947-01-01" CPIAUCSL_20130208="21.48"/>
  <observation date="1947-02-01" CPIAUCSL_20130208="21.62"/>
  <observation date="1947-03-01" CPIAUCSL_20130208="22.0"/>
  </observations>

T:\ftemp>xslt obs.xml obs.xsl obs.csv

T:\ftemp>type obs.csv
date,CPIAUCSL
1947-01-01,21.48
1947-02-01,21.62
1947-03-01,22.0

T:\ftemp>type obs.xsl
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="1.0">

<xsl:output method="text"/>

<xsl:template match="observations">
  <xsl:text>date,CPIAUCSL
</xsl:text>
  <xsl:for-each select="observation">
    <xsl:value-of select="@date"/>,<xsl:value-of select="@CPIAUCSL_20130208"/>
    <xsl:text>
</xsl:text>
  </xsl:for-each>
</xsl:template>

</xsl:stylesheet>
T:\ftemp>

The key to outputting text is that what gets serialized to the file are all of the text nodes of the result tree.  Any element or attribute nodes in the result tree are ignored, so don't even bother trying to create them ... just create text nodes and they all get concatenated into the output.
To go in the other direction, from CSV to XML, I've made the http://www.CraneSoftwrights.com/resources/#csv package freely available (and it works for TSV files as well) for use with XSLT 2.0.


text:
Q: Не могу понять почему мой правильно написанный код не работает. Python Мой код должен проверять литерал строки на наличие сторонних символов, таких как "+","&","@" и т.д. Но когда я ввожу их, то удаляется лишь определенная часть, и к тому же, если ввести один символ "+" в инпут, то произойдет ошибка. Пожалуйста, обьясните почему код не удаляет копии одного символа, то есть все символы. Прошу, помогите разобраться, я уже совсем отчаялся.
inp = list(input())

i = 0

while i != len(inp):
    if not inp[i].isalnum():
        del inp[i]

    i+=1

print(inp)

A: сколько раз повторять - НЕЛЬЗЯ удалять элементы списка по которому вы при этом еще и двигаетесь!!!
и зачем вообще удалять символы, наоборот - оставляйте нужные символы и формируйте из них новую строку
res = ''.join(letter for letter in input() if letter.isalnum())

print(res)

P.S.
а у вас происходит следующее - вы удаляете элемент, список уменьшается на 1 элемент, вы при этом делаете еще i += 1, т.е. еще на 1 символ сдвигаетесь, так что во-первых часть символов будет выпадать из анализа, а во вторых появляется шанс просто попасть уже за пределы списка

A: Потому как длинна меняется и i оказывается за границами на последних операциях. Проход по списку или строке с удалением только в обратном направлении:
i = len(inp)
while i:
    i-=1
    if not inp[i].isalnum():
        del inp[i]

И это тоже является плохим кодом.
Используйте только фильтры для таких задач:
inp = ''.join(filter(lambda x: x.isalnum(), inp))

Еще плохой, но рабочий вариант:
i = 0
while i != len(inp):
    if not inp[i].isalnum():
        del inp[i]
    else:
        i+=1

A: В данном случае можно просто вынести i+=1 в блок else:
inp = list(input())
i = 0
while i != len(inp):
    if not inp[i].isalnum():
        del inp[i]
    else:
        i+=1
print(inp)

Хотя другие отвечающие и комментаторы правы - лучше так не делать (не удалять элементы из списка по которому проходите), в других обстоятельствах это может привести к весьма неприятным багам.


text:
Q: INS positioning attitude update with quaternions gives wrong direction solution I'm trying to calculate position with accelerometer and gyroscope data I get from the phone. In this calculation I am using quaternations for attitude update but the calculated point coordinates are going left rather than right. So actually, if I take the symmetric right side, I will get the correct values.
Calculation results:

Arrow shows the North direction. The actual route to go is shown in red.
The formula I used is as follows:
T_s = sampling period
w = refers to gyro values.
q_k = updated attitude

The yaw angle, which should be referenced for the left deflection, is 355 degrees, but as I mentioned before, it turns to the right with this angle. I couldn't figure out where the problem came from, can you help?


text:
Q: Basic post request for users using express (React) I am having serious issues trying to solve this issue and any help would be appreciated greatly
So all I am trying to do is a simple register activity for users where I will be able to sign them up to the site.
I am using mssql, and express.
This is My Register.js. All I want is for the details input into the buttons to be passed through to the json body so it can then be used in my server.js.
Register.js
class AddUsers extends React.Component {
  constructor() {
    super();

    this.state = { users: [] };
    this.onSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(e) {
    e.preventDefault();
    const data = { email: this.ref.email, password: this.ref.password };
    // const data = { name: "", password: "" };

    fetch("/admin-Add-Users", {
      method: "POST", // or 'PUT'
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify(data)
    })
      .then(response => response.json())
      .then(data => {
        console.log("Success:", data);
      })
      .catch(error => {
        console.error("Error:", error);
      });
  }

  render() {
    console.log(this.state.users);
    return (

        <LoginForm></LoginForm>

        <form onSubmit={this.onSubmit}>
          <input type="text" placeholder="email" ref="email" />
          <input type="text" placeholder="password" ref="password" />
          <input type="submit" />
        </form>

    );
  }
}

This is my server.js (config file is working). Here all I want is for the data previously added to be stored in my database (SQL server).

app.post("/admin-Add-Users", function(req, res) {

  const { password, email } = req.body;

  var request = new sql.Request();

 // query to the database and get the records
    request.query( "insert into Login (email, password) values ('"+email+"','"+password+"')", function(err, recordset) {
      if (err) console.log(err);

  });
  res.send({ message: "Success" });
});

I have no idea how to get the data from the inputs to just be stored through my server.js. Please any help or examples are appreciated. I am new to react so please explain like I am five years old.
Error I am now receiving
Warning: This synthetic event is reused for performance reasons. If you're seeing this, you're accessing the method `isPropagationStopped` on a released/nullified synthetic event. This is a no-op function. If you must keep the original synthetic event around, use event.persist().

A: You should try to avoid use refs in react unless you have a good reason to use them (some things like animations need to be controlled imperatively).
The React way is to do things declaratively with state, so changing an input updates the associated state field, and then the onSubmit function takes the values from state.  Something like this:
class AddUsers extends React.Component {
  constructor() {
    super();

    this.state = { users: [], email: '', password: '' };
    this.onSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(e) {
    e.preventDefault();
    const data = { email: this.state.email, password: this.state.password };

    fetch("/admin-Add-Users", {
      method: "POST", // or 'PUT'
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify(data)
    })
      .then(response => response.json())
      .then(data => {
        console.log("Success:", data);
      })
      .catch(error => {
        console.error("Error:", error);
      });
  }

  render() {
    console.log(this.state.users);
    return (

        <LoginForm></LoginForm>

        <form>
          <input type="text" placeholder="email" value={this.state.email} onChange={e =>
               this.setState({email: e.target.value})} />
          <input type="text" placeholder="password" value={this.state.password} onChange={e =>
              this.setState({password: e.target.value})} />
          <input type="submit" onPress={this.onSubmit} />
        </form>

    );
  }
}


text:
Q: What is the p values taken by sklearn chi2 I am trying to understand the implementation of the sklearn chi2 for feauture selection algorithm.
I think I understand the chi2 formula.

After getting this value we will see the table for 1 degree of freedom and according to ou need choose the p value.If chi2 value is greater than keep it otherwise ignore it.
My question is how does sklearn package choose this p-value on its own?It just requires X and y array as input.
http://scikit-learn.org/stable/modules/generated/sklearn.feature_selection.chi2.html
and are the chi2 scores always normalized?
link to the paper-http://courses.ischool.berkeley.edu/i256/f06/papers/yang97comparative.pdf

A: The idea is to perform univariate feature selection:

*

*For each feature, you compute some kind of a statistic (in your case a chisquared-statistic)

*Create a set of (hopefully) most important features by combining 1) with some selection method (SelectKBest, SelectPercentile)

So going back to your question, I think you misunderstood the following point:

*

*You always run the chi2 test for all features and then you only keep those that had highest chi2-statistic (=lowest p value). You do not specify a cutoff threshold since your is goal to keep the most informative features. If you insist and really want to use a cutoff threshold then you would have to write your own Transformer and  it is not obvious at all what this cutoff value should be (even when applied to p-values).


text:
Q: command line argument from file content with quote I have a file containing command line arguments that I would like to pass to another script.
But this file contain element such as "param 1" param2 param3.
Let's call the file with arguments test.tmp and the script file script.sh.
If I do:
script.sh -p `cat test.tmp` -other_params 1 2 3

The script.sh receives after p:

*

*"param

*1"

*param2

*param3
But I would like:

*

*param 1

*param2

*param3
Any idea?
Small precision: assume that script.sh is not modifiable. The solution must take place in the shell.

A: ASSUMPTION: test.tmp needs to contain a parameter per line with this approach.
You may use xargs with a linefeed delimiter:
cat test.tmp | xargs -d '\n' script.sh -p

A: You can wrap the command in eval:
eval "script.sh -p `cat test.tmp` -other_params 1 2 3"

$ cat test.tmp
"params 1" param2 param3

$ cat script.sh
#!/bin/bash
echo $1
echo $2
echo $3
echo $4
echo $5
echo $6

$ eval "./script.sh -p `cat test.tmp` other_params 1 2 3"
-p
params 1
param2
param3
other_params
1

A: Lay out your file like this:
param 1
param2
param3

then read it into an array like this:
mapfile -t params < file

then call your script like this:
script.sh -p "${params[@]}" -other_params 1 2 3

The advantage of this approach is that it only uses built-in bash commands and doesn't require an eval.
To do it all in one line, you can use:
mapfile -t params < file && script.sh -p "${params[@]}" -other_params 1 2 3

i.e. use && to execute the second command if the first one succeeded.

A: Using grep with Perl regex:
IFS=$'\n'; ./script.sh -p $(grep -woP '((?<=")[^"]*(?="))|([\S]+)' test.tmp)

Example:
script.sh:
#!/bin/bash
echo "$1"
echo "$2"
echo "$3"
echo "$4"
...

Output:
-p
param 1
param2
param3
...

Note: It will change the IFS of the current shell (where you are running these commands).


text:
Q: Overflow hidden issue with double scrolling on iOS The problem is that I have a body (which it can't be positioned fixed because it causing bugs to the current project) with a lot of content and a modal with scrollable content inside, the problem is that on iOS if I turn the overflow to hidden nothing happens.
In my case, setting height: 100vh and overflow: hidden to class="parent" is not working.
I tried different things and tried different hacks to solve this issue but nothing fixed yet I saw here also different methods but for different situations.
I looked also for overflow hidden alternatives but nothing found yet...
If you guys have some ideas/refs/a way to solve it post it here I appreciate, thank you.
Here is the snippet https://codepen.io/anon/pen/zJQoJR

Body scrollable content

Modal scrollable content

A: Putting the overflow hidden on your html tag might help:
html, body {
  height: 100%;
  width: 100%;
  overflow: hidden;
}

A: I got pretty good results by adding this to your css:
body.modal-open > .parent {
    position: fixed;
    overflow: hidden;
    height: 100%;
}

And to make the modal 'bouncy' on your iOS device, change your .container-child css to:
.container-child {
    position: fixed;
    background-color: rgba(0,0,0,0.4);
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;

    -webkit-overflow-scrolling: touch; /* <-- added */
}

Here's a demo on codepen: https://codepen.io/anon/pen/mzJXPJ


text:
Q: I want to achieve rotation of cards by clicking of first and last element I have a carousel of three cards, rotating on Y-axis and it works.
When you click on button up it goes up and when you click on button down it goes down but I want to achieve that functionality like this.
When you click top card it goes up and when you click on the bottom card it goes down.
I can select the first div and it works but when you click on the first element it becomes second and so on and that is a problem. How to trigger rotation only on an element that is on top and on the bottom?
var cards = $("#carousel > .card"), Next, Previous,
    nexttransforms =[
        {y: '-55%', z: '-50px', scale: 0.8,},
        {y: '55%', z: '-50px', scale: 0.8,},
        {y: 0, z: 0, scale: 1,},
    ];
Next = function(){
    nexttransforms.push(nexttransforms.shift());
    for(i=0; i<cards.length; i++){
        var kartica = cards[i];
        $(kartica).css({
            'transform': 'translateY('+ nexttransforms[i].y +') translateZ(' + nexttransforms[i].z + ') scale(' + nexttransforms[i].scale+')',
        });

    }
};
Previous = function(){
    for(i=0; i<=cards.length-2; i++){
        nexttransforms.push(nexttransforms.shift());

    }
    for(i=0; i<cards.length; i++){
        var x = nexttransforms[i];
        var kartica = cards[i];
        $(kartica).css({'transform': 'translateY('+  x.y +') translateZ(' + x.z + ') scale(' + x.scale+')',
        });
     }
};
$('#down').on('click', function(){
    Previous();
});
$('#up').on('click', function(){
    Next();
});

<!DOCTYPE html>

    <meta charset="UTF-8">
   <title></title>
    <link rel="stylesheet" href="css/style.css">

1

2

3

<button id="up">Up</button>
<button id="down">Down</button>

#carousel {
    position: absolute;
    top: 40px;
    left: 200px;
    -webkit-transform-style: preserve-3d;
    transform-style: preserve-3d;
    opacity: 1;
}

.card {
    position: absolute;
    width: 200px;
    height: 200px;
    -webkit-transform-style: preserve-3d;
    transform-style: preserve-3d;
    transition: 1s;
    background: black;
    -webkit-transform: translateY(-55%) translateZ(-50px) scale(0.8);
    transform: translateY(-55%) translateZ(-50px) scale(0.8);
}

.card:nth-child(3) {
    -webkit-transform: translateY(0) translateZ(0);
    transform: translateY(0) translateZ(0);
    background: #add8e6;
}

.card:nth-child(1) {
    -webkit-transform: translateY(-55%) translateZ(-50px) scale(0.8);
    transform: translateY(-55%) translateZ(-50px) scale(0.8);
    background: #ff7f50;
}

.card:nth-child(2) {
    -webkit-transform: translateY(55%) translateZ(-50px) scale(0.8);
    transform: translateY(55%) translateZ(-50px) scale(0.8);
    background: #7fff00;
}

So the end result would be, when you click on the top card it goes up and when you click on the bottom card it goes down and that should work endlessly.

A:

$(function(){

  $('.card').click(function(e){
    e.preventDefault();

    var thisCard = $(this);

    var topCard = $('.card.top');
    var midCard = $('.card.middle');
    var botCard = $('.card.bottom');

    if (thisCard.hasClass('top'))
    {
      topCard.removeClass('top').addClass('bottom');
      midCard.removeClass('middle').addClass('top');
      botCard.removeClass('bottom').addClass('middle');
    }
    else if (thisCard.hasClass('bottom'))
    {
      topCard.removeClass('top').addClass('middle');
      midCard.removeClass('middle').addClass('bottom');
      botCard.removeClass('bottom').addClass('top');
    }
  });

});
#carousel {
    position: absolute;
    top: 50px;
    left: 200px;
    -webkit-transform-style: preserve-3d;
    transform-style: preserve-3d;
    opacity: 1;
}

.card {
    position: absolute;
    width: 80px;
    height: 80px;
    -webkit-transform-style: preserve-3d;
    transform-style: preserve-3d;
    transition: 1s;
    background: black;
    -webkit-transform: translateY(-55%) translateZ(-50px) scale(0.8);
    transform: translateY(-55%) translateZ(-50px) scale(0.8);
}

.card.middle {
    -webkit-transform: translateY(0) translateZ(0);
    transform: translateY(0) translateZ(0);
    background: #add8e6;
}

.card.top {
    -webkit-transform: translateY(-55%) translateZ(-50px) scale(0.8);
    transform: translateY(-55%) translateZ(-50px) scale(0.8);
    background: #ff7f50;
}

.card.bottom {
    -webkit-transform: translateY(55%) translateZ(-50px) scale(0.8);
    transform: translateY(55%) translateZ(-50px) scale(0.8);
    background: #7fff00;
}


text:
Q: Jumbled out put of RFID Tags I am working on a project, in which I have to interface multiple RFID Readers (I'm Using EM 18, With Serial out) with Raspberry Pi. I'm using an USB to TTL Converter to connect EM 18 to Raspberry Pi. I've connected two RFID Readers using USB to TTL Adapter.
This is my code for one station
Code
import serial, time
while True:
    try:
        print 'station one Is Ready!! Please Show your Card'
                card_dataa = serial.Serial('/dev/ttyUSB0', 9600).read(12)
        print card_dataa
        continue
    except serial.SerialException:
        print 'Station 1 is Down'
    break

My Issues are

*

*I would like to get the readings from both the RFID Readers in the same program simultaneously.

*I've two Programs with the above code, station1.py and station2.py.
Station1.py is for USB0 and Station2.py is for USB1.
I am executing the programs in different Terminal simultaneously.
For example station1.py in terminal 1 and station2.py in terminal 2. The program executes fine, but the readings are jumbled. For example, 6E0009D2CC79 and 4E0070792760 are the tag id's that i'm using for testing. if I'm executing only one program i'm getting the reading properly, but if I'm executing both programs simultaneously in two terminals I'm getting the tag Id's jumbled.

*I want to combine both the readings in the same program.

Thanks in Advance

A: I'd recommend create a new Serial object once and reading multiple times, as needed:
import serial, time

try:
    station1 = serial.Serial('/dev/ttyUSB0', 9600)
    print 'station one Is Ready!! Please Show your Card'
except serial.SerialException:
        print 'Station 1 is Down'

while True:
    card_dataa = station1.read(12)
    print card_dataa

Optionally you can set a timeout of 0:
import serial, time

try:
    station1 = serial.Serial('/dev/ttyUSB0', 9600,timeout=0)
    print 'station one Is Ready!! Please Show your Card'
except serial.SerialException:
        print 'Station 1 is Down'

while True:
    card_dataa = station1.read(12)
    if len(card_dataa) > 0: print card_dataa

You should also easily be able to open 2 serial connections in the same program:
import serial, time

station1 = None
station2 = None

try:
    station1 = serial.Serial('/dev/ttyUSB0', 9600,timeout=0)
    print 'station 1 Is Ready!! Please Show your Card'
except Exception,e:
        print 'Station 1 is Down',e

try:
    station2 = serial.Serial('/dev/ttyUSB1', 9600,timeout=0)
    print 'station 2 Is Ready!! Please Show your Card'
except Exception,e:
        print 'Station 2 is Down',e

while True:
    if station1 != None:
        card_dataa1 = station1.read(12)
        if len(card_dataa1) > 0:    print card_dataa1
    if station2 != None:
        card_dataa2 = station2.read(12)
        if len(card_dataa2) > 0:    print card_dataa2

This means the 2nd reader would wait for the 1st reader to finish before printing, which is why fingaz recommended threading.
Here's a basic commented proof of concept for threading:
import threading,time,serial

#subclass threading.Thread
class RFIDSerialThread(threading.Thread):
    SLEEP_TIME = 0.001 #setup sleep time (update speed)
    #constructor with 3 parameters: serial port, baud and a label for this reader so it's easy to spot
    def __init__(self,port,baud,name):
        threading.Thread.__init__(self) #initialize this instance as a thread
        self.isAlive = False #keep track if the thread needs to run(is setup and able to go) or not
        self.name = name     #potentially handy for debugging
        self.data = ""       #a placeholder for the data read via serial
        self.station = None  #the serial object property/variable
        try:
            self.station = serial.Serial(port,baud,timeout=0) #attempt to initialize serial
            self.isAlive = True #and flag the thread as running
        except Exception,e:
            print name + " is Down",e #in case of errors print the message, including the station/serial port

    def run(self): #this gets executed when the thread is started
        while self.isAlive:
            if self.station != None:    self.data = self.station.read(12) #read serial data
            time.sleep(RFIDSerialThread.SLEEP_TIME)

if __name__ == '__main__':
    #initialize the two readers
    station1 = RFIDSerialThread('/dev/ttyUSB0',9600,"station #1")
    station2 = RFIDSerialThread('/dev/ttyUSB1',9600,"station #2")
    #start the threads
    station1.start()
    station2.start()

    while True:#continously print the data (if any)
        if len(station1.data) > 0:  print station1.name,station1.data
        if len(station2.data) > 0:  print station2.name,station2.data

Note that I haven't attached actual hardware to test, so this may not work as is, but should provide enough info to progress.
I would also suggest trying to physically distance the readers. Depending on the readers and their capabilities they may be interfering witch each other which might result in faulty data. In case you still have issues with jumbled data, I'd try to figure out where the problem is by taking some assumptions out.(e.g. is the issue a hardware (readers interfering, broken reader, loose USB connector, etc.) or software(serial port not properly initialized/flushed/etc.), taking one thing out at a time)

A: To have a concurrent flow, you can use the threading module. Here's a link to the documentation:
https://docs.python.org/2/library/threading.html


text:
Q: Почему dropdown меню появляется только 1 раз? При первом наведении выпадание срабатывает, после необходимо перезагрузить страницу, чтобы оно опять выпало при наведении
.navigation-item {
   display: inline-block;
   margin-right: 2%;
   padding: 10px 0;}
.dropdown > .dropdown-link::after {
    content: "";
    float: right;
    margin: 10px 5px;
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-top: 10px solid #CCC;}

  .dropdown .dropdown-list {
    list-style-type: none;
    display: block;
    margin: 0;
    padding: 0;
    position: absolute;
    width: 120px;
    overflow: hidden;}

  .dropdown .dropdown-link {
    display: block;
    width: 100%;
    color: #F5F5F7;
    font-size: 18px;}

  .dropdown-item-link {
    color: #F5F5F7;
    font-size: 18px;
    opacity: 0.8;}

  .dropdown-item-link:hover {
    opacity: 1;
    text-shadow: 0 0 10px rgba(255, 255, 255, 0.5);
    transition: all 0.3s ease-in-out;}

  .dropdown-item-link:not(:hover) {
    transition: all 0.3s ease-in-out;}

  .dropdown .dropdown-item {
    height: 0;
    width: 100%;
    overflow: hidden;
    transition: all 500ms;
    transition-delay: 300ms;}

  .dropdown.hover:hover .dropdown-item{
    height: 40px;}

  .dropdown.hover:hover .dropdown-item:first-child {
    padding-top: 15px;}

A: все прекрасно работает, просто у тебя дочерние элементы выходили за пределы родитетя, а ты курсор не достаточно отводил.  вот тебе твой пример  с добавленныим background
hover наследуется

html,
body {
  width: 100%;
  height: 100%;
  background-color: #fcfcfc;
}

.navigation-item {
  display: inline-block;
  margin-right: 2%;
  padding: 10px 0;
  width: 100px;
  height: 100px;
  background: #ccc;
}

.dropdown>.dropdown-link::after {
  content: "";
  float: right;
  margin: 10px 5px;
  width: 0;
  height: 0;
  border-left: 5px solid transparent;
  border-right: 5px solid transparent;
  border-top: 10px solid #CCC;
  background: #000;
}

.dropdown .dropdown-list {
  list-style-type: none;
  display: block;
  margin: 0;
  padding: 0;
  position: absolute;
  width: 120px;
  overflow: hidden;
  background: #444;
}

.dropdown .dropdown-link {
  display: block;
  width: 100%;
  color: #F5F5F7;
  font-size: 18px;
  background: #252525;
}

.dropdown-item-link {
  color: #F5F5F7;
  font-size: 18px;
  opacity: 0.8;
  background: #0f0f0f;
}

.dropdown-item-link:hover {
  opacity: 1;
  text-shadow: 0 0 10px rgba(255, 255, 255, 0.5);
  transition: all 0.3s ease-in-out;
}

.dropdown-item-link:not(:hover) {
  transition: all 0.3s ease-in-out;
}

.dropdown .dropdown-item {
  height: 0;
  width: 100%;
  overflow: hidden;
  transition: all 500ms;
  transition-delay: 300ms;
}

.dropdown.hover:hover .dropdown-item {
  height: 40px;
}

.dropdown.hover:hover .dropdown-item:first-child {
  padding-top: 15px;
}

zina0

zina1

zina2

zina3

zina4


text:
Q: how can I convert a 'hello world' to b'hello world' I want to convert a string
'hello world'

to
b'hello world'

in python, how can I do that?

A: You can use the str.encode() method to convert a string to bytes.
>>> 'hello world'.encode()
b'hello world'
>>>

Please refer to: https://docs.python.org/3/library/stdtypes.html#str.encode

A: You can use b = bytes(mystring, 'utf-8') notation to turn your string into bytes object. But there are many similar questions and related answers in stackoverflow to your question. You should have searched for your question first.

A: >>> """b'hello world'"""
b'hello world'


text:
Q: Отсутствие подключения к MySQL Добрый день, только начал программировать на php.
Установил Apache + php, MySql. Подключился к серверу через Devart MySql и создал базу.
Скрипты php работают, а подключиться к базе -не могу - даже не выводит что ошибка- просто белый экран.
Код:
<?php
$host="localhost";
$user="Roman";
$pwd="11111";
$db="MySQLDB";
    echo $host." ".$user." ".$pwd." ".$db;

$link=@mysql_connect($host,$user,$pwd,$db);
if ( !$link ) {
  echo "Could not connect: " . mysql_error();
} else {
  echo "Connect OK.";
}
?>

Подскажите, пожалуйста, в чём дело, т.к. гугл не помог- беру копирую все примеры и вижу белый экран, такое впечатление что он не знает функции mysql_connect, хотя в php.ini раскомментированы библиотеки для работы с  MySQL.
A: "даже не выводит что ошибка" - а зачем тогда @ поставили? может он и блокирует ошибку?
A: Убедись, что у тебя создан пользователь "Roman" и БД называется так же, как указано в переменной $dbname.
    $sqlhost = "localhost";
    $dbname = "MySQLDB";
    $sqluser = "Roman";
    $sqlpass = "11111";

    $dbcnx = mysql_connect($sqlhost, $sqluser, $sqlpass);
    if (!$dbcnx) {
    echo "
К сожалению, не доступен сервер MySQL
";
    exit();
    }
    if (!mysql_select_db($dbname,$dbcnx) ) {
    echo "
К сожалению, не доступна база данных
";
    exit();
    }

A: Есть одно правильное действие, которое нужно с самого начала выполнить, а именно создать php-файл с кодом
<?php
phpinfo();
?>

Затем выполнить через вызов в URL. Там будет написано все, включая даже то, какой php.ini файл используется. Сдается мне, у тебя много серверов проинсталлированы на компе, - чинишь ты один, а запросы другой перехватывает.
И еще: есть такие файлы - access.log и error.log - они лежат в папке apache/logs. Просмотри их внимательно на предмет загрузки модулей и ошибок. Только убедись сначала, что ищешь в правильном Apache.


text:
Q: Double sum - Miklos Schweitzer 2010 There is a question in the Miklos Schweitzer contest last year that keeps bugging me. Here it is:

Is there any sequence $(a_n)$ of nonnegative numbers for which $\displaystyle\sum_{n \geq 1}a_n^2 <\infty $ and $$\sum_{n \geq 1}\left(\sum_{k \geq 1}\frac{a_{kn}}{k}\right)^2=\infty\quad?$$

A: (This is not an answer.) The situation is even worse than Patrick Da Silva suggests. Let $a_n = \frac{b_n}{\sqrt{n}}$; then $\sum \frac{b_n^2}{n}$ converges, so $\liminf b_n = 0$. Moreover $\frac{a_{nk}}{k} = \frac{b_{nk}}{k^{3/2} \sqrt{n}}$, hence the above sum gives
$$\sum_{n \ge 1} \frac{1}{n} \left( \sum_{k \ge 1} \frac{b_{nk}}{k^{3/2}} \right)^2.$$
In particular, if $b_n$ is eventually monotonically decreasing (or even some weaker form of this assumption), then the sum in parentheses is eventually at most $b_n^2 \zeta \left( \frac{3}{2} \right)$ and so $a_n$ cannot be a counterexample to the given statement.
In other words, a counterexample needs to be fairly non-monotonic (if the statement is false). It seems like a good idea to make $a_n$ large if $n$ has many factors, but I haven't been able to do anything concrete with this.

A: I thought I had something, but as ShreevatsaR correctly remarked, I made a stupid mistake, and the below proof is false. However, Claim 1 is (I hope) correct, and perhaps the idea beyond claim 2 can be used by someone to produce a proof, so I will not delete the answer (at least for the time being).
Firstly, let $N(a) := \sum_n a_n^2, \lVert a \rVert := \sqrt{N(a)}$ and $S(a) := \sum_n (\sum_k \frac{a_{nk}}{k} )^2$ where $a$ is a sequence of nonnegative numers. We want to prove that $S(a)$ can be infinite while $N(a)$ is finite.
Claim 1
It suffices to show that the ratio $\frac{S(a)}{N(a)}$ can be made arbitrarily large (rather than actually infinite).
Proof
Suppose that the ratio $\frac{S(a)}{N(a)}$ can be made as large as we like. Then we can find, for any $M$ a sequence $a^M$ be a sequence with $N(a^M) < \frac{1}{2^{2M}}$ (so that $ \lVert a^M \rVert < \frac{1}{2^M}$) and $S(a^M) > M$. Now, define $a := \sum a^M$. It is a well defined and square-sumable sequence, since $\lVert \cdot \rVert$ is actually a norm. Now, $S(a) \geq S(a^M) > M$ for any $M$, since $a_n \geq a^M_n$ for any $n$ and all coefficients are nonnegative. Thus, we conclude that $S(a) = \infty$.
Claim 2
The ratio $\frac{S(a)}{N(a)}$ can be made arbitrarily large.
Proof
Fix an integer $M$ and consider the sequence $a_n = n[n \leq M]$ (which means $a_n = n$ for $n \leq M$ and $a_n = 0$ for $n > M$). We can compute:
$$N(a) = \sum_{n=1}^M n^2 $$
and
$S(a) = \sum_{n=1}^M (\sum_{k=1}^M \frac{nk}{k})^2 = \sum_{n=1}^M n^2 \cdot M^2 = M^2 N(a)$
Thus, the desired ratio is:
$$\frac{S(a)}{N(a)} = M^2$$
which is obviously sufficiently large is $M$ is sufficiently large.

A: Prof. Noam Elkies has given a answer at Mathoverflow. Here is his answer.

A: I figured out something of potential interest, but I am uncertain of its usefulness.
Also, I apparently can't comment yet because I don't have enough privilege points or something, so I'm "answering". (The scratchwork wouldn't fit in a comment anyway.)
Define $ \sum a_n^2 = L $ and note that $ n^2 \le \sigma_2(n) < \zeta(2) n^2 $ (this can be seen by factoring $ \sigma_2(n)n^{-2} $ and then noting that it is always a finite part of the Euler product for the Riemann zeta function but can allow arbitrarily many of its terms). Use $ (n,m) $ for greatest common divisor. Then
$$ S = \sum_{n \geq 1}\left(\sum_{k \geq 1}\frac{a_{kn}}{k}\right)^2 $$
$$ = \sum_{n,m=1}^\infty \left( \sum_{d|(n,m)} \frac{1}{(n/d)(m/d)} \right) a_n a_m $$
$$ = \sum_{n,m=1}^\infty \sigma_2((n,m)) \frac{a_n}{n} \frac{a_m}{m} $$
$$ = \sum_{n=1}^\infty \sigma_2 (n) (a_n / n)^2 + 2 \sum_{n=2}^\infty \left( \sum_{m<n} \frac{\sigma_2((n,m))}{m} a_m \right) \frac{a_n}{n} $$
$$ <\zeta(2) \left( L + 2 \sum_{n=2}^\infty \left( \sum_{m<n} \frac{(n,m)^2}{m} a_m \right) \frac{a_n}{n} \right) $$
Hence if we can prove
$$ M = \sup \left\{ \frac{1}{n a_n} \sum_{m<n} \frac{(n,m)^2}{m} a_m \right\} < \infty $$
we may then establish the existence of finite upper bound
$$ S < \zeta(2) (L + 2M (L-a_1^2)) .$$
I'd look into this more (namely on how to find a lower bound practical enough for the approach from the other side) but it's the middle of the night here. Maybe later.


text:
Q: How to prove an inequality of Lebesgue integral?
Definition of measurable set: A set $E$ is measurable if $$m^*(T) = m^*(T \cap E) + m^*(T \cap E^c)$$ for every subset of $T$ of $\mathbb R$.
Definition of Lebesgue measurable function: Given a function $f: D \to \mathbb R ∪ \{+\infty, -\infty\}$, defined on some domain $D \subset \mathbb{R}^n$, we say that $f$ is Lebesgue measurable if $D$ is measurable and if, for each $a\in[-\infty, +\infty]$, the set $\{x\in D \mid f(x) > a\}$ is measurable.
Definition of Lebesgue integral of simple function:
  We say that a simple function $\psi$ is Lebesgue integrable if the set $\{\psi \ne 0\}$ has finite measure. In this case, we may write the standard representation for $\psi$ as $\psi = \sum_{i=0}^n a_i \chi_{A_i}$, where $a_0 = 0, a_1, \ldots , a_n$ are distinct real numbers, where $A_0 = \{\psi = 0\}, A_1, \ldots , A_n$ are pairwise disjoint and measurable, and where only $A_0$ has infinite measure, Once $\psi$ is so written, there is an obvious definition for $\int \psi$, namely, $$\int \psi = \int_{\mathbb R} \psi = \int_{-\infty}^{+\infty} \psi(x) \ \mathsf dx = \sum_{i=1}^n a_i m(A_i).$$ In other words, by adopting the convention that $0 \cdot \infty = 0$, we define the Lebesgue integral of $\psi$ by $$\int \sum_{i=0}^n a_i \chi_{A_i} = \sum_{i=0}^n a_i m(A_i).$$ Please note that $a_im(A_i)$ is a product of real numbers for $i \ne 0$, and it is $0 \cdot \infty = 0$ for $i = 0$; that is, $\int \psi$ is a finite real number.
Definition of Lebesgue integrable of non-negative function:
  If $f: \mathbb R \to [0, +\infty]$ is measurable, we define the Lebesgue integral of $f$ over $\mathbb R$ by $$\int f = \sup \left\{\int \psi: 0 \le \psi \le f, \psi\text{ simple function and integrable }\right\}.$$

Suppose $f(x)$ and $g(x)$ are non-negative Lebesgue measurable functions defined on $E \subset \mathbb R$. How to prove $$\left(\int_{E} f(x)\ \mathsf dx\right)^{\frac{1}{2}} \left(\int_{E} g(x)\ \mathsf dx\right)^{\frac{1}{2}} \ge \int_{E} {\sqrt{f(x)g(x)}}\ \mathsf dx$$?
Besides, can anyone introduce some mathematical books about inequalities to me such as basic inequalities, integral inequalities, norm inequalities, convex inequalities and so on? I'm not sure whether there is a book covering such a board area of mathematical inequalities. So it will be pretty helpful even if your introduced book merely covering one specific area of them. Thanks in advance.
Update:
I notice that if I treat $a = \sqrt {f(x)}$ and $b = \sqrt {g(x)}$ then it will be much looked like a Holder inequality in Riemann integral.

A: When $||f||_p > 0, ||g||_{p'}>0$ and $p, p' < +\infty$, then$$a^{\frac{1}{p}}b^{\frac{1}{p'}} \le \frac{a}{p} + \frac{b}{p'}, a>0, b>0$$ and $a = \frac{|f(x)|^p}{||f||_{p}^{p}}, b = \frac{|g(x)|^{p'}}{||g||_{p'}^{p'}}$, then get $$\frac{|f(x)g(x)|}{||f||_p ||g||_{p'}} \le \frac{1}{p}\frac{|f(x)|^p}{||f||_p^p} + \frac{1}{p'} \frac{|g(x)|^{p'}}{||g||_{p'}^{p'}}$$. Integrate both side, then $$\int_E \frac{|f(x)g(x)|}{||f||_p ||g||_{p'}}dx \le \frac{1}{p} \int_E \frac{|f(x)|^p}{||f||_p^p}dx + \frac{1}{p'} \int_E \frac{|g(x)|^{p'}}{||g||_{p'}^{p'}}dx = \frac{1}{p} + \frac{1}{p'} = 1$$ where $$\int_E {|f(x)|^p} dx =||f||_p^p, \int_E {|g(x)|^{p'}} dx =||g||_{p'}^{p'}$$.


text:
Q: Angular2 no changing in browser when modify typescript file I'm using angular2 with Visual Studio 2015.
I completely new at angular2 so I'm discovering it step by step, right now I have an app.component.ts, displaying in html file, and everything works but when I'm making changes like the content of template in the typescript file nothing's moving, I style have the older content I tried to rebuild the project, close the project and re open it, tried to disable the cache like said in a topic but nothing works, what am I missing ??

A: You need to compile the typescript to javascript in order to see the changes. Simply run npm tsc in your console and your script will compile.

A: In case you are using command line I would suggest to install @angular/cli package. If you use ng serve your app will automatically reload if you change any of the source files.


text:
Q: how do I using option tag to select the specific data from database with FLASK my data from database, and I can use "SELECT * FROM factors WHERE Crash_Year = 2001/2002/2003" to display specific data. but I don't know how to achieve this function in my html.
enter image description here
For example, if I select 2002, there are display the year of data are 2002.
I want to use option tag and here are my html coding:
{% block content %}

    <form action="/show/" method="post">
        Choose the rang of the Year:

        <select id="year" name="year">
          <option value="2001">2001</option>
          <option value="2002">2002</option>
          <option value="2003">2003</option>
          <option value="2004">2004</option>
          <option value="2005">2005</option>
          <option value="2006">2006</option>
          <option value="2007">2007</option>
          <option value="2008">2008</option>
          <option value="2009">2009</option>
          <option value="2010">2010</option>
          <option value="2011">2011</option>
          <option value="2012">2012</option>
          <option value="2013">2013</option>
          <option value="2014">2014</option>
          <option value="2015">2015</option>
          <option value="2016">2016</option>
          <option value="2017">2017</option>
          <option value="2018">2018</option>
        </select>

        <input type="submit" value="Submit">
    </form>

            id
            Crash Year
            Region
            Crash Severity
            DrinkDriving
            Driver Speed
            Fatigued Driver
            Defective Vehicle
            Count Crashes
            Count Fatality
            Count Hospitalised
            Count Medically Treated
            Count Minor Injury
            Count All Casualties

        {% for row in factorsinfo %}

            {{ row.id }}
            {{ row.Crash_Year }}
            {{ row.Crash_Police_Region }}
            {{ row.Crash_Severity }}
            {{ row.Involving_Drink_Driving }}
            {{ row.Involving_Driver_Speed }}
            {{ row.Involving_Fatigued_Driver }}
            {{ row.Involving_Defective_Vehicle }}
            {{ row.Count_Crashes }}
            {{ row.Count_Fatality }}
            {{ row.Count_Hospitalised }}
            {{ row.Count_Medically_Treated }}
            {{ row.Count_Minor_Injury }}
            {{ row.Count_All_Casualties }}

        {% endfor %}

{% endblock %}

and here is my app.py:
@app.route("/show", methods=['GET', 'POST'])
def show():
    g.db = sqlite3.connect(DATABASE)
    d = {}
    d['id'] = ""
    d['Crash_Year'] = ""
    d['Crash_Police_Region'] = ""
    d['Crash_Severity'] = ""
    d['Involving_Drink_Driving'] = ""
    d['Involving_Driver_Speed'] = ""
    d['Involving_Fatigued_Driver'] = ""
    d['Involving_Defective_Vehicle'] = ""
    d['Count_Crashes'] = ""
    d['Count_Fatality'] = ""
    d['Count_Hospitalised'] = ""
    d['Count_Medically_Treated'] = ""
    d['Count_Minor_Injury'] = ""
    d['Count_All_Casualties'] = ""
    factorsinfo = []
    cursor = None
    try:
        cursor = g.db.cursor()
        rows = cursor.execute('SELECT * FROM factors ;')
        for row in rows:
            #print(row)
            d = {}  # necessary; weird ...
            d['id'] = row[0]
            d['Crash_Year'] = row[1]
            d['Crash_Police_Region'] = row[2]
            d['Crash_Severity'] = row[3]
            d['Involving_Drink_Driving'] = row[4]
            d['Involving_Driver_Speed'] = row[5]
            d['Involving_Fatigued_Driver'] = row[6]
            d['Involving_Defective_Vehicle'] = row[7]
            d['Count_Crashes'] = row[8]
            d['Count_Fatality'] = row[9]
            d['Count_Hospitalised'] = row[10]
            d['Count_Medically_Treated'] = row[11]
            d['Count_Minor_Injury'] = row[12]
            d['Count_All_Casualties'] = row[13]
            factorsinfo.append(d)
    except Exception as e:
        return """
 Error occurred when accessing the database

{}
""".format(e), 500

    if cursor:
        cursor.close()
    g.db.close()
    return render_template('show.html', factorsinfo=factorsinfo)

A: Perhaps the problem statement could be:

If route is called from a POST request, and user has selected a
  "year", only send that year's data to the html

One way to solve that would be to only send the selected year's data back to the html here
return render_template('show.html', factorsinfo=factorsinfo)
Before the return, you will need a routine to collect and send the data from factorsinfo that  contains the selected year. You will need to use flask's request.method and request.form. In pseudo code:

*

*Is it a post request? (ie request.method == 'POST')

*Is a year selected? (ie request.form['year'] is not None)

*Find the data in factorsinfo for that year

*Return that set to the render_template
It could be done in the html, but the aforementioned return would have to also send the year that was selected, and an if clause would need to added after this {% for row in factorsinfo %} clause in the html.


text:
Q: What does this icon mean in the UbuntuOne sign up screen? I'm trying to create a new UbuntuOne account, and getting this:

The email addresses are the same in both fields, and the password meets the criteria set. What exactly do the triangle icons mean? There's no alt text when I mouse over them, so I have no idea what it thinks is wrong with the new account setup information I'm providing.

A: I'm sorry it isn't working for you. You should have an "on hover" text for those alert icons; in fact, I can see them right now. However, the only thing I can think of that would produce the alert in your case is that you already have an SSO account with that email address. Try logging in rather than creating a new account.


text:
Q: php pass value to multiple select queries I'm having trouble passing a variable between MySQL queries on the same page. Maybe someone can advise what I'm doing wrong. I'm new to PHP/MySQL, but the answer seems very easy, I just don't see it. Here is what I have:
1. MySQL: Table A:
    id | gene_id | protein_id | disease_id | etc
    ----------------------------------------------
    1  | 672     | P12803     | 091312
    2  | 817     | P99613     | 020346
    3  | 411     | P52021     | 055823

2. Search result page. Displays a list of results. The reaults are identified by [$id] and an  link passes [$id] to another page for result details. This works perfectly.
3. Details Page. I get the query result from the Search results page and display related information from the table, identified by [$id]. This works fine.
    <?php

    $sql = "SELECT * FROM Table_A
    WHERE id=" . $_GET["id"];

    $rs_result = mysql_query ($sql,$connect);
    while ($row = mysql_fetch_assoc($rs_result)) {

    ?>

Gene: 	<? echo $row[gene_id]; ?>

Protein: 	<? echo $row[protein_id]; ?>

Disease: 	<? echo $row[disease_id]; ?>

    <?  } ?>

4. Show related data. On the details page, I want to show related data from Table B in the same database, using the "protein_id" from the query above. But this I can't get to work, to pass "protein_id" to the next query, as follows:
Table B:
    id | protein_asc | synonym | name | etc
    ----------------------------------------------
    11  | P12803    | ABC      | this |
    12  | P99613    | DEF      | that |

    <?php

    $new_id = $row[protein_id];

    $sqla = "SELECT * FROM Table_B
    WHERE protein_asc='".$new_id."'";

    $rsa_result = mysql_query ($sqla,$connect);
    while ($row = mysql_fetch_assoc($rsa_result)) {

    ?>

Synonym: 	<? echo $row[synonym]; ?>

Name: 	<? echo $row[name]; ?>

    <?  } ?>

I have tried many different ways to achieve this, using joins on the second Select query, but nothing seems to work. I know the second query is correct, because if I hard code "$new_id = P12803 ;" then the second query grabs the data.
Any help would be appreciated.
Thanks

A: You need to move your second loop inside first loop otherwise $row[protein_id] will return as null. Furthermore you are assign $row to both fetching, i changed second to $rowa. So change to
while ($row = mysql_fetch_assoc($rs_result)) {

?>

Gene: 	<? echo $row[gene_id]; ?>

Protein: 	<? echo $row[protein_id]; ?>

Disease: 	<? echo $row[disease_id]; ?>

<?php

    $new_id = $row[protein_id];

    $sqla = "SELECT * FROM Table_B
    WHERE protein_asc='".$new_id."'";

    $rsa_result = mysql_query ($sqla,$connect);
    while ($rowa = mysql_fetch_assoc($rsa_result)) {

    ?>

Synonym: 	<? echo $rowa[synonym]; ?>

Name: 	<? echo $rowa[name]; ?>

    <?  } ?>

<?  } ?>

Then I  would like to remember you that mysql_ functions are deprecated so i would advise you to switch to mysqli or PDO and indeed you are at risk of sql injection, have a look here How can I prevent SQL injection in PHP?. You should use prepared statment to avoid any risk


text:
Q: android- Gradle: An issue occurred configuring root project android studio I migrated from eclipse to android studio. I've create a new project and I want to run it on genymotion. When I press run icon, it begins to compile and give me this error :
Error:Gradle: A problem occurred configuring root project 'Khabar'.
> Could not resolve all dependencies for configuration ':classpath'.
   > Could not resolve com.android.tools.build:gradle:1.1.0.
     Required by:
         :Khabardar:unspecified
      > Could not GET 'https://jcenter.bintray.com/com/android/tools/build/gradle/1.1.0/gradle-1.1.0.pom'.
         > d29vzk4ow07wi7.cloudfront.net

This is some parts of my build.gradle :
    apply plugin: 'com.android.application'

android {
    compileSdkVersion 20
    buildToolsVersion "20.0.0"

    defaultConfig {
        applicationId "example.ir.khabar"
        minSdkVersion 8
        targetSdkVersion 20
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

build.gradle in root :
    apply plugin: 'com.android.application'

android {
    compileSdkVersion 20
    buildToolsVersion "20.0.0"

    defaultConfig {
        applicationId "example.ir.khabar"
        minSdkVersion 8
        targetSdkVersion 20
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:20.0.0'
    compile files('libs/universal-image-loader-1.8.4-with-sources.jar')
}

Could you help me? my  gradle version is gradle-2.2.1-all

A: For me, the solution was to add the http url for jcenter, instead of https:
buildscript {
    repositories {
        jcenter {
            url "http://jcenter.bintray.com/"
        }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.1.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

A: In addition to Al's answer, I also had to put the url inside allprojects:
allprojects {
    repositories {
        jcenter {
            url "http://jcenter.bintray.com/"
        }
    }
}

A: I was having the same issue on Ubuntu Mate 18.04. I was able to fix it by replacing ibm-java80-jdk & ibm-java80-jre with openjdk. Also, I did update my DNS to cloudflare DNS. But I don't think it had anything to do with the fix.

A: add google() in your gradle inside the repositories section will solve your problem..
buildscript {
    repositories {
        jcenter()
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'

    }
}

allprojects {
    repositories {
        jcenter()
    }
}


text:
Q: Task :app:createBundleReleaseJsAndAssets FAILED s Task :app:createBundleReleaseJsAndAssets FAILED

Task :app:createBundleReleaseJsAndAssets FAILED

FAILURE: Build completed with 2 failures.
1: Task failed with an exception.

*

*What went wrong:
Execution failed for task ':app:createBundleReleaseJsAndAssets'.

Process 'command 'cmd'' finished with non-zero exit value 1

*

*Try:

Run with --stacktrace option to get the stack trace.
Run with --info or --debug option to get more log output.
Run with --scan to get full insights.
==============================================================================

2: Task failed with an exception.

*

*What went wrong:
java.lang.StackOverflowError (no error message)

*Try:

Run with --stacktrace option to get the stack trace.
Run with --info or --debug option to get more log output.
Run with --scan to get full insights.
==============================================================================

*

*Get more help at https://help.gradle.org
Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0.
You can use '--warning-mode all' to show the individual deprecation warnings and determine if they come from your own scripts or plugins.
See https://docs.gradle.org/7.5.1/userguide/command_line_interface.html#sec:command_line_warnings
Execution optimizations have been disabled for 14 invalid unit(s) of work during this build to ensure correctness.
Please consult deprecation warnings for more details.


text:
Q: Nativescript Http Module Error Connection Refused I am getting the following error while trying to implement the Nativescript tutorial code found here
"originalStack": "Error: java.net.ConnectException: Connection refused\n
at ZoneAwareError (file:///data/data/org.nativescript.NotecardRestaurants/
files/app/tns_modules/nativescript-angular/zone-js/dist/zone-nativescript.js:993:33)\n...
Here is the source for app.module
import { NgModule, NO_ERRORS_SCHEMA } from "@angular/core";
import { NativeScriptModule } from "nativescript-angular/nativescript.module";
import { AppRoutingModule } from "./app.routing";
import { AppComponent } from "./app.component";
import { NativeScriptFormsModule } from "nativescript-angular/forms";
import { NativeScriptHttpModule } from "nativescript-angular/http";
import { UserService } from './shared/user/user.service';

import { LoginComponent } from "./login/login.component";

@NgModule({
    bootstrap: [
        AppComponent
    ],
    imports: [
        NativeScriptModule,
        AppRoutingModule,
        NativeScriptFormsModule,
        NativeScriptHttpModule,
    ],
    declarations: [
        AppComponent,
        LoginComponent
    ],
    providers: [
        UserService
    ],
    schemas: [
        NO_ERRORS_SCHEMA
    ]
})
export class AppModule { }

Here is the source for user.service that is causing the issue
import { Injectable } from "@angular/core";
import { Http, Headers, Response } from "@angular/http";
import { Observable } from "rxjs/Rx";
import "rxjs/add/operator/do";
import "rxjs/add/operator/map";

import { User } from "./user";
import { Config } from "../config";

@Injectable()
export class UserService {
  constructor(private http: Http) {}

  register(user: User) {
    let headers = new Headers();
    headers.append("Content-Type", "application/json");

    return this.http.post(
      Config.apiUrl + "/user/register",
      JSON.stringify({
        name: user.name,
        email: user.email,
        password: user.password
      }),
      { headers: headers }
    )
    .map(response => response.json().token)
    .catch(this.handleErrors);
  }
  login(user: User) {
    let headers = new Headers();
    headers.append("Content-Type", "application/json");

    return this.http.post(
       Config.apiUrl + "user/login",
      JSON.stringify({
        email: user.email,
        password: user.password
      }),
      { headers: headers }
    )
    .map(response => response.json().token)
    .catch(this.handleErrors);
  }

  handleErrors(error: Response) {
    console.dir(error.json());
    return Observable.throw(error);
  }
}

I have independently verified the integrity of the api I am using. The routes given do work. I am running the nativescript project using
tns run android --emulator

A: if you are running your application on IOS simulator or Android emulator, which is basically virtual machine and if you are referring 'localhost' or '127.0.0.1' these are IP of virtual machine not your development machine. you can solve your problem by providing IP of your development machine or in android you can use 10.0.2.2 IP for your development machine. sample of your api url is
https://10.0.2.2:5001/api/news/getnews


text:
Q: Codeforces exercise 71 I have a problem with this exercise:
https://codeforces.com/problemset/problem/71/A
My SC is:
a=input()
b=a.isdigit()
if b==False:
    if len(a)<10:
        print(a)
    else:
        b=a[0]
        c=str(len(a)-2)
        d=a[-1]
        print(b+c+d )

and it works, my output is correct but i see a a wrong verdict: wrong output format Unexpected end of file - token expected
what should i improve? what is wrong?

A: You need to add a loop to loop over all test cases.
for _ in range(int(input())):
    word = input()
    if len(word)<11:
        print(word)
    else:
        print(word[0]+str(len(word)-2))+word[-1])


text:
Q: Why am I unable to print my ArrayList generated from my SQLite table? Android developer. I have an SQLite database. One of my columns is called KEY_SWITCH. I want to convert the integers in this list into an ArrayList and then print it to my console.
Here's my code:
public ArrayList<Integer> getAllIntegerValues() {
    ArrayList<Integer> yourIntegerValues = new ArrayList<Integer>();
    Cursor result = db.query(true, DATABASE_TABLE,
            new String[] {KEY_SWITCH}, null, null, null, null,
            null, null);

    if (result.moveToFirst()) {
        do {
            yourIntegerValues.add(result.getInt(result
                    .getColumnIndex(KEY_SWITCH)));
        } while (result.moveToNext());
    } else {
        return null;
    }
    System.out.print(yourIntegerValues);
    return yourIntegerValues;
}

I run the code like this
DBAdapter_Metrics mydbmetric;

private SQLiteDatabase dbmetric;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_metric_list);
    openDBMetrics();
    populateListViewFromDNewBMetric();
    mydbmetric.getAllIntegerValues();
}

When I run the code, I get the following error:
endAllActiveAnimators on 0x915c1380 (RippleDrawable) with handle 0x8f550150
Why isn't it printing my ArrayList?
I tried to search about this error but I found the error changes depending on where in my code I launch the getAllIntegerValues()
For example, when I created a drop down menu with an option to run it, I got this error
endAllActiveAnimators on 0x8e3b5300 (MenuPopupWindow$MenuDropDownListView) with handle 0x8ef83f50
So it seems to shift depending on where I run it, which I don't understand.

A: do it like below:
    System.out.print(Arrays.toString(yourIntegerValues.toArray()));

UPDATE: another way is like below:
System.out.print(android.text.TextUtils.join(",", yourIntegerValues))


text:
Q: What are some tips to routing a one sided PCB? I'm having trouble routing this PCB in Eagle 7.1:

I have tried the following:

*

*Autorouting - it could not complete

*Moving components around

*Manually routing - I always ended up getting stuck

*Adding a ground plane - autorouter still failed.

The restrictions I have placed are 0.2mm wires with 0.45mm gap between pad-to-wire (I don't want wires running inside the SV1, but the other IC's are okay.), and 0.2mm wire-to-wire gap.
I understand the SMD led and resistor are on the bottom of the board, along with the rest of the wires.
What are some things I can do to route this board without having to route wires inside SV1?
Related question: If the autorouter can't get a 100% completion, is the chance of manual routing pretty much zero?

A: Key in routing a PCB is part placement. It can be made almost impossible by poor part placement.
Looking at it a bit ...
IC1 looks like it needs rotating 180 degrees, and then move R1 and LED1 out of the way, to the right of IC1, and they can be routed under IC2.
Rotate SV1 180, and I think it will mostly go.
Edit: Use a few jumper-wires, to connect areas of copper which need to be connected, but can't be routed on a single sided board. I can't quite tell as some air-wires are a bit obscured, but I think you might need a couple.
A 'pretty solution' which disguises jumper wires are 0ohm resistors. Unfortunately you are using SMD resistors which don't have enough space between their pads to be used to cross over a wire :-(
Edit:
When I am trying to understand part placement, I sometimes do a rough/quick routing for the many-pins parts first. Then see where the two pin parts go. That seems to help me see what is going on topologically.
I always set the grid to a useful value. That saves a lot of time and effort in Eagle.
For rough routing, I set the grid size to track+space, then it is very quick to lay tracks near each-other, without breaking a Design Rule. I often set the grid 'alt' to an even divisor of that, e.g. if track+grid is 16, then Alt might be 4. That is usually good enough; diagonal corners might be slightly further apart than 'perfect', but it is easy, quick and safe.
When I do a rough/quick routing, I assume I'll rip up all tracks. I don't necessarily complete tracks. I often only route enough to 'uncross' tracks so that it is easy to see which tracks are causing problems, and which groups might route simply and together. I am looking for opportunities to move parts to simplify routing. I expect to rip up the tracks, and hence don't waste much effort.
I believe professionals say 'shallow, 45 degree corners are good, 90 degree or sharper are bad'. So I very rarely use the 90-degree wire bends. Being able to route tracks in parallel is quick. So I rarely use arbitrary angle wire bends. It is harder to rip-up and move curved bends, so I rarely use them either. That means I only use the two 45 degree wire bends for the majority of routing.
Important: Eagle was designed many years ago, and has a user interface optimised for heavy use, when the command line was still popular. A one button mouse or track pad is awful. Use a two button mouse, preferably with a wheel. Many commands become much easier, and zooming with the wheel becomes convenient. The second button helps with moving parts, rotating, selecting wire bends, ...
Useful: Bind common actions, which require lots of clicking to function keys. I have mine set to show various combinations of layers. One key shows all the layers that I'll have manufactured. Another removes all text, but leaves 'stop' to make it easy to see what I am routing and what must not overlap. Another switches off top layer copper, etc. The way to figure out what to put onto a function key is to type the command into the command line, then paste it into the define key dialogue. Most of my layer views are on the same function key, modified by shift, control etc. to make it easy to find.
Useful: Eagles on-line help contains a lot of useful information. If you have a second screen, and can avid the screen real estate, keep it open, and use the search facility. I found a lot of little techniques that are buried in a 'ctrl-alt-click' that way, which has saved me much effort.
NB: I am doing sub 100MHz MCU's, which have the high-speed stuff on chip, so these strategies work okay. There are community members who can give much better guidance about the electronics of a PCB than me.

A: To your related question: Autorouters will almost never complete 100%. This is totally normal. That said, in your case this may be an indication of not being possible. Placing a restriction of single sided makes things more difficult, especially since so many nets appear to need to cross over.
Things which might help:

*

*Change the pinout of SV1. Of course this may not be possible if it connects to something you must match up with.

*Make the board double sided. You already have components on the other side. Is there some reason you cant do this?

*I havn't tried it exactly but it appears to be simple enough you should be able to come up with a solution by hand. Keep in mind you may need to take some rather indirect routes, in and around IC pins even.

*(Additional) I would recommend making the IC pads Oval in shape, with the long dimension aligned with the width of the part. This will allow you to make them narrower and still get good solder coverage/pad size. In this way you will have more clearance between pins for routing the one or maybe two traces which will need to go between pins. (Really only one in the layout I drew).

A Routing Attempt (Corrected)
I cant tell from the picture what pin 7 of SV1 needs but give this a shot as a first attempt:

A: Although it might be possible to route your PCB without using any jumpers, most one-sided PCB's of any complexity will require some jumpers.
Although some layout programs handle jumpers in a situation like this automatically, ones like Eagle do not (at least version 6, I have not upgraded yet to 7). There the simplest solution is to pretend the PCB is a two-layer board, and give the top layer (the one with through-hole components) a high "cost" so it won't try to put traces there unless absolutely necessary. The traces on the top will never actually exist (since you won't be etching that side), but instead these traces will represent the jumpers.
When the board is routed, you will want to make sure the traces representing the jumpers don't go under any components (if they were real traces, they could, so the router likely will try to to put some there). If there are, manually move them. When the board is stuffed, just put wires between the vias representing the ends of the traces.


text:
Q: How to add the SOAP header to all the methods in WCFSTORM tool I am trying to add the message header to all the methods in the WCFStorm , There is a concept of adding soap header to each method manually. But I couldn't find the way to add the SOAP header to all the methods automatically. Can someone guide me.
Thanks in Advance,
Sudhakar Byna.


text:
Q: Why are so many pins of 8086 active-low? Why are so many pins of 8086 active-low? Does it have to do something with the fact that more circuits are able to sink current than to source current, or is there another reason for it?

A: In some technologies, it's easier to make a N channel FET with more current capability than a P channel FET.

A: The 8086 pre-dates (fast, low voltage) CMOS logic. It's built in NMOS technology, with NMOS transistors (which, like NPN transistors, make good pull-downs) and ... I'm not sure what it used as pull-ups, possibly more NMOS transistors which, in that role, make slow, low current pull-ups.
So, analogous to contemporary TTL logic - which was used for much of the support logic, it was designed to the limitations of the available transistors, which meant critical signals were pulled down, and active low logic was easier to use for them.

A: In the TTL era, active low was the standard.
The old NMOS parts like the 8086 were designed in that time period- note that the input levels are TTL-compatible Vih=2.0V and Vil=0.8V.
Active-low allows wired-OR with open collector/drain outputs (you may have noticed that calling it 'wired-OR' implies negative logic).
Also, the NMOS parts were almost like RTL except the pull-up resistors (loads) were depletion mode n-channel MOSFETs so the negative edges would tend to be sharper with capacitive load. There are no p-channel parts in this technology (which made it simpler and thus higher yield)
CMOS parts (originally 4000 series) were not designed to be TTL compatible and generally have active-high inputs. The 74C/74HC etc CMOS parts derived from similar TTL functions tend to have active-low inputs. Remembering this difference can serve you even today- if you need a flip-flip with active high clear input you are more likely to find it in a 4xxx or 74HC4xxx part than in a 74HCxx part such as 74HC74.


text:
Q: nth-last-child selector not working I have this html:

title

one para

Maybe another para

.....

text

I want to edit the p that has the ul in it -
I thought about
.leading-4 p:nth-last-child(1){
}

and
.leading-4:nth-last-child(1){
}

but it doesn't' work either (though I didn't think it would)
What am i doing wrong please

A: What you want is last-of-type.
But as Praveen says you should fix your HTML. Use the W3C validator when in doubt.

A: You cannot have a
 inside a
 tag! So when you put

, the browser considers it as

.
So technically, there's and cannot be
 inside a
 so your CSS selector never ever selects an element under any case in HTML.
So, consider changing the element to
 instead.
Proof:

p {color: red;}
ul {color: blue;}
p ul {color: green;}

This is para

  The next UL element will be kicked out of P. Before UL.

This is LI inside UL inside P

  After UL. And this becomes normal text under the body, and not under P.

This is LI inside UL

References:

*

*ul element can never be a child of p element

*is it acceptable to put a UL inside of a paragraph??
Solution:
The solution for selecting the last
 for you would be:
p:last-of-type { /* rules */}