text:
Q: How to pass statement ' i ' in {this.props.example[i]} When i have an actual value to declare my prop's array position it works fine. But using a loop method doesn't work because it isn't seeing the statement correctly.
render: function() {
for(var i = 0; i > 3; i++) {
  var test = {this.props.example[i]}
}

Results in nothing being displayed. Is there an alternative method for this to work?

A: you can write jsx in render method :
render : function()
{
 return

{
    for(var i = 0; i > 3; i++) {
      var test = this.props.example[i]
      console.log(test);
    }
}

}

I am assuming that example is array of integer.

A: Map use of map and return an element from the render function. you can do this as
render() {
    return (

{this.props.example.map(function(item, key){
             return
{item}

           })}

    )
  }

class App extends React.Component {
  constructor(){
    super();
    this.state = {
      example : ["Hello", "Stack", "Overflow"]
    }
  }
  render() {
    return (

{this.state.example.map(function(item, key){
             return
{item}

           })}

    )
  }
}
ReactDOM.render(<App/>, document.getElementById('app'));


text:
Q: Microcontroller for embedded programming I live in a country where popular microcontrollers aren't easily available. The only ones i could find that were arm based were STM32F4 Discovery and STM32VL Discovery. The latter one is cheaper so that is preferable.
So the question is, am i looking in the right direction ? Are these microcontrollers specifically for embedded programming ? (I am a beginner) It would be really helpful if someone could set me in the right direction.
Thanks!

A: It is quite difficult to give you a precise reply to this question as the choice between one microcontroller or another only depends on the application you want to address (and you don't give more information on your objectives in the question).
If it is only for an educational purpose, the STM32 discovery boards are IMO a very good choice because they are cheap and you don't need any other piece of hardware (like a JTAG programmer) to start playing with it (you only need an external power source).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Term for someone who acquires an image What is the best word to describe someone (a person) who acquires a digital image with any instrument (which could be a digital camera, microscope, telescope or any other instrument that will produce an image)?
I was thinking of the terms "imager", but a simple Google search gives me the definition "software or equipment that makes images". "Photographer" is, I consider, too narrow.
If such a term does not exist what is the smallest way to describe this concept? "image creator"?

A: The author of an image is called its author.
That includes digital images acquired with a digital camera, microscope, telescope or any other instrument that will produce an image. Go to Wikimedia Commons, navigate to a digital image of your choosing produced with an instrument of your liking, and see for yourself.

A: I think the best word for this is photographer. You can find examples of people referring to astrophotography or electron microscope photography:

Scharf started tinkering with electron microscopes after hours in a lab where he worked as an electronics engineer in the 1970s. Back then, most electron microscope photographers took out-of-focus photos of dead and dusty specimens. — Inside the Lab of an Electron Microscope Photographer

The problem is that most photography is the standard camera sort, with visible light used to image regular objects, and we lack a commonly-used word to delimit this particular subset. But there are no clear boundaries between zoom lenses and telescopes, or macro lenses and microscopes, so all the images are presumably taken by photographers.

A: Probably  image/imaging technician is close to what you are looking for.
The term is often used in medical context but it may also refer to a wider context:

*

*Imaging technicians are more specifically known by the type of equipment they operate, and include X-ray technicians, magnetic resonance imaging techs, diagnostic medical sonographers and radiologic techs. Although these machines use different methods, they all help physicians assess medical conditions by displaying images of the interior of the human body.

Also , Digital image technician

*

*Prior to the DIT position, several other positions, such as Video Controller, Video Shader or Video Engineer, performed similar functions of exposure and color control over the live video image. While these positions continue to exist, especially in live broadcast and studio television, the DIT position has become entrenched in Cinema, Commercials and Higher End television.

Source:http://en.m.wikipedia.org/wiki/Digital_imaging_technician

A: The only thing that comes to mind seems to be a graphic designer.
The definition of graphic design on thefreedictionary.com

*

*graphic design-The practice or profession of designing print or electronic forms of visual information, as for an advertisement, publication, or website.


text:
Q: Play 2.7 background tasks and async services I'm wondering what is the correct way to work with async services (returns Future[OfResult]) inside Play background akka tasks. There is no information about it in play docs, It seems I can't just return Future[TaskResult] at the end and get things done in a reactive way, so I'm using Await.result for each async service call. And even if I use my own custom execution context, sometimes I get weird exceptions from slick db layer and task stops working, this is not resilient at all (I would expect at least next schedule to work) so I think I'm doing it wrong.
The task is simple, I have an events table in database with some fields and date range, each day I'm checking if current date is inside date range, I remove passed events and activate new events. It requires me to:

*

*Get all events - which is list of Future[Event]

*Get through the list and modify or delete events

I'm doing it in procedural style with blocking Await.result
With small events count it fails very rare but with like thousands - it fails pretty soon (I assume because of limited database pool?)
It doesn't look like just wrong database configuration because in regular async controller action everything works fine with huge amount of data so I suppose I'm doing it wrong

A: You should never use Await.result in application logic as it will block the calling thread and potentially starve your threadpool. See more in the Akka docs here: https://doc.akka.io/docs/akka/current/typed/dispatchers.html#blocking-needs-careful-management . This could be why you are seeing it failing.
If a future depends on another you should chain them using map or flatMap. For turning a List[Future[T]] into a Future[List[T]] you can use Future.sequence.
If what you mean with "background akka tasks" is using the scheduler of the ActorSystem like in this article there is no need for the operation to block the Runnable passed to the scheduler for the duration, just let it trigger your future tasks and then return.
It is important to understand that the future operations will execute on one or more other threads, so if you want to observe that it progresses and completes or fails you will have to add that with callbacks on the futures (for example onComplete on the final future).


text:
Q: Trying to insert a stored procedure into a temporary table, getting 'an object or column name is missing or empty'
Possible Duplicate:
How to SELECT * INTO [temp table] FROM [Stored Procedure]

I am new to T-SQL. I have a stored procedure that selects records. I want to query the records returned by the stored procedure, so I am trying to insert the records into a temporary table. (Stack Overflow posts and other posts say that is how to do it.)
But when I try, I get the error:

object or column name is missing or empty'

When I just run the stored procedure, I get a table that has columns with names.
select * into #temp1
exec alexander.dbo.get_uberrecords '20120101', '20120201', 'labcorp' //throws error saying columns must have names

but
exec alexander.dbo.get_uberrecords '20120101', '20120201', 'labcorp' // Returns cols with names

What am I missing?

A: Try creating the temp table first:
CREATE TABLE #temp1
(
   COL1 INT,
   COL2 VARCHAR(MAX)
)

INSERT INTO #temp1
exec alexander.dbo.get_uberrecords '20120101', '20120201', 'labcorp'

In your case of an extremely wide result set, you may want to use OPENROWSET
In any case, this SO has many options:
Insert results of a stored procedure into a temporary table


text:
Q: Movie with a spirit that looks like a bag trying to kill a group of people when they go outside This is the info my friend gave me, it's probably old, the spirit has a bag on his head and chokes people, or is visually like a bag
The spirit did kill some of the group and it came from the sky? My friend didn't finish it so this is all the info he has.


text:
Q: Mux gets damaged the moment power is on. How do I know that cause of this? I am currently using a mux, ADG1419, and i have had frequent mux failure the moment I turn on power; the power and the GND of the mux shorts after the mux gets damaged. My only assumption is that the failure of mux is due to voltage transient; therefore, I will add a tvs diode. I cannot think of anything beside the voltage transient. Can you think of one?

A: Some analog multiplexers are prone to latch-up and self-destruction if the voltages at the analog inputs exceed the supply voltage and sufficient current is available from the analog input to cause damage.
This can happen if for example the multiplexer was being used to select power supply voltages, or any other signal with high drive capability, into an A/D converter for measurement.
If, at power-on, the signal being measured was to rise above the supply rails for the multiplexer, current can flow through the protection diodes internal to the multiplexer. If enough current flows it can trigger parasitic SCR devices to cause high currents to flow with the possibility for self-destruction.
One way to minimize the chances of this occurring is to provide enough resistance in series with the analog sources to limit the current under these conditions.
Alternatively there are a few devices that are designed to avoid the problem.
The linked article suggests a couple of other solutions, such as diodes in the supply rail.
Winning the battle Against Latchup


text:
Q: IP camera: open source software for recording H.264 I have an IP camera (Axis M1054) and I would like to record video stream. I would probably start with continuous recording, but then I would like to switch to clips triggered by motion detection (with pre-rec of couple seconds before the trigger occured), recording being encoded in MPEG4 (H.264), not in MJPEG.
Is there a free open source Linux software that can do it? I did not find anything by searching the Internet. Can you recommend something that works and you successfully use? Or am I stuck with commercial software?
I have no problem replacing the camera if different model would work better with Linux.

A: What about giving a try to open source openh264 backed by Cisco? It supports Long Term Reference (LTR) frames which might help you with motion detection.

A: I've found Motion to be a great program for motion detection and cataloging.
It seems to work with remote cameras, although the docs are a bit sketchy. It's probably worth a try.

A: I use the linux Motion software combined with the command line version of VLC for my IP cameras.  (2 are MJPG streams, one is RTSP with H264).  The motion software triggers a script to have VLC record lossless in the cameras native format.  My setup does not however support pre-recording.  It actually results in missing the frame that initially triggered the motion which is fine for my use since the first frames of motion are not where I'd see the faces or license plates.

A: Your camera streams H.264 over RTP controlled by RTSP. You need a RTP client to connect to the camera in order to get to the streams.
http://www.live555.com provides a RTSP client library with a variety of sample code.
First I would try http://www.live555.com/openRTSP/ from the command line.
I have successfully used live555 to record a variety of IP cameras.
You could also use the FFMPEG library:
Receiving RTSP stream using FFMPEG library
FFMPEG also takes care of muxing (creating a container file) or decoding.


text:
Q: Name list of data frames from data frame I usually read a bunch of .csv files into a list of data frames and name it manually doing.
#...code for creating the list named "datos" with files from library
# Naming the columns of the data frames
names(datos$v1r1)<-c("estado","tiempo","x1","x2","y1","y2")
names(datos$v1r2)<-c(...)
names(datos$v1r3)<-c(...)

I want to do this renaming operation automatically. To do so, I created a data frame with the names I want for each of the data frames in my datos list.
Here is how I generate this data frame:
pru<-rbind(c("UT","TR","UT+","TR+"),
            c("UT","TR","UT+","TR+"),
            c("TR","UT","TR+","UT+"),
            c("TR","UT","TR+","UT+"))

vec<-paste("v1r",seq(1,20,1),sep="")
tor<-paste("v1s",seq(1,20,1),sep="")

nombres<-do.call("rbind", replicate(10, pru, simplify = FALSE))

nombres_df<-data.frame(corrida=c(vec,tor),nombres)

Because nombres_df$corrida[1] is v1r1, I have to name the datos$v1r1 columns ("estado","tiempo", nombres_df[1,2:5]), and so on for the other 40 elements.
I want to do this renaming automatically. I was thinking I could use something that uses regular expressions.
Just for the record, I don't know why but the order of the list of data frames is not the same as the 1:20 sequence (by this I mean 10 comes before 2,3,4...)
Here's a toy example of a list with a similar structure but fewer and shorter data frames.
toy<-list(a=replicate(6,1:5),b=replicate(6,10:14))

A: You have a data frame where variable corridas is the name of the data frame to be renamed and the remaining columns are the desired variable names for that data frame. You could use a loop to do all the renaming operations:
for (i in seq_len(nrow(nombres_df))) {
  names(datos[[nombres_df$corridas[i]]]) <- c("estado","tiempo",nombres_df[i,2:length(nombres_df)])
}


text:
Q: How do I use JDK6 ToolProvider and JavaCompiler with the context classloader? My usage case is compiling generated source files from a java program using the ToolProvider and JavaCompiler classes provided in JDK 6.  The source files contain references to classes in the context classloader (it runs in a J2EE container), but not in the system classloader. My understanding is that by default the ToolProvider will create the JavaCompiler instance with the system classloader.
Is there a way to specify a classloader for JavaCompiler to use?
I tried this approach, modified from something on IBM DeveloperWorks:
FileManagerImpl fm =
    new FileManagerImpl(compiler.getStandardFileManager(null, null, null););

with FileManagerImpl defined as:
static final class FileManagerImpl
    extends ForwardingJavaFileManager<JavaFileManager> {

   public FileManagerImpl(JavaFileManager fileManager) {
      super(fileManager);
   }

   @Override
   public ClassLoader getClassLoader(JavaFileManager.Location location) {
      new Exception().printStackTrace();
      return Thread.currentThread().getContextClassLoader();
   }

}

The stacktrace indicates it's only called once during annotation processing.  I verified the class referenced in the source file to be compiled is not on the system classpath but is available from the context classloader.

A: If you know the classpath to the files that are known to the contextclassloader you can pass them to the compiler:
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(this /* diagnosticlistener */, null, null);
// get compilationunits from somewhere, for instance via fileManager.getJavaFileObjectsFromFiles(List<file> files)
List<String> options = new ArrayList<String>();
options.add("-classpath");
StringBuilder sb = new StringBuilder();
URLClassLoader urlClassLoader = (URLClassLoader) Thread.currentThread().getContextClassLoader();
for (URL url : urlClassLoader.getURLs())
    sb.append(url.getFile()).append(File.pathSeparator);
options.add(sb.toString());
CompilationTask task = compiler.getTask(null, fileManager, this /* diagnosticlistener */, options, null, compilationUnits);
task.call();

This example assumes you're using a URLClassloader (which allows you to retrieve the classpath) but you could insert your own classpath if you wanted to.

A: Another option is to use Commons JCI.

A: You're asking two separate questions here.
One is how to compile classes not found in the system classpath. This is easily solved by passing the "-classpath" command-line argument to the compiler (as first mentioned by Leihca).
The second is how to instantiate ToolProvider and JavaCompiler on the thread context classloader. At the time of this writing, this is an unsolved question: Using javax.tools.ToolProvider from a custom classloader?


text:
Q: script to copy, delete and symlink I want to copy a file to another disk, when completed delete it, and create a symlink back to it in the original location.
example:
copyandlink.sh somefile.iso
#!/bin/bash
set -e
cp $1 /media/storage/linked/ &&
rm $1 &&
ln -s /media/storage/linked/$1 ./

or something like that.

A: You're on the right track since your script does exactly what you want.
It can be simplified and improved a little like:
#!/bin/bash
mv $1 /media/storage/linked/ &&
ln -s /media/storage/linked/$1 .

The set -e has no impact since your commands are already conditional with the &&.
I also replaced the cp and rm for mv which handles both automatically, whether on the same partition or not.


text:
Q: Nginx rewriting not enabled in server I have to change the configuration of the nginx so that, index.php in the public_html folder handles all the requests other than files and folders.
I know how to do this in htaccess
like this
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^?]*)$ /index.php?path=$1 [NC,L,QSA]

