text:
Q: Why are MAX-, AD-, LT- parts (among others) so expensive? I'm curious why some IC manufacturers like Maxim, Analog Devices, and Linear Tech's parts are so expensive? I know they are much higher quality (better electrical characteristics, etc), but for some parts it still doesn't make sense. For example:
SD Flash Media Controllers (not identical, but to do the same thing)
Maxim MAX14502: $21.69 Mouser
Microchip USB2244: $2.18 Mouser

RS-232 Transceiver (not pin-to-pin identical, but do the same thing)
Maxim MAX3232: $5.92
TI MAX3232: $1.91
ST ST3232: $1.06

Accelerometer. This might be an extreme example. They're a little different, but both are 3-axis, digital accelerometer with the same sensitivity.
Analog Devices ADXL362: $9.73 (!?)
Freescale MMA8653FC: $1.09
And there are tons of more examples.
I'll try to frame the questions so this doesn't become a discussion. As a design engineer why would you want to select a part that is 5 to 10 times more expensive? What could be some technical reasons?
Obviously there are markets that require very high quality components, but is the demand for pricey, quality components even that big? How can the expensive-chip manufacturers compete with others that can make it so much cheaper?

A: You have to be careful when you say "they do the same thing." True, the same basic function may be there, but different uses measure quality in different ways.
For example, the LM324 opamp is dirt cheap and the LT1014 of roughly the same vintage costs 10x more. They're both op-amps and will both "do the same thing" but the LM324 offset voltage, for example, is 10's of millivolts while the LT1014's is measured in microvolts. If I'm amplifying a piezo knock sensor signal to tell when a box is shaken, I'll use the 324. If I need to amplify a thermocouple, I'll use the 1014.
I took a glance at the accelerometer data sheets and the Analog one specs things that the Xtrinsic one doesn't, like linearity and cross-axis specification. If those things are important in my application, I can either just buy the Analog part, or call up Xtrinsic and try to track down the info. And then I don't have assurance that it won't change in a later batch, because it's not a property they guarantee.

A: Q. Why would I pick a part 10 times more expensive?
A. I'm building to military specs, for aircraft / space / submarine / whatever, and I need parts guaranteed to work under extreme conditions.
Those other parts MIGHT do the job, but Jupiter's orbit is a long way away [Satellite], or people's lives are a stake [submarine emergency systems].
[Edit] A compny guaranteeing that kind of performance is doing a lot of Quality Control checking on more samples per batch. They may even test EVERY chip. If a spec sheet gives a rating of [say] 100 volts, the actual part is probably tested to 120 volts.
That kind of quality control testing adds a lot to the cost of a component.

A: There are a couple of reasons: The 1st one is that these companies offer various parts that comply with very strict standards which are mandatory in certain industries. At some cases, you can see this in the datasheet or on the website.
2nd reason is that these companies tend to meet the specifications from the datasheet every time. This is something you could not care less about in low-tech products but in some special cases you base your entire accuracy and / or reliability on these spec. so you want to know you can trust the vendor.
3rd reason is that these companies are "boutique" among IC companies. They offer the highest quality products and the best support you could wish for. I used to work for a large company who worked a lot with ADI parts and we had a very good working relationship with them, which was very different from the relations we had with different parts makers (which is little to none).
The last reason is mainly because they can! They tend to make parts that target industries like medical, military, aero-space and such... Usually these companies make very expensive products so they could not care less paying $10 for a good quality op-amp because the rest of the system might come up to several hundreds of thousands or more.

A: Price is negotiable and arbitary.  If you are ordering 1- 10 off's per annun as an engineer price may not be an issue for you.
If you are ordering low volume, < 10,000 per annun, price is going to be an issue and you would need to select best pricing options from the major distributors.  Also working closely with the regional sales representatives to ensure you get good pricing.  different companies have different policies and you may need to go through procurement and deal with approved vendors.
If you are working on projects of high volume > 100,000 per annun you will have each and every sale rep from every semiconductor manufacturer knocking on your door weekly, trying to get their parts designed in early.  In these situations the price you pay is the price your purchasing people can negotiate.  It bares no resemblance to the low volume pricing you see on digikey/farnell/mouser etc.
So the difference in pricing you are seeing for similar parts is arbitrary.  Having said that good op amps from Ti, Analog devices and Linear cost more than average op amps from other manufacturers.  But you get what you pay for there ...
It comes down to how many parts your are buying ... the more units you buy the better negotiations you have on price, and the better support you get from the Field application Engineers (FAE).
Having worked in consultancies for small clients, large clients and worked in mid volume production quantities I have seen the range of support from the manufacturers vary greatly.

A: Disclosure: I currently work for one of the manufacturers mentioned, I completed an internship with a second, and I know current and former employees of a third. I can't reveal specifics but I can give some general reasons why ICs have variable costs and prices. I also can't speak about the specific ICs mentioned -- even if I knew why my company's version is priced the way it is and could reveal that information, I couldn't possibly know why other companies priced theirs differently.
There are many reasons -- both technical and non-technical -- why the price of one manufacturer's IC may be significantly higher than another's. Below are some of the major ones. Some or all of these may be true for a particular case, and manufacturers may be in different price positions for different IC types (e.g. op amps, ADCs, voltage regulators, etc.).
Technical Reasons
Fab/Assembly
Every manufacturer has a different fab process (actually many processes), and the process used by a manufacturer may have better performance for a particular application or the process may be more expensive (which of course drives up the cost and price of the final IC).
Even with identical processes and circuitry, though, the materials used in the assembly of the IC can vary in performance and cost. For example, a higher quality mold compound reduces stress on the die and therefore improves performance over temperature...at an increased manufacturing cost. To further reduce stress on the die a polyimide layer may be added. Another material choice that can affect performance and cost is the wire bond material -- for example, it is easier to meet or exceed qualification standards (e.g. temp cycle) with gold wire but gold is more expensive than copper. The added cost of higher quality materials may be important for applications which require long lifetimes, severe temperature swings, etc., but would be an unnecessary expense for shorter term applications with little temperature variation.
Test
Production test also has a large effect on overall cost and quality. Virtually every IC requires some sort of trim (e.g. laser trimming) for at least an internal bandgap voltage reference or oscillator, and possibly for offset reduction, gain correction, etc. Adding additional trims and/or trim bits can improve the performance of the trimmed IC at the cost of increased test time (which is increased test cost). Trim may also require the addition of non-volatile memory, which may require additional data retention tests that also increase the test time. The fab process may even dictate whether trimming is done at wafer probe or final test (i.e. after the die is packaged); wafer probe generally has higher throughput (so it's cheaper) and allows the manufacturer to throw out bad die before spending money packaging it, which of course reduces overall cost of test.
Also, while every IC is tested (at the very least for continuity) overall test coverage can vary. Some applications like defense, automotive, or medical require very low or 0 DPPM, which requires the manufacturer to fully test all electrical parameters (possibly over temperature, which significantly increases test cost). Other applications do not require such low DPPM and the manufacturer may choose not to test in production certain electrical parameters which demonstrated a high \$C_{pk}\$ during characterization, especially if those parameters have a long test time or require more expensive tester equipment. Skipping these tests can result in a significant cost and price reduction with very low but non-zero risk (due to the high \$C_{pk}\$) of passing a die that does not meet the spec, which may be worth it to customers in less critical applications.
Non-technical Reasons
One non-technical factor affecting price is which manufacturer was the first to market. This manufacturer has a temporary monopoly or near monopoly and can command a higher price. This manufacturer may spend less time optimizing their production for lower cost in order to be first to the market. Manufacturers which enter the market later tend to optimize for cost to undercut the manufacturer that was first to market since a customer will not switch to a different manufacturer for an identical or nearly identical IC at the same price. The manufacturer who was first to market may still be able to command a higher price if they have established design wins with large customers who do not wish to qualify a new manufacturer's IC even if the new IC is offered at a lower price.
Also, a manufacturer's prior relationships with major customers and perceived reputation can allow it to charge a higher price. Major customers may be willing to pay extra if they have an established relationship with a manufacturer's support teams and/or if the customer(s) have had quality problems with a different manufacturer in the past.
In short
Ultimately, a manufacturer's price depends on which market it is targeting: some customers are relatively low volume but have very high quality needs and are willing to pay for it (e.g. military, automotive, and medical) whereas other customers have much higher volumes and every penny counts. ICs manufactured for critical applications depend on higher margins to make up for relatively low volume, use better quality materials, have more extensive test coverage, etc. ICs manufactured for less critical but higher volume applications optimize cost to deliver lower priced ICs which make up for the lower margins with much higher volumes.


text:
Q: How to run container in background while using docker compose I used docker-compose up -d .
but my docker container exits after executing my script. This is my below docker-compose.yml file. I want to run docker container in the background.
    version: "3"
    services:
      master:
        build: .
        command: sh /opt/spark/sbin/start-master.sh
        ports:
          - 8080:8080
          - 8081:8081
          - 7077:7077
          - 4040:4040
      worker:
        depends_on:
          - master
        deploy:
          - replicas: 2
          - endpoint_mode: dnsrr
        build: .
        command: sh /opt/spark/sbin/start-slave.sh spark://172.17.0.2:7077
        ports:
          - 9080:8080
          - 9081:8081
          - 9077:7077
          - 9040:4040

================
    $ docker container ps -a
    CONTAINER ID        IMAGE                  COMMAND                  CREATED             STATUS                   PORTS               NAMES
    975a3af7dc27        mysparkdocker_master   "sh /opt/spark/sbin/…"   41 minutes ago      Exited (0) 18 seconds ago                       mysparkdocker_master_1
    e52cf60c820c        mysparkdocker_worker   "sh /opt/spark/sbin/…"   41 minutes ago      Exited (0) 17 seconds ago                       mysparkdocker_worker_1

===================================

A: The problem is that your shell scripts probably fork themselves to create a daemon, whereas in the Docker model, you would actually not want them to daemonize themselves, because the process would exit and thereby stop the container.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Authorize.net report refresh rate? I am submitting transactions, but don't see them in my authorize.net account. I am getting a response back from authorize.net. How long does it take for records to show in the reports section?
I am submitting to
https://secure.authorize.net/gateway/transact.dll

A: They should show up immediately. New transactions show up in the unsettled transaction list, not in the settled batch reports. They don't show there until they are settled overnight.

A: To see those unsettled transactions in your Authorize.Net account, click "Search" in the top navigation and then "Unsettled Transactions" in the left navigation. Once they have been settled they will show up under the "Reports" section.

A: The Report section will only show you the details about the "Settled Transactions" and "Decline Transactions".
When you submit the new transactions then then you can see those transactions in the "Unsettled Transactions". Authorize.net don't quickly Settled Transactions, it takes some time (I think 24 hours, please check) to get the transaction settled.


text:
Q: gSoap multiple calls with SSL enabled what is the efficient way to call a WS multiple times in gSoap with SSL enabled.
I have this code:
SimpleInterfaceHttpPostProxy proxy(SOAP_IO_CHUNK | SOAP_IO_KEEPALIVE | SOAP_C_UTFSTRING | SOAP_C_NILSTRING );

    proxy.soap->ssl_flags = SOAP_SSL_NO_AUTHENTICATION;
    proxy.soap->connect_timeout = TIMEOUT_CONNECT;
    proxy.soap->send_timeout = TIMEOUT_SEND;
    proxy.soap->recv_timeout = TIMEOUT_RECV;
    proxy.soap->socket_flags = MSG_NOSIGNAL;

    e__ResultAndString rsp;

int retCode = proxy.CheckChanges("someurl","/checkpath","serialnumber",&rsp);
proxy.destroy();

Now if i want to call proxy.CheckChanges and reuse SSL session and reuse connection i should probably change it to:
while(true)
{
  retCode = proxy.CheckChanges("someurl","/checkpath","serialnumber",&rsp);
  proxy.destroy();
}

If i do so, the second call always timeouts! If i don't use proxy.destroy(); it works... But does this generates memory leaks?
I mean there are a lot of examples how to use gSoap all made in main, but none that i could find that would reuse proxy/stub and make multiple calls.
So can someone please for others sake :) for the future explain how to make FAST efficient and without memory leak, calls to WS. Which approach is correct, i would like to reuse tcp connection or atleast reuse SSL session in almost 15sec calls.
Thank you!


