text:
Q: Reading a text file located on the computer with NodeMCU using Lua My problem is about reading a text file (which is located in my computer) in the NodeMCU development kit. I am able to read the file content in Ubuntu terminal using a Lua script. Here I am sharing the code that I have been using for reading. Both are working pretty well in the Ubuntu terminal.
First one:
local open = io.open
local function read_file(path)
local file = open(path, "rb") -- r read mode and b binary mode
if not file then return nil end
local content = file:read "*a" -- *a or *all reads the whole file
file:close()
return content

Second one:
local fileContent = read_file("output.txt");
print (fileContent);

function file_exists(file)
  local f = io.open(file, "rb")
  if f then f:close() end
  return f ~= nil
end

-- get all lines from a file, returns an empty
-- list/table if the file does not exist
function lines_from(file)
  if not file_exists(file) then return {} end
  lines = {}
  for line in io.lines(file) do
    lines[#lines + 1] = line
  end
  return lines
end

-- tests the functions above
local file = 'output.txt'
local lines = lines_from(file)

-- print all line numbers and their contents
for k,v in pairs(lines) do
  print('line[' .. k .. ']', v)
end

My problem occurs when I have sent the code to NodeMCU, using Esplorer to send the code in. But the error occurs like this:
attempt to index global 'io' (a nil value)
stack traceback:
    applicationhuff.lua:5: in function 'file_exists'
    applicationhuff.lua:13: in function 'lines_from'
    applicationhuff.lua:23: in main chunk
    [C]: in function 'dofile'
    stdin:1: in main chunk

My general purpose is actually to read this datas and publish it to a Mosquitto Broker via MQTT protocol. I am new to these topics. If anyone can handle my problem it will be appreciated. Thanks for your help...

A:

NodeMCU does not have an io library. Therefore you get an error for indexing io, which is a nil value.
No offense, but sometimes I wonder how you guys actually manage to find your way to StackOverflow and even write some code without knowing how to do basic web research.
https://nodemcu.readthedocs.io/en/master/en/lua-developer-faq/

The firmware has replaced some standard Lua modules that don't align
  well with the SDK structure with ESP8266-specific versions. For
  example, the standard  io and os libraries don't work, but have been
  largely replaced by the NodeMCU  node and file libraries.

https://nodemcu.readthedocs.io/en/master/en/modules/file/

The file module provides access to the file system and its individual
  files.

I hope that's enough help...


text:
Q: Initialize array from pointer and size of another array In a function, I have access to the pointer and size of another array. Passing these along with the pointer, I want to add that data to a map. How can I do that without copying the underlying data twice?
void addToMap(double* ptr, size_t size, unsigned key) {

 // Here I want to add the array corresponding to the pointer location and size to the map.
 // Since adding to the map needs to copy the data once anyway, I want to prevent any other copies.
 double array[size] = ?;

 // Can I initialize this array from the data found at (ptr) to (ptr + size) without a copy?
 array& = ptr;

 _map[key] = array;

}

The data being pointed to is deleted after this function is called. The map is just a map from an integer to an array of doubles. That simply means, I want to somehow store the data associated with this key while it is still available.
Or do you have a better idea of doing this? Would using a std::vector<double> slower here?

A: You cannot define an array variable like that because the function argument can vary at runtime, and is therefore not compile time constant which is a requirement for the size of an array variable.
You'll need to allocate the array dynamically. std::vector is the simplest way to do that.
An array can also not be directly initialised from a pointer to another array, whether you're initialising an array variable (which isn't an option here) or a dynamic array. Here too, std::vector helps with the constructors that it offers.

How would I use std::vector<double> here then?

Example:
std::unordered_map<unsigned, std::vector<double>> _map;

// addToMap
_map.emplace(key, std::vector<double>{ptr, ptr + size});

I recommend using std::span<double> as the argument instead of the pointer and size.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Are memory mapped registers separate registers on the bus? I will use the TM4C123 Arm Microcontroller/Board as an example.
Most of it's I/O registers are memory mapped so you can get/set their values using
regular memory load/store instructions.
My questions is, is there some type of register outside of cpu somewhere on the bus which is mapped to memory and you read/write to it using the memory region essentially having duplicate values one on the register and on memory, or the memory IS the register itself?

A: There are many buses even in an MCU.  Bus after bus after bus splitting off like branches in a tree. (sometimes even merging unlike a tree).
It may predate the intel/motorola battle but certainly in that time frame you had segmented vs flat addressing and you had I/O mapped I/O vs memory mapped I/O, since motorola (and others) did not have a separate I/O bus (well one extra...address...signal).
Look at the arm architecture documents and the chip documentation (arm makes IP not chips).  You have load and store instructions that operate on addresses.  The documentation for the chip (and to some extent ARM provides rules for the cortex-m address space) provides a long list of addresses for things.  As a programmer you simply line up the address you do loads and stores with and the right instructions.
Someones marketing may still carry about terms like memory mapped I/O, because intel x86 still exists (how????), some folks will continue to carry those terms.  As a programmer, they are number one just bits that go into registers, and for single instructions here and there those bits are addresses.  If you want to add adjectives to that, go for it.
If the address you are using based on the chip and core documentation is pointing at an sram, then that is a read or write of memory.  If it is a flash address, then that is the flash.  The uart, the uart.  timer 5, then timer 5 control and status registers.  Etc...
There are addresses in these mcus that point at two or three things, but not at the same time.  (address 0x00000000 and some number of kbytes after that).  But, again, not at the same time.  And this overlap at least in many of these cortex-m mcus, these special address spaces are not going to overlap "memory" and peripherals (I/O).  But instead places where you can boot the chip and run some code.  With these cortex-ms I do not think you can even use the sort of mmu to mix these spaces.  Yes definitely in full sized arms and other architectures you can use a fully blow mcu to mix up the address spaces and have a virtual address space that lands on a physical address space of a different type.


text:
Q: Partial sum of infinite series In a probability excercise I concluded that the expected value is the following infinite series:
$\sum_{i=1}^{\infty} \frac{2i}{2^i}$
I wrote down the first few terms and saw that it converges to 4, however, how do I solve this properly?


text:
Q: PHP: using type hinting (scalar types & return types) for namespaced instances What is the best way to handle scalar type & return type declarations for namespaced instances?
I use namespaced classes for everything and use the 'use' aliases at the top of the class for all classes that will be used in the file.
This is an example without using scalar type & return type declarations:
file 1
use Model\ExampleA\ClassA;
use Model\ExampleB\ClassB;

$classA = new ClassA();
$classB = new ClassB();
$result = $classB->action($classA);

file 2
namespace Model\ExampleB;

class ClassB
{
    /**
     * @param  ClassA $classA The ClassA instance.
     * @return ClassA         Returns the ClassA instance.
     */
    public function action($classA)
    {
        return $classA;
    }
}

Now if using scalar type & return type declarations, file2 will instead be:
namespace Model\ExampleB;

use Model\ExampleA\ClassA;

class ClassB
{
    /**
     * @param  ClassA $classA The ClassA instance.
     * @return ClassA         Returns the ClassA instance.
     */
    public function action(classA $classA) : classA
    {
        return $classA;
    }
}

So if using scalar or return type declarations for namespaced instances, I have to use the 'use' alias again at the top of file2 just for the type hinting to work.
I would much prefer to use the 'object' data type for scalar type or return type for namespaced instances and keep the @param and @return data types in the docblock as the instances like this:
namespace Model\ClassB;

class ClassB
{
    /**
     * @param  ClassA $classA The ClassA instance.
     * @return ClassA         Returns the ClassA instance.
     */
    public function action(object $classA) : object
    {
        return $classA;
    }
}

Is this OK? Or is my other example the best way to do this?

A: I don't really understand your problem.

*

*If both classes (ClassA and ClassB) are in the same directory, no need to use the use statement.

*Scalar type will indicate to your colleague that your method need an instance of this class. This is useful, it documents your code and prevent bugs. See that as a guideline.
Of course your comment will indicate the same thing but the problem is: comments can lie. If somebody modify your code and not your comment to accept an object ClassC (for example) instead of ClassA, it will bring quite some confusion. Imagine a whole codebase like that.
I saw misleading comment creating nasty bugs. More than once.

*A use statement at the top of your file doesn't cost anything. Even better: if you have a lot of them, it's a good indicator that your class should be split to respect the SRP. Plus it describes your dependencies. It's always good to know what you can affect when you modify your code.

Conclusion: I would suggest that you use scalar and return types and don't be afraid by the use statement.
To explain a bit why namespaces were introduced in PHP:
Namespaces allow you to have different classes with the same name located in different filepath without having any name collision. If you have two classes called ClassA, how the interpreter can know what ClassA you want to use?
Since your two classes with the same name need to be located in different folders, your namespaces will be different. PHP will know what class to use. It has nothing to do with class instantiation.
Before the namespaces you had some nasty class names like Mage_Application1_Entity_Model.php which was describing the filepath. Ugly as hell.


text:
Q: How to Populate REST APIs with Azure Data Factory Pipeline with Multiple Entries I am trying to establish a way of ingesting multiple company data with Azure Data Factory using HTTP Link Service.
The below image shows how to ingest a single data source or a single entry using the HTTP link
https://duedil.io/v4/company/gb/06999618.json

The above would give me the financials for a single company. If we want to ingest the financials of another company with company id of 07803944 we would have to replace the above link with
https://duedil.io/v4/company/gb/07803944.json
For obvious reasons it would not be practical to have a copy activity or pipeline for every company we need the financials for.
Therefore, can someone let me know if's possible to parameterize the link service to ingest multiple companies in the same copy activity? Alternatively, simply add individual company ids to the link service?
I tried the following, but it didn't work.


text:
Q: forToWhile on Practice-It I'm currently a beginner in java and while practicing I came across this practice site, and I can't quite seem to get part c. I'm supposed to convert the given for loop code into a while loop code, and I'm not sure why my code doesn't print out the exact same thing as the for loop. Any help would really be appreciated!

A: You need  to move

*

