text:
Q: Вывод на экран слов последовательности, которые отличны от последнего слова
Данная последовательность, содержащая от 2 до 20 слов, в каждом из которых от 1 до 8 строчных, между соседними словами - не менее одного пробела, за последним словом - точка.
Реализовать вывод на экран тех слов последовательности, которые отличны от последнего слова и удовлетворяют свойства симметричности.

Не могу понять, почему код работает не правильно:
Text=input("ведите слова")
print(Text,end=".")
if len(Text.split())>20:
    print()
    print("введите меньше слов")
elif len(Text.split())<2:
    print()
    print("введите больше слов")
Text_1=Text.split()
for i in Text_1:
    if i==Text_1[-1]:
        Text_1.remove(i)
    elif Text_1[0]==Text[-1]:
        Text_1.remove[0]
print()
print(Text_1,end=".")
print()
for b in Text_1:
    b=b.split()
    if b.reverse not in Text_1:
        Text_1.remove(b)#ValueError: list.remove(x): x not in list-ошибка
print(Text_1)

A: Главная проблема вашей программы (дважды):

*

*В цикле for проходите тот-же самым списком, из которого в нём удаляете члены и тем его изменяете.
Нужно проходить через копию списка (которую возможно просто получить созданием отрезка со всеми элементами , т.е. добавлением [:]за его имя.)
Вторая проблема - невозможно применить метод .reverse() к строке - сначала нужно её переводить в список символов (например функцией list()).
Но а третья - ваша программа всё равно работает тоже после ввода неправильного количества слов, только она выдает об этом сообщение. Нужно тогда снова (и снова) задать вопрос (в цикле while), пока количество слов не будет правильным.
Я немножко переработал вашу программу и использовал более удобные имена для переменных, только со строчными буквами - см. PEP 8 - руководство по написанию кода на Python - и вставил где-то пробелы (см. там-же).
while True:
    text = input("Ведите слова: ")
    words = text.split()

    if len(words) > 20:
        print("Введите меньше слов.")
        print()
        continue                        # прекратить, а снова задать вопрос
    elif len(words) < 2:
        print("Введите больше слов.")
        print()
        continue
    break                               # прекратить весь цикл

last_word = words[-1][:-1]              # [:-1] для удаления точки
words = words[:-1]                      # последнее слово уже не надо

for word in words[:]:                   # [:] строит копию списка
    if word == last_word:
        words.remove(word)

for word in words[:]:                   # [:] строит копию списка
    letters = list(word)
    letters.reverse()
    reversed_word = "".join(letters)
    if word != reversed_word:
        words.remove(word)

print(words)

Примечание:
Вместо пары команд
last_word = words[-1][:-1]              # [:-1] для удаления точки
words = words[:-1]                      # последнее слово уже не надо

можно применить команду
last_word = words.pop()[:-1]


text:
Q: Passing NSDictionary UIView objects to NSDictionaryOfVariableBindings/Autolayout If I assign a UIView to an NSDictionary and then try to recall its value in autolayout when setting constraints as here
UILabel *label = [[UILabel alloc] init];
NSDictionary *items = [[NSMutableDictionary alloc] init];
[items setValue:label forKey:@"label"];

[NSLayoutConstraint constraintsWithVisualFormat:@"|-[label]-|"
                                   options:0
                                   metrics:nil
                                   views:NSDictionaryOfVariableBindings(
                                      [items objectForKey:@"label"]
                                    )];

I get the following error
uncaught exception 'NSInternalInconsistencyException', reason: 'NSDictionaryOfVariableBindings failed because either one of the values is nil, or there's something wrong with the way the macro is being invoked.  Cannot assign value nil for key "objectForKey:@"label"]". Keys:(
"[items",
"objectForKey:@\"label\"]")'

I get the same thing if I try to pass an array objectAtIndex: element in also
Frustratingly it does work if I define it like this
[items setValue:NSDictionaryOfVariableBindings(label) forKey:@"label"];

But I'm trying to load my UIViews into a collection object (any collection object) and then be able to recall them when setting constraints
It's as though NSDictionaryOfVariableBindings is interpreting the literal text I'm passing rather than evaluating the statement

A:
It's as though NSDictionaryOfVariableBindings is interpreting the
  literal text I'm passing rather than evaluating the statement

This is exactly what is happening. If you command-click on NSDictionaryOfVariableBindings, you will see its definition as a macro that calls a private(ish) UIKit function in NSLayoutConstraint.h:
#define NSDictionaryOfVariableBindings(...) _NSDictionaryOfVariableBindings(@"" # __VA_ARGS__, __VA_ARGS__, nil)
UIKIT_EXTERN NSDictionary *_NSDictionaryOfVariableBindings(NSString *commaSeparatedKeysString, id firstValue, ...) NS_AVAILABLE_IOS(6_0); // not for direct use

The @"" # __VA_ARGS__ in the macro definition turns the list of passed arguments into a literal string, which is passed as the commaSeparatedKeysString parameter to the _NSDictionaryOfVariableBindings function.
The correct way to use NSDictionaryOfVariableBindings is to use locally-scoped variables, or _-prefixed ivars if applicable. If you don't want to do that, you can always make your own dictionary, using whatever literal string you want for the key and whatever value you want as the value. I often do this to rename my variables to something meaningful for the visual format language string. So, in your example:
UILabel *label = [[UILabel alloc] init];
NSMutableDictionary *items = [[NSMutableDictionary alloc] init];
[items setValue:label forKey:@"label"];

[NSLayoutConstraint constraintsWithVisualFormat:@"|-[label]-|"
                                   options:0
                                   metrics:nil
                                   // using Obj-C dictionary subscripting syntax
                                   views:@{ @"label" : items[@"label"] }];

Your example may be contrived, but in case it is not, the fact that UILabel *label is in scope means you could just pass NSDictionaryOfVariableBindings(label) for the views: parameter.
Edit: your items mutable dictionary is already correctly set up to just pass in as the views: parameter, if you want.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to apply texture to the material from script editor in the Spark AR I just want to recreate this kind of connections from the patch editor. Old API not support() but library not update too... So, I can't understand how to apply the 'cameraTexture' to the .DIFFUSE attribute of the material.

A: Are you just trying to set the Material texture through script? In that case you can just simply set the Material.diffuse property on the material to the texture you want to use.
See the documentation here: https://sparkar.facebook.com/ar-studio/learn/reference/classes/materialsmodule.materialbase


text:
Q: Erro ao gerar XML Fiz um sistema em PHP para exibir arquivo XML, mas está dando o seguinte erro:
This page contains the following errors:
error on line 29 at column 1: Extra content at the end of the document
Below is a rendering of the page up to the first error.
(A imagem pra que vejam que até o que é do banco ele me trás):

Meu arquivo index.php:
<?php

    include("config.php");
    include("conexao.php");

    $sql = 'select id, descricao, margem, custo, estoque from produtos';

    $resultado = mysqli_query(DBConnect(), $sql) or die (mysqli_error(DBConnect()));

    $xml = new DOMDocument('1.0', 'UTF-8');
    $xml->preserveWhiteSpace = false;
    $xml->formatOutput = true;

    $produtos = $xml->createElement('Produtos');

    while($dados = mysqli_fetch_object($resultado))
    {
        $item = $xml->createElement('Item');
        $descricao = $xml->createElement('descricao', $dados->descricao);
        $margem = $xml->createElement('margem', $dados->margem);
        $custo = $xml->createElement('custo', $dados->custo);
        $estoque = $xml->createElement('estoque', $dados->estoque);

        $item->appendChild($descricao);
        $item->appendChild($margem);
        $item->appendChild($custo);
        $item->appendChild($estoque);

        $produtos->appendChild($item);
    }

    $xml->appendChild($produtos);

    header('content-type: text/xml');
    print $xml->saveXML();

?>

<!DOCTYPE html>
<html>

    <head>

        <title> Testando conexão </title>

    </head>

    <body>

        <?php

            $teste = DBConnect();

            if($teste)
            {
                echo "Conectado com sucesso!";
            }
            else
            {
                echo "Conexão falhou!";
            }

        ?>

    </body>

</html>

Meu arquivo config.php:
<?php

    define('HOSTNAME', '127.0.0.1');
    define('USERNAME', 'root');
    define('PASSWORD', null);
    define('DATABASE', 'cadastro');
    define('CHARSET' , 'utf8');

?>

Meu arquivo conexao.php:
<?php

    function DBConnect()
    {
        $sql = mysqli_connect(HOSTNAME, USERNAME, PASSWORD, DATABASE) or die(mysqli_error());
        mysqli_set_charset($sql, CHARSET) or die(mysqli_error($sql));

        return $sql;
    }

?>

A: Como a própria descrição do erro informa, você está inserindo informações alheias extras após criar o XML a partir da linha <!DOCTYPE html>.
Para parsear o XML corretamente, remova tudo que estiver da linha <!DOCTYPE html> para baixo. Se remover a linha header('content-type: text/xml'); o erro some, mas você terá como resultado uma página HTML normal (embora inválida).


text:
Q: iOS Font closest to MS Song font What font on iOS is closest to the MS Song font on Windows?  I'm trying to create a cross platform program, but I want it to be able to format nicely so i'm looking for a similar font.
Thanks in advance!

A: You can use any font in iOS app.
To use any font you need .TTF file.
You can get font file for MS song font from this link: MS Song Font
Click on Download button and you will get .ZIP file which contan .TXT and .TTF file
You can use this .ttf file with just two step

*

*Make configuration in info.plist to add this .ttf file

*Use That Added File in creating UIFont Object

To see how to do this two step in detail visit : Use custom fonts in iPhone App

A: To use this font please download its ttf file from here . Add it to the main bundle.
Check the following links and tutorials on how to add custom fonts.
Custom Fonts Tutorial
How to use custom fonts in iPhone SDK?
Can I embed a custom font in an iPhone application?


text:
Q: How to Filter YouTube content from an iPhone app objective-c My app on the Apple Store is rated 4+. There's a link to a video tutorial using this code:
-(IBAction)videoButtonPressed:(id)sender{
    // URL from safari address bar.
    [[UIApplication sharedApplication] openURL: [NSURL URLWithString:YOUTUBE_VIDEO_TUTORIAL_LINK] options:@{} completionHandler:nil];
}

It all works fine.
However, it's been rejected on the grounds that "app allows unfiltered access to YouTube, where content with mature or suggestive themes can be accessed, it should be rated 17+"
Is there anyway in the code, that this can be filtered so I can maintain the 4+ rating?

A: If you are not able to host the content in your own system or possibly another content provider; YouTube takes in input in the HTTP params (Setting the rel param to 0) to not show recommended videos (However can still possibly show other videos from your channel). Apple still might not say this is a solution as there is no way to tell if one video on your channel is PG and another happens to be for example a horror game walkthrough.
Please see below in their documentation:
https://developers.google.com/youtube/player_parameters#rel


