text:
Q: Downgrade to Nautilus 3.4 from Ubuntu 13.10 / Nautilus 3.8 I just updated to Ubuntu 13.10 and greatly dislike Nautilus 3.8 that comes with it. In Ubuntu 13.04 I used the instructions in this article to get back some of the features from Nautilus 3.4, but unfortunately that doesn't work anymore. I particularly miss dividing up the window with F3 to have two folders show at the same time. The new search function I also find pretty terrible.
I checked out Nemo but I would much prefer downgrading to Nautilus 3.4.

A: I'm going to risk answering this question since I now feel I have collected enough information on this issue. Basically downgrading to Nautilus 3.4 seems not to be an option at this time; it was coded for an earlier version of GTK, thus it wont compile on Ubuntu 13.10. The only practical way is installing a different file browser.
As it happens, Nemo is actually a fork of Nautilus 3.4 that has kept all the features of the latter (adding a few more). I've been using it since yesterday and the interface is almost the same, a seamless transition for the user. Thus installing Nemo is not very far from downgrading to Nautilus 3.4. I haven't done it yet, but it is possible to set Nemo as the default file browser.
All features I used in Nautilus 3.4 seem to function properly in Nemo (e.g. Connect to Server). The only exception at this stage is the integration with RabbitVCS, there's a package available but non functional at the moment. Since RabbitVCS doesn't work on Nautilus 3.8 either, it is not a regression.
Update II: There's no need to install Cinnamon, just install the Nemo package:
sudo apt-get install nemo

Update I: Nemo's appearance can be tweaked into something closer to the default Unity style. Open its css file:
sudo gedit /usr/share/themes/Ambiance/gtk-3.0/apps/nemo.css

And then replace all contents with the following:
.nemo-pathbar-button,
NemoPathbarButton {
background-image: -gtk-gradient(linear, left top, left bottom,
color-stop (0, shade(@dark_bg_color, 1.1)),
color-stop (.3, shade(@dark_bg_color, 1.1)),
color-stop (.7, shade(@dark_bg_color, 0.90)),
color-stop (1, shade(@dark_bg_color, 0.80)));
border-color: shade(@dark_bg_color, 0.7);
-NemoPathbarButton-border-radius: 3px;
}

NemoPathbarButton:active {
background-image: -gtk-gradient(linear, left top, left bottom,
color-stop (0, shade(@dark_bg_color, .8)),
color-stop (.3, shade(@dark_bg_color, .9)),
color-stop (1, shade(@dark_bg_color, 1.0)));
border-color: shade(@dark_bg_color, 0.7);
}

NemoPathbarButton:hover {
background-image: -gtk-gradient(linear, left top, left bottom,
color-stop (0, shade(alpha(@dark_bg_color, 1.4), 1.25)),
color-stop (.3, shade(alpha(@dark_bg_color, 1.4), 1.25)),
color-stop (.7, shade(alpha(@dark_bg_color, 1.4), 0.95)),
color-stop (1, shade(alpha(@dark_bg_color, 1.4), 0.85)));
border-color: shade(@dark_bg_color, 0.7);
}

NemoWindow * {
    -GtkPaned-handle-size: 1;
}

NemoDesktopWindow GtkWidget {
    background-color: @transparent;
}

.nemo-canvas-item {
    border-radius: 4px;
}

/* desktop mode */
.nemo-desktop.nemo-canvas-item {
    color: @bg_color;
    text-shadow: 1px 1px alpha (#000000, 0.8);
}

.nemo-desktop.nemo-canvas-item:active {
    background-image: none;
    background-color: alpha (@bg_color, 0.84);

    color: @fg_color;
}

.nemo-desktop.nemo-canvas-item:selected {
    background-image: none;
    background-color: alpha (@selected_bg_color, 0.84);

    color: @selected_fg_color;
}

.nemo-desktop.nemo-canvas-item:active,
.nemo-desktop.nemo-canvas-item:prelight,
.nemo-desktop.nemo-canvas-item:selected {
    text-shadow: none;
}

/* browser window */
NemoTrashBar.info,
NemoXContentBar.info,
NemoSearchBar.info,
NemoQueryEditor.info {
    background-image: -gtk-gradient (linear, left top, left bottom,
                                     from (shade (@cluebar_color, 1.02)),
                                     to (shade (@cluebar_color, 0.98)));
    background-color: @cluebar_color;
    border-bottom-color: shade (@cluebar_color, 0.92);
    border-radius: 0;
    border-style: solid;
    border-width: 0px 0px 1px 0px;

    box-shadow: inset -1px 0px shade (@cluebar_color, 1.02),
                inset 1px 0px shade (@cluebar_color, 1.02),
                inset 0 1px shade (@cluebar_color, 1.04),
                inset 0 -1px shade (@cluebar_color, 1.01);
}

NemoTrashBar.info:backdrop,
NemoXContentBar.info:backdrop,
NemoSearchBar.info:backdrop,
NemoQueryEditor.info:backdrop {
    background-image: -gtk-gradient (linear, left top, left bottom,
                                     from (shade (@cluebar_color, 1.01)),
                                     to (shade (@cluebar_color, 0.99)));
    background-color: @cluebar_color;
    border-bottom-color: shade (@cluebar_color, 0.92);

    box-shadow: inset -1px 0px shade (@cluebar_color, 1.01),
                inset 1px 0px shade (@cluebar_color, 1.01),
                inset 0 1px shade (@cluebar_color, 1.02),
                inset 0 -1px shade (@cluebar_color, 1.0);
}

NemoSearchBar .entry {
}

.nemo-cluebar-label {
    font: bold;
    text-shadow: 0 1px shade (@cluebar_color, 1.06);
}

.nemo-cluebar-label:backdrop {
    color: mix (@fg_color, @cluebar_color, 0.2);
    text-shadow: 0 1px shade (@cluebar_color, 1.02);
}

#nemo-search-button *:active,
#nemo-search-button *:active:prelight {
    color: @dark_fg_color;
}

NemoFloatingBar {
    background-color: @info_bg_color;
    border-radius: 3px 3px 0 0;
    border-style: solid;
    border-width: 1px;
    border-color: darker (@info_bg_color);
}

NemoFloatingBar .button {
    -GtkButton-image-spacing: 0;
    -GtkButton-inner-border: 0;
}

/* sidebar */
NemoWindow .sidebar,
NemoWindow .sidebar .view {
    background-color: shade (@bg_color, 0.95);

    /*background-color: @bg_color;*/

    color: @fg_color;
    text-shadow: 0 1px shade (shade (@bg_color, 0.95), 1.04);
}

NemoWindow .sidebar .frame {
    border-width: 1px 0 0 0;
    border-style: solid;
    border-color: shade (@bg_color, 0.86);
    border-radius: 0;
}

NemoWindow .sidebar:backdrop,
NemoWindow .sidebar .view:backdrop {
    color: mix (@fg_color, shade (@bg_color, 0.95), 0.2);
    text-shadow: 0 1px shade (shade (@bg_color, 0.95), 1.02);
}

NemoWindow .sidebar row:selected {
    color: @selected_fg_color;
    text-shadow: 0 1px shade (@selected_bg_color, 0.8);
}

NemoWindow .sidebar row:selected:backdrop {
    background-image: -gtk-gradient (linear, left top, left bottom,
                                     from (shade (shade (@bg_color, 0.95), 0.94)),
                                     to (shade (shade (@bg_color, 0.95), 0.86)));
    border-top-color: shade (shade (@bg_color, 0.95), 0.88);

    color: @fg_color;
    text-shadow: 0 1px shade (shade (@bg_color, 0.95), 0.96);
}

NemoWindow .pane-separator {
    background-color: shade (shade (@bg_color, 0.95), 0.94);
    border-color: @dark_bg_color;
    border-style: solid;
    border-width: 0;
    box-shadow: none;
}

NemoWindow .pane-separator:backdrop {
    background-color: shade (shade (@bg_color, 0.95), 0.96);
}


text:
Q: How to check the validity of a symmetric key? User 1 sends two fields:

*

*plain_text

*password

these fields are passed to encrypt function
encrypted = encrypt(plain_text, password)

the encrypted value is stored in the database

Now User 2 wants to see this plain_text field, he sends one field to the server to request it:

*

*password

Now the server wants to check to see if the password sent by User 1 is the same as the password sent by User 2 but at the same time he did not store the password sent by User 1, how can the server check that the password is correct before sending the decrypted text.
The motive is that the server is not wanted to:

*

*send wrong decrypted text

*store the plain_text in the database

*store the correct password in the database

What is the simplest way to achieve this?

A: The standard way to do this is to use an authenticated mode, like GCM or CBC+HMAC. An authenticated mode will fail to decrypt if the key is incorrect rather than returning a corrupted plaintext.
Authenticated modes generally do not tell you that the decryption has failed until the end, which can be problematic for very large payloads. In those cases you encrypt and store a static (or computable) piece of data with the same key (or a key derived from the same key) using the same authenticated mode. You can use that to pre-flight the key before decrypting the larger payload.
But the short answer is: use an authenticated mode, ideally GCM, and you get this and more for free.
Without changing your existing mode, you can achieve this by prepending the hash of the payload to the payload before encrypting. After decrypting, split the hash and payload, hash the payload, and ensure that it matches the decrypted hash.

redpajama_set_name: RedPajamaStackExchange


text:
Q: SQL query with return columns based on grouping I have this select as follows:
SELECT SUBSTRING(Col1, 1, 3)          AS 'Series',
       b.Col2,
       CAST(c.Price * c.Qty AS MONEY) AS Total
FROM   tableName a
inner join ....
...
WHERE  DATE BETWEEN '1/1/2012' AND '1/31/2012'
       AND B IN ( 'C50', 'C51', 'C52', 'C53', 'C54' )
GROUP  BY Col1,
          b.Col2,
          c.Price,
          c.Qty

Which returns this result set:
Series       Col2        Total
----------   ----------  ----------
105          C50         5.00
105          C50         15.00
105          C53         20.00
105          C53         20.00
105          C53         20.00

And this is how I would like it to work:
Series       C50         C53
----------   ----------  ----------
105          20.00       60.00

Not sure how to do the inner selects to get that result. Any ideas?

A: Please try the following codes. You have to use PIVOT query.
create table TableName (Series varchar(20),col2 varchar(10), price decimal(8,2))

insert into TableName values ('105','C50',30)
insert into TableName values ('105','C50',10)

insert into TableName values ('105','C53',20)
insert into TableName values ('105','C53',30)

SELECT Series,
       [C50],
       [C53]
FROM   (SELECT Series,
               col2,
               price
        FROM   TableName) AS SourceTable
                   PIVOT ( SUM(price) FOR col2 IN ([C50],
                                                   [C53])
       ) AS PivotTable;

A: For potential null value for col2, please try the following code.
Note: you may need to adjust @PIV_COL size depend on how many distinct records of col2. I used 'NO_VAL' for potential NULL value of col2.
insert into TableName  values ('105',NULL,100)

DECLARE @PIV_COL VARCHAR(100)

SELECT @PIV_COL = STUFF(
(
    SELECT DISTINCT ',[' + ISNULL(COL2,'NO_VAL') + ']'
    FROM TableName  C
    FOR XML PATH('')
), 1, 1, '')

