text:
Q: default data-type of const-keyword is int-type? One Book(Object Oriented Programming with C++ by E.Balagurusamy) says that
 const size = 10;

means
 const int size = 10;

but g++ compiler (version-4.6.1 in ubuntu) issues an error as
error: 'size' does not name a type

what should I conclude based on this?

*

*g++ doesn't support the feature.

*It is new feature. Latest g++ version supports it.

*The statement is wrong. Data-type is mandatory with the const keyword.

*Something else.

A: Mr. Balagurusamy is wrong. Completely wrong. The type is compulsory, with or without const keyword.
You should stop reading this book. You should not read books by Yashwant Kanetkar also. I know that books by these authors are very popular among students of many universities in India.
I would suggest you to get an introductory book from this list:

*

*The Definitive C++ Book Guide and List

A: Looks like an error in the book ... you definitely must name a type or aliased type (i.e., a typedef) since C++ is a strongly-typed languages.
Here is what the C++03 specification states on objects, declarations and definitions:

Section 1.8/1:

The properties of an object are determined when the object is created. An object can have a name (clause 3). An object has a storage duration (3.7) which influences its lifetime (3.8). An object has a type (3.9). The term object type refers to the type with which the object is created.

Then in Section 3.1/1:

A declaration is a definition ... [note: the rest of the paragraph are exceptions to this rule and are omitted since they're not applicable in this case]

Then in Section 3.1/6:

A program is ill-formed if the definition of any object gives the object an incomplete type

Finally, in Section 3.9.2/1 it states:

... the term object type (1.8) includes the cv-qualifiers specified when the object is created. The presence of a const specifier in a decl-specifier-seq declares an object of const-qualified object type; such object is called a const object. ...

So according to 3.9.2/1, const is a qualifier, not a type, and as-such, it has to qualify a valid unqualified type.  Secondly, in the example given, according to 3.1/1, the declaration of size is also a definition, and therefore the size object must have an associated type or the program is ill-formed according to 3.1/6.

A: I would go with: The statement is wrong. Data-type is mandatory with the const keyword.


text:
Q: Why does "sum" of a list in python flatten it? I have recently discovered an interesting feature in python
If you type:
y=[[1,2],[3,4]]
sum(y,[])

Output is: [1, 2, 3, 4]
Does anyone know why the sum of a series of lists with an empty list gives a flattened version of y (i.e: all of the sub-lists of y as a single list)?
I would have expected the output to be a concatenation:
[1,2],[3,4],[]
Thanks

A: sum iterates through an iterable and adds each element. It just so happens that with lists, addition is defined to be concatenation. By setting the second parameter (start) to [], the function begins with a list and keeps adding on elements to it. Effectively:
sum([[1, 2], [3, 4]], []) == [] + [1, 2] + [3, 4]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Grammar Semantics : "May I know the issue that you are facing with your computer ? " I am in tech support and I need to ask the following question to a customer often :

*

*"May I know the issue that you are facing with your computer ?"

*"May I know what issue you are facing with your computer ?"

*"May I know what kind of issue you are facing with you computer ?"

I was wondering , which one of these would be the most appropriate ...

A: How can I help you? What problems are you experiencing?


text:
Q: Typeahead request for remote data everytime key pressed. Is there a way to arrange preventing making parallel requests ? I have the following typeahead function
$('.search-input').typeahead({
minLength: 3,
source: function (query, process) {
    return $.getJSON(
        '/search/search_autocomplete/',
        {query: query},
        function (data) {
            var newData = [];
            $.each(data,function(){
                newData.push(this.destination + "  (" + this.country + ")");
            });
            return process(newData)
        })

}

});
But everytime when I press a key after 3 chars, it goes and make a get request from server. And after a while, all the requests stuck in pending, and those parallel requests becomes a serious load for the server to response. Is there a way to arrange the parallel requests or wait for some time interval before making requests.

A: try something like this:
var running = 0;

$('.search-input').typeahead({
minLength: 3,
source: function (query, process) {
    if(running) return;
    running = 1;

    return $.getJSON(
        '/search/search_autocomplete/',
        {query: query},
        function (data) {
            var newData = [];
            $.each(data,function(){
                newData.push(this.destination + "  (" + this.country + ")");
            });
            return process(newData)
        }).always(running=0);

}

you also could try a timeout in the alway() function: setInterval(function(){running=0},500);


text:
Q: JSON Object - search for keyword inside value I'm new to javascript and JSON objects and I'm wondering, is there a way to search for a keyword within the value of one of the key/value pairs?
My JSON objects have various key/value pairs and one of them is the Message key shown here...
Message: "<?xml version="1.0" encoding="UTF-8" ?><Response Version="2.3 Build Date 15/06/2020" Type="SNMPQuery" Timestamp="1592321768"><State>"Up"</State><SNMPResponse>""</SNMPResponse></Response>"

In dev tools I can query the Message key through dot notation and therefore see the value, but is there a way to just query/return the State of the Server, so in this case the word "Up"?
I hope all this makes sense.
Thanks

A: You can use DOMParser to parse the XML.

var res = {
  Message: '<?xml version="1.0" encoding="UTF-8" ?><Response Version="2.3 Build Date 15/06/2020" Type="SNMPQuery" Timestamp="1592321768"><State>"Up"</State><SNMPResponse>""</SNMPResponse></Response>'
};
let doc = new DOMParser().parseFromString(res.Message, "text/xml");
console.log(doc.querySelector('State').textContent);


text:
Q: SQL query to find cumulative GAP I am trying to find Cumulative Grade Point Average (CGPA) from dbo.Marks table. It's columns are given below:

*

*FirstName

*LastName

*RollNumber

*AdmissionYear

*Batch

*DegreeProgram

*Semester

*CourseCode

*CourseTitle

*CreditHours

*ScoreTotal

*ScoreObtained

*GPA

*Percentage

*GradeText

I am trying this Query i.e,
select FirstName as Name, GPA AS CGPA from dbo.Marks where FirstName='Nabia' ;

But, it is not showing my desire answer.
Cumulative Grade Point Average (CGPA) = CreditHours * GPA/ SUM CreditHours
Anybody can tell me, how can I get CGPA from this desire table?

A: SELECT
    SUM(CreditHours * GPA) / SUM(CreditHours) AS CGPA
FROM
    dbo.Marks
WHERE
    FirstName = 'Nabia';


text:
Q: Приложение падает при нажатии UP button В приложении имеются три activity с фрагментами. Первый фрагмент RecyclerView со списком, второй тоже, третий фрагмент детализация предыдущего. При клике по первому списку передается id через intent и открывается второй список. Затем при клике по второму списку тоже передается id (но уже другой) через intent и открывается третья (детализированная) activity. При нажатии UP Button (в левом верхнем углу) из третьего фрагмента - приложение падает. В Stacktrace NullPointer Exception - отсутствует id для второй activity (родительской по отношению к третьей). Хотя при нажатии Back Button всё отображается и работает нормально. Каким образом мне получить этот id из родительской активности и как его вставить назад при нажатии UP Button?
Стартуем родительскую
public void onClick(View view){
        int position = getAdapterPosition();
        if (position != RecyclerView.NO_POSITION){
            Department department = mDepartments.get(position);
            int deptId = department.getId();
            Bundle bundle = new Bundle();
            bundle.putInt(DEPARTMENT_ID, deptId);
            Intent intent = new Intent(mContext, CoworkersActivity.class);
            intent.putExtras(bundle);
            mContext.startActivity(intent);
        }

Родительская activity:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_coworkers);

    if (savedInstanceState == null){

        CoworkersFragment fragment = CoworkersFragment
                .newInstance(getIntent().getExtras().getInt(DepartmentAdapter.ViewHolder.DEPARTMENT_ID));

        getSupportFragmentManager().beginTransaction()
                .add(R.id.coworkers_container, fragment)
                .commit();
    }

}

Стартуем из адаптера родительской activity детализированную с фрагментом
    public void onClick(View v) {
        int position = getAdapterPosition();
        if (position != RecyclerView.NO_POSITION){
            Employee employee = mEmployees.get(position);
            Bundle bundle = new Bundle();
            bundle.putSerializable(ARG_EMPLOYEE, employee);
            Intent intent = new Intent(mContext, DetailActivity.class);
            intent.putExtras(bundle);
            mContext.startActivity(intent);
        }
    }

A: каждый раз при нажатии на кнопку UP создавался новый instance activity без параметров, что провоцировало NPE, для того чтобы activity открывалась в том состоянии которое было, в манифесте для нее надо прописать атрибут android:launchMode="singleTop"


text:
Q: How to copy image files whose names don't end with their resolution size? I have a folder with images in it and it is organized by year and month folders (ie. /2015/08/image.jpg). Whenever an image is added, it is also copied and resized like so:
image-1024x768.jpg
image-150x150.jpg
image-300x225.jpg
image-600x450.jpg
image.jpg

I would like to make a script which will search through each year and month folder and copy only the original file into another folder on my system.
I think I need to use regular expressions, but I don't know how.
EDIT: Here are some sample file names. The ones with a star(*) next to them are the only ones that should be copied.
1450366623-20151217-109x300.png
1450366623-20151217-150x150.png
1450366623-20151217-372x1024.png
1450366623-20151217-600x1650.png
1450366623-20151217.png*
image-3-1024x768.jpeg
image-3-150x150.jpeg
image-3-225x300.jpeg
image-3-300x225.jpeg
image-3-600x450.jpeg
image-3-600x800.jpeg
image-3-768x1024.jpeg
image-3-768x576.jpeg
image-3.jpeg*
IMG_0939-1-1024x768.jpg
IMG_0939-1-150x150.jpg
IMG_0939-1-300x225.jpg
IMG_0939-1-600x450.jpg
IMG_0939-1-768x576.jpg
IMG_0939-1-e1451106610990-150x150.jpg
IMG_0939-1-e1451106610990-225x300.jpg
IMG_0939-1-e1451106610990-600x800.jpg
IMG_0939-1-e1451106610990-768x1024.jpg
IMG_0939-1-e1451106610990.jpg*
IMG_0939-1.jpg*

EDIT 2: I said that the images are organized in month/year folders, which I'm sure means it should just be recursive. However, there are other folders next to 2015 that I would prefer don't get copied.
When these pictures are copied, is it possible to copy the folder structure also?
EDIT 3: Thank you to everyone that has answered my question. I must apologize and regretfully admit that I am in over my head with this project and have decided to abandon it. I'm not even sure how to implement most of your answers.

A: You don't need a regular expression, you need extended globbing patterns. I assume your shell is bash:
shopt -s extglob
cd parent-directory-of-2015
for original in */*/!(*-+([0-9])x+([0-9]).jpg); do
    echo "an original: $original"
done

That pattern will exclude files with matching "-digitsxdigits.jpg"

A: Looks like the x within the size of the image in the name could be used, so I'd write it something like this. looking for any file thats name does not have the x using a substring then copy all of them, leaving the others alone.
#!/bin/bash

typeset -i count
let count=0

MAXF="$(find /path -type f -name "*.*" | wc -l)"

find /path   -type f -name "*.*" | while [[ $count -ne $MAXF ]] ;
 do read FILENAME;

name=${FILENAME##*/}
substring="x"

if [[ "$name" != *"$substring"* ]] ; then
     cp -v "$FILENAME" /path/newname
     ((count++))
fi
((count++))
 done

I did not test this... its off the cuff, but that'll set up up to complete what other things you already have in mind to do with your little project.
for this part of your question "When these pictures are copied, is it possible to copy the folder structure also?" is yes, but it can become a complexed script, if you are only coping some files, and not all of them  into a like structor but in a different parent directory.
because it has to be on a different partition or parent directory name in order to have the same subDirectory structor. here is a sniplet of one of my scripts that I do something simluar in it.
This hopegully will help you to figure out how to use variables and command line and the logic to get'er done. the ... indecate code before this would be in place in order for the rest of this code to work properly. the first three statments sets up your dir paths to use srtipt_dir may not really be needed within your script it all depends on how and what you are doing within the script to make it a needed item. move_to can be changed to copy_to.
this is a two loop set up I am using, working off one "base" Dir at a time, then going though every file within that dir before moving on to another "base" dir within a tree and its subdirectories. Checking in a different branch of the tree structor to see if the same dir name is already there, if not then I  move it into that new branch off the tree, if it is then I copy the contents of the branch into that other branch off the tree structor then delete whatever is left in the old branch of the tree (dir structor).
use echo a lot to check your work first before putting it into action
#!/bin/bash

script_dir="path"
files_dir="path"
move_to="path/dirName"

........

    # if this is say /home/picures/myFotos
    # then this statment will check the last dir name is there
    # if it is not there. It will then create it.

   # you will have to then take off of the old dir structor and
   # recreate it off of this statement

    if [[ ! -d "$move_to" ]] ; then
            mkdir -v "$move_to"
        fi

      # set for 5th Directory to be Artist Dir
        echo;echo
        OldDirName=${DIRNAME#*/*/*/*/*/}
        echo "1 - OldDirName $OldDirName"
        echo
        OldDirName=${OldDirName//\/*}
        echo "2 - OldDirName $OldDirName"
        echo
        echo;echo "OldDirName : $OldDirName"
        echo
    # if no artist on file tag present then keep orginal DirName
        if [ ! -z "$changeDirName" ] ; then

            newDirName="$changeDirName"
        else
            #if no Artist MetaData
            newDirName="$OldDirName"
        fi

########### CHANGE NAME OF PARENT DIR WHERE IT IS AT FIRST
        echo;echo "Old Dir Name != newDirName " echo "this is MP3Count - "$MP3Count""

        echo;echo "[[ "$OldDirName" != "$newDirName" ]]"

        if [[ "$OldDirName" != "$newDirName" ]] ; then

            oldDirPathNewName=""$working_dir"/"$newDirName""
            Dir="$newDirName"
            echo;echo "oldDirPathNewName "$oldDirPathNewName""
            echo ""$OldDirName" not = to "$newDirName""

           #change name of dir to artist/band name
            echo "mv "$OldDirName" to "$oldDirPathNewName""

            #change old dir name to new dir name
            #mv -v "$working_dir"/"$OldDirName" "$oldDirPathNewName"

            mv -v "$working_dir"/"$OldDirName" "$oldDirPathNewName"
            echo
        else
            Dir="$OldDirName"
        fi

            from=""$working_dir"/"$Dir""
            to=""$move_to"/"$Dir""

    #check if the desanation directory is already there if not move it or
    # copy it into it then remove left overs

        if [[ ! -d "$to" ]] ; then
        #move_to"/"$Dir" ]] ; then

            echo "inside ck if move to parent / artist to dir is there"
            echo
            echo ""$move_to"/"$Dir" is not there moving "$Dir""
            echo
            #then move the new dir name to a different
            # place for safe keeping
            echo
            echo;echo "just befor move "
            echo
            echo

            echo "$from -> $to"
            mv -vf "$from" "$to"

            echo
            echo "DirIsaidtoDo Left : $DirIsaidtoDo"
            echo

        else

            echo ""$move_to"/"$stringNewDir" is there moving within it into"
            echo
            echo "$move_to"/"$stringNewDir"
            echo

            echo
            cp -Rv "${from}"/* "$to"
            echo
            rm -rv "$from"
            echo
            echo "DirIsaidtoDo Left : $DirIsaidtoDo"
            echo
        fi

    fi

            echo "********** NEXT FILE ***********************"

        done
        let DirCountDn++
        echo "Dir Count Dn "$DirCountDn""
        echo "******************************************"
        let AmountDirs--
        echo "Amount Dirs to go $AmountDirs"
        echo
        let DirIsaidtoDo--

        echo;echo;echo

    done #FOR DIR Names

to create more then one dir in a path dir cretion order, this creates all dirNames setting up a parent dir and its subDir too
 mkdir -pv path/dirName/DirName/DirName


text:
Q: How to pass objects to a TemplateView? I am just learning CBVs and having a tough time with passing an object to a TemplateView. This has been pretty demoralizing as I know this should be very basic.
Here is my views.py:
from __future__ import absolute_import
from django.views import generic
from company_account.models import CompanyProfile

class CompanyProfileView(generic.TemplateView):
    template_name = 'accounts/company.html'

    def get_context_data(self, **kwargs):
        context = super(CompanyProfileView, self).get_context_data(**kwargs)
        return CompanyProfile.objects.all()

And here is my Models.py:
from __future__ import unicode_literals

from django.db import models
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse

class CompanyProfile(models.Model):
    company_name = models.CharField(max_length=255)

    def __str__(self):
        return self.company_name

Here is urls.py
urlpatterns = [
    url(r'^accounts/companyprofile/$', CompanyProfileView.as_view()),
]

And finally, here is the template:
{% extends '_layouts/base.html' %}

{% block title %}Company Profile{% endblock %}

{% block headline %}
Company Profile
{% endblock %}

{% block content %}{{ CompanyProfile.company_name }}{% endblock %}

What am I missing? Thank you in advance for your help.

A: The template cannot read the model CompanyProfile. You have to create an instance of the model first before you get any attribute.
Suppose you have the several instances of CompanyProfile:
CompanyProfile.objects.get(pk=1) --> this has a company_name="Adidas"
CompanyProfile.objects.get(pk=2) --> this has a company_name="Nike"
And suppose you want to display Nike and Adidas.
Then here's how you can do it:
class CompanyProfile(models.Model):
   company_name = models.CharField(max_length=25)

class CompanyProfileView(views.TemplateView):
   template_name = 'my_template.html'

   def get_context_data(self, **kwargs):
       context = super(CompanyProfileView, self).get_context_data(**kwargs)
       # here's the difference:
       context['company_profiles'] = CompanyProfile.objects.all()
       return context

Then, render your template like this:
{% for company in company_profiles %}
    {{ company.company_name }}
{% endfor %}

I hope that helps!


text:
Q: Google Charts - How to stretch x axis over chart's full width I can't figure out why Google Charts draws this simple chart aligned to center and doesn't fill entire white area.
Note: X axis is discrete because it represents weeks.

Do you have any idea what can I do with it?

A: That is how the charts display when you use a discrete (string) axis.  If you want edge-to-edge lines, you need to use a continuous (number, date, datetime, timeofday) axis.  See an example of the differences here: http://jsfiddle.net/asgallant/Xfx3h/.


text:
Q: Как пользоваться setPersistance в firebase? Не работает локальное сохранение пользователя через setPersistance.
В документации firebase не совсем понятно объяснено. Правильно ли я пользуюсь setPersistance?
const handleLogin = (email, password) => {
        const auth = getAuth();
        setPersistence(auth, browserSessionPersistence)
            .then(() => {
                return signInWithEmailAndPassword(auth, email, password)
                    .then(({user}) => {
                        dispatch(setUser({
                            email: user.email,
                            id: user.uid,
                            token: user.accessToken
                        }))
                        navigate('/')
                    })
                    .catch(() => dispatch(authError()))
            })
            .catch((error) => {
                const errorCode = error.code;
                const errorMessage = error.message;
            });
    }


text:
Q: what happens when an xml file tries to be read while it is being written? I have an iOS app that allows users to update the cover charges at local bars. The data is then displayed on the app for other users to see. The updates are made by sending a request to a php script and then the script updates and xml file. What will happen if a user tries to read the xml while another user is updating it, i.e. while the file is being rewritten with a new update?
Thanks!

A: The user has a 50-50 chance of getting the updated version, depending on the server speed and there connection speed it may differ. I agree with AMayer, once the file gets big it's going to be hard on your server to download and upload the ENTIRE xml file again and again! I would just setup a MySQL database now and use it instead of the XML.


text:
Q: Performance monitoring for Google Cloud DataProc We are using GoogleCloudPlatform for big-data analytics.
For processing we are currently using the google cloud dataproc & spark-streaming.
We would like to check the job performance using some monitoring utilities like Ganglia, Graphite, Dr.Elephant etc.
For setting up of any of these requires modification of configuration in each nodes.
I would like to know, if the dataproc natively supports any of such performance monitoring tools?

A: None of those are supported out of the box, but you could add Ganglia using this initialization action. You can configure it however you like by editing the script.
You would then have to follow these instructions to access the Web UI.


text:
Q: getting error in launching video file from local server D/MULTI_WINDOW_SWITCH_ENABLED: false
D/SurfaceView: UPDATE null, mIsCastMode = false
V/MediaHTTPService: MediaHTTPService(android.media.MediaHTTPService@9f7e182): Cookies: null
V/MediaHTTPService: makeHTTPConnection: CookieManager created: java.net.CookieManager@1ccd093
V/MediaHTTPService: makeHTTPConnection(android.media.MediaHTTPService@9f7e182): cookieHandler: java.net.CookieManager@1ccd093 Cookies: null
D/DecorView[]: onWindowFocusChanged hasWindowFocus false
D/DecorView[]: onWindowFocusChanged hasWindowFocus true
D/OpenGLRenderer: endAllActiveAnimators on 0xb400007ab41e8400 (RippleDrawable) with handle 0xb400007a50bde960
W/System: A resource failed to call close.
E/MediaPlayerNative: error (1, -2147483648)
E/MediaPlayer: Error (1,-2147483648)
D/VideoView: Error: 1,-2147483648
D/IS_CTS_MODE: false
D/MULTI_WINDOW_SWITCH_ENABLED: false
D/CompatibilityChangeReporter: Compat change id reported: 171228096; UID 10427; state: ENABLED
D/DecorView[]: onWindowFocusChanged hasWindowFocus false
D/DecorView[]: onWindowFocusChanged hasWindowFocus true
Please give me the solution


text:
Q: Creating a snap for JavaFX application I'm trying to create a snap for a JavaFX application, but I can't seem to figure out how to structure the yaml file.
I've read that I need to use the desktop-launch command, but I also need to call Java's java -jar command. I'm not sure how to put these two things together.
Anyway, here's my current snapcraft.yaml file.
name: apuviewer # you probably want to 'snapcraft register <name>'
version: '1.0' # just for humans, typically '1.2+git' or '1.3.2'
summary: Single-line elevator pitch for your amazing snap # 79 char long summary
description: |
  Description

grade: devel # must be 'stable' to release into candidate/stable channels
confinement: devmode # use 'strict' once you have the right plugs and slots

apps:
  apuviewer:
    command: desktop-launch $SNAP/apuViewer-1.0.jar
    plugs: [home, network, x11]

parts:
  apuviewer:
    source: .
    plugin: dump
    after: [desktop-gtk3]
    build-packages:
    - ca-certificates
    - ca-certificates-java
    - openjdk-8-jre-headless
    stage-packages:
    - openjdk-8-jre-headless

It's currently throwing this error:
/snap/apuviewer/x1/bin/desktop-launch: line 545: exec: /snap/apuviewer/x1/apuViewer-1.0.jar: cannot execute: Permission denied

I've tried many different things, but can't seem to get it to run. Any help is much appreciated!


text:
Q: Loading design-time WPF resources in Visual Studio through .csproj In Expression Blend 4, it's possible to load design-time resources by editing your project file. Here's an example of what that would look like:
<Page Include="Properties\DesignTimeResources.xaml"
    Condition="'$(DesignTime)'=='true'
    OR ('$(SolutionPath)'!='' AND Exists('$(SolutionPath)')
    AND '$(BuildingInsideVisualStudio)'!='true'
    AND '$(BuildingInsideExpressionBlend)'!='true')">
    <Generator>MSBuild:Compile</Generator>
    <SubType>Designer</SubType>
    <ContainsDesignTimeResources>true</ContainsDesignTimeResources>
</Page>

Now I've been trying to get the same thing working in Visual Studio 2010 without success. Has anyone gotten design-time data to load like this in Visual Studio or is this feature only supported using Expression Blend?

A: You are looking for the use of d:DesignData and d:DataContext. Here is an example on Jag Reehal's blog using Blend and Visual Studio. And a Microsoft Walkthrough


text:
Q: Typescript generate enum from an interface keys with index number I would like to convert this interface to a enum with the index of the element
interface CsvUser {
  firstname: string;
  lastname: string;
  email: string;
  remoteAddress: string;
  team: string;
  role: string;
  post: string;
  site: string;
  workspace: string;
  zone: string;
}

to
enum CsvUserColumnId {
  firstname = 0,
  lastname = 1,
  email = 2,
  remoteAddress = 3,
  team = 4,
  role = 5,
  post = 6,
  site = 7,
  workspace = 8,
  zone = 9,
}

I only find a way to go from enum to interface but not interface to enum like this
type CsvUser = {
  [K in keyof typeof CsvUserColumnId]: string;
}


text:
Q: How to populate and maintain listView with images? I want to design a listView such that when a user adds a photo, it will automatically update the listView with the name of the image and it's thumbnail. However my current attempts don't even render the image. Is it possible to dynamically set the ImageView for each cell of a listView and have it be updated when I add a new element to the Adapter?
XML for listView and add button:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".Photos"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.Toolbar
        android:id="@+id/view_album_bar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        android:elevation="4dp"
        android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

    <ListView android:layout_marginTop="?android:attr/actionBarSize"
        android:id="@+id/photos_list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:choiceMode="singleChoice"
        android:listSelector="@android:color/darker_gray" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/add_photo_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"
        android:layout_marginBottom="25dp"
        android:layout_marginEnd="25dp"
        android:clickable="true"
        android:src="@drawable/plus"/>

</RelativeLayout>

Activity:
    public class ViewAlbum extends AppCompatActivity {
        public Album activeAlbum;
        private ListView photoList;
        private ArrayList<String> currentPhotos = new ArrayList<String>();
        private ArrayAdapter<String> adapter;
        private int currentSelected = -1;
        public static final int PICK_IMAGE = 1;

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

            final Context context = getApplicationContext();
            Toolbar albumBar = findViewById(R.id.view_album_bar);
            setSupportActionBar(albumBar);

            photoList = findViewById(R.id.photos_list);
            Bundle bundle = getIntent().getExtras();
            String albumName = bundle.getString("album_name");
            activeAlbum = Album.loadAlbum(this.getFilesDir().getPath()+"/"+albumName+".txt");
            for(Photo photo: activeAlbum.photos){
                ImageView thumbnail = findViewById(R.id.photo_thumbnail);
                if(thumbnail == null){
                    System.out.println("why?");
                    //Don't understand why it is null, can't set image
                }
                currentPhotos.add(photo.name);
            }
            adapter = new ArrayAdapter<String>(this, R.layout.photo_cell,
                    R.id.photo_name,currentPhotos);
            photoList.setAdapter(adapter);
            photoList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    currentSelected = position;
                }
            });
            FloatingActionButton addPhotoBtn = (FloatingActionButton)findViewById(R.id.add_photo_btn);
            addPhotoBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent();
                    intent.setType("image/*");
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
                }
            });
        }
        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data){
            super.onActivityResult(requestCode, resultCode, data);
            if (requestCode == PICK_IMAGE && resultCode == Activity.RESULT_OK
                    && data != null && data.getData() != null)  {
                Uri uri = data.getData();
                Photo newPhoto = new Photo("name", uri.getPath());
                activeAlbum.photos.add(newPhoto);
                activeAlbum.saveAlbum();
            }
        }

Each ListView Cell:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="?android:attr/activatedBackgroundIndicator">

    <LinearLayout android:id="@+id/thumbnail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="3dip"
        android:layout_alignParentLeft="true"
        android:layout_marginRight="5dip">

        <ImageView
            android:id="@+id/photo_thumbnail"
            android:layout_width="106dp"
            android:layout_height="77dp" />
    </LinearLayout>

    <TextView
        android:id="@+id/photo_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="25dp"
        android:text="Album Name"
        android:textColor="#0984e3"
        android:textSize="25dip"
        android:textStyle="bold"
        android:typeface="sans" />

</RelativeLayout>

A: When you get result on OnActivityResult() add it to currentPhotos,
then call notifyDataSetChanged()

A: Firstly, I think album.photo is not the same array as the array you passed when you create the adapter (currentPhotos). So adding new Photo to album.photo does not reflect that item in the listView.
Secondly, as user dev points out, whenever you change the data you need to tell the adapter by adapter.notifyDataSetChanged(). However in your case, you always add to the end i think it is better to call adapter.notifyDataInserted(currentPhotos.size() - 1)

A: If you are working with images which are locally stored or on the web. Using a lib like implementation 'com.squareup.picasso:picasso:2.71828' is probably a good idea as it can handle image and URL based exception and had a catch of the data so that it is easier to open apps memory can be used minimally.


text:
Q: Spinner selected option must be stored in google form main activity
package com.example.wastewarriorsnew;

public class MainActivity extends Activity implements OnItemSelectedListener {

final String myTag = "DocsUpload";
String location,name,check_in,check_out,recy,nonrecy,recy_wt,nonrec_wt,new_loc,num,total_wt;
InputStream is=null;
String result=null;
String line=null;
int code;
String id;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // Spinner element
    Spinner spinner = (Spinner) findViewById(R.id.spinner1);

      // Spinner click listener
      spinner.setOnItemClickListener((OnItemClickListener) this);

      // Spinner Drop down elements
      List<String> categories = new ArrayList<String>();
      categories.add("Dehradun");
      categories.add("Pune");
      categories.add("Mumbai");
      categories.add("Delhi");
      categories.add("Goa");
      categories.add("Solapur");

      // Creating adapter for spinner
      ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);

      // Drop down layout style - list view with radio button
      dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

      // attaching data adapter to spinner
      spinner.setAdapter(dataAdapter);

    final EditText ed2 = (EditText)findViewById(R.id.workername);
    final EditText ed3 = (EditText)findViewById(R.id.Checkin);
    final EditText ed4 = (EditText)findViewById(R.id.Chechout);
    final EditText ed5 = (EditText)findViewById(R.id.Recycle);
    final EditText ed6 = (EditText)findViewById(R.id.NonRecycle);
    final EditText ed7 = (EditText)findViewById(R.id.Recycleweight);
    final EditText ed8 = (EditText)findViewById(R.id.Nonweight);
    final EditText ed9 = (EditText)findViewById(R.id.newlocation);
    final EditText ed10 = (EditText)findViewById(R.id.Number);
    final EditText ed11 = (EditText)findViewById(R.id.totalweight);

    final Button bt1=(Button)findViewById(R.id.button1);
bt1.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View arg0) {

        name=ed2.getText().toString();
        check_in=ed3.getText().toString();
        check_out=ed4.getText().toString();
        recy=ed5.getText().toString();
        nonrecy=ed6.getText().toString();
        recy_wt=ed7.getText().toString();
        nonrec_wt=ed8.getText().toString();
        new_loc=ed9.getText().toString();
        num=ed10.getText().toString();
        total_wt=ed11.getText().toString();

        Log.i(myTag, "OnCreate()");
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                postData();

            }
        });
        t.start();
        // TODO Auto-generated method stub

    }

});

}
public void postData() {

    String fullUrl = "https://docs.google.com/forms/d/e/1FAIpQLScXtmI3Ev-cxc04Ai5_6zmnudLoF6W9g/formResponse";
    HttpRequest mReq = new HttpRequest();

    final EditText ed2 = (EditText)findViewById(R.id.workername);
    final EditText ed3 = (EditText)findViewById(R.id.Checkin);
    final EditText ed4 = (EditText)findViewById(R.id.Chechout);
    final EditText ed5 = (EditText)findViewById(R.id.Recycle);
    final EditText ed6 = (EditText)findViewById(R.id.NonRecycle);
    final EditText ed7 = (EditText)findViewById(R.id.Recycleweight);
    final EditText ed8 = (EditText)findViewById(R.id.Nonweight);
    final EditText ed9 = (EditText)findViewById(R.id.newlocation);
    final EditText ed10 = (EditText)findViewById(R.id.Number);
    final EditText ed11 = (EditText)findViewById(R.id.totalweight);

    //String col1 = "Hello";
    //String col2 = "World";

    String data =// "entry.1178044604=" + URLEncoder.encode(location) + "&" +
                  "entry.224535232=" + URLEncoder.encode(name)      + "&" +
                   "entry.829233547="+ URLEncoder.encode(check_in)  + "&" +
                    "entry.1814499237=" + URLEncoder.encode(check_out)+"&"+
                    "entry.1206946186="+ URLEncoder.encode(recy)+ "&" +
                  "entry.651664232=" + URLEncoder.encode(nonrecy) + "&" +
                    "entry.1115147786="+ URLEncoder.encode(recy_wt)+"&"+
                    "entry.472878985=" + URLEncoder.encode(nonrec_wt) +"&"+
                    "entry.1615743649="+ URLEncoder.encode(new_loc)+"&"+
                    "entry.2005603514="+ URLEncoder.encode(num)+"&"+
                    "entry.871683438="+ URLEncoder.encode(total_wt);

    String response = mReq.sendPost(fullUrl, data);
    Log.i(myTag, response);

}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    // TODO Auto-generated method stub
     // On selecting a spinner item
      String item = parent.getItemAtPosition(position).toString();

      // Showing selected spinner item
      Toast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
    // TODO Auto-generated method stub

}

}

xml file
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:id="@+id/scrollView1"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:background="@drawable/back" >

<LinearLayout
android:layout_width="match_parent"
android:layout_height="630dp"

android:orientation="vertical"
tools:context=".MainActivity" >

    <TextView android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:text="Location address"    />

    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:text="Worker name"/>
    <EditText
    android:id="@+id/workername"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="Worker Name"
    android:inputType="text" />

    <TextView android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:text="Check in"/>

<EditText
    android:id="@+id/Checkin"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="Check-in time"
    android:inputType="time" />

<TextView android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:text="Check out"
      />

 <EditText
 android:id="@+id/Chechout"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:hint="Check-out time"
 android:inputType="time" />

 <TextView android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:text="No. of recyclable bags"
      />
 <EditText
   android:id="@+id/Recycle"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:hint="No of bags used for recyclable material"
   android:inputType="number" />

 <TextView android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:text="No. of non-recyclable bags"
      />
 <EditText
android:id="@+id/NonRecycle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="No of bags used for non-recyclable material"
android:inputType="number" />

 <TextView android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:text="Wt. of recycle material"
      />
 <EditText
android:id="@+id/Recycleweight"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Weight of recyclable material"
android:inputType="text" />

 <TextView android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:text="Wt. of non-recycle material"
      />
 <EditText
    android:id="@+id/Nonweight"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="Weight of non-recyclable material"
    android:inputType="text" />

 <TextView android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:text="New location(if shifted)"
      />
 <EditText
    android:id="@+id/newlocation"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="New location(if shifted)"
    android:inputType="text" />

 <TextView android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:text="No. of persons"
      />
 <EditText
    android:id="@+id/Number"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="No. of persons per loaction"
    android:inputType="number" />

 <TextView android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:text="Total weight"
      />
 <EditText
     android:id="@+id/totalweight"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:hint="Total weight of recyclable and non-recyclable material"
     android:inputType="number" />

 <LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

 <Button
    android:id="@+id/button1"
    android:layout_width="80dp"
    android:layout_height="40dp"
    android:layout_marginLeft="40dp"
      android:layout_marginTop="50dp"
    android:text="Save" />

</LinearLayout>
</LinearLayout>
</ScrollView>

The error i was getting in logcat is:

08-03 04:49:03.828: E/AndroidRuntime(773): java.lang.RuntimeException:
  Unable to start activity
  ComponentInfo{com.example./com.exampleMainActivity}:
  java.lang.ClassCastException: com.example.MainActivity cannot be cast
  to android.widget.AdapterView$OnItemClickListener

but now there are no msgs in the logcat,but still the msg is:

Unfortunately stopped working.

As the app will run,from main activity the details will be added and clicking on save button,it will be stored in google forms.
Help me .


text:
Q: Jquery File Upload Plugin - File Delete - Authorization header I am using jquery file upload plugin for one of my project, using basic browser authentication for user access control. Once logged in, I am passing the base64 encoded string of username and password across the calls on the user session. Base64 encoded string is sent to server via http authorization header. I was fairly successful in setting authorization header for all the calls except file delete one. Would appreciate, if any one can give pointers in that direction
I am setting the authorization header for other calls as below
$('#fileupload').addClass('fileupload-processing');
  $.ajax({
    // Uncomment the following to send cross-domain cookies:
    url: $('#fileupload').fileupload('option', 'url'),
    dataType: 'json',
  type: 'GET',
  beforeSend: function(xhr) {
    xhr.setRequestHeader('Authorization', btoa(userId,password));
  }

A: In jquery.fileupload-ui.js file, add the below code in the code block of "Callback for file deletion:"
data.beforeSend = function(xhr) {
                    xhr.setRequestHeader('Authorization', make_base_auth(userId,userId));
                  };

A: I did this in another way. I used event which is fired before send delete request and added header to data object
$('#fileupload')
    .bind('fileuploaddestroy', function (e, data) {
        data.headers = {
            'Authorization_Token': "any_token"
        };
});


text:
Q: Why can't I pip install the latest version of fabric? I'm using a requirements file that lists all packages to install as part of my virtual env. One of these is Fabric=1.10.2, the most recent release. However, this fails to match:

Could not find a version that satisfies the requirement
  fabric==1.10.2 (from -r stable-req.txt (line 4)) (from versions:
  0.0.1.macosx-10.4-i386, 0.0.2.macosx-10.4-i386, 0.0.3.macosx-10.4-i386, 0.0.4.macosx-10.4-i386, 0.0.5.macosx-10.4-i386, 0.0.1, 0.0.2, 0.0.3, 0.0.4, 0.0.5, 0.0.6, 0.0.7, 0.0.8, 0.0.9, 0.1.0, 0.1.1, 0.9.0, 0.9.1, 0.9.2, 0.9.3, 0.9.4, 0.9.5, 0.9.6, 0.9.7, 1.0.0, 1.0.1, 1.0.2, 1.0.3, 1.0.4, 1.0.5, 1.1.0, 1.1.1, 1.1.2, 1.1.3, 1.1.4, 1.1.5, 1.1.6, 1.1.7, 1.1.8, 1.10.0, 1.10.1, 1.2.0, 1.2.1, 1.2.2, 1.2.3, 1.2.4, 1.2.5, 1.2.6, 1.3.0, 1.3.1, 1.3.2, 1.3.3, 1.3.4, 1.3.5, 1.3.6, 1.3.7, 1.3.8, 1.4.0, 1.4.1, 1.4.2, 1.4.3, 1.4.4, 1.5.0, 1.5.1, 1.5.2, 1.5.3, 1.5.4, 1.5.5, 1.6.0, 1.6.1, 1.6.2, 1.6.4, 1.7.0, 1.7.1, 1.7.2, 1.7.3, 1.7.4, 1.7.5, 1.8.0, 1.8.1, 1.8.2, 1.8.3, 1.8.4, 1.8.5, 1.9.0, 1.9.1, 1.9.2, 0.0.1.macosx-10.4-i386, 0.0.2.macosx-10.4-i386, 0.0.3.macosx-10.4-i386, 0.0.4.macosx-10.4-i386, 0.0.5.macosx-10.4-i386, 0.0.1, 0.0.2, 0.0.3, 0.0.4, 0.0.5, 0.0.6, 0.0.7, 0.0.8, 0.0.9, 0.1.0, 0.1.1, 0.9.0, 0.9.1, 0.9.2, 0.9.3, 0.9.4, 0.9.5, 0.9.6, 0.9.7, 1.0.0, 1.0.1, 1.0.2, 1.0.3, 1.0.4, 1.0.5, 1.1.0, 1.1.1, 1.1.2, 1.1.3, 1.1.4, 1.1.5, 1.1.6, 1.1.7, 1.1.8, 1.10.0, 1.10.1, 1.2.0, 1.2.1, 1.2.2, 1.2.3, 1.2.4, 1.2.5, 1.2.6, 1.3.0, 1.3.1, 1.3.2, 1.3.3, 1.3.4, 1.3.5, 1.3.6, 1.3.7, 1.3.8, 1.4.0, 1.4.1, 1.4.2, 1.4.3, 1.4.4, 1.5.0, 1.5.1, 1.5.2, 1.5.3, 1.5.4, 1.5.5, 1.6.0, 1.6.1, 1.6.2, 1.6.4, 1.7.0, 1.7.1, 1.7.2, 1.7.3, 1.7.4, 1.7.5, 1.8.0, 1.8.1, 1.8.2, 1.8.3, 1.8.4, 1.8.5, 1.9.0, 1.9.1, 1.9.2) No distributions matching the version for fabric==1.10.2 (from -r stable-req.txt (line > 4))

Am I stuck with 1.10.1 until this has been propped somewhere? Is there a way I can initiate that prop, or whatever needs to happen? I'm not too well versed in how this works behind the scenes, so any insight would be super.
Update 1
To address the comments and answers provided, calling upgrade isn't really an option, because we want to explicitly upgrade to 1.10.2, which just happens to be the latest release at the moment. Once 1.10.3 is released, we don't want our scripts to auto-update our clients with this version until we tell it to do so.

A: try:
sudo pip install --upgrade pip
pip uninstall fabric
pip install fabric==1.10.2

A: Well I think you can try to install it via commit id.
I think the commit you want is:
https://github.com/fabric/fabric/commit/c5065944e7f274cbd5b97c248681f89705972b3a
So you can try the following command:
pip install git+git://github.com/fabric/fabric.git@c5065944e7f274cbd5b97c248681f89705972b3a

PS: this not solve the problem (installing via version 1.10.2) but you might be able to install to work with the same code base of version you need.
Hope it helps! =)

A: Latest version will be installed with
pip install django


text:
Q: Application Request Limit issue (Occuring Random with Random Scenarios) I have tried raising this concern on Facebook/Support/Bugs but they said I should post implementation issues here. I have read it everywhere and it seems to be quiet open issue till now. I am not sure, If this will be solved or not.
So, what we are doing is, we have clients - Android and iOS.
Apps on Android/iOS allows users to login into the app and generate the token on the basis of permissions set we have, and we are passing this token to server for fetching further data as and when required for client. As our userbase is increasing we are getting Application request limit reached quiet often.
We are fetching photos of users and their friends using FQL. So, when parallely fetching photos for around 8-10 different users, we are reaching the Application request limit sometimes, which is quiet random and we are not aware of the actual scenario when it breaks up and how. According to facebook the limit, which is 1M calls per day, but we are hitting around 80K - 1 Lac API calls in a day, but as users are increasing it is stretching a bit further, Less than or equal to 200 approax calls/user. We tried doing batch calls as well and we hit the application request limit as well.
If anyone of you could help us understand the complete concept of API limit and how this can be handled, then we will really appreciate the help. We want to understand how API limit is decided and it's rate is calculated over which interval so that we will be able to configure on our side accordingly.
Earlier in the day, we ran into a unique API call issue. Our server started to break for API calls for user tokens that are with us, we (on our systems, other than server) tried fetching the data for those tokens (Simple calls - /me or /me/home), and it was working alright for us but not for server, then we tried setting up another server and redirected the requests to our new server then this server works well for the same set of users. Not sure, what went wrong in this case and how it breaks up. Please help.
Many Thanks,
Reno Jones

A: Did you look at the Insights -> Developer section of developer.facebook.com for your app?
This will show you a breakdown per api call, including warnings and ones that are currently being throttled and why.
Also, are you sure you're using User token authorization and not just your App token?
Beyond that, we take the information from Insights to find api calls to cache on our side rather than hitting Facebook every time. You will likely have to do something similar if you're not already. They have limits for calling too often, as well as for requesting too much data. For those, we had to reduce the limits of historical data we requested.


text:
Q: How to convert this code based on lists to code based on numpy arrays? I am working with the keras and there is always a from with a lists, so I guess that always everything has to be converted to the numpy array which are very illogical for me. I guess that it is associated with performance? I don't see any other reason? However my problem looks like shown below. I have to convert this part of code:
output_sentence = []
final_output_sentence = []

for key in row['o'].lower():

    temp_list = []

    if key in dictionary.keys():

        temp_list.append(dictionary[key])
        output_sentence.append(temp_list)

    else:

        dictionary[key] = len(dictionary)
        temp_list.append(dictionary[key])
        output_sentence.append(temp_list)

final_output_sentence.append(output_sentence)

to the code based on numpy arrays. I try in this way:
output_sentence = np.array([], dtype=int)
final_output_sentence = np.array([], dtype=int)

for key in row['o'].lower():

    temp_list = np.array([], dtype=int)

    if key in dictionary.keys():

        temp_list = np.append(temp_list, dictionary[key])

        output_sentence = np.append(output_sentence, temp_list)

    else:

        dictionary[key] = len(dictionary)
        temp_list = np.append(temp_list, dictionary[key])
        output_sentence = np.append(output_sentence, temp_list)

final_output_sentence = np.append(final_output_sentence, output_sentence)

however instead of this [[[1], [2], [3], [2], [4]]] I get this [1 2 3 2 4]. Any ideas how to solve this?
UPDATE
What do you think about solution shown below? Any tips for performance optimization?
output_sentence = []

for key in row['o'].lower():

    temp_list = []

    if key in dictionary.keys():

        temp_list.append(dictionary[key])
        output_sentence.append(temp_list)

    else:

        dictionary[key] = len(dictionary)
        temp_list.append(dictionary[key])
        output_sentence.append(temp_list)

final_output_sentence = np.array(output_sentence)

final_output_sentence = final_output_sentence.reshape(1, final_output_sentence.shape[0], 1)

A: output_sentence = []
for key in row['o'].lower():
    if key not in dictionary.keys():
        dictionary[key] = len(dictionary)
    output_sentence.append(dictionary[key])

final_output_sentence = np.array(output_sentence).reshape(1,-1,1)

*

*If the key does not exist in dictionary then add it with the next size

*Append the value corresponding corresponding to the key into output_sentence

*Finally, output_sentence is a list but since you want a 3D array, convert it into numpy array and reshape it.

*x.reshape(1,-1,1) => reshape x such that size of 0th axis is 1, size of 2nd axis is 1 and the size of 1st axis will be same a elements in x.


text:
Q: visual studio Python tools plugin command line: pass '%09' as a string and NOT have it be interpreted as tab i'm in Visual studio 2010 debugger using the Python tools plugin (which is FABULOUS by the way). i set my command line args to 'BON7%09/13' and I want that passed in as a string. Now visual studio tells me I have two command line args, not one: "BON7" and "/13". This is because %09 is ascii code for tab, and it's converting the char. But I don't want that conversion. How do I block it?
  I tried all the usual escapes (single quotes around the string, double quotes around the string, backslash in front of the %) but none of those help. How do I make visual studio treat that command line arg as pure text?
   For what it's worth, it doesn't convert the %09 when I run from command line without Visual Studio. Also, I tried the same thing in C# but it works fine there.

A: You could try a work around of using %3709 which if consumed as you described should create %09.


text:
Q: Difference of Do while/Do until in VBscript What is the difference between Do while and Do until loops in vbscript, and what are the equivalent loops statements in javascript ?

A: The only difference between do while and do until is that the first one loops as long as the condition is true, while the second one loops as long as the condition is false.
In Javascript you use do {} while() or while() {}. Example:
var cnt = 0;
do {
  cnt++;
} while (cnt < 10);

and:
var cnt = 0;
while (cnt < 10) {
  cnt++;
}

Use the ! operator to negate the condition to get the same functionality as until.

A: Do while, (Repeat Code While a Condition is True)
Do While i>10
  some code
Loop

or
Do
  some code
Loop While i>10

Do until, (Repeat Code Until a Condition Becomes True)
Do Until i=10
  some code
Loop

or
Do
  some code
Loop Until i=10

javascripts,
while ( i>10)
{
   some code
}

or,
do
{
   some code
} while (i>10);

Hope you got the idea

A: Google is your friend. The do-while loop executes 1 or more times, while a while loop executes 0 or more times.
From MSDN:
While   Required unless Until is used. Repeat the loop until condition is False.
Until   Required unless While is used. Repeat the loop until condition is True.


text:
Q: Problems finding derivative - simple I have some scalar function $S: \mathbb R^{m \times n} \to \mathbb R$
I also know some other function $h:\mathbb R^{m \times n} \to \mathbb R^{m \times n}$.
I know the derivative $\frac{\partial S(h(z))}{\partial h(z)}$. It is of size $m$ by $n$, as expected.
What I want to find is $\frac{\partial S(h(z))}{\partial z}$. It should also be of size $m$ by $n$ since $z \in \mathbb R^{m \times n}$.
If we use chain-rule, we will get that:
$\frac{\partial S(h(z))}{\partial z} = \frac{\partial S(h(z))}{\partial h(z)}\frac{\partial h(z)}{\partial z}$
Since we expect that $\frac{\partial S(h(z))}{\partial z}$ is $m$ by $n$, and we know that $\frac{\partial S(h(z))}{\partial h(z)}$ is $m$ by $n$, it follows that we must have $\frac{\partial h(z)}{\partial z}$ is $n$ by $n$.
The problem is that it isn't. According to my calculations $\frac{\partial h(z)}{\partial z}$ is $m^2$ by $n^2$. So we have a dimension mismatch and multiplication is not possible.
I asked earlier today a question that resembles this, and was told that chain-rule does not always work in matrix calculus. Fine, this must be one of those examples, but I still need to find that derivative, how do i do it?
More in-depth details
In reality, I have a matrix $z \in \mathbb R^{m \times n}$. I then compute the $h$ matrix as follows: $h_{ij} = g(z_{ij}) = \frac{1}{1+e^{-z_{ij}}}$. This is called a sigmoid function. It has the special property that $g'(x) = g(x)(1-g(x))$.
My original function $S$ is a function of this new matrix $h$. But I need to find the derivative with respect to $z$.
More clearly:
If $z = \begin{pmatrix} z_{11} & z_{12} & \dots & z_{1n} \\ \vdots & \dots & \dots & \vdots \\ z_{m1} & z_{m2} & \dots & z_{mn}\end{pmatrix}$ then $h = \begin{pmatrix} g(z_{11}) & g(z_{12}) & \dots & g(z_{1n}) \\ \vdots & \dots & \dots & \vdots \\ g(z_{m1}) & g(z_{m2}) & \dots & g(z_{mn})\end{pmatrix}$
Now if for example we look at the derivative with respect to $z_{11}$, we will simply get the matrix $\begin{pmatrix} g(z_{11})(1-g(z_{11})) & 0& \dots & 0 \\ \vdots & \dots & \dots & \vdots \\ 0 & 0 & \dots & 0\end{pmatrix}$ which is $m$ by $n$.
So overall if we look at the derivative of $h$ wrt entire $z$, we will have an $m^2$ by $n^2$ matrix. Which again does not make much sense and does not help us at all to find the derivative of $S$ wrt $z$, which is what we originally wanted.

A: $\frac{\partial h(z)}{ \partial z} = \nabla h(z)$ will be a linear operator from $\mathbb{R}^{m \times n}$ to $\mathbb{R}^{m \times n}$, so if we vectorize $z$  we will need a matrix of size $mn \times mn$ to represent it. This matrix will have entries defined by partial derivatives $(\nabla h(z))_{(i,j),(k,l)} = \frac{\partial h(z)_{i,j}}{ \partial z_{k,l}}$. However, in your case this matrix will be diagonal with diagonal entries $(\nabla h(z))_{(i,j),(i,j)} = g(z_{i,j})(1 - g(z_{i,j}))$.
How $\nabla h(z)$ interacts with $\nabla S $ will be more sort of composition than multiplication if you think about differentials as linear operators i.e
$$ \nabla (S \circ h) (z) = \mathrm{vec}^{-1}(\nabla h(z)(\mathrm{vec} \nabla S(h(z)))) \in \mathbb{R}^{m \times n} $$
where $\mathrm{vec} : \mathbb{R}^{m \times n} \to \mathbb{R}^{mn} $ associates a matrix with a vector of its entries.
The main idea here is to think about differentials as linear transformations instead of plain matrices. In this case you can forget about $\mathrm{vec}$ and remember it only for computations.
(Sorry for change of notation)


text:
Q: Converting StreamWriters to StreamReader I was just wondering really if there was an easy way to redirect the output from a StreamReader (in my case one from a NamedPipeClientStream) to the input of a StreamWriter (in my case the one in Console.Out).
Of course you could do this fairly easily with a simple while loop redirecting the data but at the same time I also want to redirect the console's input to a stream writer and out to the Pipe.
I could do it with threads but it seems a bit of a waste of a thread... So I ask, is there a nice way to link streams together?
Been at this all day and I haven't found an easy way yet :/

A: From .NET 4.5 on, there is the Stream.CopyToAsync method:
How do I copy the contents of one stream to another?
http://msdn.microsoft.com/en-us/library/system.io.stream.copytoasync.aspx


text:
Q: Procedure is having some issue I have a procedure test
alter Procedure [dbo].[test]
(
@Branch nvarchar(100)
)
AS
BEGIN

SELECT        res.f_Employee_Id AS Employee_Id, emp.f_Employee_Name, q.f_Question AS Question, ISNULL(ans.f_Name, res.f_Answer) AS Answer, CONVERT(nvarchar, res.f_Created_Date, 103) AS Feedback_Date,
                     emp.f_Grade AS Grade, emp.f_Branch_DESC AS Branch
FROM            T_PAF_EmployeeResult AS res WITH (nolock) LEFT OUTER JOIN
                     t_PAF_FeedbackAns_Master AS ans WITH (nolock) ON res.f_Answer = ans.f_Code INNER JOIN
                     t_PAF_FeedbackQues_Master AS q WITH (nolock) ON res.f_Question_Id = q.f_Uid INNER JOIN
                     T_PAF_EmployeeList_2017 AS emp WITH (nolock) ON emp.f_Employee_ID = res.f_Employee_Id
WHERE

((@Branch = emp.f_Branch_DESC) OR
                     (@Branch IS NULL)) and f_Company_Id=1031

ORDER BY Employee_Id, res.f_Question_Id
END

exec test 'Head Office'
Output
Employee_Id f_Employee_Name     Question                                                            Answer          Feedback_Date   Grade   Branch

1234        XYZ         My appraiser is aware of all the work i am involved in.                                     Strongly Disagree   29/06/2017  L10 C   HEAD OFFICE

1234        XYZ         My appraiser tries to understand my point of view when he or she discusses problems or work  with me .              Disagree        29/06/2017  L10 C   HEAD OFFICE

1234        XYZ         My appraiser has good understanding of my strengths and weaknesses.                             Neutral         29/06/2017  L10 C   HEAD OFFICE

1234        XYZ         My appraiser gives me clear direction for the work that i am expected to do.                            Agree           29/06/2017  L10 C   HEAD OFFICE

1234        XYZ         My appraiser provides me with necessary support to resolve issues at work (team related/client related/schedule related etc).   Strongly Agree      29/06/2017  L10 C   HEAD OFFICE

alter
alter Procedure [dbo].[test]
(
@Branch nvarchar(100)
)
AS
BEGIN

SELECT        res.f_Employee_Id AS Employee_Id, emp.f_Employee_Name, q.f_Question AS Question, ISNULL(ans.f_Name, res.f_Answer) AS Answer, CONVERT(nvarchar, res.f_Created_Date, 103) AS Feedback_Date,
                     emp.f_Grade AS Grade, emp.f_Branch_DESC AS Branch
FROM            T_PAF_EmployeeResult AS res WITH (nolock) LEFT OUTER JOIN
                     t_PAF_FeedbackAns_Master AS ans WITH (nolock) ON   res.f_Answer = ans.f_Code INNER JOIN
                     t_PAF_FeedbackQues_Master AS q WITH (nolock) ON res.f_Question_Id = q.f_Uid INNER JOIN
                     T_PAF_EmployeeList_2017 AS emp WITH (nolock) ON emp.f_Employee_ID = res.f_Employee_Id

WHERE

        ((@Branch = emp.f_Branch_DESC) OR
                     (@Branch IS NULL)) and f_Company_Id=1031
        and
        (
            ans.f_Name in ('Agree','Disagree') or res.f_Answer in ('Agree','Disagree')
        )

ORDER BY Employee_Id, res.f_Question_Id
END

exec test 'Head Office'
Output is Blank
When i add this code in my procedure it is coming blank:
and
    (
        ans.f_Name in ('Agree','Disagree') or res.f_Answer in    ('Agree','Disagree')
    )

A: Try this in your condition
and
(
      ISNULL(ans.f_Name, res.f_Answer) like '%Agree%'
)


text:
Q: How to fill an array with algorythm I would like to make a test about a sudoku like table.
The first part of code can make a 7x7 table with numbers like sudoku without any normal appareance.
The second part of the code make a 7x7 table with a basic appareance.
How can i mix it together?
<?php
$n = 7; //szám

$seed_row = range(1, $n); //mettől meddig
shuffle($seed_row); //keverés

$result = array();
for($x = 0; $x < $n; $x++)
{
    $tmp_ar = array();
    $rnd_start = $seed_row[$x];
    for($y = $rnd_start; $y < ($n + $rnd_start); $y++)
    {
        if($y >= $n) $idx = $y - $n;
        else $idx = $y;
        $tmp_ar[] = $seed_row[$idx];
    }
    $result[] = $tmp_ar;
}

for($x = 0; $x < $n; $x++)
{
    echo implode(' ', $result[$x]) . "
\n";

}

//second part

echo '
';
    for ($i=0; $i < 7; $i++) {
        echo "
";
            for ($j=0; $j < 7; $j++) {
                echo "";

                echo "	";
                }
        echo "
";
    }
echo "
";
?>

A: You only need to output your array in a for loop
   <?php
    $n = 7; //szám

    $seed_row = range(1, $n); //mettől meddig
    shuffle($seed_row); //keverés

    $result = array();
    for($x = 0; $x < $n; $x++)
    {
        $tmp_ar = array();
        $rnd_start = $seed_row[$x];
        for($y = $rnd_start; $y < ($n + $rnd_start); $y++)
        {
            if($y >= $n) $idx = $y - $n;
            else $idx = $y;
            $tmp_ar[] = $seed_row[$idx];
        }
        $result[] = $tmp_ar;
    }

    //second part

    echo '
';
        for ($i=0; $i < 7; $i++) {
            echo "
";
                for ($j=0; $j < 7; $j++) {
                    echo "";
                    echo $result[$i][$j];
                    echo "	";
                    }
            echo "
";
        }
    echo "
";
    ?>


text:
Q: Copy specific cells after certain period I have a file name Sample.xlsm
I need to copy data updated on specific cells on  i.e. Sheet3 C13, D13, E13
to Sheet4 B1, C1, D1
Data need to updated every 5 min & it should be pasted on the next row i.e. B2:C2, B3:C3.

it is giving me runtime error.

A: Assuming the line with the breakpoint is throwing the error, the returned cell is likely the last cell in column B (B1048576) and you are performing an offset of one row which is out of range of the cells.  Instead try something like:
Range("B2:B" & Range("B1048576").End(xlUp).Row).Offset(1, 0).Select

This should get you on the right path but it is hard to know without seeing your data or code.


text:
Q: How to perform swipe down programmatically in android Hi I want to refresh a application by swiping down programmatically (for example Facebook app) from a service running in the background. Is it possible?

A: Not generally.  Apps can't send touch events to one another.  It can be done if its your app in the foreground receiving the gesture (although then there's easier ways to do this than faking a gesture), or it can maybe be done if you're an accessibility service (but they won't allow you on Google Play if you're using accessibility for something like this).
If its a personal app, you can checkout AccessibilityService and dispatchGesture() for a possible solution.


text:
Q: why do connections remain in pg_stat_activity after a client process has been killed? I'm debugging a "sorry, too many clients already" issue with Postgres and just learned about the pg_stat_activity table.  I noticed there are a lot of dangling idle connections in it for nonexistent PIDs, here are just two examples:
 datid |   datname    |  pid  | usesysid | usename  |            application_name             | client_addr | client_hostname | client_port |         backend_start         |          xact_start           |          query_start          |         state_change          | wait_event_type |     wait_event      | state  | backend_xid | backend_xmin |                                                                                query                                                                                |    backend_type
-------+--------------+-------+----------+----------+-----------------------------------------+-------------+-----------------+-------------+-------------------------------+-------------------------------+-------------------------------+-------------------------------+-----------------+---------------------+--------+-------------+--------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+---------------------
 32998 | clarity_test |  4700 |       10 | postgres |                                         | 172.19.0.1  |                 |       65056 | 2020-12-26 23:09:44.000108+00 |                               | 2020-12-26 23:09:47.41226+00  | 2020-12-26 23:09:47.439006+00 | Client          | ClientRead          | idle   |             |              | UPDATE "MQTTDevices" SET "numFailedPasswordsTried"=0 WHERE "id" = 6 RETURNING *                                                                                | client backend
 32998 | clarity_test |  4704 |       10 | postgres |                                         | 172.19.0.1  |                 |       65114 | 2020-12-26 23:09:45.435574+00 |                               | 2020-12-26 23:09:45.496313+00 | 2020-12-26 23:09:45.496469+00 | Client          | ClientRead          | idle   |             |              | UNLISTEN "MQTTDeviceChannels/deviceId/4"

In all likelihood I killed the test processes that created these connections with Ctrl-C.
I must fundamentally misunderstand something because I would have expected Postgres to find out that the sockets got broken, and close those connections, rolling back transactions if necessary.  As far as I read in https://dba.stackexchange.com/questions/81408/is-a-postgres-long-running-query-aborted-if-the-connection-is-lost-broken, when I terminated those processes my OS should be sending RST on the TCP sockets and Postgres should get it.
I'm running Postgres via Docker for Mac, I don't suppose that could somehow interfere with this?
I wouldn't think it should make a difference, but I'm using node-pg, some connections via pooling, others via individual client instances (e.g. for LISTEN).


text:
Q: best_in_place updated data doesn't display until page is refreshed Realize there's a question that's exactly like this, but the solution didn't help me (best_in_place gem, view not displaying updated edit without page reload).
FWIW, I'm also getting a 422 Unprocessable Entity error in the console:
Failed to load resource: <update path> the server responded with a status of 422 (Unprocessable Entity

But the edit IS going through. Database is being updated fine. It's just that until I refresh the page, I don't see the updates.
Here's my code:
def update_ri_notes
    @ri = Item.find_by_id(params[:id])
    respond_to do |format|
        @ri.update_attributes(update_ri_notes_params)
        @ri.save
        format.json { respond_with_bip(@ri) }
    end
end

<%= best_in_place ri, "admin_notes", as: :input, url: update_ri_notes_path(ri) %>

jQuery(".best_in_place").best_in_place();

Because the code is working, I won't post the routes or the update_ri_notes_params, we can assume those are correct.
My Gem versions:
ruby '2.1.2'
gem 'rails', '4.1.1'
gem 'best_in_place', '~> 3.0.1'


text:
Q: What is special about `PATH` with respect to the rest of the environment and sudo? From Command not found when using sudo

it's in fact possible to have sudo use the current
  PATH (with the env command) and/or the rest of the environment
  (with the -E option) just by invoking it right:
sudo -E env "PATH=$PATH" <command> [arguments]

In fact, one can make an alias out of it:
alias mysudo='sudo -E env "PATH=$PATH"'

(It's also possible to name the alias itself sudo, replacing the
  original sudo.)

Why is it to have sudo use the current PATH with the env command, instead of  the -E option?
Why is it to have sudo use the rest of the environment with the -E option, instead of the env command?
Is it correct that PATH is part of the environment?
What is special about PATH with respect to the rest of the environment?
Thanks.

From sudo manpage

sudo tries to be safe when executing external commands.
  To prevent command spoofing, sudo checks "." and "" (both denoting
  current directory) last when searching for a command in the user's
  PATH (if one or both are in the PATH). Note, however, that the actual
  PATH environment variable is not modified and is passed unchanged to
  the program that sudo executes.

Does it mean that the user's PATH is passed unchanged to the command which sudo executes, by "the actual PATH environment variable is not modified and is passed unchanged to the program that sudo executes"?

A: If env_reset is enabled (which it is, by default), sudo clears out the environment, and in particular provides its own PATH (see secure_path in /etc/sudoers). If env_reset is disabled, env_check and env_delete still apply, and PATH is still likely to be cleared. You can see this in action by comparing the output of
echo $PATH

and
sudo printenv PATH

If you have a customised PATH, you won't see it in the output of sudo printenv.
The env trick works around the environment clean-up:
sudo env "PATH=$PATH" command

asks sudo to run env "PATH=$PATH" command, with $PATH expanded by your shell to contain your current PATH; env, running as root, then stores the given value of PATH in its environment and runs command with that environment.
So PATH isn't special, except in the context of sudo, depending on your configuration. Any variable can be made "special" in the same way by configuring sudo appropriately, and PATH can be made "unspecial" too. See the sudo and sudoers manpages for details.


text:
Q: Slow Download Speed on Windows LocalHost I installed localhost (xammp, wampserver) on a VDS.  When I try to get a file using PHP Curl and file_get_contents, the download speed is very low. I can download a 100mb file in 10 minutes. If I try to download the same file with a browser, the duration is only 3 seconds. What can be the reason?
Thanks for your interest.

A: Downloading content at a specific URL is common practice on the internet, especially due to increased usage of web services and APIs offered by Amazon, Alexa, Digg, etc. PHP's cURL library, which often comes with default shared hosting configurations, allows web developers to complete this task.
u can try
/* gets the data from a URL */
function get_data($url) {
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}

The Usage
$returned_content = get_data('http://davidwalsh.name'); //something like  this
Alternatively, you can use the file_get_contents function remotely, but many hosts don't allow this.


text:
Q: My project keeps logging me out, Why is this happening? (CLOSED) I'm writing a code that will allow me to save my data into the database. But for some reason, whenever I type in a response, it refers to the else statement and logs me out.
Here's my code:
username = "storagei"
password = "something"

# asking for a username and password.
userInput = input("welcome back to safespace! Please type in your username to access your data.\n")

if userInput == username:
    userInput = input("Password?\n")
    if userInput == password:
       print("Welcome back to safespace Izzy!")

    else:
       print("That is the wrong password. Please try again.")
       exit(1)
else:
    print("There is no username that matches what your responce. Please try again.")
    exit(2)

print "You can open_storage, add_to_storage, or log_out"
userInput = input("What would you like to do?\n")

log_out = "Thanks for using safespace. Come back soon!"
open_storage = "opening files."
add_to_storage = "what do you like to add?"

if userInput == log_out:
   print("Thanks for using safespace. Come back soon!")
   exit(3)
   if userInput == open_storage:
      print("opening storage. Please wait...")
   if userInput == add_to_storage:
      print("what would you like to add?")
else:
    print("not a valid input. Logging you out.")

So for some reason, when it gets to this part of the code:

print "You can open_storage, add_to_storage, or log_out"
userInput = input("What would you like to do?\n")

log_out = "Thanks for using safespace. Come back soon!"
open_storage = "opening files."
add_to_storage = "what do you like to add?"

if userInput == log_out:
   print("Thanks for using safespace. Come back soon!")
   exit(3)
   if userInput == open_storage:
      print("opening storage. Please wait...")
   if userInput == add_to_storage:
      print("what would you like to add?")
else:
    print("not a valid input. Logging you out.")

I have fixed my code on my own. Here is the working script I have with all the edits if you would like to see them.
username = "storagei"
password = "something"

# asking for a username and password.
userInput = input("welcome back to safespace! Please type in your username to access your data.\n")

if userInput == username:
    userInput = input("Password?\n")
    if userInput == password:
       print("Welcome back to safespace Izzy!")

    else:
       print("That is the wrong password. Please try again.")
       exit(1)
else:
    print("There is no username that matches what your responce. Please try again.")
    exit(2)

print "You can open_storage type in o. add_to_storage type in a. log_out type in l. delete_files type in d. or edit_files type in e."
userInput = input("What would you like to do?\n")

l = "l"
o = "o"
a = "a"
d = "d"
e = "e"

if userInput == l:
   print("Thanks for using safespace. Come back soon!")
   exit(3)
if userInput == o:
      print("opening storage. Please wait...")
if userInput == a:
      print("what would you like to add?")
if userInput == d:
      print("what file do you want to delete?")
if userInput == e:
      print("what file do you want to edit?")

else:
  if userInput != l:
    if userInput != o:
      if userInput != a:
        if userInput != d:
          if userInput != e:
             print("not a valid input. Logging you out.")

A: Try this
if userInput == 'open_storage':
   print("opening storage. Please wait...")
elif userInput == 'add_to_storage':
   print("what would you like to add?")
elif userInput == 'log_out':
   print("Thanks for using safespace. Come back soon!")
   exit(3)
else:
   print("not a valid input. Logging you out.")


text:
Q: Multi-variable Expression Evaluation of two dummy variables I was given the following multi-variable function $f(x,y)=x+ (xy)^\frac{1}3$. My question is in regards to the usage of dummy variables, and direct substitution in this case.
I have to evaluate the following two:
$f(t,t^2)$
$f(x,x^2)$
My thoughts, and work is that I get the same output $2t$, and $2x$. I am currently new to multi-variable functions. So dummy variables currently apply here, as they do in singular variable mathematics? Is there anything that I should be on the look out for in regards to substitution?


text:
Q: scipy.integrate.odeint with segmentation fault I am integrating a (somewhat large --- 687378 equation) system of ODEs using scipy.integrate.odeint.
It appears to be running fine, but then I get a sudden segmentation fault.  Not much of an error message: Segmentation fault: 11.
In inspecting what is happening, I have outputed the time at each evaluation of the functions.  The step size doesn't appear to be showing anything unusual, but then suddenly it drops from a step size of about 0.08 (which had been standard in the calculation) to no apparent change in the step size.  After about 20 evaluations where it outputs the same value of time, it simply stops and I get the segmentation fault error.
It appears that the integration was correct to this point.  I'm solving a system of equations that should approximate some simulations I've done, and it does seem to be a good fit. Unfortunately, I can't really create an MCVE since I've been asked to keep the data set this is based on private, and it seems to handle other examples okay.
I'm monitoring computer memory as it runs and there's no sign of anything unusual.
Any suggestions for what might be the cause and what I can do to test it?


text:
Q: TeamCity forgotten admin password - where to look? I need to recover/reset the admin password for JetBrain's TeamCity.
I have full RDP access to the server so no problems there. It's just been 2 months since we used it so now I have forgotten my login - my usual ones don't work.
It is setup without a database at the moment, so was hoping the usernames would just be in a file somewhere, but no luck finding it so far.

A: From TeamCity 8 you can log in as a super user and change the password that way. You just need to use an empty username and last occurrence of the "super user authentication token" found in the logs\teamcity-server.log file as your password.
Please see the following for more information:

*

*TeamCity 8 - http://confluence.jetbrains.com/display/TCD8/Super+User

*TeamCity 9 - http://confluence.jetbrains.com/display/TCD9/Super+User

*TeamCity 10 - https://confluence.jetbrains.com/display/TCD10/Super+User

A: For TeamCity 6.5.4
From a command prompt in the [TeamCity install folder]\webapps\ROOT\WEB-INF\lib:
..\..\..\..\jre\bin\java -cp server.jar;common-api.jar;commons-codec-1.3.jar;util.jar;hsqldb.jar ChangePassword admin NewPassword

My username was 'admin' in my case (I think I set it during installation but I can't be sure).
I ommitted the path to TeamCity argument, it's smart enough to use the correct path (mine was c:\users\administrator.BuildServer)
When I provided the (wrong) path to TeamCity as an argument I received this message:
Using TeamCity configuration directory path: c:/TeamCity/.BuildServer
Exception in thread "main" java.sql.SQLException: Table not found in statement [UPDATE users SET PASSWORD = ? WHERE USERNAME = ? AND REALM IS NULL]
    at org.hsqldb.jdbc.Util.throwError(Util.java:58)
    at org.hsqldb.jdbc.jdbcPreparedStatement.<init>(jdbcPreparedStatement.java:1833)
    at org.hsqldb.jdbc.jdbcConnection.prepareStatement(jdbcConnection.java:580)
    at ChangePassword.main(ChangePassword.java:14)

In case this confuses other people too.

A: Super user direct URL :
http://servername:port/login.html?super=1

Open TeamCity log folder (Example C: drive: C:\TeamCity\logs) : teamcity-server.log, find the key: "Super user authentication"
[2019-03-04 12:14:30,770]   INFO -   jetbrains.buildServer.SERVER - Super user authentication token: `8347518935696887114` (use empty username with the token as the password to access the server)

A: In case none of those works, see http://sebastienlachance.com/post/Resetting-TeamCity-Password.aspx.
Open a command prompt and go to \webapps\ROOT\WEB-INF\lib folder. Now type the following :
..\..\..\..\jre\bin\java.exe -cp server.jar;common-api.jar;commons-codec-1.3.jar;util.jar;hsqldb.jar ChangePassword username newpassword

A: You could try to reset the installation of TeamCity, by removing TeamCity data directory ($/.BuildServer directory by default)

A: Try the following:
First stop the TeamCity service (would also stop the build agent if installed).
Next open up a console, go to your java directory and run the following command from there:
java.exe -cp server.jar; hsqldb.jar ChangePassword USERNAME PASSWORD "PATH_TO_YOUR_TEAMCITY_INSTALLATION".BuildServer

A: I've just had to go through this pain with v5 EAP.
I managed to reset the password successfully by running:
C:\TeamCity\webapps\ROOT\WEB-INF\lib>..\..\..\..\jre\bin\java -cp server.jar;common-api.jar;commons-codec-1.3.jar;util.jar;hsqldb.jar ChangePassword admin password c:\TeamCity\.BuildServer

Although you'll need to substitute C:\TeamCity with wherever your installation is located.

A: In case this helps someone else, whoever installed TeamCity on my server placed the build directory under the Administrator's Profile, not in C:\TeamCity.

A: Specifically for TeamCity running on Tomcat on Windows it will be C:\ProgramData\JetBrains\TeamCity
The directory specified as the last parameter needs to be your Data Directory (find in /logs/teamcity-server.log)
You'll get the 'Table not found' error if you don't have this correct.
You'll get a 'The database is already in use' error if you've got TeamCity running.
you can also search you /logs/teamcity-server.log to see whether you created admin, administrator, or some other admin user name.

A: For everyone that may arrive at this article years after the original answer like I just did, there's a built-in super user account, and the password is regenerated every time team city is started, and the password is in the log.  You can use this super user to login and reset any passwords.  It's super easy.
https://confluence.jetbrains.com/display/TCD9/Super+User

A: TeamCity always uses a database - if you haven't explicitly configured one, it uses a HSQLDB database to store data internally.
When using an external database, user information is stored within that database, so it seems pretty likely that the user information in your case will be stored within the HSQLDB system.
You might be able to gain access to the system by futzing around with the database - but I'd suggest taking a backup first.
Second suggestion - drop the support guys at JetBrains an email. Even before my workplace splashed out on a TeamCity Enterprise license, their support was superb - fast, accurate and helpful.

A: With TeamCity 5 using MySQL (probably other versions and RDBMs as well, but untested), it's possible to update the password directly via SQL:
mysql> update users set password = md5("mypass123") where username = "bob";

Nevertheless, I'd stick with the CLI versions already mentioned by others if there isn't a good reason not to do so.

A: First point is if you logout the login screen has the username 'TCAdmin' already filled in, when it should be 'administrator'.  TCAdmin is the full name of (I think) the default version 5 admin user.  Changing that to administrator and then using the password I thought it was solved my issue.
For resetting...
In case it helps someone else on Windows XP on version 5 of TeamCity, my .BuildServer config info was also under my current logged in user's documents and settings folder.  Also I was tripped up by a space in the list of jar files in Sebastien's good answer above.
So I changed to this directory in a command prompt:
 c:\teamcity\webapps\ROOT\WEB-INF\lib

and then this command line (to set password: Password1) worked for me:
C:\TeamCity\webapps\ROOT\WEB-INF\lib>..\..\..\..\jre\bin\java.exe -cp server.jar;commonapi.jar;commons-codec-1.3.jar;util.jar;hsqldb.jar ChangePassword administrator Password1

Which gave output:
Using TeamCity configuration directory path: C:/Documents and Settings/tamw/.BuildServer
Password changed successfuly

A: *

*Stop teamcity

*You should pass path to your buildserver
e.g. if you installed build server to dir "c:\.BuildServer"

........\jre\bin\java.exe -cp server.jar;common-api.jar;commons-codec-1.3.jar;util.jar;hsqldb.jar ChangePassword username newpassword c:\.BuildServer

A: To change user password:
Shutdown server
Switch to the /webapps/ROOT/WEB-INF/lib directory
Invoke the following command:
Windows platform:
java -cp server.jar;common-api.jar;commons-codec-1.3.jar;util.jar;hsqldb.jar ChangePassword
Unix platform:
java -cp server.jar:common-api.jar:commons-codec-1.3.jar:util.jar:hsqldb.jar ChangePassword
You can skip the  option, if you are using default path for TeamCity data files: /.BuildServer
[Ref:  http://confluence.jetbrains.com/display/TCD7/Changing+user+password+with+default+authentication+scheme]

A: Here's what worked for me.
Shut down server services
> cd c:\TeamCity\webapps\ROOT\WEB-INF\lib>

then
> ..\..\..\..\jre\bin\java.exe -cp server.jar ;common-api.jar;commons-codec-1.3.jar;util.jar;hsqldb.jar ChangePassword admin password1 C:\ProgramData\JetBrains\TeamCity\

Without the path at the end, it would fail with:
Exception in thread "main" java.sql.SQLException: Table not found in statement [
UPDATE users SET PASSWORD = ? WHERE USERNAME = ? AND REALM IS NULL]
        at org.hsqldb.jdbc.Util.throwError(Util.java:58)
        at org.hsqldb.jdbc.jdbcPreparedStatement.<init>(jdbcPreparedStatement.ja
va:1833)
        at org.hsqldb.jdbc.jdbcConnection.prepareStatement(jdbcConnection.java:5
80)
        at ChangePassword.main(ChangePassword.java:14)

A: We are using Teamcity 7 with MS SQL Server as the RDBMS.
To reset your password you can use the following query:
UPDATE users SET password = LOWER(SUBSTRING(sys.fn_sqlvarbasetostr(HASHBYTES('md5','your_new_password')),3,32))
 where username = "your_user_name";

A: Alternatively, You could use the TeamCity Server Log and retrieve the Super User token.
Using the token, go to the URL : http://(server):(port)/login.html?super=1
ie: http://localhost:92/login.html?super=1
Once you logged in, you could always create a new user or reset the password for the account in question.

A: I passed in the same situation and did login with super user, follow steps below:
1 - Get Token in the "teamcity-server.log" in the path "XX:\TeamCity\logs";
2 - Access and login using token at url: "/login.html?super=1";
More about it:
https://confluence.jetbrains.com/display/TCD18/Super+User


text:
Q: Install module without the original npm installation There is a module that I want to try and make some changes to, for a test.
The code is here:
https://github.com/BTMorton/angular2-grid
Right now to install this in my project I just need to type: npm install angular2-grid from my terminal.
My question is:
If I downloaded the code from github and made some changes to it,
How do I install it in my product and test it if my test changes are not on npm repo?

A: Way 1: Relative Path

*

*clone repo and edit the code, then build it.

*Use it with relative path.

Done!
import { NgGridModule } from './angular2-grid';

Way 2: npm link
cd ~/projects/angular2-grid # go into the package directory (and edit and build)
npm link                    # creates global link
cd ~/projects/myProject     # go into some other package directory.
npm link angular2-grid      # link-install the package

Way 3: npm install <git repo>
Fork and push changes to your repo and
npm install --save <your repo address>

example,
npm install --save https://github.com/YOURUSERNAME/angular2-grid

There are probably lot of other ways to deal with it. But these above will be enough for you.

A: You can install npm modules locally.
Just use npm install file:/path/to/your/repo
Alternately, you could fork the repo and then use a github link:
npm install github:yourname/angular2-grid.git


text:
Q: Dual monitor flickering: the secondary monitor does the flicker I am experiencing flickering with my dual monitor setup. The nature of the flicker is "on/off", i.e.  the screen gets completely black for a split second (sometimes a few seconds) and it goes back on. Sometimes it happens when I am not doing anything on that monitor, and sometimes it seems like it is triggered when pixels change on the monitor (opening something, or even just moving the mouse cursor)
I have a dual monitor set up at work with my MacBook Pro 13" 2017 (two thunderbolt 3 ports).
I am using the following to connect these monitors to my Mac:

*

*BenQ BL2780T monitor

*AOC I2475PXQU

*Kensingon S4600P docking station

*Belkin HDMI-USB-C adapter

The docking station connects to the MacBook via a thunderbolt 3 cable. The AOC monitor is connected directly to the docking with DisplayPort. The BenQ is then connected to the remaining Thunderbolt 3 port on my Mac via a HDMI-USB-C adapter. The docking station provides power to the Mac.
It seems random which monitor flickers; sometime it is the BenQ, other times it is the AOC. Also, it is random which port is involved in the flicker. However, I only see flickering when two monitors are connected at once.
I have also used a Satechi slim multiport (as a very simple docking station), and I see the same flickering behavior. I have tried different cables, and the issue persists.
I have also tried another AOC (same model) monitor together with the BenQ, and it still flickers.
I am going to try another MacBook Pro (same model) this week, and will report back.
Is this a software issue with High Sierra? Are the two monitors "incompatible" for some reason? I see no reason why the flickering happens. I really hope someone can help me out. It seems similar issues are common, but I have not yet found a common explanation to fix these things. Needless to say, I have tried the standard things, like various resets etc.

A: Rebooting my MacBook with both monitors plugged in actually fixed the second monitor flickering issue. Yay.

A: Sounds to me like it might be an SMC issue - at least that's one of the first things I would try - reset the SMC.
Easy enough to do...
https://support.apple.com/en-us/HT201295

A: Had this issue once - the solution is to make sure that all the monitors are set to the same refresh rate (Display Settings -> Advanced Display Settings).
In my case, I had 2 identical HD external monitors with the same refresh rate but not compatible with my laptop's which I was extending. I made sure both monitors were set to the same refresh rate and turned off the third (laptop's) monitor in the display settings.


text:
Q: Index Metadata in a Numeric Field I was trying to index some metadata in a numeric field of lucene.net but I don't know how to do it. I built a class to find measures on descriptions, that class returns a list of measures in these form: "150{inch} 200{mm}" etc. And I want to index these values to search for them simultaneously, numeric value and the measure unit. How can I do that? I need to create a custom field?
Thank you.

A: A couple of ideas (from the Lucene.Net mailing list)

*

*Store all units of measure converted to a common unit. If user input is feet, or meters, or inches, convert that to your common unit and then search

*Store a separate field for the unit type and the measure. Then you can do a search like unit:mm AND measure:100 or unit:feet AND measure:[4 to 7]