text:
Q: Executing remote command in Vertica using Python I'm trying to execute a remote command like this:
ssh root@192.168.1.2 'su - vertica -c "vsql -c \"select * from tableName where timestamp > '2016-05-15 00:00:00' limit 1 \" "'"

It gives me an error
ERROR 4856:  Syntax error at or near "00" at character 61
LINE 1: ...rom tableName where timestamp > 2016-05-15 00:00:00 l...

Although when I execute this query directly in the remote machine, it works just fine.
Can someone provide any clues here please ?

A: You don't need those outside quotes on the ssh command. This should work fine (I also fixed some quoting mistake you had at the end):
ssh root@192.168.1.2 su - vertica -c "vsql -c \"select * from tableName where timestamp > '2016-05-15 00:00:00' limit 1 \" "

I feel like I really have to mention here though that you shouldn't be doing this. Why ssh to a root account to run a job under another user? Why not just ssh to that user directly?  Create a private key, add the public to the authorized_keys list and do this instead:
ssh vertica@192.168.2.1 /opt/vertica/bin/vsql -c \"select \* from tableName where timestamp \> \'2016-05-15 00:00:00\' limit 1 \"

Notice that I escaped more characters in this version though.
The only trick will be your shell variables if you need them.  You might need to run bash or source the .bashrc (although be warned in some distributions, there is a block in the .bashrc for noninteractive shells that may need to be fixed).


text:
Q: Why is there so much fear surrounding LiPo batteries? I've been trying to design a charging system for a small robot powered by a 2S 20C lithium polymer (LiPo) battery. Were I to trust everything I read online, I would believe that the LiPo will kill me in my sleep and steal my life savings. The common advice I read, if you are brave enough to use LiPo batteries, is "never leave unattended", "never charge on top of a flammable or conductive surface", and "never charge at a rate faster than 1 C".
I understand why this is prudent, but what is the actual risk with LiPo batteries?
Nearly every cell phone, both Android and iPhone alike, contains a LiPo battery, which most people, including myself, charge while unattended—often-times while left on a flammable or conductive surface. Yet you never hear about someone bursting into flames because their cell phone exploded. Yes, I know there are freak accidents, but how dangerous are modern LiPo batteries? Why do so many online commenters treat stand-alone LiPo batteries like bombs waiting to go off, but don't even think twice about the LiPo sitting in their pocket?

A: To use Lipo batteries safely, you must treat them with the same respect you would anything that can store and rapidly release a large amount of chemical and/or electrical energy. The bigger the battery and the lower the internal resistance (e.g. higher C rating) the more you need to be careful. They can be used safely... just like gasoline can be used safely but to do so you must learn about how they operate and how they can fail.
When you think about it, it's no surprise that, for instance, a Tesla battery has about the same level of risk as the gas tank it replaces... they both store a lot of energy that can be released rapidly when needed. Well actually, I lie somewhat because a Tesla battery only holds the energy of a tiny gas/petrol tank and it's got more safety checks built into it.
I have safely used large Lipo batteries in high performance R/C airplanes and helicopters (up to 90C batteries) for about 15 years (I was an early adopter.) Besides my own experience I have that of others in my clubs. I've seen packs fail in the past, but it's really rare now, because we've learned to use them with respect. Here's what I learned living life on the edge. :)
Failure modes
The most common failure modes are:

*

*physical damage (this causes them to short out internally)

*over charging (caused by faulty/bad charger)

*over heating due to high discharge current (causes puffed pack or worse if the heat is really high)

The least common modes of failure I've heard of (but never witnessed) are:

*

*spontaneous cell failure due to shoddy manufacturing that caused internal short (usually aggravated by physical shock but not always)

All failure modes list above can result in "vent with smoke" or "vent with flames". Newer lipos with less volatile electrolytes can "vent with smoke" but you can never be sure; so you have to plan for the worse case.
Standard Operating Procedure (SOP)
Here is the minimal standard operating procedure (SOP) for using a high discharge (any R/C pack is high discharge) bare lipo packs that I use:
Physical Protection

*

*cells must be protected from physical damage

*if your environment is rough, consider an R/C car hard pack (carbon fiber case around soft Lipos)

*cells must be inspected for physical damage before and after each use

*if any cell is physically damaged in any way, they should be moved to a fire safe area and then slowly (1C) discharged down to 2 volts per cell or less, and then safely disposed of (no damaged cell should ever be considered safe again)

*do NOT transport damaged cells; treat them with the same respect you'd treat a firework whose wick you aren't sure is out yet and that could still go off at any time!

By the way, unlike what @metacolin wrote, it IS safe to discharge a Lipo to a low voltage and is the preferred thing to do before disposing of a pack. You want to remove all chemical energy from a pack to make it safe. What isn't safe is to discharge a cell below 2V and then to charge it. Charging a low voltage cell can cause Lithium to plate out making the cell unstable.
Charging (this is the most critical time for safety)

*

*do this away from anything flammable and that wouldn't suffer smoke damage (e.g. outside)

*always ensure that each cell is being individually monitored during charging; a quality R/C charger with "balanced" charging will do this

*check cell voltages before charging (a quality R/C charger will do this automatically), if any cell is below 3V, treat the pack with suspicion and balance charge it slowly to see if recovers

*if any cell voltage is below 2V don't charge (a quality charger will do this automatically); discharge the other cells and then safely dispose of the pack... once a cell goes below 2V, it's not safe to charge any more because lithium metal can plate out and make the cell unstable during subsequent charging

*don't use a low end charger that does have good voltage calibration

Discharging

*

*rapid discharging that builds up too much heat is a problem; see Heat discussion below

*over discharging is safe... once; but don't ever charge again; see Charging discussion above

Heat

*

*ensure cells never get hot (due to rapid discharge, rapid charge, sitting in sun, etc.) 45 Celsius is the absolute maximum that I tolerate... but under 35 Celsius is much better

*don't discharge or charge cells that are too cold; warm them up first... cells work best from about 10 Celsius to 30 Celsius; lithium plating can again be a problem if they are used when they are too cold

Long life

*

*if you want your cells to last a long time (calendar) it's best to follow the 80/20 rule with Lipo batteries; that is don't discharge them below 20% capacity or above 80% capacity; this is what modern battery management systems (BMS) do (e.g. Tesla, iPhone, etc.)

*when batteries are in storage for more than a week, ensure they are balanced charged to about 60% capacity per cell (again, a good R/C charger can do this automatically for you.)

Final thoughts about your question
So, yes, if you develop safe SOPs and take actions to mitigate risk you could use a Lipo in your robot. Until you fully understand safe SOPs, I wouldn't even consider making your own charger or BMS. Smart people have spent years stuff like that.
Otherwise, depending on your design needs, maybe a simple NiMh, SLA battery could meet your needs. However, even NiMh and SLA batteries they have their own SOPs to follow. For instance, NiMh cells can blow up due to pressure during charging if they are overcharged and their pressure valve fails. SLA's generate hydrogen gas! during charging... so they need to be well vented.
Remember everything useful can also be dangerous. Lipo's are no worse than a chef knife, or a airplane wing full of kerosene. The trick is to learn how to use them all wisely.
Edit: Confronting misinformation
Myth 1
@metacollin, writes that Lipo "anode and cathode experience significant mechanical strain"
False ... Lithium Polymer cells are not under any significant stress during normal operation. This is why they can be packed in plastic pouches.
But don't take my word for it. Watch this expert say it at 10:00. (Spoiler alert: he calls the affect "benign".)
https://www.youtube.com/watch?v=pxP0Cu00sZs
P.S. I highly recommend watching the whole video if you want information from and expert (rather than somebody on here that pretends to be an expert.)
NiMh or NiCd chemistry are in fact more dangerous in regards to strain/pressure build up. Both can generate excess oxygen if they are overcharged. This is one reason why NiMh and NiCd cells are contained in round metal cans with safety vents and not plastic containers like LiPo's. Read this spec. sheet for a full explanation:
http://data.energizer.com/PDFs/nickelmetalhydride_appman.pdf
Myth 2
@metacollin, "They need protection circuitry to be safe, and they are not even remotely safe without it."
True. However, what is important is that the complete system of batteries and charging work together to keep all the cells of a battery operating withing spec. There is more than one way (topology) for this to be done:

*

*Include a "protection" circuit per cell and don't rely on the charger or user to be within spec. The "protection" circuit does these things:

*

*turn off cell (open circuit) if current goes too high

*turn off cell if voltage goes too low

*turn off cell if voltage goes too high

Because cell mounted "protection" circuits can only be of limited size, they generally are only good for low current scenarios.

*Alternately you can use bare cells as long as you always use them with a smart balanced charger that:

*

*refuses to charge if voltage is too low

*ensures charge voltage never goes too high

If you desire fusing, you can place an appropriate fuse inline with pack.
This is what R/C users do because they want batteries to be as light as possible and able to deliver high current.

*The ultimate strategy is to use bare cells wired into a more complete battery management system (BMS). BMS's can have many different topologies based on what parameters you are optimizing for. BMS's can also do other non-safety related things like adding features (e.g. a state of charge gauge) and trying to increase the lifespan of the battery by controlling operating parameters. Modern electric cars and electric bikes use BMS's (and not "protected" cells.) Additionally, modern consumer electronics with built-in LiPo's have switched away from using protected cells to using BMS's. E.g. iPhones, iPods, etc.

From a safety aspect, all these setups do the same thing as a complete system. They just do it in different ways because they are optimized to different parameters.

A: I think your info is outdated.
I had a coworker who was into RC airplanes. They were early adopters of LiIon technology because they are light and hold a lot of power.
He related how they had two failure modes, one of which was incindiary. Planes would literally explode in a ball of fire while in flight.
Eventual commercial cells have, I later read, multiple different safety features integrated into the sellable units, required by law.
They are safe now, as long as you don't break or breach one, or allow it to get too hot.  Heat control is part of the finished device design: you might have poor venting or improper thermal fusing and thus allow it to go critical.  Some newer products are not quite so safe, in particular "bag cells" that don't have the durability to handle without being integrated in a properly designed device.
So, learn how to use them safely, and learn the specific details of the parts you choose for your design.

A: Every cell phone (as well as laptop and nearly everything with a rechargeable battery) uses LiIon/LiPo (essentially equivalent for the purposes of this discussion). And you're right: In terms of actual incidences, lithium-ion and lithium-polymer are the safest battery chemistry to be in wide use, bar none.
And the only reason this now ubiquitous chemistry hasn't murdered you and/or your family several times over is that these cells aren't charged unattended. You may not be attending it personally, but every single one of those lithium-ion batteries has a significant amount of protection and monitoring circuitry that is permanently integrated into the pack. It acts as the gatekeeper. It monitors every cell in a battery.

*

*It disconnects the output terminals and prevents them from being overcharged.

*It disconnects the output if they are discharged at too high a current.