EXEC
('
    SELECT Series,' + @PIV_COL + '
    FROM   (
                SELECT Series,
                   ISNULL(COL2,''NO_VAL'') col2,
                   price
            FROM   TableName ) AS SourceTable
                       PIVOT ( SUM(price) FOR col2 IN ('+ @PIV_COL + ')
    ) AS PivotTable
')


text:
Q: Setuptools never found on AWS Lambda I'm attempting to use AWS Lambda to do some python package introspection.
What I'm trying to do is, on a git push, checkout a package, install its dependencies (the package dependencies are required for introspection), and run the tooling. AWS does not by default have pip installed (you're supposed to bundle your own dependencies)--so I bundle pip in with my lambda function.
Every other part of my lambda works, except for trying to install package dependencies. When attempting to use my bundled pip with the checked-out package, it fails trying to run setuptools:
Collecting alembic==0.8.3 (from -r /tmp/tmpnx0tY0/requirements.txt (line 1))
Downloading alembic-0.8.3.tar.gz (935kB)
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: No module named setuptools
 ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/tmp30m2KN/alembic

I've tried everything: add the current path (with setuptools) to path, copy setuptools to the temp directory, run pip install setuptools, passing options using --global-options, tried to pOpen with an env specifying PYTHONPATH, even tried to use older versions of pip with: pip install -r requirements.txt --download --no-install. Nothing seems to work.
How can I get this python setup.py egg_info call to successfully locate setuptools?

A: Have you considered using Jenkins (or any other CI tool) to hook into your Git repository,  build the repository on push and then upload the packaged lambda with all dependencies to S3 before running it?
Within AWS Lambdas, you can only download files to the /tmp folder and you have a limit of 50mb of space. This 50mb includes the space consumed by your lambda function also. Lambdas are zipped and don't contain pip for a reason.

A: I used Lambda for a bit and I don't think Lambda supports that. You need to use your own CI tools(Jenkins is a good choice). Otherwise, You need to build it on your local then use AWS Lambda plugin to upload your code with dependencies installed.


text:
Q: reflection is possible on obfuscation I am struggling with this problem since last one week. I have obfuscated exe of my application. Our application is offline tool for online web application. Client will install this application and connect once to internet, application will download relevant information and store in xml file on client machine for further display. for security purpose we are encrypting these xml files. Unfortunately we have one method GetCryptXML inside exe which will read encrypted settings.xml on client machine and return it after decrypting. this setting.xml contain encryption key for other xml as well.
Problem I am facing here is, even after obfuscation, person can invoke GetCryptXML method by passing obfuscated name.
Is there any way to solve this problem?
This is my idea to solve problem but I am not sure how to implement.
My idea: Only way to invoke my function is through reflection by using InvokeMember() function. before one can call this function he/she needs to load assembly by using this.
Assembly.LoadFrom("myapplication.exe")

If code inside myapplication.exe can identify which application is trying to load me then we can restrict them to load if it is not intended application. I dont know how can I solve.
Any help is greatly appreciated.
Thanks.

A: Obfuscation doesn't change the underpinnings of .net or your application - in the end, all it does is make it much harder to read, and tries to add cases that decompilation tools cannot handle... but either way the IL is still there.  If you give them the encrypted text (the xml) and the key (sent over the wire or hidden in your code), they can decrypt it.  All you are doing is making it harder, not impossible.
One thing you can do is strong name your assemblies, and verify that the caller of your type is from a specific strongly-named assembly with the StrongNameIdentityPermission attribute.  Note that KeeperOfTheSoul is correct- full trust assemblies can bypass this in versions of .net prior to 4.0 (it is my understanding that in 4.0 this attribute no longer uses the identity permission and only succeeds if the correct evidence is there).
You can also write code to get the call stack via System.Diagnostics.StackTrace, and check the calling methods to verify that it is one of the expected callers.  This means a bit slower execution and more code, but you would have control of it.
EDIT See here for a walkthrough of using the StrongNameIdentityPermission.  And here is an article on inspecting the stack trace.  Again, note that neither of these is a silver bullet, but can add one more hurdle to the attacker, if you think it's worth your time.  (Remember that in the day of the internet, it only takes one successful attacker for any number of people to google the result)

A: If you want to restrict access to a method to a particular assembly you could do the following:
    private void RestrictedMethod() {
        Assembly calling = Assembly.GetCallingAssembly();
        if(calling.FullName != "myapplication, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null") {
            throw new InvalidOperationException();
        }
        // Do method work...
        return;
    }

One of the advantages of this approach is that if someone used reflection from an unauthorized assembly the call would fail.

