text:
Q: Enumerating attached DVD drives in Linux / Java / Scala In my Scala (runs on top of Java) Application I would like to get a list of all drives that contain DVD media, e.g. something like this:

*

*/dev/scd0    Star Trek DS9 DVD1

*/dev/scd0    The 4400 DVD1

Not sure if it's possible to get the name of the disc, but the path is the important thing for me anyway.
I would prefer a pure Java / Scala solution (using file.io stuff). If that's not possible, accessing the right Linux files is fine, too (like /proc/something).
Thanks in advance!

A: I think you're out of luck with java.io.* but if you don't mind making calls out to Linux commands, you could assemble the data by:

*

*Calling "mount" and capturing the first column of output.

*Calling "volname" on each value you captured from step 1.

According to the man page for volname, it only returns data for ISO-9660 filesystems (e.g. DVDs), so any device path that returns empty can be ignored.

A: There is one (untested) possibility to get your drives with pure Java code. At least on Windows.
Its a little bit hacky and doesn't work under linux (because linux gets not as much integration love from sun I believe).
import javax.swing._
import javax.swing.filechooser._
val chooser = new JFileChooser()
val view = chooser.getFileSystemView()

The FileSystemView clas provides a few features such as asking the possible roots if they
are a drive (isDrive()). Swing uses this to present the file chooser with the right icons to
you so it should work under windows because IIRC it shows the correct symbols there. Under
Linux it unfortunately does only show the "/" root.
One of the reasons this doesn't work under linux could be, that the linux developers constantly change their preferred way of presenting such information to the user space. at the moment it is IIRC hal and dbus. Maybe SUN didn't want to publish a new java version each time this changes.
If pure java doesn't cut it maybe you could use a little bit of jni (which is not so hard to use anymore if you're using tools like JNA or such) to access the linux apis directly. I haven't done that but could try if you're interested.


text:
Q: How do I conditionally show text field in react? I have some categories in the folder structure by clicking on one of the folders or files and then clicking on the 'new' button. I need to add a text field below that in a tree structure. How can I achieve this?

In the above, I have a new button on the top right corner; selecting 'manufacturing' and clicking on the 'new' button text field should be added as shown in the image.

A: maybe you can try this code below

import {useEffect,useStatus} from 'react'
const Index = ()=>{
  const [type, setType] = useStatus(null)

  return <form>
    <input type="radio" name="type" value="type1" onChange={()=>setType('type1')} />
    <input type="radio" name="type" value="type2" onChange={()=>setType('type2')}/>
    <br />
    {type=='type1' && <input type="text" name="type1input" />}
    {type=='type2' && <input type="text" name="type1input" />}
  </form>
}

export default Index;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sequelize - fetch from a table that is not defined (but is created from association) I'm working on a new project and I'm facing this problem;
So let's say in sequelize the tables User and Project are defined.
In the DB, there is a third table ProjectsUsers, and I need to fetch from that.
This table only has columns like userId, createdAt, updatedAt, which are the default ones, so the table isn't defined in the model.
Should I define it (as an empty table) in the model (not sure if it would break things or not, but seems unlikely to work).
How can I query that table?

A: Just define a table with right association and you will be able to query on it.
For example:
var UserModel = sequelize.define('user', {},{});
var ProjectModel = sequelize.define('project', {}, {});
var ProjectsUsersModel = sequelize.define( 'ProjectsUsers', {}, {} );

UserModel.hasMany( ProjectModel );
ProjectModel.hasMany( UserModel )
CourseTopics.belongsTo( topicModel ).belongsTo( ProjectModel );

ProjectsUsersModel.findAll({include:[UserModel, ProjectModel]})
.success(function(projectsUsers) {
 });


text:
Q: EF Core Update Foreign Key in Disconnected Scenario I have a model class in my Blazor Server project as follows
public class TestModel
{
     public Client Client { get; set; }
     ... other value types follow etc.
}

My Client class is defined as below:
public class Client
{
    public string ClientID { get; set; }
    public string ClientName { get; set; }
    public ICollection<SetupModel> SetupModels { get; set; }
}

Client loads from a view and will never be updated by my application (users change its value using a dropdown). I am defining this as a one to many relation in OnModelCreating as each Client can have  many TestModels.
modelBuilder.Entity<Client>().HasMany(x => x.SetupModels).WithOne(x=> x.Client);

The ClientID shadow property of TestModel need to be updated whenever the user changes the Client in a dropdown. I am using local storage to handle drafts so it is not possible to use traditional entity tracking, as I often need to parse json back into the relevant classes. My first attempt was to use Entry.CurrentValues.SetValues:
using var context = Factory.CreateDbContext();
var existing = await context.SetupForm.SingleOrDefaultAsync(x => x.ID == model.ID);
context.Entry(existing).CurrentValues.SetValues(model);
await context.SaveChangesAsync();

SetValues doesn't work for reference properties, however, so I am stuck unable to update the foreign key on my TestModel in this disconnected scenario. I have spent several hours on this today and think I am overlooking something simple. How should I handle this scenario?


text:
Q: Error using vl_gmm - Attempt to execute script as function Hello I want to use Fisher Vector for my SIFT descriptors. I tried to use the function from VL_FEAT. I added the directory in MATLAB and also run vl_startup. It runs successfully but when I try the example
It gives me this error:
Attempt to execute SCRIPT vl_gmm as a function:
C:\vlfeat-0.9.19.tar\vlfeat-0.9.19\vlfeat-0.9.19\toolbox\gmm\vl_gmm.m

Anyone help me how can i solve this?

A: I have a couple of suggestions for you to get VLFeat working.  I'm not sure if you have tried them all, but I will suggest them as we go:
Suggestion #1 - Compiling VLFeat if you downloaded just the source
Did you only download the source files?  If you did, did you compile VLFeat first?  Specifically, did you run vl_compile first when you downloaded the source?
Functions like vl_gmm require a MEX wrapper to be compiled before you can use the function.   If you look in the toolbox/gmm directory, there are two files: vl_gmm.m and vl_gmm.c.  vl_gmm.m is simply a MATLAB file that contains the documentation on how to use the function.  The actual function is in vl_gmm.c and it is a MEX file.  You only get this error if you didn't compile VLFeat first because it's trying to run the .m file by default, which contains nothing but documentation.
As such, make sure you compile VLFeat by running the vl_compile.m script before trying to run your example.
Suggestion #2 - Download the pre-compiled binaries
Alternatively, you can get VLFeat pre-compiled by downloading the binaries: http://www.vlfeat.org/download/vlfeat-0.9.19-bin.tar.gz .  If you have trouble compiling the libraries, then download the actual pre-compiled binaries through the link I gave you, then try running vl_setup.m from there.


text:
Q: jQuery plugin, get .data() for original element I've created a dropdown jquery plugin. That hides a regular html select and adds a div and a number of child divs as options to show instead.
Following the general rule of thumb I am initializing the plugin like so:
$.fn.dropdown = function (options) {
    return this.each(function() {
        if (undefined === $(this).data('dropdown')) {
            var dropdown = new $.dropdown(this, options);
            $(this).data('dropdown', dropdown);
        }
    });
};

I am also copying any class given to the select element to the replacement div
When trying to get the data for the element by using a class as a selector, the selector is obviously returning the generated div in the element array.
This results in a 'data is not defined' error for the div.
Should I change something from the plugin or expect whoever uses the plugin to get the data by using an id instead of a class to select the element after initialization?

A: Well you really don't have many options here. Inside of you $.dropdown constructor just create one more data reference to this instance. It's quite cheap anyway since it's going to be just a object reference:
$.dropdown = function(element, options) {
    // ... newElement is what replaces original select
    newElement.data('dropdown', this);
};


text:
Q: how to match answers of questions stored in differnet lists in python? I have a external file where I stored all the questions. There is another file where I stored answers. I have converted the questions.txt file in to list. same thing I will do for answers.txt. I want to show random questions to user and then match the answer of that question. I also want to display what was the correct answer. I also want to prevent duplication of questions. There will be no options for the user. user have to give answer to his own.
Here is my code.
import random
def python():
   txt_file = open("python_mcqs.txt", "r")
   file_content = txt_file.read()
   #print("The file content are: ", file_content)

   content_list = file_content.split(",")
   txt_file.close()
   #print("The list is: ", content_list)
   question = []
   for x in content_list:
      question.append(x.replace("\n", ","))
   #print(list(question))
   i= 1
   while i<=10:

      question_display = random.choice(question).rstrip()
      user_answer = input(question_display)
      if user_answer.lower() == "yes": # it is just a testing condition. yes will replace answers
         pass
      else:
         pass

      i = i + 1

python()

Note: I am a beginner programmer. Please suggest me with simple code so that I can understand easily.

A: So the simplest way to go this would be to randomise the list of questions so that they're in a random order, and then you can just go through them one after another without having to pick a random one each time, which obviously could cause duplication
python's random library already has a function for this:
random.shuffle(question_list)

