text:
Q: Why does my code not return anything? It is suppose that to an entry such as:

1 1 524 5 true -1

where the first parameter is the idOrder, the second parameter is the number of products in idOrder, the third parameter is a code, the fourth parameter is the amount of products, the fifth parameter is a boolean to distinguish the product and the sixth parameter is the final mark.
It should return an output such as:

524 -1 5

where the first parameter is the code of the product, the second parameter is the final mark and the third parameter is the amount of products.
This is my code:
#include <stdio.h>

typedef enum {false, true} bool;

int main()
{
    const int END = -1;

    int idOrder, numProducts, idCodeProduct, amount, total, temp;
    bool generic, endSeq;

    scanf("%d", temp);
    /*printf("%d ", temp);*/
    idOrder = temp;
    endSeq = temp == END;

    if (endSeq != true) {
        total = 0;
        scanf("%d", &temp);
        numProducts = temp;
        scanf("%d", &temp);
        idCodeProduct = temp;
        scanf("%d", &temp);
        amount = temp;
        scanf("%d", &temp);
        generic = temp;

        if (generic == true) {
            total = total + amount;
            printf("%d", idCodeProduct);
        }
    }
    printf("%d ", END);
    printf("%d ", total);
    return 0;
}

When I run this code, it doesn't return anything at all and I don't know why.

A: The problem is that you have a trailing whitespace in the format codes to scanf. While this causes scanf to read and discard whitespace, it also causes scanf to read until it finds a non-whitespace. If there's nothing more to read, then scanf will wait indefinitely for more input.
Drop the trailing space in the format and it should work better. As long as you are scanning for normal strings or numbers you have to remember that scanf actually skips leading whitespace automatically.
I recommend you read e.g. this scanf reference.

A: 1) Remove trailing space in formats as suggested by @Joachim Pileborg.
2) Change temp to &temp as suggested by @Anonymous
3) Do not try to read "true" as an int as comment ed by @BLUEPIXY.  Read as string and convert.
4) No need for temp @Joachim Pileborg
5) Always check scanf() results.
6) Initialize total
7) Avoid your own typedef enum {false, true} bool;, use stdbool.h
8) Simplify
int main() {

  const int END = -1;
  char tf[6];
  int idOrder, numProducts, idCodeProduct, amount;
  int total = 0;
  bool generic, endSeq;

  for (;;) {
    if (scanf("%d", &idOrder) != 1)
      Handle_BadInput();
    endSeq = idOrder == END;
    if (endSeq)
      break;
    if (scanf("%d%d%d%5s", &numProducts, &idCodeProduct, &amount, tf) != 4)
      Handle_BadInput();
    if (strcmp(tf, "true") == 0)
      generic = true;
    else if (strcmp(tf, "false") == 0)
      generic = false;
    else
      Handle_BadInput();
    if (generic) {
      total = total + amount;
      printf("%d ", idCodeProduct);  // add space
    }
  }
  printf("%d ", END);
  printf("%d ", total);
  return 0;

}

A: scanf takes a pointer. scanf("%d", &temp);


text:
Q: Where will the data go after delete from memory? Where does the PERMANENTLY DELETED DATA go from memory? And where will the data go after clicking shift+delete keys.

A: You have to understand the concept of File System first. When you press shift+delete, OS calls File System routine to delete file from entry table. File System could either chose to just remove the entry (mark file as deleted) or zero out data of the file and then remove permanently from entry table.
In case of shift+delete, File System assure you to delete file permanently i.e. zero out data and remove entry from the directory table. In that case it is not recoverable. Although some hardware hacks are possible to recover data, by analyzing magnetic fingerprints of hard disk.
If you delete file simply by pressing delete key; It actually just mark file as deleted in file system entry, thus file system could use It's data sector and overwrite with other content. In this case file is recoverable but not guaranteed to be 100%, File System could have corrupted it by overwriting It's data sector.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is this Space Homotopy Equivalent to $S^2$ Let $X$ be the space $S^1$ with two $2$-cells attached via maps of relatively prime degrees. This space is simply connected and has the homology of $S^2$, but is it homotopy equivalent to $S^2$?

A: By Hurewicz theorem, $\pi_2(X) \cong \Bbb Z$. Let $f : S^2 \to X$ be a generator of $\pi_2(X)$. This map is of degree one by the same theorem and hence induces isomorphisms on all homology groups. Since $X$ is a CW complex and both $X$ and $S^2$ are simply connected, it follows that $f$ is a homotopy equivalence by the homology version of Whitehead's theorem. For a statement and proof of this theorem, see corollary 4.33 in Hatcher's Algebraic Topology.

A: Take one of the 2-cells in $X$ and call it $A$. Then $(X,A)$ is a CW-pair, hence it has the homotopy extension property. Since $A$ is contractible, it then follows that the quotient map $\pi: X \rightarrow X/A$ is a homotopy equivalence. But $X/A$ is homeomorphic to $S^2$.

A: There is a solution here http://www.math.ku.dk/~moller/blok1_05/AT-ex.pdf?q=allen-hatcher page 25
Briefly, it can be stated like this:
$Y^0={e_0}$, $Y^1=S^1$, $Y^2=Y$, where we denote the $1$-cell: $e_1$ and the $2$-cells $e_a$ and $e_b$. where $a,b$ are relatively primes
$\pi_1(S^1\cup e_a, e_0)=\{e_1|(e_1)^a\}$. The attaching map $f_a:S^1\rightarrow S^1\subset S^1\cup e_a$ is an element in $\pi_1(S^1\cup e_a, e_0)$ and $[f_a]=e_1^a=e_1$. Thus, the attachment map is homotopic to the degree one attachment map $id:S^1\rightarrow S^1\subset S^1\cup_{id} e_a$. Let $0:S^1\rightarrow S^1$, $0(S^1)=e^0$ be the constant map. We have the following homotopies: $Y=S^1\cup_{f_a}e_a\cup_{f_b}e_b\sim S^1\cup_{f_a}e_a\cup_{id}e_b=S^1\cup_{id}e_b\cup_{f_a}e_a=D_2\cup_{f_a}e_a  \sim D^2\cup_0 e_a=D^2\vee S^2\sim S^2.$ The homotopies rely on 0.18 from Hatcher's book.


text:
Q: Partial linking of object files with Visual Studio We have a project which has a multistage build system: it's split into modules consisting of multiple source files, and each module is compiled and partially linked into a single object file. Then these object files are linked together into the final program. (This approach is required for non-technical reasons.)
Currently we use gcc and binutils for this, and it's very easy there: ld -r will partially  link multiple object files into one.
Unfortunately, we've now been faced with a platform for which there is no gcc/binutils support, only Visual C support. So I've been reworking the build system to use the native Microsoft tools. Unfortunately I have not yet found a way to do a partial link --- link.exe seems to only support outputting EXE or DLL files.
Does anyone know of a way to do a partial link in Visual Studio?
Note that .LIB libraries are not adequate. Neither is incremental linking. And this is all happening from the command line.


text:
Q: MS Bot Framework : How to write tests for buttons? I have a dialog that presents a list of options as buttons :
  bot.dialog('menu', [
        (session) => {
            builder.Prompts.choice(
                session,
                'Your choices',
                ['A', 'B', 'C', 'Exit'],
                {
                    listStyle: builder.ListStyle.button
            });

        },
        (session, results) => {
            let input = _.get(results, 'response.entity', null) || _.get(session, 'message.text', null);
            switch (input) {
                default:
                    session.endDialog("Please chose from available options.");
                    break;
                case 'A':
                    session.send("You chose A");
                    break;
                case 'B':
                    session.beginDialog("You chose B");
                    break;
                case 'C':
                    session.beginDialog("You chose C");
                    break;
                case 'Exit':
                    session.endDialog("Thanks for using menu!");
                    break;
        }
    }]
    ).triggerAction({
        matches: /^(menu)$/i
    })
}

This works when I either press the button or enter the choice through the text input.
However, when I test the dialog through an automated test, it is not happy with the text input.
Here's the test :
describe('menuDialog', function (done) {
    this.timeout(50000);

    // Test case for menu
    it('should present a list of options', function (done) {
        var step = 0;
        var connector = new builder.ConsoleConnector();
        var bot = universalBot(connector);

        // Register a dialog to test
        menuDialog(bot, builder);

        bot.on('send', function (message) {
            switch (++step) {
                case 1:
                    console.log(`Step : ${step}`);
                    assert(message.text == 'Your Choices');
                    connector.processMessage('A');
                    done()
                    break;
                case 2:
                    console.log("STEP : ", step)
                    assert(message.text == 'You Chose A');
                    done()
                    break;
           }
       });
        connector.processMessage('menu');
    });

});

The test fails and message.text at step 2 is :
Oops something went wrong and we need to start over.

How do I test for the buttons if not through connector.processMessage() ?
Thanks

A: You need to put your bot's dialog code inside the test block, so that the test can access it.
Here is a working version of your test intent:
// BEGIN buttons.test.js

var builder = require('botbuilder');
var assert = require('assert');

describe('menuDialog', function() {
    this.timeout(5000);
    // Test case for menu
    it('should present a list of options', function (done) {
        var step = 0;
        var connector = new builder.ConsoleConnector();
        //var bot = universalBot(connector);
        var bot = new builder.UniversalBot(connector);

        bot.dialog('/', [
            (session) => {
                builder.Prompts.choice(session, 'Your choices', ['A', 'B', 'C', 'Exit'], {listStyle: builder.ListStyle.button});

            },
            (session, results) => {
                console.log('selected option: ' + results.response.entity);

                switch (results.response.entity) {
                    case 'A':
                        session.send("You picked A");
                        break;
                    case 'B':
                        session.beginDialog("You picked B");
                        break;
                    case 'C':
                        session.beginDialog("You picked C");
                        break;
                    case 'Exit':
                        session.endDialog("You picked Exit");
                        break;
                    default:
                        session.endDialog("Please chose from available options.");
                        break;
                }
            }
        ]);

        bot.on('send', function (message) {
            switch (++step) {
                case 1:
                    console.log(`Step: ${step}`);
                    assert(message.text == 'Your choices');
                    connector.processMessage('A');
                    done();
                    break;
                case 2:
                    console.log(`Step: ${step}`);
                    assert(message.text == 'You picked A');
                    done();
                    break;
            }
        });
        connector.processMessage('start');
    });
});

// END buttons.test.js
// to run: mocha buttons.test.js


text:
Q: Como abrir uma nova View após clicar sobre um item de uma tableView Tenho uma lista de itens dentro de uma TableView
Gostaria de quando clicar em um item da lista uma nova ViewController seja aberta contendo as informaçoes referentere ao item selecionado
Não estou conseguindo fazer a view abrir utilizando o metodo abaixo:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    // Muro selecionado

    NSInteger linha= indexPath.row;

    Muro *c =[Muros objectAtIndex:linha];

     //navega para a tela detalhes

    DetalhesMuroViewController *detalhes = [[DetalhesMuroViewController alloc] init];

    detalhes.muro = c;

    [self.navigationController pushViewController:detalhes animated:YES];