text:
Q: Remove encoding from URL with htaccess I've found an error in Google Webmaster Tools that I need to redirect. I've done the following, but it will not work. Is there anything else I can try?
I would like http://www.domain.com/blog/category/%E2%80%8E to get redirected to http://www.domain.com/blog/category/
Code:
RewriteEngine on
RewriteCond %{REQUEST_URI} ^/blog/category/\%E2\%80\%8E$
RewriteRule ^(.*) http://www.domain.com/blog/category/ [R,L]

I've tried a few other potential solution from SO, but with no luck

A: Replace your rule with this:
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+(blog/category)/%E2%80%8E\s [NC]
RewriteRule ^ /%1 [L,R]

THE_REQUEST represents the original HTTP request as received by the Apache web server.


text:
Q: Correctly Sizing a Canvas inside a JFrame my current project is a small desktop application in Java that functions like a room decorator similar to the IKEA software that lets you plan out your room before you go and buy furniture. When I thought about that concept my mind immediately jumped to the RTS Genre of games. Thinking about WC3 and StarCraft experiences I had my thought was to implement a basic grid interface where i can just place down squares as a starter demonstration type of deal.
I understand scaling a Canvas (java.awt.Canvas) inside a basic JFrame is .. weird since the Frame itself consumes space for its outer border display. So it converted the 1600/900 Frame width/height to 1584/861 Canvas width/height.
What I want is to be able to divide the display into a grid of 5x5 squares but, as you might immediately recognize, neither 1584 nor 861 is cleanly divisible by 5.
I fumbled a bit with Modulo ( % ) and quickly ran out of ideas so I turned to the internet for help yet google and stackoverflow was suprisingly void of information about the ratio at which jframes steal away size from its inner components.
My question now would be, is there any efficient method to tell the frame to wrap itself around a canvas of a certain size rather than taking the space it needs from it? or any other mechanic i can use to arrange a Canvas to a certain size disregarding the space the frame needs? Because just trial and error on fumbling together the right frame size for this to work seems to me like an ugly solution that only works for the specific case of 5x5 squares.


text:
Q: SQL join result fulltext I have two tables, which I will call table1 and table2. Table1 has 2 fields, id and auth, table2 also has two fields, id and keywords. Note that id of table1 and table2 match.
This is my query:
SELECT id, MATCH(keywords) AGAINST('example') FROM table2 WHERE MATCH(keywords) AGAINST('example')

How am I going to exclude results where the auth (table1) of that same id is not 1?

A: SELECT id, MATCH(keywords) AGAINST('example')
  FROM table2 t2
 WHERE MATCH(keywords) AGAINST('example')
   AND NOT EXISTS (select 1 from table1 t1 where t1.id = t2.id and t1.auth != 1)

A:   SELECT *
  FROM table1 t1
  INNER JOIN table2 t2
  ON t1.id != t2.id


text:
Q: In Android, sending notifications to android phones via code in Firebase I am developing an application that saves some data in the Firebase Database. As soon as the data is saved, I want it to be given as a notification to all the users connected to the application through code.
I couldn't understand the procedure to do so. Can anyone explain me how one can send push notifications via code in the chain as Android phone -> Firebase Database -> Notification to Android Phone with the data.

A: it isn't Possible to solve your Problem with Firebase only. You have to create a MySQL Server and work with PHP. Maybe this Video from Filip Vujovic could help you.
https://www.youtube.com/watch?v=LiKCEa5_Cs8

A: You can use GCM,it's simple.The GCM service handles all aspects of queueing of messages and delivery to client applications running on target devices, and it is completely free.


text:
Q: Как удалить файлы старше одного месяца? Необходимо удалить файлы, старше одного месяца, но необходимо удалять те, которые созданы больше месяца назад, к примеру, файл может быть изменен сегодня, но создан более месяца назад, скрипт должен удалить этот файл, нужно использовать.bat

A: В системах Vista и новее, идет утилита forfiles, которая позволяет перебрать все файлы по заданным критериям
forfiles /p . /s /m *.* /d -31 /c "cmd /c del @file"

Данная команда удалит (cmd /c del @file) все файлы (/m *.*) из текущего каталога (/p .), старше, чем 31 день /d -31
Для WinXP можно использовать forfiles.exe из новых систем.
Второй способ - парсить вывод команды dir


text:
Q: Summoning Bitbucket personal repo to Careers profile does not link We have an option to link our personal repositories to our profile but when I try to link my personal Bitbucket repository to my profile - it does not show a link to my repository.
This feature was working fine 2-3 weeks back. Recently something has changed due to which the link to the personal repository is not showing up.

A: Allowing listing of private repositories was initially an oversight.
This has now been corrected where we no longer list anything on a public CV that's not publicly visible.