*int j = 1; to inside the first loop, below while (i <= 2) {

*int k = 1; to inside the second loop, below while (j <= 3) {
If you don't do that, then neither of the inner loops will run after the first iteration of the outer loop, because their exit conditions have  already been met.  But resetting the index variables to 1 in both cases allows the inner loops to re-run.


text:
Q: cURL posting xml : getting Error Message: Generic Error I have the following code, to send XML data to a web service,
I keep getting this error message  [GENERIC ERROR] as a resopnse
I searched well, and couldn't find where is the error,
I am not sending from an SSL enabled website, and I have cURL enabled,
<?php
include "curl.php";
$xml2 = "<CC5Request>
<Name>esttest</Name>
<Password>EST741852</Password>
<ClientId>4444</ClientId>
<Mode>P</Mode>
<OrderId>8e8d031cb20a9d274f4ae3ccd0516053</OrderId>
<Type>Auth</Type>
<Number>4242424242424242</Number>
<Expires>10/09</Expires>
<Cvv2Val>000</Cvv2Val>
<Total>4.72</Total>
<UserId>ismail</UserId>
<Currency>949</Currency>
<email>imengubeti@est.com</email>
<BillTo>
<Name>ismail</Name>
<Street1>deneme</Street1>
<City>adfs</City>
<PostalCode>06700</PostalCode>
<Country>792</Country>
<TelVoice>0_312_446_50_07</TelVoice>
</BillTo>
<ShipTo>
<Name>ismail</Name>
<Street1>deneme</Street1>
<City></City>
<PostalCode>06700</PostalCode>
<Country>792</Country>
</ShipTo>
<Extra>
</Extra>
</CC5Request>";

$URL = "https://url/cc5ApiServer";

$ch = curl_init($URL);
curl_setopt($ch, CURLOPT_MUTE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
curl_setopt($ch, CURLOPT_POSTFIELDS, "$xml2");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
if(curl_errno($ch))
    print curl_error($ch);
else
    print_r($output);
curl_close($ch);

?>

A: It is likely that the string you get is actually the response body from the remote server serving $URL, so there's no problem with curl, the problem is that the server doesn't like the exact contents you sent it.


text:
Q: How to pass length in CRC16 modbus calculation in java? How to pass length in  CRC16 modbus calculation in java?
I have found the following method in the link:
http://www.codeproject.com/Articles/19214/CRC-16-Calculation
How to pass length value in the second argument.
public int crc16(byte[] modbusframe,int Length)
 {
    int i;
    int index;
    int crc_Low = 0xFF;
    int crc_High = 0xFF;

    for (i = 0; i<Length; i++ )
    {
         index = crc_High ^ (char)modbusframe[i];
         crc_High = crc_Low ^ crc_table[index];
         crc_Low = (byte)crc_table[index+ 256];
    }

    return crc_High*256+crc_Low;
 }

Thanks in advance..

A: Number of initialized variables array modbusframe.
modbus_bytes[**0**]=device_address;
modbus_bytes[**1**]=data_type;
modbus_bytes[**2**]=(byte)start_address_higer;
modbus_bytes[**3**]=(byte)start_address_lower;
modbus_bytes[**4**]=0x00;
modbus_bytes[**5**]=length;

int crc_result=CRC.crc16(modbus_bytes,**6**);


text:
Q: "Boy howdy!" Where did this expression come from, who uses it, and what does it convey? I recently became aware of "Boy howdy!" and figured it was some kind of rural expression of enthusiasm, but I want a bit more clarity.
My first encounter was in a Western novel:

It was strange, having the local bar next to the cemetery, but I'd seen stranger things since arriving in Vietnam. Boy howdy.
Johnson, Craig. Another Man's Moccasins: A Longmire Mystery (Walt Longmire Mysteries Book 4) (p. 27). Penguin Publishing Group.

The second encounter was in the TV series letterkenny, a comedy about rural Canadians. The characters use the term quite a bit. The show is a lampoon of the characters, mainly the farm-raised ones who are self-labeled the "hicks".
The Free Dictionary gives this citation:

Boy howdy! Rur. an exclamation of excited surprise.
Bob: Well, I finally got here.
Fred: Boy howdy! Am I glad to see you!
Bill: How do you like my horse?
Fred: That's one fine-looking filly! Boy howdy!

Urban Dictionary is less kind about the usage, as usual, suggesting the term can be used ironically, but some of the participants add this curious gloss:

*An anatomical orifice used in the act of sex, such as a woman's vagina or a person's anus. The mouth is not typically referred to as a 'boy howdy,' though it, too, fits this description.

Which throws me a curve. I've never heard such a term for that particular portion of anatomy until now.
So I'd appreciate something a bit more authoritative about this idiom in all its aspects.

A: "Boy Howdy" was made famous in the USA by the cover of CREEM, which used an image by R. Crumb for its logo starting with its second issue in summer 1969. There are differences of opinion as to whether Crumb was actually commissioned to do this or not:
https://www.crumbproducts.com/Boy-Howdy-t-shirt_p_596.html
https://www.creem.com/shop/boy-howdy
The Crumb page has this to say about the origin of the phrase:
Boy Howdy! is an exclamation that was popular during the era of World War 1. Crumb probably heard it on one of his 78 records from that time. Example of its use: "Boy Howdy is it hot!"
Google Ngram Viewer seems to bear this out:
https://books.google.com/ngrams/graph?content=Boy+howdy&year_start=1800&year_end=2019&corpus=en-2019&smoothing=3

A: As is often the case, the Urban Dictionary definition is completely made up in order to troll/amuse/confuse people. Note that anyone can submit a definition and that there is very little moderation; such "definitions" are common.
The true etymology is almost certainly from "howdy" (see The Free Dictionary), a word for "hello" stereotypically associated with the American West. The definition you cited above—"an exclamation of excited surprise"—is likely accurate.
This article from "Word Detective" presents a more detailed etymology; I'm not sure if the source is reliable, but it seems very plausible:

"Howdy" is a short form of the phrase "How do you do?", a social greeting that dates back to 16th century England.  The form "Howdy" took root in the Southern US in the 19th century and was carried West by veterans of the US Civil War.  "Howdy Doody" is simply another jocular form of "How do you do?"  Although "Howdy" as a greeting is usually associated with the West, it's actually used all over the US today, and I often hear myself blurt "Howdy!" when I'm passed on the street by someone who has a stronger memory of me than I have of them.
"Boy howdy" is another Southernism, usually attributed to Texas and evidently popular in that state.  It's a simple combination of the exclamation "Boy!" (indicating surprise) and our friend "Howdy," together used to mean "Wow!" or to indicate strong agreement with a statement or question ("Was your mom mad at you?"  "Boy howdy!  I'm grounded for a month.").  The phrase seems to have been popularized in the years after World War I, when returning soldiers who had heard it from Texans in the service brought it back to civilian life.  A related form, "boy hidy," is a fairly weird but nonetheless popular variation.  Texas, land of mystery.
Speaking of exclamations, the interjection "boy!" ("Boy, that sauce is hot!") is short for "Oh boy," used to introduce and emphasize a statement since the early 20th century.  The original lexical function of the phrase was simply to catch the listener's attention, equivalent to saying "Hey, mister…", but today "boy" used this way signals that the speaker considers what follows to be important or surprising ("Boy, I never thought they'd actually fire me").

A: According to J.E. Lighter, Random House Historical Dictionary of American Slang (1994) use of "boy!~" as an interjection meaning roughly the same thing as "wow!" or "gee!" or "man!" goes back only to 1894 (citing George Ade, Chicago Stories from that year).
The earliest matches in Google Books for the word pair "boy howdy" do not involve that kind of interjection, however. Instead, they use the words as a greeting. From Frances Baylor, Behind the Blue Ridge: A Homely Narrative (1887):

"That's Willy. Tildy's cousin. Bob's son. He's livin' with us now."
"Well, Willy boy, howdy," said John Shore, and the child limped down to him and they shook hands, John Shore full of kind interest and Willy all eyes.

From a subhead in the "Publishers Department: Items of Interest" section of the [Detroit, Michigan] Bulletin of Pharmacy (May 1894):

Shakespeare, Old Boy, Howdy!

And from Charles Stevenson, "Howdy," in Lippincott's Monthly Magazine: A Popular Journal of General Literature, Science, and Politics (April 1902):

"Kind o' like to hear 'em say it!— / 'Howdy, howdy!' / Know who's who right there an' then, / That's the moral truth, now, men,— / Put my trust right in him when / Man sez 'Howdy!'"
"Yes, sir, sounds like ol' times comin',— / 'Howdy, howdy!' / Hez the heft, an makes you feel / Like yore rely in the deal, / An yore friend kin sort o' 'spiel',— / Sayin' 'Howdy!'
"Folks all say in Mizzouree!— / 'Wal, wal, howdy!' / Hearty, honest, homely, gruff, / Gentle, kindly, yard-wide stuff, / Man that sez it's good enuff,— /  'Ol' boy, howdy!'
"Yes, sir, like to hear 'em say it! / 'Howdy, howdy!' / Hez a cheery, earnest ring, / No put-on, the A-I thing, / Gives yore own good-will a swing, / 'N you say, 'Howdy!'"

During World War I, "boy howdy" seems to have become a commonplace greeting among soldiers in the U.S. expeditionary force in Europe. From Burris Jenkins, Facing the Hindenburg Line: Personal Observations at the Fronts and in the Camps of the British, French, Americans, and Italians, During the Campaigns of 1917 (1917):

To give still more the atmosphere of Dixie, there is a big negro cook in a certain company. Down at the French port, where the boys landed, he saw another gentleman of color strolling about, and immediately breezed up to him as to a brother and opened up, "Boy, howdy!" The second negro replied in French.
...
This big cook has a voice like a bass violin and called out to every lad a half block away, "Boy, howdy," as nearly as I can make out and spell the vernacular greeting current in the American army.

And from "War Advertising," in the Tacoma [Washington] Times (June 1, 1918):

"Six of our [advertising] posters which are repeated around camp a good deal are:
"'Boy howdy, is your bayonet sharp?'

"Boy howdy" as an exclamation of surprise or enthusiasm appears in print by 1918. From "Americans Drive On Impetuously," in the [Philadelphia, Pennsylvania] Evening Public Ledger (July 19, 1918):

"We were just rushed into the trenches last night," said one youngster. "We were only there half an hour when the captain said, 'Boys in just twenty minutes we go over the top. There is time for every man to have a good smoke.'
"Before we reached their trenches the Heinies were running. Boy howdy! It sure gave me a glorious feeling to see the Heinies hop out like rabbits. We couldn't help laughing at 'em."

From "Canteen Notes," in the [Chicago Illinois] Advance Club News (September 15, 1918):

This man [a sergeant]'s departure seems to be the signal for more excitement, for before we could possibly have him out of sight of the canteen a boy from Camp Funston bound for Boston in the service of his Uncle Sam wants a place to lay his head and on being questioned it is learned that his funds have run out, probably a result of reckless financing, and that he has had nothing to eat since breakfast. We force him to eat and after a bath he feels better and does eat. "Boy Howdy" how he eats. You perhaps recall a time when you thought you were hungry, but this man proved he needed food by the way he put it out of sight.

From "Morale Is Maintained by 'Smokes'," a letter dated May 12, 1918, by Captain Alexander Withers of the U.S. Army, in McClure's Magazine (September 1918):

A few words to tell you how much the men appreciate the tobacco sent to them, and how much the officers appreciate their receiving it.
I heard men in the trenches bringing up supplies to-night. Suddenly the sentry in front of my dugout cried out in an excited manner, 'Boy howdy! Here it comes!' The Sergeant stepped outside of the door and returned, looking sheepish. 'It's tobacco, sir, and the men were out of it.'

From a submission from Toledo, Ohio, in "Correspondence of Local Unions," in the [Chicago, Illinois] American Photo-Engraver (December 1918):

We had our November meeting a week late on account of the [influenza] ban, and it was held on "Peace" night. Refreshments and everything. Boy howdy.

And from a letter from Captain Charles Harmon of the American Air Service in Roycroft (December 1918):

The Entente Cordiale is nowhere more cordial than between American Sammies and French Mademoiselles. One Sergeant doped it out for me thus: "We American guys and these French dames is the real grub-getters in our own countries. Us Americans have been so soft wid our women that they all the time want some more swell attention that don't jibe wid our income. And these here he-Frenchies have been petted to death. Natcherly us fellers and them girls hit it off together. Wy, this here little French gal of mine can take a couplerthree francs and go out and buy mor' 'n she can tote. And cook—Boy Howdy! Me, I gonna take home a wife that amounts to sumpin, believe me!"

The key stages in the emergence of "boy howdy" as an expression of enthusiasm thus seem to have been (1) affectionately greeting a person with words "[Name], old boy, howdy" (from the late 1800s); (2) using "boy, howdy!" as a two-word form of greeting to a person whether known to the speaker or not (popularized among U.S. troops during World War I, by 1917); and (3) extending the exclamatory use of "boy howdy!" to indicate excitement or enthusiastic approval (also popularized among U.S. troops during World War I, by 1918).
Although the earliest instance I found of "boy howdy" as a two-word greeting involves a Black military cook (attached to soldiers from the U.S. South)—and although a slightly earlier instance of such usage (from 1916), cited in the Dictionary of Regional English and mentioned in a now-deleted answer posted by user 66974, involves its use by a Black man at an army camp in Eagle Pass, Texas, there is too little evidence to assert with any confidence that "boy howdy" as a standalone greeting originated in African American speech.
Use of "boy howdy" as an excited exclamation seems not to have crossed over from U.S. troops to British troops in World War I. At any rate, Eric Partridge (who had a strong interest in British military slang of the twentieth century) never mentions it.


text:
Q: MariaDB, tomcat connection pool access denied Error First of all, I am sorry, I am not good at English.
Hi! I have some problems about connecting mariaDB from Java web project using tomcat connection pool and JNDI.
Here are Exception logs from eclipse console.
java.sql.SQLException: Cannot create PoolableConnectionFactory (Access denied for user 'root'@'localhost' (using password: YES))
    at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createPoolableConnectionFactory(BasicDataSource.java:735)
    at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createDataSource(BasicDataSource.java:605)
...(etc)
Caused by: java.sql.SQLInvalidAuthorizationSpecException: Access denied for user 'root'@'localhost' (using password: YES)
    at org.mariadb.jdbc.internal.util.exceptions.ExceptionMapper.get(ExceptionMapper.java:238)
...(etc)
Caused by: java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)
Current charset is UTF-8. If password has been set using other charset, consider using option 'passwordCharacterEncoding'
...(etc)

and I set connection pool information into Tomcat server context.xml file like this
<Resource
        name = "jdbc/maria"
        auth = "Container"
        type = "javax.sql.DataSource"
        driverClassName = "org.mariadb.jdbc.Driver"
        url="jdbc:mysql://localhost:3306/pcj01142"
        username = "root"
        password = "mypassword"
        maxActive="50"
        maxWait = "-1"/>

and There are some facts that

*

*I can connect mariadb through client console, and HeidiSQL using id 'root' and password 'mypassword'.

*Default combination of mariadb server is 'utf8_general_ci'

*There is a database in mariadb server which is named 'pcj01142'

Here are some attempts I have tried to fix my problem but doesn't work

*

*Reinstalling mariadb and apache tomcat9

*Resetting root user password

*Adding new user which have all privileges

*Stoping DB server and restarting

I also tried to start tomcat itself not through the eclipse but, result was same.
How can I fix this problem?

A: I solved this problem myself.
The problem was collision between MySQL and MariaDB using same port number(3306).
When I stoped MySQL, problem wad solved.


text:
Q: Is there a way to run git within Powershell? Is there a way to run git within Powershell?
I have a Windows 7 box with msysgit.  I'd like to have a single shell to also run all my git commands as well as play around with Powershell scripting.

A: For a better experience try the following links:

*

*Git & PowerShell Revisited

*Using Git (and everything else) through PowerShell

*Displaying GIT Branch on your PowerShell prompt

*Pimp your command-line for git

*Using Git with Windows Powershell

A: Yes, when you run the msysgit installer make sure you choose the option to install git to be able to run from the Windows command prompt.

This will add git to your PATH variable, which will make it available to PowerShell.


text:
Q: How to convert special characters in dictionary to unicode in swift //temporary dictionary
let tempDict =  ["ttTasks":"€ is euro symbol"]

//conversion should replace  € symbol with \u20ac
so final dictionary would be
finalDict = ["ttTasks":"\u20ac is euro symbol"]

NOTE: please do not suggest me replaceOccurencesOfString as i need to do this for every special character.

A: Something like this maybe:
for key in tempDict.keys {
    let data = tempDict[key]?.data(using: String.Encoding.nonLossyASCII)
    tempDict[key] = String(data: data!, encoding: String.Encoding.utf8)
}


text:
Q: Using same riverpod state provider for multiple pages I I'm using provider for state management (actually riverpod)
In my project I have a tabview and use each tab for a category and each shows news list. tabview size is not fix and I use same page for all tabs and pass category id to page.
The problem is that newsProvider allways keep last category id and all pages show same news list.
Who I can separate newsProvider list for each pages?
//create tabview in my stateFullWidget
@override
Widget build(BuildContext context) {
   return Scaffold(
   body: DefaultTabController(
     length: europeanCountries.length, // europeanCountries has dynamic size
         child: new Scaffold(
            appBar: new AppBar(

            flexibleSpace: new Column(
               children: [
                  new TabBar(
                      tabs: europeanCountries.map<Widget>((e) => getTab(e, FontAwesomeIcons.newspaper)).toList()),
                    ],
                  ),
                ),

               // dynamically create NewsList and pass category id
                body: TabBarView(children: europeanCountries.map((catItem) => NewsList(category: Category(title: catItem.title, id:catItem.id))).toList()),
              ),
            )
       )
 }

class NewsList extends StatefulWidget {
  Category category;

  NewsList({this.category});

  @override
  State<StatefulWidget> createState() {
    return _NewsListState(category:category);
  }
}

class _NewsListState extends State<NewsList> with AutomaticKeepAliveClientMixin<NewsList> {
  Category category;

  _NewsListState({this.category});

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      context.read(newsProvider).getNewsList(category.id);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Consumer(builder: (ctx, watch, child) {
      return watch(newsProvider.state).map(
        init: (value) {
          return Container();
        },
        loading: (value) {
          return Container(
            child: Center(
              child: CircularProgressIndicator(),
            ),
          );
        },
        success: (value) {
          return Container(child: getNewsItem(value.newsList));
        },
        serverError: (value) {
          return Container();
        },
      );
    });
  }

  @override
  bool get wantKeepAlive => true;
}

final newsProvider = StateNotifierProvider.autoDispose<NewsListNotifier>((ref) {
  var newsService = ref.watch(newsServiceProvider);
  return NewsListNotifier(newsService);
});

class NewsListNotifier extends StateNotifier<NewsListState> {
  final NewsService serviceRepository;

  NewsListNotifier(this.serviceRepository) : super(NewsListState.init());

  getNewsList(int catID) async {
    state = NewsListState.loading();
    DataResponse request = await serviceRepository.getNewsList(catID);
    request.maybeWhen(
      success: (value) {

        if (value.data != null) {
          state = NewsListState.success(newsList: value.data);
        }
      },
      error: (error) {
        state = NewsListState.serverError(error);
      },
      orElse: () {},
    );
  }

}

A: I finally find the answer. thanks @EdwynZN
By using family keyword, I can create some thing like a family for each category
class NewsList extends StatefulWidget {
  Category category;

  NewsList({this.category});

  @override
  State<StatefulWidget> createState() {
    return _NewsListState(category:category);
  }
}

class _NewsListState extends State<NewsList> with AutomaticKeepAliveClientMixin<NewsList> {
  Category category;

  _NewsListState({this.category});

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {

      // add category.id to newsProvider, instead of getNewsList()
      context.read(newsProvider(category.id)).getNewsList();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Consumer(builder: (ctx, watch, child) {

      //newsProvider(category.id) just listen to specific category id and not listen to all ids
      return watch(newsProvider(category.id).state).map(
        init: (value) {
          return Container();
        },
        loading: (value) {
          return Container(
            child: Center(
              child: CircularProgressIndicator(),
            ),
          );
        },
        success: (value) {
          return Container(child: getNewsItem(value.newsList));
        },
        serverError: (value) {
          return Container();
        },
      );
    });
  }

  @override
  bool get wantKeepAlive => true;
}

//using family here and pass <My State, Category id>
final newsProvider = StateNotifierProvider.family<NewsListNotifier, int>((ref, catID) {
  var newsService = ref.watch(newsServiceProvider);
  return NewsListNotifier(newsService, catID);
});

class NewsListNotifier extends StateNotifier<NewsListState> {
  final NewsService serviceRepository;
  int catID;

  NewsListNotifier(this.serviceRepository, this.catID) : super(NewsListState.init());

  getNewsList() async {
    state = NewsListState.loading();
    DataResponse request = await serviceRepository.getNewsList(catID, page, 20);

    request.maybeWhen(
      success: (value) {

        if (value.data != null) {
          state = NewsListState.success(newsList: value.data);
        }
      },
      error: (error) {
        state = NewsListState.serverError(error);
      },
      orElse: () {},
    );
  }

}


text:
Q: What is the fastest way to convert string to array in python? This is a line I read from a text file:
[54, 95, 45, -97, -51, 84, 0, 32, -55, 14, 50, 54, 68, -3, 57, 88, -1]

I used readline() to read it in as a string. Now what is the fastest way to convert it back to an array?
Thank you!

A: If that's the string, go here http://docs.python.org/2/library/functions.html#eval
>>> s = "[54, 95, 45, -97, -51, 84, 0, 32, -55, 14, 50, 54, 68, -3, 57, 88, -1]"
>>> eval(s)
[54, 95, 45, -97, -51, 84, 0, 32, -55, 14, 50, 54, 68, -3, 57, 88, -1]

A: I'm not sure that this is the fastest, but it's definitely the safest/easiest:
import ast
lst = ast.literal_eval(s)

regular eval would work too:
lst = eval(s)

Some basic timings from my machine:
>>> s = '[54, 95, 45, -97, -51, 84, 0, 32, -55, 14, 50, 54, 68, -3, 57, 88, -1]'
>>> def f1():
...    eval(s)
...
>>> def f2():
...    ast.literal_eval(s)
...
>>> timeit.timeit('f1()', 'from __main__ import f1')
31.415852785110474
>>> timeit.timeit('f2()', 'from __main__ import f2')
46.25958704948425

So, according to my computer, eval is about 50% faster than ast.literal_eval.  However, eval is terribly unsafe and should never be used on any string unless you trust it completely.  Unless this is a real demonstratable bottleneck and you trust the input 100%, I would consider the little bit of extra time worth it in exchange for being able to sleep soundly at night.

A: Since we care about speed, in this particular case I might use json.loads:
>>> import ast, json
>>> s = "[54, 95, 45, -97, -51, 84, 0, 32, -55, 14, 50, 54, 68, -3, 57, 88, -1]"
>>> %timeit ast.literal_eval(s)
10000 loops, best of 3: 61.6 µs per loop
>>> %timeit eval(s)
10000 loops, best of 3: 45.7 µs per loop
>>> %timeit json.loads(s)
100000 loops, best of 3: 6.61 µs per loop
>>> json.loads(s)
[54, 95, 45, -97, -51, 84, 0, 32, -55, 14, 50, 54, 68, -3, 57, 88, -1]

(Note that this works here because this line is sufficiently JSON-like.  It can't be used everywhere that ast.literal_eval can because not all Python literal syntax is valid JSON.)

A: I'm using python 3.6
Here's my result of an actual string separated by spaces
stringValue = "123 456 789 012 345 678"

String to List
intValue = list(map(int, stringValue.split(' ')))

result

time taken 7.586999345221557e-06
[76, 96, 127, 255, 136, 164]
time taken trying to print it 6.697199933114462e-05

String to List to numpy
intValue = np.array(list(map(int, stringValue.split(' '))))

result

time taken 2.631999996083323e-05
[ 76  96 127 255 136 164]
time taken trying to print it 0.002241893000245909

String to numpy array
intValue = np.fromstring(stringValue,dtype=int,sep=' ')

time taken 1.3830000170855783e-05
[ 76  96 127 255 136 164]
time taken trying to print it 0.0003395890007595881


text:
Q: Catch repeat - letter in PHP - Regular expressions I need to look at a string, and find - character that is used more than 1 time
$input = "stack-overflow - 2014 - new" //Contains repeated character - more than 2 times
I found all sorts of really close answers already, but not quite.
Is there a PHP regular expression to catch this case? (I have a basic regexp knowledge but this is too much for me)
$regex=' '; //// that what i need
if (preg_match('/(\w)\1{5,}/', $input)) {
 # Successful match
} else {
 # Match attempt failed
}

A: I think what you're asking is how to match multiple hyphen characters (-) with RegEx? If so, this expression will do the trick:
/-+/

/ = delimiter
- = match the hyphen character
+ = match multiple occurrences of the preceding character

A: Regex is not the best choice to count the occurrence in a string. For PHP, there exists a method called substr_count()
e.g.
$s = 'stack-overflow - 2014 - new';
if (substr_count($s, '-') >= 2) {
    // at least 2 times
}


text:
Q: How to create input samples from pandas dataframe for a LSTM model? I'm trying to create a LSTM model that gives me binary output buy or not. I have data that is in the format of: [date_time, close, volume], in millions of rows. I'm stuck at formatting the data as 3-D; Samples, Timesteps, features.
I have used pandas to read the data. I want to format it so I can get 4000 samples with 400 timesteps each, and two features (close and volume). Can someone advise on how to do this?
EDIT:
I am using the TimeseriesGenerator as advised, but I am not sure how to check my sequences and replace the output Y with my own binary buy output.
df = normalize_data(df)

print("Creating sequences for NN \n")
targets = df.drop('date_time', 1)
train = keras.preprocessing.sequence.TimeseriesGenerator(df, targets, 1, sampling_rate=1, stride=1,
                                                         start_index=0, end_index=int(len(df.index)*0.8),
                                                         shuffle=True, reverse=False, batch_size=time_steps)

This is running without error, but now the output is the first close value after input timeseries.
EDIT 2:
So thus far my code looks like this:
df = data.normalize_data(df)
targets = df.iloc[:, 3]  # Buy signal target

df.drop('y1', axis=1, inplace=True)
df.drop('y2', axis=1, inplace=True)

train = TimeseriesGenerator(df, targets, length=1, sampling_rate=1, stride=1,
                            start_index=0, end_index=int(len(df.index) * 0.8),
                            shuffle=True, reverse=False, batch_size=time_steps)

# number of samples
print("Samples: " + str(len(train)))
x, y = train[0]
print(str(x))

The output is as follows:
Samples: 8
Traceback (most recent call last):
File "/home/stian/.local/lib/python3.6/site-
packages/pandas/core/indexes/base.py", line 3078, in get_loc
return self._engine.get_loc(key)
File "pandas/_libs/index.pyx", line 140, in
pandas._libs.index.IndexEngine.get_loc
File "pandas/_libs/index.pyx", line 162, in pandas._libs.index.IndexEngine.get_loc
File "pandas/_libs/hashtable_class_helper.pxi", line 1492, in pandas._libs.hashtable.PyObjectHashTable.get_item
File "pandas/_libs/hashtable_class_helper.pxi", line 1500, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: range(418, 419)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "./main.py", line 94, in <module>
data_menu()
File "./main.py", line 42, in data_menu
data_menu()
File "./main.py", line 56, in data_menu
nn_menu()
File "./main.py", line 76, in nn_menu
nn.nn_gen(pre_processed_data)
File "/home/stian/git/stian9k/nn.py", line 33, in nn_gen
x, y = train[0]
File "/home/stian/.local/lib/python3.6/site-packages/keras_preprocessing/sequence.py", line 378, in __getitem__
samples[j] = self.data[indices]
File "/home/stian/.local/lib/python3.6/site-packages/pandas/core/frame.py", line 2688, in __getitem__
return self._getitem_column(key)
File "/home/stian/.local/lib/python3.6/site-packages/pandas/core/frame.py", line 2695, in _getitem_column
return self._get_item_cache(key)
File "/home/stian/.local/lib/python3.6/site-packages/pandas/core/generic.py", line 2489, in _get_item_cache
values = self._data.get(item)
File "/home/stian/.local/lib/python3.6/site-packages/pandas/core/internals.py", line 4115, in get
loc = self.items.get_loc(item)
File "/home/stian/.local/lib/python3.6/site-packages/pandas/core/indexes/base.py", line 3080, in get_loc
return self._engine.get_loc(self._maybe_cast_indexer(key))
File "pandas/_libs/index.pyx", line 140, in pandas._libs.index.IndexEngine.get_loc
File "pandas/_libs/index.pyx", line 162, in pandas._libs.index.IndexEngine.get_loc
File "pandas/_libs/hashtable_class_helper.pxi", line 1492, in pandas._libs.hashtable.PyObjectHashTable.get_item
File "pandas/_libs/hashtable_class_helper.pxi", line 1500, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: range(418, 419)

So it seems that even tough I am getting 8 objects from the generator I am not able to look them up. If I test the type: print(str(type(train))) I get TimeseriesGenerator object. Any advise is much appreciated again.
EDIT 3:
it turns out timeseriesgenerator did not like pandas dataframes. The issue was resolved by converting to numpy array as well as converting pandas timestamp type to float.

A: You can simply use Keras TimeseriesGenerator for this purpose. You can easily set the length (i.e. number of timesteps in each sample), sampling rate and stride to sub-sample the data.
It would return an instance of Sequence class which you can then pass to fit_generator to fit the model on the data generated by it. I highly recommend to read the documentation for more info about this class, its arguments and its usage.

A: THANKS! I was getting lots of crazy numbers coming from the dataframe. Converting it with to_numpy() just before using it solved the issue!
input_convertido = df.to_numpy()
output_convertido = df["close"].to_numpy()
gerador = TimeseriesGenerator(input_convertido, output_convertido, length=n_input, batch_size=1, sampling_rate=1)


text:
Q: Odoo module breaks after attempting to change menu After I tried to change an menu of a report in accounting module. Maybe I set something wrong at the actions field. The accounting module breaks into pieces.
Photo of current state
Is there a way for me to assemble the accounting module back? Also, whenever I press on the reporting menu, it now instant close the menu. Is there a way to fix that too?
As the odoo system is now being used, it would be great if this is possible without harming the data on the system.


text:
Q: how to iterate through array object and check the parameter matches in javascript I would like to know how to iterate through array of objects and return name in javascript.
I have array object obj in which based on type , return name.
var obj=[
{name: "suzuki", type: "vehicle"},
{name: "home", type: "land"}
]

var result = obj.forEach(e => {
  if(Object.key(e) === 'vehicle'){
    return e;
    }
});

Expected Output

suzuki

A: With the same code you've used:
var obj = [
    { name: 'suzuki', type: 'vehicle' },
    { name: 'home', type: 'land' }
];

var vehicleArray = [];

obj.forEach(e => {
    if (e.type === 'vehicle') {
        console.log(e.name); # suzuki;
        vehicleArray.push(e.name);
    }
});
console.log(vehicleArray);

Live Preview

FYI

*

*In case if you need to push those into an array use push("")

*Objects can be accessed via dot(e.type) notation

A: You can use filter to filter the array (type 'vehicle' in your case) and then use map to get the names only.

var obj = [{
    name: "suzuki",
    type: "vehicle"
  },
  {
    name: "home",
    type: "land"
  }
]

var result = obj
  .filter(e => e.type === 'vehicle')
  .map(e => e.name);

console.log(result);

A: You can make use of flatMap:

const obj=[{name: "suzuki", type: "vehicle"},{name: "home", type: "land"},{name: "car", type: "vehicle"}];

const carNames = obj.flatMap(o=>o.type=='vehicle' ? o.name : []);

console.log(carNames);


text:
Q: Create a link share feature like facebook I want to create a feature similar to facebook share link in php or javascript
When we share a link in facebook, it automatically fetch the thumbnail, title, description etc from that page.
I want to develop same feature
Thanks in Advance

A: please try this.
share

Thanks.


text:
Q: How to join 2 Xpath query? I have html structure like below (this I just take little from my html):

     //some content here

     //some content here

I want to extract content from class col-md-4 and class col-md-8 and I have got what I want with this code:
$test1 = $xpath->evaluate('//div[contains(@class,"col-md-4")]')->item(0)->nodeValue;
$test2 = $xpath->evaluate('//div[contains(@class,"col-md-8")]')->item(0)->nodeValue;

$test = $test1.$test2;

If I write code like this
$test = $xpath->evaluate('//div[contains(@class,"row")]')->item(0)->nodeValue;

I can get the result but, it's not the result in classcol-md-4 and class col-md-8 because I have many class row in my html.
and this code not work
$test = $xpath->evaluate('//div[contains(@class,"row")]//div[contains(@class, "col-md-4")]//div[contains(@class, "col-md-8")]')->item(0)->nodeValue;

With my first code that it worked, is there any to join it into one Xpath query?
Thank in advance for help me:)

A: You can use concat to combine the results of 2 or more strings, each of which can be the results of an xpath selector:
concat(//div[contains(@class,"col-md-4")], //div[contains(@class,"col-md-8")])

Example here


text:
Q: Error en la consola de grails Cuando entro a mi proyecto y desde una terminal corro el comando grails me da el siguiente error:
| Starting daemon.....
grails> | Error Interactive mode exited with error: Error reading input: Recurso no disponible temporalmente
java.lang.RuntimeException: Error reading input: Recurso no disponible temporalmente
    at grails.build.logging.GrailsConsole.readLine(GrailsConsole.java:793)
    at grails.build.logging.GrailsConsole.showPrompt(GrailsConsole.java:779)
    at grails.build.logging.GrailsConsole.showPrompt(GrailsConsole.java:805)
    at grails.build.logging.GrailsConsole$showPrompt$0.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:117)
    at org.codehaus.groovy.grails.cli.interactive.InteractiveMode.showPrompt(InteractiveMode.groovy:50)
    at org.codehaus.groovy.grails.cli.interactive.InteractiveMode$showPrompt.callCurrent(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:52)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:154)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:158)
    at org.codehaus.groovy.grails.cli.interactive.InteractiveMode.run(InteractiveMode.groovy:113)
    at org.codehaus.groovy.grails.cli.GrailsScriptRunner.main(GrailsScriptRunner.java:216)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.codehaus.groovy.grails.cli.support.GrailsStarter.rootLoader(GrailsStarter.java:236)
    at org.codehaus.groovy.grails.cli.support.GrailsStarter.main(GrailsStarter.java:264)
