text:
Q: What is bootstrapping? I keep seeing "bootstrapping" mentioned in discussions of application development.  It seems both widespread and important, but I've yet to come across even a poor explanation of what bootstrapping actually is; rather, it seems as though everyone is just supposed to know what it means.  I don't, though.  Near as I can figure, it has something to do with initialization tasks required of an application upon launch, but I could be completely wrong about that.  Can anyone help me to understand this idea?

A: See on the Wikipedia article on bootstrapping.
There is a section and links explaining what it means in Computing. It has four different uses in the field.
Here are some quotes, but for a more in depth explanation, and alternative meanings, consult the links above.

"...is a technique by which a simple computer program activates a more complicated system of programs."
"A different use of the term bootstrapping is to use a compiler to compile itself, by first writing a small part of a compiler of a new programming language in an existing language to compile more programs of the new compiler written in the new language."

A: Boot strapping the dictionary meaning is to start up with minimum resources.    In the Context of an OS the OS should be able to swiftly load once the Power On   Self Test (POST)  determines that its safe to wake up the CPU. The boot strap  code  will be run from the BIOS. BIOS is a small sized ROM. Generally it is a   jump instruction to the set of instructions  which will load the Operating   system to the RAM. The destination of the Jump is the Boot sector in the Hard Disk. Once the bios  program checks it is a valid Boot sector which contains  the starting address of the stored OS, ie whether it is a valid MBR  (Master Boot Record) or not. If its a valid MBR the OS will be copied to the   memory (RAM)from there on the OS takes care of Memory and Process management.

A: As the question is answered. For web develoment.
I came so far and found a good explanation about bootsrapping in Laravel doc. Here is the link

In general, we mean registering things, including registering service
container bindings, event listeners, middleware, and even routes.

hope it will help someone who learning web application development.

A: "Bootstrapping" comes from the term "pulling yourself up by your own bootstraps." That much you can get from Wikipedia.
In computing, a bootstrap loader is the first piece of code that runs when a machine starts, and is responsible for loading the rest of the operating system. In modern computers it's stored in ROM, but I recall the bootstrap process on the PDP-11, where you would poke bits via the front-panel switches to load a particular disk segment into memory, and then run it. Needless to say, the bootstrap loader is normally pretty small.
"Bootstrapping" is also used as a term for building a system using itself -- or more correctly, a predecessor version. For example, ANTLR version 3 is written using a parser developed in ANTLR version 2.

A: An example of bootstrapping is in some web frameworks. You call index.php (the bootstrapper), and then it loads the frameworks helpers, models, configuration, and then loads the controller and passes off control to it.
As you can see, it's a simple file that starts a large process.

A: In the context of application development, "bootstrapping" usually comes up when talking about modular and/or auto-updatable software.
Rather than the user downloading the entire app, including features he does not need, and re-downloading and manually updating it whenever there is an update, the user only downloads and starts a small "bootstrap" executable, which in turn downloads and installs those parts of the application that the user needs. Additionally, the bootstrap component is able to look for updates and install them each time it is started.

A: Bootstrapping has yet another meaning in the context of reinforcement learning that may be useful to know for developers, in addition to its use in software development (most answers here, e.g. by kdgregory) and its use in statistics as discussed by Dirk Eddelbuettel.
From Sutton and Barto:

Widrow, Gupta, and Maitra (1973) modified the Least-Mean-Square (LMS)
  algorithm of Widrow and Hoff (1960) to produce a reinforcement
  learning rule that could learn from success and failure signals
  instead of from training examples. They called this form of learning
  "selective bootstrap adaptation" and described it as "learning with a
  critic" instead of "learning with a teacher." They analyzed this rule
  and showed how it could learn to play blackjack. This was an isolated
  foray into reinforcement learning by Widrow, whose contributions to
  supervised learning were much more influential.

The book describes various reinforcement algorithms where the target value is based on a previous approximation as bootstrap methods:

Finally, we note
   one last special property of DP [Dynamic Programming] methods. All of them update estimates
  of the values of states based on estimates of the values of successor
  states. That is, they update estimates on the basis of other
  estimates. We call this general idea bootstrapping. Many reinforcement
  learning methods perform bootstrapping, even those that do not
  require, as DP requires, a complete and accurate model of the
  environment.

Note that this differs from bootstrap aggregating and intelligence explosion that is mentioned on the wikipedia page on bootstrapping.

A: I belong to the generation who flipped switches to enter a boot program. In the early 1980s, I worked on a microcomputer called Micro-78, developed by Electronics Corporation of India Ltd (ECIL). It was a sort of clone of Altair 8800. I distinctly remember what happens when a small boot program was entered using the toggle switches and executed by pressing a button. The program reads a second boot program contained in the 1st track of the floppy disk and overwrites it on itself in such a way that the second boot program starts executing to load a disk operating system. I think the term "bootstrap" refers to this process of the first boot program reading and overwriting the second boot program on itself, in a way "pulling itself up" with the additional functionality of the second boot program. That may be the origin of the original meaning of "the bootstrap program".

A: Alex, it's pretty much what your computer does when it boots up. ('Booting' a computer actually comes from the word bootstrapping)
Initially, the small program in your BIOS runs. That contains enough machine code to load and run a larger, more complex program.
That second program is probably something like NTLDR (in Windows) or LILO (in Linux), which then executes and is able to load, then run, the rest of the operating system.

A: In terms of it in regards to using the popular Twitter Bootstrap I feel like this type of bootstrapping is the action of integrating a modular component into a Web application without the Web application having to even acknowledge the modular component exists until it needs it or references it.
The developer can seamlessly integrate a default copy of the CSS Twitter Bootstrap theme by simply loading (referencing) it into the Web application. Vuola! Then you may need to override some of these changes, but you can do so in such a way that the resource/component is untouched and completely reusable.
This same concept is how Web Devs implement jQuery APIs and so on, but it's not really expressed by Devs as bootstrapping per se. What it does is it improves flexibility and reusability while allowing the isolation of different components/resources of an app to reside freely either on the same server/s or possibly on a CDN.
NOTE: In computing bootstrapping deals with the MBR and in UNIX it requires a special bootloader or manager which is a small program in ROM that loads the OS into RAM. If you think about it the same concept takes places in the action of the bootstrap loader checking the MBR and loading the OS based on this table which occurs without the OS having any idea that this takes place.

A: IMHO there is not a better explanation than the fact about How was the first compiler written?
These days the Operating System loading is the most common process referred as Bootstrapping

A: For completeness, it is also a rather important (and relatively new) method in statistics that uses resampling / simulation to infer population properties from a sample. It has its own lengthy Wikipedia article on bootstrapping (statistics).

A: The term "bootstrapping" usually applies to a situation where a system depends on itself to start, sort of a chicken and egg problem.
For instance:

*

*How do you compile a C compiler written in C?

*How do you start an OS initialization process if you don't have the OS running yet?

*How do you start a distributed (peer-to-peer) system where the clients depend on their currently known peers to find out about new peers in the system?

In that case, bootstrapping refers to a way of breaking the circular dependency, usually with the help of an external entity, e.g.

*

*You can use another C compiler to compile (bootstrap) your own compiler, and then you can use it to recompile itself

*You use a separate piece of code that sets up the initial process  without depending on any functions provided by the OS

*You use a hard-coded list of initial peers or a hard-coded tracker URL that supplies the peer list

etc.

A: Bootstrap file is responsible for loading contents of main file. It is a wrapper around main file. This way we can catch errors if loading of file was unsuccessful for some reason.