And when I searched, I found this code in nginx config file would do the same.
location / {
try_files $uri $uri/ /index.php?$args;
}

And I did set this up in the configuration file.
However, the home page works just fine, but, the other routes such as www.example.com/login does not work.
But, example.com/index.php/login shows the content of www.example.com/login
What could be wrong in this case ?
I am very new to nginx and only have very little knowledge in it.
Could anyone help ?

A: You can rewrite it like this:
if (!-e $request_filename) {
    rewrite ^(.*)$ /index.php?path=$1 last;
    break;
}


text:
Q: Previewing blog post in jekyll site I have the index.html page so far using jekyll, here is the quote:
---
layout: layout
title: "Posts"
---

    {% for post in site.posts %}

{{ post.title }}

    {% endfor %}

What I'm trying to do is preview the first 25-30 words of the particular post under the title and link.
What is the best way to go about it? I actually found the solution but I didn't save the link and have now spent 2 days searching to no avail.
Thank you for your help.

A: If you're specific about just showing a certain amount of words then you'll need to use Javascript to split content using spaces and count the words (something like this).
Most likely though, you'd like to show a small section of the post like a preview. If that's the case I'd suggest inserting your post body into a
 with the following CSS:
.listing p{
    overflow: hidden;
    text-overflow: ellipsis;
    -o-text-overflow: ellipsis;
    white-space: nowrap;
    width: 60%; /* or whatever you'd like */
}

DEMO
This will neatly preview the text with an ellipsis at the end of the width.

A: The most recent version of jekyll, 1.0.x, offers a post.excerpt variable for all posts, which consists of he first paragraph of the post. It can quite safely be used to preview the post.
See https://gist.github.com/benbalter/5555369 for details.


text:
Q: Using the onchange event to get value of select color list in order to change a picture I'm using a select list to change the color of a preview image of a picture of a shirt. So I have a global variable named chosenColor and I want to use that to change the picture when I select a color from the select list. It only works to change the color to blue but it won't work to change the color back to red.
This is the relevant javascript
var chosenColor="Red";

function chooseBlue() {
     document.getElementById("largerview").src = "bluezigzag.jpg";
     chosenColor = "Blue";
     }

function chooseRed() {
     document.getElementById("largerview").src = "redzigzag.jpg";
     chosenColor = "Red";
     }

function getSelectionChange() {      //selects the color that the user selects in the selection list
     if (this.value = "red") {
         chooseBlue();
         window.alert(chosenColor);
     }
     else if (this.value = "blue") {
         chooseRed();
         window.alert(chosenColor);
     }
}

And this is the selection list
<select size="1" name="color" onchange="getSelectionChange();">
     <option value="red">Red</option>
     <option value="blue">Blue</option>
</select>