| Error Interactive mode exited with error: Error reading input: Recurso no disponible temporalmente
| Daemon Started

¿Alguien sabe por que puede ser?
Gracias!


text:
Q: Stop a user from circumventing IP block? A user is somehow avoiding an IP block in apache 2.2/2.4, and I can not figure out how. The company I work for hosts hundreds of sites in different datacenters; this user is attacking several of the sites we host.
Depending on the datacenter, the user with comes in with their IP in the remote_addr or X-Forwarded-For fields. We maintain two lists of "bad actors" which are in a file based on their IP address in either the remote_addr or X-Forwarded_For fields, and this file is included in the apache.conf. The lines either look like
SetEnvIf X-Forwarded-For 41\.216\.xxx\.xxx BlockedBot
or SetEnvIf Remote_Addr 41\.216\.xxx\.xxx BlockedBot. We then have the following in our apache.conf, near the bottom:
<Location />
    <IfVersion < 2.4>
        AuthType none
        Require valid-user
        Satisfy any
        Order Deny,Allow
        Deny from env=BlockedBot
        Deny from env=EmptyHost
    </IfVersion>
    <IfVersion >= 2.4>
        <RequireAll>
            Require all granted
            Require not env BlockedBot
            Require not env EmptyHost
        </RequireAll>
    </IfVersion>