text:
Q: Android Element similar to MAP ELEMENT in HTML Is it possible to replicate the MAP element of HTML ( http://www.w3schools.com/tags/tryit.asp?filename=tryhtml_areamap ) in android. If so how ? I plan to put the touch event on the image and get the co ordinates of the place where the click happened. But I feel this is not a proper solution if the image is something like this
http://www.channel4.com/media/images/Channel4/c4-news/2014/March/27/27_solar_system_r_w.jpg
then it would be a problem for me.

A: The question asked here is pretty much what you want, assuming your not trying to do it with html / webviews, and has a simple and straightforward answer that works.


text:
Q: How to actually clone a div but the duplicated div has different content I know how to duplicate div but the question is how can I make another duplicated div a different text.
Let's say I have a JSON file with the different contents that looks like this.
I will call the first file game1.json.
{
    "game": {
        "name": "Something...",
        "description": "smol"
    }
}

And the second one I call it game2.json
{
    "game": {
        "name": "Hello World",
        "description": "Hi"
    }
}

The main JSON code will parse those 2 JSON for the divs
{
    "library": {
        "game1": "apps/game1.json",
        "game2": "apps/game2.json"
    }
}

After the parse is complete, I wanna duplicate a div of game1 for game2 but with a different content as described from game2.json. The problem is, how do I do it?

A: Create html template with div id and name from json key game1 and game2
So two div will be created with id and name as game1 for first div and game2 for second div
Contents of div will be from json file


text:
Q: Product of elements in a list in GAP I just started learning GAP and I'm trying to do simple exercises.
The following problem is something I have not been able to figure out.
So I found the character degrees of $S_4$ using the following code:
CharacterDegrees(CharacterTable($"S_4"$));
Now this gives the output [ [ 1, 2 ], [ 2, 1 ], [ 3, 2 ] ]
, which means that there are two irreducible character of degree 1, one irreducible character of degree 2 and two irreducible characters of degree 3. I want to calculate the product of irreducible character degrees from this list. i.e., I want to calculate 1.1.2.3.3 directly from this list. Is there a command or a function that can be used in a situation like this?
Thak you!

A: I don't know if there's any inbuilt function to do this, but you could easily make one as follows:
myFunction := function( L )
    return Product( List( L, x -> x[1]^x[2] ) );
end;

You can then use it like this:
gap> L := CharacterDegrees( CharacterTable( "S4" ) );
[ [ 1, 2 ], [ 2, 1 ], [ 3, 2 ] ]
gap> myFunction( L );
18


text:
Q: aldryn-search for Django CMS to search full text How this could be done?
For now I get only indexes that are addressed to the page titles. Like cms.title objects are indexed.
I have add the app like intended:
    #settings.py
    #TODO: It's not recommended for production use but it will return results.
    HAYSTACK_CONNECTIONS = {
        'default': {
            'ENGINE': 'haystack.backends.simple_backend.SimpleEngine',
        },
    }
    HAYSTACK_ROUTERS = ['aldryn_search.router.LanguageRouter', ]
    ALDRYN_SEARCH_REGISTER_APPHOOK = True

Is there any trigger that I'm unaware of?

A: Though it's a old question, i hope this may help other people
I also added
INSTALLED_APPS = [ 'aldryn_search', 'spurl', 'haystack', 'standard_form' ]
see Mention that the aldryn search view requires standard_form #87


text:
Q: Problemas com lógica (&& ou ||) Achei estranho o código que está em meu sistema:
if (cmbCdTipoProcesso.SelectedValue != "3" && cmbCdTipoProcesso.SelectedValue != "4")
{....}

Aparentemente o código está estranho, pois eu nunca vou ter cmbCdTipoProcesso.SelectedValue = 3 ou cmbCdTipoProcesso.SelectedValue = 4 e assim por diante, aí eu pensei: Então porque a lógica AND e não a OR?
Voltando para eletrônica, tratando de álgebra booleana, numa lógica AND eu tenho uma saída 1 quando todas as entradas forem 1, caso o contrário a saída será sempre 0, mas aplicando à programação.
Parece que a situação nunca vai acontecer ou eu estou errado? Situação do if.

A: Leia de novo olhando caractere por caractere. Sua leitura do código, de acordo com a explicação que você escreveu abaixo dele está levando em consideração que está vendo se ambos são iguais a 3 e 4 ao mesmo tempo. De fato isto é impossível acontecer.
O problema é que o código está verificando se ambos são diferentes de 3 e 4. E isto é perfeitamente possível.
OU seja, este código está pegando qualquer valor exceto os que sejam 3 e 4.
Por alguma razão o código precisa que excluir estes valores. Não sei se é óbvio porque precisa desconsiderar estes valores para a ação. Por isto é importante comentar código, ou melhor ainda, escrever código que mostre porque está fazendo isso.
Neste caso estaria errado se usasse o || já que sempre daria verdadeiro. Assim como um número nunca pode ser igual a outro diferente, um número sempre será diferente de outro.
Fiz uma tabela de resultados tentando fazer diversas comparações com a mesma variável e valores diferentes.
using static System.Console;

public class Program {
    public static void Main() {
        var x = 1;
        WriteLine(x == 1 || x == 2);
        WriteLine(x == 1 || x != 2);
        WriteLine(x != 1 || x != 2);
        WriteLine(x == 1 && x == 2);
        WriteLine(x == 1 && x != 2);
        WriteLine(x != 1 && x != 2);
        WriteLine(x == 3 || x == 2);
        WriteLine(x == 3 || x != 2);
        WriteLine(x != 3 || x != 1);
        WriteLine(x == 3 && x == 2);
        WriteLine(x == 3 && x != 2);
        WriteLine(x != 3 && x != 2);
    }
}

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.

A: É muito mais fácil resolver este problema matematicamente, simplesmente substituindo os teus longos nomes de variáveis com letras tipo A ou B, substituindo o símbolo && com um simples and ou AND ou e, (e ignorando, por motivos práticos, que "3" e "4" são strings). No teu caso temos:
cmbCdTipoProcesso.SelectedValue != "3" && cmbCdTipoProcesso.SelectedValue != "4"

Que traduzido mais simplesmente quer dizer:
A != 3 e A != 4

Ou seja:
A é diferente de 3 e A é diferente de 4

*

*Supõe A é 3.
Vamos là valutar a expressão:
A é diferente de 3 e A é diferente de 4
A expressão em cima vai ser valutada falsa, porque A = 3, mesmo que A != 4.

*Se A fosse 4, seriamos na mesma situação.

*Só no caso em que A é diferente ao mesmo tempo de 3 e 4 é que o bloco do teu if vai ser executado.

Num caso mais geral, onde tempos A e B a ser valutados:
if A != 3 e B != 4

ou seja, segundo uma das leis de De Morgan:
if !(A == 3 ou B == 4)

ou seja, em português:
se não (A igual a 3 ou B igual a 4)

Ou seja o bloco do if vai ser executado quando a situação entre parêntesis é falsa (porque a negação de falso é verdadeiro), ou seja todos os casos em que A é diferente de 3 e B é diferente de 4 ao mesmo tempo, por exemplo:
A = 2 // A é diferente de 3
B = 7 // B é diferente de 4

Se A é igual a 3 ou B é igual a 4, ou os dois, a expressão do if não vai ser considerada verdadeira. Repito, A tem que ser diferente de 3 e B tem que ser diferente de 4, se não o bloco do if não vai ser executado.

A: O que esse trecho nos diz é que o valor selecionado deve ser diferente de 3 E diferente de 4.
Lembrando que o operador lógico != significa diferença e não igualdade.
Uma outra forma de escrever a mesma lógica seria igual a: valor < 3 && valor > 4,são duas maneiras diferentes de construir a mesma roda....
Quanto a outra dúvida de lógica booleana, eu não entendi aonde você quis chegar, poderia explicar melhor?
--EDIT, o que o @Maniero disse está correto, a utilização do || nesse caso seria equivocado, porque tiraria a unicidade da condição.


text:
Q: Android Email Intent doesn't populate recipients I am having an issue with Email Intent in Android.
The recipients field is not populating properly.
My code is as such:
Extensions.kt
// Returns a Mail Intent
fun requireMailIntent(subject: String, body: String) = Intent(Intent.ACTION_SENDTO).apply {
    data = Uri.parse("mailto:")
    putExtra(Intent.EXTRA_EMAIL, arrayOf("email@gmail.com"))
    putExtra(Intent.EXTRA_SUBJECT, subject)
    putExtra(Intent.EXTRA_TEXT,body)
}

/**
 *  Checks whether the intent has an app that can
 *  handle it.
 *  Should be called before starting an intent
**/
fun Intent.hasSuccessor(context: Context) = resolveActivity(context.packageManager) != null

Fragment.kt
// Submit button
    binding.ButtonSubmit.setOnClickListener {
        val emailConstruct = constructEmail()
        val intent = requireMailIntent(emailConstruct.first, emailConstruct.second)
        if(intent.hasSuccessor(requireContext())){
            Log.v("INTENT_TEST", "Launching Intent")
            startActivity(intent)
        }else{
            Log.v("INTENT_TEST", "No app found")
        }
    }

private fun constructEmail(): Pair<String,String>{
    val subject = "MES :: Bug Report :: ${viewModel.bugIdentified}"
    val message = "Below are the steps \n ${viewModel.bugSteps}"

    return Pair(subject, message)
}

Manifest.xml
<!-- For basic package querying, ie browsers, email... -->
<uses-permission
    android:name="android.permission.QUERY_ALL_PACKAGES"
    tools:ignore="QueryAllPackagesPermission" />

Gradle
    // SDK Versions
    sdk_compiled_version = 30
    sdk_minimum_version = 24

    // Build tools
    build_tools = "29.0.3"

Upon clicking the button, Android shows me the app chooser, but when i click Gmail, everything populates except the recipients field.
Can someone please help ?

A: Try using URI
val uriText = "mailto:contact@example.com" +
            "?subject=" + "your subject here" +
            "&body=" + body
    val uri = Uri.parse(uriText)
    val sendIntent = Intent(Intent.ACTION_SENDTO)
    sendIntent.data = uri
    startActivity(Intent.createChooser(sendIntent, "Send Email").addFlags(FLAG_ACTIVITY_NEW_TASK))


text:
Q: .vbp could not be loaded and NOT in notepad neither As of yesterday, my vbp file refuses to open '.vbp could not be loaded'. If i try to open the individual forms, some of them work (open in vb6), some of them produce error .log file with two class errors : Class TabDlg.SSTab of control mstTabArticles was not a loaded control class. Line 3672: Class MSComCtl2.DTPicker of control dtpTicketDate was not a loaded control class.
I cannot open the vbp in notepad neither (=empty) and in wordpad i only get small squares...
Any help please?

A: Your .vbp file is corrupt. You will either need to restore from your backup or source control (you do have both of those don't you?).
Failing that, you will need to recreate the project file from scratch and readd each of the forms. You'll need to figure out what controls and references were loaded though.
As for the errors when loading the form files, this is normal as the controls have not been added to the project.

A: One other possibility is to open your file with a hex editor.  You may be able to rescue a good deal of the text from the corrupt file and copy it to a new one.


text:
Q: Proving the existence of a bridge in a tree Let $G$ be a connected graph, and let $e \in E(G)$. Prove that $e$ is a bridge if and only if every spanning tree of $G$ contains $e$.
Can someone help me with this please? Thank you!

A: Suppose $e$ is a bridge  in $G$ and $T$ a spanning tree on $G$ not containing $e$. Then, since $T$ is a tree, it must be connected, but since $T$ is a subgraph of $G\setminus\{e\}$, a disconnected graph, it must be disconnected. Therefore, any spanning tree contains every bridge.
Now suppose $e$ is not a bridge. Then $G\setminus\{e\}$ is still connected, and so has a spanning tree $T$. However, since $G\setminus\{e\}$ has the same vertices as $G$, $T$ is also a spanning tree of $G$ that does not contain $e$. Therefore, any edge in every spanning tree is a bridge.


text:
Q: Partial function matching a type erased type In following code I want the hitA to be called only when the type of i is A. The type to check is provided as a type parameters, therefore it is type erased and a match fails on it, giving me a compiler warning:

abstract type pattern T is unchecked since it is eliminated by erasure

The desired output of the code is:

Hit A
Not hit

In current version when I run the code I get Hit A followed by a ClassCastException.
I understand what is happening and why the warning and the exception is there, but I am not sure how to get around this. I have read basic articles on TypeTags and I understand how to use them in basic cases, but I fail to see how could I create a partial function using TypeTags.
import scala.reflect.runtime.universe._

object TestMatch extends App {
  abstract class I

  class A extends I {
    def hitA() = println("Hit A")
  }

  class B extends I

  def processOpGen[T <: I : TypeTag](op: PartialFunction[I, Unit])(i: I) = {
    val fallback : PartialFunction[I, Unit] = {case _ => println("Not hit")}
    (op orElse fallback)(i)
  }

  def partialMatchGen[T <: I : TypeTag](op: T => Unit)(i: I) = {
    processOpGen[T] {
      case c: T => op(c) // can TypeTag be used here for matching somehow?
    }(i)
  }

  partialMatchGen[A](a => a.hitA())(new A)
  partialMatchGen[A](a => a.hitA())(new B)

}

A: Just replace TypeTag with ClassTag:
import scala.reflect._

object Main extends App {
  abstract class I

  class A extends I {
    def hitA() = println("Hit A")
  }

  class B extends I

  def processOpGen[T <: I : ClassTag](op: PartialFunction[I, Unit])(i: I) = {
    val fallback : PartialFunction[I, Unit] = {case _ => println("Not hit")}
    (op orElse fallback)(i)
  }

  def partialMatchGen[T <: I : ClassTag](op: T => Unit)(i: I) = {
    processOpGen[T] {
      case c: T => op(c) // can TypeTag be used here for matching somehow?
    }(i)
  }

  partialMatchGen[A](a => a.hitA())(new A)
  partialMatchGen[A](a => a.hitA())(new B)
}

Processing...
Reused last reload result
[info] Loading project definition from /tmp/rendererL3zBdh8HOA/project/project
[info] Loading project definition from /tmp/rendererL3zBdh8HOA/project
[info] Set current project to rendererWorker (in build file:/tmp/rendererL3zBdh8HOA/)
[info] Reapplying settings...
[info] Set current project to rendererWorker (in build file:/tmp/rendererL3zBdh8HOA/)
[info] Formatting 1 Scala source {file:/tmp/rendererL3zBdh8HOA/}rendererWorker(compile) ...
[warn] Scalariform parser error for /tmp/rendererL3zBdh8HOA/src/main/scala/test.scala: Expected token RBRACKET but got Token(XML_START_OPEN,<,335,<)
[info] Compiling 1 Scala source to /tmp/rendererL3zBdh8HOA/target/classes...
[success] Total time: 11 s, completed Oct 13, 2015 5:16:45 PM
Now running...
[info] Running Main
Hit A
Not hit
[success] Total time: 0 s, completed Oct 13, 2015 5:16:45 PM


text:
Q: Flash and Accessibility As a web developer, a number of the projects I work on fall under government umbrellas and hence are subject to 508 Accessibility laws, and sometimes W3C accessibility guidelines. To what extent can Flash be used while still meeting these requirements?
For using javascript, the mantra is "Degrade gracefully" by providing the same content and function, just on different pages, or in a less interactive/dynamic way. This allows non-javascript browsers/users still use the site, as well as allowing search engine bots to access all of the content. Users of screen reading software, such as JAWS and Orca also are still able to fully use the site.
With flash, is there a similar way to gracefully fall back for non-flash users? If not, how accessible is flash-based content to search engine bots? And also, how do screen readers handle flash-based content?

A: I'm a totally blind user of Jaws and the short answer is it depends. For example on YouTube I can access the mute and play/pause buttons. Things such as sliders however don't work. I don't think Flash will determine how accessible your site is if coded properly nearly as much as the content itself will. For example, if you need to play videos, is there enough narration so that a blind individual can follow the video? If you are displaying charts, is there a textual description of that data? I agree with the poster who said to use JavaScript / JQuery if possible, but for things such as videos that need Flash you can make it accessible enough to do things like mute the video, stop the video, etc.

A: I'm visually impaired to the point where I use magnification tools and TTS for convenience but not as a necessity. I can tell you that Flash just doesn't work with the majority of accessibility tools out there.  I believe JAWS (the market leader for Windows but not overwhelmingly dominant by any means) says it has Flash support, but most Flash developers don't seem to put in the work necessary to allow JAWS to grok the textual content of the Flash movie.  And many visually impaired users just don't even have flash installed because for 95%+ of the time it's simply useless to them.
Another consideration is that the built-in Text-to-speech that Mac OS X provides also can't do anything with most Flash movies.
IMO 'degrading' or offering a link to an HTML version of your content is probably the only practical means of ensuring your site is accessible.  If you are starting from scratch I would strongly consider JavaScript / JQuery over Flash if at all possible.

A: Flash can be made accessible to visually impaired, but it takes some time and effort. It's not automaticly a no-go area. It's still important to check if the different browsers play along with flash in this way, as Alxp notes.
There is one additional problem with flash: it steals the keyboard shortcuts. With a piece of flash on the page, many standard browser keyboard controls stop functioning. These shortcuts are very important to people with mouse-problems, and people who prefer the keyboard for any other reason.

A: If you're using Flash for things like navigation, then I would beg you on bended knee to use HTML and CSS instead. They degrade more gracefully, not just for people using site readers, but also to people who:

*

*Are on slower connections (like tethered phones)

*Have Flash turned off

*Are on a computer where Flash isn't installed, and they don't have admin rights

*Their version of Flash is terribly outdated, and they can't/won't update.

However, if you're creating something like a game, where Flash is vital, there are a few tips I have for the hearing impaired:

*

*If you use bells or sounds in your game to indicate a game event, add an option to turn this into a visual bell.

An example of this would be in the game Plants vs. Zombies. I played it with the sound off for months (I usually had music playing in the background). I didn't realize that some zombies were announced by sounds several seconds before they appeared. This made the game harder for me.

*

*If you have audio instructions, please put them in text as well. This goes for videos as well! A text-over is better than a text file next to the game/video, as it can be difficult to pair up the visual with the audio.


text:
Q: scrapy response is nothing like the page source I am trying to using scrapy shell to get in "ykc1.greatwestlife.com" which should be a public website, though there are lots of things if I look at page source manually, I can not get a correct response using scrapy.
scrapy shell response result
Do I need to use scrapy-splash in this case?
any ideas? Thanks

A: You can actually see the two back-to-back requests, caused by
      <head>
        <script language="javascript">
            document.cookie = "cmsUserPortalLocale=en;path=/";
            document.cookie = "cmsTheme=advgwl;path=/";
            document.cookie = "siteBrand="+escape(location.hostname)+"; path=/";
            window.location.reload(true);
        </script>

where the first request is substantially smaller, and likely causing what you're experiencing. Thankfully, since the cookies appear to be static, you can reproduce that behavior quite easily:
def parse(self, response):
    # this is required because the response that arrives to parse()
    # has session cookies but we need to add 3 more to them
    new_cookies = {
      "cmsUserPortalLocale": "en",
      "cmsTheme": "advgwl",
      "siteBrand": "ykc1.greatwestlife.com",
    }
    yield response.follow(url=request.url, cookies=new_cookies,
                          callback=self.parse_home)

def parse_home(self, response):
    # and now you have the full body


text:
Q: Escape # in Rails link_to, Twitter Share link I'm trying to include an anchored article link in a Twitter share link dynamically with Rails link_to method:
<%= link_to "http://twitter.com/home?status=Check Out #{article.title} link.com/#{article.title.parameterize}" do %>

<% end %>

The Twitter link share content outputs to:

Check Out ARTICLE TITLE link.com/ARTICLE-TITLE.

The thing is I want to add a # character before ARTICLE-TITLE, as it is an anchor link in my view. I just can't seem to get the # to escape properly. Is this even possible?

A: %23 = # (in a Twitter share link).
ex. link.com/%23#{article.title.parameterize}
Looks like it's rendered as a hashtag (#thattookwaytoolongtofigureout #ihopethishelpssomeone)

A: In general it's a bad idea to build URLs with string concatenation—especially when you need to do something like put a URL in a query parameter of another URL.
To create correctly-encoded query parameters, use Rails' handy Hash#to_query method.
Let's take it from the inside out.
# Build the article URL
article_base_url = 'http://example.com/path'
article_url_hash = article.title.parameterize # => "my-article"
article_url = "#{article_base_url}##{article_url_hash}"
# => "http://example.com/path#my-article"

# Next, build the query string for the tweet URL
tweet_url_query = {
  status: "Check out #{article.title} #{article_url}"
}.to_query
# => "status=Check%20out%20My%20Article%20http%3A%2F%2Fexample.com%2Fpath%23my-article"

# Finally, build the tweet URL:
base_tweet_url = 'https://twitter.com/home'
tweet_url = "#{base_tweet_url}?#{tweet_url_query}"
# => "https://twitter.com/home?status=Check%20out%20My%20Article%20http%3A%2F%2Fexample.com%2Fpath%23my-article"

<%= link_to tweet_url do %>

<% end %>

As perhaps you've already guessed, it's probably best to put this all in a helper:
ARTICLE_BASE_URL = 'http://example.com/'
TWEET_BASE_URL = 'http://twitter.com/home'

def tweet_url(title)
  query = { status: tweet_text(title) }.to_query
  "#{TWEET_BASE_URL}?#{query}"
end

def tweet_text(title)
  "Check out #{title} #{article_url(title)}"
end

def article_url(title)
  "#{ARTICLE_BASE_URL}##{title.parameterize}"
end

<%= link_to tweet_url(article.title) do %>

<% end %>

(You could, of course, reduce the above to a single two-line helper at the expense of readability and testability, but it would be a mistake.)


text:
Q: Additional key/value pair does not appear when added to an Object When I try to add status to participant, status is not available inside the participant. But when I log participant.status, it does contain the value.
May I know what the potential problem causing it?
exports.getMyInvitationParticipants = async function(req) {
    const invitation = await getMyInvitation(req)
    const participants = invitation.participants
    for (let index = 0; index < participants.length; index++) {
        var participant = participants[index]
        const member = await Member.findOne({ loginId : participant.phoneNumber })
        if (member) {
            const memberInvitation = await MemberInvitation.findOne({ memberId : member._id })
            if (memberInvitation) {
                participant.status = memberInvitation.status

                console.log(participant.status)
                console.log(participant)
            }
        }
    }
    return participants
}

router.get('/invitation/my/:invitationId/participants', authenticate, async (req, res) => {
    try {
        const participants = await invitationController.getMyInvitationParticipants(req)
        return res.send(participants)
    } catch (err) {
        return res.send(err)
    }
})

console.log output
PENDING <---- participant.status
{
  _id: 5ce113e21c6fc1549c4221ad,
  name: 'Dummy name'
}

A: Given the result as pending, I believe memberInvitation.status to be an unresolved promise.
So, try adding await before the memberInvitation.status as you want the value and not the promise itself.
    if (memberInvitation) {

        participant.status = await memberInvitation.status

Updated code :
exports.getMyInvitationParticipants = async function(req) {
const invitation = await getMyInvitation(req)
const participants = invitation.participants
for (let index = 0; index < participants.length; index++) {
    var participant = participants[index]
    const member = await Member.findOne({ loginId : participant.phoneNumber })
    if (member) {
        const memberInvitation = await MemberInvitation.findOne({ memberId : member._id })
        if (memberInvitation) {
            participant.status = await memberInvitation.status

            console.log(participant.status)
            console.log(participant)
        }
    }
    }
    return participants
}
router.get('/invitation/my/:invitationId/participants', authenticate, async (req, res) => {
    try {
        const participants = await invitationController.getMyInvitationParticipants(req)
        return res.send(participants)
    } catch (err) {
        return res.send(err)
    } })

A: It turns out, schema of invitation.participants lack of status. So when I try to assign status to participant, it does not work.
I've come out a solution to solve that.
exports.getMyInvitationParticipants = async function(req) {
    const invitation = await getMyInvitation(req)
    const participants = invitation.participants.map((participant) => {
        return {
            _id : participant._id,
            name : participant.name,
        }
    })
    for (let index = 0; index < participants.length; index++) {
        const participant = participants[index]
        const member = await Member.findOne({ loginId : participant.phoneNumber })
        if (member) {
            const memberInvitation = await MemberInvitation.findOne({ memberId : member._id })
            if (memberInvitation) {
                participant.status = memberInvitation.status
            }
        }
    }
    return participants
}


text:
Q: VIP and private IP on same NIC Is it possible to configure in the same NIC a VIP and a private IP (different) and both be enabled/accesible?
If yes, is there a guarantee that the communication path for these 2 IPs will be exactly the same?
Update: If this is possible, if I e.g. do a ping (or traceroute) from a specific machine will I always have the same route for both these 2 IPs?

A: You can have as many virtual IPs on the same physical device. On Linux you can create virtual interfaces for an IP (mostly) like this:
ifconfig eth0:0 10.10.10.42 netmask 255.255.255.0 up

or via /etc/network/interfaces
The route for every IP can be determined independently. Every IP can have a different default route. But you can ping in and out from every of this IPs

A: Having multiple IPs on a NIC is not an issue at all. You can use regular tools like ip addr add 1.2.3.4/24 dev eth0 and a configuration file would be distribution dependent.
The switch where your nic is connected will broadcast a "who has IP a.b.c.d" and your NIC will respond if it is one of the IPs it has. Receiving packets is not an issue.
The outgoing packets, however, are a different story. In response to a ping, the outgoing packet's source IP will be determined from the routing table (ip route show). This will be most likely based on the destination IP, and depending on which IP got pinged, you could have problems.


text:
Q: Set GridView selector default Within my Android app currently, I have a GridView that uses a custom adapter to populate it with multiple custom views.
This GridView is defined as follows:
<GridView
 android:id="@+id/grid"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:drawSelectorOnTop="false"
 android:isScrollContainer="false"
 android:listSelector="@drawable/selector"
 android:numColumns="3"
 android:stretchMode="columnWidth" />

As you can see, I have defined a custom 'List Selector' that allows users to see what item of the grid view they have selected.

What I want to know is the following, Is it possible that when the grid view is created using the custom adapter the List Selector can be set to a default value and be visible? (Currently the list selector only appears once a user has made a choice - obviously).

The custom GridView adapter is a simple adapter that extends BaseAdapter.
Many thanks


text:
Q: node.js referenceError variable is not defined I am trying to implement device groups in my node.js file to trigger notifications.
I want to get the token_id and create a notification_key for the device groups for a single user.
but i am getting the error as.
ReferenceError: options is not defined
at Object.<anonymous> (D:\SweExpress\functions\index.js:13:9)
at Module._compile (internal/modules/cjs/loader.js:678:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:689:10)
at Module.load (internal/modules/cjs/loader.js:589:32)
at tryModuleLoad (internal/modules/cjs/loader.js:528:12)
at Function.Module._load (internal/modules/cjs/loader.js:520:3)
at Module.require (internal/modules/cjs/loader.js:626:17)
at require (internal/modules/cjs/helpers.js:20:18)
at C:\Users\user\AppData\Roaming\npm\node_modules\firebase-tools\lib\triggerParser.js:21:11
at Object.<anonymous> (C:\Users\user\AppData\Roaming\npm\node_modules\firebase-tools\lib\triggerParser.js:61:3)

and my index.js file is.
'use-strict'

 const functions = require('firebase-functions');
 const admin = require('firebase-admin');
 var request = require('request');
 admin.initializeApp();
 var headers = {
 'Authorization': 'key =  my service account key here',
 'project_id': 'server_id',
 'Content-Type': 'application/json'
 }

 request(options, function (error, response, body) {
 console.log(body)
 })

 exports.sendNotification = functions.firestore.document("Users/  {user_id}/Notifications/{notification_id}").onWrite((change,context) => {

const user_id = context.params.user_id;
const notification_id = context.params.notification_id;

return admin.firestore().collection("Users").doc(user_id).collection("Notifications").doc(notification_id).get().then(queryResult => {

 const from_user_id = queryResult.data().from;
 const from_message = queryResult.data().message;

 const from_data = admin.firestore().collection("Users").doc(from_user_id).get();
 const to_data = admin.firestore().collection("Users").doc(user_id).get();

 return Promise.all([from_data, to_data]).then(result => {

     const from_name = result[0].data().name;
     const to_name = result[1].data().name;
     const token_id = result[1].data().token_id;

     var options = {
      url: 'https://android.googleapis.com/gcm/notification',
      method: 'POST',
      headers: headers,
      json: {'operation': 'create',
      'notification_key_name': 'you@example.com',
      'registration_ids': [token_id]}
      }

      request(options, function (error, response, body) {
      console.log(body)
      })

      var notificationKey = body;

     const payload = {
        notification: {
            title: "Notification From: " + from_name,
            body : from_message,
            icon : "notification.png",
            sound: "orion.mp3"
        }
     };
      return admin.messaging().sendToDeviceGroup(notificationKey,payload).then(result => {
      var c = console.log("Notification sent ");
        return c;

      });

 });

});

 });

I am new to node.js as well.
Secondly, is my index.js file correct? or I am doing something wrong?.

A: Your options object is defined after its first use:
request(options, function (error, response, body) {
  console.log(body)
})

Define
var options = { ...

before it is used in
request(options ...

Hope that helps :)

A: Without initializing variable named option, your are passing it as a parameter for the request. Thats why you are getting following error ReferenceError: options is not defined. Here I commented the unused part. checkout this snippet now
'use-strict'

 const functions = require('firebase-functions');
 const admin = require('firebase-admin');
 var request = require('request');
 admin.initializeApp();
 var headers = {
 'Authorization': 'key =  my service account key here',
 'project_id': 'server_id',
 'Content-Type': 'application/json'
 }

 /* Code which causes error
 request(options, function (error, response, body) {
 console.log(body)
 })*/

 exports.sendNotification = functions.firestore.document("Users/  {user_id}/Notifications/{notification_id}").onWrite((change,context) => {

const user_id = context.params.user_id;
const notification_id = context.params.notification_id;

return admin.firestore().collection("Users").doc(user_id).collection("Notifications").doc(notification_id).get().then(queryResult => {

 const from_user_id = queryResult.data().from;
 const from_message = queryResult.data().message;

 const from_data = admin.firestore().collection("Users").doc(from_user_id).get();
 const to_data = admin.firestore().collection("Users").doc(user_id).get();

 return Promise.all([from_data, to_data]).then(result => {

     const from_name = result[0].data().name;
     const to_name = result[1].data().name;
     const token_id = result[1].data().token_id;

     var options = {
      url: 'https://android.googleapis.com/gcm/notification',
      method: 'POST',
      headers: headers,
      json: {'operation': 'create',
      'notification_key_name': 'you@example.com',
      'registration_ids': [token_id]}
      }

      request(options, function (error, response, body) {
      console.log(body)
      })

      var notificationKey = body;

     const payload = {
        notification: {
            title: "Notification From: " + from_name,
            body : from_message,
            icon : "notification.png",
            sound: "orion.mp3"
        }
     };
      return admin.messaging().sendToDeviceGroup(notificationKey,payload).then(result => {
      var c = console.log("Notification sent ");
        return c;

      });

 });

});

 });


text:
Q: Referencing the instance of a generic type T Is it possible to return the instance of Generic type T when Animal class override Zoo class?
classInstance<T>() returns a type mismatch; required class<T> found T.
    private inline fun <reified Eat : T> classInstance(): Eat = Eat::class.java.newInstance()

    abstract class Animal<Result> {

        abstract fun bark(): Class<Result>

    }

    open class Zoo<T>(protected var listener: RequestListener<T>?) : Callback<T>, Animal<T>() {

        override fun bark(): Class<T> = classInstance<T>()
    }

bark() function will be use for the following purpose:
Gson().fromJson(inputStreamReaderResult, bark()) where, bark() must be of type Class


text:
Q: how to create one simple alert if crosser horizonal line? i tried my best to make it work but i get errors every time:(.. i just want to create a simple alert once the price start crossing up and crossing Down the Horizon Line by 2% will trigger the alert.. so far this is my code but i know that i missed up if you can please guide me to make it right
(Breakup and Breakdown is a Horizon Lines that i renamed)
//@version=3
study(title="Alert", overlay=true)

up  = Breakup(close, 2%)
down  = Breakdown(close, 2%)

alertcondition(condition=crossover(close, up), title="Cross Up", message="Breakup")

alertcondition(condition=crossunder(close, down), title="Cross Down", message="Breakdown")

A: Just calculate price + 2% and price - 2% and use those values in your cross conditions.
Say your target price is 100:
target_price = 100
per = 0.02  // 2%
target_up = target_price * (1 + per)
target_down = target_price * (1 - per)

is_cross_up = crossover(close, target_up)
is_cross_dwn = crossunder(close, target_down)

alertcondition(is_cross_up, "Cross Up")
alertconditino(is_cross_dwn, "Cross Down")


text:
Q: Change standard invoice address in checkout When customer add a new invoice address in checkout, this new address will be add as new address but ist not the standard for the next order. This is inconvenient, because normaly the invoice address only change after relocation.
How can I change the process, so that the last added invoice address is the standard for the next purchase?


text:
Q: Count the total number of bullets used in a word document I have a document in which there is text in bullets as well as numbers. I want to find the total number of bullets and numbers the word document has.
This is a sample text that i tried:
This is a bullet test for the word document
•   Lets work on this to play a game of fame
•   Light the bulb before the candle goes dark
•   Run like there is no tomorrow
I am also putting in numbers because I want to count bullets as well as numbers

*

*This is a number

*This is another number

*There are so many numbers

I have tried the following code:
my_file = "Bullet_test.docx"
    from docx import Document
    document = Document(my_file)
    styles = document.styles

Reading the bullets
from docx.enum.style import WD_STYLE_TYPE
   paragraph_styles = [
        s for s in styles if s.type == WD_STYLE_TYPE.PARAGRAPH
        ]
   paragraph_styles

I am getting the following output:
[_ParagraphStyle('Normal') id: 106125072,
    _ParagraphStyle('List Paragraph') id: 106126528]

I want to find the total number of bullets and numberings which should give me a total of 6 for the sample word document. Could you please let me know what am I doing wrong.

A: What you are doing wrong is trying to find a bullet by going over styles, even though, in your document, you have no style called Bullet or something like that.
If you want to use style to find bullets, you must have them defined as a style (by adding a style called "Bullet").
Here is what I did on my machine:

After that I ran this:
>>> d = Document(my_file)
>>> d.styles
<docx.styles.styles.Styles object at 0x026B4830>
>>> d.styles['Bullet'] # to check that indeed the style 'Bullet' exists
_ParagraphStyle('Bullet') id: 40587152
>>> for p in d.paragraphs:
...     if p.style.name == 'Bullet':
...             print '~'
...

and voila, 4 bullets were detected!
~
~
~
~

Adding a style could be done directly using Python, by (taken from here):
>>> from docx.enum.style import WD_STYLE_TYPE
>>> styles = document.styles
>>> style = styles.add_style('Citation', WD_STYLE_TYPE.PARAGRAPH)
>>> style.name
'Citation'
>>> style.type
PARAGRAPH (1)

and then applying it by:
>>> document = Document()
>>> paragraph = document.add_paragraph()
>>> paragraph.style
<docx.styles.style._ParagraphStyle object at <0x11a7c4c50>
>>> paragraph.style.name
'Normal'
>>> paragraph.style = document.styles['Heading 1']
>>> paragraph.style.name
'Heading 1'


text:
Q: Parse Promise to update multiple rows I want to update multiple rows in a class in Parse. I need to add a new field using "set". I tried saveAll and Promises in parallel to update, but these both are asynchronous. So they consume lot of resources and bandwidth.
How can I do that in a synchronous way. It would be better for me if you can answer using promises in series
Here is the code I'm using currently.But I need in a series way
Parse.Cloud.define("Updating",function(request,response){
    var query = new Parse.Query("FollowUp");
    query.find({
        success: function(results){
            for (var i = 0; i < results.length; i++) {
                results[i].set("testfield","sometext");
            }
            Parse.Object.saveAll(results,{
                success: function(list){
                    response.success("ok");
                },
                error: function(error){
                    response.error("failed");
                }
            });
        },
        error: function(error) {}
    });
});

A: This code is working fine and it is synchronous.
Parse.Cloud.define("Updating",function(request,response){
var query = new Parse.Query("FollowUp");
query.find().then(function(results) {
  var promise = Parse.Promise.as();
  _.each(results, function(result) {
    // For each item, extend the promise with a function to save it.
    result.set("newfield","somevalue");
    promise = promise.then(function() {
      // Return a promise that will be resolved when the save is finished.
      return result.save();
    });
  });

  return promise;

}).then(function() {
    response.success("working!!");
  // Every object is updated.
});

});

or you can even use "for" loop instead of _.each
Parse.Cloud.define("Updating",function(request,response){
var query = new Parse.Query("FollowUp");
query.find().then(function(results) {
  var promise = Parse.Promise.as();
  for(var i=0;i<results.length;i++){
    results[i].set("newfield","somevalue");
    promise = promise.then(function() {
      // Return a promise that will be resolved when the save is finished.
      return results[i].save();
    });
  });

  return promise;

}).then(function() {
    response.success("working!!");
  // Every object is updated.
});

});


text:
Q: ColVis Selection Appears Behind Bootstrap Modal I have the same issue as presented here:
jQuery Datatables Column list rendering behind the jQuery Modal Dialog
I have a DataTables table inside a Bootstrap modal window, and I am trying to use the ColVis extension to DataTables to make the columns selectable. When I click the Show Columns button, which is visible on the modal, nothing appears. However, when I close the modal I find the column list with a checkbox for each column sitting behind the modal.
The ColVis selection panel needs to be visible on top of the modal and needs to come and go with the modal.
I have altered the z-index property in three places in the file ColVis.css, multiplying each by a factor of 10:
div.ColVis_collectionBackground {
    background-color: black;
    /*z-index: 1100;*/
    z-index: 11000;
}

div.ColVis_collection {
    position: relative;
    width: 150px;
    background-color: #f3f3f3;
    padding: 3px;
    border: 1px solid #ccc;
    /*z-index: 1102;*/
    z-index: 11020
}

div.ColVis_collection button.ColVis_Button {
    background-color: white;
    width: 100%;
    float: none;
    margin-bottom: 2px;
}

div.ColVis_catcher {
    position: absolute;
    /*z-index: 1101;*/
    z-index: 11010;
}

(The original values are commented out.)
These alterations seem sufficient to me, but have had no effect. The z-index value of the Bootstrap modal is found in a file called bootstrap.css. Here is the class:
.modal {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 1040;
  display: none;
  overflow: auto;
  overflow-y: scroll;
}

Does anyone know what I need to do?

A: This is a z-index order problem.The old colVis extension is retired, try using colVis of buttons extension and if the problem still exists use the following code in your css:
 .dt-button-background {
   z-index: 1 !important;
  }
 .dt-button-collection {
   z-index: 2 !important;
  }


text:
Q: innetHtml property not getting the css I have a html page with two forms. For the first form css is working fine. The second form is rendering from property innerHtml. But css is not working for form2. May be this is a simple issue but i am getting stuck to find what is going wrong. Anyone please help me. I have attached an image of my html code..

A: You shouldn't concatenate each bit of HTML separately. Construct a string that contains the whole form, and assign that to .innerHTML. The reason is that the browser parses the HTML after each assignment to .innerHTML. If you have an unclosed tag, it will "fix" it by adding the closing tag. The result is that your <input> elements aren't inside the form.
var quiz = document.getElementById("quiz");
var question1 = "
Question 1
";
question1 += "<form id='form2'>";
question1 += "<input type='radio' name='choices' value='a'> A";
...
question1 += "</form>";
quiz.innerHTML = question1;


text:
Q: data.table: subset by observations in last 24 hours, per group Say I have a data.table that looks as follows:
dt = data.table(group = c(1,1,1,2,2,2,3,3,3),time = c("2016-03-09T08:31:00-05:00","2016-03-08T11:31:00-05:00","2016-03-06T08:31:00-05:00",
                                                "2016-04-04T23:28:00-04:00","2016-04-10T23:28:00-04:00","2016-04-09T23:28:00-04:00",
                                                "2016-05-11T19:52:00-04:00","2016-05-10T20:52:00-04:00","2016-04-11T19:52:00-04:00"))

dt
   group                      time
1:     1 2016-03-09T08:31:00-05:00
2:     1 2016-03-08T11:31:00-05:00
3:     1 2016-03-06T08:31:00-05:00
4:     2 2016-04-04T23:28:00-04:00
5:     2 2016-04-10T23:28:00-04:00
6:     2 2016-04-09T23:28:00-04:00
7:     3 2016-05-11T19:52:00-04:00
8:     3 2016-05-10T20:52:00-04:00
9:     3 2016-04-11T19:52:00-04:00

For each group in this data.table, I want to only retain the observations that are within 24 hours of the most recent date. I cooked up a nasty solution for this, but it's not nearly as fast as I need it to be on large datasets.
library(lubridate)
set(dt,j = "time",value = ymd_hms(dt[["time"]]))
dt[,.(mostRecent = max(time),time),by = group][
  time > (mostRecent - days(1)),.(group,time)]

   group                time
1:     1 2016-03-09 13:31:00
2:     1 2016-03-08 16:31:00
3:     2 2016-04-11 03:28:00
4:     3 2016-05-11 23:52:00
5:     3 2016-05-11 00:52:00

Does anyone have tips on how to accomplish more elegantly/faster?

A: First, put the thresholds in a table:
thresh_dt = dt[, .(time = max(time)), by=group][, time := time - 24*60*60][]

The max is taken separately from subtracting the day's worth of seconds to take advantage of the "GForce" optimized max. Also see ?datatable.optimize.
Next, do a rolling or non-equi join:
thresh_dt[dt, on=c("group", "time"), roll=TRUE, nomatch=0]

# or, on data.table 1.9.7+
thresh_dt[dt, on=.(group, time <= time), nomatch=0]

   group                time
1:     1 2016-03-09 13:31:00
2:     1 2016-03-08 16:31:00
3:     2 2016-04-11 03:28:00
4:     2 2016-04-10 03:28:00
5:     3 2016-05-11 23:52:00
6:     3 2016-05-11 00:52:00

Benchmark. The benefits of the GForce max and rolling only show up when you have enough groups. My example data extends @sbstn's so that the number of groups is a parameter:
N = 5e6
ng = 1e5

all_times = seq(from = as.POSIXct('2016-01-01 10:00:00'),
                to = as.POSIXct('2016-06-30 10:00:00'),
                by = 60)
all_times_int = as.integer(all_times)
idx = sample(seq.int(length(all_times)), N, replace = TRUE)
dt = data.table(group = sample(ng, N, replace = TRUE),
                time = all_times[idx],
                time_int = all_times_int[idx])

# sbstn, no gmax
system.time({
  dt[, cutoff_time := max(time) - 24*60*60, by = group]
  dt[time >= cutoff_time]
})
#    user  system elapsed
#    8.50    0.01    8.47

# sbstn, with gmax
system.time({
  dt[, maxtime := max(time), by = group][, cutoff_time := maxtime - 24*60*60]
  dt[time >= maxtime]
})
#    user  system elapsed
#    4.98    0.01    4.99

# gmax and roll
system.time({
  thresh_dt = dt[, .(time = max(time)), by=group][, time := time - 24*60*60]
  thresh_dt[dt, on=c("group", "time"), roll=TRUE, nomatch=0][, list(group, time)]
})
#    user  system elapsed
#    1.29    0.06    1.36
# (Caveat: I didn't verify that these results match.)

My answer involves grouping rows twice (once to calculate the max, and again to join back with the original data). By cutting this down to one grouping operation, Clayton Stanley's answer also manages to be fast (at least I think that's what's going on):
system.time(dt[order(group, -time)
    ][, groupP := shift(group, type='lag')
    ][, head := is.na(groupP) | group != groupP
    ][, copy(.SD)[.SD[head == T], rTime := i.time, on=c(group='group')]
    ][time > (rTime - 24*60*60)
    ][, .(group, time)
    ][order(group, -time)
    ])
#    user  system elapsed
#    1.32    0.25    1.14

A: Simple solution creating a cutoff time for each group (assuming time is already transformed):
dt[, cutoff_time := max(time) - 24*60*60, by = group]
dt[time > cutoff_time]

EDIT:
The comment on "GForce optimized max" made me curious, so I created some bigger fake data in order to compare speed. Note that integer plays nicely with both max and >=:
require(data.table)

require(microbenchmark)

N = 100000
N_g = 100

all_times = seq(from = as.POSIXct('2016-01-01 10:00:00'),
                to = as.POSIXct('2016-06-30 10:00:00'),
                by = 60)

all_times_int = as.integer(all_times)

idx = sample(seq.int(length(all_times)), N, replace = TRUE)

dt = data.table(group = sample(seq.int(N_g), N, replace = TRUE),
                time = all_times[idx],
                time_int = all_times_int[idx])

f1a = function (x) {
  x[, cutoff_time := max(time) - 24*60*60, by = group]
  x[time >= cutoff_time, list(group, time)]
}

f1b = function (x) {
  x[, cutoff_time := max(time_int) - 24*60*60, by = group]
  x[time_int >= cutoff_time, list(group, time)]
}

f2 = function (x) {
  thresh_dt = x[, .(time = max(time)), by=group][, time := time - 24*60*60]
  thresh_dt[x, on=c("group", "time"), roll=TRUE, nomatch=0][, list(group, time)]
}

microbenchmark(f1a(dt),
               f1b(dt),
               f2(dt))

Unit: milliseconds
   expr       min        lq      mean   median        uq       max neval
 f1a(dt)  9.842106 10.593243 11.593148 11.62311 12.478853 14.335338   100
 f1b(dt)  3.391178  3.763598  4.403264  4.00142  5.018182  8.335717   100
  f2(dt) 14.422669 15.701397 17.090674 16.56990 17.695653 52.926897   100

identical(f1a(dt), f1b(dt)) # TRUE
identical(f1a(dt), f2(dt)) # TRUE

EDIT 2:
And one more with N = 1,000,000 and N_g = 10,000 groups:
> microbenchmark(f1a(dt),
+                f1b(dt),
+                f2(dt),
+                times = 10)
Unit: milliseconds
    expr       min       lq      mean    median        uq      max neval
 f1a(dt) 634.91473 647.5662 670.74597 663.28238 694.29595 728.2481    10
 f1b(dt)  64.61488  67.3692  76.68925  68.42335  72.36862 113.1407    10
  f2(dt) 205.67688 208.6491 229.65610 213.59476 249.16703 278.7713    10

> microbenchmark(f1a(dt),
+                f1b(dt),
+                f2(dt),
+                times = 10)
Unit: milliseconds
    expr       min        lq     mean    median        uq       max neval
 f1a(dt) 620.11090 624.33587 645.0220 642.13648 657.74347 697.27674    10
 f1b(dt)  64.80214  67.43851  67.9140  67.99647  68.63552  69.74466    10
  f2(dt) 198.39200 199.56088 209.6908 204.60183 216.23255 241.76792    10

> microbenchmark(f1a(dt),
+                f1b(dt),
+                f2(dt),
+                times = 10)
Unit: milliseconds
    expr      min        lq      mean    median        uq      max neval
 f1a(dt) 619.2903 645.22617 656.58883 660.99508 664.82678 682.7618    10
 f1b(dt)  63.2454  67.31781  72.10255  68.19679  71.91441 106.7493    10
  f2(dt) 195.9335 210.06171 222.19868 215.75979 241.74100 245.9022    10

A: Probably the bottleneck is in the max(*), by computation. If so:
dt[order(group, -time)
   ][, groupP := shift(group, type='lag')
   ][, head := is.na(groupP) | group != groupP
   ][, copy(.SD)[.SD[head == T], rTime := i.time, on=c(group='group')]
   ][time > (rTime - 24*60*60)
   ][, .(group, time)
   ][order(group, -time)
   ]

   group                time
1:     1 2016-03-09 13:31:00
2:     1 2016-03-08 16:31:00
3:     2 2016-04-11 03:28:00
4:     3 2016-05-11 23:52:00
5:     3 2016-05-11 00:52:00
>


text:
Q: Faker Package, Database Seeder Issues I'm pretty deep down the rabbit hole on this one. This question is actually part of a bigger question related to getting my Laravel app to function correctly. Here's the link to the other question if you'd like to see more about my troubles: Model, Database Error in Laravel.
So, now I'm trying to use the database seeder package, Faker, to populate my database. I've installed it correctly, but I'm having trouble making it work for me beyond the User table. Here's what I've got for my UserTableSeeder:
class UserTableSeeder extends Seeder {

  public function run()
  {
    $faker = Faker\Factory::create();

    for ($i = 0; $i < 100; $i++)
    {
        User::create(
            [
                'id' => $faker->randomDigit,
                'first_name' => $faker->firstName,
                'last_name' => $faker->lastName,
                'email' => $faker->freeEmail,
                'notify' => $faker->randomElement($array = ['y', 'n']),
                'created_at' => $faker->dateTime($max = 'now'),
                'updated_at' => $faker->dateTime($max = 'now')
            ]
        );
    }
  }
}

This is half-working when I run php artisan db:seed; it creates only a dozen rows or so. My users table has seven columns:
id (its type is integer),
first_name(varchar),
last_name(varchar),
email(varchar),
notify(enum),
created_at(timestamp),
and updated_at(timestamp)
Any code that would handle this correctly or serve as a template for a similar table would be greatly appreciated. Thanks folks.

A: 'id' => $faker->randomDigit is likely causing conflicting IDs (I'd bet you get ten rows, not a dozen, as there are ten possible digits). Try $faker->randomNumber instead.

A: Migration: $table->increments('id');
Having this you don't need to set any value on the ID and you will avoid the id collision


text:
Q: SMART hard disk check has detected an imminent failure Since two years ago I have this problem. I have a HP Pavilion dm4 Notebook PC. Every time I turn on my laptop it comes a black screen like this one(I found it in Internet):

In this two years nothing have happened. Therefore, I would just like to know how to remove this screen, if it's possible, each time I boot my computer.

A: Your hard drive is indicating that it is failing. Although you have had two years of this, does not mean that space on the drive is not damaged, and the damage growing from being used to hold your data. It may be rewriting it to good sectors, until those sectors go bad and rewriting again.
You would most benefit from a new drive replacement. This will stop the error screen and maybe even boost performance if the drive has been doing a lot of rewriting.


text:
Q: java.lang.nullpointerexception error: app crashes I am having a problem with my app crashing after I press the button that activates my xml where my radio buttons are located.
The logcat says my error is java.lang.nullpointerexception.
I have included my logcat, java where error occurred, and manifest.
I originally had problems with my RadioButtons where the program allowed me to have them both checked and impossible to uncheck. When I changed around the coding to include the onCheckChange listener the app now crashes whenever I press a RadioButton.
07-17 18:09:37.067: W/dalvikvm(329): threadid=1: thread exiting with uncaught exception (group=0x40015560)
07-17 18:09:37.077: E/AndroidRuntime(329): FATAL EXCEPTION: main
07-17 18:09:37.077: E/AndroidRuntime(329): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.com.proto1/com.example.com.proto1.Voiceprompt}: java.lang.ClassNotFoundException: com.example.com.proto1.Voiceprompt in loader dalvik.system.PathClassLoader[/data/app/com.example.com.proto1-2.apk]
07-17 18:09:37.077: E/AndroidRuntime(329):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1569)
07-17 18:09:37.077: E/AndroidRuntime(329):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
07-17 18:09:37.077: E/AndroidRuntime(329):  at android.app.ActivityThread.access$1500(ActivityThread.java:117)
07-17 18:09:37.077: E/AndroidRuntime(329):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
07-17 18:09:37.077: E/AndroidRuntime(329):  at android.os.Handler.dispatchMessage(Handler.java:99)
07-17 18:09:37.077: E/AndroidRuntime(329):  at android.os.Looper.loop(Looper.java:123)
07-17 18:09:37.077: E/AndroidRuntime(329):  at android.app.ActivityThread.main(ActivityThread.java:3683)
07-17 18:09:37.077: E/AndroidRuntime(329):  at java.lang.reflect.Method.invokeNative(Native Method)
07-17 18:09:37.077: E/AndroidRuntime(329):  at java.lang.reflect.Method.invoke(Method.java:507)
07-17 18:09:37.077: E/AndroidRuntime(329):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
07-17 18:09:37.077: E/AndroidRuntime(329):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
07-17 18:09:37.077: E/AndroidRuntime(329):  at dalvik.system.NativeStart.main(Native Method)
07-17 18:09:37.077: E/AndroidRuntime(329): Caused by: java.lang.ClassNotFoundException: com.example.com.proto1.Voiceprompt in loader dalvik.system.PathClassLoader[/data/app/com.example.com.proto1-2.apk]
07-17 18:09:37.077: E/AndroidRuntime(329):  at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:240)
07-17 18:09:37.077: E/AndroidRuntime(329):  at java.lang.ClassLoader.loadClass(ClassLoader.java:551)
07-17 18:09:37.077: E/AndroidRuntime(329):  at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
07-17 18:09:37.077: E/AndroidRuntime(329):  at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
07-17 18:09:37.077: E/AndroidRuntime(329):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1561)
07-17 18:09:37.077: E/AndroidRuntime(329):  ... 11 more

    package com.example.com.proto1;

import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;

public class VoicePrompts extends Activity implements OnCheckedChangeListener {

    RadioButton on, off, onc, offc;

    // Button Sound
    MediaPlayer buttonSound1 = MediaPlayer.create(VoicePrompts.this, R.raw.vpo);
    MediaPlayer buttonSound2 = MediaPlayer
            .create(VoicePrompts.this, R.raw.vpof);
    MediaPlayer buttonSound3 = MediaPlayer
            .create(VoicePrompts.this, R.raw.vpoc);
    MediaPlayer buttonSound4 = MediaPlayer.create(VoicePrompts.this,
            R.raw.vpofc);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.voiceprompts);

        // Setting up the button references
        on = (RadioButton) findViewById(R.id.vbutton1);
        off = (RadioButton) findViewById(R.id.vbutton2);
        onc = (RadioButton) findViewById(R.id.vbutton1);
        offc = (RadioButton) findViewById(R.id.vbutton2);

        buttonSound1 = MediaPlayer.create(VoicePrompts.this, R.raw.vpo);
        buttonSound2 = MediaPlayer.create(VoicePrompts.this, R.raw.vpof);
        buttonSound3 = MediaPlayer.create(VoicePrompts.this, R.raw.vpoc);
        buttonSound4 = MediaPlayer.create(VoicePrompts.this, R.raw.vpofc);
    }

    public void onCheckedChanged(RadioGroup arg0, int checkedId) {
        // TODO Auto-generated method stub
        switch (checkedId) {
        case R.id.vbutton1:
            on.setOnLongClickListener(new View.OnLongClickListener() {

                public boolean onLongClick(View v) {
                    // TODO Auto-generated method stub
                    try {
                        buttonSound1.prepare();
                        buttonSound1.start();
                        startActivity(new Intent("android.intent.action.VPON"));

                    } catch (Exception e) {

                    }
                    return false;
                }
            });

            onc.setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    try {
                        buttonSound3.prepare();
                        buttonSound3.start();
                        startActivity(new Intent("android.intent.action.VPON"));
                    } catch (Exception e) {

                    }
                    ;

                }
            });

            break;
        case R.id.vbutton2:

            off.setOnLongClickListener(new View.OnLongClickListener() {

                public boolean onLongClick(View v) {
                    // TODO Auto-generated method stub
                    try {
                        buttonSound2.prepare();
                        buttonSound2.start();
                        startActivity(new Intent("android.intent.action.VPOFF"));
                    } catch (Exception e) {

                    }
                    ;
                    return false;

                }
            });

            offc.setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    try {
                        buttonSound4.prepare();
                        buttonSound4.start();
                        startActivity(new Intent("android.intent.action.VPOFF"));
                    } catch (Exception e) {

                    }
                    ;

                }
            });

            break;
        }

    }

}

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.com.proto1"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".mainj"
            android:label="@string/title_activity_mainj" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".menu"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MENU" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Infoactive"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.INFOSCREEN" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <activity
            android:name=".VoicePrompts"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.VOICEPROMPTS" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <activity
            android:name=".VPon"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.VPON" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <activity
            android:name=".VPoff"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.VPOFF" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
    </application>