will randomly shuffle the list of questions for you (it doesn't return anything, it shuffles the list in-place)
Next, you'll need a way to add answers to your questions, this would be easiest to do by adding them into the same text file. In python, when you open a file, you can put it in a for loop to have it go through each line one-by-one
question_list = []
txt_file = open("python_mcqs.txt", "r")
for line in txt_file:
  question_list.append(line.split(", "))

With that code, you can store the questions in the text file like this

question 1, answer 1

question 2, answer 2

and they will be automatically converted into:
["question 1", "answer 1"], ["question 2", "answer 2"]

And so when you go through each question in the array you can simply do:
question_display = question[0]
answer = question[1]

to get the question and the answer


text:
Q: Where to put external archives to configure running in Eclipse? As a Java/Eclipse noob coming from a Visual Studio .NET background, I'm trying to understand how to set up my run/debug environment in the Eclipse IDE so I can start stepping through code.
I have built my application with separate src and bin hierarchies for each library project, and each project has its own jar. For example, in a Windows environment, I have something like:
c:\myapp\myapp_main\src\com\mycorp\myapp\main
...and a parallel "bin" tree like this:
c:\myapp\myapp_main\bin\com\mycorp\myapp\main
Other supporting projects are, similarly:
c:\myapp\myapp_util\src\com\mycorp\myapp\util
(and a parallel "bin" tree), etc.
So, I end up with, e.g., myapp_util.jar in the ...\myapp_util\bin... path and then add that as an external archive to my myapp_main project.
I also use utilities like gluegen-rt.jar, which I add ad external dependencies to the projects requiring them.
I have been able to run outside of the Eclipse environment, by copying all my project jars, gluegen-rt DLL, etc., into a "lib" subfolder of some directory and executing something like:

java -Djava.library.path=lib
  -DfullScreen=false -cp lib/gluegen-rt.jar;lib/myapp_main.jar;lib/myapp_util.jar;
  com.mycorp.myapp.Main

In the IDE, however, When I first pressed F11 to debug I got a message about something like /com/sun/../glugen... not being found by the class loader.
So, to debug, or even just run, in Ecplipse, I tried setting up my VM arguments in the Galileo Debug -> (Run/Debug) Configurations to be the command line above, beginning at "-Djava.libary.path...". I've put a lib subdirectory - just like the above with all jars and the native gluegen DLL - in various places, such as beneath the folder that my main jar is built in and as a subfolder of my Ecplipse starting workspace folder, but now the debugger can't find the main class:

java.lang.NoClassDefFoundError:
  com.mycorp.myapp.Main

Although the Classpath says that it is using the "default classpath", whatever that is.  Bottom line, how do I assemble the constituent files of a multi-project application so that I can run or debug in Eclipse?

A: if you want project A to have project B (and its libs) on its classpath, then goto project A's properties, select Java Build Path, then select the Projects tab.  Here you Add project B.
Although you may be generating jars for each project, eclipse doesn't pay much attention to the jars.  If you are going to have lots of java projects with lots of 3rd party dependencies, you may want to look at something like m2eclipse.

A: The recommended way of doing things is to configure the build path. This is a nice article describing the process.


text:
Q: How to change innerHTML without refresh or refresh and output with same button in javascript I am trying to create a random phrase generator with words. My problem is to get a new phrase I have to refresh the page first and then it creates a new phrase. I want it to generate phrase without refreshing whole page or at least generate and refresh with same button here is my code.
var output = "hai " + randomBodyPart + " come un "  + randomWord + " " + randomAdjective + "!";

//Pagereloder
            function myFunction() {
                location.reload();
            }

//Genretor Button
          var button = document.querySelector("button");
          button.addEventListener("click", function() {
                (document.getElementById("viewer").innerHTML= output);
          });

and here is HTML

Random word Genretor

<button class="btn">Click me</button><button class="btn" onclick="myFunction()">Relod</button>

Here

A: <button id="myButton">Click to change the number</button>

*

*Create the button and the container for the random text.

*Capture both elements.

*Add a listener to the button.

*When someone click the button you want to change the innerHtml, so, do it in the callback.

*I change the innerHtml with random numbers... its an example right =)

*The param evt its there because if you want to do something else with the event, you can erase that if you want.

*I give you a Bunny too:

*(|_/)