</Location>

My problem is, after putting this bad actor's ip in both files, making sure they were both included, his requests still come through fine.  To double check, I used curl with the bad actor's IP in the X-Forwarded-For field, and it correctly blocks my request:
curl --header "X-Forwarded-For: 41.216.xxx.xxx" www.testexample.com/images/fpo/check-14aca5cd1a.png
The bad actor issuing the same exact request with his IP in the XFF field gets through with a 200 status code, no problem. How is this possible?


text:
Q: Bizarre IMAP issue with Outlook 2013 Have a client that is using Outlook 2013 with a GoDaddy hosted IMAP email account. This was recently setup and they created a number of new folders by right clicking on the left side near Inbox and selecting New Folder. They then moved a number of very important emails into several of these folders.  Within several minutes they started receiving popups in Outlook stating something along the lines of "IMAP server does not allow a top level folder created here" at which point the folders began to show up on the side with the tag (This computer only) indicating they were now local only folders.  This wouldn't have been a problem if the emails could be copied back out of the folders and into the Inbox but after several minutes the folders all disappeared from the tree listing and were nowhere to be found, not in the trash and no longer on the server. Unfortunately the only other computer configured with OL2013 and this same IMAP account was turned on and synced the changes before it could be taken offline to export the missing emails. Spoke to GoDaddy tech support and had them roll the mailbox to two days prior but the emails are still not on the server.
I understand that Ooutlook 2013 has made major changes to IMAP operations and now uses an OST file to store data. Any idea if there is a way to extract these disappeared "This computer only" folders from the OST file?
Has anyone else experienced something like this?