A: If something can be called through Reflection, it has to be callable (somehow) through regular code.
I would suggest against this (as there is no way to fully thwart somebody that is adamant about executing code they shouldn't).
If you're truly interested in doing something like this, you could break the OO Principals of C# and make all of your methods private. That way only code executing from inside your class could call them regularly. Everybody else would have to call them via Reflection (and calling private members via Reflection is considered bad practice more often than not).
Oddly enough, the more I think about it, the method should probably be marked as private anyway since you don't want everybody to be able to call it. Callers should have to call through a public facade which would determine if you're allowed to call the method or not...and only allow authorized calls.


text:
Q: Alpha beta pruning Im building a Reversi game with alpha beta, and i need your help in the alpha beta.
Problem is that the computer keep choosing one of the squares that are in the low side of the board. I have a List of possible moves for the computer (as you can see in the code below), meaning the computer is almost always choosing the last or one of the last moves in that List, even if its not the best move. My evaluation function is simple: black pieces minus white pieces. BTW: it works fine in depth=1, but i need it to work in depth=3.
public int AlphaBeta(int depth,int turn,TreeNode root,int alpha,int beta)
{
    if(depth==0)
        return evaluationFunc(turn,turns,root.board,root);
    else
    {
        buildSons(turn,root);
        TreeNode head =  generateList(root.sons);
        return executeCheckTheSons2(depth,turn,head,alpha,beta);
    }
}

public int executeCheckTheSons2(int depth,int turn,TreeNode head,int alpha,int beta)
    {
        int score;
        if(turn==1)
        {
            while(head!=null)
            {
                head.board=simulateTheMove(head.board,head.getX(),head.getY(),turn);
                score=AlphaBeta(depth-1,turn*-1,head,alpha,beta);
                if(score > alpha)
                {
                    alpha=score;
                    setMove(head);
                }
                if(alpha >= beta)
                    return alpha;
                head=head.next;
            }
                return alpha;
        }
        else
        {
            while(head!=null)
            {
                head.board=simulateTheMove(head.board,head.getX(),head.getY(),turn);
                score=AlphaBeta(depth-1,turn*-1,head,alpha,beta);
                if(score<beta)
                {
                    beta=score;
                    setMove(head);
                }
                if(alpha >= beta)
                    return beta;
                head=head.next;
            }
            return beta;
        }
    }

    public void setMove(TreeNode root)
    {
        while(root.father.father!=null)
            root=root.father;
        pnt.setX(root.getX());
        pnt.setY(root.getY());
    }

A: I think the error is in the setMove function. I suppose this is the function which sets the final coordinates to set the piece. At the moment you are calling this for every depth in the tree even if the result from this branch is not the best possible result globally.
For example imagine you are evaulating the last possible move. You start with depth=3 and then you call yourself recursively for depth=2. When you enter in executeCheckTheSons2 now you will start with a score of 0 and evaluate the possible moves. One of these moves will probably give you a score greater than 0, so you will call setMove(head) and set the coordinates to move to to the last possible move. When you return now from the function you record the score for this depth in score, but globally seen it's not a great move. However the last call for setMove is still active and you don't change it afterwards.
You should move this call out of executeCheckTheSons2 and move it in some upper layer function. Alternatively record the x and y coordinates in a local variable of the executeCheckTheSons2 function and then call setMove before returning from the function instead.
If this question is useful for you, please accept this as an answer.


text:
Q: Selecting multiple objects by id using JPA and ObjectDB? I'm having trouble getting ObjectDB to select multiple values based on their ids. My query is super simple:
Query query = getEntityManager().createQuery("SELECT i FROM " + getEntityClass().getSimpleName() + " i WHERE i.id IN :ids", entityClass);
query.setParameter("ids", ids);
List<Object> values = query.getResultList();

But no matter what, this always returns an empty list.
The ids list contains a list of existing ids, all as Long objects. I triple-checked this.
Queries like:
entityManager.find(getEntityClass(), id);

...and...
Query query = entityManager.createQuery("SELECT i FROM " + getEntityClass().getSimpleName() + " i", entityClass);

...work fine.
Also, if I do:
    entityManager.find(getEntityClass(), 1L);
I get the result correct result: a single instance.
But:
List<Long> ids = new LinkedList<Long>();
ids.add(1L);
Query query = getEntityManager().createQuery("SELECT i FROM " + getEntityClass().getSimpleName() + " i WHERE i.id IN :ids", entityClass);
query.setParameter("ids", ids);
List<Object> values = query.getResultList();

returns an empty list to the values variable.
What am I missing? Is this something ObjectDB just doesn't support?
Thanks!

A: It should work. Please try the following simple test:
import java.util.*;

import javax.persistence.*;

public class TestInIds {

    public static void main(String[] args) {

        EntityManagerFactory emf =
            Persistence.createEntityManagerFactory(
                "objectdb:$objectdb/db/test.tmp;drop");
        EntityManager em = emf.createEntityManager();

        em.getTransaction().begin();
        em.persist(new MyEntity());
        em.persist(new MyEntity());
        em.getTransaction().commit();

        Query query = em.createQuery("SELECT e FROM MyEntity e WHERE e.id in :ids");
        List<Long> ids = new LinkedList<Long>();
        ids.add(1L);
        query.setParameter("ids", ids);
        List resultList = query.getResultList();
        System.out.println("result size: " + resultList.size());

        em.close();
        emf.close();
    }

    @Entity
    static class MyEntity {
        @Id @GeneratedValue
        private Long id;
    }
}

It should print 1. If it doesn't try the last ObjectDB version.
If you do get 1 as output try to check what is different in your application.


text:
Q: What does the trait after the trait name mean? I came across this trait definition while reading about Rust:
trait Enchanter: std::fmt::Debug {
    ...
}

From this I understand that the name of the trait is Enchanter, but I do not understand what the std::Format:Debug part implies since it is also a trait (I think).

A: This is declaring a supertrait. It is equivalent to:
trait Enchanter
where
    Self: std::fmt::Debug,
{
}

In short, it requires any type that wants to implement Enchanter to also implement std::fmt::Debug. Otherwise, an error will be raised:
error[E0277]: `S` doesn't implement `Debug`
 --> src/lib.rs:4:6
  |
4 | impl Enchanter for S {}
  |      ^^^^^^^^^ `S` cannot be formatted using `{:?}`
  |
  = help: the trait `Debug` is not implemented for `S`
  = note: add `#[derive(Debug)]` to `S` or manually `impl Debug for S`
note: required by a bound in `Enchanter`
 --> src/lib.rs:1:18
  |
1 | trait Enchanter: std::fmt::Debug {}
  |                  ^^^^^^^^^^^^^^^ required by this bound in `Enchanter`


text:
Q: How to Find or Message someone by their Telegram numerical user ID? So here is my situation, I had about 8000 users in Telegram message my bot but Unfortunately I did not know I had to save their chat IDs, instead I saved their User IDs which is the numerical one like 123456789
Now what are the options that I have to contact those people again ? even having a way to access their profile by their User ID would be good (Granting they did not block the bot)


text:
Q: should we explicitly join a thread to finish should we explicitly join a thread to finish? I mean is this like process world: when we don't wait for them to finish we got zombie processes.

A: Not necessarily; you can always detach a thread if you don't wan't to explicitly wait for it.
There are a few things to consider:

*

*If you don't join a non-detached thread it will become a zombie thread (yes, there are such things)

*If you don't join a thread, your main thread might end before the "child" ends

*Once you detach a thread there is no way to attach it back

How do you detach a thread ? There are two ways:
detachstate = 1;
rc = pthread_attr_setdetachstate(&attr, detachstate);
if (rc) {
    handle error;
}

pthread_create(&thr, &attr, th_fun, NULL);

And the second way
void *th_fun(void *arg)
{
    pthread_detach(pthread_self());
}


text:
Q: Is there a legitimate use-case for putting a fieldset outside of a form? I was recently corrected, and according to the HTML4 DTD, it is legitimate to use a fieldset outside of a form:
http://www.w3.org/TR/html401/sgml/dtd.html#block
Previously I had not known this, and wonder if anyone can think of a legitimate use case for doing so.  I feel like using one to decorate would be frowned upon by most designers.  So is there a legitimate use case, or can you link to a site where this has been found appropriate and used as such?

A: I used a field set to decorate sections when printing documents. For example an invoice might have a Bill To and a Ship To, and drawing the frame around them with the legend text embeded in the frame can look really slick.

A: I think its more than legit to use it for decoration. Its simple and elegant and with the use of  tag its pretty nice.
Check w3schools example out

A: I don't think there is a legitimate case to semantically have a fieldset outside a form element, since a fieldset is a set of (input) fields - the clue's in the name! If you have input fields, you will likely always have a form, even if you're not posting back to the server.
I have occasionally used from a presentational aspect, because the fieldset+legend combo is impossible to replicate exactly in CSS, specifically, the broken line behind the legend.

A: It is acceptable to use all form field control outside of a form element, including fieldset.
This is appropriate wherever you have fields that only talk to JavaScript, instead of ever being submitted back as to the server side.
(This didn't originally used to work in Netscape 4, but that's hardly a concern this century...)

A: Well, using it to decorate can be frowned upon by designers AND be legitimate, so there is a legitimate use case.

A: A form is simply a container for the fields you wish to submit via post back.  Most regular site pages may not even have one.  That said, using a fieldset as a styling tag is legitimate and has nothing at all to do with whether a form tag exists or not.

A: You can use a fieldset to wrap multiple form controls that you need to disable together:

<fieldset disabled>
<input type="text" placeholder="disableable input" />
<button type="button">Some action that needs to be disabled</button>
<button type="button">Some other action</button>
</fieldset>


text:
Q: Morphing line with raphael.js Is it possible using the raphael.js or paper.js to draw a line with an arrow that moves with some animation morphing?

A: It's not entirely clear what you're trying to do, but the short answer to your question is almost certainly yes.  I can only speak for RaphaelJS, but it's easy to tell Raphael to morph from one path to the other.  Consider this fiddle and that fiddle, both of which rely on using raphael's animate function to modify the path element over time, often in conjunction with one or more transforms.  The only caveat is that raphael's built-in path morphing doesn't always unwind in the way you might expect or desire.  But in an attempt to animate something like the figure above, I'd do something like this:
var canvas = Raphael( 0, 0, 320, 240 );

var path1 = "M0,120 h300 l10,-10 l10,10 h100";
var path2 = "M0,120 h100 l10,-10 l10,10 h300";

var path = canvas.path( path1 ).attr( { stroke: 'black', fill: 'none', 'stroke-width': 1 } );

path.animate( { path: path2, stroke: 'red', 'stroke-width': 3 }, 3000, function()
              { path.animate( { path: path1, stroke: 'black', 'stroke-width': 1 }, 3000 ); } );

You can see this in action here.


text:
Q: Proof that membership is well-founded in NBG without axiom of choice I am reading a book on NBG (von Neumann-Barnays-Godel set theory) by Taras Banakh (https://arxiv.org/abs/2006.01613) and I encountered on page 26 well-founded relations. In this book, a relation $R$ is well-founded if every nonempty class $X$ contains an element $x\in X$ such that $\overleftarrow{R}(x)\cap X=\emptyset$. Here, $\overleftarrow R(x)$ is the initial $R$-interval of $x$ defined as $\overleftarrow R(x)=\{z\mid (z,x)\in R\}\backslash\{x\}$.
I want to prove that the membership relation $\mathbf E=\{(x,y)\mid x\in y\}$ is well-founded without using the axiom of choice. The axiom of foundation as worded in this book is
$$\forall x\in\mathbf U\,(x\ne\emptyset\implies\exists y\in x\,\forall z\in y\,(z\notin x)).$$
I managed to prove that $\mathbf E$ is well-founded, but I had to assume both the axiom of choice and the axiom of foundation. A sketch of that proof is as follows.
Under the axiom of foundation, for every $x\in\mathbf U$ we have $\overleftarrow{\mathbf E}(x)=x$. Assume $\mathbf E$ is not well-founded. Then there is a class $X$ such that for every $x\in X$, there is $y\in x\cap X$. Define a function $f:X\to\mathbf U$ such that for each $x\in X$, we choose $f(x)\in x\cap X$. Then we create a sequence $x_n$ such that for each $n\in\mathbb N$ we have $x_{n+1}\in x_n$. Then the set $\{x_n\mid n\in\mathbb N\}$ will fail the axiom of foundation, so we have a contradiction.
I had some ideas on proving this without the axiom of choice by using the following proposition for the subset relation (the proposition in the book right after the definition of a well-founded relation states that a transitive set-like relation is well-founded if and only if every nonempty set $a\subseteq\text{rng}[R]$ contains an element $y\in a$ such that $\overleftarrow R(y)\cap y=\emptyset$, but I didn't manage to do this.
Is there a way to do this without assuming the axiom of choice? I have no trouble assuming it, but the name "well-founded" makes me think that it is a generalized statement of the axiom of foundation, but for every relation. So if we have to assume the axiom of choice for it, then the name doesn't quite capture its intent from what I can understand.
EDIT: Scanning the book above further along, I see that there is a very difficult proof of this fact without using the axiom of choice. It involves defining the von Neumann universe $\mathbf V$ and proving that $\mathbf E\cap(\mathbf V\cap\mathbf V)$ is well-founded, and then proving that $\mathbf V=\mathbf U$. I will study this approach, but I would still like to see if anyone has a less convoluted proof.

A: Of course we don't need the axiom of choice. In fact, there is nothing to prove.
Since you are considering $\bf E$ to be a class of ordered pairs, you are implicitly requiring that both $x$ and $y$ are sets, i.e. members of $\bf U$, otherwise they cannot be elements of an ordered pair.
Moreover, since $\overleftarrow{\bf E}(x)=x$ follows immediately from the Axiom of Extensionality, the Axiom of Foundation just tells you that $\bf E$ is well-founded.

To prove that $\in$ is also well-founded on classes, suppose that $X$ is a class, note that if $X$ is a set, then we have nothing to check, so we can assume it is a proper class, and so it is also non-empty.
Next, let $x_0\in X$ be some set, and now define $x_{n+1}=\bigcup x_n\cap X$, then $x_{n+1}$ is a set, by Union and Separation, and by Replacement, $\{x_n\mid n<\omega\}$ is also a set. Let $x=\bigcup\{x_n\mid n<\omega\}$, then it is a set, $x\subseteq X$, and so we have two options:

*

*$x=\varnothing$, in which case we have that $x_0\subseteq x$, so $x_0=\varnothing$, so $x_0\cap X=\varnothing$.

*Otherwise, by Foundation, there is some $y\in x$ such that $y\cap x=\varnothing$. However, if $y\in x$, then $y\in X$, and moreover, since $y\in x$ means $y\in x_n$ for some $n$, if $z\in y\cap X$, then $z\in x_{n+1}$. Therefore, since $y\cap x=\varnothing$, it must be that $y\cap X=\varnothing$ as well.
In either case, we found an element of $X$ which is disjoint from it.
Alternatively, you can just prove that assuming $\sf NBG$, we can write $\bf U$ as the union of its von Neumann hierarchy, $\{V_\alpha\mid\alpha\in\rm Ord\}$, so if $X$ is a proper class, there is a least $\alpha$ such that $X\cap V_\alpha$ is non-empty, and by minimality, any member of that intersection must be disjoint from $X$.


text:
Q: Get the nth rownum based on date descending with Google Datastore Hi I'm using google app engine to create a picture hosting website and each page holds 5 images, I want to get a bool which will tell me if there is a subsequent page (they are stored in descending date order). I have a page limit and a page number so what I need is a datastore query that will:
get a single value for the rownum pagenumber * pagelimit (check if theres something stored after the 5 displaying on the page).
Currently I have:
    Query query = new Query("PicturePost").addSort("date",Query.SortDirection.DESCENDING);
    List<Entity> results;

    results = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(pageLimit)
                                    .offset(pageLimit*(pageNumber)));

    boolean lastPage = results.isEmpty();

but this would be inefficient as it gets all 5 entities from the next page.
If anyone could help me I'd be very grateful, thankyou !

A: This seems to work pretty well for me. YMMV. I always include a date_created field [auto_now_add=True] on any entity that needs serial access. The browser client should call the handler function with two inputs: number_of_images to return, and date_limit. First call will have an empty string for date_limit, so you use the current system datetime. Other calls will include the earliest of the dates you sent back in the previous call.
Your query will be (date_created < date_limit) and date_created DESC. Do a keys_only fetch of the number of desired images, and send the keys back for the img src="key_goes_here" setup. If you return less than the desired number of images, or zero then your are out of new images.
If this is an active page, I would be sure to use ndb for the automatic memcaching and tell the browser to cache it in your content header. (You can very easily write a simple memcache function if using db.) Yes this is not perfect: a small % of the time you incur a wasted call because you return N images, and do not know that the next call will return zero. If super active site, you might have a  duplicate of date_created on your image put(). You have the carry the overhead of a custom index, but I think you will incur this cost no matter what approach. As with many GAE things there are often tradeoffs. HTH. -stevep


text:
Q: Add children to existing node using R XML I have the following XML file test.graphml that I am trying to manipulate using the XML package in R.
<?xml version="1.0" encoding="UTF-8"?>
<graphml xmlns="http://graphml.graphdrawing.org/xmlns"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns
     http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">
  <graph id="G" edgedefault="directed">
    <node id="n0"/>
    <node id="n1"/>
    <node id="n2"/>
    <node id="n3"/>
    <node id="n4"/>
    <edge source="n0" target="n1"/>
    <edge source="n0" target="n2"/>
    <edge source="n2" target="n3"/>
    <edge source="n1" target="n3"/>
    <edge source="n3" target="n4"/>
  </graph>
</graphml>

I would like to nest nodes n0, n1, n2, and n3 into a new graph node as shown below.
<?xml version="1.0" encoding="UTF-8"?>
<graphml xmlns="http://graphml.graphdrawing.org/xmlns"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns
     http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">
  <graph id="G" edgedefault="directed">
    <graph id="g1">
       <node id="n0"/>
       <node id="n1"/>
       <node id="n2"/>
       <node id="n3"/>
    </graph>
    <node id="n4"/>
    <edge source="n0" target="n1"/>
    <edge source="n0" target="n2"/>
    <edge source="n2" target="n3"/>
    <edge source="n1" target="n3"/>
    <edge source="n3" target="n4"/>
  </graph>
</graphml>

The code I have written has unknowns and errors that I am unable to resolve due to lack of experience with XML processing. I would greatly appreciate some pointers to that will help me proceed.
library(XML)

# Read file
x <- xmlParse("test.graphml")
ns <- c(graphml ="http://graphml.graphdrawing.org/xmlns")

# Create new graph node
ng <- xmlNode("graph", attrs = c("id" = "g1"))

# Add n0-n3 as children of new graph node
n0_n1_n2_n3 <- getNodeSet(x,"//graphml:node[@id = 'n0' or @id='n1' or @id='n2' or @id='n3']", namespaces = ns)
ng <- append.xmlNode(ng, n0_n1_n2_n3)

# Get only graph node
g <- getNodeSet(x,"//graphml:graph", namespaces = ns)

# Remove nodes n0-n3 from the only graph node
# How I do this?
# This did not work: removeNodes(g, n0_n1_n2_n3)

# Add new graph node as child of only graph node
g <- append.xmlNode(g, ng)
  #! Error message:
  Error in UseMethod("append") :
  no applicable method for 'append' applied to an object of class "XMLNodeSet"

A: Consider XSLT, the special-purpose language to transform XML files. Since you require modification of the XML (adding parent node in a select group of children) and have to navigate through an undeclared namespace prefix (xmlns="http://graphml.graphdrawing.org/xmlns"), XSLT is an optimal solution.
However, to date R does not have a fully compliant XSL module to run XSLT 1.0 scripts like other general purpose languages (Java, PHP, Python). Nonetheless, R can call external programs (including aforementioned languages), or dedicated XSLT processors (Xalan, Saxon), or call command line interpreters including PowerShell and terminal's xsltproc using system(). Below are latter solutions.
XSLT (save as .xsl, to be referenced in R script)
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
     xmlns:doc="http://graphml.graphdrawing.org/xmlns"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">
  <xsl:output method="xml" omit-xml-declaration="no" indent="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:template match="doc:graphml">
    <xsl:copy>
      <xsl:copy-of select="document('')/*/@xsi:schemaLocation"/>
      <xsl:apply-templates select="doc:graph"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="doc:graph">
    <xsl:element name="{local-name()}" namespace="http://graphml.graphdrawing.org/xmlns">
      <xsl:apply-templates select="@*"/>
      <xsl:element name="graph" namespace="http://graphml.graphdrawing.org/xmlns">
        <xsl:attribute name="id">g1</xsl:attribute>
        <xsl:apply-templates select="doc:node[position() < 5]"/>
      </xsl:element>
      <xsl:apply-templates select="doc:node[@id='n4']|doc:edge"/>
    </xsl:element>
  </xsl:template>

  <xsl:template match="doc:graph/@*">
    <xsl:attribute name="{local-name()}"><xsl:value-of select="."/></xsl:attribute>
  </xsl:template>

   <xsl:template match="doc:node|doc:edge">
    <xsl:element name="{local-name()}" namespace="http://graphml.graphdrawing.org/xmlns">
      <xsl:attribute name="{local-name(@*)}"><xsl:value-of select="@*"/></xsl:attribute>
    </xsl:element>
   </xsl:template>
</xsl:stylesheet>

PowerShell script (for Windows PC users, save as XMLTransform.ps1)
param ($xml, $xsl, $output)

if (-not $xml -or -not $xsl -or -not $output) {
    Write-Host "& .\xslt.ps1 [-xml] xml-input [-xsl] xsl-input [-output] transform-output"
    exit;
}

trap [Exception]{
    Write-Host $_.Exception;
}

$xslt = New-Object System.Xml.Xsl.XslCompiledTransform;
$xslt.Load($xsl);
$xslt.Transform($xml, $output);

Write-Host "generated" $output;

R Script (calling command line operations)
library(XML)

# WINDOWS USERS
ps <- '"C:\\Path\\To\\XMLTransform.ps1"'  # POWER SHELL SCRIPT
input <- '"C:\\Path\\To\\Input.xml"'      # XML SOURCE
xsl <- '"C:\\Path\\To\\XSLTScript.xsl"'   # XSLT SCRIPT
output <- '"C:\\Path\\To\\Output.xml"'    # BLANK, EMPTY FILE PATH TO BE CREATED

system(paste('Powershell.exe -executionpolicy remotesigned -File',
             ps, input, xsl, output))              # NOTE SECURITY BYPASS ARGS
doc <- xmlParse("C:\\Path\\To\\Output.xml")

# UNIX (MAC/LINUX) USERS
system("xsltproc /path/to/XSLTScript.xsl /path/to/input.xml -o /path/to/output.xml")
doc <- xmlParse("/path/to/output.xml")

print(doc)
# <?xml version="1.0" encoding="utf-8"?>
# <graphml xmlns="http://graphml.graphdrawing.org/xmlns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">
#   <graph id="G" edgedefault="directed">
#     <graph id="g1">
#       <node id="n0"/>
#       <node id="n1"/>
#       <node id="n2"/>
#       <node id="n3"/>
#     </graph>
#     <node id="n4"/>
#     <edge source="n0"/>
#     <edge source="n0"/>
#     <edge source="n2"/>
#     <edge source="n1"/>
#     <edge source="n3"/>
#   </graph>
# </graphml>


text:
Q: Let $f$ be twice differentiable function on $(0,1)$. Let $f$ be twice differentiable function on $(0,1)$. Given that for every $x\in(0,1)$, $|f''(x)|\leq M$ where $M$ is a non-negative real number. Prove that $f$ is uniformly continuous on $(0,1)$.
My Approach:
Since $f$ is twice differentiable function on $(0,1)$, it follows that $f'$ is continuous in $(0,1)$. So, by Mean Value Theorem, for any $x,y\in (0,1)$ with $x<y$, there is a $z$ with $x<z<y$ such that $|\frac{f'(x)-f'(y)}{x-y}|=|f''(z)|$. That is, $|f'(x)-f'(y)|\leq M|x-y|$ for all $x,y\in(0,1)$.
Now , I don't know how to proceed further.

A: The inequality at which you arrived implies that $|f'(x) - f'(y)| \leq M$ for all $0 < x,y < 1$. If $f'$ is unbounded on $]0,1[$, then for every $B > 0$ there are some $0 < x,y < 1$ such that $|f'(x) - f'(y)| > B$; hence $f'$ is bounded on $]0,1[$ from above by $M$. Then mean-value theorem gives that for every pair of $0 < x,y < 1$ there is some $x < \xi < y$ such that  $|f(x)-f(y)| \leq |f'(\xi)||x-y| \leq M|x-y|$. If $\varepsilon > 0$, the number $\delta := \varepsilon/M$ is such that $|x-y| < \delta$ implies $M|x-y| < \varepsilon$; hence $f$ is uniformly continuous on $]0,1[$.

A: We have since $f''$ is bounded $f'$ is Lipschitz and hence uniformly continuous on $(0,1)$ Then $f'$ is bounded because given any $x,y$ in $(0,1)$ we have $\frac{|f'(x)-f'(y)|}{|x-y|}\le M$ and hence $|f'(x)-f'(y)|\le M$. Thus $f'$ is bounded so $f$ is Lipschitz once again and hence uniformly continuous.


text:
Q: How to decrypt notepad++ nppcrypt encrypted message in programming language plain text:Hello leon
password & iv:leon1234leon1234
cipher: rijndael cbc 128bits
nppcrypto encrypt info
<nppcrypt version="1016">
<encryption cipher="rijndael" key-length="16" mode="cbc" encoding="base64" />
<key algorithm="scrypt" N="16384" r="8" p="1" salt="HA==" />
<iv value="bGVvbjEyMzRsZW9uMTIzNA==" method="custom" />
</nppcrypt>
/8r4DGLVYC+YJSPMFQ8lFQ==

I use java BouncyCastle lib to test, but the encrypt result is diffent
related code is at my github repo
https://github.com/Leon406/Crypto/blob/master/src/main/kotlin/me/leon/modern/PBE.kt
nppcrypt plugin repo: https://github.com/jeanpaulrichter/nppcrypt
Edit: code here as well
package me.leon.modern

import com.lambdaworks.crypto.SCryptUtil
import me.leon.base64Decode
import me.leon.toBase64
import org.bouncycastle.crypto.generators.BCrypt
import org.bouncycastle.crypto.generators.KDF2BytesGenerator
import org.bouncycastle.crypto.generators.SCrypt
import org.bouncycastle.util.encoders.Hex

/**
 *
 *
 * https://www.bouncycastle.org/specifications.html
 * https://antofthy.gitlab.io/info/crypto/key_derivation.txt
 * https://www.openssl.org/docs/manmaster/man1/openssl-kdf.html
 * key derivation function
 * SCrypt   BCrypt  PBKDF2    Added in OpenSSL 3.0
 * Question? how to interact notepad++ nppcrypto
 */
object PBE {
    @JvmStatic
    fun main(args: Array<String>) {
        val pwd = "leon1234leon1234"
        val salt = "HA=="
        val ivbase64 = "leon1234leon1234"
        val key = SCrypt.generate(pwd.toByteArray(), salt.base64Decode(), 16384, 8, 1, 16).toBase64()
        val key2 = BCrypt.generate(pwd.toByteArray(), "iP/MuFEP/jgHs7lBGez7kg==".base64Decode(), 8).toBase64()
        println(key)

        SCryptUtil.scrypt(pwd,16384,8,1).also {
            println("scrypt $it")
        }
        //$s0$e0801$YzXui6dcQ0qbWnTBP36t+Q==$AW81b69h3HepUIi7pW7ThAKuDdpb1oZ7bFIJrF9zQzA=
        //$s0$e0801$bGvjR0//WiaHqAiSDi5Q9g==$8DzAr+nhUyW5fhdj3MLIpovRdp+dLfVoXGqN+Pp3kZU=
         SCrypt.generate(pwd.toByteArray(), "YzXui6dcQ0qbWnTBP36t+Q==".base64Decode(), 16384, 8, 1, 32).toBase64().also {
             println("scrypt dd $it" )
         }
        val r = SymmetricCrypto.encrypt(key, "Hello leon", ivbase64, "AES/CBC/PKCS5Padding")
            .also { println(it) }
        val r2 = SymmetricCrypto.encrypt(key2, "Hello leon", ivbase64, "AES/CBC/PKCS5Padding")
            .also { println(it) }

        SymmetricCrypto.decrypt(key, r, ivbase64, "AES/CBC/PKCS5Padding").also { println(it) }
        SymmetricCrypto.decrypt(key2, r2, ivbase64, "AES/CBC/PKCS5Padding").also { println(it) }
    }
}

A: You pass the key to SymmetricCrypto.decrypt() Base64 encoded, but you do not perform Base64 decoding there, but UTF8 encoding, s. here. For this reason the decryption fails.
Usually key and IV are binary data and not a string. Therefore both should be passed as ByteArray in encrypt()/decrypt(). If they are to be passed as a string, then a reliable binary-to-text encoding must be performed, such as Base64.
The following fix uses the second variant, i.e. passes to decrypt() a Base64 encoded key and IV and Base64 decodes both there:
import org.bouncycastle.crypto.generators.SCrypt
import org.bouncycastle.jce.provider.BouncyCastleProvider
import java.security.Security
import java.util.*
import javax.crypto.Cipher
import javax.crypto.SecretKey
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec
...
val pwd = "leon1234leon1234"
val salt = "HA=="
val key = SCrypt.generate(pwd.toByteArray(), salt.base64Decode(), 16384, 8, 1, 16).toBase64().also { println(it) } // 6owLoTdeL67pEHxJ5gLY9Q==
val iv = "bGVvbjEyMzRsZW9uMTIzNA=="
val ciphertext = "/8r4DGLVYC+YJSPMFQ8lFQ=="
/*SymmetricCrypto.*/decrypt(key, ciphertext, iv, "AES/CBC/PKCS5Padding").also { println(it) } // Hello leon
...
fun decrypt(key: String, data: String, iv: String, alg: String): String {
    val cipher = Cipher.getInstance(alg)
    val keySpec: SecretKey = SecretKeySpec(key.base64Decode()/*toByteArray()*/, alg.substringBefore("/")) // pass key Base64 encoded and Base64 decode here
    if (alg.contains("ECB".toRegex()))
        cipher.init(Cipher.DECRYPT_MODE, keySpec)
    else
        cipher.init(Cipher.DECRYPT_MODE, keySpec, IvParameterSpec(iv.base64Decode()/*toByteArray()*/)) // pass iv Base64 encoded and Base64 decode here
    return String(cipher.doFinal(Base64.getDecoder().decode(data)))
}

A few notes concerning security:

*

*Static IVs are insecure. nppcrypt supports random IVs. The IV should not be identical to the password.

*A 1 byte salt is too short.

*ECB is insecure (just for completeness, since ECB is not used in the posted example, but is implemented).


text:
Q: fadeIn onLoad function So, Im trying to get this id to fade in on the load of the page.  I've seen the posts about fade in.  However, I haven't found any related to an onLoad function.  Could anyone help me out with this?
HTML:

 HELLO, I AM

Javascript:
$( "#intro" ).onLoad(function() {
  $( "#intro" ).fadeIn( "slow")
});

A: There's no such jQuery function as onLoad. Also, you'll probably want to set the default display of your element to "none" using CSS. And, as @Andreas commented, you would then put the $.fadeIn() call in a $(document).ready() callback, so it only executes once the DOM is loaded. So, all together now:
HTML:

 HELLO, I AM

CSS:
#intro {
  display: none;
}

JS:
$(document).ready(function() {
  $("#intro").fadeIn("slow");
});


text:
Q: How to save the content of scrollview to photo library in ios I am new to ios development. I am trying to implement an ios application with UIScrollview.
The purpose of my scroll view is to arrange some images. I need to save the content of the scrollview to photo Library, attach it to email, etc.
Is it posible?
If it is possible, how can I do this?
If any body know please clear my doubt. Thanks in advance.

A: According to the comments, I understand that you want to save the whole content of a UIScrollView.

*

*Firstly, whenever you use UIScrollView, you always have to set another UIView as its content. That UIView is exactly the whole content of your UIScrollView.

*So the question becomes how to save a UIView as an image or attach it into email, well I find a few pages to you which is exactly what you want.
Save UIView's representation to file
http://www.icodeblog.com/2009/07/27/1188/
http://cocoatouch.blog138.fc2.com/blog-entry-57.html


text:
Q: Why appending element to previously appended element not working? Can I simply append element to already appended element? Row exists in google chrome tools, but there are no child elements. Obviously, if case alerts "No".
var row_index = 0;
for (let row of object_data){
$("#data-screen").append(`<div style='width:100%' class='row' id='row_${row_index}'></div>`)
row_index += 1;
for (let elem of row){
    if ($(`#row_${row_index}`).length > 0){
    alert("yes")
    }
    else {alert("no")}
    $(`#row_${row_index}`).append(`<div style='border-bottom:1px solid black;' class='col-md-${column_counter}'>${elem}</div>`)
    }
    }

Dataset:
['3240', 'Job for Python', 'Jobs', 'Mon, 30 May 2022 14:41:37 GMT']
['3241', 'OratorClub & VmesteRosta', 'Club', 'Mon, 30 May 2022 14:41:37 GMT']
['3242', 'DriverClub', 'Drivers', 'Mon, 30 May 2022 14:41:37 GMT']

Jsfiddle:
Fiddle

A: When you use append, you need to wrap in $(...) too. :)