o que eu estou fazendo de errado ?
Nesse link estao todos os arquivos do projeto GaleRio.
Tentei usar a segunda opção e ele me retorna o seguinte erro de compilação
No visible @interface for "DetalhesMuroViewController" declares the selector "setItem"
O codigo ficou mais ou menos assim
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard_iPhone" bundle:nil];
DetalhesMuroViewController * detailViewController = [storyboard instantiateViewControllerWithIdentifier:@"Detalhes"];

[detailViewController setItem:[Muros objectAtIndex:indexPath.row]];
[self.navigationController pushViewController:detailViewController animated:YES];
}

A: Você pode fazer de duas maneiras.
A primeira:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {
        [self performSegueWithIdentifier:@"Segue" sender:self];
    }

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if ([segue.identifier isEqualToString: @"Segue"]) {
        DetalheItemViewController * itemInformationViewController = [segue destinationViewController];
        [itemInformationViewController setItem: item];
    }
}

A segunda:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard_iPhone" bundle:nil];
    DetalheItemViewController * detailViewController = [storyboard instantiateViewControllerWithIdentifier:@"Detalhes"];

    [detailViewController setItem:[items objectAtIndex:indexPath.row]];
    [self.navigationController pushViewController:detailViewController animated:YES];
}


text:
Q: AspectJ Around Advice I'm writing my master thesis and the title is "Aspect-oriented software development". I have to do a simple project in AspectJ so I set up Eclipse with AspectJ.
I'm having trouble understanding the AROUND advice. I created 3 files:
1) message_out . java
2) message_test . java
3) simple_aspect . aj
In the simple_aspect file:
1) BEFORE and AFTER advice are working as (I think) expected - so, I "commented" them out.
2) The around advice works only for MESSAGE_ONE() method.
My questions are:
1) Can anyone please explain me (from simple_aspect file) the logic behind naming the parameters in the around advice (WHYTHIS, WHYTHAT)??
2) How to make the aspect accept and change TWO arugments (messages) from MESSAGE_TWO() method.
Thanks :)
message_out.java:
package mypackage;
public class message_out {
    public static void message_one(String message) {
        System.out.println(message);
    }
    public static void message_two(String message1, String message2) {
        System.out.println(message1 + ", " + message2);
    }
}

message_test.java:
package mypackage;
public class message_test {
    public static void main(String[] args) {
        message_out.message_one("AAAAA");
        message_out.message_two("BBBBB", "CCCCCC");
    }
}

simple_aspect.aj:
package mypackage;
public aspect simple_aspect {
    /*pointcut message_before() : call (* message_out.message_one(..));
    before() : message_before() {
        System.out.println("BEFORE");
    }

    pointcut message_after() : call (* message_out.message_one(..));
    after() : message_after() {
        System.out.println("AFTER");
    }*/

    pointcut message_around(String WHYTHIS)
    : call(* message_out.message_one(String)) && args (WHYTHIS);
    void around (String WHYTHAT) : message_around(WHYTHAT) {
        WHYTHAT = "CHANGED";
        proceed (WHYTHAT);
    }
}

A: So, found a book: "Mastering AspectJ" from Gradecki J. and Lasiecki N. Took me a few hours to understand the logic behind the around advice. I still don't get it completely, but I got an idea how it should work.
pointcut firstPointcut (String s, String t) : call (public void helloWorld(String, String)) && args (s, t);

void around (String s, String t) : firstPointcut (s, t) {
    System.out.println("1st passed value: " + s);
    System.out.println("2nd passed value: " + t);
    s = "changed first one";
    t = "changed second one";
    proceed (s, t);
}

The below extract helped me understand a "one argument" and thus apply the logic to "two arguments".
Extract from the book:
1) ARGS designator provides the associated advice code with access to the parameters originally passed to the helloWorldUnique() method.
2) The single parameter type in the method signature - only calls with a single parameter should be considered.
3) ARGS designator has a single parameter. This parameter is directly related to the single parameter passed to the method defined as part of our join point.
4) The pointcut completely defines a single parameter based on a combination of the join point and the args designator.
5) Therefore, if the pointcut is expecting a String called s, there should be a join point defined with a String parameter and an args designator with a variable defined as s.
6) When the pointcut uniqueLog is triggered, its String parameter defined by the s variable is made available to the before() advice body.


text:
Q: Entity Framework 4.1 and OriginalValues/CurrentValues and DbContext I'm currently using DbContext with Ef 4.1, and I'm trying to audit all changes some of my entities. I can capture the original and current values for any Properties of an entity, however I cannot figure out how to capture the association (Foreign Key) OriginalValues of a NavigationProperty. Has anyone figured this out?

A: You must either include foreign keys to your entities so they will be tracked as normal values or you must convert your DbContext to ObjectContext and use more powerful (and more cumbersome) ObjectStateManager where you can get instances of ObjectStateEntry for both entities and relations.
To convert DbContext to ObjectContext use:
var objectContext = ((IObjectContextAdapter)dbContext).ObjectContext;

To get entries use:
var entires = objectContext.ObjectStateManager
                           .GetObjectStateEntries(~EntityState.Unchanged);

Iterate through entries and use their State, CurrentValues and OriginalValues properties to do your logging. Relationship should not be in modified so you should only need to check for deleted and added relationships (instead of updating the old is deleted and new is added). The problem is with deleted once because they will not provide you their values. You can try small workaround by changing their state, get values and changing state back to deleted - if it doesn't work you will not be able to log old values for relations.


text:
Q: SQL Select - Distinct - Random these are fields of my table table1 (position, club, country, flag) and
and I need to show randomly club name without repeating the country,
a use this query
select top 4 position
from table1 where flag = 0
and exists(select distinct country from table1) order by newid()

but turns out to repeat the name of the country,
can you help me?
thank you,
AM

A: If  you want to select distinct country and club , use  DISTINCT key word . Else please provide what is your select clause should contain.

A: I am using SQL Server, and I'm trying to pick at random from different countries 4 clubs, ...
club country                    correct option
benfica Portugal
chelsea england
inter italy
madrid spain
club    country    incorrect option
benfica Portugal
chelsea england
man utd england
madrid spain
tks,
AM


text:
Q: What is the difference between private member and public member in a base class? #pragma pack(push, 4)
class Father
{
 public:
  int b;
  char c;
};
class Child : public Father
{
  char e;

};
#pragma pack(pop)

sizeof(Father)=8
 sizeof(Child)=12
 But if We change class Father like this:
class Father
{
 private:// change from public
  int b;
  char c;
};

sizeof(Child)=8

A: It's an implementation detail of the compiler. In other words, not really your business, unless you really, really need to make your data as small as possible. Beware premature optimization here.
In the end, it probably comes down to peculiarities of the Common C++ ABI, using terms like "POD for the purpose of layout" and "base class padding reuse".
Edit: Or not, because those pragmas suggest you're using Visual Studio. In that case, never forget that the MS ABI is a jungle of wild backwards compatibility hacks.

A: The difference in size you are seeing is a result of the compatibility to C. C only knows about struct where everything is public. So, when you use public members in a C++ struct or class, the ABI is compatible with C, hence it needs to follow the alignment rules of C.
When you declare the members private, the C++ ABI has more freedom to optimize the packing of the members.

A: First, you're using a #pragma, which probably makes your
compiler non-standard; I don't know what impact it might have
here, but it certainly means that the compiler may do wierd
things (including laying out the class in a way that is totally
incompatible with any other interface).
Having said that, I get the same results with or without the
#pragma: with g++, these results mirror yours; with VC++,
I get 12 for the derived class in all cases.  The first thing to
note is that whether private or public, and whether g++ or
VC++, the size of the base class is always 8.  This is due to
alignment considerations: both compilers try to keep int
aligned on a multiple of four, and in order to do this in an
array of Father, the total size of Father must be 8, with
three bytes of padding after the c.  Since Child also
contains (indirectly through inheritance) an int, the same
alignment considerations apply.  At first glance we would expect
Child to have a size of 12: the 8 bytes of Father, plus
1 byte for its data, plus 3 bytes padding for alignment.  This
is the case with VC++.  However, the C++ standard allows
something called "empty base class optimization" (because it was
originally designed to allow empty base classes to not occupy
memory): what it says is that when used as a base class, the
derived class can reuse any padding in the base.  So Child can
put its member e at the address of Father + 5 (since that's
where the padding in Father begins), and thus, only needs
6 bytes (rounded up to 8 for alignment reasons).
Why VC++ doesn't do this optimization, I don't know; perhaps
they were influenced by the name of the optimization.  (They do
do it when the base class has no data members.)  Why g++ would
only do it if there are private members, and not public, is even
stranger, but the standard doesn't require it.
Note that when the optimization is applied, something like:
Father* p1 = new Child;
Father* p2 = new Child;
memcpy( p2, p1, sizeof(Father) );

may have surprizing consequences, size the space actually
occupied by Father may be smaller than what sizeof
indicates.  This may account for the logic behind the choice of
g++: memcpy is not valid if the class has private members, so
they can apply it; it would be valid if all of the members are
public (and a few other conditions), so they don't apply it, in
order to avoid breaking things like the above.  (Adding
a constructor, which also makes memcpy illegal, causes g++ to
apply the optimization.)


text:
Q: Line Graph in Power BI Two-line graph with slicers:  Everything looks fine until date selections are made.
I figure that this failure has something to do with the line graph and date functionality.  Date selections work together in a very weird way.  Selecting only 2019 months and then only 2020 months, both lines disappear.
If the date slicers are going to work together, I should expect inclusive behavior, rather than "NOT 2020 AND NOT 2019"!
See relationships.
How do I get the behavior intended on one two-line graph?
Thanks!

A: I agree with @teylyn, sometimes less is more.
The problem is how Power Bi works and how your measures are calculated. You have two averagex-measures, both pointing to same date table. In Power BI, two separate filters from a single dimension can't do "union", they are laid down on top of each other. You are telling that first I want to filter by 2019 November and after the filter has been evaluated, you tell that you want to filter 2020 January. Power BI adds new filter to already filtered dataset, but the dataset doesn't contain anything that match both filters, so the end result is empty.
One way to get around this problem is to create separate date-tables for filtering purposes for blue and green. Here is an example of the data model needed:

Then you update the date-filters in second tab. Set blue date filter to one date-dimension and green date filter to another. This way they aren't filtering the same table and the graph should work the same as before.


text:
Q: call a function after all fadeOut I want to detect when all my fadeOut are finished
My fadeOut are on random duration, on all item of an container.
after each fadeOut I remove item, to put a new one after all item fadeOut. This new Item are hiden, waiting to fadeIn
function fadeOutItem(){
$('div.wrapper').children('.item-box').each(function(){
    $(this).fadeOut(Math.floor(Math.random() * 1300) + 200, function(){
        $(this)[0].remove();
    });
});
}

A: Basically, you need to know when your wrapper doesn't contain any children anymore. You could do that in the callback function of the fadeOut itself:
function fadeOutItem(){
    $('div.wrapper').children('.item-box').each(function(){
        $(this).fadeOut(Math.floor(Math.random() * 1300) + 200, function(){
            $(this).remove();
            if ($('div.wrapper').children('.item-box').length === 0) {
                // add new item
            }
        });
    });
}

