text:
Q: Inserting data into MagicFields using mysql queries PART 01: INTRO
Hey Stackexchange
Greetings from the Snowy alps of Norway
I have now tried for two full consecutive days to
reverse engineer Magic Fields. Why?
Because I am a simple man, and want to import data to my wordpress from an exotic database using CSV (and not programming a php routine, which I don't know nor understand).
This has worked for all vanilla Wordpress fields, i.e. post-data, categories and so on. (I used LibreOffice Calc to fine-tune the CSV data, Quest Toad for MySQL import and to create MySQL queries).
My designer has designed this entire thing extensively using the Magic Fields plugin. Therefore I have to deal with Magic Fields for the rest of the data that I need to have imported. It's a movie database, so it's the typical meta-data for movies like
"productionyear" "producer" "imdblink" "youtubetrailerlink" and so on.
My question is that I am hoping to get some insights/ideas/support on how to import these data into the magic fields. I have tried and given up the "magic fields importer", it is not documented and does not give any error messages when I try to import various csv formats.
PART 02: Understanding Magic Fields
My question is how can I populate(insert) a magic field with data using a mysql query?
I have tried to understand what it is Magic Fields is doing when I put some data into a magic field and press save, in the admin-edit-post-frontend.
It does a lot of things that I can't seem to re-create. For one it is not enough to insert data into the two places where the data is referenced.
wp_postmeta and wp_mf_post_meta.
This example post is not sufficient to get the data to "work" i.e. display themselves in wordpress neither in the admin-post-editor nor the front-end for the user:
INSERT INTO `wp_postmeta` (`post_id`,`meta_key`,`meta_value`) VALUES ('474','originaltitle','Die Hard 3');

INSERT INTO wp_mf_post_meta ( meta_id, field_name, field_count, group_count, post_id )  VALUES ( 1100083, 'originaltitle' , 1,1 ,474 );

Also with that meta_id number, Magic Fields creates a number series of 10 for each post, like 7000-7010 and then 8000-8010. I don't understand where it takes those numbers from, and whether they have to be sequential/consecutive. I have found that once entered by the admin-post-editor frontend, I can change the meta-id's in wp_postmeta and wp_mf_post_meta and it still works. But again when I try to create them myself with a SQL query, "it just doesn't work (TM)".
After enabling MySQL querylogging and examining the logfile from the MySQL db engine gives and then trying to insert the queries manually (that I can make out from the logs),
I still can't make Wordpress "find" the data and display them properly on the page.
I can modify the data with mysql queries after I have populated them using the frontend with no problems.
Also using the query logs, I found that after I push "SAVE" in the Wordpress frontend-post-editor it does no less than ~780 mysql query lines (regardless if I populate 1 or 10 of my magic fields)!
The other thing I have tried is to take a snapshot of the database before and after I have done the post of the magic fields, and then used a diff-tool (various, WinMerge and Notepad++ mainly).
I can't understand what it's doing but I THINK it is doing some hidden trickery in wp_term_taxonomy. This is just speculation.
Part 03: Conclusion
I don't know programming so any practical solution, would be deeply apprechiated.
the full query I want to do per post (I have about 800 of these) is here: http://pastebin.com/5cZT3AjA
The FULL list of queries that Magic Fields is doing after I push save in the admin-front-end is listed here (which I call the 'robot-at-work').
http://pastebin.com/c2c6qUQt
To be sure I have checked three times that it wasn't something extraordinary that it is doing ~780 lines after I push save.
I guess if I could find a way to bulk-edit all of my posts, and then have the "robot" i.e. admin-post-edit frontend do the work to create all these lines in the database. I could then change the fields afterwards... But the bulk-editor doesn't show the magic-field editor either.
I have twisted my head around this problem 10 times now, and can't twist anymore!

A: Thank you so much buddy. I wish I had seen your post before!
Meta_id 's must be chronological and can't be arbitrary (i.e. random).
data must be inserted into wp_mf_postmetaand wp_postmeta.
these records relate to post_id, meta_id and the key-value stores of
the data itself such where key would be "movietitle" and value would be "Die Hard".
I have uploaded the csv I created to do this and create the mysql queries.
I used LibreOffice Calc to finetune the data and Toad for MySQL (by Quest, free)
to create the MySQL queries.
These two records need to be modified for the data to be properly inserted:
note that the META_ID must be chronological i.e. 11001, 11002, 11003 per field per post.
so if meta_key is "Movietitle" first then that has meta_id of 11001, if "productionyear" is second then that is 11002 and if "country" is third then that is 11003.
Also note that for the wp_mf_postmeta the fieldname is the same value as meta_key
from wp_postmeta , I.e. the meta key.
INSERT INTO `wp_postmeta` (`post_id`,`meta_key`,`meta_value`) VALUES (346,'produksjonsar','18001');

INSERT INTO wp_mf_post_meta ( meta_id, field_name, field_count, group_count, post_id )  VALUES ( 18001, 'produksjonsar' , 1,1 ,346 );

The file I have used for this import is available here, if anyone
needs to see an example of how to do this import. Again I used
Toad for MySQL to create the SQL Queries by using the IMPORT function.

*

*http://ge.tt/9Q5h4zC
This also solves this question which I posted on the Wordpress Forums, Stackoverflow and Stackexchange.
http://wordpress.org/support/topic/importing-data-to-custom-fields?replies=2#post-2592976
Inserting data into MagicFields using mysql queries
https://stackoverflow.com/questions/8698631/importing-data-into-wordpress-magic-fields-using-mysql-queries
Massive props to Hameedullah Khan Stackexchange, profile here https://wordpress.stackexchange.com/users/5337/hameedullah-khan , for basically providing the clue needed to find the solution.

A: I had the same problem but I was successful importing from an self produced xml (for the  postmeta).
<wp:postmeta>
<wp:meta_key>telefono</wp:meta_key>
<wp:meta_value><![CDATA[$tel_azienda]]></wp:meta_value>
</wp:postmeta>

The problem was that after that the data were not available to use with MF, I've solved it with this mysql query:
INSERT IGNORE wp_mf_post_meta (`id`, `group_count`, `field_count`, `post_id`, `field_name`, `order_id`)
SELECT `meta_id`, 1, 1, `post_id`, `meta_key`, 1 FROM `wp_postmeta` WHERE  `meta_key` = 'mini_descrizione' OR  `meta_key` = 'imagen_en_categoria' OR `meta_key` = 'direccion' OR `meta_key` = 'codigo_postal' OR `meta_key` = 'ciudad' OR `meta_key` = 'provincia' OR `meta_key` = 'telefono' OR `meta_key` = 'email'OR `meta_key` = 'web' OR `meta_key` = 'google_map'

It copies the metas from the wp_postmeta table to the wp_mf_post_meta.


text:
Q: Google Play Alpha|Beta Link cant be found I recently published my first application so I did Alpha, the console status is "Published", create a community, I've added people, they have accepted the invitation and received the link.
https://play.google.com/apps/testing/com.package

but after 30-40 minutes the link to download the application is deactivated. my question is I need to do something or how average waiting time for the application is available
this is the link generate by the previous link
https://play.google.com/store/apps/details?id=com.package

A: You have to give it time to propagate within all Google servers, so as a ballpark figure I'd say wait 24hours.
It's like publishing any new website.
This answer actually says 48 hours:
Android App Market Update Propagation

Another issue I have noticed with people is, make sure the device they are looking for the link with is signed in with the same Google Account as accepted the G+ group invite

redpajama_set_name: RedPajamaStackExchange


text:
Q: I can't proceed in creating Developer Account in wp I want to deploy my app in Windows Phone store but Microsoft still asking credit card account and I don't have that.
I use Dream Spark account for student because it is free. Is there other way of creating an developer's account for free without asking a credit card info? I don't have any info that I can provide.
Thanks.

A: I am beginner in Windows Phone development. I faced same issue that I had Dreamspark account, but did have credit card. I googled around and could not find any solution. But, for a try, I simply entered my ATM Debit Card (that was Visa card, may work with Mastercard as well ), it worked!!!!!. Actually, they charge small amount(refundable, for my case Rs. 2) for verification and it doesnot matter whether it is Debit Card or Credit Card.
(Correct me, if I am wrong.)

A: Well you have one option in this case: you have to look for MSP(Microsoft Student Partners) community from your University and you may apply to enter in MSP.
Once you are a MSP member you will gain for free a Developer Account.
More information : Microsoft Student Partners.


text:
Q: calculating probability mass function Not quite sure how to approach this question - let's say you're looking at a toll booth lane that can hold up to $7$ cars at a time.
$X$ is the $\#$ of cars in the lane at a randomly chosen time
with the probability $X = x$ proportional to $(x + 1)(8 - x)$.
How do you calculate the probability mass function (pmf) and then the probability that $X$ will be at least $5$? I have absolutely no idea how to calculate for the pmf, but I think calculating for $P(X > 5)$ goes like this:
\begin{array}{ll}
P(0) &= (0+1)(8-0) = (1)(8) = 8\\
P(1) &= (1+1)(8-1) = (2)(7) = 14\\
P(2) &= 18\\
P(3) &= 20\\
P(4) &= 20\\
P(5) &= 18\\
P(6) &= 14\\
P(7) &= 8\\
\end{array}
and so
$$
P(X > 5) = P(5)+P(6)+P(7) = 18 + 14 + 8 = 40.
$$
If someone could point me in the right direction, that'd be great.

A: You have overlooked the word proportional.
You don't have $P(0)=8$.  Instead, you know there is a constant $c$ such that $P(0)=8c$.
Similarly, you have $P(1)=14c$, $P(2)=18c$, etc.
Now, use the fact that $P(0)+P(1)+P(2)+...+P(7)=1$ and solve for $c$.  Then you will be able to calculate all values of $P$ exactly.


text:
Q: Which groups in a data.table share a corresponding set of dates Example
set.seed(2016)
dt <- data.table(
  Grp = sample(1000, 1000000, replace=TRUE),
  Date = as.Date("2016-1-1") + sample(365, 1000000, replace=TRUE)
)
dt <- unique(dt)

dt[order(Grp, Date)]
         Grp       Date
     1:    1 2016-01-02
     2:    1 2016-01-03
     3:    1 2016-01-05
     4:    1 2016-01-06
     5:    1 2016-01-07
    ---
341526: 1000 2016-12-27
341527: 1000 2016-12-28
341528: 1000 2016-12-29
341529: 1000 2016-12-30
341530: 1000 2016-12-31

How do I know which (if any) groups share the exact same set of dates?  I guess I can dcast the data and then search for matching rows, but is there a better way?

A: As @Frank points out, your example doesn't actually include any examples.
I think probably your best bet is something like the following:
dt_agg = dt[order(Date), .(dates = list(Date), count = .N), by = Grp]
setkey(dt_agg, count)

dt_agg[ , if (.N > 1L && any(duplicated(setDT(transpose(dates))))) .SD,
        by = count]

The key efficiency (I think) is not to bother running comparison unless two Grps have the same number of unique Dates in the first place (hence grouping by count).
Within count, actually figuring out which Grps contain set-identical Dates I'm a bit less confident on (also the code as is doesn't exactly pull out which Grps are identical, but I don't think that's a far stretch from the code presented here.
Anyway this code ran on my machine almost instantly, so it's hard to evaluate efficiency.


text:
Q: Using hyphen as a letter in command names I am using hyphen as a letter for command names.  But I allow users to rename them if necessary.  Then use \catcode`-=11.  Suppose I keep the hyphen as a letter in command names, I wonder if users could encounter problems if they keep \catcode`-=11 for the entire document.

A: Setting the catcode of the hyphen to letter in a document is a very bad idea. A few examples for a test:
\documentclass{article}
\usepackage{tikz}
\begin{document}

\catcode`-=11

\tikz\draw(0,0)--(1,0); %errors

some long\-word\-with\-hyphenation %errors

\setlength{\parindent}{-1cm} %errors
\end{document}

which errors with
! Package tikz Error: Giving up on this path. Did you forget a semicolon?.

See the tikz package documentation for explanation.
Type  H <return>  for immediate help.
 ...

l.86 \tikz\draw(0,0)-
                     -(1,0);
?
! Undefined control sequence.
l.88 some long\-word
                    \-with\-hyphenation
?
! Undefined control sequence.
l.88 some long\-word\-with
                          \-hyphenation
?
! Undefined control sequence.
l.88 some long\-word\-with\-hyphenation

?
! Missing number, treated as zero.
<to be read again>
                   -
l.90 \setlength{\parindent}{-1cm}

?
! Illegal unit of measure (pt inserted).
<to be read again>
                   -
l.90 \setlength{\parindent}{-1cm}

A: Some  LaTeX constructs that fail if - is catcode 11:
\documentclass[a4paper]{article}

%\catcode`\-=11

\usepackage{array}[2021-01-01]
\usepackage{textgreek}

\begin{document}

aaa\-bbb\-ccc aaa\-bbb\-ccc aaa\-bbb\-ccc
aaa\-bbb\-ccc aaa\-bbb\-ccc aaa\-bbb\-ccc
aaa\-bbb\-ccc aaa\-bbb\-ccc aaa\-bbb\-ccc
aaa\-bbb\-ccc aaa\-bbb\-ccc aaa\-bbb\-ccc
aaa\-bbb\-ccc aaa\-bbb\-ccc aaa\-bbb\-ccc

$ \cos-x=\cos x$

$\alpha-\beta$

\textalpha-rays

\verb-\SomeCommand-

\begin{tabular}{lll}
  1&2&3\\
  \cline{2-3}
  a&b&ct
\end{tabular}

\end{document}

If you use - internally like @ classically or _ in expl3 you could provide
\DashLetterOn and \DashLetterOff  like \makeatletter/\makeatother to allow local access to that syntax in the preamble, but do not use - for commands intended for document use.


text:
Q: Embedding Documents Directly in Documents with mongoid I need to  to bulk insert the array of embedded documents to an existing document. I have tried the below code, but it was not working
 arr_loc = []
 arr_loc << Location.new(:name=> "test") << Location.new(:name=> "test2")
 biz = Business.first
 biz.locations = arr_loc
 biz.save # not working

currently i am inserting each doc separately by looping the array, i hope there is a better cleaner way to do this.
from mongo shell we can easily do this like this
> var mongo = db.things.findOne({name:"mongo"});
> print(tojson(mongo));
{"_id" : "497da93d4ee47b3a675d2d9b" , "name" : "mongo", "type" : "database"}
> mongo.data = { a:1, b:2};
{"a" : 1 , "b" : 2}
> db.things.save(mongo);
> db.things.findOne({name:"mongo"});
{"_id" : "497da93d4ee47b3a675d2d9b" , "name" : "mongo" , "type" : "database", "data" : {"a" : 1 , "b" : 2}}
>

check the link for more info.. is it possible to do this with mongoid?

A: It turns out to be a problem in calling save method after assignment
 biz.locations = arr_loc  #this is fine
 biz.save # no need for that

Mongoid updates the document on the assignment itself, no explicit save required. Refer this mongoid google group thread (Thanks Nick hoffman) for more info


text:
Q: Confusion in implicit differentiation steps
A curve has equation $$x^3-xy+y^2=7$$
  a) show that tangent to the curve is horizontal at $(1,3)$
  b) determine $y''$ at $(1,3)$