text:
Q: Displaying Image in ListBox based on FileName I am trying to display an Image in a ListBox for each Filetype returned from the database. Below is the code I am using. I think my problem is I am  trying to pass a property from the db to DirectoryInfo Property. Everything is correct until I get to FileImage = di.GetFiles();  Then I get a exception cannot find file in bin folder.  What is the best way of accomplishing this?   Thanks for any replies.
Converter stored in a folder with other converters(not in code behind).
public class ConvertFileImage : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value as string == string.Empty) return null;

            var file = @"Media/file_" + value.ToString().Substring(1) + ".png";
            ImageSource src = new BitmapImage(new Uri(file, UriKind.Relative));
            return src;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

Class that stores the files from the db
public class FilesFromDb
{
     public int Id { get; set; }
     public byte[] Data { get; set; }
     public string FileName { get; set; }
}

Property the listbox is binding to
public ObservableCollection<FilesFromDb> Files
{
     get
     {
          return mFiles;
     }
}

Property to get the image from the filename
public FileInfo[] FileImage { get; set; }

I am trying to use a foreach loop to take the Filename from the database and use that for the directory, I am failing here.
foreach (var imagetype in Files)
                    {
                        var di = new DirectoryInfo(imagetype.FileName);
                        FileImage = di.GetFiles();

                    }

Then I was binding to the converter in the xaml
<converters:ConvertFileImage x:Key="ConvertFileImage"/>

This is within a listbox item template with the listbox ItemsSource="{Binding Files}"
 <Grid Grid.Row="0" Grid.RowSpan="2" Grid.Column="0">
      <Image Source="{Binding Extension, Converter={StaticResource ConvertFileImage}}"  HorizontalAlignment="Left" />
  </Grid>

If the file was stored locally I could use something like this
 var di = new DirectoryInfo("c:/FilesFolder");  // I think that would work, but not using a property from db

A: After re-reading your question a couple of times I think I understand where you were trying to go. I believe your ConvertFileImage should look a little more like this:
public class ConvertFileImage : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
     {
         if (value as string == string.Empty) return null;

         var file = @"Media/file_" + Path.GetExtension(value.ToString()) + ".png";
         ImageSource src = new BitmapImage(new Uri(file, UriKind.Relative));
         return src;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
            throw new NotImplementedException();
    }
}

Then your binding should just pass in the filename:
<Grid Grid.Row="0" Grid.RowSpan="2" Grid.Column="0">
    <Image Source="{Binding FileName, Converter={StaticResource ConvertFileImage}}"  HorizontalAlignment="Left" />
</Grid>


text:
Q: How to use Service management ecosystem(kafka connector) in gravitee 3.x. Is their any guide or tutorial Not able to understand how to use kafka connector. do we require our own service to connect to kafka or gravitee will provide.

A: You can find out more about how to use the Kafka Connector on Gravitee here.


text:
Q: Amazon EC2 resize root device I have one amazonw ec2 instance and would like to extend root device device form 100G to 500G. After create a new 500G volume and reattached to instance.
I can see volume is there by command $lsblk. However, after I resize the disk. I cannot do it with error "The filesystem is already 26212055 blocks long.  Nothing to do!
name@ip-172-1-1-3:~$ df -h
Filesystem      Size  Used Avail Use% Mounted on
udev            3.9G  8.0K  3.9G   1% /dev
tmpfs           799M  840K  798M   1% /run
/dev/xvda1       99G   92G  3.1G  97% /
name@ip-172-1-1-3:~$ lsblk
NAME                              MAJ:MIN RM   SIZE RO TYPE
MOUNTPOINT
xvda                              202:0    0   500G  0 disk
└─xvda1                           202:1    0   100G  0 part /
name@ip-172-1-1-3:~$sudo resize2fs /dev/xvda1
resize2fs 1.42.9 (4-Feb-2014)
The filesystem is already 26212055 blocks long.  Nothing to do!

A: here's exactly what to do:
df -h #print the name of your boot partition
lsblk #show info on all your block devices
You'll see from that output what the name of the disk is of your root partition. For example, you probably see something like this:

xvde                               202:64   0   32G  0 disk
└─xvde1                            202:65   0   8G  0 part /

Our goal is to make xvde1 use the whole available space from xvde.
Here's how to resize your partition:
fdisk /dev/xvda (the disk name, not your partition)
This enters into the fdisk utility.

*

*u #Change the display to sectors

*p #Print info

*d #Delete the partition

*n #New partition

*p #Primary partition

*1 #Partition number

*2048 #First sector

*Press Enter to accept the default

*p #Print info

*a #Toggle the bootable flag

*1 #Select partition 1

*w #Write table to disk and exit

Now, reboot your instance:
reboot
After it comes back do:
resize2fs /dev/xvde1 (the name of your partition, not the block device)
And finally verify the new disk size:
df -h