A: As a humble beginner in the world of programming, and flicking through all the answers here after seeing this word used a lot in apparently slightly different ways in different places, I found reading the Wikipedia page on Bootstrapping (duh! I didn't think of it either at first) is very informative to understand differences in use of this word. Could it be......on extremely rare occasions......Wikipedia might even have better explanations of certain terms than....(redacted)? Will they bring in rep points on Wikipedia though?
To me, it seems all the meanings something to do with: start with something as simple as possible Thing1, make something slightly more complex with that Thing2, and now you can use Thing2 to do some kind of tasks more efficiently and quickly than you could originally with Thing1. Then repeat from Thing2 to Thing 3 ad infinitum...
I see it as closely connected to both biological evolution and 'Layers of Abstraction' (newbies like me see, ahem, Wikipedia, cough) - the evolution from 1940's computers with switches, machine code, Assembly, C, Python, AIs you can give all kinds of complex instructions to like "make the %4^% dinner to my default &^$% requirements and clean the floor you %$£"@:~" in drunken slang English or Amazon tribal dialect without them 'raising an exception' (for newbies again...you guessed it) - missed out lot of links there due to simple ignorance.
Then in certain specific software meanings:
Meaning1: Thing1 is used to load latest version of Thing2 (because of course Thing2 will be bigger than Thing1, just as Thing3 will be be bigger than Thing2).
Meaning2: Thing1 is a lower level language (closer to 1001011100....011001 than print("Hello, ", user.name)) used to write a little bit of the higher language of Thing2, then this little bit of Thing2 is used to expand Thing2 itself from baby vocabulary level towards adult vocabulary level (Thing2 starts to be processed, or to use correct technical term 'compiled', by the baby version of itself (it's a clever baby!), whereas the baby version of Thing2 itself could of course only be compiled by Thing1, cause it can't exist before it exists, right duh!), then child version of Thing2 compiles Surly Teenager version of Thing2, at which point programming community decides whether Surly Teenager's 'issues' (software term and metaphor term!) are worth spending enough time resolving to be accepted long term, or to abandon them to (not sure where to take the analogy here).
If yes, then Thing2 has 'Bootstrapped' itself (possibly a few times) from babyhood to adulthood: "the child is the father of the man" (Wordsworth, suggest don't try looking up the quote or the author on Stack Overflow).


text:
Q: Speed up loading external javascript file via a bookmarklet? I have a bookmarklet that (functionally) works perfectly.  You click the bookmarklet and a popup appears.  This popup is generated by a combination of javascipt files located on my Virtual Private Server.
Code Example:
My Bookmarklet

When I use the bookmarklet on my website the popup loads in 1-2 seconds.  However, if I use the bookmarklet on a different site it takes at least 5 seconds - sometimes more.  Obviously I'm trying to find a way to get the 5 second load time closer to the 1-2 second load time, because most of my testers keep thinking the bookmarklet is broken since it takes so long for the popup to appear.
My theory is that my server (which is a unix server that uses Plesk and Virtuosso), is restricting how quickly it allows its files to be loaded to an external site.  However, thus far I haven't been able to find anything in my server's managment software that suggests that for certain.  If anyone has any ideas on how to fix this I'd be highly appreciative.

A: I doubt that your theory - that the problem is originating in your server - is correct.
It seems more likely to me that problem is probably because you are testing on two different pages.
I would try to verify that the apparent speed problem is actually one of loading, and not actually one of execution. Does it seem like it is slower because you are checking network activity, or just because it completes its work slower. I have been surprised in the past by how much slower a piece of JS code ran on one page vs. another. I too thought the file was loading slow, but that wasn't actually the case.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is it possible to create JSON strings from a pipe using jq? Let's say I use the command find "$HOME" -maxdepth 1 -type d and I get the following result:
/home/user/folder1
/home/user/folder2
/home/user/folder3
/home/user/folder4

I'd like to use jq on a pipe and create different JSON lines as the following:
{ "path": "/home/user/folder1", "type":"directory"}
{ "path": "/home/user/folder2", "type":"directory"}
{ "path": "/home/user/folder3", "type":"directory"}
{ "path": "/home/user/folder4", "type":"directory"}

I expected to solve it with jq to avoid putting this list of folders inside an array and creating them one by one in a loop. In pseudo-code the idea would be:
find "$HOME" -maxdepth 1 -type d | jq '.logic-to-create-json-strings'

Is it possible to do with jq?

A: This answer assumes that your filenames (or whatever text you wish to JSON encode) is valid UTF-8.
Two alternatives:
Not using xargs:    Call jq with the pathnames as positional parameters directly from find with -exec.  Read the found pathnames with --args and access them as the array $ARGS.positional[] in the jq expression.  For each pathname, create a JSON object.
find "$HOME" -maxdepth 1 -type d \
    -exec jq -n -c '$ARGS.positional[] as $path | { path: $path, type: "directory" }' --args {} +

Using xargs:  Use -print0 with find and -0 with xargs to safely pass the found pathnames from find to xargs. The jq expression is identical to the above, only the manner in which the pathnames are passed between find and jq differs.
find "$HOME" -maxdepth 1 -type d -print0 |
xargs -0 jq -n -c '$ARGS.positional[] as $path | { path: $path, type: "directory" }' --args

With both approaches above, jq would encode the found pathnames to be able to represent them as JSON strings.

To read lines into a set of objects like you show, you may use the following jq command, which reads from its standard input stream:
jq -R -c '{ path: ., type: "directory" }'

A: JSON cannot directly represent arbitrary file paths (which are sequences of bytes other than zero) in its strings which are sequences of UTF-8 encoded characters. Also note that the output of find is not post-processable unless you use -print0.
For instance a file path might be $'/home/St\xc3\xa9phane\nChazelas/ISO-8859-1/R\xe9sum\xe9' (here using ksh93-style $'...' notation to represent byte values), with a é UTF-8 encoded in Stéphane, and ISO-8859-1 encoded in Résumé.
JSON cannot represent that file path unless you use some encoding. That could be for instance URI encoding:
{ "path": "/home/St%C3%A9phane\nChazelas/ISO-8859-1/R%E9sum%E9" }

Another approach could be to interpret the path as if it were ISO-8859-1 encoded (or any single-byte charset where any byte value can make a valid character¹):
{ "path": "/home/Stéphane\nChazelas/ISO-8859-1/Résumé" }

jq has some support for doing URI encoding, but AFAIK cannot be fed non-UTF-8 input. AFAIK, it doesn't have any support for encoding conversion either.
On a GNU system, for the second approach where file paths are considered to be ISO-8859-1 encoded you may however be able to do something like:
find ~ -type d -print0 |
  iconv -f iso-8859-1 -t utf-8 |
  tr '\0\n' '\n\0' |
  jq -Rc '{"path":sub("\u0000";"\n"),"type":"directory"}'

Which on our example above gives:
{"path":"/home/Stéphane\nChazelas/ISO-8859-1/Résumé.pdf","type":"directory"}

¹ though iso-8859-1 specifically is an obvious choice as its code points match those of Unicode. So if your json string contains a U+00E9 character for instance, you know it corresponds to the 0xE9 byte. You could add the -a option to jq for non-ASCII characters to be represented as \uXXXX instead.


text:
Q: F#: Recursive Functions: concatenate 2 lists which have common elements So here is what I have so far. It feels close but im not sure how to fix the problems in line 84 (2nd to last line: elif List.append(isolate(a),isolate(b)) != [] then List.append(isolate(a),isolate(b))).
    (* val isolate : l:'a list -> 'a list when 'a : equality *)
    let rec isolate (l:'a list) =
        match l with
        | [] -> []
        | x::xs ->
            if memberof(x,xs)
            then
                let xs = remove (x,l)
                isolate xs
            else isolate xs
    ( * val common : 'a list * 'a list -> 'a list when 'a : equality *)
    let rec common (k: 'a list, l:'a list) =
        match ((k:'a list),(l:'a list)) with
        | (a, b) ->
            if a=[] then []
            elif b=[] then []
            elif List.append(isolate(a),isolate(b)) != [] then List.append(isolate(a),isolate(b))
            else []

edit:
asked to post whole code:
(* val sumlist : l:float list -> float *)
let rec sumlist l =
    match (l:float list) with
    | [] -> 0.0
    | a::x -> (sumlist x) + a
    (* :: creates a list. *)
sumlist([1.0;2.0;3.0])
(* val squarelist : l:float list -> float list *)
let rec squarelist l =
    match (l:float list) with
    | [] -> []
    | a::x -> (a*a)::(squarelist x)

(* val mean : l:float list -> float *)
let mean l =
    match (l:float list) with
    | [] -> 0.0
    | l -> (sumlist l)/(float)l.Length
mean([1.0;2.0;3.0])
(* val mean_diffs : l:float list -> float list *)
let mean_diffs l =
    match l with
    set a = mean(l)

    | [] -> []
    let rec diffs (a,l)=
        match l with
        | x::xs -> (x-(mean(l))::diffs(xs)
        | [] -> l
mean_diffs([1.0;2.0;3.0])

(* val variance : l:float list -> float *)
let variance l =
    match (l:float list) with
    | [] -> 0.0
    | l -> (sumlist (squarelist (mean_diffs l)))/(float)l.Length

(* End of question 1 *) (* Do not edit this line. *)

(* Question 2 *) (* Do not edit this line. *)

(* val memberof : 'a * 'a list -> bool when 'a : equality *)
let rec memberof l=
    match (l: 'a * 'a list) with
    | (t,[]) -> false
    | (t, x::xs) when t=x -> true
    | (t, x::xs) -> t=x || memberof(t,xs)

(* val remove : 'a * 'a list -> 'a list when 'a : equality *)
let rec remove ((k:'a),(l:'a list)) =
    match l with
    | [] -> []
    | x::xs when x=k -> xs
    | x::xs ->x::(remove(k,xs))

(* End of question 2 *) (* Do not edit this line *)

(* Question 3 *) (* Do not edit this line *)

(* val isolate : l:'a list -> 'a list when 'a : equality *)
let rec isolate (l:'a list) =
    match l with
    | [] -> []
    | x::xs ->
        if memberof(x,xs)
        then
            let xs = remove (x,l)
            isolate xs
        else isolate xs

(* End of question 3 *) (* Do not edit this line *)

(* Question 4 *) (* Do not edit this line *)

(* val common : 'a list * 'a list -> 'a list when 'a : equality *)
let rec common (k: 'a list, l:'a list) =
    match ((k:'a list),(l:'a list)) with
    | (a, b) ->
        if a=[] then []
        elif b=[] then []
        elif List.append(isolate(a),isolate(b)) <> [] then List.append(isolate(a),isolate(b))
        else []
common([1.0;2.0;6.0;10.0],[5.0;6.0;10.0])

It seems that <> has fixed the problem but do you have any advice on my function mean_diffs?

A: Since this appears that you are working on a course and it is building upon the previous exercises, the code is converted to more F# idiomatic and a standardized format of recursive functions to make them easier to use when you get to currying See: F# for fun and profit and Functions as First-Class Values (F#) and other more advanced concepts.
The format is basically
let funXYZ list =
    let rec funXYZInner list acc =
        match list with
        | head :: tail ->
            let acc = (somefunc head) :: acc
            funXYZInner tail acc
        | [] -> acc
    funXYZInner list []

where funXYZ is an exposed function name that does NOT have a rec. I can't recall the source but if you can implement a function needing a rec with the rec not being exposed it makes the code more portable.
The basic concept is that you take a list and pull the list apart into a head and tail:
head :: tail

then you process the head:
somefunc head

then accumulate the result into the accumulator
let acc = value :: acc
let acc = value + acc
let acc = acc + (value * value)

then process the remainder of the list, e.g. tail, passing the accumulator
funXYZInner tail acc

When the input list matches empty
| []

just return the result which was accumulated in the accumulator
acc

The inner function funXYZInner does have a rec and uses an accumulator, i.e. acc. This will help in understanding how to use tail calls which will keep you from running out of memory on large computations.
You probably know already that with match statements you want to cover all of the cases of the match variable. This is because of algebraic data types and is the reason you see those warnings about not all cases being covered. If you see one of those warnings and don't know why you are getting it you need to fix them, or run the risk of unexpected runtime errors or crashes.
While the code you gave can only work with float type list, in the future to make it work with more types you will need to learn about LanguagePrimitives.GenericZero<^T> Type Function (F#).
There are some more basic functions that were added because they were needed, e.g. reverse, and help to show the progression as the examples get more complex.
Do to the fact that examples build upon themselves and you had a specific error in the last one, it was better to give the examples a better foundation which should mitigate common problems encountered when first learning about recursive functions.
With regards to the accumulator, the accumulator can hold different types, e.g. float, list, int, and there can be more than one accumulator being used in the recursive function, e.g. numeratorAcc, denominatorAcc. Also by pulling out the calculation of the accumulator value, e.g.let acc = ..., when you get to more advanced functions you can just pass in a function to replace that calculation.
There is one predicate function memberof which does not use an accumulator. A predicate is a function that returns true or false, and once you reach the desired value you can stop processing the remainder of the list.
Also of note is that while some of the functions could call earlier defined functions, the examples don't make the calls so that they can process the list in one pass. When functions call other functions with list, each function has to process the entire list to return the result. By using rec functions it is sometimes possible to process the list once by doing multiple calculations with the head. However there are times this cannot be done. I did not maximize the functions one way or the other but left them a way that give more variation for learning. Feel free to rewrite them which will lead to function composition.
You will probably have more questions about these examples, so please ask as separate SO questions instead of building on this one.
All the code
// val reverse : l:'a list -> 'a list
let reverse l =
    let rec reverseInner l acc =
        match l with
        | x::xs ->
            let acc = x :: acc
            reverseInner xs acc
        | [] -> acc
    reverseInner l []

reverse [ 3.0; 2.0; 1.0 ]  // val it : float list = [1.0; 2.0; 3.0]

// val length : l:'a list -> int
let length l =
    let rec lengthInner l acc =
        match l with
        | x::xs ->
            let acc = acc + 1
            lengthInner xs acc
        | [] -> acc
    lengthInner l 0

length [ 3.0; 2.0; 1.0 ]  // val it : int = 3

// val sum : l:float list -> float
let sum l =
    let rec sumInner l acc =
        match l with
        | x::xs ->
            let acc = acc + x
            sumInner xs acc
        | [] -> acc
    sumInner l 0.0

sum [ 1.0; 2.0; 3.0 ]  // val it : float = 6.0

// val square : l:float list -> float list
let square (l : float list) =
    let rec squareInner l acc =
        match l with
        | x::xs ->
            let acc = (x * x) :: acc
            squareInner xs acc
        | [] -> reverse acc
    squareInner l []

square [ 1.0; 2.0; 3.0 ]  // val it : float list = [1.0; 4.0; 9.0]

// val mean : l:float list -> float
let mean l =
    let rec meanInner l sumacc lengthacc =
        match l with
        | x::xs ->
            let sumacc = sumacc + x
            let lengthacc = lengthacc + 1.0
            meanInner xs sumacc lengthacc
        | [] -> sumacc / lengthacc
    meanInner l 0.0 0.0

mean([1.0;2.0;3.0]) // val it : float = 2.0

// val mean_diffs : l:float list -> float list
let meanDiff l =
    let rec meanDiffInner l m acc =
        match l with
        | x::xs ->
            let diff = (x - m)
            let acc = diff :: acc
            meanDiffInner xs m acc
        | [] -> reverse acc
    meanDiffInner l (mean l) []

meanDiff [ 1.0; 2.0; 3.0 ]  // val it : float list = [-1.0; 0.0; 1.0]

// From: https://en.wikipedia.org/wiki/Variance
// Suppose a population of numbers consists of 3, 4, 7, and 10.
// The arithmetic mean of these numbers, often informally called the "average", is (3+4+7+10)÷4 = 6.
// The variance of these four numbers is the average squared deviation from this average.
// These deviations are (3–6) = –3, (4–6) = –2, (7–6) = 1, and (10–6) = 4.
// Thus the variance of the four numbers is ((-3)^2 + (-2)^2 + (1)^2 + (4)^2) / 4 = 15/2 = 7.5

// val variance : l:float list -> float
let variance l =
    let deviations = meanDiff l
    let rec varianceInner l numeratorAcc denomenatorAcc =
        match l with
        | devation::xs ->
            let numeratorAcc = numeratorAcc + (devation * devation)
            let denomenatorAcc = denomenatorAcc + 1.0
            varianceInner xs numeratorAcc denomenatorAcc
        | [] -> numeratorAcc / denomenatorAcc
    varianceInner deviations 0.0 0.0

variance [ 1.0; 2.0; 3.0 ]          // val it : float = 0.6666666667
variance [ 3.0; 4.0; 7.0; 10.0 ]    // val it : float = 7.5

(* End of question 1 *) (* Do not edit this line. *)

(* Question 2 *) (* Do not edit this line. *)

// val memberof : l:'a list -> item:'a -> bool when 'a : equality
let memberof l item =
    let rec memberInner l item =
        match l with
        | x::xs ->
            if x = item then
                true
            else
                memberInner xs item
        | [] -> false
    memberInner l item

memberof [ 1.0; 2.0; 3.0 ] 0.0  // val it : bool = false
memberof [ 1.0; 2.0; 3.0 ] 1.0  // val it : bool = true
memberof [ 1.0; 2.0; 3.0 ] 2.0  // trueval it : bool = true
memberof [ 1.0; 2.0; 3.0 ] 3.0  // val it : bool = true
memberof [ 1.0; 2.0; 3.0 ] 4.0  // val it : bool = false

// val remove : l:'a list -> item:'a -> 'a list when 'a : equality
let remove l item =
    let rec removeInner l item acc =
        match l with
        | x::xs ->
            if x = item then
                removeInner xs item acc
            else
                let acc = x :: acc
                removeInner xs item acc
        | [] -> reverse acc
    removeInner l item []

remove [ 1.0; 2.0; 3.0 ] 0.0    // val it : float list = [1.0; 2.0; 3.0]
remove [ 1.0; 2.0; 3.0 ] 1.0    // val it : float list = [2.0; 3.0]
remove [ 1.0; 2.0; 3.0 ] 2.0    // val it : float list = [1.0; 3.0]
remove [ 1.0; 2.0; 3.0 ] 3.0    // val it : float list = [1.0; 2.0]
remove [ 1.0; 2.0; 3.0 ] 4.0    // val it : float list = [1.0; 2.0; 3.0]

(* End of question 2 *) (* Do not edit this line *)

(* Question 3 *) (* Do not edit this line *)

// val isolate : list:'a list -> 'a list when 'a : equality
let isolate list =
    let rec isolateInner searchList commonlist =
        match searchList with
        | x::xs ->
            if (memberof commonlist x) then
                isolateInner xs commonlist
            else
                let commonlist = (x :: commonlist)
                isolateInner xs commonlist
        | [] -> reverse commonlist
    isolateInner list []

isolate [ 1.0; 2.0; 3.0 ]                                    // val it : float list = [1.0; 2.0; 3.0]
isolate [ 1.0; 1.0; 2.0; 3.0 ]                               // val it : float list = [1.0; 2.0; 3.0]
isolate [ 1.0; 2.0; 2.0; 3.0 ]                               // val it : float list = [1.0; 2.0; 3.0]
isolate [ 1.0; 2.0; 3.0; 3.0 ]                               // val it : float list = [1.0; 2.0; 3.0]
isolate [ 3.0; 2.0; 1.0; 1.0; 2.0; 3.0; 2.0; 1.0; 1.0; 3.0]  // val it : float list = [3.0; 2.0; 1.0]

(* End of question 3 *) (* Do not edit this line *)

(* Question 4 *) (* Do not edit this line *)

// val common : a:'a list -> b:'a list -> 'a list when 'a : equality
let common a b =
    let rec commonInner a b acc =
        match (a,b) with
        | (x::xs,b) ->
            if (memberof acc x) then
                commonInner xs b acc
            else
                let acc = x :: acc
                commonInner xs b acc
        | ([],y::ys) ->
            if (memberof acc y) then
                commonInner [] ys acc
            else
                let acc = y :: acc
                commonInner [] ys acc
        | ([],[]) -> reverse acc
    commonInner a b []

common [ 1.0; 2.0; 6.0; 10.0] [ 5.0; 6.0; 10.0 ]   // val it : float list = [1.0; 2.0; 6.0; 10.0; 5.0]


text:
Q: Extract the value of a variable that matches a pattern in TCL I have a list called parameters and the content of this list can be different but it will look something like:
var1=2;
var2=2'h2;
var3=2'h0;
....

This list comes from reading a file and done some preformating already. I just want to grab the value of var1 and store it in a variable. Eg whatever is in between '=' sign and ';' sign but only for var1 (in this case number 2). Equally I can remove all the lines that are not matching 'var1'.

A: Assuming your parameters list is already set, you can do something like:
foreach item $parameters {
  if {[regexp "var1\\s*=\\s*(\\w+);" $item wholeMatch myVal]} {
       break
  }
}
puts "value is '$myVal'"

The regular expression I use allows for optional spaces before and after the equal sign. Take a look at Tcl's regex syntax and adjust as necessary.
It might be easier to just do a regex search through your whole file using, rather than parsing your file into a list. But again, take a look at Tcl's documentation.


text:
Q: AWS S3 HTTPS API request(URL) signed with temporary security credentials to access object How to generate the HTTPS API request(URL) signed with temporary security credentials  to access AWS S3 object.I am able to access object using amazon java sdk but I would like to generate the complete url with temporary security credential like pre signed url.
package com.siriusxm.repo.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import com.amazonaws.auth.BasicSessionCredentials;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.regions.Region;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.ObjectListing;
import com.amazonaws.services.securitytoken.AWSSecurityTokenServiceClient;
import com.amazonaws.services.securitytoken.model.Credentials;
import com.amazonaws.services.securitytoken.model.GetSessionTokenRequest;
import com.amazonaws.services.securitytoken.model.GetSessionTokenResult;
import com.siriusxm.repo.DownloadServiceImpl;

public class TemporaryCredential {

    private static String bucketName = "myrepo";
    private static String key  =  "test.pdf";

    public static void main(String[] args) {
        System.out.println("");

        AWSSecurityTokenServiceClient stsClient = new AWSSecurityTokenServiceClient(
                new ProfileCredentialsProvider());
    //  stsClient.setRegion(regionName);sts.us-west-2.amazonaws.com
        //
        // Start a session.
        GetSessionTokenRequest getSessionTokenRequest = new GetSessionTokenRequest();
        GetSessionTokenResult sessionTokenResult = stsClient
                .getSessionToken(getSessionTokenRequest);
        Credentials sessionCredentials = sessionTokenResult.getCredentials();
        System.out.println("Session Credentials: "
                + sessionCredentials.toString());
        // Package the session credentials as a BasicSessionCredentials
        // object for an S3 client object to use.
        BasicSessionCredentials basicSessionCredentials = new BasicSessionCredentials(
                sessionCredentials.getAccessKeyId(),
                sessionCredentials.getSecretAccessKey(),
                sessionCredentials.getSessionToken());

        AmazonS3Client s3object = new AmazonS3Client(basicSessionCredentials);
        // Test. For example, get object keys for a given bucket.
        ObjectListing objects = s3object.listObjects(bucketName);
        s3object.getObject( new GetObjectRequest(bucketName, key));
        System.out.println("No. of Objects = "
                + objects.getObjectSummaries().size());
    }
}

This code generate the dynamically access key,secret key and security token.Now i need to generate url with authorization header with signature so that i can access S3 object directly.Is there way?
From this code i want to generate url using x-amz-security-token

A: if you want to do this in java, you have to use AmazonS3.generatePresignedUrl
AmazonS3 s3client = new AmazonS3Client(new ProfileCredentialsProvider());

java.util.Date expiration = new java.util.Date();
long msec = expiration.getTime();
msec += 1000 * 60 * 60; // 1 hour.
expiration.setTime(msec);

GeneratePresignedUrlRequest generatePresignedUrlRequest =
              new GeneratePresignedUrlRequest(bucketName, objectKey);
generatePresignedUrlRequest.setMethod(HttpMethod.GET); // Default.
generatePresignedUrlRequest.setExpiration(expiration);

URL s = s3client.generatePresignedUrl(generatePresignedUrlRequest);

if you want to do this from the console, go to you s3 bucket, click download on the object. This displays a box where you can click on "download". If you right click on this link and copy the address link, you get a pre-signed url for this object


text:
Q: How do I add my own header file directory to Mac Terminal gcc? I'm trying to compile a C program (myProgram.c) that includes a custom .h file that is in a specified directory. How can I add the directory to gcc so that I can build myProgram.c anytime using just a command like gcc myProgram (with no flags and what not)

A: You can do this by altering the C_INCLUDE_PATH environment variable, e.g.
C_INCLUDE_PATH=~/include
export C_INCLUDE_PATH

You can add that to your .bashrc or .bash_profile or whatever to always have the environment variable set properly. Here's a reference on how you can do the same for libraries and C++.

A: had to use a whole set of flags to get this working on El Capitan:
export DYLD_LIBRARY_PATH=/usr/local/include
export CPPFLAGS="-I/usr/local/include/snappy-c.h"
export CFLAGS="-I/usr/local/include/snappy-c.h"
export CXXFLAGS="-I/usr/local/include/snappy-c.h"
export LDFLAGS="-L/usr/local/lib"

A: Makefiles would be helpful in this situation, they ease the compilation of multiple file projects.
Assuming you are using these same files and they are in the same directory

*

*main.c

*custom.c

*custom.h

A sample makefile could look like
all: main.o custom.o
    gcc main.o custom.o -o myExecutable

main.o: main.c
    gcc -c main.c

custom.o: custom.c custom.h
    gcc -c custom.c

clean:
    rm -f *.o myExecutable

Or something similar, the general format is
name: dependency
    command

So by running make all from the commandline you would be instructing the compiler to compile your source code into object files, and then link those object files together into an executable.
Make should be easily available on any modern system. For more information on basic makefiles and usage refer to this simple tutorial: http://mrbook.org/tutorials/make/


text:
Q: How to build a nested IF statement in SQL I have an issue where I want use certain query in certain case, but can not get the syntax to work. I am guessing it is because of the multiple IF´s but could someone enlighten me please how to fix it?
    IF smthn = 1 THEN
     SELECT stuff ,
      IFNULL(t3.value3,0.00) av_value,
       IF (t1.value1= t2.value2, t1.value1+ IFNULL(t3.value3,0.00) , t1.value1) kumul ,)
    t2.value2 summa
    FROM tbl_1 t1

    END//
        END IF;

   IF smthn = 2 THEN
     //make the query with different calculations//

    END//
        END IF;

Thanks

A: IF smthn = 1 THEN
    SELECT
        stuff,
        IFNULL(t3.value3,0.00) av_value,
        IF (t1.value1= t2.value2, t1.value1+ IFNULL(t3.value3,0.00) , t1.value1) kumul , -- Lose the extra closing bracket here.
        t2.value2 summa
FROM tbl_1 t1

-- You don't need END before your END IF
-- END//
END IF;

IF smthn = 2 THEN
    -- make the query with different calculations//

END IF;

Could you please try this variation of your code? I've commented the lines I've changed.

A: SQL Server Syntax
IF smthn = 1
BEGIN
 SELECT stuff ,
 ISNULL(t3.value3,0.00) av_value,
 case when (t1.value1= t2.value2 then t1.value1+ ISNULL(t3.value3,0.00) t1.value1) kumul ,)t2.value2 summa
FROM tbl_1 t1
END
ELSE IF smthn = 2
BEGIN
     --make the query with different calculations//
END


text:
Q: PyEphem Ephemeride Calculation Uncertainties I'm using PyEphem to calculate the future position of the Moon to high accuracy and am interested in quantifying the uncertainties and returning them as part of my script. Is there functionality within PyEphem to return uncertainties for body positions or do I need to calculate them myself?
I'm considering the position of the moon in J2000 RA and DEC and am trying to get lunar positions from the current time to 1 month in the future.
Thanks!

A: Alas, no — PyEphem does not provide any data about uncertainty. The best you could do would be to consult the source code to find what algorithm it uses (VSOP87, I think?) and then look up the uncertainties of that in the literature.


text:
Q: How to call a dialog box from another (Win32 application) I implemented a dialog-based Win32 Visual C++ application (Visual Studio Ultimate 2012) by following this article.
What is the way to call another dialog box (by clicking on a button) from the one I already created?

A: Add a button to the dialog in the dialog resource view. Just drag a button from the toolbar onto the dialog template. When the button is clicked you will get a WM_COMMAND message containing the button ID and the BN_CLICKED notification code.
http://msdn.microsoft.com/en-us/library/windows/desktop/bb761825(v=vs.85).aspx
Add a case in your DialogProc to detect the click. When you get it, create a new dialog by calling the DialogBox API.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms645452(v=vs.85).aspx
This second dialog will need you to write a new DialogProc2, just like the first DialogProc, to handle messages from the second dialog.


text:
Q: Identify identical geometry in column with common number in QGIS? I'm trying to identify identical (or duplicate) geometry in QGIS by adding a common number for each identical set. For example, if there are 4 features, and 2 are identical:
1| Identical with 2
2| Identical with 1
3|
4|
I want the following:
1|1
2|1
3|2
4|3
With ArcGIS, there is a tool called "Find Identical" that creates a table for geometry duplicates - you choose a shapefile and choose "Shape" under the list to identify within, and it produces a table of identicals, as above. Here is a screenshot of the tool:

A: There is Add unique value index field tool in QGIS 3.
(1) Preparation: create a WKT attribute field by geom_to_wkt($geometry) using the Field Calculator.

(2) Start Add unique value index field tool (in Processing Toolbox | Vector table) and assign your WKT field to Class field.

Output field (e.g. NUM_FIELD) has index number starting from 0. Probably you need to add 1 to obtain what you want (1, 2, 3...).


text:
Q: How to disable the screenshot in native iOS using objective c/Swift? Hello SO users since i started my career in swift and my current project is in objective c i need to convert my swift code into objective c .
I've requirement to disable taking screenshot in iOS device. since Apple not giving support for that, another workaround Im trying is - get notified when screenshot is taken using UIApplicationUserDidTakeScreenshotNotification and get last photo from photo gallery and delete it as below code in swift.
    func deleteAppScreenShot() {
    NSLog("i am here")
    let fetchOptions = PHFetchOptions()
    fetchOptions.sortDescriptors?[0] = Foundation.NSSortDescriptor(key: "creationDate", ascending: true)
    let fetchResult = PHAsset.fetchAssets(with: PHAssetMediaType.image, options: fetchOptions)
    guard let lastAsset = fetchResult.lastObject else { return }
    PHPhotoLibrary.shared().performChanges {
        PHAssetChangeRequest.deleteAssets([lastAsset] as NSFastEnumeration)
    } completionHandler: { (success, errorMessage) in
        if !success, let errorMessage = errorMessage {
            print(errorMessage.localizedDescription)
        }
    }
}

However the above approach is not the desired solution as it will always ask the user permission to delete the last photo
Can someone kindly tell how to disable the screenshot in iOS ?

A: A)
First of all iOS does not allows you to disable the screenshot so you must clearly convey to the Client or Any business person that it is not a feasible thing as it is OS related.
B)
Next thing the solution provided you is not an apt solution as it just detects when the screenshot is taken and after that user has to manually delete the screenshot with his permission . It cannot be done automatically(without user permission) as APPLE PHOTOS API does not allows you to do that because of strict user privacy policy. So this solution is the last implementation if any case client is adamant or anyhow wants to implement it, but according to my experience it is not a 100 percent solution and must not be implemented
I can understand the trouble of converting back from Swift to Objective c . Since i have the same experience i can share snapshot of Objective C codes which you can assemble together to achieve the desired result . The code is:
For getting last object:
PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init];
fetchOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
PHFetchResult *fetchResult = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:fetchOptions];
PHAsset *lastAsset = [fetchResult lastObject];

For deleting perhaps:
PHFetchResult *asset = [PHAsset fetchAssetsWithALAssetURLs:@"Your asset url" options:nil];
[asset enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
     NSLog(@"%@",[obj class]);
     [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
         BOOL req = [obj canPerformEditOperation:PHAssetEditOperationDelete];
         if (req) {
             NSLog(@"true");
             [PHAssetChangeRequest deleteAssets:@[obj]];
         }
     } completionHandler:^(BOOL success, NSError *error) {
         NSLog(@"Finished Delete asset. %@", (success ? @"Success." : error));
         if (success) {
            NSLog(@"delete successfully");
        }
    }];
    }];

Follow link1 link2 and yes write to me back in comment in any case.


text:
Q: Projection matrix: combining transition and fertility matrices for second stage group I would like to ask how to combine the following information into the projectio matrix. I do have data for transition (T) and fertility (F) matrices, so the projection matrix (A) is equal to the sum of these two matrices, i.e. A=T+F.
Concerning individuals in transition matrix, they may either move to unit time unit up (become one time unit "older") or down (vice versa) (i.e. entries in transition matrix are either subdiagonal or superdiagonal values).
The question would be how to combine T and F values in A for second stage group, where T and F entries overlap? That is, if probability to move from stage 2 to 3 is equal to e.g. 0.4, and from stage 2 to stage 1 = 0.1, it overlaps with the F value - 3 (which is not a probability, but a different unit). How to meaningully combine this information? Thank you in advance.
Please find below matrix to illustrate the problem. P(i) - probability of moving from one stage to another, and Z(i) - probability of moving from one stage to another backwards (time reversability); F(i) - fertility values.
A=
    [,1] [,2]           [,3]   [,4] [,5]
[1,] 0.0  F(i)???Z(i)   F(i)   F(i)  F(i)
[2,] P(i)  0.0          Z(i)   0.0   0.0
[3,] 0.0  P(i)          0.0    Z(i)  0.0
[4,] 0.0  0.0           P(i)   0.0   Z(i)
[5,] 0.0  0.0           0.0   P(i)   0.0

A: Since the expected number of individuals in stage 1 at time t+1 contributed by individuals in stage 2 at time t is indeed F(i)+Z(i) (i.e., individuals can both produce offspring and regress one stage, provided that they reproduce before they regress), the value of A[2,2] should indeed be F(i)+Z(i).


text:
Q: Why does $e^{(-x)^8}$ = $e^{x^8}$ can someone please explain to me why $e^{(-x)^8}$ = $e^{x^8}$ ?
Edit: OH CRAP I CAN'T TYPE... MY TITLE WAS WRONG. But my question is the same. When I typed out on desmos: $e^{(-x)^8}$, I get the same curve as $e^{(x)^8}$
Edit 2: OH MY GOD... I READ IT WRONG. IT'S $e^{(-x)^8}$

A:
Why does $e^{-x} = e^{x}?$

It doesn't, except for when $x = 0.$

Post-edit second question:

Why does $e^{(-x)^8} = e^{x^8}$?

This is, in fact, true. When you raise a negative to an even power, you get a positive. You may already know that
$$(-1)^2 = (-1)\cdot (-1) = 1.$$
More generally,
$$(-x)^{2n} = (-x)^n\cdot (-x)^n = (-1)\cdot(-1)\cdot x^n\cdot x^n =  x^{2n}.$$
Try instead $e^{(-x)^7}$, which won't equal $e^{x^7}$ because $7$ isn't even.


text:
Q: Combining a sortable table with a checkbox sum output My current code has a checkbox sum function which takes values from database.
I am also trying to apply another Javascript code to my table that allows me to sort the data in the rows.
For example, after sorting the rows to display all 5 ACER assets on the top. i want tick the checkboxes of the top 5 displayed ACER assets and sum them.
This is my current code:
<?php
    include('connect1.php');
    $retrieve = $db->prepare("SELECT count(*) FROM Asset");
    $retrieve->execute();
    $fetchrow = $retrieve->fetch(PDO::FETCH_NUM);
    $calculated=$fetchrow[0];
?>

<link rel="stylesheet" href="style.css" />

Total Cost : <input type="text" name="sen" id="totalcost" value="" />

Asset ID

Vendor

Hardware

Cost

Date Of Purchase

Select Values

        <?php
            // include('connect1.php'); you already included this file
            $result = $db->prepare("SELECT * FROM Asset");
            $result->bindParam(':userid', $res);
            $result->execute();
            for($i=0; $row = $result->fetch(); $i++){
            ?>

                <?php echo $row['Asset_ID']; ?>
                <?php echo $row['Vendor_Name']; ?>
                <?php echo $row['Hardware_ID']; ?>
                <?php echo $row['Asset_Cost']; ?>
                <?php echo $row['DateOfPurchase']; ?>

<INPUT TYPE="checkbox" NAME="items[]" value="<?php echo $row['Asset_Cost'] ?>" id="sum_m_<?php echo $i ?>" onclick="UpdateCost()">

            <?php
            }
        ?>

        <select onchange="sorter.size(this.value)">
            <option value="5">5</option>
            <option value="10" selected="selected">10</option>
            <option value="20">20</option>
            <option value="50">50</option>
            <option value="100">100</option>
        </select>
        Entries Per Page

Displaying Page  of

This is the Javascript :
var TINY={};

function T$(i){return document.getElementById(i)}
function T$$(e,p){return p.getElementsByTagName(e)}

TINY.table=function(){
    function sorter(n){this.n=n; this.pagesize=20; this.paginate=0}
    sorter.prototype.init=function(e,f){
        var t=ge(e), i=0; this.e=e; this.l=t.r.length; t.a=[];
        t.h=T$$('thead',T$(e))[0].rows[0]; t.w=t.h.cells.length;
        for(i;i<t.w;i++){
            var c=t.h.cells[i];
            if(c.className!='nosort'){
                c.className=this.head; c.onclick=new Function(this.n+'.wk(this.cellIndex)')
            }
        }
        for(i=0;i<this.l;i++){t.a[i]={}}
        if(f!=null){var a=new Function(this.n+'.wk('+f+')'); a()}
        if(this.paginate){this.g=1; this.pages()}
    };
    sorter.prototype.wk=function(y){
        var t=ge(this.e), x=t.h.cells[y], i=0;
        for(i;i<this.l;i++){
      t.a[i].o=i; var v=t.r[i].cells[y]; t.r[i].style.display='';
      while(v.hasChildNodes()){v=v.firstChild}
      t.a[i].v=v.nodeValue?v.nodeValue:''
    }
        for(i=0;i<t.w;i++){var c=t.h.cells[i]; if(c.className!='nosort'){c.className=this.head}}
        if(t.p==y){t.a.reverse(); x.className=t.d?this.asc:this.desc; t.d=t.d?0:1}
        else{t.p=y; t.a.sort(cp); t.d=0; x.className=this.asc}
        var n=document.createElement('tbody');
        for(i=0;i<this.l;i++){
            var r=t.r[t.a[i].o].cloneNode(true); n.appendChild(r);
            r.className=i%2==0?this.even:this.odd; var cells=T$$('td',r);
            for(var z=0;z<t.w;z++){cells[z].className=y==z?i%2==0?this.evensel:this.oddsel:''}
        }
        t.replaceChild(n,t.b); if(this.paginate){this.size(this.pagesize)}
    };
    sorter.prototype.page=function(s){
        var t=ge(this.e), i=0, l=s+parseInt(this.pagesize);
        if(this.currentid&&this.limitid){T$(this.currentid).innerHTML=this.g}
        for(i;i<this.l;i++){t.r[i].style.display=i>=s&&i<l?'':'none'}
    };
    sorter.prototype.move=function(d,m){
        var s=d==1?(m?this.d:this.g+1):(m?1:this.g-1);
        if(s<=this.d&&s>0){this.g=s; this.page((s-1)*this.pagesize)}
    };
    sorter.prototype.size=function(s){
        this.pagesize=s; this.g=1; this.pages(); this.page(0);
        if(this.currentid&&this.limitid){T$(this.limitid).innerHTML=this.d}
    };
    sorter.prototype.pages=function(){this.d=Math.ceil(this.l/this.pagesize)};
    function ge(e){var t=T$(e); t.b=T$$('tbody',t)[0]; t.r=t.b.rows; return t};
    function cp(f,c){
        var g,h; f=g=f.v.toLowerCase(), c=h=c.v.toLowerCase();
        var i=parseFloat(f.replace(/(\$|\,)/g,'')), n=parseFloat(c.replace(/(\$|\,)/g,''));
        if(!isNaN(i)&&!isNaN(n)){g=i,h=n}
        i=Date.parse(f); n=Date.parse(c);
        if(!isNaN(i)&&!isNaN(n)){g=i; h=n}
        return g>h?1:(g<h?-1:0)
    };
    return{sorter:sorter}
}();

this is the actual working sortable table:
<?php
    include('connect1.php');
    $retrieve = $db->prepare("SELECT count(*) FROM Asset");
    $retrieve->execute();
    $fetchrow = $retrieve->fetch(PDO::FETCH_NUM);
    $calculated=$fetchrow[0];
?>

<input type="button" value="Search" onclick="window.location.href='http://mp04.bit-mp.biz/Ashvin/SearchACost.php'" />

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Costing</title>
<link rel="stylesheet" href="style.css" />

Asset ID

Vendor

Hardware

Cost

<INPUT TYPE="checkbox" NAME="items[]" value="<?php echo $row['Asset_Cost'] ?>" id="sum_m_<?php echo $i ?>" onclick="UpdateCost()">

        <?php

        mysql_connect("localhost","user","pass");
mysql_select_db("db");

$result = mysql_query("SELECT * FROM Asset");

        while($row = mysql_fetch_array($result))

         for($i=0; $row = $result->fetch(); $i++){
 {

    echo "
";

    echo "" . $row['Asset_ID'] . "	";
    echo "" . $row['Vendor_Name'] . "	";
    echo "" . $row['Hardware_ID'] . "	";
    echo "" . $row['Asset_Cost'] . "	";

    echo "
";
 }
         }
echo "
";

            ?>

            <select onchange="sorter.size(this.value)">
            <option value="5">5</option>
                <option value="10" selected="selected">10</option>
                <option value="20">20</option>
                <option value="50">50</option>
                <option value="100">100</option>
            </select>
            Entries Per Page

Displaying Page  of


text:
Q: Multipart form parse error - Invalid boundary in multipart: None content-type issue? I am working on simple CRUD with react and react-redux and having trouble with POST in client side
BoardList.js
import React, { Component, Fragment } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { getBoards, deleteBoard, addBoard } from "../../actions/boards"

export class BoardList extends Component {
    static propTypes = {
        boards: PropTypes.array.isRequired,
        getBoards: PropTypes.func.isRequired,
        deleteBoard: PropTypes.func.isRequired,
        addBoard: PropTypes.func.isRequired
    }
    componentDidMount() {
        this.props.getBoards();
    }
    shouldComponentUpdate(nextProps, nextState){
        return this.props.boards !== nextProps.boards
    }
    render(){
        return (
            <Fragment>

Boards

                            ID
                            Author
                            Title
                            Created
                            Updated

                        {this.props.boards.length > 0 && this.props.boards.map(board => (

                             // Uncaught TypeError: Cannot read property 'id' of undefined
                                {board.id}
                                {board.author}
                                {board.title}
                                {board.created}
                                {board.updated}

                                    <button
                                      className="btn btn-danger btn-sm"
                                      onClick={this.props.deleteBoard.bind(this, board.id)}
                                      >
                                      Delete</button>

                        ))}

            </Fragment>
        )
    }
}

const mapStateToProps = state => ({
    boards: state.boards.boards,
})

export default connect(mapStateToProps, {getBoards, deleteBoard, addBoard})(BoardList)

reducers/boards.js
import { GET_BOARDS, DELETE_BOARD, ADD_BOARD } from "../actions/types.js";

const initialState = {
    boards : []
}

export default function(state=initialState, action) {
    switch (action.type) {
        case GET_BOARDS:
            return {
                ...state,
                boards: action.payload
            }
        case DELETE_BOARD:
            return {
                ...state,
                boards:state.boards.filter(board => board.id !== action.payload)
            }
        case ADD_BOARD:
            return {
                ...state,
                boards:[...state.boards, action.payload]
            }
        default:
            return state;
    }
}

actions/boards.js

export const addBoard = board => (dispatch, getState) => {
    const token = getState().users.token;
    const config = {
        headers: {
            'Content-Type': undefined   //I suspect this is wrong
        }
    if(token){
        config.headers["Authroization"] = `Token ${token}`
    }
    axios
      .post("api/boards/",board, tokenConfig(getState))
      .then(res=> {
          dispatch(createMessage({ addBoard: "Board added"}));
          dispatch({
              type:ADD_BOARD,
              payload: res.data
          })
      })
      .catch(err => dispatch(returnErrors(err.response.data, err.response.status)));
}

I know this error message is related to django rest framework, however I can POST it through the Postman. So I think it is my Content-Type issue.(If I am wrong, please correct me) At very first time, I thought django rest framework pass json, so I used application/json. then I got The submitted data was not a file. Check the encoding type on the form. I also used multipart/form-data and undefined then I get Multipart form parse error - Invalid boundary in multipart: None error.
How can I handle this issue?

A:

// **This is solve from my project**

  export const Get_user_profile=(data)=>new Promise((re, rej)=>{
    const  usertoken ={
        'Content-Type': 'application/json',
        'Authorization':`Bearer ${Cookies.get('access_token')}`
        }
    const  get_profile=async()=>{
        await axios({

            method: 'post',
            url:`http://127.0.0.1:8000/api/v1/User_profile/`,
            headers: {
                'Authorization':`Bearer ${Cookies.get('access_token')}`,
                'Content-Type': 'multipart/form-data'
              },
            data:data,
             })
        .then(response =>{
            re(response)
        }).catch(error=>{
        rej(error)
        })
      }
      get_profile()
})

   //===============data==
  const profile_pic=useRef()
  let formData = new FormData()
    formData.append('profile_pic', profile_pic.current.files[0])

 //===============send request=========================
   Get_user_profile(formData).then(response=>{
        var val=[response.data]
        val.map(x=>{
          dispatch(User_profile(x))
        })
        toast.success("Sucessfully update");
      }).catch(error=>{
        toast.error(error.request);
        console.log(error.request)
      })

A:     let formData = new FormData()
    formData.append('userPhotos', file)
    formData.append('your_field', your_data)
    formData.append('your_field', your_data)
    formData.append('your_field', your_data)

    axios({
        withCredentials: true,
        url: 'your_url',
        method: 'POST',
        data: formData
    })


text:
Q: Write a basic program that takes number and returns its corresponding month abbreviation I'm trying to write a basic function that takes a number and returns the abbreviation of each month. It sounds simple enough, but how can I use a "try-except"block to handle any exceptions?
Here's what I have so far.
def month():
    months = "JanFebMarchAprilMayJuneJulyAugSepOctNovDec"
    n = eval(input("Enter month Number: "))
    pos = (n-1)*3
    monthAbbrev = months

    return monthAbbrev

I guess my question is how can I put in a try-expect handle indexes that are out of range?
I'm completely lost here. Thanks for your help

A: This simply returns the month at the correct index and if it doesn't exist it retruns the String Error replace it by whatever you need.
def month(n):
        months = ("Jan", "Feb", "Mar", ...)
        try:
            return months[n-1]
        except IndexError:
            return "Error"

A: import datetime
mydate = datetime.datetime.now()
mydate.strftime("%b")
Get month name from number
Surround that with a try except to catch any errors


text:
Q: Whats the quickest way to crop pics? What is the quickest tool that can let me choose a rectangle (of a predefined size) within any picture file, and it should crop it to that. Something like the tool you get when uploading a Gravatar ... remember?
Typical image editing software like Paint.NET or Photoshop is too slow, you have to open the image file, select a rectangle manually, crop, save, close ....

A: There is JPEGCrop, which is a Windows GUI application for most of the jpegtran features:

A new -crop option has been added to jpegtran for 'lossless' cropping of JPEG images:

    -crop WxH+X+Y  Crop to a rectangular subarea

A: I made a free tool to do that:
https://github.com/weclaw1/inbac
Just select the part of image you want to crop and press X to crop or Z to crop and go to the next image.

A: ImageMagick has crop options.

A: my tool of choice:
PhotoFiltre, dead fast, free and portable.

A: I use MSPaint for this, and it's pretty quick. It's almost a reflex.
The fact that it loads quickly and is available on any (windows) machine you use makes it particularly appropriate.

A: It doesn't get any simpler than in Google's Picasa.
Draw the box, hit the button and you are done.
Be aware that Picasa does not make permanent changes to the image - it stores the edits and re-applies them when you view the image.
If you want to send the cropped image, or view it in another app, you would export a copy of the image.
http://picasa.google.com/#utm_campaign=en&utm_source=en-ha-na-us-bk&utm_medium=ha&utm_term=picasa

A: If you have microsoft office it's quick and easy: 'Open with' Microsoft Office Picture Manager, Click 'edit pictures' at the top, A window will open to the right with 'crop'

A: There are lot of online tools to do that quickly:
http://www.cutmypic.com
http://www.cropmyimage.net

A: After a lot of searching and evaluating, i eventually found a tool called "Click 2 crop".
Its simple and dead fast for manual cropping. It have the options you are asking for.
Its not free but offers a 15 day evaulation.


text:
Q: Creation of one AR causes creation of another AR In DDD, is it okay if creation of one AR forces creation of another AR?  Take for example:
class User
{
  // User related functins
}

class Schedule
{
  // Schedule related functions
}

class Scheduler
{
  private ScheduleRepository repo; // injected

  public void Schedule(User user, Event event)
  {
    Schedule schedule = repo.FindByUser(user);
    schedule.Add(event);
    repo.Save(schedule);
  }
}

There is a 1:1 mapping between user and schedule.  When a user is created they need to have a schedule.  I cannot see why a schedule would exist without a user.  Additionally, when a user is removed from the roster/database, I still want their old schedule to persist in the scheduling database.
The User object will not have a reference to their actual schedule.  You would have to use the Scheduler object to actually schedule the event.  User would have a private ID and numerous Identity properties such as 'Name', 'Email', etc.
Am I overcomplicating this?  Additionally, when a user is created, I would assume I would need to query the UserRepository to get the ID (PK?) to associate with the Schedule object.

A: Creation patterns are weird....

In DDD, is it okay if creation of one AR forces creation of another AR?

"It depends", which is part of the problem.
Aggregates, as described Evan's in the blue book, are consistency boundaries;  you use the aggregate root to manipulate the state encapsulated within that boundary, and thereby ensure that it is always in a self consistent state.
This works great if you are single threaded.
When you are multi-threaded, you now have an additional concern: to ensure that one thread doesn't clobber writes made in another thread.  In other words, you need to start thinking about transaction boundaries, and data races.
In particular, if you have one transaction that tries to update aggregates that are stored in different persistence structures, then you have two phase commit to worry about.
This has lead a number of people to the conclusion that aggregates should be in alignment with transaction boundaries as well, which is to say that a modification to an aggregate should never be allowed to change data that might be stored separately.
In effect, this pushes the orchestration of the (potential) two phase commit back into the domain model, where you can manage it explicitly (process managers/sagas).  Implemented in this fashion, your processes start to look more like the domain model pattern described by Fowler
Imagine, for example, that the UserRepository and the ScheduleRepository are two different in memory collections.  You write to the first one, you write to the second, oops, that failed, you try to undo the write to the first... which already has additional changes written into it that you now need to worry about....
When your persistence store is a relational model (which was frequently the case in the early 2000s when Evans was writing), you can use something like a UnitOfWork pattern to manage the disconnect -- if the two collections are stored together.  You can achieve something similar with in memory collections, if you work at it enough, although you get the same sorts of contention concerns.

Additionally, when a user is removed from the roster/database, I still want their old schedule to persist in the scheduling database.

You may want to review Udi Dahan's essay Don't Delete -- Just Don't

A:
In DDD, is it okay if creation of one AR forces creation of another AR?

Yes, it is OK. You may encounter this when you try to apply SRP to Aggregates.

Additionally, when a user is removed from the roster/database, I still want their old schedule to persist in the scheduling database.

This is another indication that you need two separate Aggregates.
However, keep in mind that, because you have two Aggregates, you have eventual consistency between them, this means that it could take a while before the second Aggregate is created. An Aggregate can ensure only its own consistency.
As @VoiceOfUnreason said, the creation of the second Aggregate may fail and your system should not panic when this happens. One solution to cope with this situation is to model the creation of the two Aggregates as a Saga/Process manager. This Saga would have the responsibility that, eventually, the second Aggregate gets created (i.e by retrying or by notifying an Administrator to take some action).


text:
Q: Does uploading reduce download speed in torrent? I was searching to know: "Does uploading and downloading at the same time reduce download speed?" and I found this:
Should uploading a file on DSL kill the download speed?
but it is related to TCP connections, not UDP.
I know torrent uses UDP connection. Then does allowing torrent upload reduce torrent download speed?

A: Whether UDP or TCP is used, to have a reliable transfer, packets have to be acknowledged.  (In the case of UDP, the application itself must generate the acks since the protocol doesn't.)  Thus the same reasoning applies as to the other question you referred to.
Saturating the "up" part of your Internet connection slows downloading because packets coming "down" have to be acknowledged by your computer and those acknowledgements have to go out via the up link.  If your computer falls too far behind in acks because the up link is choked with data, the sender will slow down and start retransmitting the unacknowledged packets.  This will appear to you as a decrease in download speed.

A: It will affect your download speeds, yes - especially since you are on DSL. If your network is maxing out it's outbound bandwidth with packets to peers (sharing), you won't have enough spare outbound bandwidth to ask for more pieces of the torrent you are receiving.
Adjust your outbound bandwidth to about two-thirds what your link can handle, and you should be golden.


text:
Q: Stream static video file through webrtc what I am trying to accomplish is to have on my page audio and video file. And then send them through webrtc. I managed to do this with audio using web audio api like this.
HTML:
  <audio id="audio">
    <source src="../assets/outfoxing.mp3" />
  </audio>

JS:
const audioElement = document.getElementById("audio");
const incomingSource = audioContext.createMediaElementSource(audioElement);

const outgoingStream = audioContext.createMediaStreamDestination();
incomingSource.connect(outgoingStream);
const outgoingTrack = outgoingStream.stream.getAudioTracks()[0];
audioElement.play();
await this.sendTransport.produce({ track: outgoingTrack });

For webrtc I am using mediasoup
Now I want to do the same with the video. But there is no such thing like web video api so I am stuck. How can I accomplish this task.

A: There are some limitations, but you could refer to this sample implementation.
It uses the captureStream() method.


text:
Q: Part of the TimePicker is cropped in landscape TimePicker is working fine for me, except in landscape view, where it is either cropped a bit from the right not showing the whole clock, or the clock is not even visible, just giving me the background colors (left is pink and right is white) instead. Tried to look for solutions all came back as "don't set a title", I didn't set a title, even tried setting the title as null, didn't work.
xml file
<?xml version="1.0" encoding="utf-8"?>
<TimePicker xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/dialog_time_picker"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

</TimePicker>

called using these lines
FragmentManager fm = getFragmentManager();
TimePickerFragment dialog =
        TimePickerFragment.newInstance( mTimeString );
dialog.setTargetFragment( NewBlockFragment.this, REQUEST_TIME );
dialog.show(fm, DIALOG_TIME);

and the timepicker class
public class TimePickerFragment extends DialogFragment {

    public static final String EXTRA_TIME = "com.x";
    private static final String ARG_TIME = "time";

    private TimePicker mTimePicker;

    public static TimePickerFragment newInstance(String time) {
        Bundle args = new Bundle();
        args.putSerializable(ARG_TIME, time);
        TimePickerFragment fragment = new TimePickerFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        String time = getArguments().getString(ARG_TIME);
        int hour = Integer.parseInt(time.split(":", -1)[0]);
        int minute = Integer.parseInt(time.split(":", -1)[1]);

        View v = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_time, null);

        mTimePicker = (TimePicker) v.findViewById(R.id.dialog_time_picker);
        mTimePicker.setIs24HourView(true);

        if(android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            mTimePicker.setHour(hour);
            mTimePicker.setMinute(minute);
        } else {
            mTimePicker.setCurrentHour(hour);
            mTimePicker.setCurrentMinute(minute);
        }

        return new AlertDialog.Builder(getActivity())
                .setView(v)
                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        int hour;
                        int minute;

                        if(android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                            hour = mTimePicker.getHour();
                            minute = mTimePicker.getMinute();
                        } else {
                            hour = mTimePicker.getCurrentHour();
                            minute = mTimePicker.getCurrentMinute();
                        }

                        sendResult(Activity.RESULT_OK, hour + ":" + minute);
                    }
                })
                .setNegativeButton(android.R.string.cancel, null)
                .create();
    }

    private void sendResult(int resultCode, String time) {
        if (getTargetFragment() == null) {
            return;
        }
        Intent intent = new Intent();
        intent.putExtra(EXTRA_TIME, time);
        getTargetFragment()
                .onActivityResult(getTargetRequestCode(), resultCode, intent);
    }
}