A: You are using the assignment operator = instead of the comparison operator === or ==:
if (this.value = "red") {

...

else if (this.value = "blue") {

should be
if (this.value === "red") {

...

else if (this.value === "blue") {

When you use this.value = "red" it sets the value to "red" and then the expression returns "red" - which is truthy, so execution goes into that if block.
Have you considered replacing the separate choose colour functions with something like this:
function getSelectionChange() {
     document.getElementById("largerview").src = this.value + "zigzag.jpg";
     window.alert(this.value);
}

Obviously you could still set a global chosenColor variable, but I'm not sure what you'd need it for.
EDIT: Also if you are using an inline onchange= handler to call a function, this will be the element in question within the onchange attribute's code, but not in the function called from there - unless you explicitly set it:
onchange="getSelectionChange.call(this);"


text:
Q: SQL Management Console can't find SQL Server Express 2008 R2 on MacBook Pro Bootcamp After some problems with "landingpage.exe" errors and a bunch of reinstalls - I had a successful install of SQL Server 2008 R2 on my Macbook Pro 13" Bootcamp partition. SQL Server is showing as an active service in control panel, etc. When I opened the Management Console it could not find the SQL Server, it just shows no local server. Fiddling around with other SQL Server tools I would get "named pipes" errors, which may or may not relate to the lost Server. Has anyone successfully used R2 with Bootcamp and if so what am I doing wrong? Thanks

A: I'm going to answer my own question in case someone else has this frustrating problem. It was purely a MS issue. On a laptop with local database two problems occurred - first was an error "cannot find landingpage.exe..." - Delete the Microsoft_Corporation folder from location C:\Documents and Settings[USR]\Local Settings\Application Data and that will fix the first installation error.
Next I got an error 40 where the running SQL service could not be found. I finally manually replaced (local) in SQL Management Studio with [machine_name]\SQLEXPRESS and that worked. What fooled me is that the SQLEXPRESS name did not appear after a browse for instances - always before all available SQLSERVER instances had been listed. Anyway, typing in the name worked for me.


text:
Q: How to check the type of a template parameter for a polymorphic subclass I have a class hierarchy in which I<T> and O<T> are a templated classes that extend B (regular class). I aggregates O by means of a pointer, like so:
class B { ... };
template <class T>
class O : public B
{
    T getValue() { return value; }
private:
    T value;
}
template <class T>
class I : public B
{
    T getValue() { return ptr->getValue(); }
    void setPtr(O<T>* po) { ptr = po; }
private:
    O<T>* ptr;
}

The code above is indeed simplified to show only its bare bones. "Connecting" I and O is done automatically although through user configuration parameters. Because of that, a Singleton table stores polymorphic B pointers to all I and O objects and performs the linking by calling I::setPtr as necessary.
The problem though is that the user can actually mess up and confuse template types of I and O objects, e.g. user can ask to connect an I<int> with an O<float>. E.g.:
O<int>* oi = new O<int>();
O<float>* of = new O<float>();
I<int> ii;
ii.setPtr(oi);  /* This is OK. */
O<int>* oi_wrong = static_cast<O<int>*>((B*)of);  /* This happens. */
ii.setPtr(oi_wrong); /* This is bad. */

In order to prevent this sort of behaviour, I included a member variable in both I and O that stores typeid(T).name(), thus allowing to check whether the template parameter is actually the same.
Is there a better way?
EDIT: Would there be a better way to do the casting here? Is it not a good idea to store and work with polymorphic pointers in this case?

A: There's really nothing much you can do if your user is going out of the way to misuse your interface - you should (reasonably) design your code without assuming that your user is going to use static_cast and reinterpret_cast liberally.
In your case, I wouldn't add any additional code/checks. Just assume that your user acts in a reasonable manner.

If you really want, you could use assert and dynamic_cast to check if the passed pointer is actually what you expected in DEBUG builds:
struct A { virtual ~A() { } };
struct B : A { };
struct C : A { };

void setPtr(A* po)
{
    assert(dynamic_cast<C*>(po) != nullptr);
}

int main()
{
    B b;
    setPtr((C*)&b); // might trigger assertion
}

But I strongly suggest against it, as this is overkill.

A: How about using a friend function for setPtr(), so the user is forced to input fitting types for I and O:
    class B { };
    template <typename T>
    class O : public B
    {
    public:
      T getValue() { return value; }
      void setPtr(I<T>& ref_i) { ref_i.ptr = this; };
    private:
      T value;
    };

    template <typename T>
    class I : public B
    {
    public:
      T getValue() { return ptr->getValue(); }
      friend void O::setPtr(I<T>& ref_i)
    private:
      O<T>* ptr;
    };

    int main()
    {
      O<int>* oi = new O<int>();
      O<float>* of = new O<float>();
      I<int> ii;
      of->setPtr(ii);  /* This fails. */
      O<int>* oi_wrong = static_cast<O<int>*>((B*)of);  /* This CAN                 happen. */
      oi->setPtr(ii); /* This is OK. */
    }


text:
Q: Using asymmetric encryption for license file I want to send to a client an encrypted file that contains the license data for my application. As I will use asymmetric encryption, I will encrypt the file using a private key and send it to the client. The application on the client's pc will decrypt the sent file using a public key located in the application code.
The threat model I aspect here is that the public key could be extracted from the application .dll files (using .net reflector for example) and used to regenerate the license.
So is there a way to protect my application ?
Update:
I went through the code example in the following link for encryption the xml file.
The problem I am facing now is that both keys will be generated in the client pc same as mine according to the code sample. So is this right or there is a misunderstanding from me?
Also as Alexe Barlescu suggested to use the ProtectedData class to protect the private key, how can I achieve that ?

A: Asymmetric Encryption uses two keys:

*

*a public key for encrypting the data

*a private key for the decryption of the data

Encrypt the file containing the license with client's Public Key, so only he can decrypt it, with his Private Key.
To make your client's Private key safe, encrypt it with Protect method located in ProtectedData class in System.Security.Cryptography namespace. The Private key will be stored on his computer encrypted, he can decrypt the key only when he needs to decrypt a message sent from you.


text:
Q: Different Project Type in a Single Website I have developed a website in asp.net and I have some additional tasks, improvements to develop. In order to get experience in asp.net/mvc, I want to create an admin panel using asp.net mvc.
Is this a logical next step?

P.S. The project is small and 20% of the website is mine, so there are not any restrictions. There is no problem if I do not meet deadlines! :)

A: It is fairly common to transition from one web framework over to another, doing new development in the once and future framework and migrating the older projects as there is time (frequently, there is never time).
It would generally be a little more frowned upon to maintain two web applications written in the same language running different frameworks as a planned way of life--in most corporate settings, homogeneity in framework choice is encouraged.
That said, for smaller projects or personal projects, I would not really worry about it.

A: The discussion between those two similiar technologies are very long, and no one is better than other, only is for two different things.
On the ASP.NET WebForms (classic ASP.NET) you have a lot of controls, an extense collection of controls which you can pick, drag and drop and configure, its really fast but you have a lot of impediments when you want to manage at lower level the html of the page, and the code are very disordered.
On ASP.NET MVC you a lot of control on your html and you can do almost anything, i mean anything with styles and html but mostly you need to do by hand. But one of the great advantages of MVC is de order of the code, you always have ordered solution, projects, and clases, its a really great pattern.
Finally do not care to have different projects with different technologies, its a common case, most than you think, and if you think that MVC is better for the new project go ahead, its a really good choice.
I'll hope this help you. I'm a teacher of web development on the course 10264


text:
Q: How to resize the width of a div to fit word wrap? Is it possible to resize a div element when word wrap occurs? For demonstration purposes, look at this example from a similar question:

.mypost {
  border: 1px solid Peru;
  margin: auto;
  min-width: 200px;
  display: inline-block;
  background: red;
}

.test {
  margin: 10px;
  background: cyan;
}

I represent the imagdfv fdvdsdfsdfve.

If you make the window smaller so that word wrap occurs, you will see that there is a blue empty space to the right of the text. Instead, I want the blue area to decrease until it reaches the last letter of the first line.

(In this image I am forcing word wrap. I want the blue area to shrink.)
Is this possible?

A: By default div elements are block-level elements meaning they occupy 100% of the width of its parent element. As the other answer shows you can use javascript to set the width of the div according to the content.
However, if you are only concerned with constraining the background color to be within the boundaries of inline content (i.e. text and images), you could just make the element inline with the display: inline declaration. You would have to remove the margin and instead add padding to the parent element.
Here is an example I created from modifying your code. I added display: inline to .test, removed margin: 10 from .test, and added padding: 10 to .mypost. I also had to play around with line-height and font-size to make sure there is no gap between the lines.

.mypost {
    border: 1px solid Peru;
    margin: auto;
    min-width: 200px;
    width:300px;
    display: inline-block;

    background: red;
    font-size:18px;
    line-height:20px;

    padding:10px;

}
.test {
    background: cyan;
    display:inline;
}

        EDIT ME..... Lorem ipsum dolor sit amet, consectetur adipiscing elit.

The snippet is an interactive demo. You can directly edit the content of the div to see how word wrap behaves.
I have also found this duplicate question but it didn't have any satisfactory answers: How to remove extra space caused by word-wrap in shrunk to fit element?

A: tl;dr: No.
Once word wrapping occurs, the block-level element containing the text is considered to be as wide as possible to fill its container regardless of where the text breaks.
One can use javascript to find a minimum-width box of the starting height but this is inefficient due to repeated redraws and it's less friendly to CSS:

target = document.getElementsByClassName('test')[0];
height = target.clientHeight;
minWidth = 1;
maxWidth = target.clientWidth;
while(maxWidth - minWidth > 1) {
  var newWidth = (minWidth + maxWidth) / 2;
  target.style.width = newWidth + "px";
  if(target.clientHeight > height) {
    minWidth = newWidth;
  }
  else {
    maxWidth = newWidth;
  }
}
target.style.width = maxWidth + "px";
.mypost {
    border: 1px solid Peru;
    margin: auto;
    width: 300px;
    display: inline-block;
    background: red;
}
.test {
    margin: 10px;
    background: cyan;
}

I represent the imagdfv fdvdsdfsdfve.

A: For me, I would make the inner div display: inline-block;
So:

    .mypost {
        border: 1px solid Peru;
        margin: auto;
        min-width: 200px;
        display: inline-block;
        background: red;
    }
    .test {
        display: inline-block;
        margin: 10px;
        background: cyan;
    }

I represent the imagdfv
fdvdsdfsdfve.


text:
Q: как изменить имя root Чтобы вместо root@ubuntu было чтоугодно@ubuntu

A: Да, наверное это возможно. НО ЭТО СКОРЕЕ ВСЕГО, ЭТО НАРУШИТ РАБОТУ ВАШЕЙ СИСТЕМЫ. Многие программы могут использовать имя root для проверок и сравнений, к примеру: [[ $USERNAME = "root" ]].
Если посмотрим
$ getent passwd root
# то увидим примерно следующее
root:x:0:0:root:/root:/usr/bin/zsh

Можно отредактировать файл /etc/passwd, заменив имя пользователя с идентификатором 0.

*

*man passwd

*man shadow

Лучше всего, не использовать root вообще и запретить авторизацию через ssh для этой учетной записи. Для выполнения команд  от имени root используйте sudo.


text:
Q: Reduce the number of authors in references I would like more than 3 author citations to show up using et al. rather than with full names.
Example:
* were death cases because of the autopsy Rao, Sood, Pathak,
and Dongre (2014).*
I need to show >3 author names like (Rao et al., (2014))
Code
\documentclass{UnimasThesis}
\usepackage{graphicx}
\usepackage[labelfont=bf]{caption}
\captionsetup{labelfont=bf}
\usepackage{pdflscape}
\usepackage{adjustbox}
\usepackage{dcolumn}
\usepackage{booktabs}
\usepackage{amsmath}
\usepackage{cases}
\usepackage[os=win]{menukeys}
\usepackage[paper=a4paper]{geometry}
\usepackage{multirow}
%\usepackage{enumerate}

\usepackage{listings}
\lstset{language=[LaTeX]TeX,columns=fullflexible,
basicstyle=\ttfamily,texcsstyle=*\bfseries\color{NavyBlue},
commentstyle=\itshape\color{PaleVioletRed4},
frame=single,framesep=6pt,
framexleftmargin=6pt,framexrightmargin=6pt,
xleftmargin=12pt,xrightmargin=12pt,
breaklines=true,breakatwhitespace=true}

\title{AUTOMATIC SEGMENTATION OF CARDIAC MAGNETIC RESONANCE IMAGES FOR OEDEMA ASSESSMENT}
\author{Amajd Khan}
\faculty{Faculty of Computer Science and Information Technology }
\facultyColour{6c7a8c} %% 6-digit RGB hexadecimal code
\submissionyear{2017}
\degreetype{Doctor of Philosophy\\(Computer Science)}

% If using APA bibliography style

\usepackage[natbibapa]{apacite}
\bibliographystyle{plainnat}
%\usepackage{natbib}
%\bibliographystyle{apalike}

\makeatother

\begin{document}
\maketitle

\frontmatter

\mainmatter
% Each chapter from a separate file
\input{chap1-Introduction}

% references are listed in refs.bib
\bibliography{refs}

\end{document}

.bib file
    @article{rao:2014,
    title={Causes of Sudden Cardiac Death on Autopsy Findings; a Four-Year Report},
    author={Rao, Dinesh., and Sood, Divya., and Pathak, P., and Dongre, Sudhir, D},
    journal={Journal  of Emergency-An Academic Emergency Medicine},
    volume={2},
    number={1},
    pages={12-17},
    year={2014}
}


text:
Q: Finding line-wraps Supposing I have some random block of text in a single line. Like so
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
But for whatever reason (width settings on the containing element, use of text-zoom etc.), on the viewer's screen it displays as two or more lines.
Lorem ipsum dolor sit amet,
consectetur adipiscing elit.
or
Lorem ipsum dolor sit
amet, consectetur
adipiscing elit.
Is there any way to find out via javascript where those line-wraps happen?
$('p').text() and $('p').html() return Lorem ipsum dolor sit amet, consectetur adipiscing elit. regardless of how the text is displayed.

A: The solutions above don't work once you have more complex structure like a link in a paragraph (e.g. you can have  within a
).
So I made a javascript library to detect where lines wrap that works in those cases: http://github.com/xdamman/js-line-wrap-detector
I hope this helps.

A: Well, if you want something that's ridiculously simple and probably too useless for you (it'll need major modification if you have any sort of HTML inside the paragraph), then have a look at this:
var para = $('p');

para.each(function(){
    var current = $(this);
    var text = current.text();
    var words = text.split(' ');

    current.text(words[0]);
    var height = current.height();

    for(var i = 1; i < words.length; i++){
        current.text(current.text() + ' ' + words[i]);

        if(current.height() > height){
            height = current.height();
            // (i-1) is the index of the word before the text wraps
            console.log(words[i-1]);
        }
    }
});

It's so ridiculously simple it might just work. What this does is to break up the text by spaces, then append the words back word by word, watching for any increase in the height of the element, which would indicate a line wrap.
Have a look at it here: http://www.jsfiddle.net/xRPYN/2/

A: For a use case like pdf generation.
You can limit to characters per line, if a split occurs middle word, adjust appropriately.
To gain a more accurate characters per line you can use monospaced fonts then determine the width per character for each font allowed. Then divide the character width by the size of the allowed text line width, and you'll have the allowed characters per line for that font.
You could use non monospaced fonts, but then you'll have to measure each letter's width - ugh. A way you can automate the width guessing is having a span that has no margin or padding, add in each character for each font (and size) then measure the width of the span and use that.
I've done up the code:
/**
 * jQuery getFontSizeCharObject
 * @version 1.0.0
 * @date September 18, 2010
 * @since 1.0.0, September 18, 2010
 * @package jquery-sparkle {@link http://www.balupton/projects/jquery-sparkle}
 * @author Benjamin "balupton" Lupton {@link http://www.balupton.com}
 * @copyright (c) 2010 Benjamin Arthur Lupton {@link http://www.balupton.com}
 * @license Attribution-ShareAlike 2.5 Generic {@link http://creativecommons.org/licenses/by-sa/2.5/
 */
$.getFontSizeCharObject = function(fonts,sizes,chars){
    var fonts = fonts||['Arial','Times'],
        sizes = sizes||['12px','14px'],
        chars = chars||['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','y','x','z',
                        'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','Y','X','Z',
                        '0','1','2','3','4','5','6','7','8','9','-','=',
                        '!','@','#','$','%','^','&','*','(',')','_','+',
                        '[',']','{','}','\\','|',
                        ';',"'",':','"',
                        ',','.','/','<','>','?',' '],
        font_size_char = {},
        $body = $('body'),
        $span = $('').appendTo($body);

    $.each(fonts, function(i,font){
        $span.css('font-family', font);
        font_size_char[font] = font_size_char[font]||{};
        $.each(sizes, function(i,size){
            $span.css('font-size',size);
            font_size_char[font][size] = font_size_char[font][size]||{};
            $.each(chars,function(i,char){
                if ( char === ' ' ) {
                    $span.html(' ');
                }
                else {
                    $span.text(char);
                }
                var width = $span.width()||0;
                font_size_char[font][size][char] = width;
            });
        });
    });

    $span.remove();

    return font_size_char;
};

/**
 * jQuery adjustedText Element Function
 * @version 1.0.0
 * @date September 18, 2010
 * @since 1.0.0, September 18, 2010
 * @package jquery-sparkle {@link http://www.balupton/projects/jquery-sparkle}
 * @author Benjamin "balupton" Lupton {@link http://www.balupton.com}
 * @copyright (c) 2010 Benjamin Arthur Lupton {@link http://www.balupton.com}
 * @license Attribution-ShareAlike 2.5 Generic {@link http://creativecommons.org/licenses/by-sa/2.5/
 */
$.fn.adjustedText = function(text,maxLineWidth){
    var $this = $(this),
        font_size_char = $.getFontSizeCharObject(),
        char_width = font_size_char['Times']['14px'],
        maxLineWidth = parseInt(maxLineWidth,10),
        newlinesAt = [],
        lineWidth = 0,
        lastSpace = null;

    text = text.replace(/\s+/g, ' ');

    $.each(text,function(i,char){
        var width = char_width[char]||0;
        lineWidth += width;
        if ( /^[\-\s]$/.test(char) ) {
            lastSpace = i;
        }
        //console.log(i,char,lineWidth,width);
        if ( lineWidth >= maxLineWidth ) {
            newlinesAt.push(lastSpace||i);
            lineWidth = width;
            lastSpace = null;
        }
    });

    $.each(newlinesAt,function(i,at){
        text = text.substring(0,at+i)+"\n"+text.substring(at+i);
    });

    text = text.replace(/\ ?\n\ ?/g, "\n");

    console.log(text,newlinesAt);

    $this.text(text);

    return $this;
};

$(function(){
    var $body = $('body'),
        $textarea = $('#mytext'),
        $btn = $('#mybtn'),
        $div = $('#mydiv');

    if ( $textarea.length === 0 && $div.length === 0 ) {
        $body.empty();

        $textarea = $('<textarea id="mytext"/>').val('(When spoken repeatedly, often three times in succession: blah blah blah!) Imitative of idle, meaningless talk; used sometimes in a slightly derogatory manner to mock or downplay another\'s words, or to show disinterest in a diatribe, rant, instructions, unsolicited advice, parenting, etc. Also used when recalling and retelling another\'s words, as a substitute for the portions of the speech deemed irrelevant.').appendTo($body);
        $div = $('
').appendTo($body);
        $btn = $('<button id="mybtn">Update Div</button>').click(function(){
            $div.adjustedText($textarea.val(),'300px');
        }).appendTo($body);

        $div.add($textarea).css({
            'width':'300px',
            'font-family': 'Times',
            'font-size': '14px'
        });
        $div.css({
            'width':'auto',
            'white-space':'pre',
            'text-align':'left'
        });
    }

});

A: Here's what I ended up using (feel free to critique and copy for your own nefarious purposes).
First off, when the edit comes in from the user, it's broken up with $(editableElement).lineText(userInput).
jQuery.fn.lineText = function (userInput) {
   var a = userInput.replace(/\n/g, " \n
 ").split(" ");
   $.each(a, function(i, val) {
      if(!val.match(/\n/) && val!="") a[i] = '' + val + '';
   });
   $(this).html(a.join(" "));
};

The newline replacement happens because the editing textbox is populated with $(editableElement).text(), which ignores
 tags, but they will still change the height of the following line in the display for typesetting purposes. This was not part of the initial objective, just fairly low-hanging fruit.
When I need to pull out formatted text, I call $(editableElement).getLines(), where
jQuery.fn.getLines = function (){
   var count = $(this).children(".word-measure").length;
   var lineAcc = [$(this).children(".word-measure:eq(0)").text()];
   var textAcc = [];
   for(var i=1; i<count; i++){
      var prevY = $(this).children(".word-measure:eq("+(i-1)+")").offset().top;
      if($(this).children(".word-measure:eq("+i+")").offset().top==prevY){
         lineAcc.push($(this).children(".word-measure:eq("+i+")").text());
   } else {
     textAcc.push({text: lineAcc.join(" "), top: prevY});
     lineAcc = [$(this).children(".word-measure:eq("+i+")").text()];
   }
   }
   textAcc.push({text: lineAcc.join(" "), top: $(this).children(".word-measure:last").offset().top});
   return textAcc;
};

The end result is a list of hashes, each one containing the content and vertical offset of a single line of text.
[{"text":"Some dummy set to","top":363},
 {"text":"demonstrate...","top":382},
 {"text":"The output of this","top":420},
 {"text":"wrap-detector.","top":439}]

If I just want unformatted text, $(editableElement).text() still returns
"Some dummy set to demonstrate... The output of this wrap-detector."

A: I have a situation where I need to wrap each line in a span. I do this so that I can add a padded highlight effect to a text block. Adding the background to a span tag that wraps the text will only pad the beginning and ending of the text block, each line must be wrapped individually.
This is what I came up with based on the suggestions above:
$.fn.highlghtWrap = function () {
    this.each( function () {
      var current = $( this );
      var text = current.text();
      var words = text.split( ' ' );
      var line = '';
      var lines = [];

      current.text( words[ 0 ] );
      var height = current.height();
      line = words[ 0 ];
      for ( var i = 1; i < words.length; i++ ) {
        current.text( current.text() + ' ' + words[ i ] );

        if ( current.height() > height ) {
          lines.push( line );
          line = words[ i ];
          height = current.height();
        } else {
          line = line + ' ' + words[ i ];
        }
      }
      lines.push( line );
      current.html( '' );
      $.each( lines, function ( v, a ) {
        current.html( current.html() + '' + a +
          ' ' );
      } );
    } );
  }

  $( '.home-top_wrapper h2' ).highlghtWrap();
  $( '.home-top_wrapper p' ).highlghtWrap();

A: A conceptually simple way that also works when there's internal markup and arbitrary fonts and styles, is to make a first pass that simply puts every word into its own element (maybe 'SPAN', or a custom name like 'w').
Then you can iterate using getBoundingClientRect() to find where the 'top' property changes:
function findBreaks() {
    var words = document.getElementsByTagName('w');
    var lastTop = 0;
    for (var i=0; i<words.length; i++) {
        var newTop = words[i].getBoundingClientRect().top;
        if (newTop == lastTop) continue;
        console.log("new line " + words[i].textContent + " at: " + newTop);
        lastTop = newTop;
    }
}

It sounds slow, but unless the documents are really big you won't notice.


text:
Q: How to check the equality of two identical URLs if one of them has "www"? The following URLs are identical:

*

*http://example.com

*http://www.example.com
Can I get the expected result using a method provided in .Net framework like Compare() method in Uri class? or should I handle this case manually?

A: As mentioned in the comments, these are actually not identical urls and cannot be treated as such.
That aside, it may help you to check the equality after removing the www part:
string urla = @"http://example.com";
string urlb = @"http://www.example.com";

if (urlb.contains("www.")) urlb = urlb.replace("www.", "");
if (urla == urlb) {
    // url matches
}

A: Unfortunately I don't have enough rep to leave a simple comment for you to ponder about so I'll just leave an answer as food for thought.
I can see a few possible solutions which should cover most scenarios (I'm pretty certain I will probably miss quite a few but everyone makes mistakes):

*

*Use a loop to move over both URIs and compare each part/component as you see fit with break early conditions to speed it up

*Clean up the URIs as much as you can using arbitrarily defined rules (eg. remove protocol, remove www prefix, trim ending /) then use Equals() to compare

*If you're feeling bold you could use something similar to lexical analysis to convert both URIs into a objects/tokens/parts and compare the subsequent result (harder to implement but probably the most accurate)

Just keep in mind that the guys in the comments are right. The URLs aren't technically the same and the logic you implement in your ultimate solution is purely defined around your definition of 'identical'.
Also, I wouldn't use the solution that simple replaces "www." with "" since someone crazy could easily put a 'www.' somewhere else in their URL and break that implementation unless you perform the replace on both URLs which is also quite risky since one could have more 'www.' instances than the other and would still be considered 'identical'


text:
Q: How to automatically update tag file in vim? I use vim C++ tag file for navigation using Ctrl-]. The problem is whenever some file gets modified, the links are no longer valid and I have to re-run ctags and update the tag file. Our code base is huge and it takes quite a while for generating tag file.
Is there any tool which periodically updates the tag file in background? Can I configure VIM to do the same?
I use gvim under Windows.

A: An idea:
Use Vim autocommands (:help autocommand) to trigger running of a script every time a buffer is saved using the BufWritePost event.
This script starts the ctags generation and contains some additional small logic to not run while it's already running (or to run at most every 10 minutes, etc.).
Edit:
Something similar was asked here beforehand, see Vim auto-generate ctags

A: From its repository: vim-gutentags is a plugin that takes care of the much needed management of tags files in Vim. It will (re)generate tag files as you work while staying completely out of your way. It will even do its best to keep those tag files out of your way too. It has no dependencies and just works.
You can give it a try at https://github.com/ludovicchabant/vim-gutentags.

A: Further to Blixtor's answer, you'll need to think a little carefully about the design of the script.  I'd recommend segregating the design such that the autocommand uses the Windows "start" command or similar to run an external script in the background: thereby preventing Vim from being unresponsive while the tag file is generated.
That script could then generate the tag file using a different file name (i.e. not "tags": ctags -R -o newtags .) and, when ctags is complete, delete tags and rename newtags to tags.  This will prevent the tag file from being unavailable in Vim while the generation is done.

A: I wrote the vim-easytags plug-in to do exactly this. I initialize my tags file once by scanning a whole project (using the command :UpdateTags **/*.[hc] for example) and afterwards the plug-in will automatically update the tags file as I edit and :update my source code files in Vim. While it updates the tags file it will block Vim, but because it only scans the current file it doesn't take long.
Update (2014-07-30): Still working on the vim-easytags plug-in :-). Nowadays it supports an asynchronous mode to avoid blocking Vim. At the time I write this the asynchronous mode is not the default mode yet, but after some more feedback I'll probably switch the default mode.

A: I already wrote a plugin to do all the hard job with ctags: Indexer.
It provides painless automatic tags generation for the whole project(s) and keeps tags up-to-date. Tags is generated in background, so, you do not have to wait while ctags generates tags. You can use it independently or as an add-on for another plugin project.tar.gz.
In the first way, you can declare your projects in ~/.indexer_files like this:
[CoolProject]

/home/user/cool_project

[AnotherProject]
option:ctags_params = "--languages=c++"

/home/user/another_project/src
/home/user/another_project/lib

And then, when you open any file from /home/user/cool_project , all this project will be indexed by ctags. When you open tags from another project, tags is generated for it too. Tags from different projects is never mixed. When you save file from project, tags is silently updated. You do not have to care about it, it just works.
For detailed information, see the article: Vim: convenient code navigation for your projects, which explains the usage of Indexer + Vimprj thoroughly.
It is successfully tested on Vim 7.3, on the following systems:

*

*Archlinux

*Ubuntu 10.4

*Windows XP

*Mac OS X Lion

A: This logic works for most cases: When opening a new file in vim, change to the directory of that file and generate a tags file there if it does not already exist. When saving a changed buffer, generate a tags file in the directory of the file being saved:

function! GenerateTagsFile()
  if (!filereadable("tags"))
    exec ":!start /min ctags -R --c++-kinds=+p --fields=+iaS --extra=+q --sort=foldcase ."
  endif
endfunction

" Always change to directory of the buffer currently in focus.
autocmd! bufenter *.* :cd %:p:h
autocmd! bufread  *.* :cd %:p:h

" Generate tags on opening an existing file.
autocmd! bufreadpost *.cpp :call GenerateTagsFile()
autocmd! bufreadpost *.c   :call GenerateTagsFile()
autocmd! bufreadpost *.h   :call GenerateTagsFile()

" Generate tags on save. Note that this regenerates tags for all files in current folder.
autocmd! bufwritepost *.cpp :call GenerateTagsFile()
autocmd! bufwritepost *.c   :call GenerateTagsFile()
autocmd! bufwritepost *.h   :call GenerateTagsFile()

A: http://vim.wikia.com/wiki/Autocmd_to_update_ctags_file
function! DelTagOfFile(file)
  let fullpath = a:file
  let cwd = getcwd()
  let tagfilename = cwd . "/tags"
  let f = substitute(fullpath, cwd . "/", "", "")
  let f = escape(f, './')
  let cmd = 'sed -i "/' . f . '/d" "' . tagfilename . '"'
  let resp = system(cmd)
endfunction

function! UpdateTags()
  let f = expand("%:p")
  let cwd = getcwd()
  let tagfilename = cwd . "/tags"
  let cmd = 'ctags -a -f ' . tagfilename . ' --c++-kinds=+p --fields=+iaS --extra=+q ' . '"' . f . '"'
  call DelTagOfFile(f)
  let resp = system(cmd)
endfunction
autocmd BufWritePost *.cpp,*.h,*.c call UpdateTags()

A: I found this really simple and useful:

*

*cd into the code directory.

*ctags -R


text:
Q: Suppose A & B are disjoint events with probability $P\{A\}= 0.4$, $P\{B\}=0.5$ Find
(a) $P\{A \cup B\}$
(b) $P\{A^c\}$
(c) $P\{A^c \cap B\}$
This is what I have right now:
(a) $P\{A \cup B\}=0.4+0.5=0.90$
(b) $P\{A^c\}= 1-0.4=0.60$
(c) $P\{A^c \cap B\}= (0.6)\cdot(0.5)=0.30$
Am I doing it correctly?

A: For any two events $A$ and $B$, $$P(A\cup B)=P(A)+P(B)-P(A\cap B)$$
If $A$ and $B$ are mutually exclusive, then $P(A\cap B)=0$ and thus $$P(A\cup B)=P(A)+P(B)$$
If $A$ and $B$ are independent, then $P(A\cap B)=P(A)\times P(B)$ and thus $$P(A\cup B)=P(A)+P(B)-P(A)P(B)$$
Thus (a) is wrong, while (b) and (c) are correct.

A: According to your comment, $A$ and $B$ are indepentent (not disjoint). Be careful, the two things are not equivalent.
Anyway, if $A$ and $B$ are independent, your answer to (a) is not correct.
Indeed,
 $$P(A\cup B)=P(A)+P(B)-P(A\cap B).$$ Since $A$ and $B$ are independent $P(A\cap B)=P(A)P(B)$. Hence $P(A\cup B)=0.4+0.5-0.2=0.7$.
On the other hand, (b) and (c) are correct.


text:
Q: Arduino Nano - LED - MPR121 - HC_06BT PCB check I´m working on a multi-touch Bluetooth device with integrated LEDs for a multimedia-installation. Because I'm new in PCB design and electronics in general, I would like to know if this schematic/PCB makes sense.

A: Your schematics seems good.
Looking at your PCB design, it's not so clear in the picture.
Did you use ground plane on the bottom of the PCB?
Touch sensing is sensitive for capacitance.
Thus, you'd better not to put ground plane near or under the routing to your 12-pin connector. Anyhow, current design might work, but if you read the touch sensor datasheet or design guidelines, you can know how more.


text:
Q: SQL Select including Data type and Data values How could I select data from a table and include the data type with the values?
For example, I have table called EMPLOYEE with fname, lastname, phone, etc.
If I do:
SELECT * FROM EMPLOYEE

I get all the columns. If I do:
SELECT COLUMN_NAME, DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'EMPLOYEE'
ORDER BY ORDINAL_POSITION

I get all the column names and their data types.
I need to combine these two so I have the values displayed along with the data type.
I'm new to SQL but I have searched on the web some and tried various JOIN and UNION statements, but I could just be entering them wrong.

A: You could SELECT EMPLOYEE.COL1, INFO.DATA_TYPE FROM EMPLOYEE, INFORMATION_SCHEMA.COLUMNS INFO WHERE INFO.TABLE_NAME='EMPLOYEE' AND COLUMN_NAME='COL1'
But to select more fields, you'd have to add another instance of INFORMATION_SCHEMA.COLUMNS again with a different alias.
But you should not do this for many reasons.
Technically: CROSS JOIN (the tables in FROM listed simply with a comma) is much strain on the database server. FROM T1, T2 pairs up all rows of T1 with all rows of T2 and examines the result rows. If T1 has n rows and T2 has m then the result has n*m rows.
Logically 1: You should not need this information to be returned. When you enter a query (a SELECT) the the returned schema is known; the query determines what datatypes the result columns are.
Logically 2: Since every row has the same datatypes in the columns, you do not need the type information to be returned in every row. E.g. your example returning data of 1000 employees would unnecessarily transfer on every line that the AGE field is INTEGER, the NAME is VARCHAR and so on...
If you somehow would not know the schema of the result (e.g. because of generated queries or the like) then the above solution would not help you.


text:
Q: Adding new rows with new values at some specific columns in pandas Assume we have a table looks like the following:

id
week_num
people
date
level
a
b

1
1
20
1990101
1
2
3

1
2
30
1990108
1
2
3

1
3
40
1990115
1
2
3

1
5
100
1990129
1
2
3

1
7
100
1990212
1
2
3

week_num skip the "4" and "6" because the corresponding "people" is 0. However, we want the all the rows included like the following table.

id
week_num
people
date
level
a
b

1
1
20
1990101
1
2
3

1
2
30
1990108
1
2
3

1
3
40
1990115
1
2
3

1
4
0
1990122
1
2
3

1
5
100
1990129
1
2
3

1
6
0
1990205
1
2
3

1
7
100
1990212
1
2
3

The date starts with 1990101, the next row must +7 days if it is a continuous week_num(Ex: 1,2 is continuous; 1,3 is not).
How can we use python(pandas) to achieve this goal?
Note: Each id has 10 week_num(1,2,3,...,10), the output must include all "week_num" with corresponding "people" and "date".
Update: Other columns like "level","a","b" should stay the same even we add the skipped week_num.

A: This assumes that the date restarts at 1990-01-01 for each id:
import itertools
# reindex to get all combinations of ids and week numbers
df_full = (df.set_index(["id", "week_num"])
             .reindex(list(itertools.product([1,2], range(1, 11))))
             .reset_index())
# fill people with zero
df_full = df_full.fillna({"people": 0})
# forward fill some other columns
cols_ffill = ["level", "a", "b"]
df_full[cols_ffill] = df_full[cols_ffill].ffill()
# reconstruct date from week starting from 1990-01-01 for each id
df_full["date"] = pd.to_datetime("1990-01-01") + (df_full.week_num - 1) * pd.Timedelta("1w")
df_full

# out:
    id  week_num  people       date  level    a    b
0    1         1    20.0 1990-01-01    1.0  2.0  3.0
1    1         2    30.0 1990-01-08    1.0  2.0  3.0
2    1         3    40.0 1990-01-15    1.0  2.0  3.0
3    1         4     0.0 1990-01-22    1.0  2.0  3.0
4    1         5   100.0 1990-01-29    1.0  2.0  3.0
5    1         6     0.0 1990-02-05    1.0  2.0  3.0
6    1         7   100.0 1990-02-12    1.0  2.0  3.0
7    1         8     0.0 1990-02-19    1.0  2.0  3.0
8    1         9     0.0 1990-02-26    1.0  2.0  3.0
9    1        10     0.0 1990-03-05    1.0  2.0  3.0
10   2         1     0.0 1990-01-01    1.0  2.0  3.0
11   2         2     0.0 1990-01-08    1.0  2.0  3.0
12   2         3     0.0 1990-01-15    1.0  2.0  3.0
13   2         4     0.0 1990-01-22    1.0  2.0  3.0
14   2         5     0.0 1990-01-29    1.0  2.0  3.0
15   2         6     0.0 1990-02-05    1.0  2.0  3.0
16   2         7     0.0 1990-02-12    1.0  2.0  3.0
17   2         8     0.0 1990-02-19    1.0  2.0  3.0
18   2         9     0.0 1990-02-26    1.0  2.0  3.0
19   2        10     0.0 1990-03-05    1.0  2.0  3.0


text:
Q: How get indexPath and write in NSMutableArray I'm starter!
I have 7 cell-(7 days) in TableViewController
How get indexPath for all selected cells and write in NSMutableArray
My Project is Alarm Clock
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.accessoryType = UITableViewCellAccessoryCheckmark;

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.accessoryType = UITableViewCellAccessoryNone;

}

please help or tell me something

A: you can get indexpath array using  this.
NSArray *indexPathArray = [yourTableView indexPathsForSelectedRows];


text:
Q: Statistical analysis for comparing expertise levels between 3 groups I hope you are all safe and healthy considering the current climate.
I was wondering if someone could help with a statistical dilemma I have on my hands.
I am trying to explore whether IQ tests can distinguish academics of difference expertise levels.
I have an overall of 63 participants. 17 professors, 26 PhD students and 19 bachelor students. These have then been split into 7 nominal categories of experience levels (i.e. bachelor 1-3 year, etc).I have tested them on 4 individual IQ tests. My data is not normally distributed, as to be expected. I want to perform the test on SPSS.
What statistical analysis can I now run, to determine whether certain individuals of specific experience levels have higher IQ tests. That is, do people with more experience score higher on IQ tests.


text:
Q: Selecting with jquery Can't manage to be specific enough I have the following HTML :
<div class="myclass">
    <form class="aform">
       <select name="first"></select>
       <select name="second"></select>
    </form>
</div>

I curently had all the div into a variable :
mydiv = $(".myclass");

Now I need to select one of the "select" tag. I tried the following query :
$('select[name="first"]',mydiv).html("Cool things to insert!");

But my jquery selection is changing both select in the form intead of changing only the one I've selected by name.
Where did I go wrong?

A: Try mySelect = $(.myclass select[name="first"]);.

A: Try it:
$('.myclass').find('select[name="first"]').html("Cool things to insert!");

See the jQuery documentation:  .find()
Hope this answer can help you!

A: I think your code is running fine (try it at http://jsfiddle.net/wVccE/).
If you inspect the element, you'll see that only the first select changed.
But I don't see any point in changing a select inner html, perhaps what you really want is a single select with multiple option?


text:
Q: Recommended way of clearing large lava pools Next on my list of Minecraft todo's is building a slime farm. I looked up the spawning locations online and chose my location.
I dug out the spawning plateau (16x32x5 blocks) and dug out an extra surrounding 3x3 blocks for tunneling. All went well; 2-3 diamond pickaxes did the trick. After that I lit up the place with glowstone so no angry mobs would spawn.
I think it will be a successful project, because slimes spawn in constantly already.
I've started to work on the collection area. Basically, I want to build a large room there that looks out over the spawning plateaus. The problem I have is that the exact area I want to work with is filled with lava pools.
When I visited that place earlier I poured water over the lava, which turns it into obsidian. That was stupid; now it takes me ages to harvest, and I can not blast it away.
Now I use the gravel method: just filling the lava block-by-block. When I am out of gravel, I dig up the back parts and go on. This really takes a while though.
I wonder if there are any better ways to clear a large-lava filled chunk.

A: In my experience dropping gravel in from above is the best method, however if you want an alternative you could try convering the laval into cobblestone using water and then mining out the cobblestone.
As with the gravel method you first need to dig so that you are above the lava, and then Place a water source somewhere above the lava so that it will flow over the lava creating a floor of cobblestone.  Then carefully mine away the cobblestone (most of it will drop into the lava below) and start again on the next layer.
Honestly though, using gravel is probably easier.

A: Moving the lake 10 to the side is actually a faster and easier way of managing your lava,
When you find a large Pool, don't want to use it just yet, but need it removed, Putting it into a nearby 2d pool is very handy, gets it out of your way, and yo know the dimensions of your self made pool.  Unfortunately, you can't just place lava beside lava, you need a wall to click on, so make a long run, 20 by 2, into a wall where you wont step on it, so you can click on the back wall for the first row, and click on the floor of the "ditch" for the second row. I've made many long passages lit by this kind of floor light:
Vertical Cross-section of hallway:
X=any none burnable block,
Z=Lava
A=air (the hallway I use usually are 3 tall and 2 wide)

XXXXXXX Because the connection is only one high you wont
XAAXXXX accidentally slip into it if your running down
XAAXXXX the passage. You could do this to both sides of
XAAXXXX your hallway, but if I'm just using it to store
XAAAXXX lava I need moved, I haven't needed to make anything
XXXZZXX larger than 32x2 during excavation.
XXXXXXX

A: Unfortunately if you want to remove the lava completely and then be where that pool is gravel/sand really is the best way to go about clearing that out.
The only alternate that I can think of would be to bucket every block of lava out and then put it into a single block area. This would then just require a single piece of gravel to get rid of. If you are good at bucketing then this might be a bit faster and save you on some shovels.

A: Bucketing the lava out, althought probable, is almost more time consuming than using gravel, and is very dangerous. I would suggest just using water. The resulting obsidian is very valuable and althought it takes awhile to mine (12 seconds with a diamond pick) it is well worth the effort, as it can be used to create bomb shelters when blasting with TNT, creeper proof rooms/buildings, and portals into the ever fun and fantastic Nether.

A: Build a layer of dirt through the uppermost lava layer, which is therefore replaced by dirt. Remove the dirt and go on with the next, now uppermost lava layer. If you crouch, most removed dirt (and you) won't fall into the lava.


text:
Q: Monitor Linux process with STAT status Don't know if anyone has idea on how I can monitor Zombie processes using Zabbix. Zabbix agent currently has a predefined template "proc.num[,,,]" which I can use to monitor 'zombie' processes but this only shows STAT with 'Z'.
I have a script that can check for STAT with either 'X' or 'Z' i.e X = Dead & Z = Zombie
ps aux | awk '$8=="X" || $8=="Y"' | wc -l

How can this script be used in Zabbix

A: OK I figured this out. Using Zabbix Agent template called 'system.run':
system.run[ps aux | awk '$8=="X" || $8=="Y"'|wc -l,]


text:
Q: html appengine redirect URL I want to redirect a user to the next URL after authenticating on a third party web page. In the redirect URL I want it to contain some info about the user, i.e. session id. For example my redirect URL will be www.z.appspot.com/?session=x/ when the user returns to my page I want to parse some of their details from the new URL, for example www.z.appspot.com/?access_code=x/?token=y&user_id=u but when trying to parse out the information it is unable to see the token in the URL as it takes it to be part of session. I tried using & but still no joy

A: You want a module called cgi, and a function called FieldStorage.  Do it like this:
import cgi

url_parms = cgi.FieldStorage()
session = url_parms.getvalue("session","default")

You can do this for any of the URL parameters.  Replace "default" with whatever you want the default value to be (like an empty string).

A: Your question is a bit confusing, but is there a reason your other service can not redirect to: www.z.appspot.com/?access_code=x/&token=y&user_id=u?  That should be correctly parsed:
import urlparse
import cgi

url = "www.z.appspot.com/?access_code=x/&token=y&user_id=u"
query = urlparse.urlparse(url).query
print cgi.parse_qs(query)
# output: {'access_code': ['x/'], 'token': ['y'], 'user_id': ['u']}

If you can not change the format of the url, you could do something like:
import urlparse
import cgi

url = "www.z.appspot.com/?access_code=x/?token=y&user_id=u"
query = urlparse.urlparse(url).query
access_code, query = query.split('?', 1)
access_code = access_code.split('=', 1)[1]
print access_code
# output: 'x/'
print cgi.parse_qs(query)
# output: {'token': ['y'], 'user_id': ['u']}

Or, if you're just trying to ask how to embed parameters in the URL they will be redirected to, see Python's urlencode.
Update:
import urllib
encoded = urllib.urlencode({'app_id': 11,
                            'next': 'http://localhost:8086/?access_token=%s' % (access_token,)})
hunch_url = 'http://hunch.com/authorize/v1/?%s' % (encoded,)

Then pass hunch_url to your template.

A: It looks like the service you're redirecting to doesn't compose query parameters in the continue URL correctly. The easiest way around this would be (as I suggested in your original question) to send the parameter as part of the path, rather than the query string - that is, use URLs of the form:
http://www.yourapp.com/continue/1234

Where 1234 is the user's session ID or user ID.


text:
Q: how to create zip and stock it in a link MVC or provide zip to user and redirect I am able to create a zip with no problem, the only thing I cannot do, stock the zip file in a link so that when the user clicks on the link it will download the file
Response.Clear();
Response.ContentType = "application/zip";
Response.AddHeader("content-disposition", "filename=Photo.zip");

using (ZipFile zip = new ZipFile())
        {
            foreach (var pictures in pictureList)
            {
                zip.AddFile(Server.MapPath("~\\Content\\pictures\\upload\\" + pictures.name),"images");
            }
            zip.Save(Response.OutputStream);
        }
Response.End();

A: Code below works for the file downloading.
public void DownloadFile(string fileName)
 {
    FileInfo file = new FileInfo(@"D:\DOCS\"+fileName);
    Context.Response.Clear();
    Context.Response.ClearHeaders();
    Context.Response.ClearContent();
    Context.Response.AddHeader("Content-Disposition", "attachment;  filename=" + file.Name); Context.Response.AddHeader("Content-Length", file.Length.ToString());
    Context.Response.ContentType = "application/zip";
    Context.Response.Flush();
    Context.Response.TransmitFile(file.FullName);
    Context.Response.End();
}

However, Calling Response.Redirect after Response.End() will not going to work. If you really want to redirect the page you might have to think of an alternative way.


text:
Q: How to correctly use mavon-editor like markdown editor in Vue3.js apps? I tried to install mavonEditor as markdown editor for my latest vue3.js app and also used vite for building vue.js apps.
First of all, I followed the document of mavonEditor, mavon component is not defined.
I installed mavon-editor(v2.10.4) using by npm.
And then, change the main.js like below.
import { createApp } from "vue";
import App from "./App.vue";
import "./assets/tailwind.css";
import mavonEditor from "mavon-editor";
import "mavon-editor/dist/css/index.css";

createApp(App).use(mavon).mount("#app");

and I tried to use editor component to App.vue like that.
<template>
  <div>
    <mavon-editor v-model="value" />
  </div>
</template>

<script>
import { ref } from "@vue/reactivity";

export default {
  setup() {
    const value = ref("its my first mavon editor!");
    return { value };
  },
};
</script>

Open the browser(Chrome), but any items wasn't show.
Instead of editor, that error occurred in console.
Uncaught ReferenceError: mavon is not defined

I really want to know how to correctly use mavon-editor in Vue3.js.
Does anyone help me, please?

A: you can add this
app.use(mavonEditor)

and remove mavon from
createApp(App).use(mavon).mount("#app");

hope this help you solve the problem


text:
Q: Why "git clone" when I can do the same with "git pull" after "git init"? I have created a git repository using git init and added a remote repo URL by using git remote add origin https://remote-url
When I did git pull origin master after setting up the necessary upstream branch by using git branch --set-upstream-to=origin/master master to track remote branch (my local master branch was set to track the remote master branch this after doing git checkout master), I am able to pull all the revision history of my remote project branch into my local repo.
If I can very well do this with git pull, then why git provides git clone as a separate command and an alternative? Does it serve any special purpose or do I miss anything by doing git pull alone?

A: That's not an unreasonable question.  But so is this one:
You can run:
git write-tree
git commit-tree -p HEAD -m message <hash-from-git-write-tree>
git branch -f <current-branch> <hash-from-git-commit-tree>

This does the same thing—well, it does if there are no errors—as:
git commit -m message

so why do we have a git commit command at all?
Here's a followup question: Which of these is easier to use?

The git clone command is actually equivalent to running up to six commands, five of which are Git commands.  The six steps involved in git clone are:

*

*mkdir path, to make a new empty directory in which to run git init.  (This step is skipped in the special case in which you give git clone the path name of an existing but empty directory, in which case it uses that.)

*git init, to create a new empty repository in the new directory.

*git remote add remote url, where remote is from your git clone option -o, or is origin if you did not specify this option, and the url is the one you specified in the clone command.

*Any additional git config commands from options supplied to git clone.

*git fetch remote, to obtain commits from the Git at the supplied URL.

*git checkout branch, where the branch is the one you specified with the -b option in your git clone command, or a branch specified by the other Git if you did not specify a branch, or master if the other Git does not specify any branch.
The git clone command also handles various errors that can occur during this process that you would otherwise have to handle yourself.

The git pull command is equivalent to running git fetch followed by a second Git command.  That second command is usually git merge, though you can tell Git to use git rebaseinstead.  But git pull has one more special mode: when you git pull into a completely empty repository, as you did in your question, it can run git checkout as its second command instead of either of the other two.

Note: unlike git clone, where it's very rare to need anything between the six steps, with git pull it's pretty common for me to need to inspect the commits that git fetch obtained before I run a second command.  So I generally avoid git pull entirely, because it forces me to choose the second command to run, and to run it immediately upon the completion of the fetch step, when I would like to do something else after fetch, before I choose whether to use merge, or rebase, or something else entirely.


text:
Q: Defining friendships in a Data Frame I have a task in which it is necessary to determine the presence of a friendly connection. Let me explain, there is a checkpoint at work. The employee, passing through it, gets into the database, where his time of passage and his name are recorded. If an employee often passes through the point with the same person, then it is possible to assume with some probability that there is a friendly relationship between them. It is also necessary to take into account the difference in time with which they passed, if the difference in the passage is large, then they probably did not even see each other. For example, I made a small time Series:
    import pandas as pd
dict_df={
    'Data':['2020-02-10 10:00:23','2020-02-10 10:01:23','2020-02-10 10:01:30','2020-02-10 10:01:43',
            '2020-02-10 10:02:02','2020-02-10 10:02:30','2020-02-10 10:02:35','2020-02-10 10:02:50',
            '2020-02-10 10:02:58','2020-02-10 10:03:02','2020-02-10 10:03:10','2020-02-10 10:03:15',
            '2020-02-10 10:03:26','2020-02-10 10:03:32','2020-02-10 10:03:38','2020-02-10 10:03:40',
            '2020-02-10 10:03:46','2020-02-10 10:03:50','2020-02-10 10:04:04','2020-02-10 10:04:12',
            '2020-02-10 10:04:23','2020-02-10 10:04:27','2020-02-10 10:04:45','2020-02-10 10:04:50',
            '2020-02-10 10:04:59','2020-02-10 10:05:20','2020-02-10 10:05:26','2020-02-10 10:05:40',
            '2020-02-10 10:05:56','2020-02-10 10:06:12','2020-02-10 10:06:18','2020-02-10 10:06:30',
            '2020-02-10 10:06:37'],
    'Name':['Ann','Jhon','Chase','Bruce','Evan','Fred','Hugh','Gregory','Jack','Caleb','Eric','James',
            'Ann','Gerld','Jess','Juan','Luke','Kyle','Neil','Owen','James','Eric','Jhon','Jess','Norman',
            'Hugh','Fred','Gregory','Ryan','Angel','Cole','James','Eric']}

df=pd.DataFrame(dict_df)

This is what it looks like:
 Data                Name
0   2020-02-10 10:00:23 Ann
1   2020-02-10 10:01:23 Jhon
2   2020-02-10 10:01:30 Chase
3   2020-02-10 10:01:43 Bruce
4   2020-02-10 10:02:02 Evan
5   2020-02-10 10:02:30 Fred
6   2020-02-10 10:02:35 Hugh
7   2020-02-10 10:02:50 Gregory
8   2020-02-10 10:02:58 Jack
9   2020-02-10 10:03:02 Caleb
10  2020-02-10 10:03:10 Eric
11  2020-02-10 10:03:15 James
12  2020-02-10 10:03:26 Ann
13  2020-02-10 10:03:32 Gerld
14  2020-02-10 10:03:38 Jess
15  2020-02-10 10:03:40 Juan
16  2020-02-10 10:03:46 Luke
17  2020-02-10 10:03:50 Kyle
18  2020-02-10 10:04:04 Neil
19  2020-02-10 10:04:12 Owen
20  2020-02-10 10:04:23 James
21  2020-02-10 10:04:27 Eric
22  2020-02-10 10:04:45 Jhon
23  2020-02-10 10:04:50 Jess
24  2020-02-10 10:04:59 Norman
25  2020-02-10 10:05:20 Hugh
26  2020-02-10 10:05:26 Fred
27  2020-02-10 10:05:40 Gregory
28  2020-02-10 10:05:56 Ryan
29  2020-02-10 10:06:12 Angel
30  2020-02-10 10:06:18 Cole
31  2020-02-10 10:06:30 James
32  2020-02-10 10:06:37 Eric

I need it to be like this:
 Data                Name   cluster
0   2020-02-10 10:00:23 Ann     0
1   2020-02-10 10:01:23 Jhon    0
2   2020-02-10 10:01:30 Chase   0
3   2020-02-10 10:01:43 Bruce   0
4   2020-02-10 10:02:02 Evan    0
5   2020-02-10 10:02:30 Fred    1
6   2020-02-10 10:02:35 Hugh    1
7   2020-02-10 10:02:50 Gregory 1
8   2020-02-10 10:02:58 Jack    0
9   2020-02-10 10:03:02 Caleb   0
10  2020-02-10 10:03:10 Eric    2
11  2020-02-10 10:03:15 James   2
12  2020-02-10 10:03:26 Ann     0
13  2020-02-10 10:03:32 Gerld   0
14  2020-02-10 10:03:38 Jess    0
15  2020-02-10 10:03:40 Juan    0
16  2020-02-10 10:03:46 Luke    0
17  2020-02-10 10:03:50 Kyle    0
18  2020-02-10 10:04:04 Neil    0
19  2020-02-10 10:04:12 Owen    0
20  2020-02-10 10:04:23 James   2
21  2020-02-10 10:04:27 Eric    2
22  2020-02-10 10:04:45 Jhon    0
23  2020-02-10 10:04:50 Jess    0
24  2020-02-10 10:04:59 Norman  0
25  2020-02-10 10:05:20 Hugh    1
26  2020-02-10 10:05:26 Fred    1
27  2020-02-10 10:05:40 Gregory 1
28  2020-02-10 10:05:56 Ryan    0
29  2020-02-10 10:06:12 Angel   0
30  2020-02-10 10:06:18 Cole    0
31  2020-02-10 10:06:30 James   2
32  2020-02-10 10:06:37 Eric    2

You can see that Fred, Gregory and Hugh have passed together several times, so a friendly connection is established. Also, James and Eric passed together, so it is also a friendly relationship.
Help us solve it using machine learning, say clustering or graph analysis. Tell me, maybe someone has thoughts.

A: No need for clustering algorithms.  Such algorithms are useful if your data has multiple traits.  In this case, there is only one: arrival time.    Simply keep track of how often pairs arrive "together".
loop over arrivals
   loop over previous arrivals, recent enough to be friends
       increment count for this pair
loop over pairs
   if count above minimum, mark as friends

Setting the maximum time between friends arriving to be 20 secs, and the minimum frequency for a pair to be recognized as friends to be 2, then we get:
togerther count:
Angel Cole 1
Angel James 1
Ann Gerld 1
Ann Jess 1
Ann Juan 1
Ann Luke 1
Bruce Evan 1
Caleb Eric 1
Caleb James 1
Chase Bruce 1
Cole Eric 1
Cole James 1
Eric Ann 1
Eric James 3
Eric Jhon 1
Fred Gregory 2
Fred Hugh 2
Gerld Jess 1
Gerld Juan 1
Gerld Kyle 1
Gerld Luke 1
Gregory Caleb 1
Gregory Eric 1
Gregory Jack 1
Gregory Ryan 1
Hugh Gregory 2
Jack Caleb 1
Jack Eric 1
Jack James 1
James Ann 1
James Gerld 1
Jess Juan 1
Jess Kyle 1
Jess Luke 1
Jess Norman 1
Jhon Bruce 1
Jhon Chase 1
Jhon Jess 1
Jhon Norman 1
Juan Kyle 1
Juan Luke 1
Kyle Neil 1
Luke Kyle 1
Luke Neil 1
Neil James 1
Neil Owen 1
Owen Eric 1
Owen James 1
Ryan Angel 1

and so the friends are
friends:
Eric James 3
Fred Gregory 2
Fred Hugh 2
Hugh Gregory 2

You can see C++ code implementing this at https://gist.github.com/JamesBremner/cba0a5e8bbda9388c3e983c3bc5dfd9b


text:
Q: Filling in nans for numbers in a column-specific way Given a DataFrame and a list of indexes, is there an efficient pandas function that put nan value for all values vertically preceeding each of the entries of the list?
For example, suppose we have the list [4,8] and the following DataFrame:
index     0      1
5         1      2
2         9      3
4         3.2    3
8         9      8.7

The desired output is simply:
index     0        1
5         nan      nan
2         nan      nan
4         3.2      nan
8         9        8.7

Any suggestions for such a function that does this fast?

A: Here's one NumPy approach based on np.searchsorted -
s = [4,8]

a = df.values
idx = df.index.values
sidx = np.argsort(idx)
matching_row_indx = sidx[np.searchsorted(idx, s, sorter = sidx)]
mask = np.arange(a.shape[0])[:,None] < matching_row_indx
a[mask] = np.nan

Sample run -
In [107]: df
Out[107]:
         0    1
index
5      1.0  2.0
2      9.0  3.0
4      3.2  3.0
8      9.0  8.7

In [108]: s = [4,8]

In [109]: a = df.values
     ...: idx = df.index.values
     ...: sidx = np.argsort(idx)
     ...: matching_row_indx = sidx[np.searchsorted(idx, s, sorter = sidx)]
     ...: mask = np.arange(a.shape[0])[:,None] < matching_row_indx
     ...: a[mask] = np.nan
     ...:

In [110]: df
Out[110]:
         0    1
index
5      NaN  NaN
2      NaN  NaN
4      3.2  NaN
8      9.0  8.7

A: It was a bit tricky to recreate your example but this should do it:
import pandas as pd
import numpy as np

df = pd.DataFrame({'index': [5, 2, 4, 8], 0: [1, 9, 3.2, 9], 1: [2, 3, 3, 8.7]})
df.set_index('index', inplace=True)
for i, item in enumerate([4,8]):
    for index, row in df.iterrows():
        if index != item:
            row[i] = np.nan
        else:
            break


text:
Q: Create Folder on SFTP server iOS I have tried SimpleFTPSample for performing Basic FTP operation on remote server.(e.g Download file, Upload file and Create Directory on sftp Server).But getting Stream Open error/kCFStreamErrorDomainFTP. Please help me on some of my questions.
1) is this sample code will work on SFTP?
-) In CreateDirController.m,
I am getting networkStream nil on
self.networkStream = CFBridgingRelease(
            CFWriteStreamCreateWithFTPURL(NULL, (__bridge CFURLRef) url)
        );

for SFTP server.
2) Can i use NSURLSession NSURLSession Api for SFTP request(Create Directory on SFTP server and List directory of SFTP server)?


text:
Q: Refresh UI component on DB update I have an exposed REST API and an UI component (Label) in outsystems.
The REST API insert some data on database.
So, my requirement is, when my external application insert a data using REST API in outsystems the UI component update its value automatically (real-time).
How it is possible in outsystems?

A: You can start a process on an insert on an entity. But this will not refresh the UI.
To refresh the UI, you can use Javascript to refresh the page periodically.
You need to add two expressions to the page. The first one at the top of the page (i.e. first element in MainContent section), and the second one in the Footer section.
Add some Javascript to the expressions as the Value.

*

*First expression: "<script>function refresh(){setTimeout(function(){ $('#"+RefreshButton.Id+"').click();refresh(); }, 5000);};</script>"

*Second expression: "<script>refresh();</script>"
NOTE: Remember to set Escape Content to No on both expressions!

A: Best option would be to something like socket.io
Socket.io is a good bi-directional client server communication js library which can "emit" events the client can "listen" to.
It is non blocking and real time
Socket IO
Run Javascript on outsystems


text:
Q: How to add title under annotation? I managed to make my annotations with a personalized image by annotation and the title in the popup.
My question: Is it possible to also add the title below the annotation?
Thank you in advance for your feedback.
The view controller
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
        let pageDecouverte = listeDesPoints[view.tag]
        selectedLieuDecouverte = pageDecouverte
        self.performSegue(withIdentifier: "showPageDecouverte", sender: nil)
    }

    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView?
    {
        if !(annotation is MKPointAnnotation) {
            return nil
        }

        let annotationIdentifier = "location"
        var annotationView = carteRegion.dequeueReusableAnnotationView(withIdentifier: (annotationIdentifier))

        if annotationView == nil {
            annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: annotationIdentifier)
            annotationView!.canShowCallout = true
        }
        else {
            annotationView!.annotation = annotation
        }

        if annotation is MyAnnotation {
            let imageName = (annotation as! MyAnnotation).imageName
            annotationView?.tag = (annotation as! MyAnnotation).tag
            if imageName != nil{
                let interetImage = UIImage(named: imageName!)
                annotationView!.image = interetImage

            }

        }
        annotationView?.clusteringIdentifier = annotationIdentifier
        annotationView?.canShowCallout = true
        annotationView?.rightCalloutAccessoryView = UIButton(type:.detailDisclosure)
        return annotationView

    }
}

For my MyAnnotation
import UIKit
import MapKit
import Parse

class MyAnnotation: MKPointAnnotation {

    var imageName: String?
    var annotationTitle: String?
    var tag : Int = 0
    var pageDecouverte:PFPageDecouverte?
}

A: Instead of MKAnnotationView use the subclass MKMarkerAnnotationView to render the title below the marker.
Also in MyAnnotation rename annotationTitle to title, then MKMarkerAnnotationView automatically knows what to render.
See the definition of protocol MKAnnotation to see why.


text:
Q: Mechanism for returning a string from C main() program I know that C program generally ends with return, where we return the status of the program.
However, I want to return a string. The reason is that, I will be calling the C-executable from a shell script and printing the returned string.
Is there any mechanism for the same ?

A: You cannot.
The best thing you could do is writing the string somewhere (on standard output, standard error or some file); then the shellscript will get your string from there.
Standard output (thus using just a printf) is probably the best solution, since it will be very easy from your C program print the string, and very easy for the shellscript getting that data:
From shell script:
STRING="$( ./your_program argv1 argv2 )"

A: There is not way to return a string from main(). Maybe the program itself should print the string ?

A: Just output the string you want to return to standard output with printf.  Then in your script, do something like this:
SOMESTRING="`./yourprogram`"

The backticks will capture the output of the program, which will be the string you printed.

A: There is no such mechanism; the return code is expected to be a byte. If you want to output a string from your program then use something like printf() and command substitution in the shell script to capture it.

A: You can't, but you don't need to either.  You return a stat code from main, but you can always re-direct the output and capture it in your shell script.

A: You cannot - you can only return an integer.
Remember that C was developed alongside Unix. Unix programs return an integer value which is intended as a status code. If a program was to return string(s) it would write them to stdout, and then the user (or a script) would pipe it into something useful.
MS DOS also had number-only status values.

A: You have to print the string to stdout and use the shell's command substitution to read the result:
"`command`"

or:
"$(command)"

Either way, you should use the enclosing double-quotes as above. Note that this method has a potentially-serious problem that it removes all training newlines from the command's output. If you need to preserve the exact output, try:
output="$(command ; echo x)"
output="${output%x}"

Since OP mentioned that this is for a password, another piece of advice: once you've read a password into a shell variable, never pass it on the command line to other programs. Command lines are usually world-readable. Instead of something like
wget "http://$user:$pass@host/foo"

try something like
wget -i - << EOF
http://$user:$pass@host/foo
EOF

Here-files as in this example are useful with a number of programs which need to take passwords from scripts.


text:
Q: RSpec test omniauth logout through Rails app with api only flag I am creating a separate backend for my class project. I have a rails app with the api flag as I want to build this out to end points to be consumed with React or React Native. I was able to test authenticating or creating a user through the api endpoint. Now I'm trying to find a way to test the logout feature. I know how to check to make sure the login call back works. Without views to check for current path or page content, how can I test to ensure that the user is logged out successfully?

A: I ended up using this.
it 'can log out user' do
  get '/api/v1/auth/google_oauth2/callback', params: stub_omniauth
  user = JSON.parse(response.body)

  expect(request.session[:user_id]).to_not be_nil
  expect(user['name']).to eq('Rick Astley')
  expect(User.last.name).to eq('Rick Astley')

  get '/api/v1/signout'
  expect(request.session[:user_id]).to be_nil

end


text:
Q: Stripe - No API key provided (Laravel 5.1) I have problem with providing the Stripe API key. Everything is included, packages, all dependencies...
The error message I get: No API key provided. (HINT: set your API key using "Stripe::setApiKey()". You can generate API keys from the Stripe web interface. See https://stripe.com/api for details, or email support@stripe.com if you have any questions.
Controller:
    public function upgradeBronze() {

        $bid = Session::get('builderId');

        Stripe::setApiKey(env('KEY_SECRET'));
        $token = $_POST['stripeToken'];

        // Create the charge on Stripe's servers - this will charge the user's card

        try {

            $user = \App\User::find($bid);
            $user->subscription('monthly')->create($token);
            return Redirect::route('builders-packages');

        } catch(\Stripe\Error\Card $e) {
            return Redirect::route('builders-packages');
        }

}

Error SS: http://pokit.org/get/img/5f7886d0d9a50ecf349312225c8c47ea.jpg

A: SOLVED
It seems that Stripe integration doesn't work fine on Laravel 5.1 version, if you follow the default documentation you probably won't succeed.
In this case the solution was to put the stripe api key into AppServiceProvider, into register() class.

A: Set the Stripe API key from stripe.php like
public static $apiKey='sk_test_your api_key';

A: Setting stripe API keys in my .env file (worked for me, Laravel 5.8):
STRIPE_KEY=your pk key here
STRIPE_SECRET=your sk key here


text:
Q: mikrotik add hotspot user from javascript API I try to develop an app to create user in mikrotik user manager via api. And I also tried JavaScript in the terminal by using following command:
$node script name.js

That is working and a user created.
Then I tried to run that JavaScript by on click html button. Then JavaScript doesn't run and no user crated. Code follows:
<html>
<head>

 </head>
<body>
<button type = "button" onclick="conn();">Try it</button>
<script type="text/javascript">
var api = require('mikronode');
 var connection = new api('192.168.5.1','admin','xxxxxx');
 connection.connect(function conn() {

    conn.closeOnDone(true); // All channels need to complete before the connection will close.

    var actionChannel=conn.openChannel();
    // These will run synchronsously
    actionChannel.write(['/tool/user-manager/user/add','=username=tiran','=password=123456','=customer=admin']); // don't care to do anything after it's done.
    actionChannel.write(['/tool/user-manager/user/create-and-activate-profile','=customer=admin','=numbers=tiran','=profile=general']); // don't care to do anything after it's done.
    //actionChannel.write('/tool/user-manager/user/print',function(chan) {

       //chan.on('done',function(data) {
          //packets=api.parseItems(data);
          //packets.forEach(function(packet) {
              //alert('done');
             //alert('user: '+JSON.stringify(packet));
              //console.log('user: '+JSON.stringify(packet));
          //});
          //listenChannel.close(); // This should call the /cancel command to stop the listen.
       //});
    //});
    actionChannel.close(); // The above commands will complete before this is closed.
 });
</script>
 </body>
 </html>

A: That code is for NodeJS, you cannot run in directly on the browser as JavaScript


text:
Q: Why won't file from S3 bucket load with Spark? I am attempting to load data from an AWS S3 bucket with spark. I continue to get the error:

Py4JJavaError: An error occurred while calling o152.csv.
: com.amazonaws.services.s3.model.AmazonS3Exception: Status Code: 403, AWS Service: Amazon S3, AWS Request ID: M4Z1B0MTQAY2GDCD, AWS Error Code: null, AWS Error Message: Forbidden, S3 Extended Request ID: GS9ftm1p/TpmZNS4KtsAVmmRfQOIVnIg/22rhnI4i5HKF40pT/QGBAXTwrVNWsHCUQFhEOXD3Gk=
at com.amazonaws.http.AmazonHttpClient.handleErrorResponse(AmazonHttpClient.java:798)

My code can be seen below:
I saved my AWS Access Key ID and AWS Secret Access key in the credentials.cfg file.
I have a file called payment.csv in a bucket called datalakesexamp1 in S3.
from pyspark.sql import SparkSession
import os
import configparser

config = configparser.ConfigParser()

config.read_file(open('aws/credentials.cfg'))

os.environ["AWS_ACCESS_KEY_ID"]= config['AWS']['AWS_ACCESS_KEY_ID']
os.environ["AWS_SECRET_ACCESS_KEY"]= config['AWS']['AWS_SECRET_ACCESS_KEY']

spark = SparkSession.builder\
                     .config("spark.jars.packages","org.apache.hadoop:hadoop-aws:2.7.0")\
                     .getOrCreate()

df = spark.read.csv("s3a://datalakesexamp1/payment.csv")

I believe that it could be the 2.7.0 version of hadoop but I can't seem to figure out where to find the correct one. I have tried other versions and seem to get similar errrors.


text:
Q: Picking compression algorithm for low-memory device - what works without being entirely in memory? I'm writing an app that, on a low-memory device, needs to be able to read the list of contained files and also extract specific (but random) files from a tarball (or some sort of archive).
Here's my question: can a bz2 tarball be "streamed" as it's decompressed (where "stream" means that I can read the list of files or extract a random file without reading the entire tarball into memory)?
What about for a gz tarball?
Are there any formats that are better or worse for this?
I have really tried to find this info online but I'm having trouble.

A: Yes. But you need to define "low" in "low-memory". All commonly-used compression formats stream. Though they also all have some amount of memory required for history information, independent of the length of the entire stream. E.g. ~4MB for bzip2, ~32K for zlib/gzip.


text:
Q: Jordan chevaley decomposition and cyclic vectors Suppose that $g \in GL_{n}(F)$ has jordan chevalley decoposition $ g=su$ where $s$ and $u$ denote the semisimple and unipotent parts respectively.
Is it true that if $g$ is cyclic (on the natrual action on $F^{n}$) then either $s$ or $u$ must also be cyclic?
I believe this to be true but I am stuck finding a proof.
**By cyclic I mean that there exists a non-zero vector $v \in F^{n}$ such that the vectors $v,g.v,\dots g^{n-1}.v$ span $F^{n}$.
Thanks

A: It's false.
Take $g=diag(I_2+J,-I_2+J)$ where $J$ is the nilpotent Jordan block of dimension $2$. $g$ is cyclic.
Then $g=su=diag(I_2,-I_2)diag(I_2+J,I_2-J)$. $s$ and $u$ are not cyclic.