A: You can add a if conditional statement to look for total elements like below
function fadeOutItem(){
$('div.wrapper').children('.item-box').each(function(i){
    $(this).fadeOut(Math.floor(Math.random() * 1300) + 200, function(){
        $(this)[0].remove();
    });
    // Check for the instance and then add it
    if (i === $('div.wrapper').children('.item-box').length) {
                //At the last element add your elements
        }
});
}

A: Try to Use $(this).remove(); instead of $(this)[0].remove(); and Follow The Link For More Details


text:
Q: How to specifically select item from a list with index information and assign them to library I am working on a function to exclude all occurrences in a list and return a tuple/list with index information that will be assigned to a library. For example:
for a list input:
x = [0,0,1,2,3,0,0,]

output:
{"inds":[2,3,4],"vals":[1,2,3]}

My current solution is very ungly:
def function(x):
    b = list()
    c = list()
    d = {'inds': [], 'vals': []}
    a = list(enumerate(x))
    for i in a:
        if i[1]!=0:
            b.append(i[1])
            c.append(i[0])
    d["inds"] = c
    d["vals"] = b
    return d

I am looking forward a concise solution.

A: You're basically there, you have the concept in mind. There's just a few ways to clean up your code.
There's no need to create lists b and c, when you can simply append the new data into the dictionary:
x = [0, 0, 1, 2, 3, 0, 0]
d = {'inds': [], 'vals': []}
for i, j in enumerate(x):
    if j != 0:
        d['inds'].append(i)
        d['vals'].append(j)
print(d)
# Prints: {'vals': [1, 2, 3], 'inds': [2, 3, 4]}

There's also no need to call list() around enumerate(). I'm going to assume you use Python 3 here and that when you do enumerate(), you see something like:
<enumerate object at 0x102c579b0>

This is ok! This is because enumerate returns a special object of its own which is iterable just like a list, so you can simply loop through a. Also, since the list will have two values per item, you can do for i, j like I have.

A: You can do it also like this:
d = dict((i, v) for i, v in enumerate(x) if v)
d = {'inds': d.keys(), 'vals': d.values()}

EDIT:
If order matters, then like this (thanks to comments):
import collections
d = collections.OrderedDict((i, v) for i, v in enumerate(x) if v)
d = {'inds': d.keys(), 'vals': d.values()}

A: idx, vals = zip(*[[n, v] for n, v in enumerate(x) if v])
d = {"inds": idx, "vals": vals}
>>> d
{'inds': [2, 3, 4], 'vals': [1, 2, 3]}

A: Your solution is ok, but you have some superfluous lines.
def function(x):
    d = {'inds': [], 'vals': []}
    for index, value in enumerate(x):
        if value != 0:
            d['inds'].append(index)
            d['vals'].append(value)
    return d

If performance is an issue for very long arrays you could also use numpy:
def function(x):
    x_arr = np.array(x)
    mask = x_arr != 0
    indices = np.argwhere(mask)[:,0]
    values = x_arr[mask]
    return {'inds': list(indices), 'vals': list(values)}

A: It can be done by this ugly functional one-liner:
{'inds': list(filter(lambda x: x>0, map(lambda (i,x): i if x>0 else 0 , enumerate(x)))), 'vals': list(filter(lambda x: x!=0, x))}

output:
{'inds': [2, 3, 4], 'vals': [1, 2, 3]}

this gives you inds:
list(filter(lambda x: x>0, map(lambda (i,x): i if x>0 else 0 , enumerate(x))))

this gives you values:
list(filter(lambda x: x!=0, x))


text:
Q: I wanted to connect android studio to mysql I wanted to insert data in mysql and also to retrieve, modify and delete rows in it. I don't have any programming knowledge, just a little database manipulation. This android studio is a whole new thing for me and its like i'm having problems from the tutorials regarding on connecting android studio to  mysql. I tried to use the ip add of my computer, the 10.0.2.2 , the 127.0.0.1 and even registering for a free web hosting but it still doesn't insert data.
Another thing the dialog box that should display the status of registration doesn't work.
One last thing I know that the mistake is in this code because when i looked on their tutorial it worked but i can't figure it out why it doesn't work on me.
I really appreciate any help you can provide.
here's the php file
conn.php
<?php
$db_name = "dbapp";
$mysql_username="root";
$mysql_password="";
$server_name="localhost";
$con = mysqli_connect($server_name,$mysql_username,$mysql_password,$db_name);
?>

register.php
<?php
require "conn.php";
$f_name=$_POST["first_name"];
$m_name=$_POST["middle_name"];
$l_name=$_POST["last_name"];
$email_add=$_POST["emailadd"];
$user_name=$_POST["username"];
$user_pass=$_POST["userpass"];

$sql_query = "insert into tbluser (f_name, m_name, l_name, user_emadd, user_name, user_pass) values('$fname','$mname','$lname','email_add','$user_name','user_pass')";
?>

here's some of the android studio files
Register.java
package com.example.*****.myapplication;
// Above code is not really asterisk, i just wanna hide it..
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

public class Register extends Activity{

    EditText ET_FNAME,ET_MNAME,ET_LNAME,ET_EMAIL,ET_USERNAME,ET_PASS;
    String txtfname, txtmname, txtlname, txtusername, txtemail, txtpass;

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.register);

    ET_FNAME = (EditText)findViewById(R.id.et_fname);
    ET_MNAME = (EditText)findViewById(R.id.et_mname);
    ET_LNAME = (EditText)findViewById(R.id.et_lname);
    ET_EMAIL = (EditText)findViewById(R.id.et_email);
    ET_USERNAME = (EditText)findViewById(R.id.et_username);
    ET_PASS = (EditText)findViewById(R.id.etpassword);

}

public void userReg(View view){

    txtfname = ET_FNAME.getText().toString();
    txtmname = ET_MNAME.getText().toString();
    txtlname = ET_LNAME.getText().toString();
    txtemail = ET_EMAIL.getText().toString();
    txtusername = ET_USERNAME.getText().toString();
    txtpass = ET_PASS.getText().toString();

    String method = "register";
    BackgroundWorker backgroundWorker = new BackgroundWorker(this);
    backgroundWorker.execute(method,txtfname,txtmname, txtlname, txtemail, txtusername,txtpass);
    finish();

}
}

here's another java class
BackgroundWorker.java
package com.example.*****.myapplication;

import android.app.AlertDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

public class BackgroundWorker extends AsyncTask<String,Void,String> {
AlertDialog alertDialog;
Context ctx;

BackgroundWorker(Context ctx) {
    this.ctx = ctx;
}

@Override
protected void onPreExecute() {
    super.onPreExecute();
}

@Override
protected String doInBackground(String... params) {
    String reg_url = "http://10.0.2.2/myapp/register.php";
    String login_url = "http://10.0.2.2/myapp/login.php";

    String method = params[0];
    if (method.equals("register")) {
        String fname = params[1];
        String mname = params[2];
        String lname = params[3];
        String emailadd = params[4];
        String username = params[5];
        String userpass = params[6];

              try {
                   URL url = new URL(reg_url);
                   HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                   httpURLConnection.setRequestMethod("POST");
                   httpURLConnection.setDoOutput(true);
                   OutputStream OS = httpURLConnection.getOutputStream();
                   BufferedWriter bufferedwriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
                   String data = URLEncoder.encode("f_name", "UTF-8") + "=" + URLEncoder.encode(fname, "UTF-8") + "&" +
                   URLEncoder.encode("m_name", "UTF-8") + "=" + URLEncoder.encode(mname, "UTF-8") + "&" +
                   URLEncoder.encode("l_name", "UTF-8") + "=" + URLEncoder.encode(lname, "UTF-8") + "&" +
                   URLEncoder.encode("email_add", "UTF-8") + "=" + URLEncoder.encode(emailadd, "UTF-8") + "&" +
                   URLEncoder.encode("user_name", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8") + "&" +
                   URLEncoder.encode("user_pass", "UTF-8") + "=" + URLEncoder.encode(userpass, "UTF-8");

                  bufferedwriter.write(data);
                   bufferedwriter.flush();
                   bufferedwriter.close();
                    OS.close();
                   InputStream IS = httpURLConnection.getInputStream();
                   IS.close();

                  httpURLConnection.disconnect();
                    return "Registration Success";

} catch (MalformedURLException e)
                          {
                            e.printStackTrace();
                          } catch (IOException e)
                          {
                            e.printStackTrace();
                          }

    }

        return null;
    }

    @Override
    protected void onProgressUpdate (Void...values){
        super.onProgressUpdate(values);
    }

@Override
protected void onPostExecute(String result) {

    if(result.equals("Registration Success"))
    {
    Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
    }
    else
    {
    alertDialog.setMessage(result);
    alertDialog.show();
     }
    }
}

here are the column name in mysql, it has userid as primary key and autocrement.
 fname
 mname
 lname
 email_add
 user_name
 user_pass


text:
Q: Error on line 1, column 1 of pubspec.lock: Unexpected character I tried to run flutter pub get and I got this error:
Error on line 1, column 1 of pubspec.lock: Unexpected character
╷

1 │
│ ^

  ╵
pub upgrade failed (65;   ╵)

A: Delete the file at flutter/packages/flutter_tools/pubspec.lock then try flutter pub upgrade again.
You may have interrupted the upgrade process before it finished hence the file became invalid.

A: The file pubspec.lock is a generated file, so you can delete it and then regenerate it.
Delete pubspec.lock.
Run the following command:
flutter pub get

or
flutter pub upgrade

Notes on pub upgrade (you could probably skip the delete step).

A: I took the same error,
but this error was coming from my main folder.
in this path "C:\Users"yourusername"\AppData\Local\Pub\Cache\global_packages\devtools"
I deleted the file and I started app. file has been by itself created and problem solved.

A: I got the same error while working.
I deleted pubspec.lock file.
then I ran command
flutter pub get
It created new pubspec.lock file.
Now application runs without any errors.


text:
Q: Order statistic of i.i.d exponential($\lambda$) random variables, $X_{(n, k_n)}$ convergence in probability Suppose that $X_1,X_2$,....are iid from exponential($\lambda$).For n $\geq$ 1, let $X_{(n,1)}\le X_{(n,2)}\le X_{(n,3)}\le.......\le X_{(n,n)}$ be the order statistics of $X_1,X_2....X_n$. Suppose that $k_n$ is a sequence of integers satisfying $1\le k_n \le n$ for all n, and
              ${\lim_{x\to \infty}\frac{k_n}{n}} = p\in(0,1)$
Show that as n$\to\infty$
$\qquad\qquad\qquad\qquad\mathit{{X_{(n, k_n)}\to-\frac{1}{\lambda}\log(1-p)}}$
 I am thankful for any help.

A: Fix $\epsilon > 0$.
Let $Y_1 \sim \text{Binom}(n, (1-p) e^{\lambda \epsilon})$
and $Y_2 \sim \text{Binom}(n, (1-p) e^{-\lambda \epsilon})$.
\begin{align}
P(|X_{n,k_n} + \log(1-p)/\lambda| > \epsilon)
&\le P(X_{n,k_n} < - \log(1-p)/\lambda - \epsilon)
+ P(X_{n,k_n} > - \log(1-p)/\lambda + \epsilon)
\\
&= P(\text{less than $n-k_n$ of the $X_i$ are $\ge - \log(1-p)/\lambda - \epsilon$})
+ P(\text{more than $n-k_n$ of the $X_i$ are $\ge - \log(1-p)/\lambda + \epsilon$})
\\
&= P(Y_1 < n-k_n) + P(Y_2 > n-k_n)
\\
&= P(Y_1/n < 1 - k_n/n) + P(Y_2/n > 1 - k_n/n).
\end{align}
By the law of large numbers, $Y_1/n \to (1-p) e^{\lambda \epsilon} > 1 - p$ in probability, so the first term will tend to zero. Similarly, the second term will tend to zero.


text:
Q: How to create SSDT project from existing database? I have an existing SQL database and I need to add an SSDT project to the project I am working on.
What would the correct way to add the tables and stored procs from the existing database to an SSDT project?

A: Use Schema Compare with your existing database to populate your SSDT project.  I think you will find that it is really rather simple.
Schema Compare uses two connections (connection strings) to compare two different databases, or in your case one connection string to connect to the existing database (source) and then you choose your database project project as the other (target).

A: I think this covers all the options:
https://the.agilesql.club/Blogs/Ed-Elliott/HOWTO-Get-An-Existing-Schema-Into-SSDT
Good luck, common issues when you start are references and code that doesn't actually run (procs reference dropped table etc) - for references if you use anything in msdn or master or any sys.* objects add a reference to the dacpacs for non working code, check a baseline into source control and then delete it :)
Ed


text:
Q: Using Ionic 4 on iPhone X Let's start out with the Ionic Info:
Ionic:

   ionic (Ionic CLI)             : 4.12.0 (C:\Users\Rohan\AppData\Roaming\npm\node_modules\ionic)
   Ionic Framework               : @ionic/angular 4.1.2
   @angular-devkit/build-angular : 0.13.7
   @angular-devkit/schematics    : 7.2.4
   @angular/cli                  : 7.2.4
   @ionic/angular-toolkit        : 1.4.0

Cordova:

   cordova (Cordova CLI) : 8.1.2 (cordova-lib@8.1.1)
   Cordova Platforms     : android 7.1.4
   Cordova Plugins       : cordova-plugin-ionic-keyboard 2.1.3, cordova-plugin-ionic-webview 3.1.2, (and 6 other plugins)

System:

   NodeJS : v10.13.0 (C:\Program Files\nodejs\node.exe)
   npm    : 6.4.1
   OS     : Windows 10

So I have a weird issue with Ionic 4 when testing out on iPhone X using the Devapp (since I'm on windows for now)
On a specific page, Theres a div that loads on top of the page right in the center, at first, this hit the notch area for iPhone X. Now i temporarily solved this issue by making the following function:
  checkModernAppleVariants() {
    let iOS = /iPad|iPhone|iPod/.test(navigator.userAgent);

    let ratio = window.devicePixelRatio || 1;
    let screen = {
      width: window.screen.width * ratio,
      height: window.screen.height * ratio
    };

    if (iOS && screen.width == 1125 && screen.height === 2436) {
      this.iPhoneXDetected = true;
      console.log('iPhone X detected');
      document.getElementById('notch').style.height="2.5em";
    } else {
      this.iPhoneXDetected = false;
      console.log('iPhone X not detected')
    }
  }

So what I did was basically put a div at the top with the id of 'notch', and whenever the function sees that it's an iPhone X, it gives the div a height of 2.5em, which moves everything under that 2.5em height, thereby moving it out of the way of the notch.
Here's the thing though, there has to be a "non-hacky" way of doing this. Keep in mind this is a page with no ion-header or toolbar of any sort. Just a bunch of divs (this can't be changed).
Is there a better method of detecting iPhone X/XS/XS Max (or whatever else) and automatically moving stuff out of the way of the notch area?

A: Try adding this in your global css:
body{
  margin-top: constant(safe-area-inset-top);
  margin-top: env(safe-area-inset-top);
}

A: Using margin-top rather than padding-top worked for me!
body {
    margin-top: constant(safe-area-inset-top);
    margin-top: env(safe-area-inset-top);
}


text:
Q: Trouble with UpSet(Delayed) and IgnoringInactive I'm having problems setting an upvalue for a symbol that is supposed to ignore Inactive:
IgnoringInactive[f[g[x]]] ^:= match;

Then for some reason, this fails to match:
f[Inactive[g][x]]

I also tried TagSet, as in g /: IgnoringInactive[f[g[x]]] := match but that didn't work either.
What is the intended way to assign a rule to g while ignoring possible Inactive wrapper around g?


text:
Q: How to map function symbol to address range What is the proper way to determine the address range for a function symbol (string)?
I'll be working with statically-linked, non-stripped C programs on Linux.
For example, I'd like to do something like this:
char* func_name = get_string_from_user();
printf("start address: %p \n", get_addr_range(func_name).start);
printf("end address: %p \n", get_addr_range(func_name).end);

Where the start address should be the actual address of the function as layed out currently in memory.
I think gdb and objdump perform similar actions, so it should be possible, right?
Thanks.

A: You could look at the BFD library provided with binutils (with objdump and and the rest). I have used it once briefly and it's not exactly trivial as far as I remember.
There are some usage examples out there (search for "using libbfd" or something like that).
I'd recommend reading the binutils utilities source code also.
There is also elfutils which comes with ELF and DWARF routines. Haven't used that one though and documentation looks sparse.

A: It is not generally possible to get the entire range of a function.
At best, you can get the starting address.  Here is an example, it is NOT portable:
#include <stdio.h>
int main(int argc, char *argv[])
{
    printf("fputs = %p\n", (void *)fputs);
    return 0;
}

The reason why this is not possible is because in general, the only information the linker uses about each object, whether function or data, is its address and its name (and a few bits of other data).  The linker just doesn't care about how big something is.
Now, you can find out how big a function is by examining the debugging data, if the debugging data is present for the given function.  There are libraries you can use to parse the data, as it can be somewhat complicated.  Here's a link to some information about DWARF, if that's the format you're using:

*

*http://wiki.dwarfstd.org/index.php?title=DWARF_FAQ

*http://reality.sgiweb.org/davea/dwarf.html
Note that you can put the debugging data in whatever format you like when you compile the program, or leave it out entirely.  STABS and DWARF are common on Linux.  However, just because the executable or library isn't stripped doesn't mean that the debugging data is there.

A: It' possible to get the start address, but difficult to get the end address, for a function.  GTK does something similar to what you ask with dynamic Glade bindings.
To do this yourself, you compile your application as a dynamically-loaded image (like a shared library) using libtool, and set the image to have exported names using the libtool -export-dynamic option.
For more information see this link to Libtool documentation.
The link command to use is:
libtool gcc -export-dynamic -o program main.o
Once you have compiled with the -export-dynamic switch required, you may call dlopen() to dynamically open your executable image as a dynamic library, and dlsym() to obtain the address of specific symbols.


text:
Q: What are the black egg-like lumps with green bubbles in LEGO Jurassic World? As I roam the hub islands I've come across these black egg-like structures with green bubbles/glow coming from them - none of the characters I've unlocked yet seem to be able to interact with them, and I can't read the contents of the hexagon that appears when I'm near them.
What are they and how do I interact with them?

A: According to the Prima Guide, there is a dinosaur ability called "Goo Spit" with the following description:

Dilophosauruses can spit venom goo at black LEGO objects to destroy them.


text:
Q: There can be degeneracy in 1D energy eigenfunctions even if one of them and its derivative does to zero as $x\to\infty$? In 1D, the energy eigenvalue equation for an energy value $E$
$$
-\frac{\hbar^2}{2m}\psi''(x) + V(x)\psi(x) = E\psi(x)
$$
can have at most two linearly independent solutions, $\psi_1$ and $\psi_2$, with their Wronskian, $\psi_1'\psi_2 - \psi_1\psi_2'$ being a constant. Then it is said that

if $\psi_1$ is such that it and its first derivative go to zero as $x\to -\infty$ or $x\to\infty$, then this Wronskian is uniformly zero.

It is then used to show that $\psi_1$ and $\psi_2$ are linearly dependent.
However, consider the functions $f(x):=x^2$ and $g(x) := 1/x$. Clearly they are linearly independent, with their Wronskian being the nonzero constant $3$, while $g$ anf $g'$ both go to zero as $x\to\infty$. Of course these functions are not appropriate candidates for the eigenfunctions, but what's the guarantee that even the eigenfunctions obeying the imposed BC's can't show such behavious?
So clearly, there have to be additional hypotheses in the quoted statement to conclude the constant Wronskian being zero. What are they?

A: A possible additional condition is that $\psi_2$ and $\psi_2'$ are bounded. Then
$$\lim_{x\to\infty}\psi_1' \psi_2=\lim_{x\to\infty}\psi_1 \psi_2'=0$$
and since the Wronskian is a constant, this constant must be identically $0$. But if $\psi_2$ or $\psi_2'$ are unbounded, then it might be that $\lim_{x\to\infty} \psi_1'\psi_2\ne0$ and similarly for the second term, and then the result doesn't necessarily hold, as your counterexample shows.
I think this is just a sufficient condition, and one could perhaps come up with an example where $\psi_2$ and $\psi_2'$ are both unbounded and the two limits happen to match, or the difference happens to converge to $0$, but since in QM boundedness is usually a requirement, this should be enough to clarify your doubt.


text:
Q: Output distinct values in SQL column with PHP I have a table with two collumns (shortened), NAME and CATEGORY.
I want to output the number of distinct categorys. For an examle: Sport : 5 , Houses : 10.
I use this one:
$test = mysqli_query($con,"SELECT category, COUNT(category) as count FROM tablename GROUP BY category ORDER BY count DESC");

This work then I run the code in SQL Shell, but I have no clue on how to output it in PHP. I have searced Google up and down without any successfull solution.
Any help?
I want to output it in a table format.
EDIT: Here is my full code: (tablename is changed, and $con is removed)
$test = mysqli_query($con,"SELECT DISTINCT lkategori, COUNT(lkategori) as count FROM tablename GROUP BY lkategori ORDER BY count DESC");

while($row = mysql_fetch_array($test)) {
    echo $row['lkategori'] . ":" . $row['count'];
    die("test");
}

A: $test = mysqli_query($con,"SELECT DISTINCT lkategori, COUNT(lkategori) as count FROM tablename GROUP BY lkategori ORDER BY count DESC");

echo "
";
    while($row = mysqli_fetch_array($test)) {
        echo "
";
        echo "" . $row['lkategori'] . "	";
        echo "" . $row['count'] . "	";
        echo "
";
    }
echo "
";

This will output all the categories and the count returned by the sql statement into a table. Also as a sidenote you should look into PDO.
EDIT: to make sure you do get the distinct values you should use the DISTINCT keyword in your sql statement:
$test = mysqli_query($con,"SELECT DISTINCT category, COUNT(category) as count FROM tablename GROUP BY category ORDER BY count DESC");

A: use this
while($row = mysqli_fetch_array($test)) {
    echo $row['lkategori'] . ":" . $row['count'];
    die("test");
}
Thanks


text:
Q: When creating a nerd in my nerd_table I get the following error This is my code from create_users_table.php
public function up()
    {
      Schema::table('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
        $table->integer('nerd_level');
       });
    }