A: After I follow @error2007s step 12 with "a" a #Toggle the bootable flag stop and reboot. I can not bring up instance.
Disk /dev/xvda: 536.9 GB, 536870912000 bytes
255 heads, 63 sectors/track, 65270 cylinders, total 1048576000 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000

    Device Boot      Start         End      Blocks   Id  System
/dev/xvda1            2048  1048575999   524286976   83  Linux

Command (m for help): a
Partition number (1-4): 1

Command (m for help): w
The partition table has been altered!

Calling ioctl() to re-read partition table.

WARNING: Re-reading the partition table failed with error 16: Device or resource busy.
The kernel still uses the old table. The new table will be used at
the next reboot or after you run partprobe(8) or kpartx(8)
Syncing disks.
name@ip-172-1-1-3:~$ reboot
reboot: Need to be root
name@ip-172-1-1-3:~$ sudo reboot

Broadcast message from name@ip-172-1-1-3
    (/dev/pts/1) at 10:18 ...

The system is going down for reboot NOW!
$ ssh -i "a.pem" name@ec2-172.1.1.3.compute-1.amazonaws.com -p 22
ssh: connect to host ec2-172.1.1.3.compute-1.amazonaws.com port 22: Operation timed out

A: You need to extend the available space:
$ lsblk
xvda                              202:0    0   500G  0 disk
└─xvda1                           202:1    0   100G  0 part /

$ growpart /dev/xvda 1
$ resize2fs /dev/xvda1


text:
Q: Can I target a parent node with CSS or in jQuery? I'm looking for a solution to append an element (pointer carat) to all
 tags that have an
 tag member denoting the option for expansion. Other than using JS to scrape through the entire nested menu listing, it would have been nice to do:
$('ul:parent').append('>');

Any options available?

A: You can't get a parent in CSS as that only goes down the DOM tree. You can use parent in jQuery though:
$('ul').parent().append('>');

If you're trying to find all li elements which contain a ul, you can use has:
$('li').has('ul').append('>');

A: CSS4 will have a parent selector, but that is not supported by any browsers today:
$ul > li {
  ...
}


text:
Q: What is the CSS (font-family, size) for a blockquote in Bootstrap I would think this was easy to find somewhere, but I haven't been able to. I don't want to use the blockquote class, but create a custom named one. Basically I want the same font and size, but not the border of the blockquote and a custom name.
Could anybody give me the Bootstrap CSS for blockquote?

A: Check out the source code and look for the blockquote tag.
blockquote {
    padding: 10px 20px;
    margin: 0 0 20px;
    font-size: 17.5px;
    border-left: 5px solid #eee;
}

There's lots more.  CTRL + F will help you.


text:
Q: memory address translation in hypervisor guest os Assume there is a code like this.
MOV [0x1234], EAX (intel assembly)

