text:
Q: How reliable is the randomness of the shuf command? I ran the following command to generate 1 billion random numbers:
time shuf -i 1-1000000000 > "SHUF TEST 1"

To my surprise it was able to do this in less than 10 mins. I then ran the output file through uniq -d to determine how many of the generated numbers were duplicate, and was again surprised when it turned out to be 0. I also ran the output file through uniq -u and sort -u to confirm these results.
How is it that the shuf command is able to generate a billion random numbers in such a relatively short amount of time, and can I depend on its randomness? Note that I don't need a cryptographically secure random number generator for my needs, just something good enough to always return a unique number.

A: The shuf utility shuffles its input by outputting a random permutation of its input lines. According to it's manpage, "Each output permutation is equally likely". An analogy would be to shuffle a deck of cards.
If the input lines contain duplicates, the output from shuf will also contain duplicates. Why?  Because shuf performs a random permutation of it's input.  If the input lines contain no duplicates, the output from shuf will contain no duplicates.
In your example, shuf -i 1-1000000000, the -i option causes shuf to act as if it's input came from a file containing the range of unsigned decimal integers 1 through 1000000000, one unsigned integer per line. In other words, shuf acts as if it had 1000000000 lines of input with each line containing a unique unsigned integer. Hence there are no duplicates to be found in the output.


text:
Q: Keras permute_dimension causes weird tensor shapes I'm running into an issue with a model I'm trying to build. I've been trying to debug it and ran into an oddity that I think may be the cause, but I'm not sure what I'm doing wrong. I've reduced what I think the problem is into a small snippet you can run on colab.
Here's a colab where you can try running this:
https://colab.research.google.com/drive/1pSTwCwMFGlWgJOP3gn9WF6pZq2CiP4XJ
import keras
from keras.layers import Layer, Dense, Input, Reshape
import keras.backend as K

class SimplePermute(Layer):
    def __init__(self, **kwargs):
        super(SimplePermute, self).__init__(**kwargs)

    def call(self, inputs, **kwargs):
        return K.permute_dimensions(inputs, [0,2,1])
test_i = Input(shape=(10, 256))
test = SimplePermute()(test_i)
print(test.get_shape())
print(K.int_shape(test))
test = Dense(units=100, activation="softmax", name="sft2")(test)
print(test.get_shape())
print(K.int_shape(test))

I'd expect the second series of prints to print the permuted tensor shape - that is [?, 256, 10]. However, the K.int_shape() returns [?, 10, 256], while TF's get_shape() returns the properly permuted shape.
I believe this internal mismatch is causing the errors I'm seeing downstream in the model.

A: Your custom layer doesn't have the compute_output_shape method implemented. This is what Keras uses to determine the _keras_shape property of the tensors, which is returned by K.int_shape.

*

*You can use the standard Permute((2,1)) layer.

*Or you can use a Lambda(lambda x: K.permute_dimensions(x, [0,2,1])) layer.

*Or you can implement the compute_output_shape method:

.
def compute_output_shape(self, input_shape):
    return (input_shape[0], input_shape[2], input_shape[1])

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can't find WebAPI method I have declared a function on my API controller:
[HttpGet, Authorize]
public List<UIPhotoModel> GetPhotosByAlbumID(int AlbumID)
{
    ....
}

I call it from my javascript:
var urinocat = '/api/Photo/GetPhotosByAlbumID';
    $.get({ url: urinocat, contentType: "application/json" }, 0)
        .done(function (data) {
            vm.UncategorisedImages(data);
        });

And get:
GET http://localhost:54065/api/Photo/GetPhotosByAlbumID 404 (Not Found)

The only way I know how to fix it is to create a class, with an int in it, and pass accept that in my controller method. Why can't the API method be found?
All other ones work with I use a complex object and pass that bk to the controller. But an int - it fails.

A: Have you tried making the request with a query string in the url like this:
http://localhost:54065/api/Photo/GetPhotosByAlbumID/?AlbumID=1


text:
Q: Omission of object In the following sentence A, is the word "stop" an intransitive verb or a transitive verb?  If it's a transitive verb, should the object word such as that/it be added like in the sentence B?
A: Once a food culture begins to change, it is hard to stop.
B: Once a food culture begins to chabge, it is hard to stop that.
Thank you.

A: stop is both transitive and intransitive. And frankly, I've come across both the examples as in your question.
Nevertheless, I'd put an object here to remove ambiguity. You said, '..hard to stop.' but what? Your efforts? Your research? Putting an object makes it clear.

Once a [sic] food culture begins to change, it is hard to stop it (i.e. food culture).


text:
Q: Can't read json_encode I'm having an issue. I have a json_encode array in php. With ajax, I get back in my javascript script.
php
<?php
$code = 'xyz';
$email = 'xyz@gmail.com';
$back = array();
array_push($back, array("code" => $code,"email" => $email));
echo json_encode($back);
?>

ajax callback function
function(data){
alert(data);
alert(data[0].code);
}

When I try to alert data, I get [{"code":"xyz","email":"xyz@gmail.com"}]
Now when I try to alert the code (or the email) it says undefined.
Can you help me alert data[0].code properly ?

A: In your ajax options set dataType: "JSON"

A: You need to parse it
function(data){
    var obj = JSON.parse(data[0]);
    alert(obj.code)
}

A: its working ,i am tried in jsfiddle
var data=[{"code":"xyz","email":"xyz@gmail.com"}]
alert(data);
alert(data[0].code);

i got in alert xyz


text:
Q: "Cannot read property 'id' of undefined" when trying to get a user id during the development of my bot I encountered the following error:

Cannot read property 'id' of undefined

This is my code so far:
 const msg =  message.channel.send(gvg).then(async msg => {
  await msg.react('');
  await msg.react('');
  await msg.react('');
  await msg.react('⚙');

  const filter = (reaction) =>  ['', '', '', '⚙'].includes(reaction.emoji.name);

  const collector = msg.createReactionCollector(filter,{ time: 30000 }, {dispose : true });

  collector.on('collect', async (reaction, user ) => {
    const member = message.guild.members.cache.get(user.id);
    if (reaction.emoji.name === '' ) {
      member.roles.add('845380394513596446');
    }

    if (reaction.emoji.name === '') {
      member.roles.add('845380453597708299')
    }

    if (reaction.emoji.name === '') {
      member.roles.add('845380484964024330')
    }

    if (reaction.emoji.name === '⚙') {
      member.roles.remove('845380484964024330')
      member.roles.remove('845380453597708299')
      member.roles.remove('845380394513596446')
    }

  });

  collector.dispose('remove', async (reaction, user,  ) => {
    const member = message.guild.members.cache.get(user.id);
    if (reaction.emoji.name === '' ) {
      member.roles.remove('845380394513596446');
    }

    if (reaction.emoji.name === '') {
      member.roles.remove('845380453597708299')
    }

    if (reaction.emoji.name === '') {
      member.roles.remove('845380484964024330')
    }

  });

})

I hereby try to achieve that when retracting a reaction, the role of the user is removed again.


text:
Q: SignalR and foreverFrame hang with IE 9 I have an asp.net site using SignalR for pushing data from the server to the client .
I try my page with two browsers (FireFox , IE9)
I noticed , Firefox is using ServerEvent transport and IE uses ForeverFrame .
I have no problem with FF , but in IE9 after some minutes its stop working , I mean I don't get the push events from the server . (When I moved the transport to long poling its working) but I want it to be more efficient without long polling.
In the hub I call the client side each 5 sec.
Please inform me if you need more details .
Any suggestions.
Thanks in advance ...

A: Please also see the following https://github.com/SignalR/SignalR/blob/master/ReleaseNotes.md
This has the release notes until 1.0.0-rc2 and documents the breaking changes


text:
Q: Comic from 60's or 70's with a criminal whose mind is put in a war robot I remember reading a sci fi comic when I was young, early 70's, about a criminal whose sentence was having his mind transferred to a war like robot where he would die infinite deaths but his mind would just be transferred to another robot. In the end, he beats the system by allowing a tank to crush his head, rendering his brain in his human form severely mentally disabled.
I thought initially that this was included in the short stories of StarStream, but I've collected those and the story isn't among them.
Any help would be greatly appreciated.

A: This story is called Welcome Machine in Sgt. Rock Vol. 1 #316 (May,  1978)


text:
Q: Shifter Power Method If we know all the eigenvalues of a matrix A except the largest one. We want to apply shifted power iteration to get the largest eigenvalue. Something like $(A-\alpha I)$ . Then what should be the value of shift ($\alpha$) to make it converge as fast as possible ?

A: If the eigenvalues of $A$ are all real:
$$\lambda_1 \gt \lambda_2 \gt \ldots \gt \lambda_k$$
then the power iterations of the shifted matrix $A - \alpha I$ converge at the optimal rate when $\alpha = \frac{\lambda_2 + \lambda_k}{2}$.
Something similar can be done if the eigenvalues are complex but known except for the one of greatest modulus.


text:
Q: How to install Ubuntu on a zeroed-out drive? Very new at all of this...don't understand most of the answers I've read to other questions (i.e. partitions, iso images, etc.) BUT I zeroed-out my hard drive on a computer that ran XP and would like to download Ubuntu.
Can anyone explain how to do that in 'layman's' terms?

A: Please refer to How do I install Ubuntu? for help. Skip steps 8 and 9, and only if it fails, try step 9, creating a new partition after invoking the New partition table command(skip the part with reducing old partitions). If you have trouble, feel free to comment(You may comment on answers to your questions, even with one reputation).


text:
Q: Is there an eclipse plugin for developing in m4? Googling has turned up little to nothing.
I need to develop some heavy stuff in m4 and I'd love to do it in my favorite environment with all the bells and whistles thereof.
There are packages for running m4 on just about every platform, such as windows. So I know at the very least I can create a default project and test from the CLI. But I'd rather not :)

A: I'm not aware of any specific editing support for m4. However, if you have some time to spare (!) and the BNF for m4, then you could use Xtext (http://wiki.eclipse.org/Xtext) to create a syntax-coloring and -completing editor, with an outline view.
Updated an answer below suggests that m4 doesn't have a BNF, or is not BNeFfable, and certainly a short search of the literature shows no claims that an m4 BNF is available - and it appears, though not explicitly stated, that the m4 language is inexpressible in this way.
Obviously this negates my suggestion, so I must retract it, unless of course Xtext has been extended to deal with such languages. Consult the Xtext website linked above for FAQs and mailing list links.

A: You can also try colorer for Eclipse (http://colorer.sourceforge.net/eclipsecolorer/) — it almost certainly supports m4 syntax (though I did not check).

A: Unfortunately, just syntax coloring will be of little help - you need something that's capable of interpreting m4 because unless defines are processed you can't tell if it's just a word or a predefined macro. mc (Midnight Commander) has some rudimentary highlighting for m4, you might take a look at that.

A: If you are familiar with (and like) vim, you could try out Eclim and then setup syntax highlighting for m4.


text:
Q: How can I test my socket program in java using 2 virtual machines? I wrote a simple socket program in java and I test it using CMD and it works.
But it is required from me to test the program using 2 virtual boxes
So could you help me and tell me the procedure that i must follow to test my program?
Here is the codes
import java.io.*;
import java.net.*;
public class Server {

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        ServerSocket ss = new ServerSocket(1201);
        Socket s = ss.accept();

        DataInputStream din = new DataInputStream(s.getInputStream());
        DataOutputStream dout = new DataOutputStream(s.getOutputStream());

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        String msgin = "",msgout="";
        while(!msgin.equals("end")) {
            msgin = din.readUTF();
            System.out.println(msgin);
            msgout = br.readLine();
            dout.writeUTF(msgout);
            dout.flush();
        }
        s.close();
    }

}

import java.io.*;
import java.net.*;
public class Client {