let object_data = [
  ['3240', 'Job for Python', 'Jobs', 'Mon, 30 May 2022 14:41:37 GMT'],
  ['3241', 'OratorClub & VmesteRosta', 'Club', 'Mon, 30 May 2022 14:41:37 GMT'],
  ['3242', 'DriverClub', 'Drivers', 'Mon, 30 May 2022 14:41:37 GMT']
]
let column_counter = 4;

function getInfo() {
  let row_index = 0;
  for (let row of object_data) {
    let el = $(`<div style="width:100%" class="row" id="row_${row_index}"/>`);
    el.appendTo($('#data-screen'));
    row_index += 1;
    for (let elem of row) {
      $(`<div style="border-bottom:1px solid black;" class="test col-md-${column_counter}">${elem}</div>`).appendTo(el);
    }
  }
}
getInfo()

<!DOCTYPE html>

         <meta charset="utf-8">
         <meta http-equiv="X-UA-Compatible" content="IE=edge">
         <meta name="viewport" content="width=device-width, initial-scale=1">
         <meta name="description" content="">
         <meta name="author" content="">

A: Consider the following.

$(function() {
  var object_data = [
    ['3240', 'Job for Python', 'Jobs', 'Mon, 30 May 2022 14:41:37 GMT'],
    ['3241', 'OratorClub & VmesteRosta', 'Club', 'Mon, 30 May 2022 14:41:37 GMT'],
    ['3242', 'DriverClub', 'Drivers', 'Mon, 30 May 2022 14:41:37 GMT']
  ];

  $.each(object_data, function(i, row) {
    // Create the Row
    $("
", {
      class: "row",
      id: "row_" + i
    }).appendTo("#data-screen");
    // Create the Cells, append to Row
    $.each(row, function(j, cell) {
      $("
", {
        class: "col col-md-" + row.length + " bottom-border",
      }).html(cell).appendTo("#row_" + i);
    });
  });
});
.bottom-border {
  border-bottom: 1px solid black;
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

This uses $.each() to iterate over the data and create the Rows and Cells. I had to make some guesses on what you might be trying to accomplish.
See more: https://api.jquery.com/jquery.each/
In the first loop, I use i as the Index and row as the Array element (from an Array of Arrays). In the second loop, I use j as the Index, and cell as the value of the element in the Array.
As the loop iterates each element, I create a DIV Element with a unique ID, to represent the Row. I then perform a second loop inside the first to create the Cells as DIV elements, which are appended to the DIV.


text:
Q: Extending $G$-closed sets to permutation bases of a permutation $RG$-module I'm curious if there are any papers or results about the following scenario:

Let $R$ be a commutative ring (I'm interested in particular in the $R = \mathbb{Z}$ case, but fields are okay too), $G$ a finite group, and $M$ be a finitely generated permutation $RG$-module. Suppose
$\mathcal{B}$ is a set of $R$-linearly independent elements of $M$
which is closed under $G$-multiplication. What properties must be satisfied by $\mathcal{B}$ for $\mathcal{B}$ to be extendable to a permutation basis of $M$?

I have some specific cases for when I know a set of this form can be extended to a full permutation basis, and there are plenty of counterexamples one can cook up where a set cannot be extended, but I'm wondering if this has been studied in greater detail. I wasn't able to find anything on a first pass, but this seems like something that likely has been studied before, and such results would help me extend some results to much greater generality!
I wonder as well if there are any analogous results for, in the case where $R$ is a finite field, $p$-permutation modules, i.e. considering $M$ as a permutation $RP$-module for some Sylow $p$-subgroup $P\leq G$.


text:
Q: C++ Linked List: Problem with struct inside class I've been trying to implement a linked list in C++. I found this implementation on the web, where they created a struct for the list's nodes.
When trying to add a new node to the list, I get this error:
List.C: In member function `bool Linked::addVertex(Point)':
List.C:23: error: no matching function for call to `Linked::node::node()'
List.H:35: note: candidates are: Linked::node::node(const Linked::node&)
And here's my Code, and thank you very much.. :)
List.H
#ifndef _AUXILIARY_H_
#define _AUXILIARY_H_
#include <string.h>
#include <math.h>

class Linked
{

 public:
 // Constructor: initializes a set of nodes
 Linked();

 // Linked methods
 bool addNode(Point p);
 bool removeNode(int index);
 bool getNode(int index, Point* p) const;
 bool setNode(int index, Point p);
 int getNodesCount() const;

 // Destructor: delete the set of nodes
 ~Linked();

 private:
 // Definition of the nodes on the array of nodes
 /*typedef struct _Node* pNode;
 typedef struct _Node
 {
  Point pt;
  int index;
  Node *next;
 }  Node;
 */
 struct node
 {
  Point pt;
  int index;
  node *next;
 } *pLinked;

 // Definition of Bool type
 typedef enum {FALSE, TRUE} Bool;
};

#endif // _AUXILIARY_H_

List.C
#include <string.h>
#include "List.H"

Linked::Linked()
{
     pLinked=NULL;
}

bool Linked::addNode(Point p)
{
 node *q,*t;
 int i=0;
 q = pLinked;

 while (q+i)
 {
  if ((q->pt.getX() == p.getX()) && (q->pt.getY() == p.getY()))
   return FALSE;
  q = q->next;
  i++;
 }

 t = new node;
 t->pt.setPoint(p);
 t->index = getNodesCount();
 t->next = q->next;
 q->next = t;

 return TRUE;
}

bool Linked::removeNode(int index)
{
    node *q,*r;
 q = pLinked + index;
 r = q - 1;
 if (q == NULL)
  return FALSE;
 r->next = q->next;
 delete q;
 return TRUE;
}

bool Linked::setNode(int index, Point p)
{
 node *q;
 q = pLinked + index;
 if (q == NULL)
  return FALSE;
 p.setPoint(q->pt);
 return TRUE;
}

int Linked::getNodesCount() const
{
 node *q;
 int count=0;
 for( q=pLinked ; q != NULL ; q = q->next )
        count++;
 return count;
}

Linked::~Linked()
{
 node *q;
 if( pLinked == NULL )
  return;
 while( pLinked != NULL )
 {
  q = pLinked->next;
  delete pLinked;
  pLinked = q;
 }
}

A: TAKE HEART! C(++) is a confusing morass of tradition and guesswork when you're learning it. It's a bit like a mouse crawling around inside a Mercedes engine.
Eventually you will feel like you're on the engine design team :)

A: Your code compiles fine in Visual Studio 2008, but I did use .cpp as the file extension as suggested by other users. Many compilers assume .C files are for straight C, and .cpp file are for C++. You are doing C++
Good Luck!

A: This type of error would occur if the node struct cannot be constructed automatically. Does your Point class have a constructor with zero arguments? Otherwise, you need to add a constructor to node.


text:
Q: Keep getting record_invalid while using FactoryGirl A lot of times, when I use FactoryGirl in my specs, I keep receiving errors like:
Failure/Error: f = FactoryGirl.build(:my_model)
     ActiveRecord::RecordInvalid:
       translation missing: de.activerecord.errors.messages.record_invalid

Now, if I start a console in test mode, I get a record back, and I don't get any errors.
How should I proceed with this?
EDIT: I was missing the translation and did not see the relevant message. After I switched to a :en locale, the errors were clear.

A: Probably you can't build your model, because it requires some parameters during initialization. Use initialize_with:
factory :user do
  name "John Doe"

  initialize_with { new(name) }
end

Look at https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md#custom-construction for details


text:
Q: What is the process for solving second order linear differential with nonconstant coefficients? I was reading through some of the extra sections we had not covered in my differential equations class and they describe a method for solving non-constant equations. It never really showed how to solve. Just a bunch of ways to show it exists on a certain interval.
Could someone describe what this method is of solving them (obviously integration may fail) and also (if the person is aware) make it clear which things come from the knowledge that antiderivates vary by constants? I know that sounds weird but it useful for me to know precisely what things come from the set of antiderivatives varying by constants. It allows me to use a few special tricks I know for harder problems involving piecewise continuity.
The specific equation form the section seemed to be discussing how to solve was:

$y'' + f_1(x)y' + f_2(x)y = g(x)$

It did mention transforming to the standard form but since I understand that there is no need to have it as anything else. It said there was a way to solve these for continuous f's and g and also how to prove the existence. However, it never actually said how to find the integral. If needed, I am willing to accept that g is zero. I am aware of the annihilator method so that probably comes immediately into play in dealing with g.

A: Quite honestly, I think that the answer is a lot longer than you were anticipating. There are many methods to solving such equations. You usually have to take it case by case.
First and foremost, we must separate the techniques into three categories.
1) Numerical methods such as Euler Method, midpoint method, and Runge-Kutta Fourth Order are great tools for approximating the value of such functions over a range. In essence, they perform the raw definite integration of the differential equation using a specified number of iterative steps.
2) If you already have $1$ solution, either determined from some alternative method, or perhaps found by sheer luck or circumstance of the problem, reduction of order can be used. This works analogously to undetermined coefficients, where you guess a solution comprised of your known solution and some other unknown function that you must solve for. Consequently, this method converts the 2nd order equation into a first order linear, so an integrating factor can be used.
If you know the general solution to the homogeneous equation, you can use variation of parameters to find a solution to the non-homogeneous equation.
3) As for actually solving the equation, power series method can be used in the case that the point you're expanding around isn't singular. This method entails assuming that $y$ can be written as an infinite sum of x-powers with coefficients that you solve for. This leads to a recursion, which in some case can be related back to the Taylor series of some known function to obtain a closed solution. If you are given initial conditions, it may be easiest to Laplace transform the equation, get it into a tangible form, and then inverse Laplace transform the result. Most methods become quite ugly to work with in non-linear cases, and may not even be solvable analytically, in which case we must return to numerical approximations


