text:
Q: Progress dialog not displaying I had a progress dialog which was working before kitkat now it does not display the dialog.
If i put a debug and stop the program in post execute before the dialog dismiss it show the dialog , which woul imply that the code is working too fast to display the dialog , but this is not true it takes a good time after the dailog dismiss to show the grid view?
Another strange thing , when it did work it displayed the dialog but the circle did not turn or animate.
Any comments gratefully recieved
        private class LoadPhoto extends AsyncTask<String, Void, MyPhoneImagesAdapter> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // initialize the dialog
            String searchingString = getResources().getString(R.string.searchingString);
            String searchMsgString = getResources().getString(R.string.searchMsgString);
            m_dialog.setTitle("Searching...");
            m_dialog.setMessage("Please wait while loading client photos...");
            m_dialog.setIndeterminate(true);
            m_dialog.setCancelable(true);
            m_dialog.show();
        }

        @Override
        protected MyPhoneImagesAdapter doInBackground(String... params) {
            // TODO Auto-generated method stub
        // Execution code
            // Note we can call a method in the main class but we are running it in
            // the asynchronous thread
            getPhotos();
            return getPhotos();
        }

        @Override
        protected void onPostExecute(MyPhoneImagesAdapter result) {
            super.onPostExecute(result);
// Note we can update the UI from the post execute method only note we pass the adapter which
// we created in the do in background
            GridView grid = (GridView) getView().findViewById(R.id.photoGrid);
              grid.setAdapter(result);
               // See: ImageAdapter.java
              grid.setOnItemClickListener(new OnItemClickListener() {
                  public void onItemClick(AdapterView<?> parent, View v,
                          int position, long id) {
                      String tst = "Pick";
                      String sel = path+"/"+clientPhotos[position];
                      listener.onImageSelected(sel);
                      }
              });
            m_dialog.dismiss();
        }

A: Try initializing ProgressDialog inside the class LoadPhoto
Declare ProgressDialog mProgressDialog; in LoadPhoto
And use the static method of ProgressDialog show() as,
mProgressDialog = ProgressDialog.show(MainActivity.this, "Searching...", "Please wait while loading client photos...", true, true);

A: The reason this happens is because the processor does not have time to update the UI, so you have to do this manually in loop.
I'm not a android developer, but in java, back in the days i would normally use the repaint(); function.
In c# these simple functions help to update the contorls,
textbox1.Invalidate();
textbox1.Update();
textbox1.Refresh();

I beleive java may have similar functions.


text:
Q: Qual a melhor maneira de verificar se uma string tem alguma dessas palavras? Tenho uma dúvida, considerem o seguinte:
nomes_proibidos = ['Corona', 'Clorivaldo', 'Pfizernaldo', 'Hulk', 'Naruto', 'Goku', 'Cloroquina']

def verificar_nome(n):
    for nome in nomes_proibidos:
        if n.find(nome) != -1:
            return False

    return True

verificar_nome('Pedro Hulk da Silva')

Existe uma melhor maneira de fazer isso? Estou precisando fazer algo semelhante, só que com uma lista de palavras muito maior e estou preocupado com o desempenho.

A: Uma alternativa é usar split para quebrar a string em palavras, e ver se cada uma das palavras está na lista:
def verificar_nome(frase):
    for palavra in frase.split():
        if palavra in nomes_proibidos:
            return False
    return True

Esta solução é "ingênua" porque qualquer frase um pouco mais complicada já quebra o algoritmo. Por exemplo, se a frase for Oi, tudo bem?, as "palavras" serão Oi, (com a vírgula), tudo e bem? (com a interrogação), então se "Oi" estivesse na lista de palavras proibidas, ela não seria encontrada.
Então no fundo, precisamos definir bem o que é uma "palavra", conforme já discutido aqui, aqui e aqui.
Se quer só considerar os casos simples (palavras estão sempre separadas por espaço, não há pontuação, etc) então a solução acima resolveria. Usar find pode acabar pegando trechos dentro de uma palavra (por exemplo, se a palavra proibida é "viado", usando find você bloquearia "enviado", o que não é o desejado).

Na verdade filtros de palavras são um problema antigo e até hoje não está muito bem resolvido. Mas enfim...

Nos links já citados acima (esse, esse e esse) você vai ver outras formas de quebrar uma frase em palavras, usando diferentes definições. Escolha a sua e troque o split do código acima pela opção de sua preferência.

Se quiser desconsiderar a diferença entre letras maiúsculas e minúsculas, você pode usar casefold para normalizar as palavras:
nomes_proibidos = list(map(str.casefold, ['Corona', 'Clorivaldo', 'Pfizernaldo', 'Hulk', 'Naruto', 'Goku', 'Cloroquina']))

def verificar_nome(frase):
    for palavra in frase.split():
        if palavra.casefold() in nomes_proibidos:
            return False
    return True

Claro que para casos mais simples, usar lower ou upper também funcionaria, mas a documentação diz que casefold é mais "agressivo" e trata casos excepcionais como o caractere alemão ß, cuja versão maiúscula é "SS" (ou seja, para textos em português, lower ou upper seria o suficiente).

E por fim, em vez de uma lista de palavras, pode trocar para um set, já que operações de busca nesta estrutura são mais rápidas do que em uma lista:
# usar um set em vez de lista
nomes_proibidos = set(map(str.casefold, ['Corona', 'Clorivaldo', 'Pfizernaldo', 'Hulk', 'Naruto', 'Goku', 'Cloroquina']))

Claro que para poucos nomes, a diferença será imperceptível. Então teste para confirmar (mas a princípio, deve ser mais rápido que uma lista).
Fazendo um teste rápido com o módulo timeit:
from timeit import timeit

set_nomes_proibidos = set(map(str.casefold, ['Corona', 'Clorivaldo', 'Pfizernaldo', 'Hulk', 'Naruto', 'Goku', 'Cloroquina']))
list_nomes_proibidos = list(map(str.casefold, ['Corona', 'Clorivaldo', 'Pfizernaldo', 'Hulk', 'Naruto', 'Goku', 'Cloroquina']))

def verificar_nome_set(frase):
    for palavra in frase.split():
        if palavra.casefold() in set_nomes_proibidos:
            return False
    return True

def verificar_nome_list(frase):
    for palavra in frase.split():
        if palavra.casefold() in list_nomes_proibidos:
            return False
    return True

# frase com mil palavras, e com a palavra proibida no final
frase = ('abc ' * 1000) + 'Pedro Hulk da Silva'

# executa 10 mil vezes cada teste
params = { 'number' : 10000, 'globals': globals() }
# imprime os tempos em segundos
print(timeit('verificar_nome_set(frase)', **params))
print(timeit('verificar_nome_list(frase)', **params))

Na minha máquina, a solução com set foi ligeiramente mais rápida (cerca de 0,3 segundos em média), mas isso pode variar de acordo com o hardware, as frases e a lista de palavras proibidas, então cabe a você testar para os seus casos reais e ver se faz diferença.

redpajama_set_name: RedPajamaStackExchange


text:
Q: "Git for Windows has stopped working" on Windws 7 My git suddenly failed on me. And it didn't just fail on one repo. It failed on ALL repo. It was working one minute, then after that it started to fail. When I git pull it shows "Git for Windows has stopped working" a couple of times.
And then it aborted the pull.
We have tried completely uninstalling and reinstalling git.
We have also deleted the .gitconfig file at the user folder.
We have also tried deleting the repository and then redownloading the file from bitbucket.
We have also tried system restore to no avail.
git fsck didn't work.
I am using a windows 7 for this thing. Heads-up, I have tried searching for a precedent for this problem, but I didn't see anything that matched with mine.
EDIT:
My git fails on all repos, even on newly made ones.
When I try git pull it gives me 2 "Git for Windows has stopped working" alerts and shows this on the console:
$ git pull
Cannot chdir to C:/xampp/htdocs/myProj, the toplevel of the working tree
git version is 1.8.4

A: This is usually due to an external application recently installed or updated, and which interact badly with msysgit.
See for instance this answer about an anti-virus.
Check the windows event viewer to see the full error message.


text:
Q: php code smell detector Regarding the php code smell detector at http://c2.com/cgi/wiki?DetectingCodeSmellsInPhp
When I open it in my web browser, I get an error, but when I open it in my IDE, I don't.
How to correct it?

A: Detecting a definitive code smell with code will possible the same day the halting problem will be fixed. *takes off joke hat*
What he is just doing is setting some parameters on what he thinks is bad code. And it's wrong (imo)
Having equal or more than 4 parameters is a code smell? He himself has that in the code smell detector!
More than 20 lines for a function is a code smell? The main function in this code smell detector is 49 lines of code!!
Code smell is not a thing you can program, in some cases the best way to do some function is the non standard way (whatever that way is) and in other cases it is not. You just have to trust your instinct and do as Frank Farmer said in the comments above. Just take a good wiff.

A: if you want a code sniffer, use Pears PHP_CodeSniffer. it lets you define your own rules, your own set of rules, etc.

PHP_CodeSniffer is a PHP5 script that tokenises and "sniffs" PHP, JavaScript and CSS files to detect violations of a defined coding standard. It is an essential development tool that ensures your code remains clean and consistent. It can also help prevent some common semantic errors made by developers.
A coding standard in PHP_CodeSniffer is a collection of sniff files. Each sniff file checks one part of the coding standard only.

it's fun to use (try writing a single function that adheres to the PEAR standards) and forces at least some consistency in the codebase.
it doesn't guarantee code quality, but it may help


text:
Q: What is the difference between a probability measure and a probability density function? During my research, I have repeatedly come across the terms probability measure and probability density function (pdf). I am familiar with the concept of a pdf, but I am not entirely sure how probability measures relate to pdfs, or where exactly the differences lie in theoretical terms. I have since combed StackExchange (such as this and this question), and visited the Wikipedia article for probability measures, but I still cannot see the difference, so I imagine I must be missing a nuance.
Hence my question: Could you check my understanding, and - if necessary - correct it?
To provide an example for context, let us consider the continuous-valued example of human body height. Let us denote the height of a person in meters as a random variable $X$, which maps a person's physical height to a corresponding real value $x$. In that case:

*