Solution for a)
using product rule, I got this,

$$3x^2(y+y^2)=0$$ However the teacher got,
  $$**3x^2-(y+xy')+2yy'=0**$$ then sub $x=1,y=3$
  $$3-(3+y')+6y'=0$$
  $$y'(1)=0$$

Solution for b)

$$(3x^2-xy'-y+2yy')=0$$
  $$**6x-y'-xy''-y'+2(y')^2+2yy''=0**$$
  $$6x-2y'+y''(2y-x)+2(y')^2=0$$
  sub x=1,y=3
  $$6+y''(1)(6-1)=0$$
  using y'(1)=0
  $$y''(1)=-\frac{6}{5}$$

I have difficult understanding steps where the stars are marked!
Appreciate your helps! Thanks

A: Differentiate both sides with respect to $x$. Recall that $y$ is a function of $x$. Maybe it will help if instead of $y$ we write $f(x)$. So your equation becomes
$$x^3-xf(x)+(f(x))^2=7.$$
Now let's differentiate. The derivative of $x^3$ is $3x^2$.
Now differentiate $xf(x)$. This is a product. So we use the Product Rule, and get $xf'(x)+f(x)$.
Now differentiate the function $(f(x))^2$. You can view this as a product. Then the derivative is $f(x)f'(x)+f(x)f'(x)=2f(x)f'(x)$. But for more complicated expressions, it is better to use the Chain Rule. Our function $(f(x))^2$ is $h(f(x))$ where $h(u)=u^2$. So the derivative is $(2u)f'(x)$, that is, $2f(x)f'(x)$.
On the right-hand side, we have the constant function $7$. Its derivative is $0$.
So we get
$$3x^2 -(xf'(x)+f(x))+2f(x)f'(x)=0.\tag{$1$}$$
Now we go back to the letter $y$. This really should be $y(x)$, but we suppress the $x$. Look back at Equation $(1)$, and write $y$ for $f(x)$ and $y'$ for $f'(x)$. We get
$$3x^2-(xy'+y)+2yy'=0.$$
Now let's do it without the replacement by $f(x)$. The derivative of $x^3$ is $3x^2$. For the derivative of $xy$ with respect to $x$, note that $xy$ is the product of two functions. So we use the Product rule and get $xy'+y$. Finally, to differentiate $y^2$ with respect to $x$, note that by the Chain Rule, $\frac{d}{dx}(y^2)=\frac{d}{dy}(y^2)\frac{dy}{dx}=2y\frac{dy}{dx}=2yy'$.

A: Hint:
Take the derivative of each term by itself using partial derivatives:
$$x^3-xy+y^2=7$$
$x^3 ~\text{partial}~: 3x^2$ (Power Rule)
$-xy ~\text{partial}~: -y -xy'$ (Product Rule)
$y^2 ~\text{partial}~: 2 y y'$ (Power Rule)
Now sum those and you get what the teacher has.
Find partial of:
$$(3x^2-xy'-y+2yy')=0$$
Again, do the partial of one term at a time:
$3x^2 ~\text{partial}~: 6x$
$-xy' ~\text{partial}~: -y' -xy''$
$-y ~\text{partial}~: -y'$
$2yy' ~\text{partial}~: 2(y')(y') + 2yy''$
Do you see your issues now?
Regards


text:
Q: How to make the `scrollbar` appear on the left side? In an Android ListView, how can I make the scrollbar appear on the left side?

A: example:
mView.setVerticalScrollbarPosition(View.SCROLLBAR_POSITION_LEFT);

A: You can move the scrollbar position to the left for any View using View.SCROLLBAR_POSITION_LEFT.

A: As the other two answers have mentioned, one possibility is using View.setVerticalScrollbarPosition() with SCROLLBAR_POSITION_LEFT.  However, one giant caveat is that this requires API level 11+, which at time of writing accounts for fewer than 10% of Android installations.  For most applications, that's not acceptable.
One possibility that comes to mind to accomplish what you want on older versions of Android would be to do something very kludgy: turn off the scroll bar, mirror your main layout with a narrow layout to the left of it, just wide enough to fit a scroll bar, and manually scroll the left view with scrollyBy() as your main view is scrolled (by overriding
onScrollChanged()).
That said, I wouldn't actually recommend that unless there's a very compelling reason to move the scroll bar to the left.  In most cases, you want your app to fit in and behave like any other app on the device by just letting Android follow its defaults.

A: Try my hack, seems to work at least on 2.2 and above.
import java.lang.reflect.Field;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.ListView;

/**
 * This class fixes the lack of setVerticalScrollbarPosition(View.SCROLLBAR_POSITION_LEFT) before API level 11
 * @author Genadz Batsyan
 */

public class ListViewWithLeftScrollBar extends ListView {
    private static final String LOG_TAG = ListViewWithLeftScrollBar.class.getSimpleName();
    private static final boolean DEBUG = true;

    private boolean patchInvalidate;

    public ListViewWithLeftScrollBar(Context context) {
        super(context);
        moveVerticalScrollbarToTheLeft();
    }

    public ListViewWithLeftScrollBar(Context context, AttributeSet attrs) {
        super(context, attrs);
        moveVerticalScrollbarToTheLeft();
    }

    public ListViewWithLeftScrollBar(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        moveVerticalScrollbarToTheLeft();
    }

    @Override
    public void invalidate(Rect r) {
        invalidate(r.left, r.top, r.right, r.bottom);
    }

    @Override
    public void invalidate(int left, int top, int right, int bottom) {
        int width = right - left;
        if (DEBUG) log("invalidate original w:"+ getWidth() +" h:"+ getHeight()+"  rect:"+left+", "+top+", "+right+", "+bottom);
        if (patchInvalidate && right == getWidth() && top == 0 && bottom == getHeight() && width < 30) {
            // The above condition should ensure that ListView is VERY likely to be invalidating the scrollbar.
            // In fact ListView appears to not invalidate anything except the scrollbar, ever.
            left = 0;
            right = left + width;
            if (DEBUG) log("invalidate patched  w:"+ getWidth() +" h:"+ getHeight()+"  rect:"+left+", "+top+", "+right+", "+bottom);
        }
        super.invalidate(left, top, right, bottom);
    }

    private void moveVerticalScrollbarToTheLeft() {
        try {
            if (DEBUG) log("moveVerticalScrollbarToTheLeft: Trying API Level >=11");
            tryApiLevel11();
            if (DEBUG) log("moveVerticalScrollbarToTheLeft: API Level >=11 success");
        } catch (Throwable t1) {
            if (DEBUG) {
                log("moveVerticalScrollbarToTheLeft: API Level >=11 FAILED");
                t1.printStackTrace();
            }
            try {
                if (DEBUG) log("moveVerticalScrollbarToTheLeft: Trying hack for API Level <11");
                tryApiLevelPre11();
                patchInvalidate = true;
                if (DEBUG) log("moveVerticalScrollbarToTheLeft: API Level <11 hack success");
            } catch (Throwable t2) {
                if (DEBUG) {
                    log("moveVerticalScrollbarToTheLeft: API Level <11 hack FAILED");
                    t2.printStackTrace();
                }
            }
        }
    }

    @SuppressLint("NewApi")
    private void tryApiLevel11() {
        setVerticalScrollbarPosition(View.SCROLLBAR_POSITION_LEFT);
    }

    private void tryApiLevelPre11() throws Exception {
        Class<?> viewClass = View.class;

        Field scrollCacheField = viewClass.getDeclaredField("mScrollCache");
        scrollCacheField.setAccessible(true);
        Object scrollCache = scrollCacheField.get(this);
        if (DEBUG) log("scrollCache: "+ scrollCache);

        Field scrollBarField = scrollCache.getClass().getDeclaredField("scrollBar");
        scrollBarField.setAccessible(true);
        Object scrollBar = scrollBarField.get(scrollCache);
        if (DEBUG) log("scrollBar: "+ scrollBar);

        Field verticalThumbField = scrollBar.getClass().getDeclaredField("mVerticalThumb");
        verticalThumbField.setAccessible(true);
        Object verticalThumb = verticalThumbField.get(scrollBar);
        if (DEBUG) log("verticalThumb: "+ verticalThumb);

        Drawable verticalThumbDrawable = (Drawable) verticalThumb;
        Drawable replacementVerticalThumbDrawable = new LayerDrawable(new Drawable[]{ verticalThumbDrawable }) {
            @Override
            public void setBounds(int left, int top, int right, int bottom) {
                if (DEBUG) log("setBounds original: "+left+", "+top+", "+right+", "+bottom);
                int width = right - left;
                left = 0;
                right = left + width;
                if (DEBUG) log("setBounds patched:  "+left+", "+top+", "+right+", "+bottom);
                super.setBounds(left, top, right, bottom);
            }
        };
        verticalThumbField.set(scrollBar, replacementVerticalThumbDrawable);
    }

    private static void log(String msg) {
        Log.d(LOG_TAG, msg);
    }
}

A: you can add this in xml
android:verticalScrollbarPosition="left"

like this
<ScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:verticalScrollbarPosition="left"
    android:scrollbarThumbVertical="@drawable/scrollbar"
    />

or use this code in Kotlin
scrollView.verticalScrollbarPosition = View.SCROLLBAR_POSITION_LEFT


text:
Q: Is it possible to use JSON.parse on only half of an object in JS? I have a rather long JSON file that I am using https.request to get from a URL. When I run JSON.parse on the string that I receive, I get an "Unexpected end of JSON input" error because it seems like the JSON.parse has a limit to how many characters it can parse and it will cut it off around halfway through my JSON file. Is it possible to somehow parse only half of the string, or retrieve only half of a JSON file from a URL? I am using Javascript.

A: What you're looking at is at SAX-like parser. First search: is there a SAX parser that reads json and fires events ... or streaming json parser (duplicate)
Basically, when one reads a large file, one has to know if can keep the whole file as a buffer in memory or one can read it in chunks (or per char) and you can interpret it in chunks (as stream).


text:
Q: resolv.conf to localhost For about 2 hours I've been banging my head against a wall trying to get /etc/resolv.conf to use 127.0.0.1 instead of 127.0.0.53
I've just finished grep -r on my entire partition and cannot find where this damn file is coming from. Whenever I restart the service it defaults back to 127.0.0.53
This is actually just to get a dnsmasq (running in docker) to be a pass-through DNS.

A: Looks like Ubuntu since 17.10 (possibly) now uses netplan by default to provide it's DNS source.
My Default Ubuntu (bionic) looks like this
# Let NetworkManager manage all devices on this system
network:
  version: 2
  renderer: NetworkManager

This is why I later found NetworkManager through it's X/GTK frontend to be a suitable place to set the DNS (although I also did not know about nmcli). Apparently renderers supported so far are NetworkManager and networkd, although it's noted 1 that only NetworkManager supports WiFi.
I've yet to find a place to set this up so that it can work for all interfaces like the old method of editing /etc/resolv.conf, which doesn't work in vanilla 18.04 (maybe could, but it's a lot of work, I'm end-goal oriented).

A: pre-note: never manually edit /etc/resolv.conf
127.0.0.1 in /etc/resolv.conf comes from dnsmasq.
127.0.0.53 in /etc/resolv.conf comes from systemd-resolved.
dnsmasq and systemd-resolved should normally not run at the same time... as they tend to step on each others toes.
If you want dnsmasq to run, you have to tell systemd-resolved to back off, like so...
sudo pico /etc/systemd/resolved.conf

Change:
#DNSStubListener=yes

to:
DNSStubListener=no

Then reboot.


text:
Q: .net MVC, SelectLists, and LINQ I am new to using the Html.DropDownList in the MVC framework and am having a hard time understading how to select the data out my database to bind to the DropDownList. Is there an easy way to return a bindable list (such as a SelectList) from a standard LINQ query?

A: You want to use the select keyword in the LINQ query:
var foo = new SelectList(from x in FooRepository.Items
                         select new SelectListItem { Text = x.Name, Value = x.Id });

A: The SelectList constructor takes an IEnumerable so all you need to do is pass the LINQ query to the constructor like so
 var query = from c in customers
                        select c;

 var customerList = new SelectList(query, "CustomerId", "CustomerName");

You should do this in the Controller and have the SelectList in your ViewModel.

A:     var foo = FoorePository.Items.Select(s = > new SelectListItem
                                        {
                                          Text = s.Name, Value = s.Id.ToString()
                                        }
);

Sorry about formatting.


text:
Q: how to handle the output from javascript executor(selenium) in c# I have below line of code to find all the matching elements for the given string
 var coll = ((IJavaScriptExecutor)driver).ExecuteScript(string.Format(" var x = $(arguments[0]).find(\":contains('{0}')\"); return x;", strVerify), element);

when it finds the match it returns ReadOnlyCollection of IWebElement otherwise it returns ReadOnlyCollection of object.
I am trying to write a common method to handle the output of the above but i couldn't.
meth1 gives below error when it return ReadOnlyCollection of IWebElement
Unable to cast object of type 'System.Collections.ObjectModel.ReadOnlyCollection`1[OpenQA.Selenium.IWebElement]' to type 'System.Collections.ObjectModel.ReadOnlyCollection
public static ReadOnlyCollection<object> meth1(this IWebElement element, IWebDriver driver, string strVerify)
    {
        return (ReadOnlyCollection<object>)((IJavaScriptExecutor)driver).ExecuteScript(string.Format( " var x = $(arguments[0]).find(\":contains('{0}')\"); return x;", strVerify), element);
    }

methd2 gives below error when it return ReadOnlyCollection of object
"Unable to cast object of type 'System.Collections.ObjectModel.ReadOnlyCollection1[System.Object]' to type 'System.Collections.ObjectModel.ReadOnlyCollection1[OpenQA.Selenium.IWebElement]'."}
public static ReadOnlyCollection<IWebElement> methd2(this IWebElement element, IWebDriver driver, string strVerify)
    {
        return (ReadOnlyCollection<IWebElement>)((IJavaScriptExecutor)driver).ExecuteScript(string.Format(" var x = $(arguments[0]).find(\":contains('{0}')\"); return x;", strVerify), element);
    }

How can i write one method to handle both of these outputs.
I really appreciate any help on this. Thanks in advance


text:
Q: Browserify-shim with gulp I'm testing out gulp with browserify and I'm trying to get the following working:
I have a file called export.js, which depends on another file called export2.js.
export.js
module.exports = function(){
    console.log("test export");
};

export2.js
module.exports = function(){
    console.log("export 2");
}

I have another file called app.js, where I define the following code:
var e = require("e");

I tried to define the dependency by using a shim.
The related code in my package.json looks like this:
  "browserify-shim": {
        "jquery": "$",
        "public/src/js/home/export.js":  {
            "exports": "e",
            "depends": [
              "public/src/js/home/export2.js"
            ]
        }
  },
  "browserify": {
      "transform": [
          "browserify-shim"
      ]
  },

The path should be correct.
My gulp file defines:
//Uglifies scripts
gulp.task("uglify-scripts", function(){
    return browserify({ entries:["public/src/js/home/app.js"]})
            .bundle()
            .pipe(source("bundle.js"))  // gives streaming vinyl file object
            .pipe(buffer())             //convert from streaming to buffered vinyl file object
            .pipe(uglify())             //gulp-uglify
            .pipe(gulp.dest("public/src/js/home/dist"))
            .pipe(livereload());

});

I tested the task before (uglification of app.js without the dependency), it runs fine.
However, with the shim defined, I still receive a message in the console mentioning

Cannot find module 'e'

Can you see what is going wrong or what I have misunderstood?

A: Shims are for modules that don't support commonJS. You can simply define these dependencies explicitly:
export.js
var e2 = require('./export2.js');
module.exports = function(){
    console.log("test export");
};

export2.js
module.exports = function(){
    console.log("export 2");
};

app.js
var e = require('public/src/js/home/export.js');


text:
Q: More efficient Update query (MS SQL Server 2008) I'm trying to update multiple columns from TableA below with a corresponding ADDR_IDs from TableB.  This is a snippet, in reality I have 30 Locations in TableA and 30 EXT_IDs in TableB so doing Update statements would take an eternity.  The problem is that any one of the 30 Locations in TableA could exists in any of the 30 EXT_IDs in TableB.
For example, in TableA, ID = 44231, Location A35555 might match up in TableB in EXT_ID_27, so im really hoping someone can suggest a better alternative than 900 update statements...
SQL Fiddle below
TableA
+---------+-----------+-------------------------------------+----------------+-------------------------------------+
| ID      | LOC_1     | LOC_1_ADDR_ID                       | LOC_2          | LOC_2_ADDR_ID                       |
+---------+-----------+-------------------------------------|----------------+-------------------------------------|
| 44231   | A35555    | Trying to Populate Should Be Z76543 | B68754         | Trying to Populate should be Z45545 |
| 87563   | A36666    | Trying to Populate Should Be Z83465 | Q23548         | Trying to Populate should be Z89224 |
| 85387   | R14587    | Trying to Populate Should be Z66371 | A35555         | Trying to Populate should be Z93827 |
+---------+-----------+-------------------------------------+----------------+-------------------------------------|

TableB ( EXT_ID is unique per REC_ID but multiple REC_ID's could have the same EXT_ID)
+---------+-----------+-------------+-----------+-----------+
| REC_ID  | ADDR_ID_1 | EXT_ID_1    | ADDR_ID_2 | EXT_ID_2  | (28 more external ID columns)
+---------+-----------+-------------+-----------+-----------+
| 44231   | Z76543    | A35555      | Z45545    | B68754    |
| 87563   | Z83465    | A36666      | Z89224    | Q23548    |
| 85387   | Z93827    | A35555      | Z66371    | R14587    |
+---------+-----------+-------------+-----------|-----------+

http://sqlfiddle.com/#!3/02d5c/5/0
Thanks for any suggestions!

A: If your 30 column "pairs" in table B are in fact repeated data with the same meaning (a location key/address pair), then the design should be only 2 columns with more data. The actual table isn't following this design, but the data you query can.
SELECT EXT_ID_1 AS EXT_ID, ADDR_ID_1 AS ADDR_ID FROM TableB UNION ALL
SELECT EXT_ID_2 AS EXT_ID, ADDR_ID_2 AS ADDR_ID FROM TableB UNION ALL
SELECT EXT_ID_3 AS EXT_ID, ADDR_ID_3 AS ADDR_ID FROM TableB UNION ALL
...
SELECT EXT_ID_30 AS EXT_ID, ADDR_ID_30 AS ADDR_ID FROM TableB

This gets you two columns of data, which is easier to write a query against. Dump this in a temporary table (or a table variable) and you can go ahead with 30 UPDATE statements, which is better than 900.
Alternatively, you could try this in a single statement :
WITH (
  SELECT EXT_ID_1 AS EXT_ID, ADDR_ID_1 AS ADDR_ID FROM TableB UNION ALL
  SELECT EXT_ID_2 AS EXT_ID, ADDR_ID_2 AS ADDR_ID FROM TableB UNION ALL
  SELECT EXT_ID_3 AS EXT_ID, ADDR_ID_3 AS ADDR_ID FROM TableB UNION ALL
  ...
  SELECT EXT_ID_30 AS EXT_ID, ADDR_ID_30 AS ADDR_ID FROM TableB
) AS SimplifiedTableB
UPDATE TableA
SET
  LOC_1_ADDR_ID = COALESCE(TableB1.ADDR_ID, LOC_1_ADDR_ID),
  LOC_2_ADDR_ID = COALESCE(TableB2.ADDR_ID, LOC_2_ADDR_ID),
  LOC_3_ADDR_ID = COALESCE(TableB3.ADDR_ID, LOC_3_ADDR_ID),
  ...
  LOC_30_ADDR_ID = COALESCE(TableB30.ADDR_ID, LOC_30_ADDR_ID)
FROM
  TableA
  LEFT JOIN SimplifiedTableB AS TableB1 ON TableA.LOC1 = TableB1.EXT_ID
  LEFT JOIN SimplifiedTableB AS TableB2 ON TableA.LOC2 = TableB2.EXT_ID
  LEFT JOIN SimplifiedTableB AS TableB3 ON TableA.LOC3 = TableB3.EXT_ID
  ...
  LEFT JOIN SimplifiedTableB AS TableB30 ON TableA.LOC30 = TableB30.EXT_ID

I would recommend testing this beforehand, however, both for correctness and performance reasons.

A: Noticed this is answered and since I was working on this anyway, here is an alternative ..
Some info received from Unpivot multi columns
select tblB.REC_ID, tblB.ADDR_ID, tblB.EXT_ID
into #tempTableB
from
(
  select REC_ID, ADDR_ID, EXT_ID
  from TableB
  Unpivot
    (
      ADDR_ID for ADDR_IDS in (ADDR_ID_1, ADDR_ID_2)
    ) as UnPvtADDR
  Unpivot
    (
      EXT_ID for EXT_IDS in (EXT_ID_1, EXT_ID_2)

    ) as UnPvtEXT
  where RIGHT(ADDR_IDS, 1) = RIGHT(EXT_IDS, 1)
) tblB

-- [depend on number of records in #tmepTableB]
-- Create Index on #tempTablB.REC_ID to improve performance if required

update tblA
set LOC_1_ADDR_ID = (select ADDR_ID from #tempTableB where REC_ID = tblA.ID and EXT_ID = tblA.LOC_1)
, LOC_2_ADDR_ID = (select ADDR_ID from #tempTableB where REC_ID = tblA.ID and EXT_ID = tblA.LOC_2)
-- .. and the rest of the columns
from TableA tblA
  inner join
  #tempTableB tblB
on tblA.ID = tblB.REC_ID
where tblA.ID = tblB.REC_ID

select * from TableA


text:
Q: How to create CellTree with MVP pattern As suggested in gwt documentation, I try to follow the MVP design pattern while creating my application. When using simple tree, the example in the documentation is straight forwards and makes good example of MVP and gwt. In the example the view is created and the data is given to the view to display. As far as I understand this is exactly the way to keep view, model and presenter separated.
With CellTree, the data populating happens inside the TreeViewModel's data provider. Data provider cannot be taken outside the cell tree and therefore I need to do all data populating inside the cell tree, which is in the view. Now, the view needs to know about the model and the MVP patter is broken. I wan't to dynamically populate data to the cell tree prior to showing it to user, I need to edit the data in cell tree and save it later for different format.
My question goes how to implement CellTree, or in general Cell widgets, in MVP design patter?

A: I have used CellTable with MVP.
UI:
<g:HTMLPanel>
    <g:ScrollPanel>
        <p1:CellTable ui:field="cellTable" width="100%" styleName="style.cellTable" height="100%" />
    </g:ScrollPanel>
</g:HTMLPanel>

View Interface:
public interface SomeCellListView extends IsWidget {
    void setPresenter(Presenter listener);

      // Method to set the CellTable data
    void setCellList(ArrayList<ObjectDTO> list);

    public interface Presenter {
        void goTo(Place place);
        void doSomething(int id);
    }
}

View Implementation:
   public class SomeCellListViewImpl extends Composite implements SomeCellListView {

... all Ui Binder stuff here

@UiField(provided = true)
CellTable<ObjectDTO>cellTable = new CellTable<ObjectDTO>();

SomeCellListViewImpl(){
    TextColumn<ObjectDTO> someColumn= new TextColumn<ObjectDTO>(){
        @Override
        public String getValue(ObjectDTO o) {
            return o.getSomeFieldValue();
        }
    };
    cellTable.addColumn(someColumn, "column1");

    ... add other columns here
}

// This method is called from Presenter to set CellTable data
public void setCellList(ArrayList<ObjectDTO> list) {
    cellTable.setRowCount(list.size(), true);
    cellTable.setRowData(0, list);
}

}
Activity (or Presenter):
// Set view and service in the constructor (Get the view from ClientFactory)
public void start(AcceptsOneWidget containerWidget, EventBus eventBus) {
// Make RPC call
this.service
.getCellList(new AsyncCallback<ArrayList<ObjectDTO>>(){

    @Override
    public void onFailure(Throwable caught) {
        view.setError("Error fetching details");
    }

    @Override
    public void onSuccess(ArArrayList<ObjectDTO> result) {
        view.setCelllist(result);
    }

});
view.setPresenter(this);
containerWidget.setWidget(view.asWidget());

}
Here, the view is already created by ClientFactory. View contains just the layout for CellTable. Data is not loaded when view is created. When an Activity is started (aka Presenter), the "start" method is invoked. Here we make the RPC to get Cell data and call a method in the view to set the data.
I've not used CellTree. But you asked in general about Cell widgets. Hence thought of sharing this. Hope this helps.

A: i have the same issue with OP. I read the MVP tutorial part II, and then try to use CellTable in my application, while still keep the MVP architect. But i confuse at the part: the tutorial use the syntax like Presenter, but why you only use Presenter ?


text:
Q: How to print all elements in a 2D map given the 1st index As the title says I want to print out all the elements of "group1" in this 2D map. I tried this but I just get a huge error at the for loop.
#include<iostream>
#include<string>
#include<map>
using namespace std;

int main(){
  map<string,map<int,double> > myMap;
  myMap["group1"][13] = 10.41;
  myMap["group1"][15] = 31.2;

  //print all elements in "group1"
  for (map< string, map<int,double> >::const_iterator iter =
       myMap["group1"].begin(); iter != myMap["group1"].end(); ++iter)
       {
         cout << iter->first << '\t' << iter->second << '\n';
       }

  return 0;
}

Any help would be appreciated, thanks!

A: You want an iterator to your internal map<int,double>, whereas you are trying to get and iterator to your outer map<string,map<int,double> >:
int main() {
    map<string, map<int, double> > myMap;
    myMap["group1"][13] = 10.41;
    myMap["group1"][15] = 31.2;

    //print all elements in "group1"
    for (map<int, double>::const_iterator iter =
        myMap["group1"].begin(); iter != myMap["group1"].end(); ++iter)
    {
        cout << iter->first << '\t' << iter->second << '\n';
    }

    return 0;
}

A: The type of myMap["group1"] is map<int,double> and not map<string,map<int,double>>
Then your code would look somehow like this:
const map<int,double> &grp1map = myMap["group1"];
for (map<int,double>::const_iterator iter = grp1map.begin(); iter != grp1map.end(); ++iter)
{
    cout << iter->first << '\t' << iter->second << '\n';
}

You can simplify this with auto:
auto &grp1map = myMap["group1"];
for (auto iter = grp1map.begin(); iter != grp1map.end(); ++iter)
{
    cout << iter->first << '\t' << iter->second << '\n';
}

But anyway you should do it like this:
for (auto &elem : myMap["group1"] )
{
    cout << elem.first << '\t' << elem.second << '\n';
}


text:
Q: How to update the pre-installed application using ADB command ? I have tried with adb install -r  but its not working at all . I dont want to update through Google Play Store. Android OS version is 4.0 and device isn't rooted .

A: If adb install -r not working, then it indicates your apk is not the update to the pre-installed one in your device.
adb install -r should work for updating apks signed with same keystore.


text:
Q: VS Code change file extension at file save as dialog On some files I need to change standard save as file dialog.
I want to use custom command that executed 'workbench.action.files.saveLocalFile' command with some params that can change availible file extensions.
Where I can find the params if they exist?
Another way:

*

*Custom command with showSaveDialog (my own vscode.SaveDialogOptions)

*Close unsaved editor

*Open saved file in editor
At step 2 I use 'workbench.action.closeActiveEditor' command, but I can see confirm dialog (Do you want to save the changes...)

How to remove this confirm?


text:
Q: How can I change text in capitals to proper sentence case in Excel? "IF I WRITE THIS IN EXCEL IN CAPITAL LETTERS", I want to be able to change this to "If I write this in excel in capital letters" using a formula.
What formula would I need to use to achieve this?

A: There isn't a formula for proper capitalization of a sentence. You would have to use both the UPPER and LOWER functions to achieve what you want with some string manipulation. For example:
= UPPER(LEFT(A1)) & LOWER(MID(A1, 2, LEN(A1)-1))

A: Perfect, but because  the sentence is already in upper case, you can go shorter.
=left(A1) & lower(right(A1,len(A1)-1))


text:
Q: Is there a way to know which button was pressed without making a new handler in JS? I want to use the same button handler for a vanilla JS script. Is there a way to use something like an event handler to get the ID of the button which was pressed, and pass that into the subroutine?
Pseudocode to get the point across
document.addEventListener('buttonClick', (event) => {
    drawComponent(event.clientX, event.clientY, event.buttonID);
})

I'm using ASP.Net MVC, electron, and the Razor View Engine if that's relavent.

A: Use event.target
document.addEventListener('buttonClick', (event) => {
    console.log("element: " + event.target);
    drawComponent(event.clientX, event.clientY, event.buttonID);
})


text:
Q: How do I externalize configuration with Spring Boot? It's just not working. I saw the docs at
https://docs.spring.io/spring-boot/docs/1.5.19.RELEASE/reference/htmlsingle/#boot-features-external-config
I saw the answers at
Spring boot externalize config properties/messages on Java annotations
I have
    MailTrainAPI mt = new MailTrainAPI();
    mt.sendMail(map);

...

@Component
public class MailTrainAPI {
    @Value("${mailtrain.url}")
    private String API;

    public void sendMail(MultiValueMap<String, String> map) {
        System.out.println("API = "+API);
        API = System.getProperty("mailtrain.api");
        System.out.println("API = "+API);
        API = System.getenv("mailtrain.api");
        System.out.println("API = "+API);

src/main/resources/application.properties
mailtrain.url=http://mail.galaxy.store/api/send/galaxybadge

It prints
API = null
API = null
API = null

It doesn't work because I instantiate the class myself and Spring doesn't know about it. How do I access the property in the application.properties file manually?
Spring Boot 1.5.21

A: I was able to fix it with
public void sendMail(MultiValueMap<String, String> map) {
    try {
        setAPI();
    } catch (IOException e) {
        Logger.error(this.getClass(), "sendMail()", "Cannot send mail. Cannot load mailtrain.url property: " + e.getMessage());
        return;
    }
    if (API == null) {
        Logger.error(this.getClass(), "sendMail()", "Cannot send mail. Cannot load mailtrain.url property.");
        return;
    }
    System.out.println("API = "+API);
    ...

private void setAPI() throws IOException {
    InputStream is = this.getClass().getResourceAsStream("/application.properties");
    Properties p = new Properties();
    p.load(is);
    API = p.getProperty("mailtrain.url");
}

But I thought there would be an easier and better way with less fluff.

A: MailTrainAPI is supposed to be a Spring bean, aka a component, automatically scanned because of the @Component, and then injected with the @Value("${mailtrain.url}").
However, you create a separate instance of the class yourself when you call new MailTrainAPI(). Don't do that.
Your code using the object must receive it using injection into a field, e.g.
@Autowired
private MailTrainAPI mt;


text:
Q: how can I find elements of a list that are not included in another haskell list I'm new to haskell and wanted to make the set difference between two haskell lists. For instance, I have list a and b and want a-b, i.e. [4,5,6,7].
let a = [1,2,3,4,5,6,7]
let b = [1,2,3]

Is there any built in function for doing this operation.

A: You can use the (\\) operator in Data.List, be warned that it only removes the first instances of each, so
> [1..7] \\ [1..3]
[4,5,6,7]
> [1,1,1] \\ [1,2]
[1,1]

If you want a true "set difference", use Data.Set:
> import qualified Data.Set as Set
> Set.fromList [1..7] Set.\\ Set.fromList [1..3]
> Set.fromList [1,1,1]
fromList [1]
> Set.fromList [1,1,1] Set.\\ Set.fromList [1,2]
fromList []


text:
Q: Laravel 5 - stay logged in forever I wanted to put in the login page a checkbox "stay logged in".
That should never end the session of the user unless the user logs out.
I know that in app/config/session.php I have these variables:
'lifetime' => 60,

'expire_on_close' => false,

But I wanted to maintain alive the session forever, and not be removed if the user close his navigator.
Any ideas on how should I proceed?
Thanks

A: You can set lifetime option to 35791394. It's a maximum possible number for 32-bit machines:
'lifetime' => 35791394, // Session will expire in 68 years.

A: You can set some big values. I have tried now at 7900 years

i.e, 365*24*60*7990 = 4152240000 minutes

  'lifetime' => 4152240000

A: Laravel has a built-in feature to remember users, I'd strongly recommend using it.

If you would like to provide "remember me" functionality in your
  application, you may pass a boolean value as the second argument to
  the attempt method, which will keep the user authenticated
  indefinitely, or until they manually logout. Of course, your users
  table must include the string remember_token column, which will be
  used to store the "remember me" token.

if (Auth::attempt(['email' => $email, 'password' => $password], $remember)) {
    // The user is being remembered...
}

if you want to solve the problem manually, there is workaround for this: you have to set the expires date of your cookie to a date in the wide future, somewhat like 2050. this is technically not forever, but should usually be long enough.


text:
Q: Make an image button change a different image on page I have an image at the top of the page called grid.png. There are a series of image buttons below the image. I want each image button to change the image grid to a different image (ex. grida.png, gridtable.png, etc.). I currently have it so each image button changes to a different xml page with an identical layout but with a different image in the place of grid.
However, the image button action only works on the main xml page and not any of the other pages. How would I be able to make the buttons switch grid to a different image without switching pages or make the buttons on the other pages function in the same way they do in main.xml?

A: Don't change the whole layout (you only need one), just change the contents of ImageView when one of your ImageButtons gets clicked:
final ImageView imageView = (ImageView)findViewById(R.id.imageView); // your ImageView "grid"

// then do this for each of your buttons
findViewById(R.id.imgButton1).setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            // set new content of ImageView here
            imageView.setImageResource/Drawable/Bitmap(...);
        }
    });


text:
Q: Does any .NET ORM support localized entities out-of-the-box? I need to store localized entities in a database (for instance a Product, which has a Name, which is different in English and Danish). There are several well-known ways to do this, for instance having some sort of a resource table containing the values of the localized columns.
However, this does not seem to be very easy to fit into an ORM, when I want to retrieve an instance of the Product class in the English language and expect the value of the Name property to be English.
I don't want to reinvent the wheel, and I think this is a problem that must be very common.
Does any ORM support entity localization out-of-the box ?
Since I am on the Microsoft stack, and obvious choice for an ORM would be Entity Framework 4. Are there any features in EF4 to support this ?

A: AFAIK EF4 does not provide anything like this.
Dmitri Maximov has written a good series of post covering implementation of localization for DataObjects.Net, the info there may be helpful for you even if you're using (or going to use) any other framework:

*

*Localization support, part 1. Theory

*Localization support, part 2. Domain modeling

*Localization support, part 3. CRUD operations

*Localization support, part 4. Queries - a bit outdated, I'd better recommend you to view code of working localization sample.

A: I have the exact same problem (localize content, MS stack, ORM...) and for the moment I go with Resource/ResourceValue tables.
I use Linq-to-SQL with PLINQO templates that I've slightly tuned to generate auto localized Properties in my entities.
The template detects foreign keys to the Resource table and create an appropriate column.
For example if I have a Product Table with an int NameID FK column, it will create a string Name Property on my Product class returning the appropriate value depending on the current Thread culture.
The cons are:

*

*complexity for INSERTS / UPDATES (must play with 3 tables, but Linq2Sql make it not so difficult)

*browsing tables in SQL Management is painfull because Text columns are just foreign keys

I found this question looking after a "best practice" solution, but it I havn't found one yet.

A: Maybe you have to look further, I would use NHibernate, and an interceptor to catch the load of an entity and do the localization of the entity, based on the current culture of the application and some way of store the localized strings.
Some resources:
http://elegantcode.com/2008/05/15/implementing-nhibernate-interceptors/
http://knol.google.com/k/fabio-maulo/nhibernate-chapter-11/1nr4enxv3dpeq/14#


text:
Q: Re-use web service response across datasets or subreports I'm using a web service as my XML datasource which returns entities including multiple hierarchical data like below (codes modified for project privacy);
public class UserData {
    // some scalar properties
    public string Id ...
    public string Name ...
    public string Surname ...

    // some navigational properties
    public Address address ...
    public CourseInfo[] courses ...
    public AwardInfo[] awards ...
}

To show all the entity information inside the same report, I can create different datasets in my report to call my web service and filter preferred parts of the returned service response.
To get only UserData properties:
<Query>
    <Method Name="GetUserData" Namespace="UserApp.ReportingServices"/>
    <SoapAction>UserApp.ReportingServices/IReportingService/GetUserData</SoapAction>
    <ElementPath IgnoreNamespaces="true">GetUserDataResponse{}/UserData</ElementPath>
</Query>

To get Address information together with UserData properties:
<Query>
    <Method Name="GetUserData" Namespace="UserApp.ReportingServices"/>
    <SoapAction>UserApp.ReportingServices/IReportingService/GetUserData</SoapAction>
    <ElementPath IgnoreNamespaces="true">GetUserDataResponse{}/UserData/Address</ElementPath>
</Query>

To get course information together with UserData properties:
<Query>
    <Method Name="GetUserData" Namespace="UserApp.ReportingServices"/>
    <SoapAction>UserApp.ReportingServices/IReportingService/GetUserData</SoapAction>
    <ElementPath IgnoreNamespaces="true">GetUserDataResponse{}/UserData/Courses/CourseInfo</ElementPath>
</Query>

My question raises right here: If I use multiple dataset queries like above, my report will make a web service call for every dataset it has though my service always returns the same XML response which includes all the data needed for the three datasets above.
Is there any way to re-use returned XML response of a query for the other datasets? If it would possible, my report would call the web service only one time, and datasets would filter different parts of that XML response without calling the web service again and again.
If this is not possible, than what's the best practice about showing multiple hierarchical data inside the same report? Do I have to create different web services returning different hierarchical parts of the data?

A: Reporting Services datasets are limited to a simple table of rows and columns - they can't handle data with multiple hierarchies as you have described.
I would redesign your web service to reflect this, probably splitting it into the three sets of data you described. Then there will be three web service calls, but without the duplication of content.  They will also be executed in parallel which will probably be more efficient overall than your current design.


text:
Q: redirect after authentication in zend framework 2 I am trying to implement a control to check if the password is expired whenever a user authenticates. I am using a ListenerAggregateInterface to listen to the ZfcUser event authentication.success.
After I perform my check I am not able to redirect the user to the change password page. How can I do that?
Looking around, usually people have a MvcEvent and so they can use the method getReponse to modify the headers and perform a 302 redirect, or they use redirect functionality available in controllers. In my case I have an AdapterChainEvent and I'm not in a controller.
Any hint is highly appreciated

A: All you would need to do is return a response instance; it doesn't need to be the response instance (although you could inject it into your listener aggregate if you register the aggregate via the service manager).
This will stop event propagation an return the response to the controller. The ZfcUser\Controller\UserController will then return this performing the redirect.


text:
Q: Moving to previous form I'm trying to move back to the previous form with the information I filled out on it, but when i click the previous button it just generates a new previous form. Heres my code for both next and previous. Is there any way to move back to a previous form with the information I put in already without generating a new previous form? thanks.
//moves to next form
    public void next()
    {
        Form3 f4 = new Form3();
        f4.Show(this);
        Hide();
    }

    //Moves to previous form
    public void Back()
    {
        Form1 f1 = new Form1();
        f1.Show(this);
        Hide();
    }

A: Problem : You are creating new instance of Form1 in Back() method so eachtime it creates a New Form1 instance in memory and displays the same to you rather than displaying the existing Form1 which hasbeen filled with values (already hidden) by taking it from memory.
Solution: You can use Application.OpenForms[] to get the required Form which is already available in memory.
Try This:
//Moves to previous form
public void Back()
{
  Form myform = (Form1)Application.OpenForms["Form1"];
  myform.Show();
}

A: ou could show form f4 using ShowDialog() instead of Show(). This would bring execution back to form f1 after form f2 has closed.

A: In Form2 :
private void button1_Click(object sender, EventArgs e)
{
    this.Hide();
    formRegistration.ShowDialog();
    // We get here when formRegistration's DialogResult gets set
    this.Show();
}

A: Agree with @Sudhakar.
Alternative:
public void next()
{
    Form3 f4 = new Form3(this);
    this.Hide();
    f1.BringToFront();
    f4.Show();

}
public void Back()
{
    Form1 f1 = new Form1(this);
                this.Hide();
                f1.BringToFront();
                f1.Show();
}

Also, add something into all your form class and constructors:
Form storedPrev;

public Form1(Form prev)
{
    this.storedPrev = prev;
}

In your form closing event handler, add this code:
storedPrev.Show();


text:
Q: Best practices of creating a filesystem representation on the frontend I want to create a web interface for a folder structure on my server. Basically like dropbox or any other cloud storage but only with read functionality, no creation of new files or uploading.
I'm wondering what the best way would be to create a "virtual" representation of an existing folder structure on my server.
My idea was to recursively loop through the directory on the server and create a database entry for every file or folder. I'd create a hash of every file to uniquely identify them.
Like this:
'1382b6993e9f270cb1c29833be3f5750': {
    type: 'folder',
    name: 'root',
    path: '/',
    parentPath: null,
    parentID: null,
    children: ['147d0ef33fe657ce53a83de6a630473d']
  },
'147d0ef33fe657ce53a83de6a630473d': {
    type: 'folder',
    name: 'pictures',
    parentID: '1382b6993e9f270cb1c29833be3f5750',
    parentPath: '/',
    path: '/pictures',
    children: ['8f7c5959dbb088c0aef8b145dbdf6e43']
  },
'8f7c5959dbb088c0aef8b145dbdf6e43': {
    type: 'file',
    name: 'cat.jpg',
    parentID: '147d0ef33fe657ce53a83de6a630473d',
    parentPath: '/pictures',
    path: '/pictures/cat.jpg'
  },

To account for changes in the directory I'd periodically run a process to scan it and update the database accordingly.
It should be said that the directory is rather big with many subfolders and hundreds of files.
Since the whole folder structure is rather big I could see it being a problem to keep the whole tree in the react state, but I guess that could be fixed by always fetching the directory contents when navigating on the frontend.
Does this approach make sense or is there a better way?

A: You can either optimize the disk usage or the CPU usage based on what is more convenient for you. It is just a tradeoff between the two in the end.
If you want to maximize your CPU load and know that disk space is cheap, you can store the content of your entire filesystem's tree representation like you did and make periodic updates. The main pro is that you will have a very little CPU footprint and if your app is used by many users, your server won't be overloaded by API requests. The main cons is that is takes a lot of CPU and disk usage once in a while when you need to periodically update your filesystem's tree and you may have synchronization issues (when a file has been created but not stored in the database).
In the database aspect of things, a high-readonly purpose database should be constructed using NoSQL database instead of SQL database when there is little to no relations between data and/or you want fast read access to them in a large scale.
If you want to stick to SQL databases, you should be using a foreign key for storing the parent folder such as when creating a database entry for a file, you can do something similar.
INSERT INTO files(path, type, parent) VALUES("/home/johndoe", "FOLDER", 987126398726387)

Where 987126398726387 would be the id column of a files row related to the /home folder for instance. That way your reconciliation folder's algorithm will be very simple since you will only make a single request to retrieve all files for a folder.
SELECT * FROM files WHERE parent = 987126398726387;

And you can use all the power of your SQL to order, group and do the stuff that you might want to do there.
Instead of loading your disk usage, you can trade disk usage for more CPU usage by completely removing your database and having a single API endpoint that looks like https://api.com/folders/:tree, where tree is the folder's tree requested by the client.
For instance, if I start the application, I'll probably want to request the https://api.com/folders/ endpoint, and you can send only the content of that folder without its subfolder, thus removing the need for a recursive algorithm. Then, if I need to go in the /home folder, I can call the https://api.com/folders/home endpoint. Then, I'll go in the /home/johndoe folder with https://api.com/folders/home/johndoe, and in the /home/johndoe/code folder with https://api.com/folders/home/johndoe/code, etc...
You can even pass the requested path in the body of your asynchronous HTTP request from the client instead.
GET /folders HTTP/2
Host: api.com
Content-Type: application/json

{
  "path": "/home/johndoe/code"
}

You can display a loader while you are updating the current folder on the client side while the API respond. This will obviously make much more API calls but you save a lot of disk usage by doing that. And if you need speed or less CPU usage, you can use a compiled language like V, Go or Rust for that and make a microservice that the sole purpose is to get the content of a folder fast.


text:
Q: Cardview not allowing child views Anyone know why I would not be allowed to put any child views in a card view?
Lint (i think) is throwing a fit when I try to fill my cardview with content.

A: A bit late to the party but I've had this same problem and the fix seems to be to add this line in the build.gradle file, then sync the project. This way Gradle/Android Studio knows what CardView is and how to provide hints:
compile 'com.android.support:cardview-v7:26.0.+'


text:
Q: NSIS Installer with .NET 4.0 Is there a standard/preferred method for automatically downloading and installing the .NET 4.0 Framework from an NSIS installer, if the machine doesn't already have it?
There are several examples for making this work on older versions of the framework, but seemingly none of them work for 4.0.  Before I hack something together myself, I wanted to see if anyone here knew of something already out there.
Thank you for your time.

A: What is the problem?  The solution should be the same as for any other .NET version.
Something like this should work:
ReadRegDWORD $0 HKLM "SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Client" Install
IntOp $8 $0 & 1

Result is in reg $8
Substitute Client with Full to detect the non-client version.

A: Why not simply include the .NET 4.0 redist with your NSIS installer and execute it when you don't detect 4.0 registry entries?
If you think that 50 MB is too much to package with your installer then download it only when needed.
It would help if you listed what you've tried that has not worked. (I suspect that you've probably seen the 3rd link and the lang spec trips you up?)


text:
Q: How to take the last line and copy the required columns I would welcome any help with getting a script to work on Form onSubmit to then take the last line (New Form submitted information) from the sheet 'New Orders' to then copy the required columns into the 'DIBOND ORDERS' sheet so it will automatically place the required product for the new customers order onto the required order sheet to be ordered from the different suppliers.
As we have a few different suppliers for clothing, pavements stands, display products.
My Current Code Is
   function onEdit() {

 var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getActiveSheet();
var r = ss.getActiveRange();
if(s.getName() == "New Orders" && r.getColumn() == 5 && r.getValue() == "DIBOND") {

    var row = r.getRow();

    var numColumns = s.getLastColumn();

    var TSS = ss.getSheetByName("DIBOND ORDERS");
             var lastRow = TSS.getLastRow()+1;
      var cntr = 0
    s.getRange(row,2).copyTo(TSS.getRange(lastRow + cntr,1), {contentsOnly:true});
    s.getRange(row,5).copyTo(TSS.getRange(lastRow + cntr,2), {contentsOnly:true});
    s.getRange(row,6).copyTo(TSS.getRange(lastRow + cntr,4), {contentsOnly:true});
    s.getRange(row,4).copyTo(TSS.getRange(lastRow + cntr,8), {contentsOnly:true});
    s.getRange(row,7).copyTo(TSS.getRange(lastRow + cntr,5), {contentsOnly:true});
    s.getRange(row,8).copyTo(TSS.getRange(lastRow + cntr,6), {contentsOnly:true});
    s.getRange(row,9).copyTo(TSS.getRange(lastRow + cntr,7), {contentsOnly:true});
    //s.deleteRow(row);
}}

This Works Prefect if I am on the sheet as a On Edit Function but cannot get it to activate as On Form Submit function.
I have been trying find a way to remove the Active Sheet, Active Range... to be set for the get Last Row by using
 SpreadsheetApp.openById("ID").getRangeByName("New Orders");

Starting to think that it cannot be done or I am missing something.
Would be truly grateful for any help.
Thank you in advance Russell.

A: This will get the last line on the active spreadsheet ( the one onEdit was called ) and the sheet named "DIBOND ORDERS".
function getLastLine(){
  var ss    = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("DIBOND ORDERS");
  var range = sheet.getDataRange(); // gets all the data.
  var values = range.getValues();
  Logger.log("LAST ROW : " + values[values.length -1] );
}


text:
Q: How to dig up, through a level surface? I can dig out staircases upwards, but how do I actually cross the surface?
____
#X##
#X##       _ is the ground surface
#X         X are staircases
####       # is earth

A: Dwarf Fortress uses a Wall/Floor system to handle its staircases. That is to say, to connect between two different z-levels, you need a down stairs on the floor of one level, and an upstairs on the wall of the level below that. (An up / down stairs is simply any tile with both an up stair in the wall and a down stair in the floor).
When breaching a surface from below, this means that all you need to do is designate a downwards stairs on the surface tile itself. If there is an up stair on the z-level directly below it, dwarves will be able to access it upwards.

A: So there are several ways to do this.  It depends on whether you want stairs (straight up/down connections) or ramps (diagonal up/down connections), and whether you want to mine the upward path into a "natural wall" tile on the lower level (anywhere not yet mined) or build it into an open space.
If you have a natural wall on the lower level that you're willing to mine into and you want to make stairs:

*

*Mine an "up stair" (d-u) or "up/down" (d-i) stair into the lower wall tile.

*Mine a "down stair" (d-j) or "up/down" stair into the tile directly above that one.

If you have a natural wall tile on the lower level that you're willing to mine into and you want to use a ramp:

*

*Mine an "up ramp" (d-r) on on the lower wall tile.

*Pick a wall tile adjacent to your new ramp on the lower level.  If there isn't one, construct one (b-C-w).

*Mine the tile above the wall you just picked/built, however you like. You can put another up ramp or some stairs there if you plan to keep going up, for example.

If you want to construct stairs in open space:

*

*Build "up stairs" (b-C-r) in an empty tile.

*Mine "down stairs" (d-j) or "up/down stairs) (d-i) into the space immediately above.

If you want to construct a ramp in open space:

*

*Build an "up ramp" (b-C-r) in an empty tile.

*Channel (d-h) the tile directly above the new up ramp. (Your dwarves can reach the upper tile now from the ramp, but unlike with mined up ramps, they won't automatically mine it as part of creating the ramp itself.)

*Pick a wall tile adjacent to your new ramp on the lower level.  If there isn't one, construct one (b-C-w).

*Mine the tile directly above the wall tile you just chose or built. As for mined ramps, you can put stairs or another ramp there if you want.

Some extra notes:

*

*See this answer for why you need the adjacent walls when using ramps. Once you're all done, make sure not to mine out those walls later or your ramps will stop working. If you ever do mine them by mistake, just rebuild them with b-C-w to make your ramp usable again.

*To target a tile directly above something, here's an easy way to line it up. Start on the lower level, and press (d-j) or (d-h) as applicable. Then, line your cursor up with the tile you want to be on top of. Next, hit < to go up, and hit enter twice to designate the tile without moving your cursor. It may just look like your designation is floating in empty space if you're mining up into an unexplored level, but if it's positioned as I describe here it will work.

A: Carve a ramp, they go upwards. You can then build a downward staircase and replace the ramp with an upward staircase. The ramp may become unusable after constructing the upper staircase, so send that fish dissector if the area is dangerous or you are expecting delays.


text:
Q: How to define a timer in avr-gcc I am learning to use avr-gcc, but I have no idea, how to solve the following task:
The 8 bits from Port B should alternately set from 0 to 1 with an interval of 500 mili seconds.
I appreciate your help.

A: You can use #include <util/delay.h> , and if you write : _delay_loop_2(1000); you will have a delay of 1 ms;
You could use this function:
void delay()
{

    for(int i=0;i<500;i++)

        _delay_loop_2(1000);
}

A: Have a look at this example. This a very basic code for timer0:
#include<avr/io.h>
#include<avr/interrupt.h>
#define F_CPU 1000000UL
unsigned int t=0;
main()
{
    DDRD=0xFF;
    TCCR0=(1<<CS00);
    TCNT0=0;
    TIMSK=(1<<TOIE0);
    sei();
    while(1);
}
ISR(TIMER0_OVF_vect)
{
    t++;
    if(t==40000)
    {
        PORTD=~PORTD;
        t=0;
    }

}

A: As @Alex said you can #include <util/delay.h>, but instant of using the provided code (by @Alex) you can simple use _delay_ms(500);
This will provide you a delay of 500ms.
The choice is yours, just keep in mind that in both cases the frequency of your clock must be defined properly to your compiler:
Example for 16MHz:#define F_CPU 16000000UL


text:
Q: Calling JavaScript function from other frame present in an iFrame I have an iFrame in my HTML page iFrame_Example.html
<iframe src="1.html" height="400" width="400"></iframe>

1.html has two frames in it
    <frameset rows="30,*" frameborder=0 border=0>
        <frame id="top_frame" name="top_frame"src="top_frame.htm"></frame>
        <frame id="main_frame" name="main_frame"src="main_frame.htm"></frame>
    </frameset>

Now in top_frame.htm I have a button
<input type="button" value="Hi" onClick="top.main_frame.SayHi()">

SayHi() is in main_frame.htm
function SayHi()
{
  alert("Hi");
}

When I run 1.html in browser, the function SayHi() gets called properply. But when I run   iFrame_Example.html it deosn't work.
How do I call the function with onClick event ? Any help would be most appreciated.

A: Have you tried frames.top_frame.SayHi()?
Update: I think you may need parent.frames.top_frame.SayHi()


text:
Q: Flex components for JSF It would make sense to use Flex components with JSF, but searching around I can't find something mainstream. At least not as mainstream as ICEFaces, Woodstock and the other JSF components.

A: JSF -- which produces (X)HTML -- isn't run in the same framework as Flex, which uses flash on the client.
While it would be possible to embed a .swf within a JSF component, and reuse that component, it isn't possible to -- say -- have an mx:Panel and then put an h:inputText inside that.


text:
Q: On the Spectral Theorem
Let $H$ be a Hilbert space, $T\in B(H)$ be normal and $E$ its spectral measure.
a- Let $\delta >0$ , and let $M_{\delta}$ = $\left\{\lambda\in \sigma(T): |\lambda|\geq \delta\right\}$. Prove that $Range(E(M_{\delta}))\subseteq T(H)$.
b- Let $\sigma\subseteq \sigma(T)$ be open then $E(\sigma)\neq 0$.
c- Use the spectral theorem to prove that $T$ is positive $\Longleftrightarrow$ $\langle Tx,x\rangle \geq0$ , for all $ x\in H$.

Note we say $T$ is positive if there exists $S\in B(H)$ self-adjoint such that $T=S^2$.
Any idea how to start?
Thank you .

A: a- Note that $1_{M_\delta}(x)=x\cdot 1_{M_\delta}(x)\cdot \left( \frac{1}{x}\right)1_{M_\delta}(x) =f_1(x)f_2(x)f_3(x).$ Applying the$L^\infty$ functional calculus of $T$, this yields
$$
E(M_\delta)=1_{M_\delta}(T)=f_1(T)f_2(T)f_3(T)=TE(M_\delta)f_3(T).
$$
Now clearly the range of the latter is contained in the range of $T$.
b- This is false, as $\sigma=\emptyset $ yields $E(\sigma)=0$. But it is true of $\sigma $ is a nonempty open set. Indeed, by the spectral theorem
$$\|E(\sigma)\|=\|1_\sigma(T)\|=\|1_\sigma\|_\infty=1$$
in this case, hence $E(\sigma)\neq 0$.
c- If $T$ is positive, i.e. $T=S^2$ for some self-adjoint $S$, then $(Tx,x)=(S^2x,x)=(Sx,Sx)=\|Sx\|^2\geq 0$ for every $x$. Now assume $(Tx,x)\geq 0$ for every $x$. First show that $T$ is self-adjoint using polarization. Then check the spectrum of $T$ is nonnegative. By functional calculus, we can then set $S:=\sqrt{T}$, so that $S$ is self-adjoint and $S^2=T$.
Note: the if direction of c is false in the real case. Consider
$$
\left( \matrix{0&1\\-1&0}\right)
$$
for example.


text:
Q: Prove that triangle AMN has constant perimeter
Take a equilateral triangle .Pick a point D outside of side BC such that BD=CD and $\angle BDC= 120$.There are points M on AB and N on AC such that $\angle MDN=60$.It is required to prove that triangle AMN has constant perimeter irrespective of choice of M and N.

My observations:

ABCD is cyclic
  PQ is parallel to MN(but I am not able to prove it.I have drawn many diagrams and in each case it is true)

I tried angle chasing to produce similar and congruent triangle but failed.Any hints?
Note : This question has been asked before but solution was based on solving for a special case.Here I am looking for generalised solution

A:
Construct DT $\perp $ MN. Note that
$$DT = BD \frac{\cos \alpha_1 }{\cos \alpha_2} = CD \frac{\cos \beta_1 }{\cos \beta_2}$$
From the given, $\alpha_1 + \beta_1 = \alpha_2 + \beta_2=60$ and BD = CD. Then,
$$\frac{\cos \alpha_1 }{\cos \alpha_2} =  \frac{\cos \beta_1 }{\cos \beta_2} =\frac{\cos (60-\alpha_1 )}{\cos (60-\alpha_2)}$$
which leads to $\sin(\alpha_1-\alpha_2) = 0$ and, in turn, $\alpha_1=\alpha_2$. Similarly, $\beta_1=\beta_2$.
Thus, the right triangle pairs MBD-MTD and NCD-NTD are congruent, respectively. As a result, MB = MT, NC = NT and the perimeter of the triangle DMN is equal to $AB+AC$, which is invariant.

A:
$\require{begingroup} \begingroup$
$\def\i{\mathbf{i}}$
WLOG, let $O=0,\,R=1$.
Then the known points are
\begin{align}
A&=\i
,\\
B&=A\exp(\tfrac{2\pi}3\i)=-\tfrac12\,\sqrt3-\tfrac12\,\i
,\\
C&=A\exp(-\tfrac{2\pi}3\i)=\tfrac12\,\sqrt3-\tfrac12\,\i
,\\
D&=-\i
,\\
M&=A\,(1-t)+B\,t
=-\tfrac12\,\sqrt3\,t+\i\,(1-\tfrac32\,t)
,\quad t\in[0,1]
,\\
E&=D+(M-D)\,\exp(-\tfrac\pi3\,\i)
=\sqrt3\,(1-t)
.
\end{align}
Note that for any $t\in[0,1]$,
that is, for any point $M$ on the side $AB$,
the point $E$ is located on the $x$-axis.
The point $N$ is then found at the intersection
of the lines $AC$ and $DE$,
\begin{align}
N&=AC\cap DE
=
\frac{2\,\sqrt3\,(t-1)}{3\,t-4}
-\i\cdot\frac{3\,t-2}{3\,t-4}
.
\end{align}
The side lengths of  $\triangle AMN$ are
\begin{align}
|AM|=|A-M|&=t\,\sqrt3
,\\
|AN|=|A-N|&=
\frac{4\,\sqrt3\,(1-t)}{4-3\,t}
,\\
|MN|=|M-N|&=
\frac{\sqrt3\,(3\,t^2-6\,t+4)}{4-3\,t}
\end{align}
And the perimeter of $\triangle AMN$ is found as
\begin{align}
p=
|AM|+|AN|+|MN|
&=2\sqrt3
.
\end{align}
Corresponding Maxima session log:
Maxima 5.38.1 http://maxima.sourceforge.net
using Lisp GNU Common Lisp (GCL) GCL 2.6.12
Distributed under the GNU Public License. See the file COPYING.
Dedicated to the memory of William Schelter.
The function bug_report() provides bug reporting information.
(%i1 )     _(z):=conjugate(z)$
(%i2 )     xpoint(z1,z2,z3,z4):=
    ((z1-z2)*(_(z3)*z4-_(z4)*z3)-(z3-z4)*(_(z1)*z2-_(z2)*z1))
    /((z1-z2)*(_(z3)-_(z4))-(z3-z4)*(_(z1)-_(z2)))$
(%i3 )     declare([A,B,C,D,E,M,N],complex)$
(%i4 )     declare([t,AM,AN,MN,p],real)$
(%i5 )     assume(t>0,t<1,(3*t^2-6*t+4)>0)$
(%i6 )     A:%i$
(%i7 )     B:expand(A*exp(%i*2*%pi/3))$
(%i8 )     C:expand(A*exp(-%i*2*%pi/3))$
(%i9 )     D:-A$
(%i10)     M:expand(A*(1-t)+B*t)$
(%i11)     E:factor(D+(M-D)*exp(-%i*%pi/3))$
(%i12)     N:expand(xpoint(A,C,D,E))$
(%i13)     N:factor(realpart(N))+factor(imagpart(N))*%i$
(%i14)     AM:sqrt(factor(realpart((A-M)*_(A-M))))$
(%i15)     AN:sqrt(factor(realpart((A-N)*_(A-N))))$
(%i16)     MN:sqrt(factor(realpart((M-N)*_(M-N))))$
(%i17)     p:AM+AN+MN$
(%i18)     factor(expand(p));
(%o18)                             2 sqrt(3)

$\endgroup$

A: Please take a look at the Picture.

A:
COMMENT:
When DM is coincident on DB , MN will be coincident on AB and the measure of the third side AN is zero. That is the perimeter of AMN tends to $2AB$. similar thing happens id N  and M coincide on C and A respectively. When  DM and DN are mirror about AD AMN is equilateral and we have:
$P=\frac{2AB Cos(30^o)}{3}\times 3=2AB$
For other positions of M and N , as can be seen in drawing we always have:
$AB=AN Cos(30^o)+ AD-AM Cos (30^o)$
Or:
$|AN-AM|=\frac{AD-AB}{Cos(30^o)}=constant$
$|AN-AM| Cos(30^o)=(MN) Sin(\angle PNM)=$
Eliminating $|AN-AM|$ we get:
$MN=\frac{(AD-AB) Cos^2567 (30^o)}{Sin (\angle PNM)}$
Seems reasonable to conclude that perimeter of AMN is equal to $2AB$.

A: I think your idea of finding cyclic quadrilaterals is good, I'll show a proof only using a bunch of these cyclic quadrilaterals. But first,  I need some labels, so
Let $R$ the intersection of $MD$ and $BC$.
Let $S$ the intersection of $ND$ and $BC$.
Now I can start with the proof:

*

*You found out that $\angle BMD=\angle BSD=30+\alpha$. That means that $BMSD$ is cyclic. In particular $\angle MSD=180-\angle MBD=90$

*Similarly, $\angle CND=\angle CRD=90-\alpha$. That means that $CNRD$ is cyclic. In particular $\angle NRD=180-NCD=90$

*Since $\angle MSN=\angle NRM=90$, we have that $MRSN$ is cyclic.

*Since $MRSN$ is cyclic we have $\angle RMN=\angle RSD=30+\alpha$ and $\angle MNS=\angle SRD=90-\alpha$. [This also proves that $PQ$ is also parallel to $MN$]

*Construct $T$ in $MN$ such that $DT\perp MN$.

*Note by symmetry of the quadrilaterals $BMTD$ and $DTNC$ that $MT=MB$ and $TN=NC$.

*Conclude that $AM+MN+NA=AM+MT+TN+NA=AM+MB+NC+CA=AB+AC$


text:
Q: Could not add multiple counters in react I want to make a counter app with increment, decrement and add counter button. But add counter function is not working. It's showing this error:

Parsing error: Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...?

i have already tried enclosing it in tags,still its not working.
import React,{Component} from 'react';
import './App.css';

export class App extends Component {
  state={
    count:0,
  }

  increment=()=>{
    this.setState({ count: this.state.count + 1 });
  }

  decrement=()=>{
    this.setState({ count: this.state.count - 1 });
  }

  addCounter=()=>{

        <button onClick={this.increment}>+</button>

         {this.state.count}
         <button onClick={this.decrement}>-</button>

  }

  render() {
    return (

      <button onClick={this.addCounter}>Add Counter</button>

    )
  }
}

export default App;

add counter function should add another counter just below the previous counter.

A: Basically extract a Counter component.
Then have your App maintain a list of Counter components.
// Counter Component
export class Counter extends React.Component {
  state = {
    count:0,
  }

  increment=()=>{
    this.setState({ count: this.state.count + 1 });
  }

  decrement=()=>{
    this.setState({ count: this.state.count - 1 });
  }

  render() {
    return (

        <button onClick={this.increment}>+</button>
        {this.state.count}
        <button onClick={this.decrement}>-</button>

    );
  }
}

// App Component
export class App extends React.Component {
  state = {
    counters: [], // additional state for Counter components
  }

  addCounter = () => {
    this.setState({
      counters: [
        ...this.state.counters,
        Counter
      ]
    })
  }

  render() {
    return (

        <button onClick={this.addCounter}>Add Counter</button>
        { this.state.counters.map((Counter, index) => (
           <Counter key={index} />)
        )}

    )
  }
}

Demo

A: You are just adding more spans and button but refering to the same counter.
state={
  i : 0,
  count:0,
}
var newCount="counter"+this.state.i;
this.setState({
 i : this.state.i+1,
})
this.setState({
  count: {
     ...this.state.count,
     newCount: 0
  }
});

So with this you add a new counter with a progresive autoincrement number.

A: You have to add another functional Component instead of adding JSX. DEMO
import React from 'react';
const counter = (props) => {
   return (

         <button onClick={() => props.increment(props.index)}>+</button>
             {props.count}
         <button onClick={() => props.decrement(props.index)}>-</button>

   )
}
export default counter;

And your main App component
import React, {Component} from 'react';
import Counter from './Counter';
import './App.css';

export class App extends Component {
  state={
     counters: []
  }

  valueChanger = (index, inc) => {
     this.setState((prevState) => {
        const counters = prevState.counters.slice();
        counters[index] += inc;
        return {
            counters: counters
        }
     });
  }

  increment=(index)=>{
     this.valueChanger(index, 1);
  }

  decrement=(index)=>{
     this.valueChanger(index, -1);
  }

  addCounter=()=>{
     this.setState((prevState) => {
        return { counters: [...prevState.counters, 0] }
     });
  }

  render() {
    let counterElems = this.state.counters.map((c, index) => {
       return <Counter key={index} index={index} increment={this.increment} decrement={this.decrement} count={c} />
    });

    return (

          {counterElems}
          <button onClick={this.addCounter}>Add Counter</button>

    )
  }
}

export default App;

A: Your "counter" needs to be a react component with its own state, what you have there will have each "counter" you add use the same component state from App. You also do not save the returned JSX to then render anywhere.
const Counter = () => {
  const [count, setCount] = useState(0);

  return (

 // <-- React components can return only a single node*

        <button onClick={() => setCount(count + 1)}>+</button>

      {count}

        <button onClick={() => setCount(count - 1)}>-</button>

  );
};

class App extends Component {
  state = {
    counters: []
  };

  addCounter = () => {
    this.setState(prevState => ({
      counters: [...prevState.counters, <Counter />]
    }));
  };

  render() {
    return (

        <button onClick={this.addCounter}>Add Counter</button>
        {this.state.counters}

    );
  }
}

* React render lifecycle function can render arrays.

A: I think it is what you want to do.

const { useState } = React;
function App(){
  const [counter, setCounter] = useState([]);

  function addCounter(){
    setCounter(counter.concat({id: counter.length, count: 0}));
  }
  function increase(id){
    setCounter(counter.map(el=>{
      if(el.id === id){
        el.count++;
      }
      return el;
    }));
  }
  function decrease(id){
    setCounter(counter.map(el=>{
      if(el.id === id){
        el.count--;
      }
      return el;
    }));
  }
  return (

      <button onClick={addCounter}>Add Counter</button>
      {
        counter.map(el=>{
          return(

              Counter #{el.id}

                <button onClick={()=>{increase(el.id)}}>+</button>
                {el.count}
                <button onClick={()=>{decrease(el.id)}}>-</button>

          )
        })
      }

  )
}

ReactDOM.render(
  <App />, document.getElementById('root')
)


text:
Q: Receiving values from multiple threads in C #include<pthread.h>
#include<stdio.h>
#include<sys/stat.h>
#include<errno.h>

#define SIZE 3

/***I'm trying to send name of each file in a thread and trying to receive their respective size in main *******/

void *doit(void *name)
{
        int *size;
        struct stat st;
        char temp_name[30];
        memset(temp_name, '\0', sizeof(temp_name));
        strcpy(temp_name, (char *)name); //type casted
        stat(temp_name, &st);
        *size = st.st_size; //calculated the size

        printf("File name is: %s\n", temp_name);
        printf("File size is: %d\n", *size);
        pthread_exit((void *)size); //exited from thread
}

int main(int argc, char *argv[])
{
        pthread_t th_id[SIZE];
        int ret_val;
        int i;
        void **size[SIZE];
        for(i=0; i<SIZE;i++)
        {
                size[i] = (void **)malloc(30*sizeof(void *)); //allocated memory to void double pointer
                if(size[i] == NULL)
                {
                        printf("Memory not allocated to %dth member of size\n", (i+1));
                }
        }
        for(i=0; i<3; i++)
        {
          /*****Creating Thread**********/
                ret_val = pthread_create(&th_id[i], NULL, &doit, (void *)argv[1+i]);
                if(ret_val != 0)
                {
                        perror("Thread creation error\n");
                        exit(0);
                }
                pthread_join(th_id[i], size[i]);
                printf("Size is %d\n",**(int **)size[i]); //typecasted and printed
        }
        pthread_exit(NULL);
        return 0;
}

In this program i'm getting segmentation fault after first call at pthread_join. when passing first file, i'm getting the proper size in main. but during call to second file i'm getting segmentation fault. With gdb i'm getting that the "**size[1] and **size[2] are getting NULL despite malloc. but in the start of main, i'm not getting error message while assigning memory. It should mean that the memory is assigned initially. Please help me what should i do.

A:     int *size;
    struct stat st;
    char temp_name[30];
    memset(temp_name, '\0', sizeof(temp_name));
    strcpy(temp_name, (char *)name); //type casted
    stat(temp_name, &st);
    *size = st.st_size; //calculated the size

You're dereferencing an uninitailized pointer. You never make size point to anything.


text:
Q: Asterisk art in python I would like to produce this picture in python!
         *
        **
       ***
      ****
     *****
    ******
   *******
  ********
 *********
**********

I entered this:
x=1
while x<10:
 print '%10s'    %'*'*x
 x=x+1

Which sadly seems to produce something composed of the right number of dots as the picture above, but each of those dot asterisks are separated by spaced apart from one another, rather than justified right as a whole.
Anybody have a clever mind on how I might achieve what I want?

A: string object has rjust and ljust methods for precisely this thing.
>>> n = 10
>>> for i in xrange(1,n+1):
...   print (i*'*').rjust(n)
...
         *
        **
       ***
      ****
     *****
    ******
   *******
  ********
 *********
**********

or, alternatively:
>>> for i in reversed(xrange(n)):
...   print (i*' ').ljust(n, '*')
...
         *
        **
       ***
      ****
     *****
    ******
   *******
  ********
 *********
**********

My second example uses a space character as the printable character, and * as the fill character.
The argument to ljust or rjust is the terminal width.  I often use these for separating sections with headings when you have chatty debug printout, e.g. print '--Spam!'.ljust(80, '-').

A: It's because of the operator precedence, use this one:
x=1
while x<10:
 print '%10s' % ('*'*x)
 x=x+1

A:  '%10s'    %'*'*x

is being parsed as
('%10s' % '*') * x

because the % and * operators have the same precedence and group left-to-right[docs]. You need to add parentheses, like this:
x = 1
while x < 10:
    print '%10s' % ('*' * x)
    x = x + 1

If you want to loop through a range of numbers, it's considered more idiomatic to use a for loop than a while loop. Like this:
for x in range(1, 10):
    print '%10s' % ('*' * x)

for x in range(0, 10) is equivalent to for(int x = 0; x < 10; x++) in Java or C.

A: print '\n'.join(' ' * (10 - i) + '*' * i for i in range(10))

A: To be exact, as your picture ends with 10 asterisks, you need.
for i in range(1, 11):
    print "%10s"%('*' *i)


text:
Q: How to create variable from 1 to n (increments of 1)? Assuming that in Stata e.g. I have one stacked variable (in column 2) of stock returns with data populating range of  1 to 2000000 (some blanks are replaced with dots). How can I create another variable next to it, which will start at 1 and jump in the increments of one (1, 2, 3, 4...) all the way down to 2000000? I need this kind of variable to merge datasets. Advice would be much appreciated.
If it helps, if I was to use VBA, I would find the last row of the stacked column and then create a variable on this basis moving in the increments of one (that would be of course if Excel allowed  2 million rows)

A: gen long id = _n

will populate a variable with the observation number.
Note that you can merge on observation number. You don't need any identifier variable(s) to do it. In practice, I would almost always be very queasy about any merge not based on explicit identifiers, unless the datasets were visibly compatible (not so with 2 million observations).


text:
Q: User role based view in django CBV I am using django class based view for my web application. I using django auth class for user sign up and login. In my app, users can be off more than 3 types. Every type of user will have more or less different privilege in the type. I dont know how can I manage different type of users.
So I need advice how can I implement this.


text:
Q: Server gives me a permission error when trying to scp, but not when ssh Is there server configuration you need to set when you want to scp to a server?  If i ssh into the machine, i use:
ssh -i file.pem user@server

but when i try the scp command, it will give me a permissions error.
scp path/to/file.pdf -i file.pem user@server:/home/user/.

What am i doing wrong, and how can i fix it?  I cant seem to figure out what's up with it.  The error reads as:
Permission denied (publickey).
lost connection

A: You need to shuffle around your options and arguments. It should be:
scp -i file.pem path/to/file.pdf user@server:/home/user

Note the omission of /. from the end of the target path. It is not necessary because if the last segement of the target is a dir it will copy the files into the directory, just like cp and mv.

Is there a way to assign the file.pem such that it just picks it up when i use: user

You can do that with an ~/.ssh/config config file:
Host            serveralias
HostName        server.com
User            user
IdentityFile    /path/to/your/key.pem

After creating that you can do:
# will effectively be like doing
# ssh -i /path/to/your/key.pem user@server.com
ssh serveralias

Or
# should pick up on the same settings and effectively like
# ssh -i /path/to/your/key.pem user@server.com
ssh user@server.com

And they should both use the IdentityFile you specified.


text:
Q: form submitted data from template is not saved in database in Django? I was doing a small project on Django where I create a simple blog mini-project. Everything worked for me but I am in issue now that I can create a post form Django administration and I wanted to do it within front-end with templates in create-post.html but I am no issue just my form is not working or it is not submitting any data or some error?
I'm using summer note rich text editor instead of the text field in Model. Experts please look at my code and suggest to me it is good or bad or where I am wrong?
my models.py
class Author(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    author_profile_pic = models.ImageField(upload_to='images',null=True)
    author_description = models.TextField(null=True)
    author_facebook_url = models.CharField(max_length=50,null=True)
    author_twitter_url = models.CharField(max_length=50,null=True)
    author_instagram_url = models.CharField(max_length=50,null=True)
    author_github_url = models.CharField(max_length=50,null=True)
    def __str__(self):
        return f'{self.user}'

class Category(models.Model): # show string title in Admin panel
    title = models.CharField(max_length=30,null=True)
    def __str__(self):
        return self.title

class Blogpost(models.Model):
    title = models.CharField(max_length=100,null=True)
    thumbnail = models.ImageField(upload_to='images')
    post_body = models.TextField()
    slug = models.SlugField(null=True,blank=True)
    posted_date = models.DateField(default=date.today)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)
    categories = models.ManyToManyField(Category)
    publish = models.BooleanField()

and my form
from django import forms
from .models import Blogpost
from django_summernote.widgets import SummernoteWidget

class CreatePostForm(forms.ModelForm):
    class Meta:
        model = Blogpost
        fields = "__all__"
        widgets = {
            'post_body': SummernoteWidget(),
        }

and views.py
def create(request):
    form = CreatePostForm
    return render(request,'create-post.html',{'form':form})

def createpost(request):
  form = CreatePostForm()
  if request.method == 'POST':
    form = CreatePostForm(request.POST)
    if form.is_valid():
      form.save()
      return redirect('homepage')

  else:
    form = CreatePostForm()
  return render(request, "create-post.html", {'form': form})

and urls.py
urlpatterns = [
    path('admin/', admin.site.urls),
    path('',views.homepage,name='homepage'),
    path('create',views.create,name='create'),
    path('createpost',views.createpost,name='createpost')
]

create-post.html
{% extends 'base.html' %}
{% block content %}
<h3> Creating Post</h3>
<form enctype="multipart/form-data" action="{% url 'createpost' %}" method="POST">
    {% csrf_token %}

    {{ form|safe }}

    <button type="submit">Post</button>
</form>
{% endblock %}

I'm in the learning phase so can anyone tell me where I am wrong? but it is working from Django-administration but not working through templates.