text:
Q: 'module' object is not callable typeerror django So I have a module that I successfully use. But now I added another file to module and it gives me this error.
I have a file generate_bags_uk that has method:
def generate_bags(bags, price):

And I use it like this:
from excelgenerator import generate_bags_uk
...
uk_bag = generate_bags_uk.generate_bags(tshirts, form.cleaned_data['price_uk_bag'])

And I get TypeError: module is not callable. What am I doing wrong here ?

A: Try the following code instead -
from excelgenerator.generate_bags_uk import generate_bags
...
uk_bag = generate_bags(tshirts, form.cleaned_data['price_uk_bag'])

and make sure excelgenerator folder has a __init__.py inside  it, otherwise it will not be dealt as a python package.
Also, I guess the method has a body, if it does not then at least give it a definition -
def generate_bags(bags, price):
    pass

COMMENT : From the looks of this error, the error is happening in file /home/marijus/workspace/tshirtnation/excelgenerator/generate_bags_uk.py. I think your other calls are also of similar format and thus causing error. Please change them as I mentioned. The problem should be solved.


text:
Q: MVC 5 UrlHelper without HTTPContext? I decorate my MVC 5 actions with route attributes:
[Route("this-test")]
public ActionResult ThisTest()

and with a HTTPContext I can access the route name like so:
UrlHelper helper = new UrlHelper(System.Web.HttpContext.Current.Request.RequestContext);
string actionUrl = helper.Action("ThisTest", "Home");