Main logcat exceptions I get
09-22 13:04:25.847 1784-2256/com.android.systemui E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7fb429023080
09-22 13:04:25.853 2825-2825/com.x D/android.widget.GridLayout: horizontal constraints: x1-x0>=503, x2-x1>=816, x2-x0<=864 are inconsistent; permanently removing: x2-x0<=864

A: Please give a try to this :
timePicker.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

A: Try this code
@Override
public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.<YOUR_XML_FILE_NAME>);

Change below code:
@Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
setContentView(R.layout.<YOUR_XML_FILE_NAME>);
}

A: Fixed it by totally changing the "timepickerfragment.java" code, still not sure what was wrong with the first one, but here it is for anyone that doesn't want to spend the next four days looking for answer that I couldn't find on several asking boards
import android.app.Activity;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.widget.TimePicker;

public class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener {

    public static final String EXTRA_TIME =
            "com.x.time";
    private static final String ARG_TIME = "time";

    private TimePicker mTimePicker;

    public static TimePickerFragment newInstance(String time) {
        Bundle args = new Bundle();
        args.putSerializable(ARG_TIME, time);
        TimePickerFragment fragment = new TimePickerFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        String time = getArguments().getString(ARG_TIME);
        int hour = Integer.parseInt(time.split(":", -1)[0]);
        int minute = Integer.parseInt(time.split(":", -1)[1]);

        // TODO this for 24-hours, make the final false for AM/PM or make it variable
        return new TimePickerDialog(getActivity(), this, hour, minute, true);
    }