*we could define a probability density function $p(x)$ over all theoretically possible heights $x$. The pdf must be non-negative for all $x$, i.e. $p(x)\geq0 \; \forall \; x$, and it must integrate to $1$, i.e. $\int_{-\infty}^{\infty} p(x) dx=1$. We can integrate $p(x)$ over subintervals to learn the probability that a person's height is in this interval.

*the definition of a probability measure seems related. Let us denote the set of all possible body heights $x$ as $S_1$. Based on this set, we design another set $S_2$ which contains $S_1$ and all possible subsets of $S_1$. The probability measure then assigns values between $0$ and $1$ to each entry in $S_2$, with the condition that the entry $\{\text{all }S_1\}$ in $S_2$ is assigned $1$, $\{\}$ is assigned $0$, and certain additivity properties are met (see the image below, taken from Wikiedpa)

Concerning my understanding of the difference: A pdf $p(x)$ can assign values $\geq1$ to $x$, as it describes a density and only requires that the integral over all $x$ be equal to $1$. The limitation of probability measures to values below $1$ would probably correspond to a role more similar to integrating (vanishingly small) sub-intervals of $p(x)$. Is this the distinction between pdfs and probability measures? Why is this distinction important? Am I missing or misunderstanding something?

A: A probability density function induces a probability measure with Reimann-Stiljes integration, but the space of probability measures is bigger. Take, as an example, the Cantor distribution which has no probability density function, but whose distribution function, the Cantor function, meets criteria of a probability measure, (i.e. it is cadlag, tends to 0 as $x \rightarrow -\infty$ and tends to 1 as $x \rightarrow \infty$). The Cantor function is an intuitive and elementary example in measure theory of a function that is continuous measurably everywhere, has derivative of 0 measurably everywhere, but is not constant.


text:
Q: Sqlalchemy mock return value with join table If I want to mock a return value of sqlalchemy table Assignment, I'll do the following way.
def get_all_assignments():
    return db.session.query(Assignment).all()

@patch('get_all_assignments')
def test_get_all_assignments(get_all_assignments_mock):
    get_all_assignments_mock.return_value = [
        Assignment(id=1)
    ]

    assignments = get_all_assignments()
    assert len(assignments) == 1
    assert assignments[0].id == 1

How to mock if the function involved with another table? EX:
def get_all_assignments_with_teacher():
    return db.session.query(Assignment, Teacher).join(Assignment.teacher).all()

A: Since no one answered, I'll just share my solution.
We can utilize magicmock to do the trick.
@patch('get_all_assignments_with_teacher')
def test_get_all_assignments_with_teacher(get_all_assignments_with_teacher_mock):
    mock = MagicMock
    mock.Assignment = Assignment(id=1)
    mock.Teacher = Teacher(id=1)
    get_all_assignments_with_teacher_mock = [mock]


text:
Q: Inconsistency with Running Macros Copy/Paste When I exclusively run the Sub "EmailAbertura" (below) I get the desired result. However, when I run it within a list of other subs it copy and pastes a number that isn't even on the sheet. Why would that be occuring?  Thanks!
Sub EmailAbertura()
Dim Email As Workbook
Dim Sheet As Worksheet
Dim LCA As Workbook
Dim Lastro As Worksheet

Set Email = Workbooks("Email")
Set Sheet = Email.Sheets("Sheet1")
Set LCA = Workbooks("Controle de Lastro LCA_FEC - Test")
Set Lastro = LCA.Sheets("Controle Lastro")

Lastro.Range("B7").Copy
Sheet.Range("F2").PasteSpecial
End Sub

But When I include it in this macro, it doesn't work.
Sub DoLCA() 'fazer todos de LCA para fechamento e abertura'
AddEmLCA
MenosResLCA
LCAHist
SalvarLCA
EmailDadosLCA
MudaDataLCA
DeleteDateLCA
EmailAbertura
SalvarLCA_aber
Fechar
End Sub

A: Is it possible that two (or more) macros are using Copy/Paste to perform their duties? Perhaps a second "Copy" is being performed before the corresponding "Paste" is executed. So, in other words, you did a second copy before you got to perform your first paste.


text:
Q: Submit Html Templates to Database I have a drag and drop module which is used to create html templates. I mean drag and drop html text, header, footer etc. I have many layouts like two column, three column etc. in which these html elements can be dropped. What I want is the following .

To determine which element (header,footer,text etc.) is in the columns
  in a 2 column or 3 column structure

Is there any way to save these?

A: This question was a duplicate of this. I am not deleting this because someone could find this in their search. Here is the answer to the question


text:
Q: Do all shards (within index) have the same content? Do all shards (within index) have the same content?
If yes, more shards = longer propagation (save) time?
If no, when one of shards failed = data is incomplete when merging?

A: First, you need to understand what is sharding and why it's important in distributed systems like elasticsearch. You can read some good resources on shards here here and here.
Now Coming to your question,

Do all shards (within index) have the same content.

The answer, is no (assuming you are referring to primary shards here, of course, replica shard is just a copy of primary shard), let's take an example.
Your Index contains around 100 million docs and you have a 10 data nodes cluster, then you want to horizontally scale your index, so you started with the setting of 10 primary shards and 1 replica shards. In this case, elasticsearch will physically divide your data into 10 primary shards and each primary shard will be on a different node of a cluster as there are 10 data nodes and similarly every primary shards copy which is called replica of a shard which is on a different node of its primary shard.
Now coming to your follow-up question.

If yes, more shards = longer propagation (save) time? If no, when one
  of shards failed = data is incomplete when merging?

As elasticsearch doesn't store the same data in all the primary shards, so more shards mean longer propagation or save time is invalid and also when one of the shards is failed then elasticsearch recover its data from its replica shard as it's present physically on a different data node server.
Bonus tip:- Shards are used to split your data and to make your application horizontal scalable, while the replica is to make your application is highly available as it contains the duplicated data, so the application can recover easily from the scenario you just asked in your follow-up question.
Let me know if you need any clarification or more details.

A: short answer:
Q-1: no
if-no: if index has not a replica, it affects the whole index but not other shards of the index .
please read this document:
https://www.elastic.co/guide/en/elasticsearch/reference/6.2/_basic_concepts.html


text:
Q: class not registered I am installing an application on a client machine.  The application is throwing an exception that I am logging that states "Class Not Registered".  This an app written in Visual Studio 2005 using VB.NET.  The dll dependencies of my .exe are located in the same folder as the .exe.  What class is this talking about and how can I resolve this issue?

A: Does the application use any COM components? If so, make sure that they get registered properly on the client machine. You can either have the setup do this for you (if you have created a setup), or use the regsvr32 utility.
Based on the comments, I would say that you will need to install SQL Server on the client machine. I am no SQL Server expert, but I would guess it would be sufficient with the Client Components.

A: Try commenting out most/all of the code in the project (or create a hello,world setup) to isolate whether it's one of your 4 dependencies or something else entirely.


text:
Q: Maximum Likelihood estimator and one application for real life I am studying maximum likelihood estimators (MLE) right now. I am trying to do a little article about how to apply maximum likelihood estimators to one real life problem.
But I see that MLE mostly is about to "prove" estimators to known distributions.
In some universities exams I see that professors give you a probability density function that is very... mmm..."exotic", and you figure out its parameters by MLE, but I'm not sure that those PDFs work in real life.
Am I wrong in my apprehension?
Are there some real applications of MLE in real life for me to write my article about?


text:
Q: Magento admin menu with file upload I have developed a website in magento version 1.9.2, i have lot of products in excel, so I want to upload this file in magento admin, for that how to create menu and upload file in magento back end, I have just googled and founded some solutions but none of them working.
I am new in magento.

A: To upload product in magento admin no need to create menu, Magento already give a tab
system -> import/export -> import

or
 system -> import/export -> Dataflow - profiles

Here you will able to upload bulk products using CSV

A: If you want to import all products to your website,just follow the following instructions.

*

*First of all, create all categories and create one product in your website,

*After this, export that data and keep that with you.

*Now arrange the data which you want to import, that total have to be arrange in the format of your exported data.

*After arranged you can easily import the data into your website which you want to import newly in usual manner.

*Then go to system-->import/Export-->Data flows-->Follow that rules...


text:
Q: When I open a custom UIView from a UITableViewController, how do I close the custom view and go back to the table view? I'm using a UITableViewController for a menu in a game. The table view opens a a view controller for my custom UIView that shows the game. When the game finishes the UIView is notified (which is kinda ruining the MVC principals) and from there I am kinda lost.
Questions:

*

*Can a UIView communicate with its controller? How?

*Can one controller talk to the one that started it? How?

*How do I transition between all of this complicated web of views and controllers gracefully?

A: *

*Use a delegate protocol here.  Your custom game UIView can use a delegate property and call methods on this delegate when events happen (game over, game paused, view closed, etc).  Here's a great post on using delegates: How do I create delegates in Objective-C?

*I'd recommend using a UINavigationController.  You don't necessarily need to show the navigation bar, but if you nest your view controllers in a navigation controller you have access to -pushViewControllerAnimated: and -popViewControllerAnimated: which make it really easy to navigation between levels of nested view controllers.

*Another benefit of UINavigationController - you'll get a nice slide animation when you switch between views.
There are other 3rd party mechanisms out there that you may prefer over the UIKit UINavigationController/UIViewController mechanisms.  Check out the Three20 project, in particular the TTNavigationCenter class.


text:
Q: PYPY and how to install with out interfering default python 2.7 install on ubuntu How does one install packages via easy_install? I don't want to use virtual environments.
One would think I can do this
easy_install --prefix=/opt/pypy/site-packages pytz

But I get the below:
easy_install --prefix=/opt/pypy/site-packages pytz
TEST FAILED: /opt/pypy/site-packages/lib/python2.7/site-packages does NOT support .pth files
error: bad install directory or PYTHONPATH

You are attempting to install a package to a directory that is not
on PYTHONPATH and which Python does not read ".pth" files from.  The
installation directory you specified (via --install-dir, --prefix, or
the distutils default setting) was:

    /opt/pypy/site-packages/lib/python2.7/site-packages

and your PYTHONPATH environment variable currently contains:

    ':/fu/classes'

Here are some of your options for correcting the problem:

* You can choose a different installation directory, i.e., one that is
  on PYTHONPATH or supports .pth files