*It disconnects the output if it is CHARGED at too high a current.

*If any of the cells are going bad, the output is disconnected.

*If any cell gets too hot, it disconnects the output.

*If anyone of the cells is over-discharged, it disconnects the output (and permanently - if you forget to charge a lithium-ion battery for too long, you will find that it will no longer charge. It is effectively destroyed, and the protection circuit will not permit you to charge the cells).

Indeed, every single phone battery, laptop battery, *whatever battery that is a rechargeable lithium chemistry is the most closely monitored, scrutinized, and actively managed, the diametric opposite of 'unattended' as one can get for a battery.
And the reason so much extra trouble is done is because lithium-ion batteries are actually that dangerous. They need protection circuitry to be safe, and they are not even remotely safe without it. Other chemistries such is NiMH or NiCad can be used relatively safely as bare cells, without any monitoring. If they get too hot, they can vent (which has happened to me personally), and it can be pretty startling, but it isn't going to burn down your house or land you an extended stay in a burn unit. Lithium-ion batteries will do both, and that's pretty much the only outcome. Ironically, lithium-ion batteries have become the safest packaged battery by being the most dangerous battery chemistry.
You might be wondering what actually makes them so dangerous.
Other battery chemistries, such as lead-acid or NiMH or NiCad, are not pressurized at room temperature, though heat does generate some internal pressure. They also have aqueous, non-flammable electrolytes. They store energy in the form of a relatively slow oxidation/reduction reaction, one whose rate of energy release is too low to, say, cause them to eject 6-foot jets of flame. Or any flame, really.
Lithium-ion batteries are fundamentally different. They store energy like a spring. That's not a metaphor. Well, like two springs. Lithium ions are forced between the atoms of covalently-bonded anode material, pushing them apart and 'stretching' the bonds, storing energy. This process is called intercalation. Upon discharge, the lithium ions move out of the anode and into the cathode. This is very much electromechanical, and both the anode and cathode experience significant mechanical strain from this.
In fact, both anode and cathode alternatively increase or decrease in physical volume depending on the battery's state of charge. This change in volume is uneven however, so a fully charged lithium-ion battery is actually exerting nontrivial amounts of pressure on its container or other parts of itself. Lithium-ion batteries are generally under a lot of internal pressure, unlike other chemistries.
The other problem is their electrolyte is a volatile, extremely flammable solvent that will burn quite vigorously and easily.
The complex chemistry of lithium-ion cells is not even completely understood, and there are a few different chemistries with different levels of reactivity and inherent danger, but the ones with high energy density all can undergo thermal runaway. Basically, if they get too hot, lithium ions will begin reacting with oxygen stored as metal oxides in the cathode and release even more heat, which accelerates the reaction further.
What inevitably results is a battery that self-ignites, sprays its highly flammable solvent electrolyte out of itself, and promptly ignites that as well, now that a fresh supply of oxygen is available. That's just bonus fire however, there is still a ton of fire from the lithium metal oxidizing with the ample store of oxygen inside.
If they get too hot that happens. If they are overcharged, they become unstable and mechanical shock can make them go off like a grenade. If they are over-discharged, some of the metal in the cathode undergoes an irreversible chemical reaction and will form metallic shunts. These shunts will be invisible, until charging expands part of the battery enough that the separating membrane is punctured by one of these shunts, creating a dead short, which of course results in fire, etc.: The lithium-ion failure mode we know and love.
So, just to be clear, not only is overcharging dangerous, but so is over-discharging, and the battery will wait until you've pumped a ton of energy back into it before spectacularly failing on you, and without any warning or measurable signs.
That covers consumer batteries. All this protection circuitry is less able to mitigate the danger of high drain applications, however. High drain generates no small amount of heat (which is bad) and more worrying, it causes huge amounts of mechanical stress on the anode and cathode. Fissures can form and widen, leading to instability if you're unlucky, or just a shorter useful life if it is not too severe. This is why you see LiPos rated in 'C', or how quickly they can be safely discharged. Please, take those ratings seriously and derate it, both for safety and because many manufacturers simply lie about the C rating of their batteries.
Even with all that, sometimes an RC Lipo will just burst into flame for no reason. You absolutely need to heed the warnings to never charge them unattended, and everything else. You should buy a safety bag to charge them in because it might prevent your house from burning down (possibly with you or loved ones inside). Even if the risk is very low, the damage it can cause is vast, and the measures needed to mitigate most of that potential for damage are trivial.
Don't ignore everything you're being told - it's all spot on. It comes from people who have learned to respect LiPos for what they are, and you should too. The thing you definitely want to avoid is having this lesson taught to you by a lithium-ion battery, instead of peers online and offline. The latter might flame you on a forum, but the former will literally flame you.
Let's see some videos of stuff exploding!
Let me go a little more into how they fail. I've discussed the mechanism, but what really happens? Lithium-ion batteries really only have one failure mode, which is kind of exploding then shooting out a stunningly huge amount of fire in a giant jet of flame for several seconds, and then continuing general burning-related activities for a bit after that. This is a chemical fire, so you cannot extinguish it (lithium-ion batteries will still shoot out huge jets of fire even in the vacuum of space. The oxidizer is contained inside, it doesn't need air or oxygen to burn). Oh, and throwing water on lithium does nothing good, at least in terms of fire reduction.
Here is a 'greatest hits' list of some good examples of failure. Note that this does sometimes happen in high drain RC cases even with proper safety measures in place. Comparing high drain applications to the much safer and lower currents of phones is not at all a valid one. Hundreds of amperes ≠ a few hundred milliamperes.
RC plane failure.
Knife stabs smartphone-sized battery.
Overcharged LiPo spontaneously explodes.
Laptop battery in a thermal runaway is lightly pressed on, making it explode.

A: All great answers.  Here is a short one.  A 7.4 volt. 5 amp-hour battery has 37 watt-hours of energy, or 133,200 joules.  Compare to a .357 Magnum's 873 joules of muzzle energy.  The trick is not to let it a bunch of it out at once by overheating or crushing.

A: When a big company wants to make a LiPo charger, they can:
A. Have experts on staff and do extensive testing to make sure the charger will work safely across the full range of operating conditions.
B. Buy pre-made ICs or assemblies that have been given that same level of care.
C. Subcontract out the work to people who know what they're doing.
When you build a charging circuit at home, you don't do any of those things.
LiPo batteries can definitely burst into flame, as a YouTube search can tell you. You'll find people actively destroying the batteries with nails or even an axe, but you can also find more realistic examples, like this one of an RC aircraft violently bursting into flame due to a charging problem.
Hence the warnings -- people on the internet can't guarantee that a homemade charging circuit will always work safely, and the failure mode of LiPo is "bomb". That's what a bomb is, after all -- lots of energy being released quickly.

A: [Though this late answer may get little exposure now that the question has exited the hot-list, I think it is essential to further emphasize the contrast between the comprehensive safety features in devices such as laptops and cellphones vs. the typically far less comprehensive safety features in hobbyist or DIY devices.]
Context is essential when evaluating those dire safety warnings that you cite. They are not targeted at devices like laptops and cellphones (from reputable manufacturers) that employ tightly integrated battery management / protection circuitry to keep them safe. Rather, they target less safe devices, e.g. unprotected LiPo cells used in RC hobbies to power Remote-Controlled cars, planes, etc. Below we take a much deeper look at these differences in safety.
Unlike other battery chemistries familiar to consumers, batteries based on Li-ion chemistry are inherently much more volatile. Due to such, they require very carefully designed battery management circuitry to protect them from catastrophic failure. This includes mechanisms that prevent them from reaching dangerous states (under or overcharge, over-temperature, over-current, etc) and, further, may disable them when dangerous conditions arise (e.g. via a FET, PTC or one-shot fuse). Such logic may even include sophisticated algorithms that continuously monitor the health of the cells in order predict impending serious failures (such as an internal short, which can lead to thermal runaway).
Unlike most user-assembled hobby / DIY devices, for laptops and cellphones the manufacturer has design control of the entire battery power subsystem, therefore they can design a very tightly integrated system including sophisticated fault tolerant protection mechanisms. Such designs follow time-tested industry standards and employ multiple levels of redundancy and comprehensive failure analysis methods, e.g. fault-tree analysis or FMEA = failure modes and effects analysis.
You may be surprised by the comprehensiveness of such analyses, e.g. below are 2 of 96 cases considered in IEEE 1625 2004, including the case that a pet urinates on the device (a PC).

You may also be surprised by the high level of redundancy of fault protection employed, e.g. according to said industry standard, laptop batteries must implement at least two independent methods to turn off the charge FET to prevent catastrophic overcharging. Furthermore, if both methods fail, then a fail-safe chemical fuse must blow. This is a special voltage-triggered 3-terminal fuse that can function even under extreme conditions such as when the battery voltage drops extremely low due to a short-circuit.
Contrast the above to your DIY project or RC hobbies where the end user is responsible for integrating the components of the battery subsystem and ensuring that they function together safely (the components being the cells, BMS/PCM protection board, device, and charger). There are many obstacles hindering such. The user may lack sufficient knowledge. The user may lack access to datasheets and technical information, which is generally not made available to consumers (cell manufacturers strongly discourage direct consumer use, e.g. recently Sony sent a cease and desist order to a NYC vaping store selling Sony 18650 cells - see below). Lack of standard communication protocols such as SBS = Smart Battery System in the RC / hobby world limits the communication between subsystems, which greatly increases the difficulty of designing sophisticated safety mechanisms such as those in laptops.
Here is a real-word example: a question from TI's battery gas gauge support forum.

I am wondering if these Chemical Fuses are a mandatory element of Lithium-ion battery packs.  I am working with a Chinese Li-ion pack
  supplier, and they produced a pack design based on a bq20z45-R1 fuel gauge IC, but there was no Chemical Fuse circuit.  Also, there
  was no secondary-overvoltage-protection IC such as the bq29412.  Are the Chemical Fuse and bq29412 (or similar IC) required for commercial
  Li-ion battery pack applications?  Is there a Regulatory requirement? BTW, I am working on a medical device design.

Above we have an example of a battery pack which lacks the 2nd and 3rd level of overcharge protection described above. Such omissions of safety features are common on many cheaper battery management systems. Not to mention some fly-by-night Chinese manufacturers who greatly exaggerate the level of protection implemented. In order to recognize such omissions and to comprehend their ramifications, when the end user is the engineer, they must have adequate background knowledge in the field. Lacking such could lead to designs with serious safety defects. That's why reputable cell manufacturers such as LG, Panasonic, Samsung, Sanyo and Sony refuse to deal directly with consumers. The risks are far too great if one does not have adequate knowledge to ensure safe design.
Below is the Sony letter mentioned above. This is typical of the attitude of reputable cell manufacturers concerning the serious safety risks posed by  consumer use of loose cells.