However I'm using Hangfire chron jobs to fire off some emails.  Since I don't have a HTTPContext I cannot use the code above to obtain my route of "home/this-test/".
Is this possible to achieve?  Thank you.

A: Look at this topic:
Passing site URL to hangfire recurrent jobs.
Relying on the answer there, there's no way to receive the domain inside a Hangfire job. It seems like passing the URL of your site as a parameter to a job is the most clear solution.


text:
Q: Exception in soap method call in PHP 5.3 I am trying to call the following web service
http://iskynettrack.skynetwwe.info/TrackingService/TrackingService_v1.asmx
but I am getting in response:

Exception in ValidateConsignor(consignorUsername, consignorPassword,
  consignorAccount, stationCode) Method: Procedure or function
  'ValidateConsignorLoginDetails' expects parameter '@UID', which was
  not supplied. Array ( [0] => SimpleXMLElement Object (
  [GetSkyBillTrackResponse] => SimpleXMLElement Object (
  [GetSkyBillTrackResult] => SimpleXMLElement Object ( [errorMessage] =>
  Exception in ValidateConsignor(consignorUsername, consignorPassword,
  consignorAccount, stationCode) Method: Procedure or function
  'ValidateConsignorLoginDetails' expects parameter '@UID', which was
  not supplied. ) ) ) ) Array ( [soap:Body] => Array (
  [GetSkyBillTrackResponse] => Array ( [GetSkyBillTrackResult] => Array
  ( [errorMessage] => Exception in ValidateConsignor(consignorUsername,
  consignorPassword, consignorAccount, stationCode) Method: Procedure or
  function 'ValidateConsignorLoginDetails' expects parameter '@UID',
  which was not supplied. ) ) ) )

I am supplying everything correctly here is my code.
$client = new SoapClient('http://iskynettrack.skynetwwe.info    /TrackingService/TrackingService_v1.asmx?WSDL', array('trace' => 1));

$datatrack=array('consignorUsername,'=>"R1803362",
'consignorPassword'=> "R1803362",
        'consignorAccount'=> "R1803362",
              'stationCode'=> "DHX",
              'isRef'=>"0",
               'shipmentNumber'=> "088800202392");

$crshipment=$client->GetSkyBillTrack($datatrack);

$strresp=$client->__getLastResponse() . "\n";


text:
Q: Delivering Java se project to complete non technical customers Suppose I have a phone book java desktop application which  uses peoples name,address,phone numbers etc stored in a database.database server used is mysql and persistence using hibernate framework.Then how am i suppose to deliver this application to so called customer who has no at all programming knowlewdge??
PS:i have used eclipse as my IDE.

A: Collect all the prerequisites, create needed batch/bash file for start and installation.
Put every thing together with the use of an installer like innosetup
That's the way i do it...