*( #.*)

*c(")(")

*ENJOY!

A: Throw your code into a function and make the button call that function:
            function myFunction() {
                var output = "hai " + randomBodyPart + " come un "  + randomWord + " " + randomAdjective + "!";
                document.getElementById("viewer").innerHTML= output
            }

//Genretor Button
          var button = document.querySelector("button");
          button.addEventListener("click", function() {
                myFunction();
          });

Also, the random generators must be inside thy function also.


text:
Q: ES6 default values for only some of params object Given a function like the following, what is the correct syntax to use in order to be able to call showToast({ text: "some text"}) and still get the default values for params.autoHide and params.action ?
function showToast (params = {text: 'Something happened!', autoHide: false, action: 'CLOSE'}) {
    //noinspection JSUnresolvedFunction
    const toast = $mdToast.simple()
        .textContent(params.text)
        .position('top right')
    ;

    if (!params.autoHide) {
        toast.hideDelay(false);
    }
    if (params.action) {
        //noinspection JSValidateTypes
        toast.action(params.action); // label for close btn
    }

    $mdToast.show(toast);
}

A: You can use object destructuring in the argument list too. The only thing that changes is you must not access the parameters through the params object:

function foo({text = "Hi", autoHide = false, action = "CLOSE"} = {}) {
  console.log(text + " " + autoHide + " " + action)
}

foo({text: "asd"});

See babel/repl.
Notice the = {} default value for the destructuring object. This makes it possible to call the function without a single parameter: foo();.

A: You can use parameter object destructuring to achieve this:
function showToast({text = 'Something happened!', autoHide = false, action = 'CLOSE'} = {}) {
    //noinspection JSUnresolvedFunction
    const toast = $mdToast.simple().textContent(text).position('top right');

    if (!autoHide) {
        toast.hideDelay(false);
    }
    if (action) {
        //noinspection JSValidateTypes
        toast.action(action); // label for close btn
    }

    $mdToast.show(toast);
}

showToast({ text: "some text" }) // defaults autoHide to false, action to 'CLOSE'

See "Setting a function parameter's default value".


text:
Q: Pull data from multiple records into one row I want to pull out the data from multiple records and insert them into different fields of a single record in another table. The work I am doing requires me to pull the cw_cat_total field(which is the sum of all the assignments corresponding to a particular category of assignment and put the appropriate data into the fields of another table.
The cw_cat_total field was calculated from a self-joined relationship. I just could not figure out how to get the individual component into the different columns of the table in the second picture.

Can anyone Filemaker programmers help me out here?
Update:
My database certainly contains more tables. It is quite complicated (from my point of view). Below is the ER graph.

What I try to achieve is to pull the component scores into the different columns of the results table so that a student's assignment score may be computed with different weightings for the different category. This coursework score, together with what the student scores for the examination at each quarter(term), will then be displayed in the reports table.
As a side note, I am a teacher of the school (not a developer). Hence, my schema may not be what the industry normally practiced. I did read up about database normalisation and think I understand (which I may not, I'm not sure). I tried my best to design around what I think the industry practices. If my ER graph is seriously flawed that affect implementing what I want to do, please point it out so I can redesign the entire database. I will need to compute the overall results (from results table) base on different weighting of different terms in the report of term 4. But I think that problem is similar to this.

A: Traditional Method: (Works for FileMaker 7 onward)
Traditionally the way to do this in FileMaker is to create additional Table Occurrences of the Coursework_Results table that are related on both "_kf_resultID" and on "type".
1: On your "Results" table create a new calculation field for each type of coursework_result. Let us use "Classwork" as the example.

*

*Name the new field _k_Classwork

*Make the field type Calculation

*Set the calculation to be type Text

*Set the calculation to return the string "Classwork"

*Uncheck "Do not evaluate if all referenced fields are empty"

Repeat this process for every "type" in the "coursework_results" table data.
2: For each "type" make a new Table Occurrence of your "Coursework_results" table. Name it "Coursework_results_Classwork". Link it to the "Results" table in the following way:
Results::_kp_resultID     \____________/ Coursework_results_Classwork::_kf_resultID
Results::_k_Classwork     /            \ Coursework_results_Classwork::type

Repeat this process for every "type" in the "coursework_results" table data.
3: Set the calculation of "classwork_percent" to be:
Sum ( Coursework_results_Classwork::mark ) / Sum ( Coursework_results_Classwork::max_mark )

Then set up the other _percent fields similarly, based on their own newly created table occurrences. (ex: Coursework_results_Quiz::mark and Coursework_results_Project::mark)
Execute SQL (Works for FileMaker 12)
FileMaker 12 gives you the new ExecuteSQL step which you can use to skip setting up new schema in your database. In this case, all you would need to do is modify the "classwork_percent" field to have the calculation:
ExecuteSQL(
    "SELECT
        SUM(mark)
     FROM
        Coursework_results
     WHERE
        _kf_resultID = ?";
     ""; ""; _kp_resultID)

For more information check out FileMaker's page: http://www.filemaker.com/12help/html/func_ref3.33.6.html
Also check out the FileMaker SQL Sugar ("@") Module for help building queries: http://www.modularfilemaker.org/2013/03/filemaker-sql-sugar/


text:
Q: Why does IE table-cell displays only when it has content? This is the HTML

      First Name(*):

          <asp:Label ID="lblFirstName" runat="server" ></asp:Label>

      Middle Name

          <asp:Label ID="lblMiddleName" runat="server" ></asp:Label>

      Last Name(*):

         <asp:Label ID="lblLastName" runat="server" ></asp:Label>

And this is the css
.contact-table th,
.contact-table td
{
   border: 1px Black solid;
}

For FF and Chrome, things are working perfectly, i.e. th and td have 1px black border around. However, for IE, only td that have content have border.
Any reason for that?
EDIT
When I add this .contact-table td span
.contact-table th,
.contact-table td,
.contact-table td span
{
   border: 1px Black solid;
}

The empty cells have border in IE, but then those cells that had border before, have an extra border inside the cells.
EDIT
When I change the rules this way
.contact-table th,
.contact-table td span
{
   border: 1px Black solid;
}

.contact-table td span
{
   width: 100%;
}

It working perfectly for IE, but FF and Chrome now display small border that wrap only the text.
Is there a way to tell css to apply different rules depending on the browser?

A: Do you have empty-cells: show set?
See: http://msdn.microsoft.com/de-de/library/ie/cc848860(v=vs.85).aspx


text:
Q: Custom pipeline operators with MongoDB Aggregation Framework Actually, I use map reduce to make some calculations.
I can't do that with the aggregation framework because there is no available pipeline operators for my calculations.
Is it possible to write custom pipeline operators?
Thanks in advance

A: The answer will depend on your definition of "possible":
1) Out of the box: NO.
As at MongoDB 2.2 there is no end user feature to allow you to add new pipeline operators.  The Aggregation Framework and pipeline operators are implemented in C++ for improved performance and concurrency over earlier aggregation options such as MapReduce (which is implemented in JavaScript).
2) If you want to write one in C++: YES (but not trivial).
MongoDB is an open source project, so you do have the option of diving into the C++ code and implementing additional functionality yourself (see: src/mongo/db/pipeline). Note that there are guidelines on Contributing to the MongoDB project and ongoing development is extremely active.
If you want to write custom functions, your best option at the moment is to continue using MapReduce.
Regardless of the above options, if there is a pipeline operator or feature you'd like to see please do suggest it in the MongoDB Jira SERVER project (component: Aggregation Framework).  This will allow others to comment, watch, and vote on the feature request .. and if you do end up implementing the feature yourself you can reference the Jira feature description in your pull request.  Before submitting a new feature request, you should also search to see if perhaps this feature has already been suggested.
For example, there are already requests such as:

*

*SERVER-4929: $group should have a $median accumulator

*SERVER-5044: $stdDev aggregation operator for standard deviation

*SERVER-7463: More operators for Aggregation Framework (percentile, top)


text:
Q: left_join(x,y) and NA After seeing this post with a nice answer by @akrun, I wanted to play with dplyr. Here are the sample data from the post and akrun.
df = data.frame(
      id1 = c(1,1,2,2,2,3,3,3,3),
      id2 = c(1,2,1,2,3,1,2,3,4),
      X1 = letters[1:9],
      X2 = LETTERS[1:9],
      stringsAsFactors = FALSE
     )
df2 <- data.frame(
      id1 = rep(c(1:3), each = 4),
      id2 = rep(c(1:4), times = 3),
      stringsAsFactors = FALSE
     )

If I replicate akrun's answer, merge() perfectly works here.
df %>%
    do(merge(., df2, by = c("id1","id2"), all = TRUE))

   id1 id2   X1   X2
 1    1   1    a    A
 2    1   2    b    B
 3    1   3 <NA> <NA>
 4    1   4 <NA> <NA>
 5    2   1    c    C
 6    2   2    d    D
 7    2   3    e    E
 8    2   4 <NA> <NA>
 9    3   1    f    F
 10   3   2    g    G
 11   3   3    h    H
 12   3   4    i    I

Then, I thought left_join(x,y) would do. left_join(x,y) includes all of x, and matching rows of y. From the examples in the dplyr tutorial pdf from UseR!2014, I expected an identical result. But, that was not the case.
> df %>%
+     left_join(df2, .)
Joining by: c("id1", "id2")
   id1 id2   X1   X2
1    1   1    a    A
2    1   2    b    B
3    1   3 <NA> <NA>
4    1   4 <NA> <NA>
5    2   1 <NA> <NA>
6    2   2 <NA> <NA>
7    2   3 <NA> <NA>
8    2   4 <NA> <NA>
9    3   1 <NA> <NA>
10   3   2 <NA> <NA>
11   3   3 <NA> <NA>
12   3   4 <NA> <NA>

The first three rows indicate that dplyr was doing the right job. But, once it encountered NA, it generated NAs till the end. Is this a bug or did I do something wrong? Thank you for taking your time.

A: There are currently a few bugs with dplyr and the _join functions:

*

*https://github.com/hadley/dplyr/issues/542

*https://github.com/hadley/dplyr/issues/455

*https://github.com/hadley/dplyr/issues/450
I looks like they are being fixed. In the mean time, if you make sure the group-by variables are the same type (they aren't in your example - you can tell by using str()), then it should work:
df = data.frame(
  id1 = c(1,1,2,2,2,3,3,3,3),
  id2 = c(1,2,1,2,3,1,2,3,4),
  X1 = letters[1:9],
  X2 = LETTERS[1:9],
  stringsAsFactors = FALSE
)

df2 <- data.frame(
  id1 = as.numeric(rep(c(1:3), each = 4)),
  id2 = as.numeric(rep(c(1:4), times = 3)),
  stringsAsFactors = FALSE
)

left_join(df2, df)


text:
Q: What is the max output length of a baseX encoding using "bitcoin style leading zero compressing"? Given a baseX encoding using a "bitcoin style leading zero compression" and an input of n bytes, what is the maximum number of characters for the encoded string?
I know the answer for traditional base64 encodings, but I couldn't find an answer for this type of encoding, and I'm not entirely clear on the algorithm used.
For example, base64 encodes n bytes of input to an output string of length 4 * ⌈n / 3⌉ (or in code e.g.: (n+2) / 3 * 4). But what is the output length of the linked encoding algorithm? (I'm mainly interested in a sensible upper bound.)


text:
Q: Sticky footer doesn't work with Angular 5 Here is my Angular project:
https://stackblitz.com/edit/angular-1g7bvn
I've tried getting the sticky footer from this example to work with no avail:
html {
    height: 100%;
    font-family: sans-serif;
    text-align: center;
}

body {
    display: flex;
    flex-direction: column;
    height: 100%;
    margin: 0;
}

header{
    flex-shrink: 0;
    background: yellowgreen;
}

.content {
    flex: 1 0 auto;
    background: papayawhip;
}

footer{
    flex-shrink: 0;
    background: gray;
}

There must be something small I'm doing wrong but I can't see it.

A: Angular is rendering your components as tags, so in your case my-app component is an actual tag on the DOM tree.

  <my-app>

  </my-app>

And all of your styles are applied to the body tag. If you add to your app.component.css your styles from body with a :host selector - it will work just fine.
:host {
  display: flex;
  flex-direction: column;
  height: 100%;
  margin: 0;
}

here's a stackblitzz example

A: Add below to your CSS.
footer{
  position: fixed;
  bottom: 0;
}

StackBlitz


text:
Q: Unable to execute cell -script using java process executor I am trying to run shell script using java process executor.It works fine for me when i am using it for PING command , however unable to produce any impact over DUMP command. Here is the code which one i am trying.
  import java.io.BufferedReader;
  import java.io.InputStreamReader;

  public class ExecuteShellComand {

public static void main(String[] args) {

    ExecuteShellComand obj = new ExecuteShellComand();

    String domainName = "www.google.com";
    String command1 = "ping -c 3 " + domainName;
    String command = "pg_dump -U kalculate Kalculate_4.1_final -f testfinal11.sql";
    String output = obj.executeCommand(command1);
    obj.executeCommand(command);
    System.out.println(output);

}

private String executeCommand(String command) {

    StringBuffer output = new StringBuffer();

    Process p;
    try {
        p = Runtime.getRuntime().exec(command);
        p.waitFor();
        BufferedReader reader =
                        new BufferedReader(new InputStreamReader(p.getInputStream()));

                    String line = "";
        while ((line = reader.readLine())!= null) {
            output.append(line + "\n");
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return output.toString();

   }

}

Here obj.executeCommand(command); is not making any impact.Any help will be appreciable.

A: I think that you have to separate the parameters into separate variables or strings.
Example:
From:
String command1 = "ping -c 3 " + domainName;
String command = "pg_dump -U kalculate Kalculate_4.1_final -f testfinal11.sql";
String output = obj.executeCommand(command1);

To:
String command1 = "ping";
String parameter01 = "-c";
String parameter02 = "3";
String output = obj.executeCommand(command1, parameter01, parameter02, domainName);


text:
Q: Typecast two model and Return other model    public static  Coupons.Domain.RejectedCoupons CoupontoRej(Coupons.Domain.Coupon coupon)             {
            Coupons.Domain.RejectedCoupons a = coupon;
           return a;

    Help me out , getting Error ,
    not working for me
Error   2   Cannot implicitly convert type 'Com.Arpur.Coupons.Domain.Coupon' to 'Com.Arpur.Coupons.Domain.RejectedCoupons'  C:\Users\Agha\Desktop\Coupon\Com.Arpur.Coupon.User\Helpers\ExtensionMethods.cs  71  48  Com.Arpur.Coupon.User

A: At first glance it seems that RejectedCoupons is not a base class of Coupons so implicit casting is not going to work (unless to have some implicit conversion operator in place)
Why not create a new RejectedCoupons and fill it with the properties of coupon
return new RejectedCoupons {
    prop1 = coupon.prop1,
    prop2 = coupon.prop2,
    ...
}


text:
Q: Custom WordPress Feeds operators? I wish to create a feed of my blog which is a feed of two categories OR the feed of some tag and not the feed of some other category
I know how to do "have a feed of this1 + this2 categories", but how do you do "OR" in a feed URL? (and in general, is more complex operators on the URL possible, and how?)
Links that don't answer the question (but help define it):

*

*http://lorelle.wordpress.com/2006/03/27/customizing-rss-feed-links-for-wordpresscom-and-wordpress-sidebar-widgets/

*http://dailycupoftech.com/2007/07/25/creating-custom-wordpress-feeds/

A: Feeds are essentially WordPress Loop with customized template. So it will take regular query_posts() arguments in URL. For example see /wp-includes/feed-rss2.php template.
Since query_posts() doesn't handle OR logic you describe it isn't possible with URL alone.
You will have to write your own feed template that runs and concatenates two sets of post. I think it will work simply as page template, but can also be hooked into existing feed mechanics, see do_feed().


text:
Q: Typescript TypeError: ......toDateString is not a function I am new to typescript and this might be something very trivial. Please help.
I am trying to extract minutes and seconds from typescript Date variable.
I have a variable timestamp declared as Date. But when I try to use functions on it like toDateString() or getMinutes() or getTime(), I get the above error saying TypeError: timestamp.getMinutes() is not a function.
Thanks.

A: It's likely that your timestamp is not a date, just a number that represents the number of milliseconds since the Unix epoch.
All you need to do is convert your timestamp to a Date, like this:
let currentDate = new Date(timestamp);

Then you can call any Date functions you want on it.

A: You can use the Angular DatePipe to achieve this-
{{current_date | date: 'shortTime'}}

You can find more information here -
https://angular.io/api/common/DatePipe

A: toDateString() is not a function is showing because u may used it with any variable
toDateString() is a method which can be used with a date object only


text:
Q: Did the Ewoks continue to think C-3PO was a god? In Return of the Jedi, our heroes are taken prisoner by Ewoks -- except for C-3PO:

THREEPIO: I could be mistaken. They're using a very primitive dialect.  But I do believe they think I am some sort of god.

Later on, the Ewoks plan to cook and eat our heroes:

THREEPIO: I'm rather embarrassed, General Solo, but it appears you are to be the
  main course at a banquet in my honor.

Luke uses the Force to lift up C-3PO and make him fly around. This makes the Ewoks afraid that C-3PO has magic powers, so they do as he says and free Luke and the others. C-3PO then tells them the story of the Rebellion, and they agree to help fight the Empire.
Did the Ewoks continue to think C-3PO was a god? Or did he explain that he was just a protocol droid?
If it's the former, then Threepio had a point: It is somewhat unethical to manipulate a Stone Age people by impersonating one of their gods, especially if you're persuading them to make war on the Galactic Empire.

A: According to the film's official novelisation, the Ewoks did indeed continue to believe that Threepio was a god, but that the decision to fight on the side of the Rebellion was taken largely because they'd shown themselves to be friends of the Ewoks ("leafbrothers") where the Empire had shown themselves to be enemies of the 'Great Forest' rather than simply because their god told them to:

Threepio translated for his friends: 'Honorable Elders, we have this
  night received a perilous, wondrous gift. The gift of freedom. This
  golden god …' - here Threepio paused in his translation just long
  enough to savor the moment; then went on - '… This golden god, whose
  return to us has been prophesied since the First Tree, tells us now he
  will not be our Master, tells us we are free to choose as we will -
  that we must choose; as all living things must choose their own
  destiny. He has come, Honorable Elders, and he will go; no longer may
  we be slaves to his divine guidance. We are free.


text:
Q: Negative numbers: "minus" or "negative"? I noticed that when negative number are used in speech, there are two dominant patterns. Taking "-10" as an example, in some cases it is pronounced "negative ten", while in others it is "minus ten".
I could not find any rules for this. A discussion in MathOverflow (which was closed) suggested that using negative was introduced in the US by "New Math" since the 1960's. If this is true, I would expect non-American speakers to mainly use minus (which I think is similar to the usage in most foreign languages), and perhaps senior Americans as well.
I'm not asking for opinions about this argument here. I'm also not looking for explanations or reasons for preference of one or another or the like.
I am looking for

*

*References for authoritative text if there is any

*Evidence of usage: I'd like to know how different dialects call negative numbers, and if there are rules or conventions for using e.g. "minus 40" or "negative 40" in different contexts in the same dialect.

A: Probably this extract from Merriam-Webster's Guide to Everyday Math may help:

Among the more commonly confused mathematical terms, minus and negative have the dubious honor of confounding teachers as well as students. The word minus refers to the operation of subtraction, not to negative numbers.

A: There is a difference here between common practice and good practice.
It is good mathematical practice to distinguish between positive and negative numbers, which entails that you should say "negative ten" for the number that is ten less than zero. It is also good mathematical practice to say "minus ten" if you mean to subtract positive ten from something.
Because, however, the minus sign is used in mathematics to designate (1) negative numbers, (2) the operation of subtraction, and (3) additive inverses, it is very common for people, even mathematicians, to use "minus" in speech indiscriminately for all three.

A: '−' is an operator, and it is pronounced 'minus'.
'Positive' and 'negative' are properties of numbers, as are 'even' and 'odd'.
−7 has the property of being an odd number, and the property of being a negative number, and has many other properties besides.
−x may or may not be an odd number or a negative number. It would therefore be completely wrong to say '−x' as 'negative odd x'. (I am listing two obvious properties to highlight the absurdity of so doing).
To say 'minus x', but 'negative seven' is confusing (as can be seen by the question posed in this thread), and absurd because it is not the properties that we list when we are saying the number, but its value.
The value of '−7' is 'minus seven', and its properties are 'negative', 'odd', ...


text:
Q: Can I use nullptr as a Linux system call parameter? I'm developing a user space application on Raspbian in C++11.
ReSharper++ advises me to use nullptr instead of NULL in the following system call:
auto ret = timerfd_settime(this->_timer_fd, 0, &timeout, NULL);
assert(0 == ret);

I think that I should stay with NULL because this library is dedicated for system programming in C.
What is the best practice in this situation?

A: Both NULL and nullptr will work fine. However, since this is syspro in C, I would go with NULL, because it's what I see more often (if not always) in that field.
If you check the reference of your system call, you will see that everywhere NULL is mentioned, not nullptr, something which you should expect (if not make sure you 'll read the following answer).
Check also NULL vs nullptr.

A: I would stay with nullptr because the intention is more clear.
There is a implicit conversion of nullptr to pointer for any type so you are definitely safe.
cppreference.com:

The keyword nullptr denotes the pointer literal. It is a prvalue of
  type std::nullptr_t. There exist implicit conversions from nullptr to
  null pointer value of any pointer type and any pointer to member type.


text:
Q: After showing output using jQuery ajax the value doesn't pass using PHP post method Hi I try to sum two data using AJAX and display it into hidden text input after that, I will pass the variable using PHP post method.
There are no problems in my jQuery AJAX code but the problem is after I submit the button, the value I retrieve from textbox total_rec[] is blank.
Here's my code below.
HTML:
<form method="post" action="<?php echo base_url() ?>user/recitem_insert">

Test

<input type="hidden" name="last_item_rec[]" value="<?php echo $row->rec_qty; ?>">
<input type="text" name="item_rec[]" id="txt" disabled="">
<input type="hidden" name="total_rec[]" value="">

</form>

JQUERY AJAX:


text:
Q: RewriteCond redirect to subdomain not working I cant make the rule to redirect the web page to a subdomain:
if the url starts with /tag like this:
http://www.my-website.com/tag/music

it should be redirected to:
http://blog.my-website.com/tag/music

I've tried this:
RewriteCond %{HTTP_HOST} ^www\.my-website\.com$ [NC]
RewriteRule ^/tag/?(.*)$ http://blog.my-website.fr/tag/$1 [QSA,L,R=301]

but it not redirecting.. it stays on www.
What am i doing wrong?
Thanks

A: try
RewriteCond %{HTTP_HOST} ^www\.my-website\.com$
RewriteCond %{REQUEST_URI} ^/tag/?(.*)$
RewriteRule ^/tag/?(.*)$ http://blog.my-website.fr/tag/$1 [QSA,L,R=301]

EDIT:
oooh k... remove the extra ? from the rule and should work.
RewriteRule ^/tag/(.*)$ http://blog.my-website.fr/tag/$1 [QSA,L,R=301]

A: This is the code you should be using in your .htaccess:
Options +FollowSymLinks -MultiViews
RewriteEngine on

RewriteCond %{HTTP_HOST} ^(www\.)?my-website\.com$ [NC]
RewriteRule ^tag/ http://blog.my-website.fr%{REQUEST_URI} [NC,L,R=301]

A: If this in an .htaccess file you mustn't have the leading / in RewriteRule patterns:
RewriteRule ^tag/?(.*)$ http://blog.my-website.fr/tag/$1 [QSA,L,R=301]


text:
Q: React native gradle build fail : "node -e console.log(require('react-native/cli').bin);" : command fail I try to run my React Native app in an android emulator on a fresh Ubuntu 18.04 installation.
In Android studio, gradle build failed with this error :
[org.gradle.api.Script] :ReactNative:Running '[node, -e, console.log(require('react-native/cli').bin);'] command failed.

[org.gradle.internal.buildevents.BuildExceptionReporter] * Where:
[ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter] Script '/home/melvine/DevProjects/production/evener/mobile/node_modules/@react-native-community/cli-platform-android/native_modules.gradle' line: 179

However, when I run the following command in the project folder, it runs successfully.
$ node -e "console.log(require('react-native/cli').bin);"

/home/melvine/DevProjects/production/evener/mobile/node_modules/react-native/node_modules/@react-native-community/cli/build/bin.js

What is wrong ?

A: I found the solution. I have installed NodeJS using nvm but (I don't know why) Gradle can't execute it. So I installed node with apt-get and now everything work well.


text:
Q: Struts 2 Execute action instead of welcome file I'm working on a Struts 2 application and I want to execute an action (in fact I'm interested more on executing an interceptor) instead of simply showing a welcome file. What is the best way to achieve this?
Thanks in advance!

A: Either redirect to the action from the welcome file, or use the action URL as a welcome file entry.
To do the latter, you'll likely need to set dispatcher elements on the  element:
<filter-mapping>
    <dispatcher>REQUEST</dispatcher>
    etc.

Add FORWARD, INCLUDE, and ERROR as well, and the normal filter name/url.

A: You have two well defined option both have been mentioned by Dave in his post.he has already described the Dispatcher option and other is to use redirection something like
<head>
    <META HTTP-EQUIV="Refresh" CONTENT="0;URL=example/MyAction.action">
</head>


text:
Q: What do #@+ and #@- in PHP comment blocks mean? I've seen several PHP files where there are some special characters at the beginning of a doc block.
It starts with /**#@+ some doc-text */ and ends with /**#@-*/.
What do these symbols mean?
I found that this seems to be used in various PHP frameworks (Zend, phpseclib, Magento) but couldn't find an explanation.
Example:
/**#@+
 * Constants for keys of data array. Identical to the name of the getter in snake case
 */
const ID = 'id';
const CUSTOMER_ID = 'customer_id';
const REGION = 'region';
const REGION_ID = 'region_id';
const COUNTRY_ID = 'country_id';
const STREET = 'street';
const COMPANY = 'company';
const TELEPHONE = 'telephone';
const FAX = 'fax';
const POSTCODE = 'postcode';
const CITY = 'city';
const FIRSTNAME = 'firstname';
const LASTNAME = 'lastname';
const MIDDLENAME = 'middlename';
const PREFIX = 'prefix';
const SUFFIX = 'suffix';
const VAT_ID = 'vat_id';
const DEFAULT_BILLING = 'default_billing';
const DEFAULT_SHIPPING = 'default_shipping';
/**#@-*/

A: They are used for DocBlock templates (see Wikipedia).

A: I also came across this in the wordpress config template.
It is a way to reduce maintaining duplicate comments on related items when doing phpdoc comments.  It is a feature of the phpDocumentor tool and there isn't really a spec although there are some proposed spec documents floating around for phpdoc (those proposals don't mention this functionality).
Using these starting/ending patterns tells phpDocumentor to apply this phpdoc comment to all items between the start and end markers.
/**#@+
 * documentation comment for "stuff"
 */
...multiple of the same thing to document...

/**#@-*/

The only documentation I could find was at manual.phpdoc.org.
docs.phpdoc.org doesn't appear to have any reference to this functionality for whatever reason.
The wiki page linked in the answer from ArSeN was edited to remove most of the copy/pasted documentation in Oct 2018.  Here is a link to the historical version of the page before it was removed.
https://en.wikipedia.org/w/index.php?title=PHPDoc&oldid=863927054#DocBlock_Templates


text:
Q: Using Coroutines inside splashscreen Hi i have made my own splashscreen in jetpack compose and i want to be able to use coroutines.launch within this screen. Though when i try to do this i get an error and it tells me to import so i click import and it does but still there is an error. I have no clue why. Is it okey to use coroutines inside splashscreen? Here is my code...
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

@Composable
fun SplashScreen(navController: NavController, viewModel : SplashViewModel = hiltViewModel()){
    val coroutineScope = rememberCoroutineScope()
    Surface(modifier = Modifier.fillMaxSize()) {

        val overshootInterpolator = remember {
            OvershootInterpolator(2f)
        }

        val scale = remember {
            Animatable(0f)
        }
        LaunchedEffect(key1 = true){
            scale.animateTo(
                targetValue = 1f,
                animationSpec = tween(
                    durationMillis = 500,
                    easing = {
                        overshootInterpolator.getInterpolation(it)
                    }
                )
            )
            delay(Constants.SPLASH_SCREEN_DURATION)
            navController.popBackStack()
            viewModel.checkIfUserExists()
            CoroutineScope.launch {

                viewModel.event.collect{event ->
                    when(event){
                        is AuthEvent.Success -> navController.navigate(PaperSellerScreens.CustomerListScreen.name)
                        is AuthEvent.Failure -> navController.navigate(PaperSellerScreens.LoginScreen.name)
                    }
                }
            }
        }
        val painterIcon = painterResource(R.drawable.logo_size_invert)
        val painterBackground = painterResource(id = R.drawable.paper_seller_background)
        Box(modifier = Modifier.fillMaxSize()){
            Image(painter = painterBackground, contentDescription = "SplashScreen",contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize())
            Image(painterIcon, "Icon Image", modifier = Modifier
                .size(200.dp, 200.dp)
                .scale(scale.value)
                .align(
                    Alignment.Center
                )
                .clip(RoundedCornerShape(10.dp)))
        }
  }
}

A: You can use collectAsState without CoroutineScope.launch
val event by viewModel.event.collectAsState(initial = AuthEvent.Checking)
when(event){
   is AuthEvent.Success ->  ...
   is AuthEvent.Failure ->  ...
   is AuthEvent.Checking -> // do nothing
}


text:
Q: Angular 4 dynamic component loading using a json schema I am in process on creating a small poc to try whether is it possible to load components according to a given json data structure. json will provide and array of component selectors. I tried a small example according to the reference materials i found via online. I used the "componentFactoryResolver" which is recommended way by Angular
I basically create couple of components and registered it with the entrycomponent decorator as follow in my module
entryComponents: [PersonalDetailsComponent, ContactDetailsComponent],

and in my app component i use the following code
  @ViewChild('dynamicInsert', { read: ViewContainerRef }) dynamicInsert: ViewContainerRef;
  constructor(private componentFactoryResolver: ComponentFactoryResolver) {
  }
  ngAfterViewInit() {
    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(PersonalDetailsComponent );
    const componentFactory2 = this.componentFactoryResolver.resolveComponentFactory(ContactDetailsComponent);
    this.dynamicInsert.clear();
    this.dynamicInsert.createComponent(componentFactory);
    this.dynamicInsert.createComponent(componentFactory2);
  }

and as you see i have to create component for each and every component i use. but having this an inside a loop might not be the best way to do it. i would much appreciate if any one could give me some heads up to do it in a proper way.
my actual json would look like something like this
{
         "step":"1",
         "viewed":false,
         "stepDependant":{
            "parentComponent":null,
            "childComponent":null,
            "varMap":null
         },
         "widgets":[
            {
               "Component":"shipper",
               "inputs":[
                  {
                     "ServiceLine":"Export"
                  }
               ],
               "outputs":[

               ],
               "name":"Shipper Details"
            },
            {
               "Component":"shipper",
               "inputs":[
                  {
                     "ServiceLine":"Export"
                  }
               ],
               "outputs":[

               ],
               "name":"Consignee Details"
            },
            {
               "Component":"status-of-shipment",
               "inputs":[

               ],
               "outputs":[

               ],
               "name":"Status of Shipment"
            }
         ]
      }

much appreciate your inputs

A: As you have already found the componentFactoryResolver is the correct way to create components dynamically from code.
With this approach what I would do in your case is create a map or service that maps the component selectors to component types. This way you can then quickly lookup the type when you are creating the dynamic components from the JSON data. From the types you then resolve the factory and then add the components like in your sample.
If you have a predefined set of components that are known another alternative would be to define them all as <ng-template> in the parent component like this:
<ng-template #shipper><shipper ></shipper></ng-template>
<ng-template #statusOfShippment><status-of-shipment ></status-of-shipment></ng-template>

Then you can get the templates in the component by using the @ViewChild decorator.
@ViewChild('shipper')
shipperTemplate: TemplateRef<any>;
@ViewChild('statusOfShippment')
statusOfShippmentTemplate: TemplateRef<any>;

And then you can create the components in a simmilar fashion than with the factory.
this.dynamicInsert.createEmbeddedView(shipper);
this.dynamicInsert.createEmbeddedView(statusOfShippment);

What is good about this approach is that you can still have classic template binding and send a different context object to every template.
<ng-template #shipper><shipper [ServiceLine]="ServiceLine"></shipper></ng-template>

this.dynamicInsert.createEmbeddedView(shipper, {ServiceLine:"Export"});

This way you could directly send an object created from your JSON and configure the component bindings. If you use the component factory you need to set everything from code manually.


text:
Q: Entity Framework - Oracle Column Type I am having a problem with EF-Oracle usage.
I working on a DB in which an ID field is defined as NUMBER(5). The real value of the field in the DB starts with 95xxx. EF automatically defines this field as short which cannot be more than 32xxx. I cannot change the field type since there are lots of apps running based on the DB.
I am wondering if there is a way to dismiss the error in the Entity model side.
(I am using EF 5)
Thanks in advance.

A: You should take this opportunity to upgrade your Oracle drivers and EF stack.
Oracle has shipped 100% managed code driver in a NuGet package called Oracle.ManagedDataAccess.


text:
Q: Quantization Uniform Let the output of image sensor take values between 0 to 10. If the samples are quantized uniformly to 256 levels, show that transition and reconstruction levels are
$$t_k=\dfrac{10(k-1)}{256},\, k=1,\cdots,257$$
$$r_k=t_k+\dfrac{5}{256},\, k=1,\cdots,256,$$
respectively.
I asked the first formula, but the second I don't know how i will be able to do ...

A: It seems "transition levels" refers to the output levels at which there is a transition in the quantized value. Quantizing the interval from $0$ to $10$ uniformly with $256$ levels leads to $256$ intervals of length $10/256$ each, and the $257$ values $t_k$ are the boundary values of those intervals: $0,10/256,20/256,\dotsc,10$. Then when you want to reconstruct an output level from a quantized level, your best guess (e.g. in the sense of mean error or root mean square error) is the midpoint of the interval, and indeed the $256$ values $r_k$ are the midpoints of the intervals: $5/256,15/256,\dotsc$.


text:
Q: How do I search for profiles online without logging into the game? I'm too poor to get this nice game but I would like to search players' profiles.
How can one find players' profiles via a web search or some similar method?

A: It seems like you cannot search for the profiles any more, but on the site
http://www.rankedftw.com/
You can search for the player name. There you see this ladder  symbol:  which leads to a stats page, which should give you an idea of the skills of that player

A: You could use SC2Ranks (no longer a valid website) to find stats on individual players.  On each player page is a link to their official profile page on Battle.net.
For example, my (sad) stats: Ewal
And near the upper left corner of that page is the link to my profile page: Ewal on Battle.net

A: If you ever do need to sign in, you can get a Battle.net account for free. You can even get a free Starcraft II Starter Edition account since August 2011.
It allows you to play online as Terran on a limited amount of maps.
Sign up here:
https://eu.battle.net/account/sc2/starter-edition/
A few more (perhaps outdated) details here:
http://www.gamew0rld.com/starcraft-ii-starter-edition/


text:
Q: Преобразование массива ArrayList в ресурс-массив Как преобразовать ArrayList в массив-ресурс?
<string-array name="name">
        <item>0</item>
        <item>3</item>
        <item>4</item>
        <item>5</item>
    </string-array>

A: Никак. Ресурсы создаются на этапе компиляции и их невозможно изменять в рантайме. Только читать.


text:
Q: Get-Dhcpserverv4XXX invalid class cimException dhcpserverv4reservation cmndlit but im getting a Invalid class cimExcetion Error Get-dhcpserverv4reservation -computername 192.168.x.x
any help wouls be appreciated

A: somehow the windows feature got uninstalled i just needed to reinstall it


text:
Q: can anyone tell me how to fix this on click listener error?
show me some error. can anyone tell me how to fix this error

A: Add { after onClick(View view) to correct mistake.
You should also click Alt+Enter to add a proper library to your java file.

A: Press Alt+Enter to import the clickListener and format your code .

A: remove bracket which is below startActivity() and also change the "S" of startActivity() with small letter like "s" e.g. startActivity(numberIntent) and press Alt + Enter on OnClickListener.


text:
Q: When embedding an OLEObject (Word/XLS/PDF doc) in Excel, how can I set the icon's position relative to the attachment button? I'm trying to create a button that will allow me to attach Word/Excel/PDF files. I've read a bunch of other articles and tutorials, so I now have the button and a VBA macro that gives me a dialogue box to browse to my file of choice. The file can be selected and embeds in the Excel fine.
Issue I'm having is with getting the position of the embedded file to sit next to the button I've created. At the moment it always defaults to the top left of the active sheet, despite my best efforts to hard code a different position in.
So two questions:

*

*How do I set the position for an OLEObject?

*Is there a way I can identify the cell reference/position of the command button, and then set the position of the OLEObject relative to it? For example, two columns to the right of the button.

Thanks
Here's my code so far:
Sub AttachFile()

'Identify the cell the command button is in and set the location for attachment icon to be 3 columns to the right
Dim buttonName As String
Dim buttonAddress As String
Dim buttonLocation As Range
Dim iconLocation As Range

buttonName = ActiveSheet.Shapes(Application.Caller).Name
buttonAddress = ActiveSheet.Shapes(buttonName).TopLeftCell.Address
Set iconLocation = Range(buttonAddress).Offset(0, 3)

'Browse for the file
Dim vFile As Variant
vFile = Application.GetOpenFilename("All Files,*.*", Title:="Find file to insert")
If LCase(vFile) = "false" Then Exit Sub

'Embed the selected file
Dim attachment As OLEObject
Set attachment = ActiveSheet.OLEObjects.Add( _
    Filename:=vFile, _
    Link:=False, _
    DisplayAsIcon:=True)

'Reposition the icon to be next to the command button
ActiveWindow.Zoom = 100
With attachment
    .Top = iconLocation.Top
    .Left = iconLocation.Left
End With
ActiveWindow.Zoom = 70
End Sub

A: I think you have correct approach. Try change your code to something like this
With attachment
    .Top = cells("H89").top
    .Left = cells("H89").left
End With

im not currently near VBA, but it was something like that


text:
Q: Firefox pop-up PHP session variable not being sent correctly Everything is working fine in Chrome, but not in FF. Here's my situation:
Parent page has a link, on click it creates a pop-up with a text field.
That information is stored in $_SESSION and is used to navigate (ie, "one" takes you to page one, "two" takes you to page two, etc.). In the pop-up, on submit three things happen:

*

*The textfield info is stored in session.

*The Parent page refreshes using text field data to tell it where to go.

*The pop-up closes.

Keep in mind, this is working fine in Chrome. However, in FF I believe it is closing the pop-up window before the info is sent to parent window, thus losing $_SESSION data. I believe this because if I make it so the pop-up doesn't close, it works fine, so it's not a case of the pop-up not sending the data back to parent window.
SO...
I think my problem is in the order that my JavaScript is being executed, even though my ordering appears correct. And again, it functions in Chrome just fine.
Here's my code, can you solve it?
(All pages have $_SESSION in header, etc, it's not a syntax problem)
I believe Firefox is closing the pop-up before the $_SESSION data is being sent! I don't know why! What happens is my browser ends up in navredirect.php, with no an empty session. It's not getting the $_SESSION data, so the PHP if statement doesn't tell it do the meta redirect. PRINT_R yields nothing.
Parent page pop up call:
Go to Page

Code for pop up page.  (enternav.php)

<form method="post"  onsubmit="proceed()" action="logscript.php">
<input type = "text" name="page"  />
<input type ="submit" value="Go to page" />
</form>

Code for logscript.php (turns text-field into session data)
<? $_SESSION['pw'] = $_POST['page']; ?>

Code for navredirect.php (
<?
if($_SESSION['pw'] == "one") {
 echo "<meta http-equiv=\"refresh\" content=\"0;URL=pwone.php\">";
}
elseif($_SESSION['pw'] == "two") {
 echo "<meta http-equiv=\"refresh\" content=\"0;URL=pwtwo.php\">";
}
else {
 echo "<meta http-equiv=\"refresh\" content=\"0;URL=wrongpw.php\">";
}
?>


text:
Q: How does light speed in a medium affect refraction? Light rays hit a convex lens and converge at a focal point after passing through as shown by the diagram below:

It is obvious by looking here that the light rays travel different distances to the focal point but they arrive at the same time. Photons travelling along the Principal axis travel in a straight line and spend the longest time in the medium. I read that the medium (of glass in this case) slows down light due to weak interaction. An airplane slowing down would lose altitude like the light changing course in the top half of the lens. I just don't understand how the direction of the light rays gets changed in an upward direction for the bottom half of the lens.
To be very blunt lets say 5 individual photons travel along each of the 5 axes shown hitting the lens at the same time ...
A) Do they arrive at the focal point at the same time?
B) How does the slowing down in the medium cause the photons to change direction both downwards and upwards yet allows the photon on the principal axis to continue unaffected?
P.S. I can see the light rays are refracted but can't seem to link this to speed
In advance, thank you for explaining this

A: Ray optics is a simplification tool useful for making calculations but not very useful for understanding light behavior. If you want to understand why light bends when it changes medium, you need to consider light as a wave, not as a particle.
The Huygens–Fresnel principle will explain the rest.


text:
Q: Simplifying polygon edge while preserving minimum area and width I am working with river buffer areas. The area that you see in the first picture is a 100-meter buffer of a polyline (a polyline isn't visible but it is there).

I want to simplify the edge in a way, where I connect the maximum points (red dots) on each "bump" as shown in the second photo while still preserving the minimum distance (width) of 100 meters from the polyline. Basically, I want to remove all the "dents" and make the edge more smooth.

The expected result (What I would like to achieve) is in the third photo. The edge should be the same or similar to the red line, which I have manually draw on it.

Is there a way to do this automatically (with a tool)? Or do I have to do it manually?

A: There are at least two possibilities: convex and concave hull. This is not software specific, both kind of hulls can be created with different software packages. The description here is based on QGIS 3.20:

*

*Convex hull: Menu Processing / Toolbox / Minimum bounding geometry, then select Convex hull (solid red line on the screenshot).

*Concave hull: Menu Processing / Toolbox / Concave hull (k-nearest neighbor). Set the value for Number of neighboring points to consider (a lower number is more concave, a higher number is smoother): The smaller the value, the nearer to the original buffer it is. The larger it is, the closer it is to the concave hull. The red dotted line is created with a value of 30.


text:
Q: How to get `incorrect password` from keytool? Windows10 user. I am trying to recover my keystore password. I am using keytool.exe found in C:\Program Files\Android\Android Studio\jre\bin.
I want to eventually change the password, but I am unsure of what the password is. I am trying to get an incorrect password error by running a command similar to:
keytool -keypasswd -keypass "foo" -new "foobar"-keystore "C:\Users\Me\Desktop\stuff\keystores\android.jks"

I have also tried:
keytool -keypass "foo" -new "foobar"-keystore "C:\Users\Me\Desktop\stuff\keystores\android.jks"

My error message for both is
Illegal option:
C:\Users\Me\Desktop\stuff\keystores\android.jks

***Side Note:
I do have the password "Remembered" in Android Studios, and am able to generate new keys and updates with it. My end goal is to transfer the keystore over to my mac. If there is another way to find the password or to handle this configuration, I am all ears.

A: I was able to find a command that issues a Enter keystore password: prompt. Command:
keytool -list -v -keystore C:\Users\Me\Desktop\stuff\keystores\android.jks

After a few attempts of doing the incorrect password, I received the error code:
keytool error: java.io.IOException: Keystore was tampered with, or password was incorrect

And finally, I was able to guess my correct password, which output:
Keystore type: JKS
Keystore provider: SUN

Your keystore contains 1 entry

Alias name: myandroidkey
Creation date: 16-Aug-2018
Entry type: PrivateKeyEntry
Certificate chain length: 1
Certificate[1]:
...

*******************************************
*******************************************


text:
Q: How to check rabbit connection in node js for unit test using mocha and chi I'm using amqplib-package for connecting to RabbitMQ in nodeJS and want to know
how I can check/verify my RabbitMQ-connection using Mocha and Chai in nodeJS?

A: You can try one of the following:

*

*you can create a valid rabbit-mq connection using a docker iamage docker-rabbitmq and make real requests to your application but this is not unit testing, but more like integration testing.

*You can mock it using sinon a very good article I can suggest on this topic is Best practices for spies, stubs, and mocks in sinonjs

*You can follow this topic on google groups NodeJS + RabbitMQ (amqplib): How to write good Unit Test against them.

A: If you are using ampqlib package and you want to test whether the connection is established or not then it is not considered as a unit test, we can call it an integration test.
Other answers have good content about integration testing, but for unit testing you can use amqplib-mocks (https://www.npmjs.com/package/amqplib-mocks) which is a simple mocking framework for amqplib.
For a basic unit test you can check if amqp.connect(url) is called and expect the URL you want.
I can also show a basic example how you can get a stubbed connection object:
(ps: This is not a running code, this is just for reference)
subscriber.js
const amqp = require('amqplib');
class Subscriber {
   async getConnection(url) {
        const connection = await amqp.connect(url);
        return connection;
   }
}

Subscriber class has a method getConnection which establishes and return a connection object with rabbitmq.
subscriber.test.js
const amqpMock = require('amqplib-mocks');
const sinon = require('sinon');

const mockConnection = await amqpMock.connect('mockurl.com');
const getConnectionStub = sinon.stub(Subscriber.prototype, 'getConnection').returns(mockConnection);

In above code you can either stub ampq.connect directly or stub getConnection method and return a connection object as  returned by amqp-mock's connect method.
To know more about sinon used above, click.


text:
Q: The annihilator induces a module Let $R$ be a ring, and $M$ an $R$-leftmodule. Let $\operatorname{Ann}_R(M)$ be the annihilator of M, meaning that $r m = 0 \space\space\space\space  \forall r \in \operatorname{Ann}_R(M), m \in M$.
Let $I \subseteq \operatorname{Ann}_R(M)$ be a two-sided ideal. Show that M is naturally an $R/I$-module.
Thanks in advance! I'm not that used to annihilators, so any help would be appreciated.

A: You have to prove that if $r\equiv s \mod I$, then $rm=sm$ for any $m\in $M$.
That is equivalent to $(r-s)m=0$, which is by definition since $r\equiv s\mod I\iff r-s\in I\subseteq\operatorname{Ann}_AM$.


text:
Q: who retweeted a tweet how do i find who retweeted a certain tweet?
The show status api call returns data on a certain tweet, according to ID, though does not show who retweeted (if retweeted)
http://dev.twitter.com/doc/get/statuses/show/:id
There's just a numerical 'retweet_count' field. I'm looking for user ID \ screen_name of the retweeters.
Thanks.

A: Have a look at the GET statuses/:id/retweeted_by API method.


text:
Q: Create a JavaScript program, that has an array of strings and the program sorts in O(nlog n) time I need to create a JavaScript program, that has an array of strings which also  sorts in O(nlog n) time.
Any help would be appreciated...

A: First up define what sorting algorithm you are going to use. There are hundreds out there, but only a few really good. You need to look specifically to O(n log n)  algorithms.
O(n log n) algorithms are also called loglinear algorithms, depending on your usecase you should use a different algorithm.
Heapsort or mergesort are the most widely known loglinear algorithms.
Heapsort is the best for selection.
Mergesort is the best for merging.
So what type of sort are you going to do?
Then when you have defined the algorithm build you code. First make two arrays and fill them with random data. Then write the javascript implementation of the sorting algorithm you are going to use.
Better do your homework yourself, its to learn from it.

Links:
Wikipedia Sorting algorithm
javascript merge sort
javascript heap sort
java heapsort but excellent reading material
again java mergesort but excellent reading material


text:
Q: link database and stmt and prepare I want to write a mysql php code
if I put the ID and passwd it will check with database
and link to the login success or login fail.
but my code it failed to go to the login success even though id and passwd is correct
$mysqli = new mysqli('localhost', 'root', '', 'project');

$username = $_POST['username'];
$password = $_POST['password'];

//to check whether the username exists or not
$stmt = $mysqli->stmt_init();

$stmt->prepare("select pid, password from person where pid = '$username' and passwd = '$password'");
$stmt->bind_param('ss', $username, MD5($password));
$stmt->bind_result($result,$result2);
$stmt->execute();

*

*Im not sure my prepare statement and the bind_param is in the right position.
it should compare the MD5(password) (encrypted) password with input password

**
if  ($stmt->fetch())
{
    session_start();
    $_SESSION['pid'] = $username;//login id
    header('Location: Login Successfully.php');
    exit();
}else{
$_SESSION['pid'] = $username;
header('Location: Failed to login.php');
}

**
and this is my  fetch. but it always go to the failed to login.php
this is my login.php before execute above code. it get the input id and passwd and pass it to the fetch code.
Login:
    Enter your username and password below:

Username: <input type="text" name="username" />

Password: <input type="password" name="password" />

<input type="submit" value="Submit" />

A: When using prepare(), you need to use placeholders ? instead of the actual variables. Also it looks like passwd should be password. So you will want to change
$stmt->prepare("select pid, password from person where pid = '$username' and passwd = '$password'");

to
$stmt->prepare("select pid, password from person where pid = ? and password = ?");


text:
Q: Double Variable Expansion From For Loop I am trying to find out how I can define variables within a for loop.   They
 must equal the values of pre-defined variables with the for loop variable being a part of those pre-defined variables names.
Example:
PROCESS1="sshd"    --> 1 will be a for loop variable 'i' value
ALIAS1=SSH
PROCESS2="snmpd"   --> 2 will be a for loop variable 'i' value
ALIAS2=SNMP

#Creating array consisting of n number of processes to feed to the for loop

ARRAY=(1 2)

for i in ${ARRAY[@]]};do
PID$i=`ps -elf | grep -i $PROCESS$i`  -->   this is where I am getting stuck
TCP$i=`netstat -anlp | grep $PID$i
done

I am trying to create PID1 equal to the value of the "ps" command output with grepping for the value of variable PROCESS1.
I've even tried this:
for i in ${ARRAY[@]]};do

PROCESS=PROCESS$i
ALIAS=ALIASP$i
PID=PID$i

PID$i=`ps -elf | grep -i $$PROCESS`
TCP$i=`netstat -anlp | grep $$PID

This only attempts to grep for "PROCESS1" instead of sshd.

A: Why don't you just use bash arrays?:
PROCESS=(sshd snmpd)
for i in $(seq 0 $((${#PROCESS[@]}-1)));do
    PID[$i]=$(pgrep "${PROCESS[$i]}")
    TCP[$i]=$(netstat -anlp | grep ${PID[$i]})
done
echo ${#PID[0]} ${#TCP[0]} ${#PID[1]} ${#TCP[1]}

Use bash associative arrays for fun:
PROCESS=(sshd snmpd)
declare -A PID TCP
for i in ${PROCESS[@]};do
    PID[$i]=$(pgrep "$i")
    TCP[$i]=$(netstat -anlp | grep ${PID[$i]})
done
echo ${#PID[sshd]} ${#TCP[sshd]} ${#PID[snmpd]} ${#TCP[snmpd]}

Use declare, get variable value using indirect reference, if you must:
PROCESS=(sshd snmpd)
for i in $(seq 0 $((${#PROCESS[@]}-1)));do
    declare PID$i="$(pgrep "${PROCESS[$i]}")"
    ref=PID$i
    declare TCP$i="$(netstat -anlp | grep ${!ref})"
done
echo ${#PID0} ${#TCP0} ${#PID1} ${#TCP1}

Never use eval:
PROCESS=(sshd snmpd)
for i in $(seq 0 $((${#PROCESS[@]}-1)));do
    eval "PID$i=\"$(pgrep "${PROCESS[$i]}")\""
    eval "TCP$i=\"\$(netstat -anlp | grep \$PID$i)\""
done
echo ${#PID0} ${#TCP0} ${#PID1} ${#TCP1}


text:
Q: How to correctly restore widgets that are resized by windows 7/vista aero snap Windows 7 has this functionality where if a window is dragged to the side of the screen, it is maximized to take half of it. My problem is - I am trying to implement restore for widget's size and position and when Windows 7 "maximizes" the widget, qt still returns its position and size as if it was still shown normally, i.e - completely incorrect position and size.
Is there any control over this in qt5? I can't find it anywhere in the docs and its strange

A: This is essentially what I ended up doing.
"framegeometry" part at the bottom is necessary to compensate for widget's borders it seems.
QT += gui-private

is needed in the .pro file for the code below to work
#include <WinUser.h>
#include <qpa/qplatformnativeinterface.h>
static QWindow* windowForWidget(const QWidget* widget)
{
    QWindow* window = widget->windowHandle();
    if (window)
        return window;
    const QWidget* nativeParent = widget->nativeParentWidget();
    if (nativeParent)
        return nativeParent->windowHandle();
    return 0;
}
#include <QWindow>
static HWND getHWNDForWidget(const QWidget* widget)
{
    QWindow* window = ::windowForWidget(widget);
    if (window && window->handle())
    {
        QPlatformNativeInterface* natInterface = QGuiApplication::platformNativeInterface();
        return static_cast<HWND>(natInterface->nativeResourceForWindow(QByteArrayLiteral("handle"), window));
    }
    return 0;
}
void SaveSize(QWidget* w)
{
    QSize size;
    QPoint pos;
    RECT pRect = { 0 };
    HWND hwnd = getHWNDForWidget(w);
    GetWindowRect(hwnd, &pRect);
    auto left = w->frameGeometry().left();
    auto right = w->frameGeometry().right();
    auto width = w->width();
    pos.setX(pRect.left);
    pos.setY(pRect.top);
    size.setWidth(pRect.right - pRect.left - (right - left - width));
    size.setHeight(pRect.bottom - pRect.top);
    //.... the rest of the code
}


text:
Q: bindParam and NULL int values I am using bindParam to set values for a MySQL insert. The column in question is an INT (11). It has a default of NULL and null is allowed. However, using bindParam it always receives a 0. I have confirmed that my $_POST['value'] is indeed null.
if(isset($_POST['value'])){
  $stmt = $db->prepare("INSERT INTO table (column) VALUES (:column)");
  $stmt->bindParam(':column',$_POST['value'], PDO::PARAM_INT);
  $stmt->execute();
}

It keeps inserting a '0' instead of NULL if the POST value was ''.

A: You should be matching the complete case (Answer and type) with === (Read More)
Which most likely means that your value is not null like you presume it is.
Ensure it is by checking (pseudo code below):
if(VALUE !=== NULL) {
   value = null
}

But you get the idea there? If not just comment :-)

And as aldanux mentioned in his comment, you have to wrap the column in backticks as it is a reserved word:
INSERT INTO table (`column`) VALUES (:column)


text:
Q: six cannot be imported/uninstalled/reinstalled/upgraded I'm trying to run lldb on my MacBook terminal, but I get errors related to the six package:
File "/Applications/Xcode.app/Contents/SharedFrameworks/LLDB.framework/Resources/Python/lldb/__init__.py", line 98, in <module>
    import six
ImportError: No module named six
Traceback (most recent call last):
  File "<string>", line 1, in <module>

I tried to launch python from terminal and then execute import six, but still:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named six

Next step was to uninstall and reinstall six, but it seems like everything related to this package is corrupted for me:
$: pip uninstall six
Uninstalling six:
  /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/six-1.4.1-py2.7.egg-info
Proceed (y/n)? y
Exception:
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pip/basecommand.py", line 122, in main
    status = self.run(options, args)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pip/commands/uninstall.py", line 59, in run
    requirement_set.uninstall(auto_confirm=options.yes)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pip/req.py", line 1035, in uninstall
    req.uninstall(auto_confirm=auto_confirm)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pip/req.py", line 598, in uninstall
    paths_to_remove.remove(auto_confirm)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pip/req.py", line 1836, in remove
    renames(path, new_path)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pip/util.py", line 295, in renames
    shutil.move(old, new)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 302, in move
    copy2(src, real_dst)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 131, in copy2
    copystat(src, dst)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 103, in copystat
    os.chflags(dst, st.st_flags)
OSError: [Errno 1] Operation not permitted: '/var/folders/_c/lj7t1035563flfh7fy4m3gfh0000gn/T/pip-YQdNMp-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/six-1.4.1-py2.7.egg-info'

Storing debug log for failure in /Users/lab5/.pip/pip.log

$: pip install --ignore-installed six
Downloading/unpacking six
  Cannot fetch index base URL https://pypi.python.org/simple/
  Could not find any downloads that satisfy the requirement six
Cleaning up...
No distributions at all found for six
Storing debug log for failure in /Users/lab5/.pip/pip.log

I downloaded six and installed it from the tar.gz file, but it still seems like the old version is installed:
$: pip install --ignore-installed ~/Downloads/six-1.5.1.tar.gz
Unpacking ./Downloads/six-1.5.1.tar.gz
  Running setup.py (path:/var/folders/_c/lj7t1035563flfh7fy4m3gfh0000gn/T/pip-zqLhAa-build/setup.py) egg_info for package from file:///Users/lab5/Downloads/six-1.5.1.tar.gz

    no previously-included directories found matching 'documentation/_build'
Installing collected packages: six
  Running setup.py install for six

    no previously-included directories found matching 'documentation/_build'
Successfully installed six
Cleaning up...

$: pip show six
---
Name: six
Version: 1.4.1
Location: /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python
Requires:

Python version: Python 2.7.15
Pip version: pip 1.5.6 from /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages (python 2.7)

Do you have any recommendations for me how to get rid of those errors and run lldb properly? I took someone's suggestion to install python again (simply brew install python), but it was not helpful.

A: You are using python2, to use brew to install python2 you need to add @2
 brew install python@2

I use the python2 installed with brew and was able to install six just fine.  From your errors, it appears when you tried pip install six you got the OSError: [Errno 1] Operation not permitted:
Try running pip with sudo -H
sudo -H pip install six --upgrade

A: I'm still not sure what the reasons for the errors were, but I could get rid of them after upgrading my python version and I'm just fine with that.
To install a new python version:
brew install python

Then, I removed the link at /usr/local/bin/python and set it again to the new version:
rm /usr/local/bin/python
ln -s /usr/local/Cellar/python/3.7.0/bin/python3.7 /usr/local/bin/python

Then, installed six with the new version's pip:
python -m pip install six

(executing python -m enforces installing with the new pip, for the new python)
I'm not 100% cool with that solution, I still have to remove old versions to have a clean python installation, but at least I can work with lldb now, which was my main goal

A: Pointing to the correct Xcode installation using xcode-select -switch solved it for me.


text:
Q: Trying to get property 'email' of non-object I am getting following error from my code written in Codeigniter when i enter a wrong E-mail.

A PHP Error was encountered Severity: Notice
Message: Trying to get property 'email' of non-object
Filename: controllers/forms.php
Line Number: 26
Backtrace:
File:
  E:\Software\XAMPP\xampp\htdocs\ciauth\application\controllers\forms.php
  Line: 26 Function: _error_handler
File: E:\Software\XAMPP\xampp\htdocs\ciauth\index.php Line: 315
  Function: require_once

Below is the controller
<?php
class Forms extends CI_Controller
{
    public function __construct()
    {

        parent::__construct();
        $this->load->database();
        $this->load->library('session');
        $this->load->helper('url');
        $this->load->model('user_model', 'auth');
    }

   public function forgot_pass()
    {
        if($this->input->post('forgot_pass'))
        {
            $email=$this->input->post('email');
            $this->load->model('user_model', 'auth');
            $this->load->library('form_validation');
            $this->form_validation->set_rules('email', 'E-mail', 'required');

            if ($this->form_validation->run() == TRUE) {
            $que=$this->db->query("select password,email from users where email='$email'");
            $row=$que->row();
            $user_email=$row->email;
            if((!strcmp($email, $user_email)))
            {
                $pass=$row->password;
                $to = $user_email;
                $subject = "Password";
                $txt = "Your password is $pass .";
                $headers = "From: user@testdomain.com" . "\r\n" . "CC: hamza_zon@outlook.com ";
                mail($to,$subject,$txt,$headers);
                $this->load->view('user/header');
                $this->load->view('user/confirm');
                $this->load->view('user/footer');
                }
            else{
            $data['error']="Invalid Email ID !";
            }
        }
            else{
                $data['error']="Email ID is required !";
            }
    }
            $this->load->view('user/header');
            $this->load->view('user/forgot_pass',@$data);
            $this->load->view('user/footer');

   }
}
?>

A: you should check before $user_email=$row->email; that the as per your criteria record exist or not, if row is not exist then you will get that error
so you should check as below
$row=$que->row();
if($row) {

   $user_email=$row->email;
}

A: Try like this
$que = $this->db->query("select password,email from users where email=".$email);

if(isset($row) && $row != ''){
  $txt = "Your password is" . $pass;
  //Coding...
}

A: Apply condition as, because in your case it may not getting the result from table for that email,
if (isset($row))
{

Note: row method returns a single result row. If your query has more than one row, it returns only the first row. The result is
  returned as an object. Here's a usage example:

$que=$this->db->query("select password,email from users where email like '$email'");

$row = $que->row();

if (isset($row))
{
    $user_email = $row->email;
    $user_password = $row->password;
}

Here is concise doc for the same.

A: You need to handle it like this,
$query = $this->db->query("select password,email from users where email=".$email);
if ($query->num_rows() > 0) {
    $row = $query->row();
    $user_email = $row->email;
} else {
    $user_email = '';
}
//then your next if condition in which you are comparing two strings

A: $row=$que->row();
$row is probably being returned as NULL or a falsy value.
var_dump($row) to check.
if(!$row)
{
    die("user not found");
}

or
if(empty($row))
{
    die("user not found");
}


text:
Q: Simple question regarding ratio and average I have 2 lists of numbers (with an equal number of numbers in each). Each number is then divided by the number of which it is paired with (by index), and a ratio is received.
I then want to calculate the global average ratio, so I try 2 ways:

*

*Sum all numbers in each column, and divide one with the other.

*Make an average of all ratios I have received from the calculation above.

Both give me different results.
How could that be? And what would be considered the true global ratio average?
Example lists:
1  : 1 = 1
2  : 1 = 2
3  : 2 = 1.5
4  : 2 = 2
-----------
         1.625 average
10 : 6 = 1.667

A: The answer to your first question is the observation that $\frac{a}{b} + \frac{c}{d}$ is in general not equal to $\frac{a+c}{b+d}$. In other words, the average of ratios is not necessarily equal to the ratio of sums.
As regards the true global ratio average is concerned- I think the answer is context specific. A meaningful answer can only be given if you could shed some light on the nature of the numbers you have.

A: Asking which is "the true global ratio average" brings you very close to Simpson's paradox where, for example, treatment A can be better for men than treatment B, and also better for women, but worse overall. There is an active literature on how to deal with the paradox when it arises.

A:
How could that be?

It is more instructive to regard just the case of lists of length 2:
You want to have
$$\frac{a}{c}+\frac{b}{d} = \frac{a+b}{c+d}.$$
But this is almost never true, there is a reason for the more complicated way to add fractions.
With 27 numbers, it does not get better.
Edit:

what would be considered the true global ratio average?

It depends on your situation what you want to calculate. For example, let's say you know of every person in a country: how much they earn and how much they spend on food.
1. Sum all numbers in each column, and divide one with the other.

*

*This gives you the ratio of the averages, which tells you what percentage of the total income in the country is spent on food.

*Outliers (in this case, the few very rich people who spend a relatively high amount on food) significantly influence the ratio of the averages.

*Use this if you want to know how food price rises impact the part of the economy that produces and sells food
2. Make an average of all ratios from the calculation above.

*

*This gives you the average of the ratios, which tells you the average percentage people spend on food.

*Outliers have less of an effect.

*Use this if you want to know how food price rises impact people


text:
Q: Google Spreadsheet ARRAYFORMULA() with INDIRECT() and ROW() I have a google spreadsheet in which I enter daily income and expenses:

On another sheet, I am trying to calculate the monthly income and expenses for every month:

I am using this formula to calculate the monthly income ('s1' is the daily sheet):
=ARRAYFORMULA(SUM(FILTER(s1!B2:B; MONTH(s1!A2:A)=MONTH(INDIRECT("A" & ROW())))))

but it does work for the whole column.
Is there any way to make the arrayformula work with the indirect and row functions?

A: I think this would work as a SUMIF instead - try:
=ArrayFormula(IF(A2:A="",,SUMIF(MONTH(s1!A2:A),MONTH(A2:A),s1!B2:B)))


text:
Q: How to create jquery UI dialog Buttons dynamically and map to function? I took this sample piece of code from the below link
How do I close a dialog using jQuery?
$(function () {
    $("a:contains('sometext')").click(function() {
        var NewDialog = $('
\

This is your dialog content, which can be multiline and dynamic.
\

');
        NewDialog.dialog({
            modal: true,
            title: "title",
            show: 'clip',
            hide: 'clip',
            buttons: [
                {text: "Submit", click: function() {doSomething()}}
            ]
        });
        return false;
    });
});

Here instead of the value doSomething I need to use a variable.
For eg:- if i have a variable temp=confirm, the value confirm should be used there.
so when i clicked the button the function confirm should be invoked.
How can i achieve this?

A: If your confirm variable is a function you can just replace click function with confirm:
Edit:

 $(function () {
    var confirm1 = function(){
        alert("confirm function 1");
    }
    var confirm2 = function(){
        alert("confirm function 2");
    }

    var temp = confirm1;

    $("a:contains('sometext')").click(function() {
        var NewDialog = $('
\

This is your dialog content, which can be multiline and dynamic.
\

');
        NewDialog.dialog({
            modal: true,
            title: "title",
            show: 'clip',
            hide: 'clip',
            buttons: [
                {text: "Submit", click: function(){temp();}}
            ]
        });
        return false;
    });

    //  Uncomment this line if you want to change temp function
    //  temp = confirm2;

});

Fiddle:
http://jsfiddle.net/nilgundag/SgFJk/4/

A: I modified the code like below and it works..

buttons: [
                  {text: "Submit", click: function() {eval(temp)()}}
              ]


text:
Q: Is there a difference between window.onload = stuff and window.onload = stuff()? I'm most familiar with Python and somewhat with C, and when I see this syntax in JS it really confuses me
function begin () {
    console.log("done did it");
}

window.onload = begin(); // the same output as
window.onload = begin;   // this one

In Python, one would be passing the return value of the function, the other a pointer to the function. What are the semantics in JS for these two statements?

A: Yes, there's a very big difference.
window.onload = stuff(); will call the stuff function and assign its return value to the onload property.
window.onload = stuff; assigns the stuff function to the property onload. The browser will call that function when the load event occurs. Functions are objects. When you refer to them by their name without calling them, you're referring to the object. This would be similar to the "function pointer" you were talking about.

A: The right way is :
window.onload = xxxx;

the xxx must be a function.
the first one:
var fn = function() {
    alert("abc");
}

window.onload = fn;

the other one:
var fn = function() {
    var abc = "abc";
    return function () {
        alert(abc);
    }
}
window.onload = fn();


text:
Q: How to sort a list with the scores in sorted set I want to sort a list with scores in a sorted set. I also want to use limit command.
I created a list and a sorted set like below.
zadd weights 10 apple 20 grape 30 banana 40 strawberry 50 melon
lpush list apple melon strawberry banana

I thought of sort command and tried like below.
sort list by weights limit 2 2
sort list by weights->* limit 2 2

I expected that list had sorted into "apple banana strawberry melon" order and only "strawberry melon" is returned by limit command.
But both command above does not work. (instead I got one that alphabetically sorted)
How can I get the result I expect?
thanks.

A: Redis doesn't work that way. According to the docs Sorting By works for sorting by external keys not by values inside the external key. To be more precise, When Redis does sort list by weights_* it checks for all the keys mathcing this pattern and compares them with the values in the list and returns you the sorted result.
Example:
lpush list apple melon strawberry banana
MSET  weights_apple 10 weights_grape 20 weights_banana 30 weights_strawberry 40 weights_melon 50

Now if you try sorting, result will be
127.0.0.1:6379> sort list by weight_*
1) "apple"
2) "banana"
3) "strawberry"
4) "melon"

As you can see sorting applies on external keys on weight_* pattern. Not within a single entity ( a hash or sorted set)
You can do the same with hashmap or sorted set but the comparison happens with keys matching a particular pattern and then a value inside that key.
For example to achieve the same with a hashmap or sorted set you have to do something like this.
127.0.0.1:6379> lpush list apple melon strawberry banana
(integer) 4
127.0.0.1:6379> hset weight_apple value 10
(integer) 1
127.0.0.1:6379> hset weight_grape value 20
(integer) 1
127.0.0.1:6379> hset weight_banana value 30
(integer) 1
127.0.0.1:6379> hset weight_strawberry value 40
(integer) 1
127.0.0.1:6379> hset weight_melon value 50
(integer) 1
127.0.0.1:6379> sort list by weights_*->weight
1) "apple"
2) "banana"
3) "melon"
4) "strawberry"

This works well if you have a data structure like storing all the info's of a gamer in a single hash and a set containing Ids of gamers. Now you want to sort them by their scores.
You can also use get command to get other associated values.


text:
Q: Migrating from south to django 1.8 raises table already exists I have a project running on django 1.6 and working to upgrade it to 1.8 which includes moving from south migration to django's migration.
I tried to follow steps mentioned by django documentation on how to update from south to django migrations here https://docs.djangoproject.com/en/1.8/topics/migrations/#upgrading-from-south
& am facing a problem when trying to migrate --initial-fake, it seems like even though some tables exists django migration is trying to create them
./manage.py migrate --fake-initial

Running migrations:
  Rendering model states... DONE
  Applying retail.0001_initial... FAKED
  Applying contenttypes.0001_initial... FAKED
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0001_initial... FAKED
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying account.0001_initial... FAKED
  Applying default.0001_initial...Traceback (most recent call last):
  File "./manage.py", line 11, in <module>
    execute_from_command_line(sys.argv)
  File "/project-path/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
    utility.execute()
  File "/project-path/lib/python2.7/site-packages/django/core/management/__init__.py", line 330, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/project-path/lib/python2.7/site-packages/django/core/management/base.py", line 393, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/project-path/lib/python2.7/site-packages/django/core/management/base.py", line 444, in execute
    output = self.handle(*args, **options)
  File "/project-path/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 222, in handle
    executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial)
  File "/project-path/lib/python2.7/site-packages/django/db/migrations/executor.py", line 110, in migrate
    self.apply_migration(states[migration], migration, fake=fake, fake_initial=fake_initial)
  File "/project-path/lib/python2.7/site-packages/django/db/migrations/executor.py", line 148, in apply_migration
    state = migration.apply(state, schema_editor)
  File "/project-path/lib/python2.7/site-packages/django/db/migrations/migration.py", line 115, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "/project-path/lib/python2.7/site-packages/django/db/migrations/operations/models.py", line 59, in database_forwards
    schema_editor.create_model(model)
  File "/project-path/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 286, in create_model
    self.execute(sql, params or None)
  File "/project-path/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 111, in execute
    cursor.execute(sql, params)
  File "/project-path/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "/project-path/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "/project-path/lib/python2.7/site-packages/django/db/utils.py", line 97, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/project-path/lib/python2.7/site-packages/django/db/backends/utils.py", line 62, in execute
    return self.cursor.execute(sql)
django.db.utils.ProgrammingError: relation "social_auth_association" already exists

Any advise please?
regards,

A: Type  python manage.py migrate --help

--fake         Mark migrations as run without actually running them.

--fake-initial Detect if tables already exist and fake-apply initial
               migrations if so. Make sure that the current database
               schema matches your initial migration before using
               this flag. Django will only check for an existing
               table name.

A: From the documentation:
The only complication is if you have a circular dependency loop of foreign keys; in this case, makemigrations might make more than one initial migration, and you'll need to mark them all as applied using:
python manage.py migrate --fake yourappnamehere

So try to run
python manage.py migrate --fake default

And it should do the trick.