For convenience, below are the links given in the letter:
Electronics Cigarette Fires and Explosions, U.S. Fire Administration, FEMA, OCtober 2014
Battery Safety, Consumer Technology Association.


text:
Q: How to Write image bytes asynchronously? I am trying to store a file in local directory using Windows.Storage but I get an error when I try to store a second image
I am using the Windows.Storage
async void ReceiveDecodedData(byte[] data, int width, int height)
{
   StorageFolder storageFolder = KnownFolders.PicturesLibrary;

   string filename = "sample" + ".jpg";

   StorageFile file = await storageFolder.CreateFileAsync(filename, CreationCollisionOption.OpenIfExists);
   await FileIO.WriteBytesAsync(file, data);

}

I want to write the bytes to the image without any error/exceptions.
Exception: "The process cannot access the file because it is being used by another process."

A: If the method does not return a Task then you can't use it within an async/await pattern. JSteward is correct that you should replace async void with async Task. If you are calling the function somewhere else then create a synchronous version of the method and call the same underlying function.
How and when to use 'async' and 'await'


text:
Q: Heading angle calculation using current lat/long from the GPS The aim of my work is given in the algorithm below.

*

*Initialize the H/W; wait until GPS module has a valid fix and then start the motor.

*Get actual position from the GPS.

*Calculate the distance and heading information to the next waypoint.

*Compare the actual heading with the current heading angle and feed the difference to the motors.

*When the actual position is close to the first waypoint, switch to the next waypoint.

*If/when the last waypoint is reached, stop the motor.

*If not go to step 2.

I'm calculating the distance between a pre-defined coordinate and the current location using Haversine formula. I need heading angle for the same pair of coordinates. But when I use the atan2 formula and compile using the Arduino IDE, I am getting the angle as 0.05,0.03. Am I doing it wrong? can the heading angle be calculated for points within a proximity of 10m?
formula
double y = sin(dlon) * cos(lat2);
double x = ((cos(lat1) * sin(lat2)) - (sin(lat1) * cos(lat2) * cos(dlon)));
double brng = atan2(y, x);


text:
Q: System.BadImageFormatException occurred when build in Release Mode I am referencing an exe file in a dll. When run in DEBUG mode everything runs fine but when run in Release mode below exception is thrown
System.BadImageFormatException occurred
  HResult=-2147024885
  Message=Could not load file or assembly 'Presensoft.InlineMarker, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An attempt was made to load a program with an incorrect format.
  Source=Presensoft.ApplicationServer
  FileName=Presensoft.InlineMarker, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
  FusionLog==== Pre-bind state information ===
LOG: DisplayName = Presensoft.InlineMarker, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
 (Fully-specified)
LOG: Appbase = file:///F:/PresensoftNewTrunk/Trunk/Email Archiver/EmailService/Presensoft.ApplicationServerHost/bin/Release/
LOG: Initial PrivatePath = NULL
Calling assembly : Presensoft.ApplicationServer, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null.
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: F:\PresensoftNewTrunk\Trunk\Email Archiver\EmailService\Presensoft.ApplicationServerHost\bin\Release\Presensoft.ApplicationServerHost.vshost.exe.config
LOG: Using host configuration file:
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework64\v4.0.30319\config\machine.config.
LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).
LOG: Attempting download of new URL file:///F:/PresensoftNewTrunk/Trunk/Email Archiver/EmailService/Presensoft.ApplicationServerHost/bin/Release/Presensoft.InlineMarker.DLL.
LOG: Attempting download of new URL file:///F:/PresensoftNewTrunk/Trunk/Email Archiver/EmailService/Presensoft.ApplicationServerHost/bin/Release/Presensoft.InlineMarker/Presensoft.InlineMarker.DLL.
LOG: Attempting download of new URL file:///F:/PresensoftNewTrunk/Trunk/Email Archiver/EmailService/Presensoft.ApplicationServerHost/bin/Release/Presensoft.InlineMarker.EXE.
ERR: Failed to complete setup of assembly (hr = 0x8007000b). Probing terminated.

  StackTrace:
       at Presensoft.ApplicationServer.ExchangeServer2010Push.PostProcessingEmailsQueue()
       at Presensoft.ApplicationServer.ExchangeServer2010Push.RunPushService(Guid appServerID) in f:\PresensoftNewTrunk\Trunk\Email Archiver\EmailService\Presensoft.ApplicationServer\ExchangeServer2010Push.cs:line 48
  InnerException:

Not sure whether there is some issue with probing exe file when running in RELEASE mode.

A: More than a Debug/Release mode I'll say it's a 32 vs 64 bits problem. Probably you have the Platform target for the Debug mode to Auto and for the Release mode to 32/64 bits and you are using a dll that is only 32 or 64 bits, so in Debug (Platform target Auto) mode the .NET can "select" between 32 and 64 bits to be compatible with the dll, while in Release (Platform target 32 or 64 bits) it can't.
(note that if you have multiple projects in the same solution you have to check all the projects properties for this! It's in the properties of each project, Build, Platform target)

A: I ran into this (or something similar) yesterday also. Both Debug and Release mode are set to AnyCPU but the exe is referencing a 32-bit dll. While debugging, the exe appears to default to 32-bit (I assume because Visual Studio is 32-bit) but when in release mode, it switches to 64-bit (I assume because my computer is 64-bit). So when I force it to always be 32-bit (x86), everything should and does work great! Hope this helped!


text:
Q: Two content area scrollable by browser's vertical and horizontal scrollbars Is it possible to design page like on this picture:

I need reach only three goals:

*

*First content can be scrolled only vertically.

*Second content can be scrolled only horizontally.

*Must be used only browsers scrollbars.

p.s. Better if we will not use javascript code.

A: Yes, this is possible.
The real difficulty is to add scrollbars outside de views.
But when done, you can easily scroll to a position your scrollviews.
I don't think this is really a good feature to make this but why not.
Be strong!


text:
Q: Sharedpreferences in Android returns null when called from another activity I made two activities, one for the widget and one for the settings activity.
There are two variables "strSavedMem1" & "strSavedMem1" initialised in the settings activity... and are made via sharedPreference method.
But when I try to use the variable in widget activity, the variable return a "null" value.
The widget Activity:
package com.eightbitcloud.example.widget;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Calendar;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.RemoteViews;

import com.shashank.pingwidget.R;

public class ExampleAppWidgetProvider extends AppWidgetProvider {
private static final String LOG_TAG = "Ping_Widget";
private static Handler handler;
static String currentTime = null ;
public String strSavedMem1;
public String strSavedMem2;
public static final String PREFS_NAME="LocalePrefs";

/**
 * Custom Intent name that is used by the AlarmManager to tell us to update the               clock once per second.
 */
public static String PING_WIDGET_UPDATE =    "com.eightbitcloud.example.widget.8BITCLOCK_WIDGET_UPDATE";

@Override
public void onReceive(Context context, Intent intent) {
    super.onReceive(context, intent);

    if (PING_WIDGET_UPDATE.equals(intent.getAction())) {
        Log.d(LOG_TAG, "Clock update");
        // Get the widget manager and ids for this widget provider, then call the shared
        // clock update method.
        ComponentName thisAppWidget = new        ComponentName(context.getPackageName(), getClass().getName());
        AppWidgetManager appWidgetManager =   AppWidgetManager.getInstance(context);
        int ids[] = appWidgetManager.getAppWidgetIds(thisAppWidget);
        for (int appWidgetID: ids) {
            updateAppWidget(context, appWidgetManager, appWidgetID);

        }
    }
}

private PendingIntent createClockTickIntent(Context context) {
    Intent intent = new Intent(PING_WIDGET_UPDATE);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent,     PendingIntent.FLAG_UPDATE_CURRENT);

    return pendingIntent;
}

@Override
public void onDisabled(Context context) {
    super.onDisabled(context);
    Log.d(LOG_TAG, "Widget Provider disabled. Turning off timer");
    AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    alarmManager.cancel(createClockTickIntent(context));
}

@Override
public void onEnabled(Context context) {
    super.onEnabled(context);

SharedPreferences sharedPreferences = context.getSharedPreferences(PREFS_NAME,0);
    strSavedMem1 = sharedPreferences.getString("MEM1", null);
    if (strSavedMem1 == null) {
        strSavedMem1="google.com";
          Log.d(getClass().getSimpleName(),"MEM1 name is: "+ strSavedMem1);
    }

    strSavedMem2 = sharedPreferences.getString("MEM1", null);
    if (strSavedMem2 == null) {
        strSavedMem2 = "1";
        Log.d(getClass().getSimpleName(),"MEM2 name is: "+ strSavedMem2);
    }

    Log.d(LOG_TAG, "Widget Provider enabled.  Starting timer to update widget every second");
    AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);

    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.add(Calendar.SECOND, 30);
    alarmManager.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(), 50000, createClockTickIntent(context));
}

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    final int N = appWidgetIds.length;

    Log.d(LOG_TAG, "Updating Example Widgets.");

    // Perform this loop procedure for each App Widget that belongs to this
    // provider
    for (int i = 0; i < N; i++) {
        int appWidgetId = appWidgetIds[i];

        // Create an Intent to launch ExampleActivity
        Intent intent = new Intent(context, WidgetExampleActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

        // Get the layout for the App Widget and attach an on-click listener
        // to the button
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget1);
        views.setOnClickPendingIntent(R.id.button, pendingIntent);
        // Tell the AppWidgetManager to perform an update on the current app
        // widget
        appWidgetManager.updateAppWidget(appWidgetId, views);

        // Update The clock label using a shared method
        updateAppWidget(context, appWidgetManager, appWidgetId);
    }
}

public  void updateAppWidget(final Context context, final AppWidgetManager appWidgetManager, final int appWidgetId) {
    //String currentTime =  df.format(new Date());
    handler = new Handler();

    Runnable runnable = new Runnable() {

        @Override
        public void run() {

            try {
                String pingCmd = "ping -c 3 " + "google.com";
                String pingResult = "";
                Runtime r = Runtime.getRuntime();
                Process p = r.exec(pingCmd);
                BufferedReader in = new BufferedReader(new
                InputStreamReader(p.getInputStream()));
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                System.out.println(inputLine);
                currentTime = inputLine + "\n";
                pingResult += inputLine+ "\n";
                currentTime = pingResult ;
                }
                in.close();
                }//try
                catch (IOException e) {
                System.out.println(e);
                }

                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        //progress.setProgress(value);
                        RemoteViews updateViews = new RemoteViews(context.getPackageName(), R.layout.widget1);
                        updateViews.setTextViewText(R.id.widget1label, currentTime+"\n"+ strSavedMem1+"\n"+strSavedMem2);
                        appWidgetManager.updateAppWidget(appWidgetId, updateViews);

                    }
                });
        }

    };
    new Thread(runnable).start();

    }
}

The settings activity is:
package com.eightbitcloud.example.widget;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.shashank.pingwidget.R;