text:
Q: Create shortcut to dial VPN connection in Windows 8 It was easy to create a shortcut that automatically dials a VPN connection in Windows 7 (e.g., see these answers). But if I create that shortcut in Windows 8, double-clicking it opens the Networks panel (and doesn't establish the connection).
How do I create a shortcut in Windows 8 that dials a VPN connection?

A: I believe you were close..
The command you were looking for is rasdial.exe
Create the shortcut on your desktop as rasdial.exe then all you need to have is the name of the network. ie... rasdial.exe "Work Network" or whatever you have called your VPN Connection.
Then put it in your Startup folder just like you would any other program you want to run on startup.

*

*Right-click the desktop, choose New > Shortcut.

*Enter rasdial.exe as the location of the item; click Next.

*Type a name for the shortcut, e.g., "Work VPN"; click Finish.

*Right-click the new shortcut, choose Properties.

*Edit the Target to be C:\Windows\System32\rasdial.exe "Work
Network"
Copy the shortcut into your Startup folder: %userprofile%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\

A: Use the rasphone utility as documented in KB555935. Assuming your VPN connection is named "Work VPN", follow these steps:

*

*Right-click the desktop, choose New > Shortcut.

*Enter rasphone.exe as the location of the item; click Next.

*Type a name for the shortcut, e.g., "Work VPN"; click Finish.

*Right-click the new shortcut, choose Properties.

*Edit the Target to be C:\Windows\System32\rasphone.exe -d "Work VPN" (change the name to be the name of your VPN connection; to see the names of existing connections, just run rasphone.exe with no arguments).

*(Optional) Click Change Icon and pick a better icon; there are a few icons of networks in Shell32.dll.

A: You can also do the following steps to add a shortcut to the desktop:

*

*Step 1: Right click on Network icon (wireless or wired) on task bar

*Step 2: Left click on "Open Network and Sharing Center (menu item)"

*Step 3: Left click on "Change adapter settings (link)" in "Control Panel\All Control Panel Items\Network and Sharing Center"

*Step 4: Right click on "Name (edit)" in "Control Panel\Network and Internet\Network Connections"

*Step 5: Left click on "Create Shortcut (menu item)"

*Step 6: Left click on "Yes (button)" in "Shortcut"


text:
Q: Making a list out of ... function arguments Here's a puzzle I just ran across:
x <- data.frame(a="hi",b="lo")
y <- data.frame(a="hi",b="lo")

getCommonNames <- function(...) {
  l <- list(...)
  sapply( l, names )
}

vs.
getCommonNames2 <- function(...) {
  sapply( list(...), names )
}

> getCommonNames2(x,y)
Error in lapply(X = X, FUN = FUN, ...) :
  argument "X" is missing, with no default
> getCommonNames(x,y)
     [,1] [,2]
[1,] "a"  "a"
[2,] "b"  "b"

Why does list(...) properly coerce its contents to a list when stored to something (or used as a return value), but not when it is used in a expression without storing it first?
This seems like a triviality, but it sort of broke my mental model of R parsing, in which everything gets resolved then stored or passed along to the next argument.  I've learned not to ignore such moments, as re-building my mental model to take the new information into account often results in a deeper understanding of things.
So...what's going on here?

A: It is probably a bug in your version of R or some missmatch in your current environment.
My version does not reproduce the same problem, it just goes as expected.
> x <- data.frame(a="hi",b="lo")
> y <- data.frame(a="hi",b="lo")
>
> getCommonNames <- function(...) {
+   l <- list(...)
+   sapply( l, names )
+ }
>
>
> getCommonNames2 <- function(...) {
+   sapply( list(...), names )
+ }
>
> getCommonNames2(x,y)
     [,1] [,2]
[1,] "a"  "a"
[2,] "b"  "b"
> getCommonNames(x,y)
     [,1] [,2]
[1,] "a"  "a"
[2,] "b"  "b"

version.string R version 2.14.0 (2011-10-31)


text:
Q: Javascript RegEx Mysteries (for a poor C programmer) This is clearly a RTFM issue, but after I did so repeatedly I just can't get the damn thing to work so there are times when asking for help makes sense:
   var text = "KEY:01 VAL:1.10,KEY:02 VAL:2.20,KEY:03 VAL:3.30";
   var pattern = '/KEY:(\S+) VAL:([^,]+)/g';
   //var pattern = '/KEY:(\S+) VAL:(.?+)(?:(?=,KEY:)|$)/g';
   //var pattern = '/KEY:(\S+) VAL:(.+)$/g';
   //pattern.compile(pattern);
   var kv = null;
   var row = 0, col = 0;
   while((kv = pattern.exec(text) != null))
   {
     row = kv[1].charAt(0) - '0';
     col = kv[1].charAt(1) - '0';
     e = document.getElementById('live').rows[row].cells;
     e[col].innerHTML = kv[2].slice(0, kv[2].indexOf(","));
   }

kv[1] is supposed to give "01"
kv[2] is supposed to give "1.10"
...and of course kv[] should list all the values of 'text'
to fill the table called 'live'.
But I can't get to have pattern.exec() succeed in doing that.
Where is the glitch?

A: First, the delimiters for the RegExp should be /s, there's no need to put them in ' delimiters.  i.e. to get your exec to run properly you should have:
var pattern = /KEY:(\S+) VAL:([^,]+)/g;

Second, you're assigning a boolean to kv which you don't want.  The while will obviously only evaluate to true if it's not null so that's redundant.  Instead you just need:
while (kv = pattern.exec(text)) {

That should get your code to work as you desire.

A: the syntax for pattern objects doesn't include quoting, such as:
var pattern=/KEY:(\S+) VAL:([^,]+)/g;

http://www.w3schools.com/jsref/jsref_regexp_exec.asp

A: It should be
var pattern = /KEY:(\S+) VAL:([^,]+)/g;

http://www.regular-expressions.info/ is a good place to start with.


text:
Q: Integrating Facebook in iOS using Parse Mobile Platform I am trying to run a simple iPhone application using Parse o integrate with facebook.
You can easily download the project here
The problem is when I login to facebook, I go to this page:

When I click on the Okay button, I get this error message:

So It does not navigate to the next ViewController (UserDetailsViewController).
Can you help me?

A: You should add the app URL scheme for you app to the info.plst
Since you did not add this, iOS does not know how to open you app.
Adde the following to your apps info.plist:
<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>fb<YOUR APPS FACEBOOK ID></string>
            <string><YOU APPS NAME></string>
        </array>
    </dict>
</array>

And replace the  with you apps facebook ID but leaf the fb, it should look like fb1231654354.

A: I think you should avoid fb which you written prior to your app_id in delegate file..
fb is needed only in urlScheme


text:
Q: Array of NSManagedObjects has null values in it after passing it to another method In my app I'm using MagicalRecord for CoreData stack and I'm having a weird behavior of NSManagedObject. I have this method in my DB class that fetches all the entries of the Stuff entity from DB. I'm calling this method from another class, and inside of this getStuff method I'm getting correct values that getting print out in the log statement below.
-(NSArray*) getStuff
{
    NSManagedObjectContext * managedObjectContext = [NSManagedObjectContext MR_contextWithStoreCoordinator:self.psc];

    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Stuff"];

    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"idNumber" ascending:YES];

    [request setSortDescriptors:[NSArray arrayWithObjects:sort, nil]];

    NSError *error = nil;
    NSArray *arr = [managedObjectContext executeFetchRequest:request error:&error];

    for (Stuff *stuff in arr) {
         NSLog(@"stuff fN: %@",stuff.idNumber);
    }

    if (arr)
       return arr;

    return [NSArray array];
}

However, the array that gets returned by this method to another class contains all these objects with null value in them.
// -- some othe class
// call DB to check if we have stuff there
NSArray* stuff = [database getStuff];

for (Stuff *stuff in stuff) {
         NSLog(@"stuff fN: %@",stuff.idNumber);
    }

Does anyone know why is this happening?! Any kind of help is highly appreciated!

A: Your getStuff method creates a new NSManagedObjectContext, which is (assuming that you compile with ARC) deallocated at the end of the method. Managed objects "live" in the context that they were created in. Accessing their properties after the context has been deallocated does not work.

A: Assuming you setup your CoreData stack with MagicalRecord you can use [NSManagedObjectContext MR_contextForCurrentThread] instead of [NSManagedObjectContext MR_contextWithStoreCoordinator:self.psc]


text:
Q: django rest framework ordering non model field(serializer field) i want to ordering on my fields like this:
class DealerBackOfficeViewSet(mixins.ListModelMixin,
                          mixins.RetrieveModelMixin,
                          mixins.CreateModelMixin,
                          mixins.UpdateModelMixin,
                          viewsets.GenericViewSet):
filter_backends = (filters.OrderingFilter,
                   )
ordering_fields = ('online',...)

this way of ordering work only on model's fields but online field defined in my serializer and while test in postman not work.
i want to done it like this :
class CustomOrdering(filters.OrderingFilter):

def filter_queryset(self, request, queryset, view):
    params = request.query_params.get(self.ordering_param)
    if params == 'online':
        ...   my serializer codes
    return super(CustomOrdering, self).filter_queryset(request, queryset, view)

this problem is other fields ordering not work!! is there a way to solve it any way?
if related docs help me please give me the link .
thanks for your site

A: after struggle in this challenge i undrestand that exist a way to some how indicate this fields as model field and not need to CustomOrdering and any extra codes!
in my get_queryset function i change the code:
queryset = Dealer.objects.all()

to:
queryset = Dealer.objects.all().annotate(bids_count=Count('bid'), device_count=Count('device'))

note that this two fields in my serializer not in my model.
in my serilizer change this two field from SerializerMethodField to IntegerField and clean the defs.
then in my api file add this:
filter_backends = (filters.OrderingFilter,)
ordering_fields = ('bids_count', 'device_count')

this my last serializer:
class DealerListSerializer(serializers.ModelSerializer):
    device_count = serializers.IntegerField()
    bids_count = serializers.IntegerField()

    class Meta:
        model = Dealer
        fields = ('id', 'last_name', 'first_name', 'username', 'person_trust', 'is_active',
                  'work_type', 'address', 'mobile', 'device_count', 'online', 'bids_count')

by this way my code is very clear and my CustomOrdering and all elif statements also clean!

A: It doesn't work because the fields defined in your serializer aren't part of the model. The ordering attribute only works for model fields. You'd probably have to introduce a work around like creating a dynamic field using annotations and then order using that field but this depends on whether or not your online field logic can be annotated.


text:
Q: Is it possible to move a TFS repository from SQL 2012 Express to SQL 2008R2? Does anybody know if it's possible to move a TFS repository from SQL 2012 Express to SQL 2008R2?
Background:
At some point someone in our shop installed TFS to test it. This was done on a SQL 2012 Express.
Over time this installation has become our de facto source control system and contains history for 25+ different solutions.
Now our Sys Admin would really like to get rid of this 2012 Express edition. Which means we have to move it to our 2008R2 SQL production server.

A: No, as far as I know this is not officialy supported. SQL Server is backward compatible meaning you can go from 2008 to 2012. The other way around however is not supported.
By far the easiest solution would be to move to a regular SQL Server 2012 install. When you have a license for TFS, you also get a license for SQL Server Standard that you can use.
If that's not possible, you should contact Microsoft support. They have a script that you can use to migrate the data from one database to another. This can be done to run a downgrade but it's only supported if Microsoft helps you with it.


text:
Q: number format in pgfplots axis How can I change the type of the decimal/thousand separator from the american one to the european one? More precisely, I want:

*

*"1000" to be written as is, instead of "1,000"

*"0,1" instead of "0.1"

A: The number formatting is changed using the /pgf/number format keys, which are described starting on page 546 of the pgfmanual. In your case, you would want to set /pgf/number format/use comma to set the comma as the decimal separator, and /pgf/number format/1000 sep={} to suppress separators for the groups of thousands.
When setting several subkeys, you can save yourself a bit of typing by first changing to the main key using /pgf/number format/.cd, and then setting the number formats.
Since I assume you want the number format to be consistent all through your plot, you should set the options for the whole axis.
Here's an example:
\documentclass{article}
\usepackage{pgfplots}

\begin{document}

\begin{tikzpicture}
\begin{axis}[
    /pgf/number format/.cd,
        use comma,
        1000 sep={}]
\addplot +[domain=0:1] {(x+rnd)*4000};
\end{axis}
\end{tikzpicture}

\end{document}

A: Edit: As per Jake's comments: using set decimal separator={,} instead of use comma introduces an unwanted thin space after the comma. Interestingly, if you use set decimal separator={.}, this doesn't happen.  So, better to use use comma instead as per Jake's solution.

Use set thousands separator={} and set decimal separator={,} which yields:

\documentclass{article}
\usepackage{pgfplots}

\begin{document}
\begin{tikzpicture}
\begin{axis}[
      y tick label style={/pgf/number format/.cd,%
          scaled y ticks = false,
          set thousands separator={},
          fixed},
      x tick label style={/pgf/number format/.cd,%
          scaled x ticks = false,
          set decimal separator={,},
          fixed}%
     ]
  \addplot coordinates {
  (0.1,1000)
  (0.2,1100)
  (0.3,1200)
  };
\end{axis}
\end{tikzpicture}
\end{document}


text:
Q: ¿Como puedo hacer scroll en la terminal Linux sin usar el mouse? Estoy utilizando UBUNTU sin interfaz gráfica, y cuando abro un fichero que es muy extenso solo se ven las últimas líneas de abajo, y quisiera saber cómo hacer un scroll en vertical hacia arriba y abajo usando el teclado (combinación de teclas) ya que cuando uso Ubuntu sin interfaz gráfica no puedo usar el mouse.

A: Para Ubuntu sin interfaz grafica puedes usar 'Shift + Page up' para hacer scroll hacia arriba y 'Shift + Page down' para scroll hacia abajo.
Si quieres ir al inicio del contenido de la terminar puede funcionar tambien 'Ctrl + Shift + Home' y para ir a la ultima linea escrita 'Ctrl + Shift + End'
Espero y te sirva.


text:
Q: Can I post items on the eBay store using their API I'm curious,
Using eBay's API can I post items to the eBay store on behalf of users?
As in, can I build my system through which i can post items to the eBay store?

A: Yes you can. If you want to just post items and leave them it's relatively simple.  You can also manage the inventory / orders / shipments etc which is a lot more advanced.
Here's a useful guide in the eBay API section:
http://developer.ebay.com/devzone/xml/docs/howto/XML_ListingAndSelling/ListingAndSelling_listing.html


text:
Q: instr versus regex for string match in oracle I am using the below to get the top count of pages visited in past 60 days, where I need a match in the url for 'abc.cfm' or '/entity/'. Is there a way to do this using regex? Is the below method ok to use or is there a better way. Thanks in advance.
SELECT url, count(URL)
  FROM tableone
  WHERE ( INSTR(url, 'abc.cfm') > 0
   or
         INSTR(url, '/entity/') > 0 )
and VIEW_DT > sysdate - 60
group by URL
order by count(URL)  desc

A: Just use like. This will usually be a bit faster than instr and much faster than regexp_like:
 WHERE (  url like '%abc.cfm%'
       or url like  '%/entity/%'
       )

I tested on a table with 1.8M rows of which 700 matched the criteria.  The approximate timings from repeated tests were:
instr         0.9 seconds
regexp_like  15.0 seconds
like          0.6 seconds

I would only use regexp_like for expressions that are too complex for like.

A: Try
regexp_like(url,'(abc.cfm|/entity/)')

instead of
( INSTR(url, 'abc.cfm') > 0
   or
         INSTR(url, '/entity/') > 0 )


text:
Q: How to convert arrayOfObject to arrayOfArray transposing in JavaScript? I have arrayOfObject like below
[{A:100,B:300,C:200},{A:200,B:400,C:100},{A:400,B:500,C:200}]

and want to convert to below data structure.
[[A,100,200,400],[B,300,400,500],[C,200,100,200]]

Could anyone tell me how to do this data conversion?

A: You can use reduce to create one object and then get its values with Object.values to get array of arrays.

const data = [{A:100,B:300,C:200},{A:200,B:400,C:100},{A:400,B:500,C:200}];
const result = data.reduce((r, e) => {
  Object.keys(e).forEach(key => {
    if (!r[key]) r[key] = [key]
    r[key].push(e[key])
  })
  return r;
}, {})

console.log(Object.values(result))

A: If all objects have the same keys, you can map them (seems better for tabular format):

var a = [{A:100,B:300,C:200},{A:200,B:400,C:100},{A:400,B:500,C:200}]

a = Object.keys(a[0]).map(k => [k, ...a.map(o => o[k])])

console.log( a )


text:
Q: App Engine Modules Project using maven and Java I want to create an App Engine Modules project using maven in Java basically for frontend and backend instance.
For that I don't have any idea of module project structure as well as archetype of the module app engine project.

A: The docs walk you through creating an App Engine module using Maven.  If you use the appengine-skeleton-archetype archetype, Maven will create the directory structure for you.
If you're using Java for all of your modules (hint: you don't have to), you will want to create a Maven module corresponding to each of your App Engine modules.
The App Engine modules documentation explains how to configure your modules.


text:
Q: Radio Button to Function as Conditional with simple_form in Rails, Not Persisted to the Database Currently I do not know how to create a radio button with simple_form that is not an attribute of a resource.
I am trying to create a radio button that is not saved to the database.  The radio button simply functions as a conditional:  If the yes radio button is checked, then I will add in some stuff with coffeescript.  If no is selected then nothing should happen.
code so far:
<%= simple_form_for(@model) do |f| %>
    <%= f.label "Were you referred here?" %>

        <%= f.radio_button :referral_check%> Yes

        <%= f.radio_button :referral_check%> No

      <%= f.button :submit %>

<% end %>

A: This is the best way I could find to do it:
<%= simple_form_for(@model) do |f| %>
   <%= f.label "Were you referred here?" %>

       <%= radio_button_tag "referral", "true" %> Yes

       <%= radio_button_tag "referral", "false" %> No

<% end %>

The attribute of referral does not need to exist as an attribute to any model. In other words, there is no column in any of the database tables named referral. This attribute will still get passed to the server with all the other parameters, but that is ok.  Thanks to strong parameters, and the fact that I used a radio_button_tag thus not tieing this input selection to the current form, Nothing will happen with this attribute.  Once it gets to the server it will simply be ignored.