QueryException in Connection.php line 647: SQLSTATE[42S22]: Column not
  found: 1054 Unknown column 'nerd_level' in 'field list' (SQL: insert
  into users (name, email, nerd_level, updated_at,
  created_at) values (dasdasd, vincentnelissen@hotmail.nl, 1,
  2017-03-31 15:41:51, 2017-03-31 15:41:51))

And when I try to edit a nerd I get the following error:

ErrorException in 17afaeb4afd6b4276e6af6ff12921ab25d74a9cc.php line
  22: Trying to get property of non-object (View:
  /var/www/vhosts/vincentspage.tk/httpdocs/Laravel/resources/views/nerds/edit.blade.php)

This is my code from edit.blade.php:
     <!DOCTYPE html>

        <title>Look! I'm CRUDding</title>
        <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap
        /3.0.0  /css/bootstrap.min.css">

    Nerd Alert

View All Nerds

Create a Nerd

Edit {{ $nerd->name }}

  {{ HTML::ul($errors->all()) }}

 {{ Form::model($nerd, array('route' => array('nerds.update',
  $nerd->id),   'method' => 'PUT')) }}

    {{ Form::label('name', 'Name') }}
    {{ Form::text('name', null, array('class' => 'form-control')) }}

    {{ Form::label('email', 'Email') }}
    {{ Form::email('email', null, array('class' => 'form-control')) }}

    {{ Form::label('nerd_level', 'Nerd Level') }}
    {{ Form::select('nerd_level', array('0' => 'Select a Level', '1' =>
    'Sees Sunlight', '2' => 'Foosball Fanatic', '3' => 'Basement
    Dweller'), null, array('class' => 'form-control')) }}

{{ Form::submit('Edit the Nerd!', array('class' => 'btn btn-primary')) }}

 {{ Form::close() }}

And when I try to delete a nerd This is the error:

FatalErrorException in NerdController.php line 128: Call to a member
  function delete() on null

return Redirect is php line 128
public function destroy($id)
{
    // delete
    $nerd = User::find($id);
    $nerd->delete();

    // redirect
    Session::flash('message', 'Successfully deleted the nerd!');
    return Redirect::to('nerds');
}

This Error can be profitable to others who have similar problems , so they know what to change in their code as well. Or not to make a similar mistake to whoever reads it first.
Can anyone help me ?
Kind regards,
Vincent

A: instead of Schema::table use Schema::create for creating new tables. you are using Schema::table and application expects that you are trying to modify an existing table.
so it would be something like this for create_users_table
public function up()
    {
      Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
        $table->integer('nerd_level');
       });
    }

Additional information

QueryException in Connection.php line 647: SQLSTATE[42S22]: Column not
  found: 1054 Unknown column 'nerd_level' in 'field list' (SQL: insert
  into users (name, email, nerd_level, updated_at,  created_at) values
  (dasdasd, vincentnelissen@hotmail.nl, 1, 2017-03-31 15:41:51,
  2017-03-31 15:41:51))

This error is because that you are trying to save a record to a table which doesn't have nerd_level field on it. so if you have created a migration and ran it first and later when you add the field it wont work. so you need to either rollback migration before bringing any changes to the file or should create a new migration for just adding nerd_level field to the existing table.
1st method

*

*to rollback the migrations run following command until the create_users_table is rolled back or declare the step. see docs
Rolling Back Migrations
php artisan migrate:rollback

*bring the required changes add following line.
$table->integer('nerd_level');

*run migration again
php artisan migrate
2nd method (preferred way). See docs Modifying Columns

*

*leave existing create_users_table as it is without $table->integer('nerd_level');

*create a new seperate migration to just add the new column.

ErrorException in 17afaeb4afd6b4276e6af6ff12921ab25d74a9cc.php line
  22: Trying to get property of non-object (View:
  /var/www/vhosts/vincentspage.tk/httpdocs/Laravel/resources/views/nerds/edit.blade.php)

this error is because as the error describes you are trying to access a property of null object, it means that you need to first have that user(model) exist on table to be able to access its properties.


text:
Q: How do i remove a friend from the database in a self join table? The below is my models.
class User(models.Model):
    name = models.CharField(max_length = 255)
    alias = models.CharField(max_length = 255)
    email = models.CharField(max_length = 255)
    password = models.CharField(max_length = 255)
    confirm_password = models.CharField(max_length = 255)
    birthday = models.DateTimeField(null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    friend = models.ManyToManyField('self')
    objects = UserManager()

The following works to add a friend.
def add_friend(request, friend_id):
    new_friend = User.objects.get(id=friend_id)
    print(new_friend.name)
    current_user = User.objects.get(id=request.session['user_id'])
    print(current_user.name)
    current_user.friend.add(new_friend)
    current_user.save()
    new_friend.friend.add(current_user)
    return redirect('/friends/')

However, i need help removing the friend from a user. The below is what i tried but it does not work. When I check sqllite, the friends are still attached to that user.
def remove_friend(request, friend_id):
    remove_friend = User.objects.get(id=friend_id)
    print(remove_friend.name)
    current_user = User.objects.get(id=request.session['user_id'])
    print(current_user.name)
    current_user.friend.remove(remove_friend)
    current_user.save()
    remove_friend.friend.remove(current_user)
    return redirect('/friends/')


text:
Q: How to programmatically show a UIView in a UIScrollView? I have UIViewA, UIViewB, UIViewC in a UIScrollView.
I want to see UIViewB first. (Note the order has to stay A, B, C)
How do I do that?
thx

A: It's hard to know exactly without more information.  But as a brief overview, let's say you have 10 views in UIScrollView that have the same dimensions as the UIScrollView bounds, so that they're oriented vertically in a row in the scroll view.  The easiest way to show the 3rd view is to set the content offset of the scrollview to the origin of the 3rd view:
One of two ways to do this.  First is to just take the 'index' of the view and multiply it by the bounds height of the scrollview (this is useful if you have your views in an Array):
NSUInteger viewIndex = [someArray indexOfObject:viewToShow];
scrollView.contentOffset = CGPointMake(0.0f, scrollView.bounds.size.height * viewIndex);

The other way would be to just set the offset to the actual frame origin of the view (this can be useful if the views aren't the same size as the scroll view bounds):
scrollView.contentOffset = viewToShow.frame.origin;

Both should work fine.


text:
Q: NFS export configuration for multiple LVM logical volumes I have setup a file server that contains two large file systems, each consisting of a single LVM logical volume (10TB and 16TB) within a single volume group.  The physical volumes making up the LV are SAN LUNs connected via iSCSI/multipath.
Now, I would like to serve these to LV via NFS to a nodes in a compute cluster.
So far, I have the following config.
On server two LV are in:
/mnt/LV1
/mnt/LV2

NFS /etc/exports looks similar to
/mnt/LV1   *(rw...)
/mnt/LV2   *(rw...)

On my client I then mount each of these separately.
My question is, can I just put this in /etc/exports instead?
/mnt *(rw)

And mount in client as single point containing these two logical volumes?
Naively, this seems odd as they are separate logical volumes, but this may be proper practice also!

A: By default, exported file systems do not include the contents of directories mounted from different file systems. That is, NFS exports do not cross file system boundaries. So, in your example, if you mount /mnt, you'd see two empty directories only (LV1 & LV2).
The reason is that NFS clients would be seeing multiple files with identical inode numbers within a single file system, which may lead to confusion for some NFS clients. Or to avoid this problem, the NFS server would have to maintain a non-identity inode number mapping.
According to the exports(5) man page, you may use the nohide option to switch this feature off, and then you may hope that no software on the client gets confused when multiple files happen to have the same inode number within a single file system.

General Options
exportfs understands the following export options:
nohide
This option is based on the option of the same name provided in IRIX
  NFS. Normally, if a server exports two filesystems one of which is
  mounted on the other, then the client will have to mount both
  filesystems explicitly to get access to them. If it just mounts the
  parent, it will see an empty directory at the place where the other
  filesystem is mounted. That filesystem is "hidden".  Setting the
  nohide option on a filesystem causes it not to be hidden, and an
  appropriately authorised client will be able to move from the parent
  to that filesystem without noticing the change.
However, some NFS clients do not cope well with this situation as, for
  instance, it is then possible for two files in the one apparent
  filesystem to have the same inode number.
The nohide option is currently only effective on single host exports.
  It does not work reliably with netgroup, subnet, or wildcard exports.
This option can be very useful in some situations, but it should be
  used with due care, and only after confirming that the client system
  copes with the situation effectively.
The option can be explicitly disabled with hide.


text:
Q: Is it normal to get several badges at the same time and rep in multiples? I was looking around a bit and stumbled on something I found really strange...
First thing that prompted my curiosity was seeing a certain user who obtained the badge "Enlightened" several times in a row within a short time span of 1 minute:

Looking around some other badges ("Nice Answer", "Good Answer", "Great Answer"), there seemed to be some more of the same thing. Well, no more about badges (you can see a bit of them on the activity page under badges), let's move on.
Onto the user's page, all the rep are in multiple of 3:

I mean, don't you just find it strange? Even the downvotes are in multiple of 3 and at exactly the same time. Could it be a bug or is it really that easy to stack up so many badges in a row. If so, I'd like to know the secret ;)
NOTE:

*

*I hope it's okay if I don't blur the username. I don't want to bring the user negative attention, but it just jumped out to me.

*I'm not sure what to tag, so I'm using the discussion tag for now, since I'm not even sure what's happening here.


text:
Q: Deleting a row from javascript object I have a javascript object which looks like this :-
var myObject = [{"id": "1", "URL": "http://shsudhf.com", "value": "1"},

                {"id": "2", "URL": "http://shsusadhf.com", "value": "2"},

                {"id": "3", "URL": "http://shsudsdff.com", "value": "0"}];

Now , I have to delete all the rows in the object with id value 2. How can this be done ?

A: If you don't need the original array after "deleting" rows, you can use splice like this:
http://jsfiddle.net/rmcu5/1/
var myArray = [{"id": "1", "URL": "http://shsudhf.com", "value": "1"},
                {"id": "2", "URL": "http://shsusadhf.com", "value": "2"},
                {"id": "3", "URL": "http://shsudsdff.com", "value": "0"}];

function removeItemsById(arr, id) {
    var i = arr.length;
    if (i) {   // (not 0)
        while (--i) {
            var cur = arr[i];
            if (cur.id == id) {
                arr.splice(i, 1);
            }
        }
    }
}

removeItemsById(myArray, "2");

console.log(JSON.stringify(myArray));

It doesn't create a new array, just modifies the original in place. If you need the original array and all of its items, then use one of the other solutions that return you a modified copy of the original.

A: Note that what you call myObject is actually an array therefore you can use array methods on it:
myObject = myObject.filter(function( obj ) {
  return obj.id != 2;
});

Demo: http://jsfiddle.net/elclanrs/LXpYj/

A: try this:
function deleteObject(array,id)
{
 var newObject=[];
  for (var o in array) {
       if(array[o].id!=id)
          newObject.push(array[o]);
    }
return newObject;
}

working JS fiddle
You can do without creating new array, you need to write remove function:
Array.prototype.remove = function() {
    var what, a = arguments, L = a.length, ax;
    while (L && this.length) {
        what = a[--L];
        while ((ax = this.indexOf(what)) !== -1) {
            this.splice(ax, 1);
        }
    }
    return this;
};

Without New Array Delete Object

A: try it with filter (its an array not a object)
var rr = [{"id": "1", "URL": "http://shsudhf.com", "value": "1"},  {"id": "2", "URL": "http://shsusadhf.com", "value": "2"}, {"id": "3", "URL": "http://shsudsdff.com", "value": "0"}];

rr = rr.filter(function(e) {
    return e.id != 2;
});

A: Here you go, this is without recreating the array or anything.
 var myObject = [{"id": "1", "URL": "http://shsudhf.com", "value": "1"},

                {"id": "2", "URL": "http://shsusadhf.com", "value": "2"},

    {"id": "3", "URL": "http://shsudsdff.com", "value": "0"}];

for(i=0,iMax=myObject.length;i<iMax;i++){
    (function (a) {
        if(this.id=="2"){
          delete myObject[a];
        }
    }).call(myObject[i],i);
}

console.log(myObject);

jsFiddle
http://jsfiddle.net/gG2zz/1/


text:
Q: Backward selection in R (looping): $ operator is invalid for atomic vectors This is my code:
DF <- data.frame(male_data)
Cols <- names(DF)
Cols <- Cols[! Cols %in% "male_data$y"]
n <- length(Cols)
id <- unlist(
lapply(1:6,
function(i)combn(1:6,i,simplify=FALSE)
)
,recursive=FALSE)

Formulas <- sapply(id,function(i)
paste("male_data$y~",paste(Cols[i],collapse="+")))

lapply(Formulas,function(i)
summary,step(Formulas, direction = "backward", trace=FALSE ))

Why do I get this error:

Error: $ operator is invalid for atomic vectors


text:
Q: Librosa 0.8.0 | Vocal separation output works, but is sped up to 200% speed I am working on this script in python to separate vocals from a track and write it to a music file.
I have chosen librosa as a library for this. Here is the code:
import numpy as np
import librosa.display
import soundfile as sf
import matplotlib.pyplot as plt
import librosa

y, sr = librosa.load('testInput.mp3')
output_file_path = "testOutput.wav"

S_full, phase = librosa.magphase(librosa.stft(y))
S_filter = librosa.decompose.nn_filter(S_full,
                                       aggregate=np.median,
                                       metric='cosine',
                                       width=int(librosa.time_to_frames(2, sr=sr)))
S_filter = np.minimum(S_full, S_filter)
margin_i, margin_v = 2, 10
power = 2

mask_i = librosa.util.softmask(S_filter,
                               margin_i * (S_full - S_filter),
                               power=power)

mask_v = librosa.util.softmask(S_full - S_filter,
                               margin_v * S_filter,
                               power=power)

# Once we have the masks, simply multiply them with the input spectrum
# to separate the components
S_foreground = mask_v * S_full
S_background = mask_i * S_full
D_foreground = S_foreground * phase
y_foreground = librosa.istft(D_foreground)
sf.write(output_file_path, y_foreground, samplerate=44100, subtype='PCM_24')

It works somewhat, however the output is sped up to 200%, which also results in the voice being pitched up a lot.
Whatever the input is, the output will sound alvin and the chipmunks alike.
Does anyone have an idea how to fix this, or what i am doing wrong?

A: librosa.load will by default resample to 22050 Hz. To preserve the original sampelrate of the input, use librosa.load(..., sr=None). However note that many parameters in librosa are tuned for 22050 Hz, like FFT lengths etc. In this example the stft and istft, at least.
So you may also want to try keeping that samplerate. In either case it would be good to use samplerate=sr in your call to sf.write() to avoid hardcoding it.


text:
Q: Building table of unique sets What I'm trying to do is build a table of unique sets of rows.
What is the aim?
I'm building an app for a service provider (let's say cable company for example). Every customer has a set of services on his connection. Every customer can have different number, type and combination of services installed.
For example some customers pays for standard cable package, they pay for HBO extra package and they also pays for online movie storage...
The system I'm building will allow the admin to create a migration. Each migration has groups and inside every group there is a matrix of service changes. Point is that the service provider is changing his portfolio and needs to migrate all the customers with certain combinations of services to different combinations.
Here's my SQL DDL code:
CREATE TABLE [Migration]
(
    [MigrationId]   INT NOT NULL IDENTITY(1,1)
    [Name]          VARCHAR(50) NOT NULL,
    [Description]   VARCHAR(250) NOT NULL
)

ALTER TABLE [Migration]
    ADD CONSTRAINT [Migration_pk]
        PRIMARY KEY CLUSTERED ([MigrationId])
                    WITH (ALLOW_PAGE_LOCKS = ON , ALLOW_ROW_LOCKS = ON )

CREATE TABLE [Migration_Service_Group]
(
    [GroupId]       INT NOT NULL IDENTITY(1,1)
    [MigrationId]   INT NOT NULL
)

ALTER TABLE [Migration_Service_Group]
    ADD CONSTRAINT [MigSerGroup_pk]
        PRIMARY KEY CLUSTERED ([GroupId])
                    WITH (ALLOW_PAGE_LOCKS = ON , ALLOW_ROW_LOCKS = ON )

CREATE TABLE [Migration_Matrix]
(
    [MatrixId]      INT NOT NULL IDENTITY(1,1),
    [GroupId]       INT NOT NULL
    [ServiceType]   INT NOT NULL,
    [OldRefId]      INT NOT NULL,
    [NewRefId]      INT NOT NULL
)

ALTER TABLE [Migration_Matrix]
    ADD CONSTRAINT [MigMatrix_pk]
        PRIMARY KEY CLUSTERED ([MatrixId])
                    WITH (ALLOW_PAGE_LOCKS = ON , ALLOW_ROW_LOCKS = ON )

ALTER TABLE [Migration_Service_Group]
    ADD CONSTRAINT [MigSerGroup_fk]
        FOREIGN KEY ([MigrationId]) REFERENCES [Migration]([MigrationId])
                ON DELETE NO ACTION
                ON UPDATE NO ACTION

ALTER TABLE [Migration_Matrix]
    ADD CONSTRAINT [MigMatrix_fk]
        FOREIGN KEY ([GroupId]) REFERENCES [Migration_Service_Group]([GroupId])
                ON DELETE NO ACTION
                ON UPDATE NO ACTION

What I don't know how to do is enforcing this rule:
Every group is unique => every set of rows in table Migration_Matrix with GroupID is unique, so that there are no same or contradicting groups of rules for migration.
For example: Group 1 (Migration_matrix => Migration_service_group, GroupId:1) has these records:
1,1,1,145,156
2,1,1,175,168

If Group 2 (Migration_matrix => Migration_service_group, GroupId:2) started like this, it would be error:
3,2,1,145, ....
4,2,1,175, ....

Because it contradicts the first group. But if group2 had an extra rows (another service change) it should be OK.
Any idea how to enforce it on the database side?

A: This type of constraint is better served on the app side. When a user starts to create/modify a matrix for a group the app locks the group. When a user hits Save the app checks constraints, updates the db and unlocks the group.


text:
Q: User Interactable line in Tradingview Pine Script I am trying to automate a simple strategy based on discretionary placement of trendlines. Ideally what I would want is place two lines manually on a chart and then interact with these lines in a pine script. For that I would need to be able to retrieve the line IDs of existing objects on the chart (or selected objects maybe?). I can't seem to find anywhere how to do this, or if at all possible.
The opposite would also be acceptable, meaning the script would place two lines on the chart using default values and the user would be able to move these around the chart so that the script can then get their coordinates afterwards.
It that at all possible? If so any documentation or reference would be very appreciated.

A: This cannot be done in Pine, because Pine does not allow for interaction with manually drawn objects, nor does it allow lines generated by Pine to be changed manually by the user.


text:
Q: Why isn't there an $i$ in the Riemannian path integral but there is one in a Pseudo-Riemannian path integral? In David Skinner's lecture note on AQFT he gives the definition of the path integral as
$$ \int_{\mathcal{C}} [\mathcal{D}\phi] \exp\left(-\frac{1}{\hbar}S[\phi]\right) $$
and later states that the when the manifold is Riemannian we'd use $S[\phi]/\hbar$ but if it was pseudo-Riemannian then we would use an additional factor of $i$. I've seen the Feynman path integral derivation and I don't see why for Riemannian manifolds you would remove the factor of $i$. Is there some reason we can remove the factor of $i$ while still being a path integral?

A: I do not know if there are any specific implications for algebraic quantum field theory. But the usual way of explaining that is by integrating over imaginary time
$$dt=id\tau$$
which is called Wick rotation. This is an analytic continuation technique (see also the quote from Zee's book in the Wikipedia article), pretty similar to the analytic continuation you can use to compute certain Fourier integrals. Wick rotation is also mentioned in the footnotes on page 5 of Skinner's lecture notes.
By replacing $dt\to id\tau$ you turn the Minkowski metric of special relativity into a Euclidean metric. At the same occasion, you turn the path integral formulation of the time evolution of the system ($exp(iS)$) into a statistical formulation of the thermal equilibrium of the system ($exp(-S)$).
That being said, I always found it strange (and Zee's quote shows that I am not the only one) that a simple mathematical trick (analytic continuation) also reveals a relationship between two seemingly very different physical concepts (time evolution and thermal equilibrium), and that these exciting things get mentioned in such a sober tone in most of the textbooks.


text:
Q: Postgres 12 CREATE Statistics not making a difference to reduce overestimate the planner is making on query hitting large table Have a query which is hitting 2 tables which are quite large in size (1 has nearly 2 billion rows and the other nearly 1 billion).
Query:
EXPLAIN (ANALYZE, COSTS, VERBOSE, BUFFERS, FORMAT JSON)
SELECT '1603710',
COALESCE(SUM(t0.play_cash_staked), '0'),
COALESCE(SUM(t0.play_cash_won), '0'),
COALESCE(SUM(t0.play_bonus_staked), '0'),
COALESCE(SUM(t0.play_bonus_won), '0')
FROM public.game t1
LEFT OUTER JOIN public.play t0 ON (t1.game_id = t0.game_id) WHERE (t1.customer_id = '1603710');

On explaining the query using the dalibo explain parser:
https://explain.dalibo.com/plan/af8b6de6742d9fbe
 Rows: ~1,167,290 (Planned: ~124,900,030) | over estimated by 110 ×

I am trying to reduce the amount it is overestimating by but having no joy.
Have tried utilising the "Create Statistics" option which is new from 10 onwards (am using postgres 12).
  CREATE STATISTICS cash_staked_won_bonus_staked_won_stt (dependencies) ON play_cash_staked ,play_cash_won,play_bonus_staked ,play_bonus_won, game_id FROM play;

But even after an analyze on the table still having issue. I have also noticed that the default statistics target is set to 100 by default. Would increasing the value at table level lock the table? If it does not, is there a particular formula to base the value off of?
Any help is much appreciated.


text:
Q: How to use .htaccess deny from all on subdirectory My folder structure is like this

*

*/home/user1/public_html/

*/home/user2/public_html/
I want to place the .htaccess file at /home/ and I only want to deny from all the /home/user1/ directory.
I don't want to place the .htaccess file inside /home/user1/.
Is this possible?

A: If you have access to the httpd configuration files themselves, you should solve this in the config file, and not via .htaccess.
To deny access to a specific resource, use the  directive:
<Directory /home/user1>
    #for httpd 2.4, use: Require all denied
    deny from all
</Directory>


text:
Q: Particle Deposition Terrain Generation I'm using Particle Deposition to try and create some volcano-like mountains procedurally but all I'm getting out of it is pyramid-like structures. Is anyone familiar with the algorithm that might be able to shed some light on what I might be doing wrong. I'm dropping each particle in the same place at the moment. If I don't they spread out in a very thin layer rather than any sort of mountain.
void TerrainClass::ParticalDeposition(int loops){
float height = 0.0;

//for(int k= 0; k <10; k++){

    int dropX = mCurrentX = rand()%(m_terrainWidth-80) + 40;
    int dropY = mCurrentZ = rand()%(m_terrainHeight-80) + 40;
    int radius = 15;
    float angle = 0;
    int tempthing = 0;
    loops = 360;

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

        mCurrentX = dropX + radius * cos(angle);
        mCurrentZ = dropY + radius * sin(angle);

        /*f(i%loops/5 == 0){
            dropX -= radius * cos(angle);
            dropY += radius * sin(angle);
            angle+= 0.005;
            mCurrentX = dropX;
            mCurrentZ = dropY;
        }*/

        angle += 360/loops;

        //dropX += rand()%5;
        //dropY += rand()%5;

        //for(int j = 0; j < loops; j++){

            float newY = 0;

            newY = (1 - (2.0f/loops)*i);

            if(newY < 0.0f){
                newY = 0.0f;
            }

            DepositParticle(newY);
        //}
    }
//}
}

void TerrainClass::DepositParticle(float heightIncrease){

bool posFound = false;

m_lowerList.clear();

while(posFound == false){
    int offset = 10;
    int jitter;

    if(Stable(0.5f)){
        m_heightMap[(m_terrainHeight*mCurrentZ)+mCurrentX].y += heightIncrease;
        posFound = true;
    }else{
        if(!m_lowerList.empty()){

            int element = rand()%m_lowerList.size();

            int lowerIndex = m_lowerList.at(element);

            MoveTo(lowerIndex);

        }
    }
}
}

bool TerrainClass::Stable(float deltaHeight){

int index[9];
float height[9];

index[0] = ((m_terrainHeight*mCurrentZ)+mCurrentX);                                                                     //the current index
index[1] = ValidIndex((m_terrainHeight*mCurrentZ)+mCurrentX+1)     ? (m_terrainHeight*mCurrentZ)+mCurrentX+1    : -1;   // if the index to the right is valid index set index[] to index else set index[] to -1
index[2] = ValidIndex((m_terrainHeight*mCurrentZ)+mCurrentX-1)     ? (m_terrainHeight*mCurrentZ)+mCurrentX-1    : -1;   //to the left
index[3] = ValidIndex((m_terrainHeight*(mCurrentZ+1))+mCurrentX)   ? (m_terrainHeight*(mCurrentZ+1))+mCurrentX  : -1;   // above
index[4] = ValidIndex((m_terrainHeight*(mCurrentZ-1))+mCurrentX)   ? (m_terrainHeight*(mCurrentZ-1))+mCurrentX  : -1;   // bellow
index[5] = ValidIndex((m_terrainHeight*(mCurrentZ+1))+mCurrentX+1) ? (m_terrainHeight*(mCurrentZ+1))+mCurrentX+1: -1;   // above to the right
index[6] = ValidIndex((m_terrainHeight*(mCurrentZ-1))+mCurrentX+1) ? (m_terrainHeight*(mCurrentZ-1))+mCurrentX+1: -1;   // below to the right
index[7] = ValidIndex((m_terrainHeight*(mCurrentZ+1))+mCurrentX-1) ? (m_terrainHeight*(mCurrentZ+1))+mCurrentX-1: -1;   // above to the left
index[8] = ValidIndex((m_terrainHeight*(mCurrentZ-1))+mCurrentX-1) ? (m_terrainHeight*(mCurrentZ-1))+mCurrentX-1: -1;   // above to the right

for ( int i = 0; i < 9; i++){
    height[i] = (index[i] != -1) ? m_heightMap[index[i]].y : -1;
}

m_lowerList.clear();

for(int i = 1; i < 9; i++){
    if(height[i] != -1){
        if(height[i] < height[0] - deltaHeight){
            m_lowerList.push_back(index[i]);
        }
    }
}

return m_lowerList.empty();
}

bool TerrainClass::ValidIndex(int index){
return (index > 0 && index < m_terrainWidth*m_terrainHeight) ?  true : false;
}

void TerrainClass::MoveTo(int index){
mCurrentX = index%m_terrainWidth;
mCurrentZ = index/m_terrainHeight;
}

Thats all the code thats used.

A: You should have a look at these two papers:
Fast Hydraulic Erosion Simulation and Visualization on GPU
Fast Hydraulic and Thermal Erosion on the GPU (read the first one first, the second one expands on it)
Don't get scared by the "on GPU", the algorithms work just fine on CPU (albeit slower). The algorithms don't do particle sedimentation per se (but you don't either ;) ) - they instead aggregate the particles into several layers of vector fields.
One important thing about this algorithm is that it erodes already existing heightmaps - for example generated with perlin noise. It fails miserably if the initial height field is completely flat (or even if it has insufficient height variation).
I had implemented this algorithm myself and had mostly success with it (still have more work to do, the algorithms are very hard to balance to give universally great results) - see the image below.
Note that perlin noise with the Thermal weathering component from the second paper may be well enough for you (and might save you a lot of trouble).
You can also find C++ CPU-based implementation of this algorithm in my project (specifically this file, mind the GPL license!) and its simplified description on pages 24-29 of my thesis.

A: Your particles will need to have some surface friction and/or stickiness (or similar) in their physics model if you want them to not spread out into a single-layer. This is performed in the collision detection and collision response parts of your code when updating your particle simulation.
A simple approach is to make the particles stick (attract each-other). Particles need to have a size too so that they don't simply converge to perfectly overlapping. If you want to make them attract each other, then you need to test the distance between particles.
You might benefit from looking through some of the DirectX SDK examples that use particles, and in particular (pun arf!) there is a great demo (by Simon Green?) in the NVidia GPU Computing SDK that implements sticky particles in CUDA. It includes a ReadMe document describing what they've done. You can see how the particles interact and ignore all the CUDA/GPU stuff if you aren't going for massive particle counts.
Also note that as soon as you use inter-particle forces, then  you are checking approximately 0.5*n^2 combinations (pairs) of particles...so you may need to use a simple spatial partitioning scheme or similar to limit forces to nearby groups of particles only.
Good luck!


text:
Q: adodc Visual Basic 6 Access 2010 I have made an application using VB6 and it's already connected to an Access database.
Everything works perfectly: I have my table field shown in my VB application as it should be. My problem is that I don't know how to link between filed that is contain (yes/no) in Access with option botton in VB. I have them in frame but that's all. Any help or code or even something to start with it.
Here's a picture:

In the picture you will notice that it's already (yes) but that is what VB6 gives me; it's suppose to be no anyway.

A: Option button is not a databound control. You will need to work directly with it's events and the data control to update or reflect the changes.
Another user has already suggested using a checkbox control, which IS a databound control.
Either way shouldn't prove too difficult, but the checkbox should be near plug and play.


text:
Q: Select multiple rows from PostGIS table where ST_Contains has multiple manual inputs Under normal circumstances I could get the spatial intersection between a table with multipolygons and another table with point geometry using some variant of
SELECT *
FROM ( SELECT * FROM point_geometries) s
JOIN polygon_geometries sg ON ST_Contains(sg.geom, s.point_geom)

But I have a situation where instead of a table, I have a list of point geometries to input. If I only have one geometry then I can do
SELECT *
FROM polygon_geometries
WHERE ST_Contains(geom, '0101000020E6100000E73B8A05101056C01F1166ED49594440')

which returns a single row from polygon_geometries giving me exactly what I want.
Now imagine I have 100+ geometries and I want to get all the rows from polygon_geometries where ST_Contains any of the points (in theory returning up to 100 rows from polygon_geometries). Is there a way to do this that doesn't involve constructing WHERE ST_Contains(geom, string1) OR ST_Contains(geom, string2)... etc?
I'd love to be able to feed a list of the strings in, if possible. I simply can not find any examples of this.

A: Two common options:

*

*a set of materialized VALUES:
WITH
  inputs(geom) AS [MATERIALIZED] (
    VALUES
      ('<WKB>'),
      ('<WKB>'),
      ...
  )
SELECT ply.*
FROM   polygon_geometries AS ply
JOIN   inputs AS inp
  ON   ST_Contains(ply.geom, ST_SetSRID(inp.geom::GEOMETRY, <SRID>)
;

*a table from UNNEST:
WITH
  inputs AS [MATERIALIZED] (
    SELECT ST_SetSRID(wkb::GEOMETRY, <SRID>) AS geom
    FROM   UNNEST(ARRAY[
             '<WKB>',
             '<WKB>',
             ...
           ]) AS wkb
  )
SELECT ply.*
FROM   polygon_geometries AS ply
JOIN   inputs AS inp
  ON   ST_Contains(ply.geom, inp.geom)
;

with the former being slightly faster in terms of creating the set, and the latter being more comfortable for copy/paste.
MATERIALIZED only applies to PostgreSQL >= 12.


text:
Q: Creating multiple dictionaries based on other dictionary values in python I have a list that contains many dictionaries. Each dictionary represents a change that has occurred within my application. The "change" dictionary has the following entries:
userid: The user ID for a user
ctype: A reference to a change type in my application
score: A score

The ctype can be one of about 12 different strings to include "deletion", "new", "edit" and others. Here is an example of one of the "change" dictionaries:
{'userid':2, 'score':10, 'ctype':'edit'}

My question is, how can I create a dictionary that will aggregate all of the change types for each user within this large list of dictionaries? I would like to add the score from each change dictionary to create a total score and add each ctype instance together to get a count of each instance. The goal is to have a list of dictionaries with each dictionary looking like this:
{'userid':2, 'score':325, 'deletion':2, 'new':4, 'edit':9}

I have been trying to work this out but I am pretty new to python and I wasn't sure how to count the actual change types. The other part that gets me is how to refer to a dictionary based on 'userid'. If someone can present an answer I am sure that all of this will become very apparent to me. I appreciate any and all help.

A: The key thing to agregate data here is to have a dictionary where each key is the userid, and each entry is the data relevant to that userid.
final_data = {}
for entry in data:
    userid = entry["userid"]
    if userid not in final_data:
        final_data[userid] = {"userid": userid, "score": 0}
    final_data[userid]["score"] += entry["score"]
    if not entry["ctype"] in final_data[userid]:
        final_data[userid][entry["ctype"]] = 1
    else:
        final_data[userid][entry["ctype"]] += 1

If you want the result as  a list of dictionaries, just use final_data.values()

A: Could you have
(Mock up not real python.)
{userid : {score : 1, ctype : ''}}

You can nest dict's as values in python dictionaries.

A: To index the dictionaries with respect to userid, you can use a dictionary of dictionaries:
from collections import defaultdict

dict1 = {'userid': 1, 'score': 10, 'ctype': 'edit'}
dict2 = {'userid': 2, 'score': 13, 'ctype': 'other'}
dict3 = {'userid': 1, 'score': 1, 'ctype': 'edit'}
list_of_dicts = [dict1, dict2, dict3]

user_dict = defaultdict(lambda: defaultdict(int))
for d in list_of_dicts:
    userid = d['userid']
    user_dict[userid]['score'] += d['score']
    user_dict[userid][d['ctype']] += 1

# user_dict is now
# defaultdict(<function <lambda> at 0x02A7DF30>,
#  {1: defaultdict(<type 'int'>, {'edit': 2, 'score': 11}),
#   2: defaultdict(<type 'int'>, {'score': 13, 'other': 1})})

In the example, I used a defaultdict to avoid checking at every iteration if the key d['ctype'] exists.

A: It could look like so:
change_types = ['deletion', 'new', 'edit', ...]
user_changes = {}
for change in change_list:
    userid = change['userid']
    if not userid in user_changes:
        aggregate = {}
        aggregate['score'] = 0
        for c in change_types:
            aggregate[c] = 0
        aggregate['userid'] = userid
        user_changes[userid] = aggregate
    else:
        aggregate = user_changes[userid]

    change_type = change['ctype']
    aggregate[change_type] = aggregate[change_type] + 1
    aggregate['score'] = aggregate['score'] + change['score']

Actually making a class for the aggregates would be a good idea.


text:
Q: Display ListView's sub items and titles I have a ListView and cannot display the sub items on the list... It only displays one or the other but not both. If I remove the number from below it will display the string (titles):
I want to display both Items and sub items.
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    this.loadData();

    String []titles_str = titles.toArray(new String[titles.toArray().length]);
    this.setListAdapter(new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_2, android.R.id.text1, titles_str));

    Number []subtitles_str = lengths.toArray(new Number[lengths.toArray().length]);
    this.setListAdapter(new ArrayAdapter<Number>(this,
            android.R.layout.simple_list_item_2, android.R.id.text2, subtitles_str));
}

A: you are using "this.setListAdapter" two times, only Second "this.setListAdapter" will reflect.
For your requirement, Please use
1)custom arrayadapter<customObject>
      or
2)simpleadapter.

1) Using custom arrayadapter, Please check http://devtut.wordpress.com/2011/06/09/custom-arrayadapter-for-a-listview-android/
2) Using SimpleAdapter:
List<Map<String, String>> data = new ArrayList<Map<String, String>>();
for (int i=0; i<titles_str.length; i++) {
    Map<String, String> datum = new HashMap<String, String>(2);
    datum.put("title", titles_str[i]);
    datum.put("subtitle", String.valueof(subtitles_str[i]));
    data.add(datum);
}
SimpleAdapter adapter = new SimpleAdapter(this, data,
                                      android.R.layout.simple_list_item_2,
                                      new String[] {"title", "subtitle"},
                                      new int[] {android.R.id.text1,
                                                 android.R.id.text2});