    public static void main(String[] args) throws UnknownHostException, IOException {
        Socket s = new Socket("127.0.0.1",1201);
        DataInputStream din = new DataInputStream(s.getInputStream());
        DataOutputStream dout = new DataOutputStream(s.getOutputStream());

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String msgin="",msgout="";
        while(!msgin.equals("end")) {
            msgout = br.readLine();
            dout.writeUTF(msgout);
            msgin = din.readUTF();
            System.out.println(msgin);
        }
        s.close();
    }

}

A: You can use docker as VM.
Just run two docker containers for each, client and server.


text:
Q: How to change data in array of Structure? my code is like below,
struct RegistrationInformation {
    let leftTitle: String
    let rightTitle: String

}

struct RegisterData{
    let vValueL : String
}
var regDatas : [RegistrationInformation] = []

       for i in 0...3 {
            regDatas.append(RegistrationInformation(leftTitle: regData[i].vValue, rightTitle: ""))
        }
        for i in 4...7 {
            regDatas.append(RegistrationInformation(leftTitle: "", rightTitle: regData[i].vValue))
        }

//output of regDatas is

       [Datas.RegistrationInformation(leftTitle: "line 1", rightTitle: ""),
        Datas.RegistrationInformation(leftTitle: "line3", rightTitle: ""),
        Datas.RegistrationInformation(leftTitle: "line5", rightTitle: ""),
        Datas.RegistrationInformation(leftTitle: "line7", rightTitle: ""),
        Datas.RegistrationInformation(leftTitle: "", rightTitle: "line2"),
        Datas.RegistrationInformation(leftTitle: "", rightTitle: "line4"),
        Datas.RegistrationInformation(leftTitle: "", rightTitle: "line6"),
        Datas.RegistrationInformation(leftTitle: "", rightTitle: "line8")]

what I want is like below in regDatas
  [Datas.RegistrationInformation(leftTitle: "line 1", rightTitle: "line2"),
        Datas.RegistrationInformation(leftTitle: "line3", rightTitle: "line4"),
        Datas.RegistrationInformation(leftTitle: "line5", rightTitle: "line6"),
        Datas.RegistrationInformation(leftTitle: "line7", rightTitle: "line8")]

I want to change data position in array struct of regDatas.
how can we do that
thank you

A: struct RegistrationInformation {

    let leftTitle: String
    let rightTitle: String

}

struct RegisterData{

    let vValueL : String

}

var regData: [RegisterData] = [
    RegisterData(vValueL: "line1"),
    RegisterData(vValueL: "line2"),
    RegisterData(vValueL: "line3"),
    RegisterData(vValueL: "line4"),
    RegisterData(vValueL: "line5"),
    RegisterData(vValueL: "line6"),
    RegisterData(vValueL: "line7"),
    RegisterData(vValueL: "line8")
]

func compressData(elements: [RegisterData]) -> [RegistrationInformation]{
    var regDatas : [RegistrationInformation] = []
    for i in 0..<elements.count {
        if i != (elements.count-1){
            regDatas.append(RegistrationInformation(leftTitle: regData[i].vValueL, rightTitle: regData[i+1].vValueL))
        }else{
            regDatas.append(RegistrationInformation(leftTitle: regData[i].vValueL, rightTitle: ""))
        }
    }
    return regDatas
}

print(compressData(elements: regData))

A: Not sure what you're trying to do, would something like this help:
let regDatas: [RegistrationInformation] = zip(0...3, 4...7)
    .map { left, right in
        RegistrationInformation(leftTitle: String(left), rightTitle: String(right))
}

or even:
let regDatas: [RegistrationInformation] = (0...3).map {
    RegistrationInformation(leftTitle: String($0), rightTitle: String($0 + 4))
}


text:
Q: BFS starting with a given node and reaching all nodes I have a scenario where

*