* You can add the installation directory to the PYTHONPATH environment
  variable.  (It must then also be on PYTHONPATH whenever you run
  Python and want to use the package(s) you are installing.)

* You can set up the installation directory to support ".pth" files by
  using one of the approaches described here:

  https://pythonhosted.org/setuptools/easy_install.html#custom-installation-locations

Please make the appropriate changes for your system and try again.


text:
Q: SQL - Return fields ONLY containing met requirement I am trying to do the following:
Assign a Y/N flag as Prior Approval which includes all policies that are policies with BI limit 25/50 and PD limit 25 and no other coverage.
So this code satisfies the first requirements:
SELECT DISTINCT
        PolNum
FROM    Results_Vehicle
WHERE   ( CovCode = 'BI'
          AND CovLimit = '25/50'
        )
        OR ( CovCode = 'PD'
             AND CovLimit = '25'
           )

I can't figure out how to not include records that have other coverage.  So basically for each policy they can have CovCodes of UMBI, COL, REN, BI, PD, etc.  But the flag should only give a Y if for that PolNum they ONLY have BI or PD as CovCode and the CovLimit defined above.
So also I'll need to put it in the Y/N format as follows, obviously this only satisfies the first part of the requirement:
SELECT  CASE WHEN ( CovCode = 'BI'
                    AND CovLimit = '25/50'
                  )
                  OR ( CovCode = 'PD'
                       AND CovLimit = '25'
                     ) THEN 'Y'
             ELSE 'N'
        END AS PriorApproval
FROM    Results_Vehicle

A: How about this query below. The union query gives you a combined list of all the PolNum's that have that type of coverage, so then you do a not in to give you all the policy numbers that AREN'T in that list, and then you do a not in on that list, which should leave you with the PolNum's that only have the desired coverage and no other coverage.
SELECT CASE WHEN
(
 (CovCode = 'BI' AND CovLimit = '25/50')
 OR
 (CovCode = 'PD' AND CovLimit = '25')
 and PolNum not in
 (
  select PolNum from Results_Vehicle as r1 where PolNum not in
    (
     select PolNum from Results_Vehicle as r2
     where CovCode = 'BI' and CovLimit = '25/50'
     union
     select PolNum from Results_Vehicle as r3
     where CovCode = 'PD' AND CovLimit = '25'
    )
 )
) THEN 'Y'
ELSE 'N'
END AS PriorApproval

FROM Results_Vehicle


text:
Q: Create and Plot spatial objects in R with lat, long & azimuth Looking for some help..
I am trying to create and plot spatial objects in R based on lat, long & azimuth. Azimuth is the angle separation at a given lat, long. Expected output as shown in below image where the objects are filled with blue color:

Input data:
df <- data.frame(Latitude = c(32.897, 32.897, 32.897, 32.811, 32.811, 32.811),
                 Longitude = c(-97.04, -97.04, -97.04, -97.12, -97.12, -97.12),
                 Azimuth = c(0, 120, 240, 60, 200, 240),
                 Site = c("A", "A", "A", "B", "B", "B"),
                 Sector = c(1,2,3,1,2,3),
                 stringsAsFactors = F)

A: #Convert df into a spatial object:
library(sp)
coordinates(df)<-~Longitude+Latitude

#Simple plot:
plot(df, col="Blue")

#Plot with icons:
plot(df, col="Blue", pch=24)
plot(df, col="Blue", pch=25, add=TRUE)

#Plot on a map: (You need the associated projection)
proj4string(df) = CRS("+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0")

library(mapview)
mapview(df)


text:
Q: How to retrieve a nested object? I have a collection with documents like this:
{
    key : "bla"
    list : [
       {id:1},
       {id:2}
    ]
}

How do I get this object: {id:1} ?
I tried a query like this: db.myCollection.find({"key":"bla", "list.id":1})
it finds the entry, but returns the complete document instead of only {id:1}

A: The $ operator is what you're looking for:
db.test.insert({key: "blah",list :[{id:1},{id:2}]})

db.test.find({'list.id' : 1},{'list.$': 1 })
#Returns:
#{ "_id" : ObjectId("521a78b342abf388fbaacf91"), "list" : [ { "id" : 1 } ] }

db.test.find({'list.id' : 2},{'list.$': 1 })
#Returns:
#{ "_id" : ObjectId("521a78b342abf388fbaacf91"), "list" : [ { "id" : 2 } ] }

If you don't need the _id of the document, you can exclude that too:
db.test.find({'list.id' : 2},{'list.$': 1 , _id: 0})
#Returns:
#{ "list" : [ { "id" : 2 } ] }

For more information, have a look at the documentation of the $ operator and read operations in general.


text:
Q: dismiss a view from class extended by InputMethodService I am created a custom keyboard. The keyboard is NOT an extension of the Keyboard class and does not use the Keyboard View class either. I have successfully created my keyboard so that it popups up. The keyboard is a LinearLayout I created from an xml file. Here is the problem: I can't get rid of it.
If it was an extension of KeyboardView, I would use
keyboard.closing();

but since its a LinearLayout, I don't have that method.
I then tried
keyboard.removeView(keyboard);

I didn't expect this to work, and it didn't.
Finally, I tried
keyboard.removeAllViews();

in hopes that it would sort of leave keyboard on the screen, but no one would no if all the views were removed. This did not work either.
Any suggestions?

A: Well if keyboard is the View you want to hide, try calling keyboard.setVisibility(View.GONE). If you want to remove it entirely you would have to find the parent view of keyboard and call removeView(keyboard) on that. I think the first approach is simpler though, depending on what you want.


text:
Q: $ Command not found with "rails new app -m myfile.rb" I'm trying to use the MongoID-Devise generator template by doing this under Ubuntu and using RVM:
rails new myapp -m https://github.com/RailsApps/rails3-application-templates/raw/master/rails3-mongoid-devise-template.rb

I've also tried to download the file and do the generation locally, but in both cases, I get:
$: command not found

As according to the guides: Application Template, I'm using the command/options correctly...
EDIT:
The following commands gives me the following results:
rails -v --> Rails 3.1.3
ruby -v --> ruby 1.9.2p290 (2011-07-09 revision 32553) [x86_64-linux]

A: The "$" you see at the beginning of the command is actually a convention that indicates a Unix console prompt. Don't include the "$".


text:
Q: Не работает код C++ в VS 2010, а в VS 2008 пашет! В чём причина? Поможете? Здравствуйте!
Прохожу обучение по C++. У учителя на мониторе код в VS 2008 работает, у меня в VS 2010 не работает. Проверял, всё написано правильно(т.е. как у учителя).
Сам код(разбита на 3 файла):
//Определение класса Point
#ifndef POINT_H
#define POINT_H

class Point
{
private:
    int x, y;
public:
    int GetX() {return x;} //inline по умолчанию
    int GetY();
    void SetX(int);
    void SetY(int);

};

inline int Point::GetY() { return y; }

#endif

2 файл:
//Реализация класса Point

#include"Point.h"

void SetX(int _x)
{
     x = _x >= 0 ? _x : 0;

}

void SetY(int _y)
{

    y = _y >= 0 ? _y : 0;

}

3 файл:
//Использованиие класса Point (клиентский код)
#include<iostream>

#include"Point.h"

using namespace std;

int main()
{
    Point a;
    a.SetX(10);
    a.SetY(20);

    cout << a.GetX() << ", " << a.GetY() << endl;

    system("pause");
}

Код ошибки отладчика VS 2010:
1>------ Построение начато: проект: Point, Конфигурация: Debug Win32 ------
1>Построение начато 21.01.2012 21:14:51.
1>InitializeBuildStatus:
1>  Обращение к "Debug\Point.unsuccessfulbuild".
1>ClCompile:
1>  usePoint.cpp
1>  Point.cpp
1>c:\users\vladislav\documents\visual studio 2010\projects\point\point.cpp(9): error C2065: x: необъявленный идентификатор
1>c:\users\vladislav\documents\visual studio 2010\projects\point\point.cpp(16): error C2065: y: необъявленный идентификатор
1>  Создание кода...
1>
1>СБОЙ построения.
1>
1>Затраченное время: 00:00:00.55
========== Построение: успешно: 0, с ошибками: 1, без изменений: 0, пропущено: 0 ==========

Что может являться причиной? Проект консольный(пустой).
Благодарен за помощь. Спасибо.
A: В файле "point.cpp" вместо
void SetX(int _x)

нужно написать
void Point::SetX(int _x)

Тоже самое с игреком.
Такой код не должен был компилироваться. Вы что-то упустили при переписывании.


text:
Q: jQuery Drag and Drop inbetween two li elements I am developing a Tree view and using JQuery Draggable and Droppable plugins to implement Drag and Drop the tree nodes.

I can drag a folder and drop over another and get the dropped element in "drop" event handler. In my drop event handler I will rearrange my nodes.
HTML Code:

Folder1

Folder11

Folder2

Folder3

Folder4

Folder5