text:
Q: ValueError, Datetime does not match format I got a CSV I want to work with imported. Trying to define the format of the time I get an ValueError.
This is how my data is formatted inside the CSV:
1979-01-01 06:00:00 +0000 UTC
This is how I use datetime:
headers = ['dt', 'dt_iso', 'timezone', 'city_name', 'lat', 'lon', 'temp', 'visibility', 'dew_point', 'feels_like',
           'temp_min', 'temp_max', 'pressure', 'sea_level', 'grnd_level', 'humidity', 'wind_speed', 'wind_deg',
           'wind_gust', 'rain_1h', 'rain_3h', 'snow_1h', 'snow_3h', 'clouds_all', 'weather_id', 'weather_main',
           'weather_description', 'weather_icon']

df = pd.read_csv('/Users/yourname/Desktop/Historical.csv', names=headers)
df['dt_iso'] = df['dt_iso'].map(lambda x: datetime.strptime(str(x), '%Y-%m-%d %H:%M:%S %z %Z'))
x = df['dt_iso']
y = df['temp']

This is the error I get:
ValueError: time data 'dt_iso' does not match format '%Y-%m-%d %H:%M:%S %z %Z'
Appreciate any help and advice!


text:
Q: select the time conflict in a single table sql i want to get the time conflict in a specific day
my table

| starttime | endtime  | day  | subject |
------------------------------------------
| 09:00:00  | 11:00:00 |  M   |   math  |
 -----------------------------------------
| 09:00:00  | 11:00:00 |  M   | science |
 -----------------------------------------
| 06:00:00  | 09:00:00 |  M   | History |
 -----------------------------------------
| 06:00:00  | 09:00:00 |  T   |   P.E.  |
 -----------------------------------------
| 10:00:00  | 12:00:00 |  M   | English |
 -----------------------------------------

the output i want to get
| starttime | endtime  | day  | subject |
------------------------------------------
| 09:00:00  | 11:00:00 |  M   |   math  |
 -----------------------------------------
| 09:00:00  | 11:00:00 |  M   | science |
 -----------------------------------------
| 10:00:00  | 12:00:00 |  M   | English |
 -----------------------------------------

A: The only interpretation of your question which makes any sense to me is that you want to identify records whose time range overlaps ("conflicts") with one or more other time ranges.  If so, we can do a self join on the condition of overlap, and then retain those ranges which do have an overlap.
SELECT DISTINCT
    t1.starttime,
    t1.endtime,
    t1.day,
    t1.subject
FROM yourTable t1
LEFT JOIN yourTable t2
    ON
        (t1.starttime > t2.starttime AND t1.starttime < t2.endtime AND t1.day = t2.day) OR
        (t1.endtime > t2.starttime   AND t1.endtime < t2.endtime AND t1.day = t2.day) OR
        (t1.starttime = t2.starttime AND t1.endtime = t2.endtime AND t1.day = t2.day AND
         t1.subject <> t2.subject)
WHERE
    t2.starttime IS NOT NULL;

Output:
    starttime   endtime day subject
1   07:00:00    10:00:00    T   History
2   07:00:00    10:00:00    T   P.E.

Demo here:
Rextester


text:
Q: Failing DDL and locked database Instance: skilled-tiger-296:db
One table became inaccessible with selects failing error 'Table doesn't exist'.
Attempts to drop table caused the same error.
Attempts to create table caused error 'Table exists already'.
Attempts to drop schema fail with internal error and disconnect from instance.
Forward-engineering schema with a new name helped for a couple days and now its failing again on the same table.
Problem 1: Lost table
Problem 2: cannot drop database (dbname: flow)
Please advice

A: It sounds like you may have a corruption problem. Try running DROP TABLE IF EXISTS and REPAIR TABLE like in this question. Also make sure in future you use InnoDB tables as these are much more robust.


text:
Q: Display content from "About Us" page on the Home Page I have a page called "About Us" with some static content. I want to display that static content on the home page. Would I need to do a custom query that returns the about page, or is there a better way?
$about_page = new WP_Query('p=7'); // is this basically it?

Is there a better way to do this? A more dynamic way that would allow me to distribute this theme to others who don't have a specific ID for an About page.
EDIT:
Found this page on the Codex. It recommends using the get_page function.

A: If you're using WP_Query, then assign that page a custom meta key 'home_content' with a value as 1. Then use WP_Query's custom field parameters to loop over it. If you can restrict the title as 'About' everywhere, use get_page_by_title, and if you can restrict the slug as 'about', use get_page_by_path. These methods will work dynamically.


text:
Q: NBody code that won't work in java - what do I need to fix? I wrote this code in Eclipse to solve the NBody physics equation however there is an unresolved error. In this line "double Fnet = Gmassmass/(distdist);" eclipse underlines Gmass in red and gives me the message "The operator * is undefined for the argument type(s) double, double[]." How do I resolve this issue? The full code is included below.
public class NBody {

    public static final String PLANETS_FILE = "planets.txt";

    // animation pause (in miliseconds)
    public static final int DELAY = 20;

    // music (2001 theme)
    public static final String MUSIC = "2001theme.wav";

    // background image
    public static final String BACKGROUND = "starfield.jpg";

    // gravitational constant (N m^2 / kg^2)
    public static final double G = 6.67e-11;

                                        // parameters from command line
    public static double T;             // simulate from time 0 to T (s)
    public static double dt;            // time quantum (s)

                                        // parameters from first two lines
    public static int N;                // number of bodies
    public static double R;             // radius of universe

    public static double[] rx;          // x position (m)
    public static double[] ry;          // y position (m)
    public static double[] vx;          // x velocity (m/s)
    public static double[] vy;          // y velocity (m/s)
    public static double[] mass;        // mass (kg)
    public static String[] image;       // name of gif

    // TODO: read the planet file, new the parallel arrays, and load
    // their values from the file.
    public static void loadPlanets(String planetFileName) {
        java.util.Scanner input = new java.util.Scanner(System.in);

            int N = input.nextInt();
            double R = input.nextDouble();
            double[] rx = new double[N];
            double[] ry = new double[N];
            double[] vx = new double[N];
            double[] vy = new double[N];
            double[] mass = new double[N];
            String[] image= new String[N];

            for (int i = 0; i < N; i++) {

                    rx[i] = input.nextDouble();
                    ry[i] = input.nextDouble();
                    vx[i] = input.nextDouble();
                    vy[i] = input.nextDouble();
                    mass[i] = input.nextDouble();
                    image[i] = "./images/" + input.next();
                }

        }

    public static void runSimulation() {

        // run numerical simulation from 0 to T
        for (double t = 0.0; t < T; t += dt) {

            // the x- and y-components of force
            double[] fx = new double[N];
            double[] fy = new double[N];

            // calculate forces on each object
            for (int i = 0; i < N; i++) {

                // reset forces to zero
                fx[i] = 0.0;
                fy[i] = 0.0;

                for (int j = 0; j < N; j++) {
                    if (i != j) {
                        double dx = rx[j] - rx[i];
                        double dy = ry[j] - ry[i];
                        double dist = Math.sqrt(dx*dx + dy*dy);
                        double Fnet = G*mass*mass/(dist*dist);

                        fx[i] += Fnet * dx / dist;
                        fy[i] += Fnet * dy / dist;
                    }
                }
            }

            //calculate acceleration, velocities and positions
            double ax = 0.0;
            double ay = 0.0;
            for (int i = 0; i < N; i++) {
                ax = fx[i] / mass[i];
                ay = fy[i] / mass[i];

                vx[i] += dt * ax;
                vy[i] += dt * ay;

                rx[i] += dt * vx[i];
                ry[i] += dt * vy[i];

            // draw background and then planets
            StdDraw.picture(0, 0, BACKGROUND);
            StdDraw.picture(rx[i], ry[i], image[i]);

            //loop to plot the N bodies

            // pause for a short while, using "animation mode"
            StdDraw.show(DELAY);
            }
        }

    }

    public static void main(String[] args) {

        // TODO: read T and dt from command line.
        T = 0;

        // load planets from file specified in the command line
        String planetFileName = "planets.txt";
        loadPlanets(planetFileName);

        // rescale coordinates that we can use natural x- and y-coordinates
        StdDraw.setXscale(-R, +R);
        StdDraw.setYscale(-R, +R);

        StdAudio.play( MUSIC );

        // turn on animation mode
        StdDraw.show(0);

        // Run simulation
        runSimulation();

        // print final state of universe to standard output
        System.out.printf("%d\n", N);
        System.out.printf("%.2e\n", R);
        for (int i = 0; i < N; i++) {
            System.out.printf("%11.4e %11.4e %11.4e %11.4e %11.4e %12s\n",
                          rx[i], ry[i], vx[i], vy[i], mass[i], image[i]);
        }

    }
}

A: You actually tried to do this:
double *  double[] * double[] / (double * double)
which obviously (I hope it is obvious) will not work.


text:
Q: connect to mysql database using php on different port my connection string is:
    $connection = mysql_connect("localhost", "root", "") or die("Could Not Connect to DB: ".mysql_error());

but on my computer i have installed IIS server first so localhost:80 is reserved by it so I changed my port to 8080 changing httpd.conf file in apache folder.
Now what should I change in connection string to connect to my database.
I am using XAMPP .
should I tried writing these:
1:
  $connection = mysql_connect("localhost:8080", "root", "") or  die("Could Not Connect to DB: ".mysql_error());

2:
$connection = mysql_connect("localhost,8080", "root", "") or    die("Could Not Connect to DB: ".mysql_error());

But Not working Help please.
Thank You

A: Default port number which Mysql server uses is 3306
Web servers default port is 80
Web server and Mysql server are independent.
Do not change your api to connect to your mysql


text:
Q: Button not disabled on page load in Xamarin.Forms I have a button in my page. I want to disable this button on page load, but its not disabled.
XAML:
 <Button IsEnabled="{Binding IsEnabledSaveBtn,Mode=TwoWay}" Text="Save" Command="{Binding SaveItem}" />

ViewModel:
bool _isEnabledSaveBtn = false;
        public bool IsEnabledSaveBtn
        {
            get { return _isEnabledSaveBtn; }
            set
            {
                _isEnabledSaveBtn = value;
                OnPropertyChanged();
            }
        }

Inside ViewModel Constructor:
public CreateDiscountViewModel(INavigation navigation)
        {
            Navigation = navigation;
            IsEnabledSaveBtn=False;
        }

I'm also validating data on TextChange event and it's working fine. But I want to disable this button on page load.
How can I solve this?

A: You need the following changes:
In your XAML you do not need two-way binding :
<Button IsEnabled="{Binding IsEnabledSaveBtn}" Text="Save" Command="{Binding SaveItem}" />

Your Property should look something like this:
    private bool _isEnabledSaveBtn;
    public bool IsEnabledSaveBtn
    {
        get { return _isEnabledSaveBtn; }
        set
        {
            _isEnabledSaveBtn = value;
            OnPropertyChanged(nameof(IsEnabledSaveBtn));
        }
    }

And in your ViewModel constructor set the value:
public CreateDiscountViewModel(INavigation navigation)
    {
        Navigation = navigation;
        IsEnabledSaveBtn = false;
    }

A: Something seems to be wrong with your OnPropertyChanged event.
Try the following, it will work.
is Button Enabled:
bool _isEnabledSaveBtn = false;
    public bool IsEnabledSaveBtn
    {
        get { return _isEnabledSaveBtn; }
        set
        {
            _isEnabledSaveBtn = value;
            OnPropertyChanged("IsEnabledSaveBtn");
        }
    }

OnPropertyChanged
 public event PropertyChangedEventHandler PropertyChanged;
            protected void OnPropertyChanged(string propertyName)
            {
                var handler = PropertyChanged;
                if (handler != null)
                    handler(this, new PropertyChangedEventArgs(propertyName));
            }

and in your contructor
IsEnabledSaveBtn = false;