*I want to run BFS starting at a particular node(let's say ID:7).

*If there are nodes unreachable from this node, I want to restart the
BFS(with any remaining node) until all vertices of the graph are
visited.

What I have so far is code(partial) that starts from node 0 and restarts with another unvisited vertex:
void BFS()
{
    // Mark all the vertices as not visited
    bool *visited = new bool[V];
    for(int i = 0; i < V; i++)
        visited[i] = false;
    // Call the recursive function starting from all vertices one by one
    for(int i = 0; i < V; i++)
        if(visited[i] = = false)
            BFSUtil(i,visited);
}

void BFSUtil(int s,bool *visited)
{
    queue<int> queue;
    visited[s]=true;
    queue.push(s);

    while(!queue.empty())
    {
        s = queue.front();
        queue.pop();
         // Get all adjacent vertices of the dequeued vertex s
        // If a adjacent has not been visited, then mark it visited
        // and enqueue it
        for(i = adj[s].begin(); i != adj[s].end(); ++i)
        {
            if(!visited[i])
            {
                queue.push(i);
                BFSUtil(id,visited);
            }
        }
    }

}

How do I efficiently change this code to suit my requirement?

A: You have most of the ideas in place already since you're storing this visited state and have #1 down. To do #2, you can simply iterate through the visited list looking for a value of false to indicate an unvisited node. Now run #1 on that one. Repeat until you find that all entries in visited are true.
Something like this:
// Loop until all elements have been visited.
bool found = false;
do
{
    // Look for an element that hasn't been processed yet
    // to run the BFS.
    found = false;
    for(int i = 0; i < V; i++)
    {
        if(visited[i] = = false)
        {
            BFSUtil(i,visited);
            found = true;
        }
    }
} while (found);

You could also avoid the linear search through visited each time after #1 with a more efficient set than a bunch of booleans you have to linearly search through, but probably the effort required isn't worth the effort unless you're searching a whole bunch of teeny, disconnected graphs, and that would normally degrade the performance of the traversal unless it was a really efficient set (or a dense + sparse one: one for constant-time quick checks, another with log or better time insertion).


text:
Q: Leaflet->how to draw a polygon with reference to another geographical position I have a basic leaflet map in which I draw a circle representing a city.
Next, I would like to locate a rectangle with reference to that circle. (more specifically drawing a rectangle not with reference to its centroid or any corner x,y; but with reference to the circles x,y. So, I need to define the distance with these two objects, and dimensions of rectangle.)
Please see the image below as a graphical expression of this issue:

A: var position = new L.Rectangle(new L.Circle([x, y], R).getBounds().addTo(map);


text:
Q: MS Office 2011 Word printing range of pages fails I tried to print pages 7-8 and 11-14 of a 14 page document. Word decided it was going to print the whole document. No matter what settings I tried; whole document. Except that you can successfully print "current page".
I have seen this issue complained about for about 2 years, but did not find any solution. Only that the problem was "intermittent" and "fixed itself."
Is there any better wisdom than the workaround of printing one page at a time?
In addition, during the attempts to use the different page range settings, I saw the the preview would occasionally report the document had 28 pages. And sometimes when printing, the pages would come out in "random" order. Very strange.

A: I had the same problem occur and I found a solution…
When you look at the number of pages in the status bar in Word (bottom left corner) it reads something like: Page: 1 of 20 (or however many pages your document has in it).
Now go to your "Insert" Tab and look for the "Page Number" menu/button and drop it down to the "Format page numbers…"  In this dialog box, what does it read for "Page Numbering/Start at:" ?  If you have changed this setting to start at a new number, that is now the new page parameter set.
That should be the beginning of the print dialog box print range.
So say you have it set to "Start at: 9"  When you go to print the page range in the print dialog box your document is actually set now as Pages: 9-29 (instead of page 1-20).
If you only want to print the last ten pages you need to say print range "19-29".

A: I was running into this same problem at the same time that I was having problems with my printer. When I ended up using some specific drivers for the printer (instead of the default/universal Apple printer driver) the problem went away. So if you are still struggling with this issue, I would suggest trying to use a printer specific driver. Hopefully that will resolve this issue for you.


text:
Q: Direct Mapped Cache A computer using a direct-mapped cache has \$2^{24}\$ words of main memory and a cache of 256 blocks. Each cache block contains 64 words.

*

*How many blocks of main memory are there?

*What is the format of a memory address as seen by the cache? (What are the sizes of the tag, block, and word fields?)

*To which block will the memory reference 0x01BD36 map?

A: For X addresses, where 2^N+1 < X < 2^N, N address lines are not sufficient, N+1 is sufficient (but leaves some address space unused). Hence you have no other option than to use (at least) N+1 address lines.

A: Solutions:

*

*B = Capacity (C) / block size (b)
B = 224 / 26
B = 218 blocks

*224 = 24-bit address
T = 24 - (8 + 6) = 24 - 14 = 10 bits
B = 256 = 28 = 8 bits
W = 64 = 26 = 6 bits

*0x01BD36 = 0000000110 11110100 1101102
T = 00000001102 (10 bits)
B = 111101002 (8 bits)
W = 1101102 (6 bits)
B = 111101002 = 244
Therefore, 0x01BD36 maps to cache block 244.


text:
Q: Using JMH as a framework for performance testing on functional/user level. Is it wrong? I want to use JMH as a framework for performance testing on functional/user level for web application. Imagine me using JMH to, say, measure how long it takes from the moment when 100 users click "Post Your Question" on this site concurrently, to the moment when user sees their question posted.
Is this entirely wrong? What are the drawbacks of such approach?

*

*I do not expect a nanosecond accuracy for those tests: half a second to a second accuracy are just fine.

*I created a first realistic test, and really liked how it looked / worked - exactly what I need. But am I missing some big trouble ahead by using micro-benchmark framework for what it's not intended to do?

*Not looking for tool recommendations

A: Now using this approach for approximately 6 months, I want to say that I still did not see any drawbacks. A few things I learned:

*

*Even though on functional/user level of accuracy is lower, it's important to learn how various configuration parameters work (especially JVM-related, e.g. fork). They may influence how you build your tests, how do you run them, and what do you measure.

*JMH is really lightweight and efficient, so comparing to the results obtained using other frameworks may not be valid (basically we saw 10-20% performance boost when running with JMH); I had to establish a new baseline.

*JMH Jenkins plug-in helps with visualizing the results


text:
Q: Split a string on each "X" I'm trying to split a string on each Cell\s\d+ without success.
My attempt was:
result = re.split(r"Cell\s\d+ - Address: .*?Cell\s\d+", subject, 0, re.DOTALL | re.MULTILINE)

But it skips every 1 record, which makes sense, because I'm including part of the next match on the regex.
I've also tried positive/negative lookahead and lookbehind without luck.
Please note that records end differently.
How do I split the string below?
wlan0     Scan completed :
Cell 01 - Address: 00:24:01:B6:4F:E1
Channel:3
Frequency:2.422 GHz (Channel 3)
Quality=70/70  Signal level=-40 dBm
Encryption key:on
ESSID:"DLink-XXXXXX"
Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 6 Mb/s; 9 Mb/s
11 Mb/s; 12 Mb/s; 18 Mb/s
Bit Rates:24 Mb/s; 36 Mb/s; 48 Mb/s; 54 Mb/s
Mode:Master
Extra:tsf=0000000000000000
Extra: Last beacon: 20ms ago
IE: Unknown: 000C444C696E6B2D423634464531
IE: Unknown: 010882848B0C12961824
IE: Unknown: 030103
IE: WPA Version 1
Group Cipher : TKIP
Pairwise Ciphers (1) : TKIP
Authentication Suites (1) : PSK
IE: Unknown: 2A0100
IE: Unknown: 32043048606C
IE: Unknown: DD180050F2020101050003A4000027A4000042435E0062322F00
IE: Unknown: DD0900037F01010000FF7F
IE: Unknown: DD0A00037F04010000000000
Cell 02 - Address: 06:24:01:B6:4F:E1
Channel:3
Frequency:2.422 GHz (Channel 3)
Quality=70/70  Signal level=-39 dBm
Encryption key:on
ESSID:"WIFI_1"
Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 6 Mb/s; 9 Mb/s
11 Mb/s; 12 Mb/s; 18 Mb/s
Bit Rates:24 Mb/s; 36 Mb/s; 48 Mb/s; 54 Mb/s
Mode:Master
Extra:tsf=0000000000000000
Extra: Last beacon: 20ms ago
IE: Unknown: 00015F
IE: Unknown: 010882848B0C12961824
IE: Unknown: 030103
IE: IEEE 802.11i/WPA2 Version 1
Group Cipher : TKIP
Pairwise Ciphers (1) : TKIP
Authentication Suites (1) : PSK
IE: Unknown: 2A0100
IE: Unknown: 32043048606C
IE: Unknown: DD180050F2020101050003A4000027A4000042435E0062322F00
IE: Unknown: DD0900037F01010000FF7F
IE: Unknown: DD0A00037F04010000000000
Cell 03 - Address: BC:4D:FB:4F:C3:B8
Channel:7
Frequency:2.442 GHz (Channel 7)
Quality=69/70  Signal level=-41 dBm
Encryption key:on
ESSID:"WIFI_2"
Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 11 Mb/s; 9 Mb/s
18 Mb/s; 36 Mb/s; 54 Mb/s
Bit Rates:6 Mb/s; 12 Mb/s; 24 Mb/s; 48 Mb/s
Mode:Master
Extra:tsf=0000000000000000
Extra: Last beacon: 20ms ago
IE: Unknown: 00083F3F3F3F3F3F3F3F
IE: Unknown: 010882848B961224486C
IE: Unknown: 030107
IE: Unknown: 32048C98B060
IE: Unknown: DD270050F204104A0001101044000102104700102880288028801880A880BC4DFB4FC3B8103C000101
IE: Unknown: 050402030080
IE: Unknown: 2A0100
IE: Unknown: 2D1A8C0116FFFF000000000000000000000000000000000000000000
IE: Unknown: 3D1607000400000000000000000000000000000000000000
IE: Unknown: 7F0101
IE: IEEE 802.11i/WPA2 Version 1
Group Cipher : CCMP
Pairwise Ciphers (1) : CCMP
Authentication Suites (1) : PSK
IE: Unknown: DD180050F2020101800003A4000027A4000042435E0062322F00
IE: Unknown: 0B0506001B127A
IE: Unknown: DD07000C4300000000
Cell 04 - Address: BC:4D:FB:4F:C3:B9
Channel:7
Frequency:2.442 GHz (Channel 7)
Quality=68/70  Signal level=-42 dBm
Encryption key:off
ESSID:"NOS_WIFI_Fon"
Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 11 Mb/s; 9 Mb/s
18 Mb/s; 36 Mb/s; 54 Mb/s
Bit Rates:6 Mb/s; 12 Mb/s; 24 Mb/s; 48 Mb/s
Mode:Master
Extra:tsf=0000000000000000
Extra: Last beacon: 20ms ago
IE: Unknown: 000C4E4F535F574946495F466F6E
IE: Unknown: 010882848B961224486C
IE: Unknown: 030107
IE: Unknown: 32048C98B060
IE: Unknown: 050401030000
IE: Unknown: 2A0100
IE: Unknown: 2D1A8C0116FFFF000000000000000000000000000000000000000000
IE: Unknown: 3D1607000400000000000000000000000000000000000000
IE: Unknown: 7F0101
IE: Unknown: DD180050F2020101800003A4000027A4000042435E0062322F00
IE: Unknown: 0B0506001B127A
IE: Unknown: DD07000C4300000000

A: As an alternative approach, you could use Python's groupby() function to spot the blocks as follows:
from itertools import groupby

subject = """ --- all the text --- """    # read in, or add text here
lines = iter(subject.splitlines())
data = [list(g) for k, g in groupby(lines, lambda x: x.startswith('Cell '))][1:]
cells = [l1 + l2 for l1, l2 in zip(*[iter(data)] * 2)]

for cell in cells:
    print cell

So if subject contains all the text from a file, you would get four cells each containing a list of lines for each:
['Cell 01 - Address: 00:24:01:B6:4F:E1', 'Channel:3', 'Frequency:2.422 GHz (Channel 3)', 'Quality=70/70  Signal level=-40 dBm', 'Encryption key:on', 'ESSID:"DLink-XXXXXX"', 'Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 6 Mb/s; 9 Mb/s', '11 Mb/s; 12 Mb/s; 18 Mb/s', 'Bit Rates:24 Mb/s; 36 Mb/s; 48 Mb/s; 54 Mb/s', 'Mode:Master', 'Extra:tsf=0000000000000000', 'Extra: Last beacon: 20ms ago', 'IE: Unknown: 000C444C696E6B2D423634464531', 'IE: Unknown: 010882848B0C12961824', 'IE: Unknown: 030103', 'IE: WPA Version 1', 'Group Cipher : TKIP', 'Pairwise Ciphers (1) : TKIP', 'Authentication Suites (1) : PSK', 'IE: Unknown: 2A0100', 'IE: Unknown: 32043048606C', 'IE: Unknown: DD180050F2020101050003A4000027A4000042435E0062322F00', 'IE: Unknown: DD0900037F01010000FF7F', 'IE: Unknown: DD0A00037F04010000000000']
['Cell 02 - Address: 06:24:01:B6:4F:E1', 'Channel:3', 'Frequency:2.422 GHz (Channel 3)', 'Quality=70/70  Signal level=-39 dBm', 'Encryption key:on', 'ESSID:"WIFI_1"', 'Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 6 Mb/s; 9 Mb/s', '11 Mb/s; 12 Mb/s; 18 Mb/s', 'Bit Rates:24 Mb/s; 36 Mb/s; 48 Mb/s; 54 Mb/s', 'Mode:Master', 'Extra:tsf=0000000000000000', 'Extra: Last beacon: 20ms ago', 'IE: Unknown: 00015F', 'IE: Unknown: 010882848B0C12961824', 'IE: Unknown: 030103', 'IE: IEEE 802.11i/WPA2 Version 1', 'Group Cipher : TKIP', 'Pairwise Ciphers (1) : TKIP', 'Authentication Suites (1) : PSK', 'IE: Unknown: 2A0100', 'IE: Unknown: 32043048606C', 'IE: Unknown: DD180050F2020101050003A4000027A4000042435E0062322F00', 'IE: Unknown: DD0900037F01010000FF7F', 'IE: Unknown: DD0A00037F04010000000000']
['Cell 03 - Address: BC:4D:FB:4F:C3:B8', 'Channel:7', 'Frequency:2.442 GHz (Channel 7)', 'Quality=69/70  Signal level=-41 dBm', 'Encryption key:on', 'ESSID:"WIFI_2"', 'Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 11 Mb/s; 9 Mb/s', '18 Mb/s; 36 Mb/s; 54 Mb/s', 'Bit Rates:6 Mb/s; 12 Mb/s; 24 Mb/s; 48 Mb/s', 'Mode:Master', 'Extra:tsf=0000000000000000', 'Extra: Last beacon: 20ms ago', 'IE: Unknown: 00083F3F3F3F3F3F3F3F', 'IE: Unknown: 010882848B961224486C', 'IE: Unknown: 030107', 'IE: Unknown: 32048C98B060', 'IE: Unknown: DD270050F204104A0001101044000102104700102880288028801880A880BC4DFB4FC3B8103C000101', 'IE: Unknown: 050402030080', 'IE: Unknown: 2A0100', 'IE: Unknown: 2D1A8C0116FFFF000000000000000000000000000000000000000000', 'IE: Unknown: 3D1607000400000000000000000000000000000000000000', 'IE: Unknown: 7F0101', 'IE: IEEE 802.11i/WPA2 Version 1', 'Group Cipher : CCMP', 'Pairwise Ciphers (1) : CCMP', 'Authentication Suites (1) : PSK', 'IE: Unknown: DD180050F2020101800003A4000027A4000042435E0062322F00', 'IE: Unknown: 0B0506001B127A', 'IE: Unknown: DD07000C4300000000']
['Cell 04 - Address: BC:4D:FB:4F:C3:B9', 'Channel:7', 'Frequency:2.442 GHz (Channel 7)', 'Quality=68/70  Signal level=-42 dBm', 'Encryption key:off', 'ESSID:"NOS_WIFI_Fon"', 'Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 11 Mb/s; 9 Mb/s', '18 Mb/s; 36 Mb/s; 54 Mb/s', 'Bit Rates:6 Mb/s; 12 Mb/s; 24 Mb/s; 48 Mb/s', 'Mode:Master', 'Extra:tsf=0000000000000000', 'Extra: Last beacon: 20ms ago', 'IE: Unknown: 000C4E4F535F574946495F466F6E', 'IE: Unknown: 010882848B961224486C', 'IE: Unknown: 030107', 'IE: Unknown: 32048C98B060', 'IE: Unknown: 050401030000', 'IE: Unknown: 2A0100', 'IE: Unknown: 2D1A8C0116FFFF000000000000000000000000000000000000000000', 'IE: Unknown: 3D1607000400000000000000000000000000000000000000', 'IE: Unknown: 7F0101', 'IE: Unknown: DD180050F2020101800003A4000027A4000042435E0062322F00', 'IE: Unknown: 0B0506001B127A', 'IE: Unknown: DD07000C4300000000']


text:
Q: Instagram Type Mode View I need to create Text mode same as Instagram Type Mode in Status .
I created it from this reference. I can manage the size with respect to width but can't control the height ratio, need logic to control both height and width.


text:
Q: What is the difference between the 'pkgs' directory and the 'site-packages' directory? [Anaconda] [Anaconda3, Windows]
What are the explicit differences between the directories 'site-packages' and 'pkgs' in my Anaconda3 (base python env) folder?
Additionally, I would like to know why 'pkgs' is significantly larger in size than 'site-packages.' On my disk 'pkgs' is 8.0 GB with 112,005 items while 'site-packages' is 1.9 GB with 57,580 items.
I have read the following link :
What's the difference between anaconda2/Lib/site-packages/<pkg> and anaconda2/pkgs/<pkg>?
I assume the difference to have to do with caching. Any knowledge or insight is appreciated.

A: packages in the Anaconda3/Lib/site-packages folder is where Python looks to import packages.
whereas packages in the Anaconda3/pkgs folder are the packages that are downloaded and extracted by Conda when you specify an update or install.
It all Depends on your settings, the folders in Anaconda2/Lib/site-packages may be symlinks or hardlinks to the equivalent folder in Anaconda2/pkgs, or it might be a copy.
See the documentation for clear picture.


text:
Q: Iterar en pandas millones de datos de forma óptima Tengo un DataFrame con casi 2 millones de filas, que tiene una columna para el ID, una columna para la fecha y una descripción de cada ID.
Cada ID debería tener una única descripción, sin embargo se da el caso de que hay ID que tienen o la descripción vacía en alguna de sus fechas o tienen más de una descripción que ha ido cambiando con el tiempo.
Lo que busco es poner a cada ID la descripción más actual (siempre que no sea una celda vacía, en caso de que sea vacía debería ser la primera descripción no vacía). He ordenado el DF por ID y por Fecha, de tal forma que para cada "grupo" de ID, la primera descripción es la más actual.
El problema lo tengo a la hora de coger esa descripción y sustituirla en el resto de filas del mismo ID. El proceso con un bucle FOR me tarda más de 30 minutos, por lo que necesito una solución mucho más eficiente.
Has ahora, mi procedimiento ha sido:

*

*sacar una lista con los ID únicos

*Iterar con un bucle for esos ID, y con un .loc sacar el campo descripción. Si la descripción más reciente es nula, le pongo un if para que pille la segunda descripción.

for id in list(df.columnid.unique()):

    if df.loc[(df.columnid == id).description.unique()[0] != "":
        description = df.loc[(df.columnid == id).description.unique()[0]

    elif df.loc[(df.columnid == id).description.unique()[0] == "" and len(df.loc[(df.columnid == id).description.unique()) >1:
        description = df.loc[(df.columnid == id).description.unique()[1]

*

*Guardar tanto el ID del producto como la descripción en un diccionario:

dicc[id] = dicc.get(id, description)

Después, con un .loc, con un .isin y un map reemplazo los valores obtenidos en la columna.
Este procedimiento funciona, pero no es nada óptimo y necesito saber cómo se podría hacer de mejor forma sin tardar más de 30 min.
df.loc[df['columnid'].isin(dicc.keys()), 'description'] = df['columnid'].map(dicc)

Un ejemplo del DataFrame (sería lo mismo pero con millones de filas) sería:
df = pd.DataFrame({"columnid": ["2321fdsf", "2321fdsf", "3gsdfer3", "4gdsfg44", "4gdsfg44", "4gdsfg44", "7fg45d"],
                 "date": ["2022-11-16","2022-10-07","2022-09-02","2021-12-04","2021-09-23","2021-03-06","2021-03-15"],
                 "description": ["aaa", "bbb", "abc", "eee", "", "aqwert", "yuiop"],
                 })

    columnid       date     description
0   2321fdsf    2022-11-16  aaa
1   2321fdsf    2022-10-07  bbb
2   3gsdfer3    2022-09-02  abc
3   4gdsfg44    2021-12-04  eee
4   4gdsfg44    2021-09-23
5   4gdsfg44    2021-03-06  aqwert
6   7fg45d      2021-03-15  yuiop

El resultado buscado tendría que ser:
    columnid       date     description
0   2321fdsf    2022-11-16  aaa
1   2321fdsf    2022-10-07  aaa
2   3gsdfer3    2022-09-02  abc
3   4gdsfg44    2021-12-04  eee
4   4gdsfg44    2021-09-23  eee
5   4gdsfg44    2021-03-15  eee
6   7fg45d      2021-03-06  yuiop

Gracias

A: En esta solución se usan solo operaciones de pandas, debería tener mejor rendimiento:
import pandas as pd
import numpy as np
df = pd.DataFrame({"columnid": ["2321fdsf", "2321fdsf", "3gsdfer3", "4gdsfg44", "4gdsfg44", "4gdsfg44", "7fg45d"],
                 "date": ["2022-11-16","2022-10-07","2022-09-02","2021-12-04","2021-09-23","2021-03-06","2021-03-15"],
                 "description": ["aaa", "bbb", "abc", "eee", "", "aqwert", "yuiop"],
                 })

"""
Remover del dataframe las filas que tengan descripcion vacía
para asegurar que en cada columnid siempre habrá una descripción
para usar.
"""
df_new = df.replace('', np.nan)
df_new.dropna(inplace=True)
"""
Como el dataframe está ordenado por fecha siendo la reciente
la de arriba entonces se agrega un número a las filas
según su agrupación por columid, de esta forma la más reciente
siempre será el 0
"""
df_new['row_number'] = df_new.groupby('columnid').cumcount()
"""
Se crea un nuevo dataframe que contenga solo el columnid
y la descripción más reciente, para eso se filtran solo
las filas que tengan `row_number` == 0
"""
recent_descriptions = df_new[df_new['row_number'] == 0][['columnid','description']]
"""
Se fusiona el dataframe con las descripciones recientes y el dataframe original
se usa `columnid` para relacionarlos
"""
merge = pd.merge(df, recent_descriptions,on='columnid')
"""
En este punto se puede ver la columna original `description`
del dataframe original y la columna `description` nueva en la que
se aplica la descripción más reciente
"""
print(merge)
"""
Completar el formato remover y renombrar columnas
"""
df_final = merge.drop('description_x', axis=1).rename(columns={'description_y': 'description'})
print(df_final)

A: Buen día,
Tengo una propuesta un poco diferente y comparé la eficiencia con el código de las otras respuestas utilizando timeit
Puedes utilizar pandas.DataFrame.groupby en combinación con pandas.DataFrame.transform y utilizar la función first adentro de transform para obtener el primer elemento de cada grupo y asignarlo directamente a la columna "description".
Para que transform tome el primer valor válido podemos reemplazar todos los string vacíos por NaN antes de obtener la descripción.
Ejemplo:
Nota: agregué una fila extra para mostrar que también funciona en caso de que el primer valor de un grupo sea un string vacío.
import pandas as pd
import numpy as np

df = pd.DataFrame({"columnid": ["2321fdsf", "2321fdsf", "3gsdfer3", "4gdsfg44", "4gdsfg44", "4gdsfg44", "7fg45d", "7fg45d"],
                 "date": ["2022-11-16","2022-10-07","2022-09-02","2021-12-04","2021-09-23","2021-03-06", "2022-05-13","2021-03-15"],
                 "description": ["aaa", "bbb", "abc", "eee", "", "aqwert", "", "yuiop"],
                 })

# Forzamos a que haya NaN en vez de cadenas vacías, para permitir el fillna
df["description"] = df["description"].replace("", np.nan)

df["description"] = df.groupby(by = "columnid")['description'].transform('first')
print(df)

Esto imprime el siguiente dataframme:
   columnid        date description
0  2321fdsf  2022-11-16         aaa
1  2321fdsf  2022-10-07         aaa
2  3gsdfer3  2022-09-02         abc
3  4gdsfg44  2021-12-04         eee
4  4gdsfg44  2021-09-23         eee
5  4gdsfg44  2021-03-06         eee
6    7fg45d  2022-05-13       yuiop
7    7fg45d  2021-03-15       yuiop

Comparación de tiempos
La solución propuesta en esta respuesta arroja el siguiente resultado:
430 µs ± 2.54 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)

La solución propuesta por el compañero  @Abulafia arroja el siguiente resultado:
1.64 ms ± 2.43 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)

La solución propuesta por el compañero @Lobos arroja el siguiente resultado:
3.44 ms ± 9.73 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

En conclusión, de acuerdo a los resultados arrojados por timeit la solución propuesta en esta respuesta es más rápida, sería cuestión que probaras las 3 y vieras cuál te funciona mejor.

A: Una máxima de pandas es: para optimizar los iteraciones, no hagas iteraciones :-)
Utiliza operaciones pandas que están vectorizadas (esto es, las iteraciones las hace pandas por debajo, implementadas en C y de forma super eficiente).
Una idea, que funciona siempre que se cumplan las siguientes condiciones:

*

*El datafram de entrada viene ordenado de modo que, aunque los ids puedan no estar agrupados, las fechas de cada id sí que están ordenadas, siendo la más reciente la primera. Si esta condición no se cumpliera, se podría forzar fácilmente con un df = df.sort_values(by=["columnid", "date"], ascending=(True, False)).

*En la columna "description", para los casos en que no hay descripción, hay almacenado un valor NaN. Esto es fácil de forzar mediante un .replace().

Bajo estas condiciones mi idea es:

*

*Realizar un groupby() por la columna "columind". Eso nos dará una serie de "mini-dataframes" en cada uno de los cuales se cumple que:

*

*La columna "columnid" tiene el mismo valor repetido

*La columna "date" está ordenada de más reciente a más antigua

*La columna "description" contiene al menos un valor no-vacio

*En cada mini-dataframe, realizar una operación fillna() sobre la columna "description" con la estrategia "bfill". Esto rellenará todos los NaN que encuentre con el siguiente valor no NaN de esa misma columna. Así, si la fecha más reciente tenia un NaN tras el fillna() tendrá el valor de la siguiente fecha con descripción disponible.

*En cada mini-dataframe reemplazar lo que haya en la columna "description" de todas las filas, por lo que hay en esa columna en la primera fila (que corresponde a la fecha más reciente).
Los dos últimos puntos son muy largos de explicar con palabras, pero se resumen en una función python de un par de líneas (siendo g, el parámetro, cada uno de los mini-dataframes que generará .groupby()):
def fill_descriptions(g):
    g.description = g.description.fillna(method="bfill").iloc[0]
    return g

Solo queda aplicar esa función al resultado del groupy, lo cual es una línea:
result = df.groupby(by="columnid").apply(fill_descriptions)

Demo
import pandas as pd
import numpy as np

df = pd.DataFrame({"columnid": ["2321fdsf", "2321fdsf", "3gsdfer3", "4gdsfg44", "4gdsfg44", "4gdsfg44", "7fg45d"],
                 "date": ["2022-11-16","2022-10-07","2022-09-02","2021-12-04","2021-09-23","2021-03-06","2021-03-15"],
                 "description": ["aaa", "bbb", "abc", "eee", "", "aqwert", "yuiop"],
                 })
# Forzamos a que haya NaN en vez de cadenas vacías, para permitir el fillna
df.description = df.description.replace("", np.nan)

def fill_descriptions(g):
    g.description = g.description.fillna(method="bfill").iloc[0]
    return g

result = df.groupby(by="columnid").apply(fill_descriptions)
print(result)

Resultado:
   columnid        date description
0  2321fdsf  2022-11-16         aaa
1  2321fdsf  2022-10-07         aaa
2  3gsdfer3  2022-09-02         abc
3  4gdsfg44  2021-12-04         eee
4  4gdsfg44  2021-09-23         eee
5  4gdsfg44  2021-03-06         eee
6    7fg45d  2021-03-15       yuiop


text:
Q: My changenotifierprovider is not updating. Not sure why Here is my change Notifier class.
class UserChamaNotifier with ChangeNotifier {
    final List<UserChama> _userChamaList = [];

      UnmodifiableListView<UserChama> get userchamaListy =>
          UnmodifiableListView(_userChamaList);

      void addUserChama(UserChama userchama) {
        _userChamaList.add(userchama);
        notifyListeners();
      }
 }

I have created the provider in main.dart:
Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(
          create: (context) => _appStateManger,
        ),
        ChangeNotifierProvider(
          create: (context) => _profileManager,
        ),
        ChangeNotifierProvider(
          create: (context) => UserChamaNotifier(),
        )
      ],

Then I proceed to add a chama object to my list:
UserChama userChama =
          UserChama(id: s['Id'], phone: s['Phone'], name: s['Name']);
      print(userChama.phone);
      Provider.of<UserChamaNotifier>(context).addUserChama(userChama);

Here i try to access the list through the provider:
class ChamaList extends StatelessWidget {
  const ChamaList({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    UserChamaNotifier userChamaNotifier =
        Provider.of<UserChamaNotifier>(context, listen: true);
    return Text(userChamaNotifier.userchamaListy.length.toString());
  }
}

At this point, i have experimented alot and i still don't have the correct way of implementation.

A: While adding data, set listen:false
  Provider.of<UserChamaNotifier>(context,listen:false)
          .addUserChama(userChama);

Check more how listen: false works when used with Provider.of(context, listen: false).


text:
Q: How can I sort by field position in querydsl? In JPQL I can use the following select u from Entity u order by u.field1, 1.
This ensures that the back-end mysql database will always return the result in the exact same order (e.g. in case u.field1 has duplicates).
At position 1 I always keep the PK(id).
How can I achieve the same (use positional sorting) with querydsl?
P.S. Sorting code is dynamically generated, so I want to avoid the requirement to provide the PK as an extra parameter to the SortUtil.

A: From what I understand, your requirement is to order by a database column, then by a number you provide as an argument. I think this will work, I've passed 1L into Expressions.constant but obviously replace this with your dynamically generated field.
.orderBy(someRelationalPathBase.field1.asc(), new OrderSpecifier<>(Order.ASC, Expressions.constant(1L)))


text:
Q: Partial matching to route to same component is possible to do something with Angular route like this
    {
        path: 'my-',
        loadChildren: './pages/my-stuff/my-stuff.module#MyStuffPageModule'
    },

then when I navigate with different paths like my-orders, my-repairs.. this match with the same route?
thanks

A: You can use URL matcher function of Route object.
The matcher function returns UrlMatchResult Object or falsy value conditionally.
https://angular.io/api/router/Route#matcher
If you are going to use this, you can't use path field.
Here is an example to begin with. https://stackblitz.com/edit/angular7-routes-5upyij


text:
Q: how to orderby after applying limit in sql I need to get the information from DB in such a way, the limit should be 3 rows and out of which i want to sort by descending order.
I used
select * from table where coloumn = 'Myfilter' order by serialNumber desc limit 3

after  the execution I am not getting the latest three records rather the first three records ordered by descending.

A: Applying limit before order by
SELECT * FROM (SELECT * FROM table WHERE coloumn = 'Myfilter' ORDER BY serialNumber LIMIT 3) a ORDER BY serialNumber DESC

A: This query solves my question thank you all for suggestions,
SELECT * FROM (SELECT * FROM table WHERE coloumn='myFilter' ORDER BY serialnumber desc LIMIT 3) a ORDER BY serialnumber asc

the query uses to select the latest 3 rows ordered by big to small serial number then again the selected rows order where reversed, thnx @Kelvin Barsana

A: "SELECT * FROM table WHERE coloumn = 'Myfilter' ORDER BY serialNumber DESC LIMIT 3";


text:
Q: PHP spec - array of specific types In phpspec how would a spec look that tested that a class property contained an array of specific types?
for example:
class MyClass
{
   private $_mySpecialTypes = array();

   // Constructor ommitted which sets the mySpecialTypes value

   public function getMySpecialTypes()
   {
      return $this->_mySpecialTypes;
   }
}

My spec looks like this:
public function it_should_have_an_array_of_myspecialtypes()
{
    $this->getMySpecialTypes()->shouldBeArray();
}

But i want to make sure that each element in the array is of type MySpecialType
Whats the best way to do this in phpspec?

A: You can use an inline matcher:

namespace spec;

use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

use MySpecialType;

class MyArraySpec extends ObjectBehavior
{
    function it_should_have_an_array_of_myspecialtypes()
    {
        $this->getMySpecialTypes()->shouldReturnArrayOfSpecialTypes();
    }

    function getMatchers()
    {
        return array(
            'returnArrayOfSpecialTypes' => function($mySpecialTypes) {
                foreach ($mySpecialTypes as $element) {
                    if (!$element instanceof MySpecialType) {
                        return false;
                    }
                }
                return true;
            }
        );
    }
}

A: PHP has no Array of specific types, therefore PHP spec can not test for that directly. You could port the obligatory code over and over and push it into your specs just to control your classes behave like you spec'ed them, or you can create such an array type and spec it.
That would allow you to move the specs to the single object of such a type, spec it once and use it everywhere.
A perhaps well looking base-type is SPLs' SplObjectStorage from your you can extend and make the type a parameter or the first addition the type to accept.


text:
Q: Excel.Application.WorksheetFunction.RTD is not recalculated when double click on the function I m writing an Excel plugin that uses a custom written RTD Server and to call ConnectData function of that RTD Server, I use Excel.Application.WorksheetFunction.RTD in VBA passing required parameters to the function.
All the functionality of RTD is working fine, but if I double-click and press enter on an RTD function in Excel (In other words, when parameters do not get changed), Excel.Application.WorksheetFunction.RTD is called but ConnectData of RTD Server does not get called.
Is there anyway of getting ConnectData called in such a situation where parameters aren t changed?
Thanks

A: I call Application.CalculateFull from Visual Basic. I have found that triggers the RTD function being called again. I then have a button on the spreadsheet which calls a macro that contains Application.CalculateFull. Anytime I want to restart, I press the button.

A: An RTD topic is created for each unique combination of topic parameters of the RTD function. When you re-enter the same function call, the RDF function is called but it does not create a new topic.
ConnectData is called only when a new topic is created.
That means if you enter the same RTD function call in multiple cells, they will all share the same RTD topic. ConnectData will only be called once.


text:
Q: Remove ellipsis (&helip;) after sub-string concatenation I am concatenating two sub-strings with an ellipsis (...) added at the end of the first sub-string. However I want this elipsis to be removed after the concatenation.
Is this possible via a script or other means, Thanks:
<?php echo substr($post_text_result2, 0, 400) . "…";?>
<?php echo substr($post_text_result2, 400, 5000);?>
:
str_replace deletes the elipsis like requested, however does not fully work in my situation:
The code below works however, The first sub-string is repeated. I need a way to remove the first sub-string.
<?php
$string = substr($post_text_result2, 0, 400) . "…";
echo $string;
?>

<?php
$string= str_replace('…','',$string); echo $string;
echo $string;
echo substr($post_text_result2, 400, 5000);
?>

A: You can store the length of the first string A and then build a new string concatenating 2 substrings:
substring 1 from 0 until length(A) - 3

substring 2 from length(A) until total length

You also could use a regex and replace "..." with "", but that could remove other "..." which is maybe unwanted.
Sorry for no code, I can't PHP but you know how to do it ;)

A: easy
<?php

$string = substr($post_text_result2, 0, 400) . "…";
$string = str_replace('…','',$string);

?>

If you want an ellipsis always at the end, just do this:
<?php

$string = substr($post_text_result2, 0, 400) . "…";
$string = str_replace('…','',$string) . "…";

?>


text:
Q: React onchange event: this.setState() not setting state? I am trying to set state via this.setState() of username and password when user types a value in username and password field. I am using onChange event type

ISSUE: the state is not changing. I log this.state.data.username in the render().

import React, { Component } from "react";
import { Form, Button } from "react-bootstrap";
import { Link } from "react-router-dom";

var Joi = require("joi-browser");

class Login extends Component {
  state = {
    data: { username: "a", password: "b " },
    errors: {
      email: "ddsfds",
      password: "aaaa"
    }
  };

  schema = {
    username: Joi.string()
      .min(0)
      .required()
      .label("Username"),
    password: Joi.string()
      .required()
      .label("Password")
  };

  handleSubmit = event => {
    event.preventDefault();
    console.log("submited.", event.target);

    const { data } = this.state;

    const { err } = Joi.validate(data, this.schema);

    if (err) {
      console.log("error is true", err);
    } else {
      console.log("not true");
    }
  };

  handleEmailOnChange = event => {
    const inputUsername = event.target.value;
    console.log("input is...", inputUsername);

    this.setState({ username: inputUsername });
  };

  handlePassword = event => {
    const passwordInput = event.target.value;

    this.setState({ password: passwordInput });
  };

  render() {
    console.log("username ", this.state.data.username);
    return (

        <Form>
          <Form.Group controlId="formBasicEmail">

Sign In

            <Form.Control
              type="email"
              placeholder="Enter email"
              onChange={this.handleEmailOnChange}
            />
            {/* {this.state.errors.username}  */}
          </Form.Group>

          <Form.Group controlId="formBasicPassword">
            <Form.Control
              type="password"
              placeholder="Password"
              onChange={this.handlePassword}
            />
          </Form.Group>

            <Link to="/register" type="button" className="btn btn-warning">
              Register Account
            </Link>
            <Button
              variant="primary"
              className="m-2"
              type="submit"
              onClick={this.handleSubmit}
            >
              Submit
            </Button>

        </Form>

    );
  }
}

export default Login;

A: You aren't updating the state correctly or not using it correctly. The state in your constructor has data object with username and password
 handleEmailOnChange = event => {
    const inputUsername = event.target.value;
    console.log("input is...", inputUsername);

    this.setState(prev => ({data: {...prev.data, username: inputUsername } }));
  };

  handlePassword = event => {
    const passwordInput = event.target.value;
    this.setState(prev => ({data: {...prev.data, password: passwordInput } }));
  };

A: The state you are changing is this.state.username, the one you console is this.state.data.username.
To set data in your state, use:
this.setState(prevState => ({
  data: {
    username: inputUsername,
    ...prevState.data
  }
})


text:
Q: Remove the "C:\" from 'Directory.GetParent' C# How do I remove "C:\" from a Directory.GetParent command in c#?
For example:
The command returns: "C:\Folder1\Folder2"
And I want it to return "Folder1\Folder2"

A: You can remove the Path.GetPathRoot from the original string:
string root = Path.GetPathRoot(folder);

if (root != null)
{
    folder = folder.Substring(root.Length);
}

A: If you want remove C:\ why don't you use string.Remove like so:
string folderName = @"C:\f1\f2";
folderName = folderName.Replace(@"C:\", "");
//Outputs f1\f2

A: try this it will remove your first three charters
folderName = folderName.Substring(3);


text:
Q: Team administrator vs. project administrator TFS There doesn't seem to be too much documentation on team administrators, but if I went into my team's page and added a user as an administrator on the left-hand side, it's not making them project administrators, just something called a team administrator. What are the differences between the team administrator and project administrator with permissions?

A: Project administrators can administer a project, team administrators are a new (2012+) role. A project can have multiple teams so their administration level is lower.
A project admin can therefore administer multiple teams.
A team administrator can administer the teams backlog, capacity, work items etc.

A: Look for a first question on msdn page.
How do permissions for Team Administrators compare with those set for Project Administrators?


text:
Q: How to properly use random projection to significantly reduce the dimensions of a vector? In my application, I have a vectors of arbitrary length, but that normally fall in the range of between 0 and 500 elements. Each value in the vector is between -1 and 1. I am computing the similarity of two arbitrary vectors with the following SQL:
1 - SUM(ABS(v1.value - v2.value)) / COUNT(*)
(where v1.value and v2.value refer to values of the same matching item)
However, the dimensions are too large for these on-the-fly similarity calculations, so I would like to perform dimension reduction to improve performance.
I found out about random projection, and I am trying to apply it, but I'm not having much luck it seems, and was wondering if anyone could spot the flaw in my logic.
First, I expensively computed the similarity between X and Y (two vectors, each with 100 dimensions). This was so that I could know what value I should be shooting for after performing dimension reduction.
I first generated 8 vectors of the maximum possible length (100), all filled with random values between -1 and 1. Let's call them V1 to V8.
I then computed the similarity of X against V1, V2, V3, V4, V5, V6, V7, and V8, and saved that vector of respective results as X1. I also computed the similarity of Y against V1, V2, V3, V4, V5, V6, V7, and V8 and saved that vector of respective results as Y1.
I then computed the similarity of X1 against Y1 with the above SQL (the same method used to compute the similarity between X and Y), but got a much different result than when I computed the similarity of X against Y. This is unfortunate because I think random projection is quoted as being surprisingly accurate, so I was hoping the similarity between X and Y would be very close to the similarity between X1 and Y1.
To clarify, X and Y are the original vectors, and X1 and Y1 are the resultant "reduced dimension" vectors.
So my questions are:
1) Did I do this properly? I'm not sure if I fully understand random projection yet so maybe I messed up a step
2) How do you determine how many random vectors to compute against? Most of my vectors are going to have between 100 and 300 dimensions. How many dimensions should my reduced vectors have and still be reasonably accurate?
3) Is this possibly not working because I am using the Manhattan Distance instead of the Euclidean Distance? I initially chose the former because the computation is much simpler and I needed it to be fast.

A: I don't know a lot (indeed, hardly anything) about random projection, but I'm guessing that the projections are supposed to be orthogonal projections. That would require that your $V$ vectors be unit-length and mutually perpendicular (with respect to the inner product you're using).
A deeper problem is that you've got vectors in various-dimensional spaces, and you're putting them all into one large-dimensional space (by filling with zeroes?) and computing inner products --- that seems like a very peculiar choice. Before advising further on how to make random projection work, I'd like to know the nature of the data we're working with. For instance, it sounds as if your resulting dataset might have a real "preference" for certain axis-aligned subspaces (those consisting of vectors with lots of zeroes at the ends). It'd be useful to know whether that has any interactions with the assumptions of the theorems about random projection.
Finally, using the Manhattan metric might have serious consequences as well.
Short summary: read the theorems on random projections and look at their hypotheses closely to see whether they apply to your situation.


text:
Q: Changing a power supply from DC output to AC output I've read an article on changing a 12 V AC-DC power supply to 9 V AC-AC by just tapping the transformer output directly, bypassing diodes and capacitor.
This only applies to older type AC power adaptors that have a large, heavy transformer. Does this modification change any aspects of the amperage? I'm trying to modify a 12 V, 1.6 A DC output power supply for a device requiring 9 V 2.1 A AC.
I also want to find out if amperage ratings for devices have any safety factor figured in, allowing for any lower amperage tolerance.

A: In general, you can't increase the current rating for the secondary unless you rewind the entire secondary. The manufacturer has placed a maximum current rating on the secondary for a (presumably) good reason, probably rated to the thickness of the wire. Removing some of the turns to lower the secondary voltage does not change the current carrying capability of that wire.


text:
Q: Concurrency of a find, hash val, and replace across large amount of rows I have a bunch of files and for each row there is a unique value I'm trying to obscure with a hash.
However there are 3M rows across the files and a rough calculation of the time needed to complete the process is hilariously long at 32days.
for y in files*; do
  cat $y | while read z; do
    KEY=$(echo $z | awk '{ print $1 }' | tr -d '"')
    HASH=$(echo $KEY | sha1sum | awk '{ print $1 }')
    sed -i -e "s/$KEY/$HASH/g" $y
  done
done

To improve this processes speed I assume I'm going to have to introduce some concurrency.
A hasty attempt based of https://unix.stackexchange.com/a/216475 led me to
N=4
(
for y in gta*; do
  cat $y | while read z; do
    (i=i%N)); ((i++==0)); wait
    ((GTA=$(echo $z | awk '{ print $1 }' | tr -d '"')
    HASH=$(echo $GTA | sha1sum | awk '{ print $1 }')
    sed -i -e "s/$KEY/$HASH/g) &
  done
done
)

Which performs no better.
Example input
"2000000000" : ["200000", "2000000000"]
"2000000001" : ["200000", "2000000001"]

Example output
"e8bb6adbb44a2f4c795da6986c8f008d05938fac" : ["200000", "e8bb6adbb44a2f4c795da6986c8f008d05938fac"]
"aaac41fe0491d5855591b849453a58c206d424df" : ["200000", "aaac41fe0491d5855591b849453a58c206d424df"]

Perhaps I should read the lines concurrently then perform the hash-replace on each line?

A: FWIW I think this is the fastest way you could do it in a shell script:
$ cat tst.sh
#!/usr/bin/env bash

for file in "$@"; do
    while IFS='"' read -ra a; do
        sha=$(printf '%s' "${a[1]}" | sha1sum)
        sha="${sha% *}"
        printf '%s"%s"%s"%s"%s"%s"%s"\n' "${a[0]}" "$sha" "${a[2]}" "${a[3]}" "${a[4]}" "$sha" "${a[6]}"
    done < "$file"
done

$ ./tst.sh file

$ cat file
"e8bb6adbb44a2f4c795da6986c8f008d05938fac" : ["200000", "e8bb6adbb44a2f4c795da6986c8f008d05938fac"]"
"aaac41fe0491d5855591b849453a58c206d424df" : ["200000", "aaac41fe0491d5855591b849453a58c206d424df"]"

but as I mentioned in the comments you'd be better of for speed of execution using a tool with sha1sum functionality built in, e.g. python.

A: As advised by Ed Morton, with a little help from python.
Create a python script /tmp/sha1.py and make it executable
#! /usr/local/bin/python -u

import hashlib
import sys

for line in sys.stdin:
  words = line.split()
  str_hash=hashlib.sha1(words[0].encode())
  words[0] = str_hash.hexdigest()
  print(" ".join(words))

The first line should contain the correct location of your python, but don't remove the "-u".
Then a ksh script, that you should also make executable.
#! /usr/bin/ksh

/tmp/sha1.py |&

for y in files*
do
  while read A B
  do
    eval "echo $A" >&p
    read A <&p
    echo \"$A\" $B
  done < $y > TMP.$y
  mv TMP.$y $y
done

# terminate sha1.py
exec 3>&p
exec 3>&-

Now, if you want performance, you should let python handle a complete file at once.  The following scripts treats each input line as a filename, and does your dirty work:
#! /usr/local/bin/python

import hashlib
import os
import sys

for IFileNmX in sys.stdin:
  IFileNm = IFileNmX.strip()
  IFile = open(IFileNm,'r')
  OFileNm = ".".join(["TMP",IFileNm])
  OFile = open(OFileNm,'w')
  for line in IFile.readlines():
    words = line.split()
    word1 = words[0].strip('"')
    str_hash=hashlib.sha1(word1.encode())
    words[0] = "".join(['"',str_hash.hexdigest(),'"'])
    OFile.write("".join([" ".join(words),'\n']))
  OFile.close()
  IFile.close()
  os.rename(OFileNm,IFileNm)

If you call this script /tmp/sha1f.py, and make it executable, I wonder how many minutes
ls files* | /tmp/sha1f.py

would take.  My system took 12 seconds to deal with a 400Mb file of a million lines.  But that's boasting, of course.


text:
Q: Ambiguity of the notation $\lhd$ If a group $G$ have two subgroups $A,B$ which are isomorphic. Can I say that  $A\lhd G$ if $B\lhd G$?
Indeed we often do in this way when we don't considerate about the concrete set of groups.


text:
Q: python multiprocessing hangs after a few iterations I am running a multiprocessing pool in a for loop over a chuck of data. It runs fine for two iterations and hangs on the third. If I reduce the size of each chuck it hangs later on perhaps the forth or fifth iteration. In the program where I discovered the problem I am running a more extensive function but this works to reproduce the error.
Is there a proper way to terminate a pool after it is finished? So that I can start it again.
import pandas as pd
import numpy as np
from multiprocess import Pool

df = pd.read_csv('paths.csv')

def do_something(user):
    v = df[df['userId'] == user]
    return v

if __name__ == '__main__':
    users = df['userId'].unique()
    n_chunks = round(len(users)/40)
    subsets = [users[i:i+n_chunks] for i in range(0, len(users), n_chunks)]
    chunk_counter = 0
    for user_subset in subsets:
        chunk_counter += 1
        print(f'Beginning to process chunk {chunk_counter}...')
        with Pool() as pool:
            frames = pool.map(do_something, user_subset)
            pool.close()
            pool.terminate()

        print(f'Completed processing chunk {chunk_counter}.')

A: I was able to prevent the hanging with the code below:
with Pool(maxtasksperchild=1) as pool:
    frames = pool.map_async(do_something, user_subset).get()
    pool.terminate()
    pool.join()

I don't understand why using map_async would prevent the hanging. I will dive deeper if I have a chance and update if I understand the reason.


text:
Q: Как поменять несколько спрайтов между собой? Изучаю юнити и решил сделать механику похожую на кубик Рубика в 2d. Возникла проблема с изменением изображения спрайтов. Т.е. мне нужно неоднократно менять их между собой + в разных плоскостях.
  Пример: из 123 получается 312, а после из 345 - 534 и т.д.
Просмотрел множество источников, но не нашел решение проблемы.

A: Создайте объект Canvas, в качестве дочернего объекта создаем пустой объект и навешиваем на него компонент Grid Layout Group, настраиваем как в примере ниже. Далее создаем в качестве дочерних объектов нужное кол-во объектов с компонентов Image. Меняя их положение внутри родительского компонента - они будут менять своё положение в гриде (красный кубик имеет позицию [0,0], но если перенести его в самый конец списка, то его позиция изменится на [2,2]).


text:
Q: How to use URLClassLoader to load a *.class file? I'm playing around with Reflection and I thought I'd make something which loads a class and prints the names of all fields in the class.
I've made a small hello world type of class to have something to inspect:
kent@rat:~/eclipsews/SmallExample/bin$ ls
IndependentClass.class
kent@rat:~/eclipsews/SmallExample/bin$ java IndependentClass
Hello! Goodbye!
kent@rat:~/eclipsews/SmallExample/bin$ pwd
/home/kent/eclipsews/SmallExample/bin
kent@rat:~/eclipsews/SmallExample/bin$

Based on the above I draw two conclusions:

*

*It exists at /home/kent/eclipsews/SmallExample/bin/IndependentClass.class

*It works! (So it must be a proper .class-file which can be loaded by a class loader)

Then the code which is to use Reflection: (Line which causes an exception is marked)
import java.lang.reflect.Field;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

public class InspectClass {
    @SuppressWarnings("unchecked")
    public static void main(String[] args) throws ClassNotFoundException, MalformedURLException {
        URL classUrl;
        classUrl = new URL("file:///home/kent/eclipsews/SmallExample/bin/IndependentClass.class");
        URL[] classUrls = { classUrl };
        URLClassLoader ucl = new URLClassLoader(classUrls);
        Class c = ucl.loadClass("IndependentClass"); // LINE 14
        for(Field f: c.getDeclaredFields()) {
            System.out.println("Field name" + f.getName());
        }
    }
}

But when I run it I get:
Exception in thread "main" java.lang.ClassNotFoundException: IndependentClass
    at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
    at InspectClass.main(InspectClass.java:14)

My questions:

*

*What am I doing wrong above? How do I fix it?

*Is there a way to load several class files and iterate over them?

A: You have to load the class by giving the fully qualified class name that is class name with with its package path as,
Class c = ucl.loadClass("com.mypackage.IndependentClass");

A: From the Javadocs for the URLClassLoader(URL[]) constructor:

Constructs a new URLClassLoader for the specified URLs using the default delegation parent ClassLoader. The URLs will be searched in the order specified for classes and resources after first searching in the parent class loader. Any URL that ends with a '/' is assumed to refer to a directory. Otherwise, the URL is assumed to refer to a JAR file which will be downloaded and opened as needed.

So you have two options:

*

*Refer to the directory that the .class file is in

*Put the .class file into a JAR and refer to that

(1) is easier in this case, but (2) can be handy if you're using networked resources.

A: You must provide the directories or the jar files containing your .class files to the URLClassLoader:
classUrl = new URL("file:///home/kent/eclipsews/SmallExample/bin/");

And yes, you can load as many classes as you like

A: I was having a similar problem but my class file was residing inside a package named "customElements". In such scenarios the URL needs to be constructed till the folder just above the root package and in the load method the complete name of the class including the package should be passed. For example, in my case; URL was like:
File customElementsDir = new File("D:/My Space");
//File customElementsDir = new File("D:\\customElements");
URL[] urls = null;
try {
    URL url = customElementsDir.toURI().toURL();
    urls = new URL[] { url };
} catch (MalformedURLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

And actual loading was like:
clazz = childFirstClassLoader
            .loadClass("customElements.CustomLoadableClass");

Where childFirstClassLoader is my classloader.

A: I had the same problem but I found this as a solution:
System.getProperty("java.class.path")

This give you the jar, and classes path. From here you are able to manage your process.


text:
Q: Xamarin Android async await not await method I m doing a Xamarin Android project, I wan't to display a list of objects from my SQLite database into a RecyclerView.
The RecyclerView is in a Fragment. I wan't to display the list when I open this fragment, and when I go back from an Activity to this fragment I wan't to refresh the data of the recycler view.
For know I get the correct values, but I don't know why the GetMyObjectsAsync result is not awaited Why ?
using System.Collections.Generic;
using System.Threading.Tasks;
using Android.OS;
using Android.Support.V7.Widget;
using Android.Views;
using Microsoft.Practices.ServiceLocation;
using System.Linq;
using Android.App;
using Android.Widget;
using Android.Util;
using System;

namespace POCProject.Droid.Fragments
{
    public class MyCustomFragment : Fragment
    {

        private IMyObjectsService _myObjectsService;

        List<ObjModel> myObjects { get; set; } = new List<ObjModel>();

        RecyclerView mRecyclerView;

        RecyclerView.LayoutManager mLayoutManager;

        MyObjectsRecyclerViewAdapter mAdapter;

        public override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            _myObjectsService = ServiceLocator.Current.GetInstance<IMyObjectsService>();

        }

        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {

            View view = inflater.Inflate(Resource.Layout.fragment_my_objects_list, container, false) as View;

            mRecyclerView = view.FindViewById<RecyclerView>(Resource.Id.MyRecyclerView);

            mLayoutManager = new LinearLayoutManager(mRecyclerView.Context);

            mRecyclerView.SetLayoutManager(mLayoutManager);

            return view;
        }

        public override void OnResume()
        {
            base.OnResume();
            Task.Run(async () => {
                try
                {
                    myObjects = await GetMyObjectsAsync(); // Here it's not awaited the result why ?
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }

            });
            mAdapter = new MyObjectsRecyclerViewAdapter(myObjects);
            Console.WriteLine("--------------------OnResume Called-------------------- " + myObjects.Count()); // Always 0 why ?

            mRecyclerView.SetAdapter(mAdapter);
        }

        private async Task<List<ObjModel>> GetMyObjectsAsync(){
            Console.WriteLine("--------------------GetMyObjectsAsync Called--------------------");
            var result = await _myObjectsService.GetAllAsync(); // Get objects in sqlite databases
            Console.WriteLine("-------------------- result" + result.Value.Count() + "--------------------");  // Return the correct value for example 5

            List<ObjModel> myOjectsTmp = new List<ObjModel>();

            if (!result.HasErrors && result.HasValue)
            {
                foreach (var obj in result.Value)
                {
                    myOjectsTmp.Add(obj);
                }
                Console.WriteLine("-------------------- myOjectsTmp"+ myOjectsTmp.Count() + "--------------------"); // Return the correct value for example 5
            }

            return myOjectsTmp;
        }

    }
}

A: Try this:
Move these two line:
mAdapter = new MyObjectsRecyclerViewAdapter(myObjects);
mRecyclerView.SetAdapter(mAdapter);

after
 myObjects = await GetMyObjectsAsync();

Like:
   myObjects = await GetMyObjectsAsync();
Activity.RunOnUiThread(() =>
                    {
    mAdapter = new MyObjectsRecyclerViewAdapter(myObjects);
    mRecyclerView.SetAdapter(mAdapter);
 });


text:
Q: Smaller emit view for couchdb What is the advantage of say
emit([doc.key1,doc.key2], 1);

vs
emit([doc.key1,doc.key2], doc);

and call the doc via ?include_docs=true
Would this actually save on couchdb space ( view sizes are shorter ) ? Also, would CPU suffer since doc is not integrated
in the emit ?
What's the Pros and Cons and when to use one over the other.

A: Using emit(..., 1); is needed for reduce functions like _sum, _count or _stats, because they need a number to work with.
Using emit(..., doc); will truly duplicate the document, so it will be stored in the view file on disk.
Using emit(..., null); will not duplicate the document, but because couchdb knows which doc is the source for the emit() it can be "re-attached" with ?include_docs=true. The key-based lookup is a little bit slower, but will not do any harm.
More on this topic can be found in the wonderful documentation.
My recommendation:

*

*Use emit(..., 1) when reduce is needed, and emit(..., null) when not.

*There are very few cases where emit(..., doc); has benefits.

A cool trick is linking a different document in the view instead of the current doc with emit(..., { _id : doc.commentId }).


text:
Q: HTML5/CSS3: How Do I Prevent LI Items From Being Pushed To The Right with No Bullet Without Using JavaScript or PHP? For HTML and CSS, how do I prevent li items with list-style: none; from actually being pushed to the right and just stick it to the edge? My English is not so good, so I'll show some examples.
I searched Google and Google doesn't seem to understand what I mean.
Here is my code snippet and please run it to realize what I mean:

<!DOCTYPE html>

    <meta http-equiv="content-type" content="text/html; charset=utf-8" />

a

1

2

3

b

c

d

i

ii

iii

NOTE: I added a border to show the alignment of the li.
Did you see how it became stair-type and it's not sticking to the edge?
My question is how do I make them stick to the edge perfectly aligned into one line like this?
a
1
2
3
b
c
d
i
ii
iii

If you have any answers, please let me know.

A: You only need to add 1 line of CSS:
padding-left: 0; to remove the padding.

body {
  border: 1px solid #000;
}

ul {
  list-style: none;
  padding-left: 0;
}

a

1

2

3

b

c

d

i

ii

iii

A:

<!DOCTYPE html>

    <meta http-equiv="content-type" content="text/html; charset=utf-8" />

a

1

2

3

b

c

d

i

ii

iii

Just clear default margin and padding of ul item.

A: I saw an older answer which said to place margin-left: -40px in my code and that was the most helpful solution and it worked!
I asked it for a navbar with padding.
That answer was removed from my post though.


text:
Q: Vertical align the content of absolutely positioned td in table I have a absolutely positioned td (second td), I want it to align at vertical center even there is content changes in the first td.
I tried using position: relative and transform: properties and all, but nothing seems to worked out.
This is my code, and you can see the record payment buttons are not vertically centered.

table {
    width: 600px;
    font-size: 14px;
    color: black;
    font-family: sans-serif;
    background-color: white;
    margin-left:0%;
    border-style: solid;border-color:#eee;
    overflow-x:scroll;
    display:table;
}

table, th, td {
    border-width: thin;
    border-collapse: collapse;
    border-style: solid;border-color:#eee;
    padding: 20px 10px;
}
td {
    text-align: left;

}

.hover-icons{
  position: absolute;
  right:30px;
}
.hover-icons ul{
  position: absolute;
   border: 0;
   top: 50%;
   right: 0;
   transform: translate(5%, 33%);
   background: #EFEFEF;
   height: auto;
   display: none;
}
td{padding:0px 0}
.hover-icons ul{
  display: flex;
}
.hover-icons ul li{
  margin: 0 6px;
}
.hover-main-icons .posi-r{position: relative;}
.btn-hover-i{

}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"></link>

test test
 test
 test
test
 testtesttest testt
esttest
testt
est
test

                        <button class="btn btn-red-bg btn-hover-i">Record Payment</button>

                        <button class="btn btn-red-bg btn-hover-i">Record Payment</button>

                        <button class="btn btn-red-bg btn-hover-i">Record Payment</button>

test test test test
test
 testtesttest testt
esttesttestt
est
test

                        <button class="btn btn-red-bg btn-hover-i">Record Payment</button>

                        <button class="btn btn-red-bg btn-hover-i">Record Payment</button>

                        <button class="btn btn-red-bg btn-hover-i">Record Payment</button>

Is there any way to place buttons that are vertically centered?

A: You need to change
.hover-icons{
  position: absolute;
  right: 30px;
}

to
.hover-icons{
 position: relative;
 right:25%;
}

Here is the working snippet:

table {
    width: 600px;
    font-size: 14px;
    color: black;
    font-family: sans-serif;
    background-color: white;
    margin-left:0%;
    border-style: solid;border-color:#eee;
    overflow-x:scroll;
    display:table;
}

table, th, td {
    border-width: thin;
    border-collapse: collapse;
    border-style: solid;border-color:#eee;
    padding: 20px 10px;
}
td {
    text-align: left;

}

.hover-icons{
  position: relative;
  right:25%;
}
.hover-icons ul{
  position: absolute;
   border: 0;
   top: 50%;
   right: 0;
   transform: translate(5%, 33%);
   background: #EFEFEF;
   height: auto;
   display: none;
}
td{padding:0px 0}
.hover-icons ul{
  display: flex;
}
.hover-icons ul li{
  margin: 0 6px;
}
.hover-main-icons .posi-r{position: relative;}
.btn-hover-i{

}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"></link>

test test
 test
 test
test
 testtesttest testt
esttest
testt
est
test

                        <button class="btn btn-red-bg btn-hover-i">Record Payment</button>

                        <button class="btn btn-red-bg btn-hover-i">Record Payment</button>

                        <button class="btn btn-red-bg btn-hover-i">Record Payment</button>

test test test test
test
 testtesttest testt
esttesttestt
est
test

                        <button class="btn btn-red-bg btn-hover-i">Record Payment</button>

                        <button class="btn btn-red-bg btn-hover-i">Record Payment</button>

                        <button class="btn btn-red-bg btn-hover-i">Record Payment</button>

A: You need to give a "height" and "display:block;" to the tr o td and than the "line-height" for the vertical align. For example If the height is "height:300;" the line-height must be "line-height:300px;"
Ps. I think position:relative is the right choise

A: Try this: without position css

table {
  width: 600px;
  font-size: 14px;
  color: black;
  font-family: sans-serif;
  background-color: white;
  margin-left: 0%;
  border-style: solid;
  border-color: #eee;
  overflow-x: scroll;
  display: table;
}

table,
th,
td {
  border-width: thin;
  border-collapse: collapse;
  border-style: solid;
  border-color: #eee;
  padding: 20px 10px;
}

td {
  text-align: left;
}

td {
  width: 100%;
}

.hover-icons ul {
  background: #EFEFEF;
  height: auto;
  display: none;
}

td {
  padding: 0px 0
}

.hover-icons ul {
  display: flex;
}

.hover-icons ul li {
  margin: 0 6px;
}

.hover-main-icons .posi-r {
  position: relative;
}

.btn-hover-i {}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"></link>

    test test
 test
 test
test
 testtesttest testt
esttest
testt
est
test

            <button class="btn btn-red-bg btn-hover-i">Record Payment</button>

            <button class="btn btn-red-bg btn-hover-i">Record Payment</button>

            <button class="btn btn-red-bg btn-hover-i">Record Payment</button>

    test test test test
test
 testtesttest testt
esttesttestt
est
test

            <button class="btn btn-red-bg btn-hover-i">Record Payment</button>

            <button class="btn btn-red-bg btn-hover-i">Record Payment</button>

            <button class="btn btn-red-bg btn-hover-i">Record Payment</button>


text:
Q: Unable to find the image edge option in Xcode 8 for UIButton As I am easily get the image edge option in Xcode 7 using storyboard -> Attribute inspector but I did not get the option in Xcode 8.

A: Please find the below screenshot for viewing the image edge option in Xcode 8.


text:
Q: Is Cartan subalgebra of a Lie algebra unique? Let $\mathfrak{g}$ be a Lie algebra. Is Cartan subalgebra of $\mathfrak{g}$ unique? I see in some places it is written "Let $\mathfrak{h}$ be a Cartan subalgebra of $\mathfrak{g}$".

A: Here is an example. If $\mathfrak{g} = \mathfrak{sl}_2(\mathbb{R})$, then both of
$$
\mathfrak{h}_1 = \mathbb{R}\begin{bmatrix}1 & 0 \\ 0 & -1 \end{bmatrix} \quad , \quad \mathfrak{h}_2 = \mathbb{R}\begin{bmatrix}0 & -1 \\ 1 & 0 \end{bmatrix}
$$
are Cartan subalgebras.
Add: To add a bit more detail: It isn't too difficult to check that both of these subalgebras are (1) nilpotent and (2) they are both equal to their own normalizers in $\mathfrak{g}$.

A: You can think in terms of the Lie group, any element is in a maximal torus and any two maximal torus are conjugate to each other. For simple-connected Lie groups the maximal torus correspond to the Cartan subalgebra. So one should expect many different copies of Cartan subalgebra in the Lie algebra. But they are all isomorphic.

A: No, Cartan algebra of a Lie algebra may not be unique.  But any two Cartan algebras are conjugate to each other.


text:
Q: Determine if input string matches clock time using regular expressions in Java I'm trying to determine if an input string is in a valid 24-hour date format (ie. hh:mm:ss). I'm using a few different logics and have been mostly successful with my test cases. My code currently fails for all the inputs I've tried (including the ones below).
The expression is supposed to work in the following way:

*

*Inputting 11:24:10 should output Valid form

*inputting 00:13:42 should output Valid form

*Inputting 24:52:25 should output Invalid form

*Inputting 05:62:55 should output Invalid form
Here's my code:
import java.util.Scanner;

public class Main {

   public static void main(String[] args) {
      System.out.print("String to check: ");
      String input = new Scanner(System.in).nextLine();

      if (input.matches("((0|1)[0-9])|(2[0-3]):[0-5][0-9]:[0-5][0-9]")) {
         System.out.println("Valid form");
      } else {
         System.out.println("Invalid form");
      }
   }
}

I've only recently started learning Java and I apologize if this question has been asked before (I googled!). Thanks for your help!

A: It should be
(((0|1)[0-9])|(2[0-3])):[0-5][0-9]:[0-5][0-9]

According to your regex
((0|1)[0-9])|(2[0-3]):[0-5][0-9]:[0-5][0-9]

It will match ((0|1)[0-9]) or (2[0-3]):[0-5][0-9]:[0-5][0-9]
You can also use non capturing group if you just want to match it as
(?:(?:(?:0|1)[0-9])|(?:2[0-3])):[0-5][0-9]:[0-5][0-9]

Your regex can be simplified further as by modifying hours part
[01][0-9]

IDEONE DEMO
EDIT
Little bit modification
(?:[01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]

REGEX DEMO

A: The issue is that your current regex will match (0|1)[0-9]) or (2[0-3]):[0-5][0-9]:[0-5][0-9]. You want your || operator to work on the (0|1)[0-9]) and (2[0-3]). So what you want is this:
((0|1)[0-9])|(2[0-3]):[0-5][0-9]:[0-5][0-9]

You also have a resource leak because you do not close your Scanner. It is best to store the new Scanner in a variable so that you can close it later. Here is the full code:
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        System.out.print("String to check: ");
        Scanner sc = new Scanner(System.in);
        String input = sc.nextLine();

        if (input.matches("(((0|1)[0-9])|(2[0-3])):[0-5][0-9]:[0-5][0-9]")) {
            System.out.println("Valid form");
        } else {
            System.out.println("Invalid form");
        }

        sc.close();
    }
}


text:
Q: Is the function $y(t)$ is a solution of the equation $y'=\sin(yt)$? Is the function $y(t)$ a solution of the equation $y'=\sin(yt)$?
any thought to start me up?
I'm not sure what is the question asking.
EDIT:
Someone tell me if I'm correct or not .
If I'm finding the general solution of the equation y'=ty, does this mean I'm finding the anti-derivative of that which is y=((t(y^2))/2)+C ?
Very confused at what the question want.

A: I think the question is: is there a function $y(t)$ such that $$\frac{\mathbb d}{\mathbb d t}y(t) = \sin{ty(t)}$$ $y(t) = 0$ certainly works. Less trivial functions, I'm pretty sure do not.

A: One way to start this is to think of what $y$ is related to. That is, it's a function of time. Meanwhile, $sin(yt)$ is also a function of time and also a function of y.
To get the solution to $y' = \sin(yt)$ one can ask what is the derivative of sine and cosine? In this case you can't separate variables. But you can assume that a general solution will look roughly like this: $A\sin(yt) + B\cos(yt)$. (I guess you could have exopnential functions but for this kind of problem that's unnecessarily harder to do).
Also the antiderivative you have isn't quite right. If you have $y' = ty$ then it's a separable equation. That means you can just move stuff to the left. So you would rearrange that as $\frac{y'}{y} = t$.
But that's an unwieldy notation to use. I would have set it up as follows:
$$y' = \frac{dy}{dt} = ty \rightarrow \frac{dy}{y} = tdt$$
That one you can integrate both sides and end up with
$\ln y = \frac{t^2}{2} + C$
And you have an exponential function to get y. $e^{\ln y} = e^{\frac{t^2}{2}+ C} \rightarrow y = e^C e^{\frac{t^2}{2}} \rightarrow A e^{\frac{t^2}{2}}$
(Because e raised to any constant power is a constant too)
And you can check this by taking a derivative and plugging it into the $y'=ty$.
I hope this helps.

A: If you set $v = ty$ then $y = \frac{v}{t}$ so the equation becomes $$(\frac{v}{t})' = \frac{v'}{t} - \frac{v}{t^2} = \sin(v)$$ WolframAlpha didn't give a solution though...

A: Let $u=ty$ ,
Then $y=\dfrac{u}{t}$
$\dfrac{dy}{dt}=\dfrac{1}{t}\dfrac{du}{dt}-\dfrac{u}{t^2}$
$\therefore\dfrac{1}{t}\dfrac{du}{dt}-\dfrac{u}{t^2}=\sin u$
$\dfrac{1}{t}\dfrac{du}{dt}=\dfrac{t^2\sin u+u}{t^2}$
$(t^2\sin u+u)\dfrac{dt}{du}=t$
Let $v=t^2$ ,
$\dfrac{dv}{du}=2t\dfrac{dt}{du}$
$\therefore\dfrac{(t^2\sin u+u)}{2t}\dfrac{dv}{du}=t$
$(t^2\sin u+u)\dfrac{dv}{du}=2t^2$
$(v\sin u+u)\dfrac{dv}{du}=2v$
Let $w=v+u\csc u$ ,
Then $v=w-u\csc u$
$\dfrac{dv}{du}=\dfrac{dw}{du}+(u\cot u-1)\csc u$
$\therefore(\sin u)w\left(\dfrac{dw}{du}+(u\cot u-1)\csc u\right)=2(w-u\csc u)$
$(\sin u)w\dfrac{dw}{du}+(u\cot u-1)w=2w-2u\csc u$
$(\sin u)w\dfrac{dw}{du}=(3-u\cot u)w-2u\csc u$
$w\dfrac{dw}{du}=(3\csc u-u\csc u\cot u)w-2u\csc^2u$
This belongs to an Abel equation of the second kind.
In fact all Abel equation of the second kind can be transformed into Abel equation of the first kind.
Let $w=\dfrac{1}{z}$ ,
Then $\dfrac{dw}{du}=-\dfrac{1}{z^2}\dfrac{dz}{du}$
$\therefore-\dfrac{1}{z^3}\dfrac{dz}{du}=\dfrac{3\csc u-u\csc u\cot u}{z}-2u\csc^2u$
$\dfrac{dz}{du}=2z^3u\csc^2u+(u\csc u\cot u-3)z^2$
Please follow the method in http://www.hindawi.com/journals/ijmms/2011/387429/#sec2


text:
Q: C++ - avoiding the implicit inlining of a function defined in the class definition In my implementation files (.cc files), I often find that it's convenient to define member functions in class definitions (such as the functions of a Pimpl class). For example:
struct X::Impl {
    void DoSomething() {
        ...
    }
};

instead of
struct X::Impl {
    void DoSomething();
};

void X::Impl::DoSomething() {
    ...
}

I think this is preferable to implementing the function outside of the class definition for several reasons. It enhances readability and facilitates the practice of keeping methods small (by making it easy to add them). The code is also easier to maintain since you never have to update method declarations.
The only downside I see is that methods defined in the class declaration are implicitly inlined, which is not usually desirable because of the increase in the size of the object code.
My questions are:

*

*Do I have this right? Are there other downsides to this practice that I'm missing?

*Is the implicit inlining something to worry about? Is the compiler smart enough to reject my implicit request to inline methods that shouldn't be inlined?

*Is it possible (via compiler extensions or otherwise) to declare that a method defined in the class definition not be inlined?

A: The simple answer is that you should not care. Member functions defined within the class definition are implicitly inline, but that does not mean that they are inlined (i.e. the code need not be inlined at the place of call).
Compiler implementors have dedicated quite a bit of time and resources to come up with heuristics that determine whether actual inlining should be done or not, based on the size of the function, the complexity and whether it can be inlined at all or not (a recursive function cannot be inlined[*]). The compiler has more information on the generated code and the architecture in which it will run than most of us have. Trust it, then if you feel that there might be an issue, profile, and if profiling indicates that you should change the code, do it, but make an informed decision after the fact.
If you want to verify whether the function has actually be inlined or not, you can look at the assembly and check whether there are calls to the function or the code was really inlined.

[*] If the compiler can transform the recursion into iteration, as is the case in tail recursion, then the transformed function could be theoretically be inlined. But then, functions with loops have lesser probabilities of being inlined anyway...

A: I don't know portable way of preventing inlining, but with GCC you can use attribute. For example:
struct X::Impl {
    void DoSomething() __attribute__((noinline)) {
        ...
    }
};

A: Add up all the CPU time that will ever be saved by your inlining choices.  Spend less than that of your own on them.  Linear pathlength worries are for paths handling now trillions of executions a day.  Four billion is near enough a second out of L1. 250 times that isn't five minutes. If nobody's complaining about performance, your and your compiler's choices are at least playing in the right league.
Opinions on readability differ widely.  It's your audience's opinion that matters.

A: Generally, the compiler will inline whatever it pleases, and it won't pay too much attention to any inline keywords given by the programmer. inline is usually treated more or less the same as static.
For example, a recursive function can usually not be completely inlined (the function body you'd inline will contain again a call that should be inlined). To test the behavior of your specific compiler, you could for example define a class like this:
class Fib {
public:
   int calc(int i);
};

int Fib::calc(int i) {
  if (i > 1)
     return calc(i-1) + calc(i-2);
  return 1;
}

With this definition, a sample program like the following would not be compilable in reasonable time or size if the compiler would feel obligated to inline all calls to calc:
#include "tst.hpp"
#include <iostream>
int main() {
   Fib f;
   std::cout << f.calc(1000) << std::endl;
};

So you can test you compilers behavior by compiling this program. If compilation succeeds, the compiler didn't inline all calls to Fib::calc.


text:
Q: How do you display one row in in a html table using php at random? Im setting up a website for my home work and I need to display 1 row at random from an sql table in a html table using php. For example, my website is called random data where the website will generate random data for you (except all it is actually doing is displaying data already inserted into a database). So, does anyone know the code required to display 1 row of data from an sql table and display it in a html table using php in each cell of the table to retrieve the data from the database? Here is what I have so far (it works when I don't try to select just one row at random, but when I select all of them, it does work. Pleas Help! :)
<?php
            $username = "root";
            $password = "root";
            $dbname = "fakedeets";

            $conn = new mysqli("localhost", $username, $password, $dbname);
            if ($conn->connect_error) {
                die("Connection failed: " . $conn->connect_error);
            }

            $sql = "SELECT FLOOR(RAND()*(10-5+1)+5);";
            $result = $conn->query($sql);

            if($row = $result-> fetch_assoc()) {
                    echo "
". $row["firstname"].
                    "	". $row["lastname"].
                    "	". $row["dob"].
                    "	". $row["gender"].
                    "	". $row["emailaddress"].
                    "	". $row["phonenumber"].
                    "	". $row["photo"].
                    "
";
                echo "
";
            }   else {
                        echo "0 results";
            }

            $conn->close();
?>

What I expect to appear is just 1 row of data displayed on a html doc selected at random from an sql database. Instead it just outputs nothin

A: You can just use SELECT {your columns} FROM {table} ORDER BY RAND() LIMIT 1
This selects the columns from the table you need, orders it randomly and then limits the set to just one entry. Replace the 1 with number of rows you need.


text:
Q: Associating values in list with integers in Python I am working on a simple Blackjack game.
deck = ['Ace',2,3,4,5,6,7,8,9,10,'Jack','Queen','King']

card_1 = random.choice(deck)
card_2 = random.choice(deck)

def my_hand(card_1,card_2):
    total = card_1 + card_2
    if total > 21:
        return "Bust!"
    elif total == 21:
        return "Blackjack!"
    elif total < 21:
        return "Hit again?"

print card_1,'and',card_2
my_hand(card_1,card_2)

How do I assign specific items in the list an integer value?  Namely, I'd like to assign 'Ace' to the integer 1 or 11, and 'Jack', 'King', and 'Queen' equal to 10.
Thank you.

A: Use a dictionary (and I suggest that you convert all keys to strings):
deck = {'Ace':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'10':10,
 'Jack':10,'Queen':10,'King':10}


text:
Q: Nilpotent Groups as Perturbations of the Identity In Terry Tao's blog, specifically this post, he says that nilpotent groups can be thought of in algebraic geometry and analysis as modeling infinitesimal perturbations of the identity. Can someone provide a reference where this point of view is used?

A: The idea of nilpotents representing infinitesimal change dates back at least to the invention/discovery of calculus by Newton and Leibniz! In deformation theory of schemes at least, the whole story begins with the study of flat families over the spectrum of $k[t]/t^2,$ which are viewed as infinitesimal perturbations of the "central" fibre parametrized by the nilpotent parameter $t.$ This is mentioned in Hartshorne II.8 in the exercises I believe, but there is an entire field of work in deformation theory dedicated to this beautiful concept. For example, Harthorne has a recent introductory book called "Deformation Theory".