public class WidgetExampleActivity extends Activity {
public static final String PREFS_NAME="LocalePrefs";
public Context ctx = null;
EditText editText1, editText2;
TextView textSavedMem1, textSavedMem2;
Button buttonSaveMem1, buttonSaveMem2;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

     textSavedMem1 = (TextView)findViewById(R.id.savedmem1);
       textSavedMem2 = (TextView)findViewById(R.id.savedmem2);
       editText1 = (EditText)findViewById(R.id.edittext1);
       editText2 = (EditText)findViewById(R.id.edittext2);
       buttonSaveMem1 = (Button)findViewById(R.id.save_mem1);
       buttonSaveMem2 = (Button)findViewById(R.id.save_mem2);

       buttonSaveMem1.setOnClickListener(buttonSaveMem1OnClickListener);
       buttonSaveMem2.setOnClickListener(buttonSaveMem2OnClickListener);

       LoadPreferences();
   }

   Button.OnClickListener buttonSaveMem1OnClickListener
    = new Button.OnClickListener(){

  @Override
  public void onClick(View arg0) {
   // TODO Auto-generated method stub
   SavePreferences("MEM1", editText1.getText().toString());
   LoadPreferences();
  }

   };

   Button.OnClickListener buttonSaveMem2OnClickListener = new Button.OnClickListener(){

  @Override
  public void onClick(View arg0) {
   // TODO Auto-generated method stub
   SavePreferences("MEM2", editText2.getText().toString());
   LoadPreferences();
  }

   };

  private void SavePreferences(String key, String value){

    SharedPreferences sharedPreferences = getSharedPreferences(PREFS_NAME,MODE_WORLD_READABLE);

        /*SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(key, value);
        editor.commit();*/

        //SharedPreferences sharedPreferences =PreferenceManager.getDefaultSharedPreferences(WidgetExampleActivity.this);

      //SharedPreferences sharedPreferences = getSharedPreferences(PREFS_NAME,  MODE_WORLD_READABLE);

        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(key, value);
        editor.commit();
       }

       public void LoadPreferences(){

    //  SharedPreferences sharedPreferences = ctx.getSharedPreferences(PREFS_NAME, MODE_WORLD_READABLE);
        SharedPreferences sharedPreferences = getSharedPreferences(PREFS_NAME,  MODE_WORLD_READABLE);

        String strSavedMem1 = sharedPreferences.getString("MEM1", "google.com");
        String strSavedMem2 = sharedPreferences.getString("MEM2", "1");
        textSavedMem1.setText(strSavedMem1);
        textSavedMem2.setText(strSavedMem2);

        strSavedMem1 = sharedPreferences.getString("MEM1", null);
        if (strSavedMem1 == null) {
            strSavedMem1="google.com";
              Log.d(getClass().getSimpleName(),"Wallpaper name is: "+ strSavedMem1);
        }

        strSavedMem2 = sharedPreferences.getString("MEM1", null);
        if (strSavedMem2 == null) {
            strSavedMem2 = "1";
            Log.d(getClass().getSimpleName(),"Wallpaper name is: "+ strSavedMem2);
        }

       }

}

A: You should

*

*check if the commit worked and returned true.

*open both SharedPreferences in the same way using MODE_PRIVATE (as a constant and not its value)


text:
Q: Saving multiple images to isolated storage I was trying to save multiple images into isolated storage by using creating a imageFolder in isolated storage and storing all my images inside.But it have an error so please anyone could help me solve the error or got other method way help me thanks.IF possible I would appreciate if you guys can show me your code that works. Actually my code would like to be under a button event handler.Thanks And the error is :Operation not permitted on IsolatedStorageFileStream.
My Code :
         private void SaveToLocalStorage(string imageFolder, string imageFileName)
    {
        imageFileName = name.Text;
        MessageBox.Show(imageFileName);

        var isf = IsolatedStorageFile.GetUserStoreForApplication();
        if (isf.DirectoryExists(imageFolder))
        {
            isf.CreateDirectory(imageFolder);
        }

        string filePath = Path.Combine(imageFolder, imageFileName);
        MessageBox.Show(filePath);
        using (var stream = isf.CreateFile(filePath))
        {
            var bmp= new WriteableBitmap(inkCanvas, inkCanvas.RenderTransform);
            bmp.SaveJpeg(stream, bmp.PixelWidth, bmp.PixelHeight, 0, 100);
      }
}

A: First off, you probably want to be creating the directory if it DOESN'T exist, not if it does:
    if (!isf.DirectoryExists(imageFolder))
    {
        isf.CreateDirectory(imageFolder);
    }


text:
Q: Can't login after installing AMD driver in Ubuntu 14.04 I can't login to my ubuntu dekstop after install amd driver in my ubuntu 14.04 , i use lenovo ideapad 110 with amd r5 grafik,  how can i fix it ? Help me please...

A: Change your drivers from the ones that are not working via the Commandline.
Log into the console, Ctrl+Alt+F2.
Use this command to list the available drivers.
$ ubuntu-drivers devices

Then pick one of the alternate drivers from the list and install it with.  Picking the one referred as recommended may be a failsafe.  Some manual proprietary drivers might not show up on the list.  You may have to reinstall a proprietary drives using the supplied install method to switch to that one.
$ sudo apt install [driver]

You may or may not have to remove or rename your current /etc/X11/xorg.conf file.  Some propriety driver installs may reconfigure it.  I would test first without touching it.  If you need to you can rm move it with.
$ rm /etc/X11/xorg.conf

Now reboot.  Now that you have a failsafe way to get back to the GUI, you can test other drivers to optimize your performance.
Note:
You can check your current driver that is in use with:
$ sudo lspci -nnk | grep -i vga -A3


text:
Q: passing nested dictionary in url request issue swift I am trying to pass a nested dictionary to the server using a URL request.
i try below dictionary format:
var pdictData = ["post_id":"JobListObj.JobID","comment":txtMsg.text,"rating[price]":viewPrice.rating,"rating[service]":viewService.rating,"rating[location]":viewLocation.rating,"rating[quality]":viewQuality.rating] as [String : Any]

it's not working at all shows me please pass the rating data
here is format suggested by my web api developer :
post_id:1830
comment:Rateing again
rating[quality]:1
rating[location]:1
rating[service]:1
rating[price]:1

A: This format looks stranger for me, probably you should pass this data on body of request instead of url parameters. Try share the API documentation  on your question (if it public).
I guess that you want send a data using post method. So, you need create a struct like this.
struct Job: Codable {
   let post_id: Int
   let comment: String
   let rating: Rating
}

struct Rating: Codable {
   let quality: Int
   let location: Int
   let service: Int
   let price: Int
}

And then configue your request:
let job = Job( .... )
let data = try? JSONEncoder().encode(job)
let url = URL(string: "MY_HOST")
var request = URLRequest(url: url)
request.httpBody = data


text:
Q: PHP Simple HTML DOM Parser - Remove Script Data I'm using the last version from here.
There's a remove_noise() function that is called on load() that looks to remove any script data, which would be great. However, it doesn't seem to work.
When parsing TechCrunch dot com and looking for all H2's (as an example), there's a lot of CDATA within a script tag. This is crashing my PHP script and would think the remove_noise() function actually cleans the output.
Am I missing something on functionality to get clean/removed output?

A: After requesting support directly from the project on Sourceforge, it turns out everything is working as expected and that regex had a limit which needed to be increased.
The code which helped me troubleshoot the issue is below:
<?php
// Normal regex doesn't work for such a large script section. The regex parser hits the backtrack limit, so we need to increase it temporarily.
ini_set('pcre.backtrack_limit', '10485760'); // 10MB

// The total file size of the webpage is also much bigger than normally allowed. Use this definition to increase the upper boundary of the parser.
define('MAX_FILE_SIZE', 10485760); // 10MB

include_once 'simple_html_dom.php';
$html = file_get_html('https://techcrunch.com/');

// This will list all headers
foreach($html->find('h2') as $h2) echo $h2->plaintext . PHP_EOL;

// Use this code to remove script tags from the DOM (i.e. if you need to save the DOM for later use. In my tests the file size went down from 1.9MB to 30KB
foreach($html->find('script') as $script) $script->remove();


text:
Q: DataTemplate not used when WPF control is opened within Windows Form Control I have a DataTemplate that I created to manage the display of the items in a ListBox.  When I open the control in a regular WPF application, it works correctly.  However, when I open it in a a Windows Form control hosted in a Windows Form application, the datatemplate is not used.  Thinking that it may be a problem with "FindResource" in that context, I added the DataTemplate in the code-behind.  Once again it worked correctly when opening in a regular WPF app, but failed when opening in the Windows Form app.
If I set the background of the ListBox itself, I see the background as well as blank rows for all of the items that "should" be displayed - so I know the data is getting there, its just that the template does not apply itself.
code to load windows form control:
_elementHost = new ElementHost();
_elementHost.Dock = DockStyle.Fill;
this.Controls.Add(_elementHost);
NavigationControl userControl = new NavigationControl(); // the wpf control
_elementHost.Child = userControl;

dataTemplate xaml:
<DataTemplate x:Key="WorkingAccountResultTemplate" >
    <StackPanel Orientation="Horizontal">
        <TextBlock Text="Test" Width="50" Foreground="Purple" Background="AliceBlue"/>
        <TextBlock Text="{Binding ItemKeyId}" HorizontalAlignment="Stretch" Background="Maroon" />
    </StackPanel>
</DataTemplate>

A: You need to start the WPF instance in your application. In order to do this create an App.xaml file in your startup or main winforms project.
App.xaml, you should have the following lines, in addition to the includes and class declaration: (You can have an empty file with just the includes, so this  section can be empty)
<Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="/PresentationFramework.Aero;component/themes/Aero.NormalColor.xaml"/>
            </ResourceDictionary.MergedDictionaries>
</Application.Resources>

App.xaml, In the code behind:
public partial class App : Application
{
    public App()
    {
        StyleManager.ApplicationTheme =new Windows7Theme();
        InitializeComponent();
    }

    public static void EnsureApplicationResources()
    {
        if (Application.Current == null)
        {
            // create the Application object
            new App {ShutdownMode = ShutdownMode.OnExplicitShutdown};
        }
    }

    protected override void OnExit(ExitEventArgs e)
    {
        if(Current != null)
            Current.Shutdown();

        base.OnExit(e);
    }
}

In the start-up method in Main.cs or Program.cs:
private static void Main()
{
// Your initialization code

//WPF instance start
                App.EnsureApplicationResources();

                Application.Run(MainForm.Instance);
}


text:
Q: An interesting geometric fact

In this question, I accidentally proved that the triangle A1B1C1 is the scaled up version  of the pedal Triangle. Is this proof valid?  By the way would someone please help me to solve this question? I have tried using the Euler line but that didn't help me out.

A: Hints for answering the question:
For a triangle $ABC$ with circumcenter at the origin of the complex plane the following statements hold:

*

*The orthocenter $H$ is given by:
$$h=a+b+c.$$

*The point $A_1$ (the intersection point of the circumcircle with the altitude drawn from $A$) is given by:
$$
a_1=-\frac{bc}a.
$$
Can you take it from here?


text:
Q: Python pandas generate list from dataframe guys below is my code which I created with the help of Pandas library in  Python:
import pandas as pd
df = pd.DataFrame({'Col1':['r0','X Y Z','A D','B','r1','r0','Y Z X','D','r1','r0','X','G','H','Z','r1']})

I want to create a list from the elements of the data frame. This list must be split to the internal list of the group elements which are between r0 and r1 as in below:
[['r0','X','Y','Z','A','D','B','r1'],
 ['r0','Y','Z','X','D','r1'],
 ['r0','X','G','H','Z','r1']]

My problem is I can do this with multiple loops. However, this way is not suitable for my code.  I would like to know what is the easiest way to solve this problem. Thank you for reading.

A: If you're okay with a list of arrays, you could use str.split + stack + np.split:
df.Col1.str.split(expand=True).stack().values
y = np.split(x, np.flatnonzero(x == 'r0'))[1:]
y

[array(['r0', 'X', 'Y', 'Z', 'A', 'D', 'B', 'r1'], dtype=object),
 array(['r0', 'Y', 'Z', 'X', 'D', 'r1'], dtype=object),
 array(['r0', 'X', 'G', 'H', 'Z', 'r1'], dtype=object)]

The reason I call [1:] is because, since your column starts with r0, np.split returns an empty array as the first split which I drop. If this is not the case, you can remove it.

As an aside, converting your result to a list of lists is extremely simple using map:
y = list(map(np.ndarray.tolist, y))

A: import operator
import functools

df1=df.Col1.str.split(' ').groupby(df.Col1.eq('r0').cumsum()).apply(list).apply(lambda x : functools.reduce(operator.concat, x))
Out[636]:
df1
Col1
1    [r0, X, Y, Z, A, D, B, r1]
2          [r0, Y, Z, X, D, r1]
3          [r0, X, G, H, Z, r1]
Name: Col1, dtype: object

df1.values
Out[639]:
array([['r0', 'X', 'Y', 'Z', 'A', 'D', 'B', 'r1'],
       ['r0', 'Y', 'Z', 'X', 'D', 'r1'], ['r0', 'X', 'G', 'H', 'Z', 'r1']], dtype=object)

A: You can reshape the underlying values array into chunks of length 5:
In [11]: df.Col1.values.reshape(-1, 5)
Out[11]:
array([['r0', 'X Y Z', 'A D', 'B', 'r1'],
       ['r0', 'Y Z X', 'D', 'r1', 'r0'],
       ['X', 'G', 'H', 'Z', 'r1']], dtype=object)

Then you can use a join/split list comprehension to split:
In [12]: [" ".join(row).split() for row in df.Col1.values.reshape(-1, 5)]
Out[12]:
[['r0', 'X', 'Y', 'Z', 'A', 'D', 'B', 'r1'],
 ['r0', 'Y', 'Z', 'X', 'D', 'r1', 'r0'],
 ['X', 'G', 'H', 'Z', 'r1']]


text:
Q: Prevent Emoji Characters from Showing I use a few special uniode chars in my app, but since iOS 5 these have been replaced with emoji characters. How can I force the unicode characters to be displayed and not the emoji characters? Thanks

A: Just to add to BFerer's helpful answer, I found this works similarly in Swift:
    "▶\u{0000FE0E}"

A: This is an old question but it plagued me a lot recently until I found the answer.
Just add '\U0000FE0E' after the character that we want to prevent from becoming an emoji.
For example:
@"▶"  // should be written as:
@"▶\U0000FE0E"

Using the escaped unicode works as well:
@"\u25B6"  // should be written as:
@"\u25B6\U0000FE0E"

We need to use Unicode variants to prevent certain characters from becoming emoji.
Here is the article that solved my problem.