    @Override
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        sendResult(Activity.RESULT_OK, hourOfDay + ":" + minute);
    }

    private void sendResult(int resultCode, String time) {
        if (getTargetFragment() == null) {
            return;
        }
        Intent intent = new Intent();
        intent.putExtra(EXTRA_TIME, time);
        getTargetFragment()
                .onActivityResult(getTargetRequestCode(), resultCode, intent);
    }
}


text:
Q: Proper way to use where clause while including TempData? ASP NET CORE I am doing a project and I am trying to display Reviews based on StaffID stored by TempData. I used a where clause to display the specific reviews based on the user's StaffID that is stored by TempData.
What I am trying to achieve is here :
In this picture above, I hard coded it and I believe my Where clause works properly. I just need to know how to properly use Where clause while including the TempData inside so it takes the StaffID directly from the SQL Database.
This picture below is what happens when I run my code without using hard coded values from my DataBase, thus it is not working. If someone knows, please do help me. Thank you so much

Controller code(where RevieweeID.Equals(@TempData["StaffID"] is the part where I need help with):
public async Task<IViewComponentResult> InvokeAsync()
{
    var applicationUserClass = _context.Review.Where(r => r.ReviewCategoryID.ToString().Equals("601C21CF-0916-4C40-B158-D7253858386F")).Where(r => r.RevieweeID.Equals(@TempData["StaffID"])).Include(r => r.ReviewCategorys).Include(r => r.Staff).Include(r => r.Staffs);
    return View(await applicationUserClass.ToListAsync());
}

A: If you want to use TempData with where,you can use TempData["xxx"].ToString():
Here is a demo worked:
Student s = _context.Student.Where(stu => stu.Id.ToString().Equals(TempData["id"].ToString())).ToList()[0];

result:


text:
Q: Not able to get access token for google+ through Oauth 2.0 in iPhone application I am trying to access Google+ APIs with Oauth 2.0 in iPhone Application. For this purpose I am using OauthConsumer library. I got the unauthorized request_token and also authorization code but not able to exchange that request_token for access_token using authorization code. I am getting error as "invalid_request". Below is the code snippet, am I doing anything wrong or missing any parameter?
Code:
-(void)getAccessTokenWithAuthorizationCode:(NSString *)code
{

    NSURL *accessTokenURL = [NSURL     URLWithString:@"https://accounts.google.com/o/oauth2/token"];

    OAMutableURLRequest *accessRequest = [[OAMutableURLRequest alloc] initWithURL:accessTokenURL
                                                                    consumer:consumer
                                                                       token:requestToken
                                                                       realm:nil   // our service provider doesn't specify a realm
                                                           signatureProvider:nil]; // use the default method, HMAC-SHA1
    [accessRequest setHTTPMethod:@"POST"];

    OARequestParameter *authCode = [[OARequestParameter alloc] initWithName:@"code" value:code];
    OARequestParameter *redirectURI = [[OARequestParameter alloc] initWithName:@"redirect_uri" value:kRedirectURI];
    OARequestParameter *granType = [[OARequestParameter alloc] initWithName:@"grant_type" value:@"authorization_code"];

    [accessRequest setParameters:[NSArray arrayWithObjects:authCode, redirectURI, granType, nil]];

    OADataFetcher *fetcher = [[OADataFetcher alloc] init];

    [fetcher fetchDataWithRequest:accessRequest
                     delegate:self
            didFinishSelector:@selector(accessTokenTicket:didFinishWithData:)
              didFailSelector:@selector(accessTokenTicket:didFailWithError:)];
}

A: FYI - I'm not familiar with Objective-C, but hopefully some knowledge of OAuth will help you figure this out.
"authorized request tokens" are used in OAuth 1.0
"authorization codes" are used in OAuth 2.0
I'm not seeing anything saying that OauthConsumer supports OAuth 2.0
You asked:
"am I doing anything wrong or missing any parameter?"
I think you are missing the client secret, which is necessary to exchange an authorization code for an access token in OAuth 2.0.  See the Google OAuth 2.0 documentation for more information on what you need to provide to exchange an authorization code for an access token.
You might want to check out the Google Toolbox for Mac - OAuth 2 Controllers:
http://code.google.com/p/gtm-oauth2/wiki/Introduction


text:
Q: Sample conditional distribution for three variables I would like to create a setup where the dependent variable y and two explanatory variables x and z with specified conditional correlations r_yxand r_zx and r_yz that I can vary myself.
r_yx <- 0.9
r_zx <- -0.5
r_yz <- 0.9

n <- 10000

x <- rnorm(n, mean = 0, sd = 1)

y <- r_yx*x + rnorm(n, mean = 0, sd = 1)

Question 1: How can I now create x so that it the correlation with y is r_yx = .9 and the correlation with z = -.5?
Question 2: Also checking cor(y,x) shows that it is not that close to 0.9. How can I set it correctly?

A: It's difficult to generate random samples that have an exact correlation, but you can get pretty close. For positive correlations with x, just add some noise to x. The better you want the correlation, the smaller you make the sd.
We can get fairly close to 0.9 and -0.5 like this
n <- 10000

set.seed(1)

x <- rnorm(n, mean = 0, sd = 1)

y <- x + rnorm(n, 0, sd = 0.5)

z <- -x + rnorm(n, 0, 1.75)

cor(x, y)
#> [1] 0.8986359

cor(x, z)
#> [1] -0.4983418

However, you cannot independently change the correlation of y to z if you have already fixed their correlation to x. In the extreme case, if y's correlation with x was 1, then y would be identical to x, and would therefore have to have the same correlation to z as x did.
Created on 2022-06-12 by the reprex package (v2.0.1)


text:
Q: Loading ORC Data into SQL DW using PolyBase I am trying to load ORC file format via PolyBase but I am facing below problems.
Problem:1
I have a CSV file which below code converts the csv file to ORC format but its selecting data from permanent table. If I remove "as select * from dbo.test" then create external table is not working. Permanent table contains 0 record.
 create external table test_orc
 with
 (
 location='/TEST/',
 DATA_SOURCE=SIMPLE,
 FILE_FORMAT=TEST_ORC
 )
 as select * from dbo.test ---Permanent Table

Problem:2
If I select the data from test_orc then I am getting invalid postscript error so, I removed my .csv file from the TEST directory. Is there any way to convert CSV to ORC  file in different directory like TEST2.
Problem:3
If I select the data from  test_orc then the count is zero and I am not getting any error.
select count(*) from test_orc---count is zero

Expectation
Need to load ORC file in the TEST directory to dbo.test table.
Please share your thought one this issue.


text:
Q: Repair/Reset Hard Disk - don't mind losing data I have an Alienware M14x R2 with a Seagate Momentus hybrid HDD/SSD.
I clean installed Windows 10 today and I booted Gparted from a USB to edit my partitions. I accidentally ended up moving the OS partition. I am ashamed to say that I panicked and I disconnected the USB.
I was able to reinstall Windows 10, but it runs slow and it is unstable. My BIOS no longer recognises the RAID0 setup and says my 750GB HDD is non-Raid and my 32gb SSD is disabled.
I would like to format the hard disk and return it to factory settings, complete with RAID setup. I don't have any important data on the hard disk.
I am sure this question has been answered many times, but I cannot find it in the sea of questions about saving important data on the disk.

A: Given that it is a Dell model there should be instructions on the web somewhere... I did the following on my old Inspiron 17R Special to get it going after I revamped its hardware. In terms of release dates they are almost identical so the steps involved are most likely identical
Intel Smart Response
Setting the quick start.


text:
Q: How do I include jquery plugin in Yii framework? I have a problem when I include jquery's plugin, image isn't visible. The image is included in a css file.
div{background-image:url('famfamfam.png');background-repeat:no-
repeat;width:16px;height:16px}

That plugin
example of my attempts. The code placed at

/webroot/protected/components/MyWidjet.php

in a method

init()

$cs = Yii::app()->clientScript;
        $cs->registerCssFile(Yii::app()->assetManager->publish(dirname(__FILE__).'/css/
 editor.css'));
     $cs->registerPackage(Yii::app()->assetManager->publish(dirname(__DIR__).'/vendor/
 minified/'));
        $cs->registerCssFile(Yii::app()->assetManager->publish(dirname(__DIR__) .
                '/vendor/minified/themes/default.min.css'));
        $cs->registerScriptFile(Yii::app()->assetManager->publish(dirname(__DIR__) .
                '/vendor/minified/jquery.sceditor.bbcode.min.js'));

  echo CHtml::script("$(function() {
            $('textarea').sceditor({
                plugins: 'bbcode',
                toolbar:
  'bold,italic,horizontalrule,underline,strike,subscript,superscript|left,center,right,\
                justify|size,color|bulletlist,orderedlist|table|
  code,quote,image,link,unlink|maximize,source',
            locale: 'ru',
            charset: 'utf-8',
            autofocus: true,
            enablePasteFiltering: true,
            spellcheck: true,
            style: 'minified/jquery.sceditor.default.min.css'
            });
        });");

Access rights are 777

A: One way of doing it theme-wide:
Add the clientScript calls to your themes/themename/views/layouts/main.php in the head, or wherever you want.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<?php Yii::app()->clientScript->registerCoreScript('jquery'); ?>
<?php Yii::app()->clientScript->registerCoreScript('cookie'); ?>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
.....

Or you can add them to controller methods, or in various other places.  But this will make sure Jquery is plagged in everywhere :)

A: http://codingtip.blogspot.com/2013/09/yii-register-client-script-add-javascript-css-file.html
http://www.yiiframework.com/forum/index.php/topic/5309-clientscript-register/
http://code.dimilow.com/yii-adding-javascript-into-your-views/
http://www.waytoblogger.com/2012/08/13/register-js-css-files-in-yii-framework/
Best way of global registering ClientScript?
:D
UPDATE: for every document you have to give relative path from index.php, since all requests are handled there


text:
Q: where are all the places C++ searches for includes? Is there a way to check all of the locations C++ searches for includes? I would like to understand why some includes are found and others are not.
EDIT: Platform is Linux, g++

A: This is compiler-dependent: you pass the locations for the headers in angular brackets, and the headers in double quotes are expected to be at the path rooted at the location of the current file; compilers also let you specify additional locations for these files.
For example, gcc has two options - -I and -i for specifying locations of headers specified as <header.h> and "header.h". If -I is not specified, the default locations of
 /usr/local/include
 libdir/gcc/target/version/include
 /usr/target/include
 /usr/include

are searched, as specified in the gcc documentation.

A: 16.2 [cpp.include] defines this for C++; the language in C is pretty much the same.
#include <header.h> searches a set of implementation-defined locations for a "header" with that name. This "header" does not have to be a file; it can be something the compiler magically knows about.
#include "header.h" also searches a set of implementation-defined locations, but it looks for a file with the name "header.h". if that search fails, it treats the directive as #include <header.h>.
Many compilers implement the second search by looking in the "current directory", which for some compilers means the directory from which the compiler was launched, and for others means the directory in which the file containing the #include directive is located.
In general, you should us the quoted form for you headers; the angle brackets, because they don't require a file, should be left for the implementation to use. Not that using angle brackets for your own headers won't work, but it's anti-thematic.


text:
Q: How to add symbols in a form field? My form has a textbox to input a 9 digit number. Once the user enters the digits, i wish to format the text box in the following way :
123456789 gets altered to 12-345-6789
How can this be achieved?

A: It's simple if you can use Java script. This code uses plain Javascript (just add it to your page).
<script>
function formatText(){
var text = document.getElementById("txt1").value;
var fmtTxt = text.substr(0,2)+"-"+text.substr(2,3)+"-"+text.substr(5,4);
document.getElementById("txt1").value = fmtTxt;
}
</script>

You still need to add the formatText method to the onchange event belonging to your text field element.
<input type="text" id="txt1" onchange="formatText()">


text:
Q: Multi dimensional (2d better 3d) scatter-plot with different errorbars in matlab I am trying to program scatterplot with specific errorbars. The only build in function i found is
errorbar()

but this only enables me to make a 2d plot with errorbars in y direction. What i am asking for is a method to plot this with errorbars in x and y direction.
At the end my goal is to make a 3D-scatter-plot with 3 errorbars.
Perfect would be if the resulting image would be a 3d-plot with 3d geometric shapes (coordinate x,y,z with expansion in the dimension proportional to the errorbars) as 'marker'.
I found this page while searching the internet: http://code.izzid.com/2007/08/19/How-to-make-a-3D-plot-with-errorbars-in-matlab.html
But unfortunately they use only one errorbar.

My data is set of 6 arrays each containing either the x,y or z coordinate or the specific standard derivation i want to show as errorbar.

A: The code you posted looks very easy to adapt to draw all three error bars. Try this (note that I adapted it also so that you can change the shape and colour etc of the plots as you normally would by using varargin, e.g. you can call plot3d_errorbars(...., '.r'):
function [h]=plot3d_errorbars(x, y, z, ex, ey, ez, varargin)

% create the standard 3d scatterplot
hold off;
h=plot3(x, y, z, varargin{:});

% looks better with large points
set(h, 'MarkerSize', 25);
hold on

% now draw the vertical errorbar for each point
for i=1:length(x)
        xV = [x(i); x(i)];
        yV = [y(i); y(i)];
        zV = [z(i); z(i)];

        xMin = x(i) + ex(i);
        xMax = x(i) - ex(i);
        yMin = y(i) + ey(i);
        yMax = y(i) - ey(i);
        zMin = z(i) + ez(i);
        zMax = z(i) - ez(i);

        xB = [xMin, xMax];
        yB = [yMin, yMax];
        zB = [zMin, zMax];

        % draw error bars
        h=plot3(xV, yV, zB, '-k');
        set(h, 'LineWidth', 2);
        h=plot3(xB, yV, zV, '-k');
        set(h, 'LineWidth', 2);
        h=plot3(xV, yB, zV, '-k');
        set(h, 'LineWidth', 2);
end

Example of use:
x = [1, 2];
y = [1, 2];
z = [1, 2];
ex = [0.1, 0.1];
ey = [0.1, 0.5];
ez = [0.1, 0.3];

plot3d_errorbars(x, y, z, ex, ey, ez, 'or')