let's say that CPU wants to process this instruction.
and let's assume there is no hypervisor.
we are just using normal x86 CPU(protected mode) in linux environment.
now, what I understand is that
since 0x1234 is a virtual address, this needs to be translated
into physical address.(let's skip segmentation part)
CPU just pass this address(0x1234) to MMU hardware.
MMU walks the page table and access the memory contents using physical address.
am I correct?
now let's assume there is hypervisor and this code
is running from guest OS.
what happens exactly??
I know that hypervisor provides another layer of page table.
but I don't understand how exactly this works.
if the guest code "MOV [0x1234], EAX" is executed
in real CPU. the virtual address 0x1234 will be translated by
real hardware MMU. so I think this instruction has to be
rewritten(0x1234 should be replaced to another address
before the code is executed), or trapped to hypervisor...
am I wrong?
if I am wrong, please fix my understanding...
thank you in advance.

A: Answering your first question: yes you are. That's basically how virtual memory works.
Now, let's see what's happen when an hypervisor is running between the MMU and a guest OS. For performance sake, an hypervisor (weither it's a type 1 or type 2) would try to avoid trapping at each guest OS memory access. The idea is to let the guest OS managing the MMU. I will elaborate with possible implementations, one for x86 and one for PowerPC.
On x86, from the Intel's manual 3B:

27.3.2 Guest & Host Physical Address Spaces
Memory virtualization provides guest software with contiguous guest physical
  address space starting zero and extending to the maximum address supported by
  the guest virtual processor's physical address width. The VMM utilizes guest physical
  to host physical address mapping to locate all or portions of the guest physical
  address space in host memory. The VMM is responsible for the policies and algorithms
  for this mapping which may take into account the host system physical
  memory map and the virtualized physical memory map exposed to a guest by the
  VMM.

The VMM knows the current PDBR base address of the VM (the PDBR is hold in the CR3 register), since an access to CR3 will cause a VM_EXIT. The VMM will be able to maintain the real page directory on the behalf of the guest OS. I mean when the guest OS modifies its page directory to map logical address A to physical address B, the VMM traps on this, and instead of mapping A to B, it maps A to C. Thus any further access to A won't cause a #PF, it will be flawlessly routed to C through the MMU. The sad part on this approach is that the guest believes it has mapped A to B, but actually A is mapped to C, thus the VMM has to maintain a virtual page directory in case that the guest would read where it has previously mapped A. The VMM traps on this read access, and instead of saying A is mapped to B, it returns to the guest that A is mapped to C.

27.3.3 Virtualizing Virtual Memory by Brute Force
A simple-minded way to do this would be to ensure that all guest attempts to access
  address-translation hardware trap to the VMM where such operations can be properly
  emulated. It must ensure that accesses to page directories and page tables also get
  trapped. This may be done by protecting these in-memory structures with conventional
  page-based protection. The VMM can do this because it can locate the page
  directory because its base address is in CR3 and the VMM receives control on any
  change to CR3; it can locate the page tables because their base addresses are in the
  page directory.

On PowerPC, you don't have an hardware table-walk of a page directory as Intel's. Each modification of the TLB is induced by an instruction, usually from the kernel memory manager. Here again, a straightforward idea is to trap on each guest access to the TLB (setting up things to cause a VM exit when the guest execute a tlbwe instruction for instance; note: tlbwe writes an entry into the TLB). Once inside the VMM, the hypervisor decodes the trapping instruction, and emulates its behaviour, but instead of mapping A to B, it maps A to C, directly into the TLB. Again the VMM has to maintain a virtual TLB in case the guest OS wants to check what's in the TLB, and returns what it believes to have put in the TLB earlier.
To conclude, although some hardware features help in virtualizing the guest physical memory, it's generally up to the VMM to manage the effective guest-physical to host-physical memory mapping.


text:
Q: Einstein Chatbot - Add "Send" button I am looking to add "Send" button in the Einstein Chatbot which users will click to send message. Right now, there is no button so when user enter something he/she need to press enter. If we need to add a button, how do we achieve it ?

A: Seems like Send button not available on chat window at moment.  Kindly review Idea and vote for this feature.
Thanks


text:
Q: Ontario Topographic and Property Data Looking for Ontario topographic data and property line data; willing to purchase the latter.  Shapefiles or file geodatabase files would be optimal.  In terms of topographic data, I am looking for: basic outline of Ontario, county or municipal outlines, contour data, water (lines, poly, etc), buildings, and so forth.

A: You can also look at geogratis, which is a Canadian repository for all sorts of data http://geogratis.gc.ca/geogratis/MostPopular?lang=en  this link will guide you to data related to topographic data.
Geobase as a good collection of administrative boundaries, such as Municipalities http://www.geobase.ca/geobase/en/data/admin/index.html

A: Along with the above mentioned sources, Land Information Ontario data is available, but I can't speak for its accuracy - http://www.ontario.ca/environment-and-energy/land-information-ontario. What you probably want is featured on geogratis.

A: For a nice set of topographic data for Ontario, there is a fun interactive map which allows you to:

*

*Select various areas and zoom in at a high magnification

*Enable a variety of active layers (such as contour lines, roads, water polygons, conservation areas and so on)

*Download the selected areas into a number of formats (shp, AutoCAD DWG, DXF etc)

You will have to register with their website if you want to download the data.
http://www.geographynetwork.ca/website/obm/viewer.htm


text:
Q: Does anyone have a good guide to designing and error tracking/control system for C? I'm new to the software engineering side of C development; does anyone have a good guide on how to design an error tracking or error control system for a C project (especially embedded)? Something talking about error tracking for C libraries would be helpful too.

A: In my experience the strategies here fall into a few camps.

*

*Use of global variables ala errno.  How this works is essentially any function can store an error code in the global variable, so after executing the function you can read the error code to see if it executed properly.  There are some obvious issues here when working in a multithreaded environment.  Although it appears that POSIX.1c specifies a solution to that problem.

*Have every function return an error code.  For example:
RESULT_CODE my_function(int param1, int param2);

RESULT_CODE error_code = my_function(10, 2);

The problem with this approach is that you lose your ability to return values from the function directly.

*

*Every function has an extra parameter that stores the result code.  For example:
void my_function(int param1, int param2, RESULT_CODE *err);

RESULT_CODE error_code;
my_function(10, 2, &error_code);
switch (error_code)
{
    case RESULT_OK:
        // all OK
        break;
    case RESULT_NO_MEM:
        // out of memory
        break;
    // etc...
}

I've seen this approach used successfully in commercial RTOS, and personally prefer it since I find it the least restrictive.  The only potential disadvantage is that you have to explicitly declare a variable to store the error code, even if you don't care about the result.  In some sense I actually kind of like that requirement, though, since it forces you to be constantly thinking about how errors are going to be handled.

A: These links may be helpful:

*

*Errors: errno in UNIX programs - Working with the standard error mechanism

*Error Reporting (The GNU C Library)

A: These are the basic things you will need to define:

*

*Trace levels (eg. Debug, Alerts, Warnings, Info, Critical, etc).  You should also have a current trace level set, so if the current trace level is INFO, then all of the messages with a trace level above info are printed.  If the current trace level is critical, then only critical messages will be printed.

   enum _TraceLevelType
   {
        INFO = 0,
        DEBUG,
        WARNING,
        ERROR,
        CRITICAL
    } TraceLevelType;

*

*Error Codes, I think the best way is to have a big enum.  Something like this:

   enum _ErrorType
   {
        //Internal errors 0-100
        APPLICATION_FAILURE = 0,
        ...
        MEMORY_FAULT,
        //UI ERRORS  101-200
        INVALID_OPTION_SELECTED = 101,
        ....
        ...
    }ErrorType;

*

*A message queue, You should have a mechanism where everybody could send messages and these messages are properly queued.  Since you are working on embedded systems this is critical.  You don't want to spend time printing debugging messages on a real time OS.  So the thread managing the error codes should have a very low priority and all messages received should be posted to a queue, so when the scheduler decides to call it, then you do the printfs to the console or to whatever output you decide.

So your error method will be something like this:

TraceError(TraceLevelType traceLevel, ErrorType errorType, char *msg)
{
    if(CURRENT_TRACE_LEVEL <= traceLevel)
       /* Ignore message */
    else
       /*Queue the Message*/
}

You could also have more parameters to indicate which module is sending the error, but I think that is basically it.


text:
Q: Generalizing valuations Let $F$ be a field, and let $\Gamma$ be a totally ordered abelian group. A valuation is a group homomorphism $v : F \to \Gamma$ such that $v(x + y) \geq \min(v(x), v(y))$. On the other hand, a valuation ring $O \subseteq F$ is a ring such that for every $x \in F^\times$, we have $x \in O$ or $x^{-1} \in O$. It is classical that the valuations on a field (up to equivalence) are in bijective correspondence with the valuation rings of that field.
Valuation theory also has important applications in number theory (since valuations correspond to prime ideals in a number field), and to algebraic geometry (because they correspond to points in affine space, among other reasons).
My question is: what work has been done to generalize valuations? The definition of a valuation makes sense without any modification if $\Gamma$ is an abelian lattice-ordered group instead of an abelian ordered group, and there are plenty of integral domains people care about that are not valuation rings. Have people studied "valuation-like" structures where the definition of a valuation is tweaked or generalized in some way? Have people studied "valuation-like rings" where that definition is tweaked or generalized in some way? Are there established correspondences between generalized valuations and generalized valuation rings?


text:
Q: plot k-means clustering graph data = [[4,1,3,4,5,0,9,10][12,3,5,1,4,9,0,9]...]

N_CLUSTERS = 8

kmeans = KMeans(init='k-means++', n_clusters=N_CLUSTERS, n_init=60)

kmeans.fit(data)

pred_classes = kmeans.predict(data)

The data is normalized between 1 and 13. How can I plot the kmeans clustering?
I am trying to follow this tutorial (right graph) http://scikit-learn.org/stable/auto_examples/cluster/plot_kmeans_silhouette_analysis.html
but this example is only for two features and I have 8.


text:
Q: How do I have animation between transition using $location.path to Redirect in AngularJS? I am using AngularJS as my structure and backend and JqueryM for the UI.
I have used $location.path to redirect using ng-click. Is there a way I can use JQM data-transitions or Ng-animate to get the transition?

A: I got a lot of this from the ngAnimate and ngView documentation.
If you set up your animation in css...
.fade.ng-enter { transition:0.5s linear all; opacity:0; }
.fade.ng-enter.ng-enter-active { opacity:1; }
.fade.ng-leave { transition:0.0s linear all; opacity:1; }
.fade.ng-leave.ng-leave-active { opacity:0; }

and refer to the class within your ng-view element...

and don't forget to include the animate library...

and add it to your module...
angular.module('myApp', ['ngRoute', 'ngAnimate'])

Then your animation should work.
Here is a quick and dirty working example.  It also lives in plunker:
<!doctype html>

  <button ng-click="location.path('/page-one')">Page One</button>
  <button ng-click="location.path('/page-two')">Page Two</button>


text:
Q: ROV competition camera real time video processing ROV competetion requires supporting the underwater ROV with camera , which is used to find certain objects ( some numbers , plates ,measuring some distances... etc)
I want to learn about how to make a software to help finding these objects , for example alerts me when a number or  shows up .
I'm asking where to start learning ?! Do I have to learn Matlab ?!
I prefer using java if it can help doing the job by the way .


text:
Q: Realizar plantilla para obtener información del IFE/INE (OCR) Estoy intentando obtener la información de una credencial del IFE/INE. He realizado pruebas con la API de Google Mobile Vision (https://developers.google.com/vision/text-overview)
para poder lograrlo pero me obtiene muy pocos campos u obtiene la información muy poco entendible.
Cabe destacar que la información de la credencial la obtiene de forma secuencial, pero en ocasiones no lo hace. Realmente no tengo idea de por qué a veces sea así y a veces no.
He descargado unos OCRs comerciales y veo que utilizan Tesseract, y me gustaría hacer una plantilla pero la verdad no tengo mucha idea de cómo realizarla.

A: ACTUALIZACIÓN: Te dejó el link con la biblioteca que hice, espero te sirva aún. https://github.com/BrandonVargas/AndroidOCRFforID
Acabo de realizar uno, lamentablemente no puedo hacerlo publico, pero puedo guiarte un poco. Estoy utilizando Mobile Vision como mencionas, antes use Tesseract el cual es muy bueno pero aumenta demasiado el tamaño de tu aplicación. Para empezar debes saber que existen 5 tipos de IFE/INE A, B, C, D y E de las cuales la única que no esta vigente es la tipo A. Ahora bien para que se haga una correcta lectura de los campos lo primero que debes hacer es recortar la foto al tamaño de la IFE/INE para que quede como la imagen que muestras, una vez hecho esto lo siguiente es sacar medidas, como hacerlo? Tomemos como referencia la imagen que pusiste. Supongamos que requerimos sacar el nombre, y que la imagen mide 5.4 de alto por 8.6 de ancho. Sabemos que android toma el origen de una imagen en la esquina superior izquierda, tomamos las medidas a partir de ahí, el nombre empieza en 0.3 cm en X y 1.6 cm en Y, tiene una anchura promedio de 4 cm y una altura de 1 cm. Una vez teniendo esas medidas como base se sacan los "porcentajes" y quedaría con  X = (0.3/8.6), Y = (1.6/5.4), ANCHO = (4/8.6) y ALTO = (1/5.4). Teniendo estos datos podemos crear un bitmap del nombre a partir del recortado anteriormente y pasarlo a la API. Es importante sacar estos datos "proporcionales" ya que en Android existe una gran variedad de cámaras y las fotos son de diversos tamaños. Cuando pueda publicar la biblioteca que hice editare esto. Saludos.


text:
Q: Using window[] to access variable contents I am trying to set content in my main div based on the variable name. For example, if I run: changeMain(nearbyCows) I want to see 'tehe', instead it seems window[page] is undefined. Any ideas why?
function changeMain(page) {
    var nearbyCows = "tehe";
    var nearbyChickens = "lol";
    var search = "meh";

    $("main").html(window[page]);
}

A: You're creating this variables in the scope of the function.  The properties of window refer to the global scope.  If you want to use the global scope like this, then you need to move your variable declarations out of the function:
var nearbyCows = 'tehe';
var nearbyChickens = 'lol';
var search = "meh";
function changeMain(page) {
    $("main").html(window[page]);
}

But, then your essentially just using the window as a look up hash, and it would be better and cleaner to keep your own look up object instead of co-opting global.
for example:
var MainChanger = {
    nearbyCows: 'tehe',
    nearbyChickens: 'lol',
    search: "meh",
    change: function(page) {
        $('#main').html(this[page]);
    }
};

MainChanger.change('nearbyCows');

A: var nearbyCows is not defined on global scope but as local variable, use then: nearbyCows = "tehe"; without using directive var.

A: Use an object, not separate variables:
function changeMain(page) {
    var items = { nearbyCows: "tehe",
                  nearbyChickens: "lol",
                  search: "meh"
    };
    $("#main").html(items[page]);
}

Then you can call it like this:
changeMain('nearbyCows');

A: You must know that there is multiples type of variable.
You have the global variable which is assign the the window (not a good practice). You can declare it like that :
window.varName = ...;
window['varName'] = ...;
varName = ...;

There is variable scope, that is the usual way to declare variable :
var varName = ...;

Those variables are accessible by inner scope aswell but not accessible by outer scope.
There is also object properties. You create an object and assign value :
var obj = {};
obj.varName = ...;
obj['varName'] = ...;

If you can see, there is no way you can access a scoped variable with a dynamic string, you need object or global variable. :
function changeMain(page) {
    //Global variable, not recommended
    window.nearbyCows = "tehe";
    window.nearbyChickens = "lol";
    window.search = "meh";

    $("main").html(window[page]);
 }

or :
var obj = {} //Declare outside if you want to access it outside the function
function changeMain(page) {
    // var obj = {}; //or inside if you want it to be a private variable
    //Object properties, recommended
    obj.nearbyCows = "tehe";
    obj.nearbyChickens = "lol";
    obj.search = "meh";

    /*Alternative declaration, faster to process :
    obj = {
        nearbyCows : "tehe",
        nearbyChickens : "lol",
        search : "meh"
    }*/

    $("main").html(obj[page]);
 }


text:
Q: Calculate Limit with large exponents by hand I want to calculate the limit of
$$\lim\limits_{x \to 0} \frac{1-\cosh(x^5)}{x^6\sin^2(x^2)}$$
I know it is $-\infty$, but I want to know how to get there by hand. I have tried L'Hospital, which did not work out and I have tried Taylor expansion:
numerator: $1-\cosh(x^5)=-\dfrac{x^{10}}{2}-\dfrac{x^{20}}{24}+O(x^{26})$
enumerator: $x^6\sin^2(x^2)=x^{10}-\dfrac{x^{14}}{3}+O(x^{16})$
If taylor expansion is the right way to solve it, I don't know how to continue...

A: $\lim\limits_{x\rightarrow0}\frac{1-\cosh{x}}{x^2}=\lim\limits_{x\rightarrow0}\frac{1-\frac{a^x+e^{-x}}{2}}{x^2}=\lim\limits_{x\rightarrow0}\frac{-(e^x-1)^2}{2e^xx^2}=-\frac{1}{2}$ and $\lim\limits_{x\rightarrow0}\frac{\sin{x}}{x}=1$.
Thus, $$\lim\limits_{x \to 0} \frac{1-\cosh(x^5)}{x^6\sin^2(x^2)}=-\frac{1}{2}\lim\limits_{x \to 0}\frac{x^{10}}{x^{10}}=-\frac{1}{2}$$


text:
Q: Convert incoming string to dictionary/map javascript I am new javascript. I could do this in 2 seconds in python/java but I am struggling here. I am developing an reactJS app. I am retrieving a string which is a dictionary/HashMap<String, ArrayList> from a server via axios. I get response.data and my data is in the form:
{ "key1": [1,23,4,5,5,2],
   "key2": [2,6,5,5,5,6,5],
   ...
}

I want to convert this into a map/dictionary so I can access it like so (get(), keys(), etc.
However, i am having trouble doing this.
console.log(typeof data) gives me string.
And when I JSON.parse() or JSON.stringify() and use new Map() i get this weird thing with thousands of integer keys and it doesn't act like I want. Any idea on how I can do this?
Thanks!

EDIT
Here is a more complete code example.
const fetchData = () => {
    const url = "http://127.0.0.1:8081/pdata";
    const promise = axios.get(url);
    console.log(promise);
    const dataPromise = promise.then((response) => response.data);
    console.log(dataPromise);

    return dataPromise;
}
export default function Home() {

  //Bind the data to a useState Hook in React, to ensure that we have the correct data
  const [data, setData] = React.useState([]);

  //This function runs on page reload, twice. Your fetch data function will run repeatedly while contained
  //within this functional component.
  useEffect(() => {
    fetchData().then((apiEndpoint) => {
      //setting data equal to the result of the FetchData function
      setData(apiEndpoint);
    }).catch(err => console.log(err))
  }, [])

  // We now have the data.
  // Convert it to a map
  const map = new Map(Object.entries(data));
  console.log(map.get("Model Used"));
  console.log([...map.keys()]);

At point We now have the data, console.log(data) prints the incoming data correctly its just is of type string not map or whatever javascript calls it.

A: Using Map and Object#entries:

const obj = { "key1": [1,23,4,5,5,2], "key2": [2,6,5,5,5,6,5] };

const map = new Map(Object.entries(obj));

console.log(map.get("key1"));
console.log([...map.keys()]);

A: From https://flexiple.com/javascript/javascript-dictionary/

Are there dictionaries in JavaScript? No, as of now JavaScript does not include a native "Dictionary" data type. However, Objects in JavaScript are quite flexible and can be used to create key-value pairs. These objects are quite similar to dictionaries and work alike.

It seems you can just parse the string that you obtained to JSON and use the parsed object obtained. For example:

var api_response = `
{
    "key1": [1,23,4,5,5,2],
    "key2": [2,6,5,5,5,6,5]
}`;

var parsed_data = JSON.parse(api_response);

console.log(Object.keys(parsed_data))
console.log(parsed_data["key2"])
console.log(parsed_data.key1)


text:
Q: Windows 2008 as home file server and more I currently have a freenas-unit as a NAS, and a Win2k8R2-unit as server. However I would like to consolidate these to units in one. What I really like about the freenas-unit is the ZFS filesystem. And the only reason I care about the ZFS filesystem is the easy way I can grow an existing filesystem just by inserting a new drive.
How would this work in Win2k8? If I setup my unit with a separate drive as C: and a 1TB drive as D:. The D: would then be segmented into d:\Videos d:\Music d:\Pictures. When everything gets close to filling the storage-drive, I would like to expand the storage, but I wouldn't want to have E:\Videos or d:\Videos2 (using the NTFS folder mount thingy). I still want all my Videos to reside in D:\Videos and I want the OS to decide which drive it's going to be stored on... Some kind of on-the-fly jbod expansion :)
Is this at all possible in Windows 2008?

A: Windows 2008 supports a dynamic, logical volume format which allows you to extend a partition beyond a single disk in a sort of software JBOD. By choosing to Expand a partition from it's right-click menu in Server Manager > Storage > Disk Management, you can convert any basic-partitioned disk into a dynamic disk and extend that partition onto any other unallocated free space on any other (non-removable) drive.
This has a few caveats, though:

*

*You can convert a Basic disk to a Dynamic disk without losing data, but to convert a disk from Dynamic to Basic requires a format of (or deleting all partitions on) that disk.

*You can grow drives just fine, but NTFS is sometimes a gigantic pain in the rear to shrink down. ZFS, on the other hand, appears to have no such issues.

*Dynamic disks are not accessible in any other operating systems other than Windows 2003 Server, 2008, 2008 R2, Vista, and 7. This can make data recovery, if a drive fails (backups, backups, backups!) an excitingly expensive endeavor.


text:
Q: java.lang.IllegalArgumentException: Invalid character found in method name. HTTP method names must be tokens I am getting the error java.lang.IllegalArgumentException: Invalid character found in method name. HTTP method names must be tokens while uploading files to the server. I am using tomcat 9 with openjdk 11 on ubuntu server.
I have created the application using struts2.5.
The error that I received is:
Jun  8 09:33:22: Error parsing HTTP request header
Jun  8 09:33:22: Note: further occurrences of HTTP request parsing errors will be logged at DEBUG level.
Jun  8 09:33:22: java.lang.IllegalArgumentException: Invalid character found in method name. HTTP method names must be tokens
Jun  8 09:33:22:     at org.apache.coyote.http11.Http11InputBuffer.parseRequestLine(Http11InputBuffer.java:416)
Jun  8 09:33:22:     at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:260)
Jun  8 09:33:22:     at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
Jun  8 09:33:22:     at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
Jun  8 09:33:22:     at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1639)
Jun  8 09:33:22:     at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
Jun  8 09:33:22:     at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
Jun  8 09:33:22:     at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
Jun  8 09:33:22:     at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
Jun  8 09:33:22:     at java.base/java.lang.Thread.run(Thread.java:829)

I am running the application on tomcat and Using a SSL certificate also.
I have configured the server.xml upto best of my knowledge. Here is my server.xml
<?xml version="1.0" encoding="UTF-8"?>

<Server port="-1" shutdown="SHUTDOWN">
  <Listener className="org.apache.catalina.startup.VersionLoggerListener" />
  <!-- Security listener. Documentation at /docs/config/listeners.html
  <Listener className="org.apache.catalina.security.SecurityListener" />
  -->
  <!-- APR library loader. Documentation at /docs/apr.html -->
<!--
  <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />

-->
  <!-- Prevent memory leaks due to use of particular java/javax APIs-->
  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
  <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" />

  <!-- Global JNDI resources
       Documentation at /docs/jndi-resources-howto.html
  -->
  <GlobalNamingResources>
    <Resource name="UserDatabase" auth="Container"
              type="org.apache.catalina.UserDatabase"
              description="User database that can be updated and saved"
              factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
              pathname="conf/tomcat-users.xml" />
  </GlobalNamingResources>

  <Service name="Catalina">

    <Connector port="80" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="443"/>

  <!-- The max post size is nearly equal to 10 MB -->
  <Connector SSLEnabled="true" acceptCount="100" clientAuth="false"
    disableUploadTimeout="true" enableLookups="false" maxThreads="150"
    maxPostSize="-1" maxHttpHeaderSize ="1048576" maxSavePostSize="-1"
    port="443" keystoreFile="conf/screen.evelynlearning.com.keystore" keystorePass="evelyn"
    protocol="org.apache.coyote.http11.Http11NioProtocol" scheme="https"
    secure="true" sslProtocol="TLS" URIEncoding="UTF-8" relaxedQueryChars="[\]^`{|}"/>

    <!-- Define an AJP 1.3 Connector on port 8009 -->
    <!--
    <Connector protocol="AJP/1.3"
               address="::1"
               port="8009"
               redirectPort="8443" />
    -->

    <!-- An Engine represents the entry point (within Catalina) that processes
         every request.  The Engine implementation for Tomcat stand alone
         analyzes the HTTP headers included with the request, and passes them
         on to the appropriate Host (virtual host).
         Documentation at /docs/config/engine.html -->

    <!-- You should set jvmRoute to support load-balancing via AJP ie :
    <Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">
    -->
    <Engine name="Catalina" defaultHost="localhost">

      <!--For clustering, please take a look at documentation at:
          /docs/cluster-howto.html  (simple how to)
          /docs/config/cluster.html (reference documentation) -->
      <!--
      <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
      -->

      <!-- Use the LockOutRealm to prevent attempts to guess user passwords
           via a brute-force attack -->
      <Realm className="org.apache.catalina.realm.LockOutRealm">
        <!-- This Realm uses the UserDatabase configured in the global JNDI
             resources under the key "UserDatabase".  Any edits
             that are performed against this UserDatabase are immediately
             available for use by the Realm.  -->
        <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
               resourceName="UserDatabase"/>
      </Realm>

      <Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">

        <!-- SingleSignOn valve, share authentication between web applications
             Documentation at: /docs/config/valve.html -->
        <!--
        <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
        -->

        <!-- Access log processes all example.
             Documentation at: /docs/config/valve.html
             Note: The pattern used is equivalent to using pattern="common" -->
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="localhost_access_log" suffix=".txt"
               pattern="%h %l %u %t "%r" %s %b" />

      </Host>
    <Host name="screen.evelynlearning.com"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">
        <Context path="" docBase="RAT" debug="0" privileged="true" />
        <Context docBase="/etc/tomcat9/Catalina/screen.evelynlearning.com/imageresource" path="imageresource"/>
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="localhost_access_log" suffix=".txt"
               pattern="%h %l %u %t "%r" %s %b" />
    </Host>
     <Host name="dashboardfortl.evelynlearning.com"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">
        <Context path="" docBase="Dashboard-3.3" debug="0" privileged="true" />
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="localhost_access_log" suffix=".txt"
               pattern="%h %l %u %t "%r" %s %b" />
    </Host>

     <Host name="knowledgepark.evelynlearning.com"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">
        <Context path="" docBase="EvelynKnowledgePark-1" debug="0" privileged="true" />
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="localhost_access_log" suffix=".txt"
               pattern="%h %l %u %t "%r" %s %b" />
    </Host>
    </Engine>
  </Service>
</Server>

When I upload files larger then 40 KB, then the files are not uploaded and the request object is dropped. If the files are smaller than 40 KB, then the files are uploaded. I am not sure why is this happening.
I am also using SSL and I am using https while accessing my site. All other functionality is working correctly on https. It is just that the I am not receiving the uploaded files when I get this error.
If anyone knows about this, please do help. I have been searching for this for a few days now.
Edit:
I am using Apache Tomcat/9.0.31 version of tomcat 9 on Ubuntu.
Edit 2:
I found that the application is throwing this exception when submitting a form on https. When I use same application without the SSL, then everything works fine. Apart from form submission everything on SSL works fine. Any help would be appreciated.


text:
Q: Show that no matter how $12$ points are put on a plane, there are $3$ among them forming an angle not greater than $18^o$. Problem : Show that no matter how $12$ points are put on a plane, there are $3$ among them forming an angle not greater than $18^o$.
I am not getting any ideas in solving this problem. So, there will be $\binom{12}{3}= 220 $ triangles which means there will be a total of $660$ angles. We need to show that at least one of out of these $660$ angles will be less than or equal to $18^o$ degrees. How should we proceed now?

A: Hint: Consider a point $P$ having minimal $x$-coordinate among the $12$ provided points. What can you say about the angles from $P$ to the other $11$ points?