</manifest>

package com.example.com.proto1;

import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class menu extends Activity {

    @Override
    protected void onCreate(Bundle aboutmenu) {
        // TODO Auto-generated method stub
        super.onCreate(aboutmenu);
        setContentView(R.layout.mainx);

        // Button Sound
        final MediaPlayer buttonSound = MediaPlayer.create(menu.this,
                R.raw.button_click);

        // Setting up the button references
        Button info = (Button) findViewById(R.id.aboutbutton);
        Button voice = (Button) findViewById(R.id.voicebutton);

        info.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                buttonSound.start();
                startActivity(new Intent("android.intent.action.INFOSCREEN"));

            }
        });

        voice.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                buttonSound.start();
                Intent voiceIntent = new Intent("android.intent.action.VOICEPROMPTS");
                startActivity(voiceIntent);
            }
        });

    }
}

A: Give Button Refrences after setContentView(R.layout.voiceprompts);
Like,
 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.voiceprompts);

         // Setting up the button references

            on = (RadioButton) findViewById(R.id.vbutton1);
            off = (RadioButton) findViewById(R.id.vbutton2);
            onc = (RadioButton) findViewById(R.id.vbutton1);
            offc = (RadioButton) findViewById(R.id.vbutton2);
    }

A: I think you have two Activity with name VoicePrompts and VoicePrompt. You declared VoicePrompts in menifest file. But your are calling VoicePrompt.
EDIT According to your new Problem
MediaPlayer buttonSound1,buttonSound2,buttonSound3,buttonSound4 ;
and init in onCreate
like
 @Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.voiceprompts);

    // Setting up the button references
    on = (RadioButton) findViewById(R.id.vbutton1);
    off = (RadioButton) findViewById(R.id.vbutton2);
    onc = (RadioButton) findViewById(R.id.vbutton1);
    offc = (RadioButton) findViewById(R.id.vbutton2);
    buttonSound1 = MediaPlayer.create(VoicePrompts.this,
        R.raw.vpo);
    buttonSound2 = MediaPlayer.create(VoicePrompts.this,
        R.raw.vpof);
    buttonSound3 = MediaPlayer.create(VoicePrompts.this,
        R.raw.vpoc);
    buttonSound4 = MediaPlayer.create(VoicePrompts.this,
        R.raw.vpofc);
}