this.setListAdapter(adapter);


text:
Q: Display a message for a deactivated link I have a navigation bar with many links. The problem is that I am not done with all the pages. Is there anyway that I can block my users from clicking on certain links and instead display a little message that notifies them that the content will be coming soon?
Edit: It did not allow me to include bootstrap within the tags--but if a solution includes bootstrap, I am comfortable with it.
Edit 2: I have some jQuery effects on the navigation bar, is there anyway to also disable these effects when the link is clicked?

A: Simply, you can use href="#" and alert message onclick:
MenuName

A: Put a class to your links which are not ready. For i.e. inactive class. And then in jQuery you can simply do it like below:
$( ".inactive" ).click(function(event) {
   alert("This page is coming soon!");
   event.preventDefault();
});

A: You can also use alert for displaying message :
HTML
Link
Link Wroking

JS
$('a.inactive').click(function( event ) {
    event.preventDefault();
    var yesno = alert("Coming Soon");
});

Add class inactive for showing message. For the link which are working, don't add class inactive.
Here is a fiddle.


text:
Q: How to get the list of pm2 in laravel I want to build a control panel for all the pm2 in Admin Dashboard and let admin have control to start/stop/restart/delete the running processes. How can i get the list of running pm2 queue in laravel.

A: You can use exec function
$processList=null;
exec('pm2 list',$processList)