A: There's a few mentions of this issue on Apple's private devforums (which you have access to if you're a registered member of the iOS developer program).
It sounds like the potential solution would be to explicitly set the font for whatever you're trying to display.

A: Use "Hiragino Mincho ProN" for the font. It worked for me, but unfortunately I had to change the insets to make things look correct. I had to add an inset to the top to place things as they were before the iOS update.
All the credit goes to Kevin Ballard who answered my post in the following discussion -
Unicode characters being drawn differently in iOS5


text:
Q: Big Number Subtraction in C I just finished my exam in an introductory C course about 20 minutes ago. The first question on the exam caught me somewhat off guard, and involved finding the difference two large numbers.
The goal was to take two structures (N1 and N2) by value, and store the difference in a structure passed by reference (N3). We were allowed to assume N3 was initiated with all '0's. The MAX size can be anything, so the solution still has to work if the numbers are over 100 digits.
Here's the base code (original may be slightly different, this is from memory)
#include <stdio.h>
#include <stdlib.h>
/* MAX can be any length, 10, 50, 100, etc */
#define MAX 10

struct bignum
{
    char digit[MAX];
    char decimaldigit[MAX/2];
};
typedef struct bignum bigNum;
void difference(bigNum, bigNum, bigNum *);

/*
    Original values in N1 and N2

    N1.digit = { '0', '0', '0', '5', '4', '8', '2', '0', '9', '0'};
    N1.decimaldigit { '0', '0', '0', '4', '9' };

    N2.digit = { '0', '0', '0', '4', '8', '1', '3', '1', '4', '5'};
    N2.decimaldigit { '8', '0', '1', '2', '0' };
*/

/*
    Result would be:
    N3.digit = { '0', '0', '0', '0', '6', '6', '8', '9', '4', '4'}
    N3.decimaldigit { '1', '9', '9', '2', '9' }
*/

The problem isn't so much in finding a solution to this problem, but that only about ~20 lines were provided for the complete answer. My method for solving involved subtracting the digits one at a time after converting to integers, and then making appropriate carries if the result was negative. This took substantially more space than what was provided.
Based on the small amount of marks and the space provided for this question, I'm lead to believe that there's a fairly trivial solution that I'm not seeing. What is it? I have now finished the course but this question is still bothering me!
A complete solution isn't required, just the inner workings of the function difference.
No bitwise operators are to be used, just in case.

A: This should work if N1 >= N2.  This also assumes that the arrays are laid out like dn...d2d1d0.e0e1...em.
char digchr(int); // Converts a single-digit integer into a character.

void difference(bigNum N1, bigNum N2, bigNum *N3) {
    int carry = 0;

    for (int i = MAX / 2 - 1; i >= 0; i--) {
        int diff = N1.decimalDigits[i] - N2.decimalDigits[i] - carry;
        if (diff < 0) {
            diff += 10;
            carry = 1;
        } else {
            carry = 0;
        }

        N3->decimalDigits[i] = digchr(diff);
    }

    for (int i = 0; i < MAX; i++) {
        int diff = N1.digits[i] - N2.digits[i] - carry;
        if (diff < 0) {
           diff += 10;
           carry = 1;
        } else {
            carry = 0;
        }

        N3->digits[i] = digchr(diff);
    }
}

A: Dear professor, subtraction should be defined in terms of addition.  I've overloaded the unary "-" operator and defined the bignum addition routine elsewhere.  I'm using 9's complement to simplify/speed up the addition (no pesky carry required!) with a table based answer lookup (why calculate the sums when there are only 10 of them?).  The bigNum subtraction routine (to your specs) follows:
void bigDifference(bigNum N1, bigNum N2, bigNum *N3) {
    bigSum(N1, -N2, N3);
}

A: The BigNumber problem in most Computer Science classes is designed to make you have to do the arithmetic "by hand" precisely as you describe: convert each character to an integer, subtract, and borrow where appropriate.
Your plan attack, just as you've described it, should be only a few lines.  In pseudocode, something like this:
for each character (right to left):
    difference = N1.digit[i] - N2.digit[i];
    if (difference < 0)
        N1.digit[i - 1]--;
        difference += 10;
    N3.digit[i] = difference;

(Plus a little extra hassle to apply the same logic to the decimal digits too.)
It sounds like you had the right idea, and perhaps just over-thought the implementation?


text:
Q: -bash: cannot execute binary file on cloned drive I cloned the SD card of one of my Raspberry Pi onto a larger SD card.
Everything went smooth and I was able to expand the root partition.  The system boots nicely and I am able to SSH to it.
Everything seems to behave normally, like on the previous SD, except for a few programs.
I cannot run lynx nor curl on the cloned card... many other programs are running fine but not these two even though they run smoothly on the original card.
When I run either lynx or curl, I get:
-bash: /usr/bin/lynx: cannot execute binary file

Any tips on what I should try ?
Fabien


text:
Q: how to get last values of email after the @ i am trying to determine the best way to determine whether an email address is an  outlook or hotmail address.
i therefore need to collect the values after the @
i.e
testemail@outlook.com

caputure the @
however this will not work in all instance as
this email address is valid:
"foo\@bar"@iana.org

i read that a solution could be to explode it, i.e:
$string = "user@domain.com";

$explode = explode("@",$string);

array_pop($explode);

$newstring = join('@', $explode);

echo $newstring;

this solution seems bit long and only captures the first values
would really appreciate some help

A: if You explode This :
$string = "user@domain.com";

$explode = explode("@",$string);

it Will be :
$explode[0] = user
$explode[1] = domain.com

A: try to use array_reverse() ti pick the last value of email:
<?php
$email='exa@mple@hotmail.com';
$explode_email=explode('@',$email);
$reversed_array=array_reverse($explode_email);
$mailserver=explode('.',$reversed_array[0]);

echo $mailserver[0];
?>

A: You could always just keep it simple and test if either value exists in the string using strpos() or stripos().
if ( FALSE !== stripos($string, 'outlook') {
    // outlook exists in the string
}

if ( FALSE !== stripos($string, 'hotmail') {
    // hotmail exists in the string
}

A: I would recommend matching with a regular expression.
if (preg_match("/\@hotmail.com$/", $email)) {
    echo "on hotmail";
} else if (preg_match("/\@outlook.com$/", $email)) {
    echo "on outlook";
} else {
    echo "different domain";
}

Additionally, if you want to capture full domain to variable, you can do it like this:
$matches = [];
if (preg_match("/^.*\@([\w\.]+)$/", $email, $matches)) {
    echo "Domain: " . $matches[1];
} else {
    echo "not a valid email address.";
}

A: I hope this will be easy for you to understand.
<?php
$emailAddress = 'mailbox@hotmail.com'; //Email Address

$emailStringArray = explode('@',$emailAddress);  // take apart the email string.

$host = $emailStringArray[1];  //last string after @ . $emailStringArray[0] = Mailbox  & $emailStringArray[1] = host
if($host == "hotmail.com" || $host == "outlook.com"){
//matches to outlook.com or hotmail.com
}
else{
    //Does not match to outlook.com or hotmail.com
}

A: Try this :
$emailAddress = 'example\@sometext\@someothertext@hotmail.com';

$explodedEmail = explode('@', $emailAddress);
$emailServerHostName = end($explodedEmail);
$emailServerNameExploded = explode('.', $emailServerHostName);
$emailServerName = $emailServerNameExploded[0];

echo $emailServerName;


text: Q: Как скомпилированное в .exe файл приложение может работать на разных архитектурах процессора? Заинтересовало, как одно приложение, которое компилируется в .exe файл (не важно на каком ЯП) может исполняться на разных архитектурах процессора (у Intel это IA-32 и IA-64, а у AMD это Zen)?


text:
Q: Ionic 6 hide part of datetime header I am using Ionic 6 with Angular. I have a datetime component and I have set the title slot, such as:
<ion-datetime [showDefaultTitle]="false" presentation="date">
  Title
</ion-datetime>

The issue is that this displays my title as subtitle and another title containing the currently selected date as the header. On their example in their own documentation this is not even there.
My question is how can I remove this additional header?
It is added with the class datetime-selected-date. I tried not displaying this class by setting the property display: none but it does not do the trick even when doing this with ::ng-deep.

A: I have used this structure to display a title above the date picker, without displaying the date in the title:
<ion-item>
    <ion-label>...</ion-label>
    <ion-datetime>...</ion-datetime>
</ion-item>


text:
Q: ajax with two events i want to know how add two events in the same ajax
 <script type="text/javascript">
$(document).ready(function(){

    $('#department').on('change',function(){
        var deptID = $(this).val(); console.log(deptID);
        if(deptID){
            $.ajax({
                type:'POST',
                url: BASE_URL+'User/listHospital',
                data:'id='+deptID,
                success:function(html){
                    $('#hospital').html(html);
                    $('#specialisation').html('<option value="">Select hospital</option>');
                         $('#special').html('<option value="">Select hospital</option>');
               }
            });
</script>

here i had used on change event i want to add one more event on focus what should i do for it please help

A: I don't completely understand your question but, is this how you want it?
$("#department").on({

    'change': function(){
          //ajax here
    }

    'focus': function(){
          //ajax here
    }

});


text:
Q: API error when adding an extension attribute I'm trying to follow Magento's tutorial for adding an extension attribute.  I want to add an extension attribute called "exportedFlag" to the Invoice class, and have it returned through the V1/invoices/ API method.
Here's my API call
http://magento.test/rest/V1/invoices/?
searchCriteria[filter_groups][0][filters][0][field]=store_id&
searchCriteria[filter_groups][0][filters][0][value]=1&
searchCriteria[filter_groups][0][filters][0][condition_type]=eq

Here's the error I'm getting:
Fatal Error: 'Uncaught TypeError: Argument 2 passed to
MyCompany\\Invoice\\Model\\Plugin\\Invoice\\Repository::afterGetList()
must be an instance of Magento\\Framework\\Api\\SearchResults,
instance of Magento\\Sales\\Model\\ResourceModel\\Order\\Invoice\\Collection given,
called in /var/www/magento2/lib/internal/Magento/Framework/Interception/Interceptor.php
on line 146 and defined in
/var/www/magento2/app/code/MyCompany/Invoice/Model/Plugin/Invoice/Repository.php:53
Stack trace:
#0 /var/www/magento2/lib/internal/Magento/Framework/Interception/Interceptor.php(146):
MyCompany\\Invoice\\Model\\Plugin\\Invoice\\Repository->afterGetList(Object(Magento\\Sales\\Model\\Order\\InvoiceRepository\\Interceptor),
Object(Magento\\Sales\\Model\\ResourceModel\\Order\\Invoice\\Collection),
Object(Magento\\Framework\\Api\\SearchCriteria))
#1 /var/www/magento2/lib/internal/Magento/Framework/Interception/Interceptor.php(153):
Magento\\Sales\\Model\\Order\\InvoiceRepository\\Interceptor->Magento\\Framework\\Interception\\{closure}(Object(Magento\\Framework\\Api\\SearchCriteria))
#2 /var/www/mag' in '/var/www/magento2/app/code/MyCompany/Invoice/Model/Plugin/Invoice/Repository.php' on line 53

Here's the relevant code
/**
 * Class Repository
 * @package MyCompany\Invoice\Model\Plugin\Invoice
 */
class Repository
{
    /**
     * Adds the "exported flag" to invoice extension attributes.
     *
     * @param \Magento\Sales\Api\InvoiceRepositoryInterface $subject
     * @param \Magento\Framework\Api\SearchCriteriaInterface $searchCriteria
     * @return \Magento\Framework\Api\SearchResults
     */
    public function afterGetList
    (
        \Magento\Sales\Api\InvoiceRepositoryInterface $subject,
        \Magento\Framework\Api\SearchResults $searchResult
    ) {
        /** @var \Magento\Catalog\Api\Data\InvoiceInterface $invoice */
        foreach ($searchResult->getItems() as $invoice) {
            $this->addExportedFlagToInvoice($invoice);
        }
        return $searchResult;
    }
}

For reference, here's the comparable bit of code from Magento's Github example
/**
 * Class Repository
 * @package MyCompany\Invoice\Model\Plugin\Invoice
 */
class Repository
{
    /**
     * Add Social Links to product extension attributes
     *
     * @param \Magento\Catalog\Api\ProductRepositoryInterface $subject
     * @param \Magento\Framework\Api\SearchCriteriaInterface $searchCriteria
     * @return \Magento\Framework\Api\SearchResults
     */
    public function afterGetList
    (
        \Magento\Catalog\Api\ProductRepositoryInterface $subject,
        \Magento\Framework\Api\SearchResults $searchResult
    ) {
        /** @var \Magento\Catalog\Api\Data\ProductInterface $product */
        foreach ($searchResult->getItems() as $product) {
            $this->addExternalLinksToProduct($product);
        }
        return $searchResult;
    }
}

Why is Magento passing an instance of Magento\\Sales\\Model\\ResourceModel\\Order\\Invoice\\Collection as my second parameter to afterGetList, when Magento's example shows that the second parameter should be \Magento\Framework\Api\SearchResults?


text:
Q: Dynamically Invoke Method from method name string? I have the following code:
 public string GetResponse()
    {
        string fileName = this.Page.Request.PathInfo;
        fileName = fileName.Remove(0, fileName.LastIndexOf("/") + 1);

        switch (fileName)
        {
            case "GetEmployees":
                return GetEmployees();
            default:
                return "";
        }
    }

    public string GetEmployees()
    {

I will have many of these. They will all return a string and want to know if there is a way to avoid the switch case. If there is, is there a way to return "Not Found" if the method does not exist?
Thanks

A: Use reflection to obtain the methods:
public string GetResponse()
{
    string fileName = this.Page.Request.PathInfo;
    fileName = fileName.Remove(0, fileName.LastIndexOf("/") + 1);

    MethodInfo method = this.GetType().GetMethod(fileName);
    if (method == null)
        throw new InvalidOperationException(
            string.Format("Unknown method {0}.", fileName));
    return (string) method.Invoke(this, new object[0]);
}

This assumes that the methods you are calling will always have 0 arguments. If they have varying number of arguments you will have to adjust the array of parameters passed to MethodInfo.Invoke() accordingly.
GetMethod has several overloads. The one in this sample will return public methods only. If you want to retrieve private methods, you need to call one of the overloads to GetMethod that accepts a BindingFlags parameter and pass BindingFlags.Private.


text:
Q: How can i implement Twitter SSO in iOS 4.x? We have, in iOS 5, a nice way to get access to the Twitter's account, and so, implement a single sign on mechanism.
Ref.: http://developer.apple.com/library/ios/#samplecode/Tweeting/Listings/Tweeting_TweetingViewController_m.html
But what happens if you wanna distribute an app that could run in iOS 4.x devices?.
Is it there a library somewhere to do so?.
Thank you!

A: This is what I use for Twitter in my iOS 4+ app: https://github.com/bengottlieb/Twitter-OAuth-iPhone
You won't get the Twitter credentials from directly from the OS like in iOS 5, but once the user enters them, it will authenticate against twitter. So if you are linking a user's Twitter account with an account in your app, this would allow you to authenticate them.
Then just only use this library for your iOS 4 users and use iOS Twitter Framework for iOS 5 users.


text:
Q: rails add object in javascript url I use this function on a js file and it works
 $(function() {

$("#badgebutton").click(function() {
    var assertions = [
        "http://www.exemple.com/patents/5555/badge.json"
    ];
    OpenBadges.issue(assertions, function(errors, successes) {
        console.log("callback called");
        console.log("Errors:", errors);
        console.log("Successes:", successes);
    });
});
});

In place of the number :
"http://www.exemple.com/patents/5555/badge.json"

I would like to use the patent.id. I tried this :
"http://www.exemple.com/patents/#{@patent.id}/badge.json"

and some other solution without success..

A: Try doing this:
"http://www.exemple.com/patents/<%= @patent.id %>/badge.json"

But, it's advisable to use routing helper methods generated by Rails when you define them in your routes.rb file. For example:
<%= badge_patents_path(@patent, :format => :json) %>

A: You should pass the patent id (or better the whole url) to the js file using JS context which can be done in a few ways:

*

*Using globals:

In your partial (erb):
<script type="text/javascript">
  window.patent_url = "http://www.exemple.com/patents/#{@patent.id}/badge.json"
</script>

Then use the global patent_url variable in the JS file.

*Redo your JS file to encapsulate the JS logic but receive proper parameters like this.

It could look something like this:
window.badgebutton_handler = function(url) {
  OpenBadges.issue(url, function(errors, successes) {
    console.log("callback called");
    console.log("Errors:", errors);
    console.log("Successes:", successes);
  });
}

and bind the handler like this in the erb file:
<script type="text/javascript">
  $("#badgebutton").click(function() {
    badgebutton_handler("http://www.exemple.com/patents/#{@patent.id}/badge.json");
  });
</script>

The issue is that you should pass the variable or url where you have it and that's the ERB template files.


text:
Q: How to get all dates of week into an array in JavaScript I am trying to get all dates into an array in JavaScript. I am given only start date and end date of week. Now I want all dates in array that lies in that range of week. For example my week range is -  Oct 26, 2014 - Nov 1, 2014. Now I want [26 ,27 ,28 ,29 ,30 ,31 , 1] which includes all dates of week.

A: Do something like this:
var date = new Date(2014, 10, 28, 0, 0, 0, 0);
const DAY = 1000 * 60 * 60 * 24;
var i;
for (i = 0; i < 7; i++) {
    alert(date);
    date.setTime(date.getTime() + DAY);
}


text:
Q: Working with Multiple Forms C++ I am currently developing a project that involves using two forms. The first form has button which opens the second form. The second form has a textbox and a button. When the button is clicked a particular result shows in the textbox. The issue is that when the second form is closed, the information in the textbox is 'forgotten'. How do I make the textbox keep its values even though the second form is closed?
The code for the button in the second form is shown below:
 int result = Convert::ToInt32(time1ComboBox->Text) * 200;
 parkTextBox1->Text = result.ToString();
 statusTextBox1->Text = "Occupied";

Any help will be appreciated thanks.

A: You are calling function to display the result not storing it any where try to use
global variables or this
String S = "Occupied"
statusTextBox1->Text = S ;

Your result will be saved there or you should give more info on problem


text:
Q: CPU % usage of all pid I can't obtain CPU% usage of all the pid, without know any program names.
I feel I am close to the solution, this is what I've done so far:
for line in $(pgrep -f chrome); \
   do echo -n $line" - ";       \
   ps -p $line -o %cpu | sed -n 2p | sed 's/ //'; done

In this example I obtain only all chrome pid.. in next step I want all executing pid.

A: You can do this easily with the top command alone.
To order by CPU percentage (descending), you could use top -o -cpu

A: If you don't want to use top for some reason, couple of other ways I can think of doing this.
> ps -e -o "%p-%C"

Or if you wanted to do it in a script, something like (alternatively could just parse ps again or check /proc/pid/stat for cpu usage)
#!/bin/bash
shopt -s extglob
for line in /proc/+([0-9]); do
  echo -n "${line##*/}- "
  ps -p "${line##*/}" -o %cpu | sed -n 2p | sed 's/ //'
done

Where

*

*shopt -s extglob Turns on extended file globing in bash

*+([0-9]) Matches any files containing 1 or more digits

*${line##*/} Strips everything before and including the last / character


text:
Q: Alternatives to Adobe's PDF Optimizer? Acrobat Professional features a PDF Optimizer tool, as reviewed here.
This tool analyzes the space usage within a PDF file in terms of image size, fonts, ...
Are there more lightweight and/or affordable tools that do the same for existing PDF files?

A: I'm not aware of any such tools.
You can try to get the information you want with pdftk and build such a tool yourself.
Here is a howto to reduce the PDF file size from the command line.


text:
Q: Novel where a predator comes into being Novel where alien enters room through wall and invites author to publish all through galaxy and predator chases him to satisfy a universal law

A: Novel where a predator comes into being
Dimension of Miracles, a 1968 novel by Robert Sheckley. Maybe you will recognize one of these covers. Plot summary from Wikipedia:

Thanks to a computer error, Tom Carmody, an unlucky civil servant, wins the main prize of the Galactic Lottery. Being a human from the Earth, he doesn't possess galactic status and shouldn't even be eligible. However, he obtains the Prize before the mistake is found out and is allowed to keep it. That's when his adventure begins, since, not being a space-traveling creature, he has no homing instinct that can guide him back to Earth, and so the galactic lottery organizers cannot transport him home. At the same time, his removal from his home environment has caused, by the 'universal law of predation', a predatory entity to spring into existence that perpetually pursues and aims to destroy him. So Carmody is forced to be on the run, and with the help of his Prize meets several well-meaning (but usually not very competent) aliens that attempt to find where, when and which Earth he belongs on. He ends up transporting from Earth to Earth: different phases and realities of his planet, which of course, is not in the time or condition he expects it to be.

Novel where alien enters room through wall
The alien messenger does not come through the wall, but appears inexplicably in the middle of Carmody's living room:

A moment later there was a clap of thunder and a flash of lightning from the middle of the living room. Carmody sat upright and clutched at his throat for no particular reason. The thunder rumbled for several seconds, then was replaced by a paean of trumpets. Carmody hastily removed his feet from the marble table. The trumpets ceased, and were replaced by a brave skirling of bagpipes. There was another flash of lightning, and a man appeared in the middle of the brilliance.

and invites author to publish all through galaxy
No, there is nothing about publishing, and the protagonist is not an author, he is some kind of office worker:

It had been a typically unsatisfactory day. Carmody had gone to the office, flirted mildly with Miss Gibson, disagreed respectfully with Mr. Wainbock, and spent fifteen minutes with Mr. Blackwell, discussing the outlook for the football Giants.

The Messenger has come to tell Carmody he's won a prize:

Then I shall explain; you, Mr. Carmody, have won a Prize in the Intergalactic Sweepstakes. Your coefficients were pulled by the Random Selector for Part IV, Class 32 Life-Forms. Your Prize—a very handsome Prize, I believe—is waiting for you at Galactic Center."

and predator chases him to satisfy a universal law

"Your predator was born out of a personification and solidification of universal law. This predator can feed exclusively and solely on you. The creature is shaped as a respondent and complement to your characteristics. Even without seeing it, we can know that its jaws are shaped to bite Carmodys, its limbs are articulated to seize and grasp Carmodys, its stomach has the peculiar and unique ability to digest Carmodys, and its personality is designed to take advantage of the Carmodic personality."


text:
Q: HTML/firefox/webkit weird behaviour of '#id' links that alters page visual content Normal page looks like this: http://hell.orts.ru:8004/snapboard/threads/id/3/
However, if …#fragment_id is used in the link, like http://hell.orts.ru:8004/snapboard/threads/id/3/#snap_post130, browser doesn't just scroll the page to that element, but visually alters (breaks) content of the page.
No javascript-effects, supposedly (at least the problem is still the same with NoScript).
What di I understand wrong, what actually happens and how to fix it?
Note: contents of the example links will certainly change in the future; I don't know where it would be appropriate to save them as more permanent examples. Source code that produces those pages is here: https://bitbucket.org/hoverhell/xmppforum/src/c38dc011d15.

A: I can't access the example web pages, but it's possible with the CSS 3 pseudo-class :target.
A simple example for a simple "tabbed page":

A
B
C

Content A

Content B

Content C

Demo: http://jsfiddle.net/UGwHH/

A: This looks like something called an incremental reflow bug. You can also trigger it by using View - Page Style - No Style and View - Page Style - Basic Page Style. But I don't know anything about what causes reflow bugs, you should file a bug.


text:
Q: Google OAuth2 authentication in page instead of popup I'm building a Bootstrap page that requires Google authentication. I've got everything setup and working, however the popup asking for authentication bugs me.  I would rather have that in a panel.
Does anyone know if that's possible, perhaps with an iFrame or so? I can't seem to find anything.


text:
Q: Real function to entire functions Let $g:[0,\infty) \rightarrow \mathbb{R}$ be an increasing function. Is there a way to construct an entire function $f(z)$ such that $f(x)=g(|x|)$ for all real $x$?

A: You should keep in mind analytic continuation. Let $f:\mathbb R\rightarrow\mathbb R$
 be a $C^\infty$ function ; if there exists an entire function extending $f$, then
(1) It is unique by analytic continuation,
(2) The function $f$ must be real-analytic.
Of course (2) is not sufficient: think about the real-analytic $x\mapsto\frac{1}{1+x^2}$, which does NOT have an entire extension, since by analytic continuation, that extension should coincide with $\mathbb C\ni z\mapsto \frac{1}{1+z^2}$, which has poles at $\pm i$. For a real-analytic $f$, you can formulate a criterion dealing with the size of derivatives. Such a function has an entire extension iff
$$\forall R>0,\exists C_R,\forall n\in\mathbb N,\quad
\vert f^{(n)}(0)\vert\le C_R\frac{n!}{R^n}.
$$
On the other hand, real-analyticity of a $C^\infty$
$f$ on the real line is equivalent to
$$
\forall x\in \mathbb R,\exists r>0,\exists C>0, \exists R>0,\forall n\in\mathbb N,\quad
\Vert f^{(n)}\Vert_{L^\infty(B(x,r))}\le C\frac{n!}{R^n}.
$$

A: You certainly need some smoothness condition for this to be possible.  In fact, the condition is that $f$ be extendable to an even, real-analytic function on the  line which kind of makes the result a tautology since then $f$ has the form $\sum_{n=1}^\infty a_{2n} z^{2n}$.


text:
Q: how to clone a unmerged git pull request given webhook information?(using script) I've tried googling and haven't had much luck. The question is pretty straight forward. Given information from a github pullrequest webhook,how would one clone that pull request? Reason is because I plan to run some stuff on future pull request on a automated basis.
Thanks

A: From the official documentation:
git fetch origin pull/<id>/head:<some_local_ref>


text:
Q: Hibernate queries - why are they so weird? I was just looking at console and I notices Hibernate queries are looking werid.
Hibernate: select client0_.id as id1_1_0_, client0_.address as address2_1_0_, client0_.name as name3_1_0_, client0_.client_no as client_n4_1_0_, client0_.ssn as ssn5_1_0_ from clients client0_ where client0_.id=?

Hibernate: select orders0_.CLIENT_ID as CLIENT_I5_1_0_, orders0_.id as id1_0_0_, orders0_.id as id1_0_1_, orders0_.CLIENT_ID as CLIENT_I5_0_1_, orders0_.ORDER_DATE as ORDER_DA2_0_1_, orders0_.ORDER_DESC as ORDER_DE3_0_1_, orders0_.ORDER_NO as ORDER_NO4_0_1_ from ORDERS orders0_ where orders0_.CLIENT_ID=?

Is this some kind of HQL?
Regards.

A: No. It's not HQL - if you read it carefully, you'll see that it's straight-forward ANSI Sql.
It has machine-generated, non-human-friendly column aliases, but it's sql.

A: Hibernate Query Language(HQL) helps to write Queries in object oriented way.So that we are free to migrate from one data base management system to other. For example MySQL to Oracle DB or vice versa.
The HQL is converted in to SQL by Hibernate. The same happens for  Criteria queries too.
For example:
         HQL : from Student
         SQL : select * from student


text:
Q: inserting test data in java entity table I used Hibernate ddl generation of SQL to generate an entity's table (I think.) Anyway, there's hashcode field. My questions are:

*

*Is that field necessary?

*If I'm inserting test data in the table using SQL, what do I set the
value to? From what I read here, native java implementation uses
memory address to feed hash function? (Java -- Object.hashCode() algorithm)

*If I wrote a mapped supperclass for all serialized entity to inherit
which performed a regular hash of the entity's Id field, would I
be causing myself some grief later?  (I think I got that idea from
'effective java'.)

A: There should be by no means a hashCode field in your table. If Hibernate generated such a field, somewhere in your class hierarchy (super-classes) there is a hashCode field defined. Try to find it and mark it as @Transient. Hibernate ignores all fields of Object.class.

If I wrote a mapped supperclass for all serialized entity to inherit which performed a regular hash of the entity's Id field, would I be causing myself some grief later? (I think I got that idea from 'effective java'.)

Of cause you are in great danager to suffer from this later on :-). Do not go with such a field unless you have to like having special instances you assign random hashCodes on instance  creation that remain consistent throughout the life-cycle of the entity (including db-life).