text:
Q: Multiprocessing Python Class Object So I let's say I have a Python class:
class Something:
    def __init__(self, a, b, c):
        initialize_object_with_args()

    def run(self):
        do_something()

    def result(self):
        return result

Now I want to create multiple objects of that class (all of which are independent - no need for data exchange between the objects) and run them in parallel on a single PC with a multicore CPU...the only thing changing are the input arguments (a,b, c) for each run...
So I would need this:
results = []
[PARALLEL START]
    obj = Something(a, b, c)
    obj.run()
    results.append(obj.results())
[PARALLEL END]

I could then evaluate the results! I see that the multiprocessing module would be what I need but i don't know the specifics nor if it can do what I need nor how?
Quick Edit: I need to be able to do this with Python...no external modules...just the standard Python install...

A: Take a look at http://wiki.python.org/moin/ParallelProcessing , especially the http://pypi.python.org/pypi/pprocess .
This small library could do exactly what you want: http://honeypot.net/yet-another-python-map

A: It seems to be very similar to this
from multiprocessing import Pool

def func(*args):
    obj = Something(*args)
    obj.run()
    return obj.results()

pool = Pool()
results = pool.map(func, ((1,2,3), (4,5,6)))


text:
Q: Replace data in text file via Powershell I need replace the data in text file. The column name is "CODE" in the text file with UserA, UserB and UserC please refer to the image for data. Any assistance would be appreciated.
I have written replace script but it adds UserA twice (for e.g. useruserA) which I am not sure why. Any assistance would be appreciated. I also need to make the first name column uppercase.
  $output = C:\temp\txt
  Import-csv -path c:\temp\.csv | select-object *.@{
  Name = "CODE"
  Expression = {$_.CODE -replace("A", "UserA") -replace ("B","UserB") -
   replace("C","UserC")}
  } -excludeProperty CODE | export-csv -path output