But you must run PHP with the same user as pm2. If you want to use different user check Running command-line application from PHP as specific user


text:
Q: shutil copy2 password protection mecanism? I have a strange issue while copying some files with python3 and shutil copy2 under windows (launching my script through PyCharm)
The files showing issue all contains 'password' or 'PASSWORD' in the name i'm trying to rename them to and it seems copy2 is automatically cutting whatever is after password and not copying the file ?
All other files work fine
my code :
def copy(rom, name, system):
  if not os.path.exists(os.path.join(distFolder, system)):
     os.mkdir(os.path.join(distFolder, system))
  shutil.copy2(os.path.join(newRomset, system, rom), os.path.join(distFolder, system, name + '.zip'))

in this example for instance we have :
rom : donquijote2.zip
name: Don Quijote de la Mancha - Parte II (Spanish) (48K) [Password: EL INGENIOSO HIDALGO]
but in the subFolder it creates a Don Quijote de la Mancha - Parte II (Spanish) (48K) [Password file with no extension and a size of zero
Same for :
rom : avespacial2.zip
name: Aventura Espacial, La - En los Dominios del Cerebelo (Spanish) [PASSWORD: CANES VENATICI]
I get a file named like Aventura Espacial, La - En los Dominios del Cerebelo (Spanish) [PASSWORD again no extension and size of 0
Is there a protection mechanism embedded into Python for this ?
I even deactivated my antivirus but no chance
Thought about too long filenames / paths too but longer files with longer names without password in it get copied fine...
Worth to mention is that no error appears at all when executing the script

A: Well I found the issue, actually nothing related to any kind of password protection !
Turns out it's the : in Password: that causes the issue, because it's an illegal character for filenames.
Replacing it by - fixes the problem.
Very strange that I get no error from python though, I'm pretty sure there was an explicit error ending the script in that exact case in some previous scripts I wrote


text:
Q: Change project in sublime text, sourcetree & codekit I'm a web developer, and often need to switch between projects. This means I need to:

*

*Change project in Sublime Text 2

*Change project in CodeKit

*Change project in SourceTree

Note: I'm using Mac OSX 10.9.1
Considering these are all changing to the same project folder, I wonder if there's a way of automating this task so I change all of them at the same time. Is there a way to do this?

A: Sublime Text and SourceTree both have command line tools (subl and stree respectively), so you could write a simple script to call both of those with the current directory as an argument.
If you keep your .sublime-project files in your project directories, you could call subl with that instead.
Unfortunately, neither Sublime Text nor SourceTree offer AppleScript automation.
Haven't got a clue about CodeKit, as I don't use it.


text:
Q: how build a wordpress query_posts based on url I want to use the query_posts function from wordpress for displaying the right posts. I want to use the url www.site.com/?s=taxonomy1=test1&taxonomy2=test2 for building the query. something like down here:
        $taxonomy1 = $_GET['taxonomy1'];
        $taxonomy2 = $_GET['taxonomy2'];

        query_posts(array(
            'posts_per_page' => 10,
            'taxonomy1' => $taxonomy1,
            'taxonomy2' => $taxonomy2,
        ) );>

How i do this?

A: the wordpress codex is your best friend when trying to build custom queries.  something like this should work as a query
$taxonomy1 = $_GET['taxonomy1'];
$taxonomy2 = $_GET['taxonomy2'];

$the_query = new WP_Query(array(
  'posts_per_page' => 10,
  'tax_query' => array(
     'relation' => 'AND',
     array(
       'taxonomy' => $taxonomy1,
       'field' => 'slug',
     ),
     array(
       'taxonomy' => $taxonomy2,
       'field' => 'slug',
     ),
   ),
));

and to display the results
while ( $the_query->have_posts() ) : $the_query->the_post();
  //the_title(), the_content(), etc
endwhile;

note that the query is using the new (as of 3.1) method for querying taxonomies.  As you can see it gives you a lot more flexibility and i would suggest reading through the above link


text:
Q: Kubernetes load balancer Network Security Group How to configure Network Security Group for a load balancer in Azure Kubernetes. Basically, want to restrict incoming external traffic to service for a range of IP Addresses only.

A: According to the Azure documentation you should be able to specify the IP addresses you want to allow in the spec/loadBalancerSourceRanges field of your Service, such as:
apiVersion: v1
kind: Service
metadata:
  name: my-lb-name
spec:
  type: LoadBalancer
  ...
  loadBalancerSourceRanges:
  - 1.2.3.0/16


text:
Q: Extracting href links from multiple directories on a page I am using a Javascript JFlot Graph to monitor a list of .rrd files I have on my server. I hard coded all the .rrd file href links into the JavaScript code of of the Graph in a drop down menu. I then realized it was bad practice to hard code them in.
Here comes the problem.
I want to write some code that each time I open the Graph, would check the server or the page, for all the .rrd files, extract them as href links, and place them inside 'something' so that the JavaScript 'drop down menu' for the Graph could read it.
I researched there was two solutions to do this, 1. Using client-side programing via JQuery and Ajax (I am not cross domain coding) 2. Server-Side via PHP and Json.
I figured Server-Side was the better option, for the understanding that it's easier and that the code wont need to download anything, regardless if it would only take a few seconds.
I just could not figure out the solution to this problem yet. I hope I explained my problem well and any advice or code is welcome, including any good practices to abide by or whether to use option 1 by extracting it from the directories on the page or 2 collecting the data from the server.
Thank You for your time and consideration I truly appreciate it.

A: As long as all the files are in one directory, you can generate the list pretty easily using PHP's glob function:
$files = glob($storage_dir . DIRECTORY_SEPARATOR . '*.rrd');
It returns an array where each entry is a file name.  You can easily convert this to JSON and send it back using:
$response = json_encode($files);


text:
Q: How to control execution flow in Powershell based on StartWith() result? Trying get this simple statement working, and I cant understand why it won't output the correct result.
$asset = "get-wmiobject -class win32_computersystem | select Name"
if ($asset.StartsWith("ME")) {
echo "Asset tag is ok" }
Else
{ echo "Asset tag needs updating" }

For some reason, despite the result from the WMI query being "ME12345" for example, the code outputs "Asset tag needs updating".
Do I need to use an /F or something to make the IF statement work with the result from the WMI statement?

A: Try this:
$asset = iex 'get-wmiobject -class win32_computersystem | select -expand Name'
        if ($asset.tostring().StartsWith("ME")) {
        echo "Asset tag is ok" }
        Else
        { echo "Asset tag needs updating" }

In $asset you are not actually executing the string, it is remaining a string, you need to use iex or Invoke-Expression to invoke the expression, then use expand the property value and execute StartsWith on a String variable.

A: Your command is wrapped in double-quotes, so you are passing a string of the command, rather than the actual returned value.
When you change it to a command and the value is returned, it is an object with the property Name, and it does not contain a method "StartsWith", instead you can use a comparison operator, and below I've gone with regex that matches lines starting with "ME".
You probably want to use CIMInstance, as it is the new version of WMIObject.
$asset = Get-CimInstance -Class win32_computersystem | Select Name
    if ($asset.Name -match "^ME") {
        Write-Output "Asset tag is ok"
    }
    Else {
        Write-Output "Asset tag needs updating"
    }