JS Code:
$( ".draga" ).draggable({
    cursor: "pointer",
    cursorAt: { top: 12, left: 18 },
    helper: function( event ) {
        var temp_name = event.target.innerHTML;
        return $( "
"+temp_name+"
" );
    }
});

$( ".draga" ).droppable({
    drop: function( event, ui ) {
        // On dropping on a node will handle here to rearrange the node.
    },
});

Now I also need to drag a node and drop in between two nodes. Like need to drag "Folder5" and drop in between "Folder2" and "Folder3".
I also need to show a helper to drop in between two nodes when the dragged hover is in between the nodes.
JSBIN - Link


text:
Q: How to reflect http method to keycloak resource when using ambassador filter I'm trying to integrate the ambassador and keycloak, so all my microservices behind the ambassador could be protected by keycloak.
Now I can implement an easy case, by setting the filter + filter policy, say my resource: GET /products/:productId , if the user want to visit this page, ambassador will intercept it and redirect to keycloak login page, the filter policy settings look like:
apiVersion: getambassador.io/v2
kind: FilterPolicy
metadata:
  name: keycloak-filter-policy
  namespace: ambassador
spec:
  rules:
    - host: "*"
      path: /product/:productId
      filters:
        - name: keycloak-filter
          namespace: ambassador
          arguments:
            scopes:

My question is, how could I define policy like: POST /product/:productId ? On Keycloak, I have resource + policies such as: product:view product:edit how can I translate these resources to Ambassador's filter policies?

A: To directly answer your question, currently, you cannot add the HTTP method to the FilterPolicy. There is a workaround if you need to define more granular access control based on what you are trying to do with the resource.
For example, if you are using HTTP2 or HTTP3 you can get the method from the request headers. There is a pseudo-header called :method
Link for HTTP spec: https://httpwg.org/specs/rfc7540.html#HttpRequest
Link for Ambassador's Filters Doc: https://www.getambassador.io/docs/edge-stack/latest/topics/using/filters/


text:
Q: Is it possible to cover all circle area with infinite lines starting from the center? Is it possible to cover all area of a circle of radius r>0 with infinite lines starting from the center?

A: Yes, it is (assuming you mean "start from the center", and you mean "infinitely many lines"). For each point on the circle, take the line going through the origin and that point. Any point in the disc lies on one of these lines, so their union covers the entire disc (and in fact the entire plane).

A: Every point in the disk is on some radius, so the union of all the radii covers the disk.

There are infinitely many radii, and all are needed to complete the cover.

But note -- the set of radii is an uncountable set. In other words, you can't list them as a sequence.


text:
Q: highcharts crosshairs wont work been trying to enable crosshairs on highcharts.... on jsfindle the example works fine, but when i put it into my web page it just won't work, can you please check the code?
Thanks

The result i get is the chart with the line, but on mouseover the crosshair doesn't show.
Thanks

A: It's not clear to me: is this the entire code of your page, or have you extracted doctype, html, head, and body tags for the sake of simplicity?
Do the crosshairs work for you in this jsbin example? They do for me.
http://jsbin.com/aworob/edit#javascript,html,live
Also, it may be to your advantage and your end users
to place your javascript src tags and your inline script at the bottom of the page, just above the closing  tag. If you did this, remove the $(document).ready(function() { wrapper. Read more at: http://developer.yahoo.com/performance/rules.html#js_bottom


text:
Q: JMeter response throwing "File Name is Invalid / Already Exists" on uploading Blazemeter Recording File I'm using Apache Jmeter version 5.3. And i am using Blazemeter for recording the "File Upload" request and for which Jmeter is throwing "File Name is Invalid / Already Exists". But the file i am trying to achieve upload has a new name which doesn't previously exist. Application is running on Azure server.
PS: I tried the file upload manually with the same filename and the upload was successful (Tried this after jmeter failed to achieve it)

A: We cannot suggest anything without seeing your test plan (or at least request) and knowing what is the contract for the file upload endpoint
So I can provide only a generic piece of advice: just compare the network request(s) associated with the file upload coming from the real browser and JMeter, identify the differences and amend your JMeter configuration so it would send the same request as the real browser does (apart from the dynamic file name and other dynamic parameters which need to be correlated). The comparison can be performed using a 3rd-party sniffer tool like Fiddler or Wireshark
You can also try using JMeter's HTTP(S) Test Script Recorder for recording your file upload event, just make sure to have the file you're uploading in JMeter's bin folder, this way JMeter will be able to generate proper HTTP Request sampler and HTTP Header Manager. See Recording File Uploads with JMeter article for more details.


text:
Q: Set Column Alias From Current Select ( MariaDB / MySQL ) My Original Data  :
id   | GRP_ID | VAL_1  | VAL_2   | VAL_3  |  TYPE
---------------------------------------------------
1    |   R2   |  B01   |         |        | COL_B
2    |   R2   |        |   A01   |        | COL_A
3    |   R3   |  B02   |         |        | COL_B
4    |   R1   |        |   C01   |        | COL_C
5    |   R2   |  C02   |         |        | COL_C
6    |   R3   |        |         |   C03  | COL_C

Then i modified like this :
-----------------------------------------
GRP_ID  | group_CONCAT1      | group_CONCAT2
-------------------------------------------
 R1     |  COL_C             | C01
 R2     |  COL_A,COL_B,COL_C | A01,B01,C02
 R3     |  COL_B,COL_C       | B02,C03

And i want get result like this :
GRP_ID  |COL_A  |  COL_B   | COL_C
----------------------------------
 R1     | ---   |   ---    | C01
 R2     | A01   |   B01    | C02
 R3     | ---   |   B02    | C03


text: Q: Jenkins hangs the browser when downloading build artifacts It seems like whenever I go and download a build artifact, the browser ends up hanging for a couple of minutes and seems to resume once the download actually starts. I'm currently using Firefox 17.0.8. Currently we're using Jenkins version 1.457.


text:
Q: How can i update my custom listView display? I'm working on a message application and wanna update my custom listView when new message arrive. I have tried several ways to do that but was unsuccessful ...please help with complete description cause m new to android. Here my code
public class SMSBroadcastReceiver extends BroadcastReceiver {
    Messages message1;
    MessageDbHelper db;
    Context context=null;
    SmsInboxList smsInboxList;
    BroadcastReceiver br;
    //  ADapter adap;
    private static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";
    IntentFilter intentFilter=new IntentFilter(ACTION);

    @SuppressLint("SimpleDateFormat")
    @Override
    public void onReceive(Context context, Intent intent) {

        // Retrieves a map of extended data from the intent.
        Bundle bundle = intent.getExtras();
        message1 = new Messages();
        this.context=context;
        //      context = context.getApplicationContext();
        smsInboxList = new SmsInboxList();
        //      adap=new ADapter(context, R.id.listView_Conversation);
        MessageDbHelper dbMessagedbHelper = new MessageDbHelper(context, null,null, 0);
        db = dbMessagedbHelper;

        try {

            if (bundle != null) {

                Object[] pdusObj = (Object[]) bundle.get("pdus");

                for (int i = 0; i < pdusObj.length; i++) {

                    SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
                    String phoneNumber = currentMessage.getDisplayOriginatingAddress();

                    String senderNum = phoneNumber;
                    String message = currentMessage.getDisplayMessageBody();
                    Long localLong = Long.valueOf(currentMessage.getTimestampMillis());
                    String datae = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(localLong.longValue()));

                    /*****************
                     ** @here we getting data for notification
                     **
                     **/
                    try {
                        message1.body(message);
                        message1.number(senderNum);
                        message1.date(datae);
                        message1.type("1");
                        Log.i(""    ,   "body++++++++++++++++" + message1.body);
                        Log.i(""    ,   "num+++++++++++" + message1.number);
                        Log.i(""    ,   "date+++++++++++" + message1.date);
                        Log.i(""    ,   "typeeee++++++++++++" + message1.type);
                        db.insertDataInMsgTable(message1);
                        createNotification(context, message1);

                    } catch (Exception e) {
                        Log.i("", "except" + e);

                    }
                    Log.i("SmsReceiver", "senderNum: " + senderNum
                            + "; message: " + message);
                }
            }
        }
    }

    public void createNotification(Context context, Messages message1) {

        Log.i("", "get body====" + message1.body + "---" + message1.number);
        Intent intent = new Intent(context, SmsInboxList.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,intent, 0);
        Notification notification = new NotificationCompat.Builder(context)
                .setContentTitle("From: " + message1.number)
                .setContentText(message1.body).setContentIntent(pendingIntent)
                .setSmallIcon(R.drawable.app_icon).build();

        NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        notification.flags |= Notification.DEFAULT_LIGHTS;
        notification.flags |= Notification.FLAG_AUTO_CANCEL;

        manager.notify(0, notification);

        try
        {
        smsInboxList.adap.notifyDataSetChanged();
        }
        catch(Exception e)
        {
            Log.i("", "error in addd==="+e);
            e.printStackTrace();
        }
    }
}

And main activity class is
public class SmsInboxList extends Activity {

    public ListView listView;
    public SmsInboxListAdapter adap ;
    Contact con;
    MessageDbHelper dbhelper;
    ProgressBar prob;
    LinearLayout rell;
    public static TextView newMsg;
    ImageView imgv;
    ImageView imgv1;
    ProgressBar pd;
    Dialog dialog;

    ArrayList<Messages> arrList = new ArrayList<Messages>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_sms_inbox_list);
        pd = new ProgressBar(SmsInboxList.this);

        pd = (ProgressBar) findViewById(R.id.progressBar_Inbox);

        dbhelper = new MessageDbHelper(this, null, null, 0);
        dbhelper.cleartable();
        Log.i("", "qwertyu==" + dbhelper.getAllreceive().size());
        listView = (ListView) findViewById(R.id.listView_Conversation);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View v, int position,
                    long arg3) {

                // TextView number=(TextView)findViewById(R.id.textViewName);

                String addr = arrList.get(position).number; // number.getText().toString();
                Log.i("" + position, "intent no==" + addr);
                Intent intent = new Intent(getApplicationContext(),ConversationChat.class);

                try {
                    String key_num = "numbrr";
                    intent.putExtra(key_num, addr);
                    Log.i("", "in intent put===" + addr);
                } catch (Exception e) {
                    Log.i("", "putExtra==" + e);
                }
                startActivity(intent);

            }
        });
        // prob=(ProgressBar)findViewById(R.id.progressBarInbox);
        rell = (LinearLayout) findViewById(R.id.relativeLayout_sent);
        imgv = (ImageView) findViewById(R.id.imageView_Setting);
        imgv1 = (ImageView) findViewById(R.id.imageView_Compose);
        newMsg = (TextView) findViewById(R.id.textView_Compose_new_message);
        imgv1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(),
                        SendMessage.class);
                startActivity(intent);

            }
        });
        newMsg.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(),
                        SendMessage.class);
                startActivity(intent);

            }
        });
        // ////////////////////////////////////
        // /////////////////////////////////////////////////////////////////////////////////
        imgv.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                //              Intent intent = new Intent(getApplicationContext(),FilterAct.class);
                //              startActivity(intent);
                 dialog=new Dialog(SmsInboxList.this);
                 dialog.setContentView(R.layout.activity_chat_theme);
                 dialog.setTitle("List");
                 ListView
                 listView=(ListView)dialog.findViewById(R.id.listView_chatTheme);

                 ArrayList<Messagesss> arr=new ArrayList<Messagesss>();
                 ArrayList<Messagesss> arr_sent=new ArrayList<Messagesss>();
                 final int
                 image_rec[]={R.drawable.recieve,R.drawable.receive_rec,R.drawable.rec_recei};
                 final int
                 image_sent[]={R.drawable.sentbubble,R.drawable.sent_rec,R.drawable.rec_sent};
                 for(int j=0;j<image_sent.length;j++)
                 {
                 Messagesss msg1=new Messagesss();
                 msg1.resid=image_sent[j];
                 arr_sent.add(msg1);
                 }
                 for(int i=0;i<image_rec.length;i++)
                 {
                 Messagesss msg=new Messagesss();
                 msg.resid=image_rec[i];
                 arr.add(msg);

                 }

                 final CategoryListAdapter1 adapter=new
                 CategoryListAdapter1(SmsInboxList.this,
                 R.id.listView_chatTheme,arr);
                 try{
                 listView.setAdapter(adapter);
                 }
                 catch(Exception e){
                 Log.i("", "error in adapter call"+e);
                 }
                 dialog.show();

                 listView.setOnItemClickListener(new
                 AdapterView.OnItemClickListener() {

                 @Override
                 public void onItemClick(AdapterView<?> arg0, View arg1,
                 int position, long arg3) {

                 int val=adapter.getItem(position).resid;
                 Log.i("", ""+val);

                 Log.i("",
                 "adapter value======"+adapter.getItem(position).resid);
                 SharedPreferences mPrefs;
                 SharedPreferences.Editor editor;
                 mPrefs=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                 editor = mPrefs.edit();

                 editor.putInt("hell_receive", image_rec[position]);
                 editor.putInt("hell_sent", image_sent[position]);
                 editor.commit();

                 dialog.dismiss();
                 }
                 });

            }
        });

        // /////////////////////////////////////////////////////
        // //////////////////////////////////////////////
        //      try {
        //          new ProgressTas().execute("");
        //      } catch (Exception e) {
        //          Log.i("", "error Progress Task==" + e);
        //      }

         try{
             getSMSInbox();
             }
         catch(Exception e)
         {
         Log.i("","getSMSInboxttry"+e);

          }

        ArrayList<Messages> mymsg = new ArrayList<Messages>(
                dbhelper.getAllreceive());

        dbhelper.insertDataInMsgTablePrimaryKey(mymsg);
        dbhelper.getAllreceiveCommon();

        for (int i = 0; i < mymsg.size(); i++) {
            Log.i("" + i, "my dataaaa mymsg=====" + mymsg.get(i).number + "---"
                    + mymsg.get(i).body + "---" + mymsg.get(i).type);

        }
        try{
            addItem(listView);
        }
        catch(Exception e)
        {
            Log.i("", "error in call of addItem in smsInbox"+e);
        }

        /*
         * Log.i("", "size my msg =="+mymsg.size()); ArrayList<Messages>
         * testArr=new ArrayList<Messages>(dbhelper.getAllreceiveCommon());
         *
         * for(int i=0;i<testArr.size();i++) { Log.i(""+i,
         * "my dataaaa mymsg test====="
         * +testArr.get(i).number+"---"+testArr.get(i
         * ).body+"---"+testArr.get(i).type);
         *
         * }
         */
        //      setup();
        //      updateUi(mymsg);
    }

    public void chatTheme(){

    }

    @SuppressWarnings({ "deprecation" })
    public List<String> getSMSInbox() {

        List<String> sms2 = new ArrayList<String>();

        Uri uri = Uri.parse("content://sms");
        Cursor c = getContentResolver().query(uri, null, null, null, null);
        startManagingCursor(c);
        arrList.clear();
        // Read the msg data and store it in the list
        if (c.moveToFirst()) {

            for (int i = 0; i < c.getCount(); i++) {

                Messages mssg = new Messages();
                mssg.set_type("" + c.getString(c.getColumnIndexOrThrow("type")));
                mssg.set_person(""
                        + c.getString(c.getColumnIndexOrThrow("person")));
                mssg.set_number(""
                        + c.getString(c.getColumnIndexOrThrow("address")));
                mssg.set_body("" + c.getString(c.getColumnIndexOrThrow("body")));
                mssg.set_date(""
                        + Functions.getTimefromMS(c.getString(c
                                .getColumnIndexOrThrow("date"))));
                //  Log.i(""+c.getString(c.getColumnIndexOrThrow("type")),
                //  "message==="+c.getString(c.getColumnIndexOrThrow("body")));
                // Log.i(""+c.getString(c.getColumnIndexOrThrow("_id")),
                // "reply path==="+c.getString(c.getColumnIndexOrThrow("reply_path_present")));

                Log.i("SmsInboxList method part ",
                                  "type===="+ c.getString(c.getColumnIndexOrThrow("type"))
                                + "name===="+ c.getString(c.getColumnIndexOrThrow("person"))
                                + "number=="+ c.getString(c.getColumnIndexOrThrow("address"))
                                + "body===="+ c.getString(c.getColumnIndexOrThrow("body"))
                                + "date===="+ c.getString(4));

                dbhelper.insertDataInMsgTable(mssg);

                c.moveToNext();
            }
        }
        /*
         * this is very important to dont close cursor if u dont wanna perform
         * next activity and backtrack to previous activity
         */
        // c.close();

        // Set smsList in the arrList
            adap = new SmsInboxListAdapter(getApplicationContext(), R.id.listView_Conversation);
            dbhelper.insertDataInMsgTablePrimaryKey(dbhelper.getAllreceive());
            arrList=new ArrayList<Messages>(dbhelper.getAllreceiveCommon());
            Log.i("", "size cmn=="+arrList.size());
         //   listView.removeAllViews();
            try {
                    try{
                    adap.notifyDataSetChanged();
                    }
                    catch(Exception e)
                    {
                        Log.i("", "error in notify dataset"+e);
                    }
                listView.setAdapter(adap);
                }
                catch (Exception e) {
                    Log.i("", "listView" + e);
                }
                for (int i = 0; i < arrList.size(); i++)
                {
                    adap.add(arrList.get(i));
                    Log.i("", "oyee!!!");
                        try{
                        adap.notifyDataSetChanged();
                        }
                        catch(Exception e)
                        {
                            Log.i("", "error in notify in smsInboxList=="+e);
                        }
                }
            Button button=(Button)findViewById(R.id.btn_notify);
            button.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    try{
                        getSMSInbox();
                        Log.i("", "getSmsInbox size of array list=="+arrList.size());
                    }catch(Exception e)
                    {
                        Log.i("", "error in notify click");
                        e.printStackTrace();
                    }

                }
            });

        return sms2;
        //
    }
}