A: -Replace will replace all occurrences in a string (AKA any the previous replacement result):
'aaa' -replace("A", "UserA")
UserAUserAUserA

I would use the switch statement for this:
Import-csv -path c:\temp\.csv |Select-Object *, @{
    Name = 'Code'
    Expression = {
        Switch ($_.Code) {
            'A' { 'UserA' }
            'B' { 'UserB' }
            'C' { 'UserC' }
        }
    }
} -excludeProperty CODE |export-csv -path C:\temp\txt


text:
Q: How to store an object (of a class type) in browser's storage and retrieve it? I want to have a page-reload proof class instances in my Angular 2 application.
In my component's .ts file I have classes:
export class AComponent implements OnInit {
  foo: Foo = new Foo();
  ngOnInit() {
    // This will always be 12, it would be nice if it would increase with each page refresh.
    this.foo.bar.baz += 1;
    console.log("baz: " + this.foo.bar.baz);
  }
}

class Bar {
  baz: number = 11;
}

class Foo {
  bar: Bar = new Bar()
}

I know that the localStorage ES6 thing can store strings. Do I have to write my own deserialization of complex class objects?
Like (I think) suggested here: Angular 2 map http response to instance of class

A: I would suggest with angular-2-local-storage node_module.
Steps:

*

*Install npm install angular-2-local-storage

*Make sure that the package is added in the config.js(systemjs or webpack)

*Import the module and service as below
import { LocalStorageModule,LocalStorageService} from 'angular-2-local-storage';

*Add the module to imports array and service to providers array as
 imports: [ BrowserModule,
   LocalStorageModule.withConfig({storageType: 'localStorage'}), ],

 providers:[LocalStorageService],

*Inject the Service as a dependency into component as below
constructor(private localStorageService: LocalStorageService) {
        this.name = 'Angular-2-Local-Storage-Demo';
        this.localStorageService.add('a',this.user);
        console.log(this.localStorageService.get('a'));
        this.valuFromLocalStorage= this.localStorageService.get('a')
}

LIVE DEMO

A: using localStorage you can do this:
import { Component, OnInit } from '@angular/core';
class Bar {
   baz: number = 11;
}
class Foo {
   bar: Bar = new Bar()
}
@Component({
  selector: 'a-component',
  template: `<br><button (click)='reset()'>Reset</button>`
})
export class AComponent implements OnInit{
  foo: Foo = new Foo();
  constructor(){
       this.incrementBaz()
  }
  ngOnInit(): void {
    this.foo = JSON.parse(localStorage.getItem('foo'))
    console.log('baz=', this.foo.bar.baz)
  }
  incrementBaz() {
    let old = JSON.parse(localStorage.getItem('foo'))
    if (old) {
        old.bar.baz += 1;
        localStorage.setItem('foo', JSON.stringify(old))
    }
    else {
        localStorage.setItem('foo', JSON.stringify(this.foo))
    }
  }
  reset() {
    this.foo = new Foo();
    localStorage.setItem('foo', JSON.stringify(this.foo))
    console.log('baz=', this.foo.bar.baz)
  }
}