A: Use
listView.invalidate();

after you have made changes to the list
Eg. you have added/removed/updated data in listView.

A: Just an idea:
Call your code public CategoryListAdapter1 adapter; as global to class.
Use adapter.notifyDataSetChanged(); whenever your list going to refresh.


text:
Q: how to parse the JSON data start with "/"? I want to parse the JSON data which response starts with the slash. I am using retrofit for parsing the data. thanks in advance. I have added the classes
/{
    "data": [
        {
            "id": "1",
            "text": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
        },
        {
            "id": "2",
            "text": "Felis donec et odio pellentesque diam volutpat commodo sed. Non arcu risus quis varius quam quisque. Nibh nisl condimentum id venenatis a condimentum vitae. Vel pharetra vel turpis nunc eget. "
        },
        {
            "id": "3",
            "text": "Volutpat sed cras ornare arcu dui vivamus arcu felis bibendum. Lobortis mattis aliquam faucibus purus in. Aliquam sem fringilla ut morbi tincidunt augue interdum."
        },
        {
            "id": "4",
            "text": "Elit scelerisque mauris pellentesque pulvinar pellentesque habitant morbi tristique. Bibendum at varius vel pharetra vel turpis nunc. Pellentesque sit amet porttitor eget dolor morbi non."
        },
        {
            "id": "5",
            "text": "Urna condimentum mattis pellentesque id. Ac tincidunt vitae semper quis. Massa tincidunt dui ut ornare lectus sit amet. Netus et malesuada fames ac turpis. Nulla facilisi cras fermentum odio eu feugiat pretium nibh."
        },
        {
            "id": "6",
            "text": "Tincidunt id aliquet risus feugiat in ante. Id donec ultrices tincidunt arcu non sodales neque sodales. Turpis massa tincidunt dui ut ornare lectus sit amet est. At ultrices mi tempus imperdiet nulla malesuada pellentesque elit."
        },
        {
            "id": "7",
            "text": "Fermentum posuere urna nec tincidunt praesent semper feugiat. Nulla facilisi etiam dignissim diam quis enim lobortis scelerisque fermentum. At auctor urna nunc id cursus metus aliquam eleifend mi."
        },
        {
            "id": "8",
            "text": "Quisque sagittis purus sit amet volutpat consequat mauris nunc congue. Malesuada fames ac turpis egestas sed. Volutpat ac tincidunt vitae semper. Aliquam nulla facilisi cras fermentum."
        }
    ]
}

I am getting this error

com.google.gson.stream.MalformedJsonException: Use
  JsonReader.setLenient(true) to accept malformed JSON at line 1 column
  2 path $

MainActivity

package com.basis.sliderapp.activity;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.Toast;

import com.basis.sliderapp.R;
import com.basis.sliderapp.adapter.DataAdapter;
import com.basis.sliderapp.apiCalls.ApiInterface;
import com.basis.sliderapp.model.BaseResponse;
import com.basis.sliderapp.model.Data;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity {

    private List<Data> searchResults = new ArrayList<>();
    private RecyclerView rec_data;
    private DataAdapter dataAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        rec_data = findViewById(R.id.rec_data);

        dataAdapter = new DataAdapter( MainActivity.this,  searchResults);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this, 1, false);
        rec_data.setLayoutManager(linearLayoutManager);
        rec_data.setAdapter(dataAdapter);

        getBasisData();

    }

    private void getBasisData() {

//        Gson gson = new GsonBuilder()
//                .setLenient()
//                .create();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://git.io/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        ApiInterface apiInterface = retrofit.create(ApiInterface.class);
        Call<BaseResponse> call = apiInterface.getData();
        call.enqueue(new Callback<BaseResponse>() {
            @Override
            public void onResponse(Call<BaseResponse> call, Response<BaseResponse> response) {

                    BaseResponse baseResponse = response.body();
                    Log.d("list", baseResponse +"");

                    searchResults =  baseResponse.getDataList();
                    dataAdapter.setList(searchResults);

            }

            @Override
            public void onFailure(Call<BaseResponse> call, Throwable t) {

                Toast.makeText(getApplicationContext(), "Something is Wrong", Toast.LENGTH_SHORT).show();
            }
        });

    }
}