with localStorage you can store whatever complex object you want.
hope this helps!

A: Your Problem
I am not understanding exactly what you are trying to do with the counter. So I went ahead and made you a real simple example of a way to manipulate your counter and save it to the localStorage.
In my example I show you how to save the data as JSON and how to handle it when you retrieve it.
My Solutions
I made a punker for you to play with till you get it done. You have to look at the Application tab in the dev tools when you inspect element. Then go to Storage. Then click on the run.plnkr.co storage link to see the counter saved to the localhost.
Link to Live Code
Please see the plunker here.
Make sure to look at the file /src/app.ts
Eyes on Example

Code Example
//our root app component
import {Component, NgModule, OnInit} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

@Component({
  selector: 'my-app',
  template: `

Hello {{name}}

  `,
})
export class App {
  foo: Foo = new Foo();
  ngOnInit() {
    // This will always be 12, it would be nice if it would increase with each page refresh.

    var counter = JSON.parse(localStorage.getItem('counter'));
    var tick = this.foo.bar.baz + counter + 1;
    localStorage.setItem('counter', JSON.stringify(tick));
    console.log('this is my tick ' + tick);
  }
}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

class Bar {
  baz: number = 11;
}

class Foo {
  bar: Bar = new Bar()
}


text:
Q: Запуск приложения без фокуса Есть необходимость в крошечном приложении, которое будет выполнять команду типа "Somepath\someApp.exe "someArguments" и сразу закрываться. Нужно сделать вызов таким образом, чтобы это не было заметно глазу. То есть, не появлялось никаких окон, не выпадал фокус из активного окна (даже если он будет сразу возвращаться). По задумке это элемент управления для rainmeter, который будет передавать некие аргументы в активные скины. Например во время игры горячей клавишей вызывается программа, и меняется позиция нужного скина на "поверх всех окон" без сворачивания самой игры. Я чет совсем тупенький, объясните на пальцах, пожалуйста, как это можно сделать. :( спасибо!

A: Пишите свою программу как стандартную оконную программу (не консольную!), но никаких окон не создавайте. Такая программа не будет видна ни на экране, ни в панели задач.
#include "windows.h"

int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) {
    // Разбираем командную строку в lpCmdLine (если надо)
    // Делаем здесь что надо делать
    return 0;
}


text:
Q: Is over provisioning working as expected on my Samsung SSD after reinstalling Windows 10 update 2004? After I reinstalled Windows 10 update 2004, I restarted the system see something strange. After the C partition is system restored the reserved parition, it was reconfigured to 10% of SSD before install OS.
Now in Samsung Magician I see something that seems strange to me regarding over provisioning. If I choose manual I can add more over provisioning at C partition at end. If I choose other drive there all as expected.
Question is if it worked as expected or I need reinstall the OS and after install create over provisioning for it work as normal; this is the way system restore reserved the partition to be at the end.
If it works and not be worried about it. Or this can work not as expected and better do all how need. And how I remembered older versions of Windows worked was to always create system reserved spaces at start at of disk, and C was always end partition. This why it confuse me.


text:
Q: Animate visibility modes when linearlayout visible I have linear layout like below
<LinearLayout
    android:id="@+id/pilihwaktu"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="125dp">

    <com.testing.CustomLinearLayout
        android:id="@+id/oneway"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:background="@drawable/field_background"
        android:padding="5dp"
        android:layout_weight=".50">

        ....
   </com.testing.CustomLinearLayout>

    <com.testing.CustomLinearLayout
        android:id="@+id/roundtrip"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:background="@drawable/field_background"
        android:padding="5dp"
        android:layout_weight=".50">

        ....

    </com.testing.CustomLinearLayout>

</LinearLayout>

and it will show view like this
+---------------+---------------+
|               |               |
|    oneway     |   roundtrip   |
|               |               |
+---------------+---------------+

I want to make the roundtrip is gone as the default and when the Checkbox is checked, I want to animate roundtrip so it will restore things to the above state (and oneway section will animate as it follows so it looks smooth). And when the checkbox is not checked roundtrip will animate to hide or gone
I've tried to follow this link but it wasn't animated and it looks like ObjectAnimator is simple way to do it...
What is the correct way to do this?

A: Easy way:
Firstly, add to your parent LinearLayout this attribute:
<LinearLayout
   android:id="@+id/pilihwaktu"
   ...
   android:animateLayoutChanges="true"
   ... />

And later set checked change listener in the code like this:
yourCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
       @Override
       public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
           roundTip.setVisibility(isChecked ? View.VISIBLE : View.GONE);
       }
});

More hard way:
This is for expand, it's simple to make it for collapse. Use this in the onCheckedChange, if it's checked
updateListener = new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                // Get params:
                final LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) roundTip.getLayoutParams();

                params.weight = (Float) animation.getAnimatedValue();
                roundTip.setLayoutParams(loparams);
                }
        };

animatorListener = new AnimatorListenerAdapter() {
    @Override
    public void onAnimationStart(Animator animation) {
        roundTip.setVisibility(View.VISIBLE);
    }
};

animator = ValueAnimator.ofFloat(0f, 0.5f);
animator.addUpdateListener(updateListener);
animator.addListener(animatorListener);
animator.setDuration(500);
animator.start();