API Inteface====>
package com.basis.sliderapp.apiCalls;

import com.basis.sliderapp.model.BaseResponse;

import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;

public interface ApiInterface  {

    @GET("/fjaqJ/")
    Call<BaseResponse> getData();

}

A: I suppose there is no method in any json parser libraries which will search for the json as a substring of the source string.
If you have any rules for the upcoming json string, for example, it always starts with /, then you can just delete it by calling String.substring(1) (it will return as a result the new string without a first character of the source string.
EDIT:
class CustomConverterFactory : Converter.Factory() {

override fun responseBodyConverter(type: Type,
                                   annotations: Array<Annotation>,
                                   retrofit: Retrofit)
        : Converter<ResponseBody, *>? = ResponseBodyConverter<Any>(type)

override fun requestBodyConverter(type: Type, parameterAnnotations: Array<Annotation>,
                                  methodAnnotations: Array<Annotation>,
                                  retrofit: Retrofit)
        : Converter<*, RequestBody>? = RequestBodyConverter<Any>()

class ResponseBodyConverter<T> internal constructor(private val type: Type) : Converter<ResponseBody, T> {

    @Throws(IOException::class)
    override fun convert(value: ResponseBody): T? {
        // here we handle this '\' on the start of the server's response
        return DEFAULT_GSON_FACTORY.fromJson<T>(value.string().substring(1), type)
    }
}

class RequestBodyConverter<T> : Converter<T, RequestBody> {

    override fun convert(value: T): RequestBody = RequestBody.create(MEDIA_TYPE, DEFAULT_GSON_FACTORY.toJson(value))

}

companion object {
    private val MEDIA_TYPE = "application/json; charset=UTF-8".toMediaTypeOrNull()
    private val DEFAULT_GSON_FACTORY = Gson() // you can define here your own gson
}

}
After that you should use it in Retrofit builder:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("your base url")
.client(okHttpClient)
.addConverterFactory(CustomConverterFactory())
.build();

A: as mentioned in this answer https://stackoverflow.com/a/40013869/5958272
use setLenient() property of gson to ignore the /
Gson gson = new GsonBuilder()
    .setLenient()
    .create();

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(BASE_URL)
    .client(client)
    .addConverterFactory(GsonConverterFactory.create(gson))
    .build();


text:
Q: MySQL query and subquery inexpert I have 4 tables:

*

*entrevista

*

*id_entrevista PK

*candidato FK candidato (#id_candidato)

*proceso FK proceso (#id_proceso)

*resultado

*candidato

*

*id_candidato PK

*proceso

*

*id_proceso PK

*dpt FK DPT (#id_dpt)

*DPT

*

*id_dpt PK

I need in my query to search, for each 'DPT', show the count of 'id_entrevista' of each 'proceso' but entrevista.resultado = 1 and has to be the last row of each entrevista.candidato
But if i have more rows of same entrevista.candidato:
for only now I can take the amount (count) of entrevista.id_entrevista:
SELECT p.id_proceso,
    (
            SELECT count(id_entrevista)
            from entrevista
            where entrevista.proceso = p.id_proceso
        ) as total
from proceso p
where dpt = 99   //this is the current dpt

But I need the subquery on:
SELECT p.id_proceso,
        (
                SELECT count(id_entrevista)
                from entrevista
                where entrevista.proceso = p.id_proceso
            ) as total,
       (
        //here
         ) as approved
    from proceso p
    where dpt = 99   //this is the current dpt

I have the idea I need to check the last entrevista of every candidato in the proceso. Something like this:
SELECT *
 FROM  entrevista
 WHERE proceso = 120 and candidato = 374
 ORDER BY fecha_entrevista DESC LIMIT 1

This will give me resultado which is 1 or 0 as result. I need only count the rows which return 1 from the query
eg:
|entrevista |
 -----------
 0001 | 0001 | 0001 | 20-12-2017 | 1
 0002 | 0001 | 0001 | 21-12-2017 | 0
 0003 | 0002 | 0001 | 20-12-2017 | 1
 0004 | 0003 | 0001 | 20-12-2017 | 1

 | candidato |
 ----------
 0001 | Foo
 0002 | Bar
 0003 | John Doe

 |proceso |
 ----------
 0001 | FooProceso | 0001

 | DPT |
 ----
 0001 | FooDPT

Expected output:
 Proceso    | Amount of interviews | Amount of pass
 --------------------------------------------------
 FooProceso | 4                    | 2

A: Thank you for your help, finally I did it with:
SELECT p.id_proceso, p.proceso,
                               (
                                SELECT count(id_entrevista)
                                from entrevista
                                where entrevista.proceso = p.id_proceso
                               ) as q_entrevistas,
                             (
                                select count(distinct(ee.candidato))
                                from entrevista ee
                                where ee.proceso = p.id_proceso
                                and ee.candidato not in (
                                                          select e.candidato
                                                          from entrevista e
                                                          where e.proceso = p.id_proceso and e.resultado = 0
                                                        )
                            ) as aptos
FROM proceso p
WHERE p.dpt = $dpt //in this case i use PHP


text:
Q: Tomcat/IIS isapi_redirect connectors not working Versions/OS

*

*Tomcat 6

*IIS 10

*Java jdk1.6.0_23

*Windows 10 Server

I've been trying to connect a Tomcat served web application to IIS following the applications step by step instruction for getting Tomcat and the IIS connectors working.
Tomcat is able to serve the site and I can connect to it through Tomcats port http://localhost:8080/sitename. Upon navigating to the IIS hosted site (on port 80 as defaulted), I see the normal default IIS site screen for IIS 10. If I were to access the site directory http://localhost/sitename, it brings me to a 404 page.
If it helps, here is the detailed error information:
Detailed Error Information:

Module
   IIS Web Core

Notification
   MapRequestHandler

Handler
   StaticFile

Error Code
   0x80070002

Requested URL
   http://localhost:80/unanet/

Physical Path
   C:\inetpub\wwwroot\unanet\

Logon Method
   Anonymous

Logon User
   Anonymous

My guess is the IIS site is having trouble using the isapi_redirect.dll file to establish a connection. The goal of this is to use IIS to add NTLM authentication for our users, so we utilize the IIS connectors for us.
I have all the necessary property files/configurations. I've checked the java environment variables. I've verified read/write rights for the users in the system, I'm running out of things to consider.

A: You can try to add the following code to web.config:
<system.webServer>
  <modules runAllManagedModulesForAllRequests="true" >
    <remove name="UrlRoutingModule"/>
  </modules>
</system.webServer>


text:
Q: JSF and EJB together in one app using Intellij I would like to create JSF and EJB modules but I have no clue how to connect them together or how to create EAR. At the moment I know how to create JSF application but what should I do next? Create EJB module with DAO and enities? Or create DAO and entities in JSF application?
Thanks for help

A: You should start reading the help manual:
https://www.jetbrains.com/help/idea/developing-a-java-ee-application.html


text:
Q: Bootstrap Modal Extetnal URL google Map I have a SearchGoogle html page which opens a google map.I want to load this html file into a modal dialog on the click of a button.
Defined a modal on my main index.jsp page and href the SearchGoogle.html. The content doesnt load up.Any help?
The below page is the remote page i want to load in an Modal Dialog.Have tried remote content loading.It is not working
<!DOCTYPE html>

<title>Search Map</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="css/googleMap.css" />

<input id="pac-input" class="controls" type="text"
    placeholder="Enter a location">

    <input type="radio" name="type" id="changetype-all" checked="checked">
    All <input type="radio"
        name="type" id="changetype-establishment"> Establishments <input
        type="radio" name="type" id="changetype-geocode"> Geocodes

A: If you look up the load method in the jQuery API doc, it says that the load method uses innerHTML to parse the page to be loaded and that:

During this process, browsers often filter elements from the document such as ,
  <title>, or  elements.

I suggest putting the googleMap.css on the modal page and moving your scripts in the page above to the body tag like this:
HTML for the page to be loaded (which I'm calling remote.html):
<!DOCTYPE html>

<title>Search Map</title>

    <button type="button" class="close" data-dismiss="modal">×Close</button>

Google Map Modal Title

    <input id="pac-input" class="controls" type="text" placeholder="Enter a location">

      <input type="radio" name="type" id="changetype-all" checked="checked">
      All <input type="radio"
        name="type" id="changetype-establishment"> Establishments <input
        type="radio" name="type" id="changetype-geocode"> Geocodes

    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

HTML for the page with the modal:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bootstrap 101 Template</title>

    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">

    <link rel="stylesheet" type="text/css" href="css/googleMap.css">

    Click me


text:
Q: Choose profile with AWS Java sdk I work on a multi env AWS project where we use Java for our Lambda functions.
Each developer has one AWS account and multiple profiles (Dev, Stg, Prod...).
Using the Java SDK, We want to be able debug the Lambda functions locally using Intellij IDEA, for that, we added a main that calls the handler.
The question is, how can we globally specify the profile to use when we execute our code ?
For every execution, we are getting a not authorized access to our AWS services like Secrets Manager or S3. We figured out that it always considers the basic account and not the profile even when we specify AWS_PROFILE environment variable.
Thank you very much.

A: The profile is controlled globally with the AWS_PROFILE environment variable.
On the Java side you should use ProfileCredentialsProvider.


text:
Q: Dask @delayed converts dataframes to pandas I have this code that calls a dask @delayed function that takes N dask dataframes as input and returns a dask dataframe as output.
There are two problems (1) inside the function the type of the dataframe is pandas instead of dask, and (2) when I get the result of the function, it's also pandas instead of dask.
What is the logic behind @delayed to get as input pandas dataframes instead of dask? I need to work only with dask dataframes.
This is the code:
df = pd.DataFrame({
    'height':  [6.21, 5.12, 5.85, 5.78, 5.98],
    'weight': [150, 126, 133, 164, 203]
})

df_dask = dd.from_pandas(df, npartitions=2)

@delayed
def some_function(*b):
    print('type b[0]: ' + str(type(b[0])) )
    ddf = b[0]
    return ddf

ddfout = some_function(df_dask, df_dask, df_dask)

computed = ddfout.compute()
>>> type b[0]: <class 'pandas.core.frame.DataFrame'> # this should be dask dataframe

type(computed)
>>> pandas.core.frame.DataFrame

A: The way to get column 0 of dask dataframe ddf is:
ddf[0]

There is no need for delayed here, the API already provides lazy operations over all the pandas methods that are supported (most of them).
Delayed is for arbitrary operations on constants and other delayed values, not dask collections like the dataframe.
See documentation: https://docs.dask.org/en/stable/delayed-best-practices.html#don-t-call-dask-delayed-on-other-dask-collections ; you probably wanted ddf.map_partitions.


text:
Q: how to use sum function with were condition and isnull check in linq to entity? happy new year... i am working with linq to entity, and got struck here,
SELECT O.InvoiceId, O.CustID, O.PickupDate, O.OrderDate, O.OrderNumber, O.ProNumber, O.PO1, O.PO2,
O.BaseRATE,O.OrderTotal,O.DiscAmount,
O.NormalDiscount,
ISNULL((Select Sum(AccessorialChargeAmount) from OrderDriverExtraCharge where OrderNumber = O.OrderNumber),0) As AccCharge,
ISNULL((SELECT Sum(AccessorialChargeAmount) FROM AccessorialCharge INNER JOIN
OrderDriverExtraCharge ON AccessorialCharge.AccessorialChargeId = OrderDriverExtraCharge.AccessorialChargeId
WHERE (((AccessorialCharge.Taxable)=1) AND ((OrderDriverExtraCharge.OrderNumberId)=O.OrderNumberId))),0) As Taxable FROM [Order] O
WHERE (((O.InvoiceId)=@InvoiceId))
Order By OrderNumberId

this is a huge sql qry i have to conver it in linq to entity query.
i am doing like
 var qry = (from O in _uow.Orders.GetAll()
join OD in _uow.OrderDriverExtraCharge.GetAll() on O.OrderNumberId equals OD.OrderNumberId
let AC in _uow.AccessorialCharges.GetAll() on OD.AccessorialChargeId equals AC.AccessorialChargeId
where O.InvoiceId == InvoiceId
select new {

});

but don't know how to use sum function with where condition, and is null :(
specially i am getting confused with this part
ISNULL((SELECT Sum(AccessorialChargeAmount) FROM AccessorialCharge INNER JOIN
    OrderDriverExtraCharge ON AccessorialCharge.AccessorialChargeId = OrderDriverExtraCharge.AccessorialChargeId
    WHERE (((AccessorialCharge.Taxable)=1) AND ((OrderDriverExtraCharge.OrderNumberId)=O.OrderNumberId))),0) As Taxable FROM [Order] O
    WHERE (((O.InvoiceId)=@InvoiceId))
    Order By OrderNumberId

don't know how to use is null with where and some conditions.
any suggestion or any related example  will be appreciated. i will mark your answer if it works for me. thanks in advance. happy new year.

A: I think you need something like this
from O in _uow.Orders.GetAll()
where O.InvoiceId == InvoiceId
orderby O.OrderNumberId
let AccCharge = (from odec in _uow.OrderDriverExtraCharge.GetAll()
                 where odec.OrderNumber == O.OrderNumber
                 select odec.AccessorialChargeAmount
                ).Sum() ?? 0
let Taxable = (from ac in _uow.AccessorialCharge.GetAll()
               join odec in _uow.OrderDriverExtraCharge.GetAll() on ac.AccessorialChargeId equals odec.AccessorialChargeId
               where ac.Taxable == 1 &&//possibly this you use boolean
                     odec.OrderNumberId == O.OrderNumberId
              ).Sum() ?? 0
select new{
    O.InvoiceId,
    O.CustID,
    O.PickupDate,
    O.OrderDate,
    O.OrderNumber,
    O.ProNumber,
    O.PO1,
    O.PO2,
    O.BaseRATE,
    O.OrderTotal,
    O.DiscAmount,
    O.NormalDiscount,
    AccCharge,
    Taxable
}

A: try this
 var qry = (from O in _uow.Orders.GetAll()
join OD in _uow.OrderDriverExtraCharge.GetAll() on O.OrderNumberId equals OD.OrderNumberId
let AC in _uow.AccessorialCharges.GetAll() on OD.AccessorialChargeId equals AC.AccessorialChargeId
where O.InvoiceId == InvoiceId
select new {

}).Sum(r => (decimal?) r.AccessorialCharges)


text:
Q: Native error when trying to implement libwebp I seemed to be getting a
JNI- java.lang.UnsatisfiedLinkError: Native error: method not found

when I try to implement libwebp into my project. I followed this link.
and it first gave me an error that it couldn't find the lib "webp". Then I used System.loadLibrary("MYPROJECT"); and it fixed the error, but generated another one saying
Native error: method not found

Every function from libwebp and libwebpJNI are generating the error, so it may have something to do with the native C code.
Any help?


text:
Q: Proof verification on invertible matrices I have the following question:

Assume $A \in M_{2\times2}(\mathbb{R})$ has the property that "if $A\vec{x}=A\vec{y}$, then $\vec{x}=\vec{y}$.  Prove that $A$ is invertible.

My attempt:

Consider $A\vec{x}=A\vec{y}$
  $A\vec{x} - A\vec{y}= \vec{0}$
  $A(\vec{x}-\vec{y}) = \vec{0}$
  Since $\vec{x}=\vec{y}$, this implies that $\vec{x} - \vec{y}= \vec{0}$
  Thus, $\operatorname{Null}(A) = \{\vec{0} \}$
  By the invertible matrix theorem, A is invertible.

What I'm worried about is if I can conclude that $\operatorname{Null}(A) = \{\vec{0} \}$.
If not, I was wondering from the hypothesis, if I could say that $A\vec{x} = \vec{b}$ has a unique solution for some $b \in \mathbb{R}^n$, and so $\operatorname{rank}(A) = n$...

A: Here's a slightly different approach which might be clearer. Suppose $A x = 0$. Then take $y = 0$, so $Ax = Ay$. But now $x = y = 0$, so the only solution to $Ax = 0$ is $x = 0$. In particular, Null($A$) is just the zero vector, so $A$ is invertible.


text:
Q: How to Assign A Structure Type In Declaration Moment? I declared a variable whose type is structure i did , but i can't assign it
Structure SHAPE
    Dim x as integer
    Dim y as integer
End Structure

Dim Shape1 As SHAPE = (15, 20) ' << The Problem is here

Public Sub test()
    Label1.Text = Shape1.x
End Sub

A: Structures don't magically understand whatever way you choose you try to get data into them. Like any type, if you want to be able to create an instance with specific data then add a constructor to do that, e.g.
Public Structure Shape

    Public ReadOnly Property X As Integer
    Public ReadOnly Property Y As Integer

    Public Sub New(x As Integer, y As Integer)
        Me.X = x
        Me.Y = y
    End Sub

End Structure

You then create an instance of that type as you would any other:
Dim shape1 As New Shape(15, 20)

A: Either create a constructor and call the constructor. Or populate the properties after constructing.
Eg.
Dim Shape1 As SHAPE = New SHAPE With {.x = 1, .y = 2}

Equivalent to:
Dim Shape1 As SHAPE = New SHAPE()
Shape1.X = 1
Shape1.y = 2

Creating a constructor is the preferred way, because structs should in general be immutable. Doing so and setting the properties to readonly is an easy way to make a struct immutable:
Public Structure Shape

    Public ReadOnly Property X As Integer
    Public ReadOnly Property Y As Integer

    Public Sub New(x As Integer, y As Integer)
        Me.X = x
        Me.Y = y
    End Sub

End Structure


text:
Q: Ошибка в простейшем алгоритме Нужно обнулить последние биты даного числа n. 0<=n<=2^31. Вводиться n, само число биты которого нужно обнулить, потом k, оно показывает сколько бит с конца обнулять. 0<=k<=30. Нельзя использовать циклы. Написал, но никак не хочет проходить 6 тестов из 50.
#include <iostream>

using namespace std;

int main() {
    long long n, k, L = 4294967295, f = 0, S = 0;
    cin >> n >> k;
    if (k == 1) f = 1;
    else {
        S = (1 - (2 << (k - 1))) / (-1);
    }
    L -= S+f;
    cout << (L&n);
}

Использовал методику геометрической прогресии, чтобы сделать k нулей в числе L, а потом просто применил к даному числу, и к числу с вырезанными нужными нулями операцию &.
Незнаю, почему не проходит 2 теста. Значительно повышал число L, но не в этом дело.

A: #include <iostream>

using namespace std;

int main()
{
    unsigned long input;
    int bits;

    cin >> input >> bits;

    input >>= bits; // Убираем все нужные биты
    input <<= bits; // Возвращаем на их место нули

    cout << input << endl;

    return 0;
}

A: unsigned int mask = 0xFFFFFFFF >> k;
unsigned int res = n & mask

это если надо биты обнулять не у числа, а у ячейки памяти (4 бита) в котором оно хранится


text:
Q: Loading a file with a name defined by attr I have an image...
<img src="images/dut7_thumb.jpg" alt="images/dut7.jpg" filetoload="test.html"/>

I am trying to load the file "test.html" into the div with id "words" using...
$list.find('.st_thumbs img').on('click',function(){
   var $this = $(this);
   $("#words").load("text/"+$this.attr('filetoload'));
});

...but filetoload is undefined?
How do I grab that file name?
Edit: Code was in the wrong place. Works fine now.

A: The code is correct. Maybe $list.find('.st_thumbs img') is wrong.
Look: http://jsfiddle.net/bBEDq/

A: It would help to see your entire html block
I was able to get it working with a little modification http://jsfiddle.net/sceVA/

A: Something wrong with the $list. Because your code seems to work. http://jsfiddle.net/UVTu9/
Have you tried checking for the value of $this, try logging in into the console.


text:
Q: accessing private websocket data from tradingview in python I am able to get live ticker data and the prior 500-100 candle chart data with this code but I am unable to get data that isn't delayed for CME_MINI:ESH2021. TradingView puts a 600 second delay I believe on the public stream. I do pay for the data and I can pull it up on the web client but I am unable to get the non-delayed data on python since I am unsure how to log into TradingView via python. If someone knows how I can fix my code to do what I want it to I would greatly appreciate your input or any advice.
from websocket import create_connection
import json
import random
import string
import re
from datetime import datetime
from time import sleep

def filter_raw_message(text):
try:
    found = re.search('"p":(.+?"}"])}', text).group(1)
    print(found)
    return found
except AttributeError:
    print("error")

def generateSession():
stringLength=12
letters = string.ascii_lowercase
random_string= ''.join(random.choice(letters) for i in range(stringLength))
return "qs_" +random_string

def generateChartSession():
stringLength=12
letters = string.ascii_lowercase
random_string= ''.join(random.choice(letters) for i in range(stringLength))
return "cs_" +random_string

def prependHeader(st):
return "~m~" + str(len(st)) + "~m~" + st

def constructMessage(func, paramList):
#json_mylist = json.dumps(mylist, separators=(',', ':'))
return json.dumps({
    "m":func,
    "p":paramList
    }, separators=(',', ':'))

def createMessage(func, paramList):
return prependHeader(constructMessage(func, paramList))

def sendRawMessage(ws, message):
ws.send(prependHeader(message))

def sendMessage(ws, func, args):
ws.send(createMessage(func, args))

# Initialize the headers needed for the websocket connection
headers = json.dumps({
'Connection': 'upgrade',
'Host': 'data.tradingview.com',
'Origin': 'https://data.tradingview.com',
'Cache-Control': 'no-cache',
'Upgrade': 'websocket',
'Sec-WebSocket-Extensions': 'permessage-deflate; client_max_window_bits',
'Sec-WebSocket-Key': '1H41q97V8BbMKUq0knV1UA==',
'Sec-WebSocket-Version': '13',
'User-Agent': 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36 Edg/83.0.478.56',
'Pragma': 'no-cache',
'Upgrade': 'websocket'
})

# Then create a connection to the tunnel
ws = create_connection(
'wss://data.tradingview.com/socket.io/websocket',headers=headers)

session= generateSession()
print("session generated {}".format(session))

chart_session= generateChartSession()
print("chart_session generated {}".format(chart_session))

symbol = "CME_MINI:ESH2021"
timeframe = "5"
candles = 100

# Then send a message through the tunnel
sendMessage(ws, "set_auth_token", ["unauthorized_user_token"])
sendMessage(ws, "chart_create_session", [chart_session, ""])
sendMessage(ws, "quote_create_session", [session])
sendMessage(ws,"quote_set_fields", [session,"ch","chp","current_session","description","local_description","language","exchange","fractional","is_tradable","lp","lp_time","minmov","minmove2","original_name","pricescale","pro_name","short_name","type","update_mode","volume","currency_code","rchp","rtc"])
sendMessage(ws, "quote_add_symbols",[session, symbol, {"flags":['force_permission']}])

theString1 = "={\"symbol\":\""
theString2 = "\",\"adjustment\":\"splits\"}"
theString3 = theString1 + symbol + theString2

sendMessage(ws, "resolve_symbol", [chart_session, "symbol_" + timeframe, theString3])
sendMessage(ws, "create_series", [chart_session,"s" + timeframe,"s" + timeframe,"symbol_" + timeframe,timeframe,candles])

sendMessage(ws, "quote_fast_symbols", [session,symbol])

sendMessage(ws, "create_study", [chart_session,"st" + timeframe,"st" + timeframe,"s" + timeframe,"Volume@tv-basicstudies-118",{"length":20,"col_prev_close":"false"}])
sendMessage(ws, "quote_hibernate_all", [session])

# Printing all the result
a=""
while True:
try:
    sleep(1)
    result = ws.recv()
    pattern = re.compile("~m~\d+~m~~h~\d+$")
    if pattern.match(result):
        ws.recv()
        ws.send(result)
        print("\n\n\n hhhhhhhhhhhhhhhhhhhhhh "+ str(result) + "\n\n")
    print(result)
    a=a+result+"\n"
except Exception as e:
    print(e)
    break

A: This post is quite old, and the OP probably has the answer already, but regardless, I'm posting for people who visit this page in the future.
This solution comes from the Github page here: https://github.com/rushic24/tradingview-scraper
In fact, what I'm about to post is literally on the front page of that link. I'm just remaking it into a step-by-step guide.
In the original code, you can find the following line:
sendMessage(ws, "set_auth_token", ["unauthorized_user_token"])
Do you see the part where it says "unauthorized_user_token"? That means you're an anonymous random person to TradingView.
So you must create an auth_token to let TradingView know you're logging in as yourself and that you indeed have paid access to real-time data.
1.
Add the following to your code:
def get_auth_token():
    sign_in_url = 'https://www.tradingview.com/accounts/signin/'
    username = 'username'
    password = 'password'
    data = {"username": username, "password": password, "remember": "on"}
    headers = {
        'Referer': 'https://www.tradingview.com'
    }
    response = requests.post(url=sign_in_url, data=data, headers=headers)
    auth_token = response.json()['user']['auth_token']
    return auth_token

Replace 'username' and 'password' with your own.
2.
replace
sendMessage(ws, "set_auth_token", ["unauthorized_user_token"])
With the following:
auth_token = get_auth_token()
sendMessage(ws, "set_auth_token", [auth_token])

*

replace
ws = create_connection('wss://data.tradingview.com/socket.io/websocket', headers=headers)
With the following:
ws = create_connection( 'wss://data.tradingview.com/socket.io/websocket?from=chart/XXyour_chartXX/&date=XXXX_XX_XX-XX_XX',headers=headers)

replace 'XXyour_chartXX' with one of your saved charts' URLs. (https://www.tradingview.com/chart/***###THIS_PART###***/)

A: this is very useful, thanks a ton!
I guess it only works with the 2FA disabled, otherwise it throws this "{'error': '2FA_required', 'code': '2FA_required', 'message': 'Second authentication factor is needed', 'two_factor_types': [{'name': 'totp'}]}"


text:
Q: Does python show problem with really large integers? I have a code to calculate highest prime factor of 600851475143.
def PRIME(a):                #Check if no is prime
    f = 0
    i = 2
    while(i < a/2):          #No factor of a no can be greater than a/2
        if (a % i == 0):
            f = 1
            break
        i = i + 1

    if(f == 1):
        return 0
    else:
        return 1

def PFIND(a):
    for i in range(1, 100000):   #Iteratively check if the no is prime
        if PRIME(a/2 - i):       #No factor of a no can be greater than a/2.
            if (a % (a/2 - i) == 0):
                return (a/2 - i)
print PFIND(600851475143)

But the code runs on and on and on and does'nt give any output.

A: Python's support for large integers is fine. I think your problem is that you're doing very slow algorithms for both brute-force finding the factor and testing whether your factor is prime. If you just invert the order of those two tests (ie, test whether it's a factor, then test whether it's prime), it'll go a lot faster.
But perhaps the problem was about using more sophisticated algorithms. Maybe you should use the Rabin-Miller test instead of brute-force.

A: Rather than starting out with a huge number for testing, try your algorithm on smaller numbers. Then try progressively larger numbers. Plot the amount of time the function takes - I'd suggest using the timeit module. Then extrapolate and estimate how long the function will take on the number you're trying.
I think you'll find that your algorithm is taking so long that it looks like it never finishes.

A: Your loop condition of
while(i < a/2):

is making your algorithm take O(N) time.
A simple modification will improve this to O(√N).
hi = int(math.sqrt(a) + 1)     # +1 in case of rounding error.
while i <= hi:

A: I've found that Python does a great job with large integers. As already mentioned, you are using two brute force tests to crack this nut.
Try this:
a = 600851475143
q = 2

while q <= a / 2:
    if not a % q:
        a /= q
        p = q
    else:
        q += 1

print p

A: I wrote some hobby code that has to do with prime numbers in the past, which I've adapted to work for your purposes. Here is the code:
def isPrime(n, primes=[]):
    """ Return True iff n is a prime number.
            If primes is non-empty, return true iff n is co-prime to every number in primes. """

    if not len(primes):
            if n <= 2:
                    return True
            elif n%2 == 0:
                    return False
            else:
                    prime = True
                    for i in range(3, n, 2):
                            if n%i == 0:
                                    prime = False
                    if prime:
                            return True
    else:
            for p in primes:
                    if not n%p:
                            return False
            return True

def next(n, primes):
    """ Return a number p such that
            1. p is co-prime to every number in primes
            2. p>n and p-n is as small as possible"""

    curr = n+1
    while 1:
            if isPrime(curr, primes):
                    return curr
            else:
                    curr += 1

def generate(n):
    """ Yield the first n prime numbers"""

    primes = [2]
    curr = 2
    for _ in range(n-1):
            p = next(curr, primes)
            primes.append(p)
            curr = p
            yield p

def primeNumbers(n):
    """ return a list of prime numbers such that all numbers in the list are at most n
            1 is a prime number"""

    answer = []
    if n <= 2:
            answer.append(n)
    else:
            for i in range(3, n+1, 2):
                    prime = True
                    for p in answer:
                            if i%p == 0:
                                    prime = False
                                    break
                    if prime:
                            answer.append(i)

    return answer

def PFIND(n):
    primes = primeNumbers(n)
    primes.reverse()
    for p in primes:
        if n%p == 0:
            return p

That should do it.
Hope this helps

A: Python's long number support is very verbose and well tested, so I doubt that's the problem. One thing I noticed about your code is that it hasn't be optimized at all and computes the value a/2 several times during in each iteration of the loop. However even if you fixed that it would likely still be too slow because finding prime factors can be a very time consuming especially for larger numbers.
For that reason I think the best approach would be to find a better algorithm. Here's code derived from one I found which calculates all the prime factors of a number. I converted it to Python and simplified it to just keep track of the largest factor it finds. It quickly returned the correct answer for your test case, whose prime factors are {71, 839, 1471, & 6857}.
def maxprimefactor(n):
    """ find the largest prime factor of a positive integer """
    maxfactor = None
    divisor = 2
    while divisor*divisor <= n:
        if n % divisor:
            divisor += 1
        else:
            maxfactor = divisor
            n /= divisor
    if n != 1:
        maxfactor = n

    return maxfactor if maxfactor else 1

print maxprimefactor(600851475143)
# 6857