text:
Q: is there any lorem ipsum generator in c#? I'm looking for a c# generator which can generate random words, sentences, paragraphs given by a number of words / paragraphs and certain syntax such as Address, numbers, postal code / zip code, country, phone numbers, email address.

A: static string LoremIpsum(int minWords, int maxWords,
    int minSentences, int maxSentences,
    int numParagraphs) {

    var words = new[]{"lorem", "ipsum", "dolor", "sit", "amet", "consectetuer",
        "adipiscing", "elit", "sed", "diam", "nonummy", "nibh", "euismod",
        "tincidunt", "ut", "laoreet", "dolore", "magna", "aliquam", "erat"};

    var rand = new Random();
    int numSentences = rand.Next(maxSentences - minSentences)
        + minSentences + 1;
    int numWords = rand.Next(maxWords - minWords) + minWords + 1;

    StringBuilder result = new StringBuilder();

    for(int p = 0; p < numParagraphs; p++) {
        result.Append("
");
        for(int s = 0; s < numSentences; s++) {
            for(int w = 0; w < numWords; w++) {
                if (w > 0) { result.Append(" "); }
                result.Append(words[rand.Next(words.Length)]);
            }
            result.Append(". ");
        }
        result.Append("
");
    }

    return result.ToString();
}

A: I wrote a C# port of the Ruby Faker gem that can be used to easily generate fake data: names, addresses, phone numbers and the lorem ipsum text.
It's available as a NuGet package (Install-Package Faker.Net) with source on Github and I also wrote a post introducing some of it's features, with sample code.

*

*Faker source code (on github)

*Faker.Net NuGet package

*Populating test data using C# for realistic unit and integration testing

A: Like this:
const string LoremIpsum = @"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";

To repeat it:
String.Join(Environment.NewLine,
            Array.ConvertAll(new int[count], i => LoremIpsum));

Or, in .Net 4.0:
String.Join(Environment.NewLine, Enumerable.Repeat(LoremIpsum, count));

A: Why not to use Lorem Ipsum Online generator?
I wrote this code that extracts the lorem ispum string from HTML page:
string LoremIpsum()
{
   string HTML = null;
   WebRequest request = WebRequest.Create("http://lipsum.com/feed/html");
   request.Credentials = CredentialCache.DefaultCredentials;
   HttpWebResponse response = (HttpWebResponse)request.GetResponse();
   Stream dataStream = response.GetResponseStream();
   StreamReader reader = new StreamReader(dataStream);
   HTML = reader.ReadToEnd(); //se citeste codul HTMl

   //searching for Lorem Ipsum
   HTML = HTML.Remove(0, HTML.IndexOf("
"));
   HTML = HTML.Remove(HTML.IndexOf("
"));
   HTML = HTML
        .Replace("
", "")
        .Replace("
", "")
        .Replace("
", "")
        .Replace("
", "");

   reader.Close();
   dataStream.Close();
   response.Close();
   return HTML;
}

A: Hello you can use WordGenerator or LoremIpsumGenerator from MMLib.RapidPrototyping nuget package.
using MMLib.RapidPrototyping.Generators;
public void Example()
{
   WordGenerator generator = new WordGenerator();
   var randomWord = generator.Next();

   Console.WriteLine(randomWord);

   LoremIpsumGenerator loremIpsumGenerator = new LoremIpsumGenerator();
   var text = loremIpsumGenerator.Next(3,3);

   Console.WriteLine(text);
}

Nuget site
Codeplex project site

A: Version using StringBuilder and without HTML tags (using new line instead of paragraph mark):
    private static string LoremIpsum(int minWords, int maxWords, int minSentences, int maxSentences, int numLines)
    {
        var words = new[]{"lorem", "ipsum", "dolor", "sit", "amet", "consectetuer", "adipiscing", "elit", "sed", "diam", "nonummy", "nibh", "euismod", "tincidunt", "ut", "laoreet", "dolore", "magna", "aliquam", "erat"};

        var rand = new Random();
        int numSentences = rand.Next(maxSentences - minSentences)
            + minSentences + 1;
        int numWords = rand.Next(maxWords - minWords) + minWords + 1;

        var sb = new StringBuilder();
        for (int p = 0; p < numLines; p++)
        {
            for (int s = 0; s < numSentences; s++)
            {
                for (int w = 0; w < numWords; w++)
                {
                    if (w > 0) { sb.Append(" "); }
                    sb.Append(words[rand.Next(words.Length)]);
                }
                sb.Append(". ");
            }
            sb.AppendLine();
        }
        return sb.ToString();
    }

A: Minor modification to Greg + Tomino's excellent method above to capitalize the first word of each sentence. I also removed the trailing newline and removed some "+ 1"s that gave one too many. Very handy for testing word wrap capabilities of user interfaces! Thanks to Tomino & Greg.
private static string LoremIpsum(int minWords, int maxWords, int minSentences, int maxSentences, int numLines)
{
    var words = new[]{"lorem", "ipsum", "dolor", "sit", "amet", "consectetuer", "adipiscing", "elit", "sed", "diam", "nonummy", "nibh", "euismod", "tincidunt", "ut", "laoreet", "dolore", "magna", "aliquam", "erat"};

    var rand = new Random();
    int numSentences = rand.Next(maxSentences - minSentences)
        + minSentences;
    int numWords = rand.Next(maxWords - minWords) + minWords;

    var sb = new StringBuilder();
    for (int p = 0; p < numLines; p++)
    {
        for (int s = 0; s < numSentences; s++)
        {
            for( int w = 0; w < numWords; w++ )
            {
                if( w > 0 ) { sb.Append( " " ); }
                string word = words[ rand.Next( words.Length ) ];
                if( w == 0 ) { word = word.Substring( 0, 1 ).Trim().ToUpper() + word.Substring( 1 ); }
                sb.Append( word );
            }
            sb.Append(". ");
        }
        if ( p < numLines-1 ) sb.AppendLine();
    }
    return sb.ToString();
}

A: There's actually a package out on Nuget that does this exact thing for you.
http://www.nuget.org/packages/NLipsum/
For example, you can generate a paragraph of text by just doing this:
var someComments = new NLipsum.Core.Paragraph();

A: There's one in NuGet called NetFx Ipsum Generator.
You can install it with
Install-Package netfx-IpsumGenerator

It's pretty minimal though, I'm currently looking for a better one, or a way to contribute.

A: Found this Lorem Ipsum generator: http://www.gutgames.com/post/Lorem-Ipsum-Generator-in-C.aspx


text:
Q: Prove that the set of all periodic sequences (from some index) of natural numbers is countable This exercise is from my course textbook and comes with a bunch of other exercises which practice the theorem that countable union of countable sets is countable.
So I started by notating for every $k\in \mathbb{N}$ the set $X_k$ as the set of all periodic sequences from the index $k$ of natural numbers. now, $X=\displaystyle{\bigcup_{k\in \mathbb{N}}{X_k}}$ so it's only left to prove that for each $k\in \mathbb{N}$  the set $X_k$ is countable but I can't find an injection from $X_k$ to a countable set.

A: Hint: Set $X_k^n$ to be the set of integer sequences that have period $k$, starting at index $n$. Now observe that $X = \bigcup \limits_{(k, n) \in \mathbb{N}^2} X_k^n$.

A: For $k \ge 1$, call $U_k = \{ \mbox{sequences } (x_n)_n \in X :  \max_n x_n =k-1 \}$. Clearly
$$X= \bigcup_k U_k$$
so it is enough to show that $U_k$ is countable. Clearly $U_1$ has only one element : the constant $0$ sequence.
For $k \ge 2$, do as follows:
 inject $U_k \longrightarrow \Bbb{Q}$ with the map
$$(x_n)_n \mapsto \sum_{n=0}^{\infty} x_n (k+1)^{-n}$$
i.e. you associate to a periodic sequence its periodic $(k+1)$-nary number, which is rational.
Maybe the most natural choice would have been $(x_n)_n \mapsto \sum_{n=0}^{\infty} x_n k^{-n}$. But the problem is that $k$-nary representation of rational numbers is not unique (problems arise for example when you have $0.49999999\dots = 0.50000000\dots$). Avoiding the largest cipher, we get uniqueness of representation.
Finally, since $\Bbb{Q}$ is well-known to be countable, you can conlude that $U_k$ is countable.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why IDBKeyRange.only() does not allow boolean? I have an index in my object store, created like this:
objStore.createIndex("pinned", "pinned");

I want to store values of boolean type there. And unfortunately I can't get only records with "pinned" field set to "true". Why does this happen? Is this my database design mistake?
IDBKeyRange.only(true)
Firefox: [Exception... "Data provided to an operation does not meet requirements."  code: "0" nsresult: "0x80660005 (DataError)"  location: "Web Console Line: 1"]

A: In IndexedDB, a boolean value is not a valid key. See http://www.w3.org/TR/IndexedDB/#dfn-valid-key
I found this at IndexedDB - boolean index .


text:
Q: Error in wbranca dynagrid update Am using wbranca yii2 to create dynamic forms but the update action returns an error of
    array_combine(): Both parameters should have an equal number of elements

This is the form for the update

                            <?php DynamicFormWidget::begin([
                            'widgetContainer' => 'dynamicform_wrapper', // required: only alphanumeric characters plus "_" [A-Za-z0-9_]
                            'widgetBody' => '.container-items', // required: css class selector
                            'widgetItem' => '.item', // required: css class
                            'limit' => 10, // the maximum times, an element can be cloned (default 999)
                            'min' => 1, // 0 or 1 (default 1)
                            'insertButton' => '.add-item', // css class
                            'deleteButton' => '.remove-item', // css class
                            'model' => $modelsPrItem[0],
                            'formId' => 'dynamic-form',
                            'formFields' => [
                                'po_item_no',
                                'quantity',
                            ],
                        ]); ?>

                                    <?php foreach ($modelsPrItem as $i => $modelPrItem): ?>

                                                    <button type="button" class="add-item btn btn-success btn-xs"></button>
                                                    <button type="button" class="remove-item btn btn-danger btn-xs"></button>

                                                <?php
                                        // necessary for update action.
                                        if (! $modelPrItem->isNewRecord) {
                                            echo Html::activeHiddenInput($modelPrItem, "[{$i}]PRID");
                                        }
                                    ?>

                                                            <?= $form->field($modelPrItem, "[{$i}]Quantity")->textInput(['maxlength' => 128]) ?>

                                                            <?= $form->field($modelPrItem, "[{$i}]Unit_Price")->textInput(['maxlength' => 128]) ?>

                                                            <?= $form->field($modelPrItem, "[{$i}]Extended_price")->textInput(['maxlength' => 128]) ?>

                                                            <?= $form->field($modelPrItem, "[{$i}]Currency_ID")->dropDownList(
                                             ArrayHelper::map(Tblcurrency::find()->all(),'CurrencyID','currency_symbol'),[]
                                            ); ?>

                                                            <?= $form->field($modelPrItem, "[{$i}]Description")->textArea(['maxlength' => 128]) ?>

                                        <?php endforeach; ?>

                                <?php DynamicFormWidget::end(); ?>

This is the model:
<?php

   namespace app\models;

       use Yii;
         use yii\helpers\ArrayHelper;

          class Model extends \yii\base\Model
       {
       /**
     * Creates and populates a set of models.
 *
 * @param string $modelClass
 * @param array $multipleModels
 * @return array
 */
public static function createMultiple($modelClass, $multipleModels = [])
{
    $model    = new $modelClass;
    $formName = $model->formName();
    $post     = Yii::$app->request->post($formName);
    $models   = [];

    if (! empty($multipleModels)) {
        $keys = array_keys(ArrayHelper::map($multipleModels, 'id', 'id'));
        $multipleModels = array_combine($keys, $multipleModels);
    }

    if ($post && is_array($post)) {
        foreach ($post as $i => $item) {
            if (isset($item['id']) && !empty($item['id']) && isset($multipleModels[$item['id']])) {
                $models[] = $multipleModels[$item['id']];
            } else {
                $models[] = new $modelClass;
            }
        }
    }

    unset($model, $formName, $post);

    return $models;
}

}
The above returns an error when i run update especially when updating more than one item

A: The error message say that the number of element in $keys and $values (alias $multipleModels  ) are not the same  so you are trying to build an associative array witth a wrong pair of key => value elements
Try var_dump (or inspect with xdebug) the content of the $keys and$multipleModels and adapt the code  to your real need .
if (! empty($multipleModels)) {
    $keys = array_keys(ArrayHelper::map($multipleModels, 'id', 'id'));
    var_dump($keys );
    var_dump($multipleModels);
    $multipleModels = array_combine($keys, $multipleModels);
}


text:
Q: New-ADUser -Name Length too long I need to add about 500 users to an OU in AD
I have scripted out everything I need, however, it gives the error:
the name provided is not a properly formed
Here is the script
New-ADUser -Name C080CAB1-9756-409F-914D-AE3971F67DE7 -Path "OU=Staging,DC=domain,DC=local" -accountPassword (convertto-securestring "zagreb+scotch8355" -asplaintext -force) -PasswordNeverExpires $True -CannotChangePassword $false -Enabled $true

I ran a couple test to confime what the problem is:
New-ADUser -Name "C080CAB1-9756-409F-914D-AE3971F67DE7" -Path "OU=Staging,DC=domain,DC=local" -accountPassword (convertto-securestring "zagreb+scotch8355" -asplaintext -force) -PasswordNeverExpires $True -CannotChangePassword $false -Enabled $true

New-ADUser -Name 'C080CAB1-9756-409F-914D-AE3971F67DE7' -Path "OU=Staging,DC=domain,DC=local" -accountPassword (convertto-securestring "zagreb+scotch8355" -asplaintext -force) -PasswordNeverExpires $True -CannotChangePassword $false -Enabled $true

New-ADUser -Name C080CAB1`-9756`-409F`-914D`-AE3971F67DE7 -Path "OU=Staging,DC=domain,DC=local" -accountPassword (convertto-securestring "zagreb+scotch8355" -asplaintext -force) -PasswordNeverExpires $True -CannotChangePassword $false -Enabled $true

Along with a couple other variations
What did work:
New-ADUser -Name C080CAB1-9756-409F -Path "OU=Staging,DC=domain,DC=local" -accountPassword (convertto-securestring "zagreb+scotch8355" -asplaintext -force) -PasswordNeverExpires $True -CannotChangePassword $false -Enabled $true

So I think it may be a length issue but I'm not sure how to get the script to work.

A: Do you want to Display name to that 36 char string or the login to be the 36 char string
If you are using server 2012 R2 you can only set the display name to 20 char however the login name can be up to 64 char (I think) using "-UserPrincipalName"
Try this
New-ADUser -Name C080CAB1-9756-409F-9 -UserPrincipalName C080CAB1-9756-409F-914D-AE3971F67DE7 -Path "OU=Staging,DC=domain,DC=local" -accountPassword (convertto-securestring "zagreb+scotch8355" -asplaintext -force) -PasswordNeverExpires $True -CannotChangePassword $false -Enabled $true

This will create the display name and to truncate value of the -UserPrincipalName which will be the user login name for the user.
See the properties of any user to set the appropriate flags.
http://thenerdservice.com/useradd.png
You can see that the pre-200 login is truncated however the User login Name is not
http://thenerdservice.com/userlogin.png

A: 20 character limit for sAMAccountName. No real way around it. What's funny is that there are 256 characters (~120 Unicode) reserved for it, but the Directory Services engine only lets you use 20.
Edit: Let me be a little more clear. You can have a Name that exceeds 20 characters, but not a sAMAccountName. That may suit your needs. Let me demonstrate:
New-ADUser C080CAB1-9756   # 20 character limit here

Rename-ADObject 'CN=C080CAB1-9756,CN=Users,DC=lab,DC=com

Get-ADUser C080CAB1-9756

DistinguishedName: CN=C080CAB1-9756-409F-914D-AE3971F67DE7,CN=Users,DC=lab,DC=com
Name             : C080CAB1-9756-409F-914D-AE3971F67DE7
SamAccountName   : C080CAB1-9756
DisplayName      :


text:
Q: Relation between line voltage and phase voltage in delta configuration I have read answers pertaining to this same question, but I could not understanf why the phase voltage is equal to line voltage. This answer says:

In a delta system, the two points required to measure a line voltage also happen to be the same two points connected across the phase.

What I don't understand is why aren't the rest two phases affecting this voltage since they both are connected to one point each and are out of phase. What am I failing to see?
I think I have not been able to express what my confusion is. I do understand since the points across which phase voltage is measured is also the point the lines are connected and I do agree with that, but if I compare the voltage for a delta configuration and other for an isolated AC supply I get the same values for the voltage. I don't understand why.

A: If I understand that what you are asking is "why are the sums of the other two phases equal to the phase I am looking at".
The other two phases are 120 degrees and 240 degrees shifted in phase from your "reference" phase if you add up sin(angle+120) and sin(angle+240) you get -sin(angle) this is consistent with your diagram and the way around your reference phase is shown connected. Hence the other two phases create exactly the same voltage as the phase you are looking at.
Following is a little table created in excel which illustrates this.


text:
Q: Google Drive API webhook returning change resources in wrong order I have a webhook setup with the Google Drive API, and it works for almost everything except when a file is deleted. It seems as though I always get 2/3 webhook notifications when a file changes, which isn't a problem.
When I delete a file however, those 2 notifications mess things up. They come out of order (i.e. change resource 989 comes before 999), and the new one comes first, invalidating the older change resource.
To explain, here are two post I received on my webhook, chronologically ordered.
This one has a good webhook, but the resource id in the param is 899.

http://i.stack.imgur.com/il3co.png
Now this one comes in after, which is has a param of 898, but I cannot use.

http://i.imgur.com/ZLwUC1Z.png
This last one most likely has the delete call I need, but cannot access.
Is this something I have to handle? Or is it something from google's side in terms of async calls?


text:
Q: Black screen on second activity on Android L emulator I am aware of the 'black screen problems' when starting Android L, see for example here:
Cannot create an emulator with Android L (API 20)
We had this problem too, and solved it by activating the 'Use Host GPU' setting. After that, we were able to start up the emulator and debug our app.
The main screen of the app appears to be fine, but as soon as we start another activity, a black screen appears. While the black screen is on screen, we can always go back to the main activity by pressing the (soft / hardware) back button.
To be clear, our app runs fine on KitKat (emulators and devices).
Any idea what could be wrong?

A: When you start another activity, A Black Screen appearance is because of the time that your system is taking to render the next activity on to your emulator's screen with your new version.
Most of the times, it does happen to render the screen/layout/activity results in black screen for longer times and if you can kill all other unused processes and help make the system cache resource free that should result in making things work fine.
I observed this happens with 4.4L emulators but there is NO issue with Kitkat or other version Emulators as the present allocated cache is enough.
As you've also mentioned that your app is working fine with KitKat version Emulator and with 4.4L you are seeing this issue but able to go back/homee without issues..the above might be the reason.
Another solution to this is in yoru HAXM settings, you can allocate more system cache than the existing and try to see if the problem goes. I've done this. Earlier, I've allocated 4GB Cache for Intel HAXM but increated to 6GB now and things look pretty cool as of now :)

A: Turns out the reason was that we were calling setContentView(_view); in onResume().
As soon as we moved that call to onCreate(), everything was working as expected.


text:
Q: what's the usage of named pipes ? can I connect from management studio using a named pipe? at the moment I turn on the TCP/IP in sql server network configuration and enable the ip used for connection
after I'm able to connect using management studio
I saw that there is also an option to connect using named pipes, but I could succeed to connect from management studio using the pipe name

A: It is possible to use named pipes only on the same machine (or on a local subnet).
Reference:
Named Pipes vs. TCP/IP Sockets

A: To quote MSDN from here http://msdn.microsoft.com/en-us/library/ms187892.aspx
Named Pipes vs. TCP/IP Sockets
In a fast local area network (LAN) environment, Transmission Control Protocol/Internet Protocol (TCP/IP) Sockets and Named Pipes clients are comparable with regard to performance. However, the performance difference between the TCP/IP Sockets and Named Pipes clients becomes apparent with slower networks, such as across wide area networks (WANs) or dial-up networks. This is because of the different ways the interprocess communication (IPC) mechanisms communicate between peers.
For named pipes, network communications are typically more interactive. A peer does not send data until another peer asks for it using a read command. A network read typically involves a series of peek named pipes messages before it starts to read the data. These can be very costly in a slow network and cause excessive network traffic, which in turn affects other network clients.
It is also important to clarify if you are talking about local pipes or network pipes. If the server application is running locally on the computer that is running an instance of SQL Server, the local Named Pipes protocol is an option. Local named pipes runs in kernel mode and is very fast.
For TCP/IP Sockets, data transmissions are more streamlined and have less overhead. Data transmissions can also take advantage of TCP/IP Sockets performance enhancement mechanisms such as windowing, delayed acknowledgements, and so on. This can be very helpful in a slow network. Depending on the type of applications, such performance differences can be significant.
TCP/IP Sockets also support a backlog queue. This can provide a limited smoothing effect compared to named pipes that could lead to pipe-busy errors when you are trying to connect to SQL Server.
Generally, TCP/IP is preferred in a slow LAN, WAN, or dial-up network, whereas named pipes can be a better choice when network speed is not the issue, as it offers more functionality, ease of use, and configuration options.

Using with SSMS
If named pipes is enabled when you install SQL Server, you can use it from SSMS. You may have to use CliConfg.exe to configure to setup a server for Named Pipes.


text:
Q: Add number to grouped pandas values in accordance to their occurrence in the group I would like to add a number to same room occurrences with the same ID. So my dataframe has two columns ('ID' and 'Room'). I want to add a number to each Room according to its occurrence in the column 'room' for a single ID. Underneath is the original df and the desired df.
Example: ID34 has 3 bedrooms so I want the first to be -> bedroom_1, the second -> bedroom_2 and the third -> bedroom_3.
original df:
ID     Room
34     Livingroom
34     Bedroom
34     Kitchen
34     Bedroom
34     Bedroom
34     Storage
50     Kitchen
50     Kitchen
89     Livingroom
89     Bedroom
89     Bedroom
98     Livingroom

Desired df:
ID     Room
34     Livingroom_1
34     Bedroom_1
34     Kitchen_1
34     Bedroom_2
34     Bedroom_3
34     Storage_1
50     Kitchen_1
50     Kitchen_2
89     Livingroom_1
89     Bedroom_1
89     Bedroom_2
98     Livingroom_1

Tried code:
import pandas as pd

import numpy as np

data = pd.DataFrame({"ID": [34,34,34,34,34,34,50,50,89,89,89,98],

                   "Room": ['Livingroom','Bedroom','Kitchen','Bedroom','Bedroom','Storage','Kitchen','Kitchen','Livingroom','Bedroom','Bedroom','Livingroom']})

df = pd.DataFrame(columns=['ID'])
for i in range(df['Room'].nunique()):
    df_new = (df[df['Room'] == ])

    df_new.columns = ['ID', 'Room' + str(i)]

    df_result = df_result.merge(df_new, on='ID', how='outer')

A: import inflect
p = inflect.engine()

df['Room'] += df.groupby('Room').cumcount().add(1).map(p.ordinal).radd('_')
print(df)

https://stackoverflow.com/a/59951701/3756587 I copied from here.

A: Lets try concatenate room with the cumcount of the df grouped by Room and ID as follows
df=df.assign(Room=df.Room+"_"+(df.groupby(['ID','Room']).cumcount()+1).astype(str))

ID          Room
0   34  Livingroom_1
1   34     Bedroom_1
2   34     Kitchen_1
3   34     Bedroom_2
4   34     Bedroom_3
5   34     Storage_1
6   50     Kitchen_1
7   50     Kitchen_2
8   89  Livingroom_1
9   89     Bedroom_1
10  89     Bedroom_2
11  98  Livingroom_1

A: Here is some code that can do that for you. I'm basically breaking it down into three steps.

*

*Perform a groupby apply to get apply a custom function on a group by operation. This allows you to generate new names for each pair of ID, Room.

*Reduce the multiindex to the original index. Because we are grouping on two columns the index is now a hierarchical grouping of the two columns. We are discarding the original because we want to use our new names.

*Perform an explode on each entry. This is because for simplicity, we are computing the apply result as an array. A subsequent explode then give each element in the array a unique row.

def f(rooms_col):
    arr = np.empty(len(rooms_col), dtype=object)
    for i, name in enumerate(rooms_col):
        arr[i] = name + f"_{i + 1}"
    return arr

# assuming data is the data from above
tmp_df = data.groupby(["ID", "Room"])["Room"].apply(f)
# Drop the old room name
tmp_df.index = tmp_df.index.droplevel(1)
# Explode the results array -> 1 row per entry
df = tmp_df.explode()
print(df)

Here is your output:
ID
34       Bedroom_1
34       Bedroom_2
34       Bedroom_3
34       Kitchen_1
34    Livingroom_1
34       Storage_1
50       Kitchen_1
50       Kitchen_2
89       Bedroom_1
89       Bedroom_2
89    Livingroom_1
98    Livingroom_1
Name: Room, dtype: object


text:
Q: Regex that match words and words with apostrophes Sorry if this is a duplicate post. I have a method that is supposed to parse all the words in a file. A word should only consist of letters a-z and an apostrophe. Here's my code snippet:
public void loadInput(File fileName) throws IOException {
        try{
            Scanner sc = new Scanner(fileName);
            int numWords = 0;
            while(sc.hasNext("[A-Za-z\']+")) {
                String word = sc.next().toLowerCase(); // case-insenstive
                numWords++;
                System.out.println(word);
            }
            System.out.println("Total words in text file: " + numWords);
            sc.close();
        } catch (Exception e) {
            System.out.println("Error has occured");
        }

    }

As an example input:
alice's conversations in it, `and what is the use of a book,'
thought alice `without pictures or conversation?'

It should match all the words including alice's but not 'without (it should match only the word without)

A: You want a negative lookbehind.
(?<!')[\w']+, find [\w']+ not preceed by a '.
See https://regex101.com/r/ZfyerX/3


text:
Q: GMVault Network Access Has anyone ever used GMVault before?  If so, are the messages downloaded from Google passed through any 3rd party server (like GMVault themselves)?  I'd only want the backup connection to be between myself and Google to keep everything secure.
Thanks!
GMVault - http://gmvault.org/

A: I confirm. I am the Gmvault developer and there is only a ssl connection between you and the Gmail IMAP server. OAuth is used to connect to the IMAP server but you could also use your password if you wanted to. OAuth is recommended method though.

A: No.
GMVault connects directly to Gmail using IMAP, and authenticates using OAuth.  (it doesn't see your password at all)


text:
Q: Does ADFS 3.0 honor the Subject attribute sent in SAML Request? According to the SAML2.0 specification, the service provider can send the Subject value in the SAML request, it sends to the IDP. This informs the IDP about the identity, the service provider needs to authenticate. But IDP has right either to honor either honor this or not. I am looking to know if ADFS honor this.
We are looking for a way to skip asking user to enter username at ADFS authentication, if the SAML request already contained it as Subject attribute.

A: I found the answer later. ADFS does not honor Subject attribute in this manner as of now.

A: For anyone else stumbling upon this, ADFS does not honor the subject, but you CAN pass the email / username using a regular query parameter:

Interesting. We support this if you send query parameters &username= or &login_hint= today. AAD uses this to send this to ADFS. It should work over SAML protocol as well.

https://windowsserver.uservoice.com/forums/304621-active-directory/suggestions/33404725-saml-subject-from-authnrequest


text:
Q: How to integrate Electron to WebStorm having no "Module is not installed" hint? My Electron project works just fine. But I can't go to the declaration of the electron plugin and I can't figure out how to solve that.
Basically I just wanna get rid of that hint shown in the image below and instead being able to go to it's declaration.
Module is not installed...
Unresolved function or method...
Thanks.

A: You'll need to install TypeScript type definitions for Electron, the first section of this blog post explains how to setup code completion for ReactJS in WebStorm:

To enhance code completion with typed parameter information we recommend that you add a TypeScript definition file for react.d.ts as a JavaScript library for the project.
Go to Preferences | Languages & Frameworks | JavaScript | Libraries, click Download…, select TypeScript community stubs, search for react and click Download. The file will be added as JavaScript library for WebStorm to use in coding assistance.

You should be able to install the Electron type definitions the same way, keep in mind that the typings for Electron are named github-electron (as opposed to just electron).


text:
Q: PowerShell merging data from multiple CSVs I have a bunch of CSV files containing information about DHCP scopes (100+ files, one for each server). I wish to merge the data from all into a new table. There are ways to merge the CSVs but that's not good enough, because one the most important piece of information is not included inside the individual CSV files...that of the server name. The server name is coming from the filename itself. Hence the approach to build a new table.
My issue is that the properties for SubnetMask, StartRange, EndRange, ScopeID and State are being output in the same "cell". I managed to do it for the ScopeName (i.e. managed to get one ScopeName per line), but not sure how to approach the rest.
$outputTable = $null
$files = Get-ChildItem -Path "C:\Temp\Discovery\" -Filter *Scopes.csv
Write-Host $files
ForEach($file in $files)
{
    $scopeFile = Import-Csv $file

    ForEach ($scopeName in $scopeFile.Name)
    {
        $outputTable += @(
                    [pscustomobject]@{
                    ` DHCPServer=$file.Name.ToString().Split(".")[0];
                    ` ScopeName=$scopeName;
                    ` SubnetMask=$scopeFile.SubnetMask;
                    ` StartRange=$scopeFile.StartRange;
                    ` EndRange=$scopeFile.EndRange;
                    ` ScopeID=$scopeFile.ScopeID
                    ` State=$scopeFile.State
                    }
                )
    }
}

$outputTable | ft

Current output:

Expected output:
DHCPServerName,ScopeName,SubnetMask,StartRange,EndRange,ScopeID,State
server1,london,255.255.0.0,192.168.0.1,192.168.0.254,192.168.0.1,Active
server1,london,255.255.0.0,192.168.1.1,192.168.0.254,192.168.1.1,Active
server1,london,255.255.0.0,192.168.1.1,192.168.0.254,192.168.1.1,NotActive

A: You can use a calculated property with Select-Object to add the file's Name as a new column of your Csv:
$merged = foreach($file in Get-ChildItem -Path C:\Temp\Discovery\ -Filter *Scopes.csv)
{
    Import-Csv $file.FullName | Select-Object @{
        Name = 'DHCPServerName'
        Expression = { $file.Name.Split(".")[0] }
    }, *
}

$merged | Format-Table


text:
Q: Broadcast Live Session From Website via WebRTC To Ant Media Server And Then To Facebook Live I'm building a web app that lets users start a live broadcast by:

*

*Going to our website & login with Facebook with the permissions to create live videos

*Click on the "Start Live Video" button on our website.

*That will create a new FB Live stream using Facebook API and an RTMPS URL will be returned

*The user starts their live broadcast. We capture video on our website and push the video stream to Ant Media Server using WebRTC.

*We then want Ant Media Server to rebroadcast the live broadcast to the RTMPS URL we'll provide it so that the broadcast will be sent to Facebook Live
We've managed to do steps 1-4 but we're having trouble with (5). Does anyone have any experience with this?
Thanks a lot.
Charles Tang


text:
Q: How to minimize my css files using webpack i'm using webpack and would like to minimize css file. At this time it is 2.25MB. I found this optimize-css-assets-webpack-plugin plugin but it din't help and my css file is same size. Here is my settings
'use strict';
const webpack = require('webpack');
const merge = require('webpack-merge');
const webpackCommon = require('./webpack-common.config');
var OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');

module.exports = merge(webpackCommon, {
   devtool: 'none',
   plugins: [
      new webpack.optimize.OccurrenceOrderPlugin(),
      new webpack.optimize.AggressiveMergingPlugin(),
      new webpack.optimize.DedupePlugin(),
      new webpack.optimize.UglifyJsPlugin({
         /\.js$/,
         beautify: false,
         comments: false,
         compress: {
            unused: true,
            dead_code: true,
            warnings: false,
            screw_ie8: true
         }
      }),
      new webpack.NoErrorsPlugin(),
      new webpack.DefinePlugin({
         'process.env.NODE_ENV': JSON.stringify('production'),
         '__DEV__': false
      }),
      new webpack.optimize.CommonsChunkPlugin({
         minChunks: 2,
         maxChunks: 15,
         minChunkSize: 10000,
         name: 'vendor'
      }),
      new OptimizeCssAssetsPlugin({
         assetNameRegExp: /\.scss$/g,
         cssProcessor: require('cssnano'),
         cssProcessorOptions: { discardComments: { removeAll: true } },
         canPrint: true
      })
   ]
});

this is prod config and it requires common config file. Here it is
'use strict';

const path = require('path')
const webpack = require('webpack')
var ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
   entry: {
      main: './src/main.js',
   },
   output: {
      filename: '[name].js',
      path: path.resolve(__dirname, '../../PashaGraph/WebClient/public')
   },
   watch: true,
   watchOptions: {
      aggregateTimeout: 100
   },
   plugins: [
      new ExtractTextPlugin("[name].css")
   ],
   module: {
      loaders: [
         {
            test: /\.js$/,
            exclude: /node_modules/,
            loader: 'babel'
         },
         {
            test: /\.scss$/,
            loader: ExtractTextPlugin.extract('style', 'css?sourceMap!sass?sourceMap')
         },
         {
            test: /\.css$/,
            loader: ExtractTextPlugin.extract('style', 'css-loader?minimize!sourceMap')
         },
         {
            test: /\.woff2?$|\.ttf$|\.eot$|\.svg$|\.png|\.jpe?g|\.gif$/,
            exclude: /node_modules/,
            loader: 'url-loader'
         }
      ]
   },
   resolve: {
      extensions: ['', '.js', '.jsx']
   }
};

as u see i use sass in my app. Maybe this is a reason why it doesn't reduce size.
Solved! actually i have fonts and they were converted and embedded into css file. Thats why it was such big event with compression (2.25mb).
By the way i found this solution to restrict maximal size for embedding
{
            test: /\.woff2?$|\.ttf$|\.eot$|\.svg$|\.png|\.jpe?g|\.gif$/,
            exclude: /node_modules/,
            loader: "url-loader?limit=60&name=fonts/[name]_[hash].[ext]"
         }

A: Just run the webpack with -p option. It will build for production with very high compression.

webpack -p

Also, you may need to set the Node_Environment to production else the final build will give some warning message in the browser's console.

A: You can also minify css classnames - that can give up to 40% in bundle size reduction.
https://github.com/vreshch/optimize-css-classnames-plugin

A: Don't use source maps in production code. Remove !sourceMap.


text:
Q: dropbox service fails or succedes depending on time spent at the login screen I think I've been doing more than a dozen system reboots in the last few minutes to check this strange behavior.
It seems that the service of dropbox succedes or fails in running at startup depending on how much time I spend at the login screen where I enter the password. I've not done any timing, so I don't know what much time exactly is, but it's not more than a half a dozen seconds.
When I enter the password quickly, Dropbox starts up, indeed I verify the following,
$ systemctl status dropbox@enrico.service
● dropbox@enrico.service - Dropbox
   Loaded: loaded (/usr/lib/systemd/system/dropbox@.service; enabled; vendor preset: disabled)
  Drop-In: /etc/systemd/system/dropbox@enrico.service.d
           └─override.conf
   Active: active (running) since Wed 2018-06-13 17:07:04 CEST; 6min ago
 Main PID: 1006 (dropbox)
    Tasks: 84 (limit: 19660)
   Memory: 148.0M
   CGroup: /system.slice/system-dropbox.slice/dropbox@enrico.service
           ├─1006 /usr/bin/dropbox
           ├─1052 dbus-launch --autolaunch 9f3c6fabb4aa40d1b7d5b3a3881af003 --binary-syntax --close-stderr
           ├─1053 /usr/bin/dbus-daemon --syslog-only --fork --print-pid 5 --print-address 7 --session
           └─1057 /usr/bin/dunst

Jun 13 17:07:05 greywarden dropbox[1006]: dropbox: load fq extension '/opt/dropbox/PyQt5.QtWebKitWidgets.so'
Jun 13 17:07:05 greywarden dropbox[1006]: dropbox: load fq extension '/opt/dropbox/PyQt5.QtWidgets.so'
Jun 13 17:07:05 greywarden dropbox[1006]: dropbox: load fq extension '/opt/dropbox/PyQt5.QtPrintSupport.so'
Jun 13 17:07:05 greywarden dropbox[1006]: dropbox: load fq extension '/opt/dropbox/PyQt5.QtDBus.so'
Jun 13 17:07:05 greywarden dbus-daemon[1053]: [session uid=1000 pid=1051] Activating service name='org.freedesktop.Notifications' requested by ':1.0' (uid=1000 pid=1006 comm="/usr/bin/dropbox ")
Jun 13 17:07:05 greywarden org.freedesktop.Notifications[1053]: Warning: 'allow_markup' is deprecated, please use 'markup' instead.
Jun 13 17:07:05 greywarden org.freedesktop.Notifications[1053]: Warning: The frame section is deprecated, width has been renamed to frame_width and moved to the global section.
Jun 13 17:07:05 greywarden org.freedesktop.Notifications[1053]: Warning: The frame section is deprecated, color has been renamed to frame_color and moved to the global section.
Jun 13 17:07:05 greywarden org.freedesktop.Notifications[1053]: Warning: Unknown keyboard shortcut: mod4+grave
Jun 13 17:07:05 greywarden dbus-daemon[1053]: [session uid=1000 pid=1051] Successfully activated service 'org.freedesktop.Notifications'

On the other hand, when I'm too slow in entering the password (e.g. type, backspace, retype, ...) or I'm simply not looking at the screen while I'm reading a book, the output is
$ systemctl status dropbox@enrico.service
● dropbox@enrico.service - Dropbox
   Loaded: loaded (/usr/lib/systemd/system/dropbox@.service; enabled; vendor preset: disabled)
  Drop-In: /etc/systemd/system/dropbox@enrico.service.d
           └─override.conf
   Active: failed (Result: exit-code) since Wed 2018-06-13 17:15:03 CEST; 39s ago
  Process: 1031 ExecStart=/usr/bin/dropbox (code=exited, status=250)
 Main PID: 1031 (code=exited, status=250)

and dropbox is indeed not running (no tray icon).
I'm running i3 on ArchLinux and LightDM login manager. I followed Prevent automatic updates and Autostart sections at the wiki page, but it's not unlikely that I made confusion between Autostart on boot with systemd and Autostart on login with systemd and that could be the root of the problem.

A: As suggested in the first comment to the question, this wikipage solved the issue.


text:
Q: How to do it right Singleton for Application? This is my code but it doesn't work
    class App : Application() {

        override fun attachBaseContext(base: Context?) {
            super.attachBaseContext(base)
        }

        companion object {
            val instance: App = App()
        }
    }

I need him that I worked with SharedPreferences.Because without a context it will be wrong
     SharedPreferences preferences = AppSingleton.getInstance().getSharedPreferences("userInfo", AppCompatActivity.MODE_PRIVATE);

            OkHttpClient client = new OkHttpClient.Builder()
                    .addInterceptor(logging)
                    .addInterceptor(new AccessTokenInterceptor(preferences))
                    .build();

There i use it to add to AccessTokentInterceptor
but it is not important
The Error
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference

Help me pls

A: AppSingleton.getInstance() is returning null.  Take a look at that class and see why it is null.

A: You should override onCreate() method and assign the reference from there
class App: Application() {
    companion object {
        lateinit var instance: App
    }

    override fun onCreate() {
        instance = this
        super.onCreate()
    }
}


text:
Q: How to disallow Perforce UNIX server to generate thousands of IDLE processes Im' asking this question because we run out of ideas on how to handle the current situation of our perforce versioning server.
The Server
The server is hosted on Scaleway and has a baremetal machine with two SSD under the hood (we know it is no hardware issue).
We are currently using the free license of perforce to evaluate it.
P4 info yields the following:

The Problem
We are using perforce on a UNIX server to version our Unreal Engine 4 project. Lately we discovered that the server stockpiled an amount of 2771 processes where around 80% of them are p4d processes. We suspect these IDLE connections / processes to swamp the server and to be the root of the connectivity issues we encounter at the office.
We enabled monitoring to keep an eye on RUNNING and IDLE processes
p4 configure set monitoring=2

When we now display the monitored processes we see IDLE ones running for more than one hour
p4 monitor show

We already tried disabling leepalive connections with
p4 configure set net.keepalive.disable=1

And we see the following which is going on for a while

The Question
Now the question I want to ask is:

*

*Does anybody else ever has encountered this behaviour with a perforce server on UNIX?

*Does anybody knows how we can tell the server that we want to discard IDLE connections ?

EDIT
So after some tracking we discovered that the proxy our office network is behind causes the problems and for some reasons don't allow the connections to close. Does anyone has some clues how to get around these issue?

A: Based on the monitor output it appears that these clients are opening a bunch of connections and holding them open, basically DOSing the server.  You could go through and kill the pids on the server side, but this sounds like a bug in the client that should be raised with Perforce technical support.


text:
Q: How does Bravia Engine get called on AOSP? I found the AOSP source code from Google and also retrieved vendor's info from                                                 https://github.com/sonyxperiadev/device-sony-sgp321
Sony added its Bravia Engine library to AOSP to improve image and video quality. It can either be called in libstagefright's awesomelocalrenderer or called at the decoding phase, when OMX addPlugin is called.
I searched both places, the code there are the same compare with other native AOSP source code. I would like to know how does Sony use its BE library?

A: My guess is that all vendor specific binaries are just implementing the standard interface defined by Android/OMX.
And these engine is complied into shared objects which can be found at /system/vendor directory.
The Android system just have to look at the directory and load the necessary shared objects.

A: Bravia engine is mainly employed for video/image post-processing prior to rendering on the framework. There is an interesting link at http://developer.sonymobile.com/2012/06/21/mobile-bravia-engine-explained-video/.
In AOSP, I presume the user settings from the menu are read and subsequent filtering is enabled/applied in SurfaceFlinger or HwComposer parts of the framework. Another link of interest could be: http://blog.gsmarena.com/heres-what-sony-ericsson-mobile-bravia-engine-really-does-review/
EDIT: Interaction between Video Decoder - AwesomePlayer - HwComposer
The following is a summary of interactions between the different actors in the playback and composition pipeline.

*

*AwesomePlayer acts as a sink to the OMX Video Decoder. Hence, it will continuously poll for a new frame that could be available for rendering and processing.

*When OMX Video Decoder completes the decoder, the FillBufferDone callback of the codec will unblock a read invoked by the AwesomePlayer.

*Once the frame is available, it is subjected to the A/V synchronization logic by the AwesomePlayer module and pushed into SurfaceTexture via the render call. All the aforementioned steps are performed as part of AwesomePlayer::onVideoEvent method.

*The render will queue the buffer. This SurfaceTexture is one of the layers available for the composition to the  SurfaceFlinger.

*When a new layer is available, through a series of steps, SurfaceFlinger will invoke the HwComposer to perform the composition of all the related layers.

*AOSP only provides a template or an API for the HwComposer, the actual implementation of which is left to the vendor.


text:
Q: PHP (Nette framework) automatic coding standards check I would like to have some type of automatic checking of coding standards for PHP Nette Framework is there anything like this? Standalone application or plugin for Eclipse, Netbeans ... For example to check Java code I use Checkstyle. Or can Checkstyle also check Nette?

A: Most up-to-date tool is https://github.com/nette/code-checker (it's extracted from https://github.com/nette/tools).

A: There is Nette code checker here: https://github.com/nette/tools
You can also try this CodeSniffer standard written: https://github.com/juzna/nette-coding-standard

A: In 2017, there is official coding standard set to be used: nette/coding-standard
If you want to use it, just follow this tutorial.


text:
Q: Is there an official XML Schema (xsd) for EDI X12 856? I am still fairly new to EDI, and learning it on a new job. We are using BizTalk for our EDI solution, and are converting the incoming EDI file into XML. I was having problems with a file from a new vendor, and at first thought the file might be incorrect. I have since learned that the file is correct, but our current XML schema is home grown, and would basically need to be tailored to accept this 856. I guess some of the data being passed in is more then what our usual vendors pass to us (still valid according to EDI X12 856 though).
While I could do this, it seems like the real answer is getting an xsd file for the actual EDI spec. It seems like with such a standardized format it should already exist. Does anyone know if such a thing is available?
UPDATE: It turns out there is a built in EDI mapping capability that is done in the pipeline through the "EDI Disassembler" component. This converts to a standardized BizTalk EDI schema and is working correctly. Apparently our code then converts that XML into our own XML schema. There is definitely room to improve, but I think the information on schema standards is what I am looking for at this point.

A: I don't quite understand the question. I'm assuming BizTalk has EDI mapping capabilities, and that you've used it to map elements of the EDI format to your XML tags. If they're sending a segment that's not in your schema, doesn't the mapper ignore it?
Assuming the sender is using XML EDI rather than binary EDI, there are schemas available. http://www.x12.org/ has a link to them (requires JavaScript), but you have to register. I'm used to paying for everything EDI-related (documentation, translation, testing, etc.) so you may have to purchase them.
Here's an additional link I found to a commercial product: stylusstudio
EDIT: Direct link: http://xml.x12.org/


text:
Q: Dice Program in Java I am making a dice simulator, and my task is to roll 4 dice at a time, add up each face of the die, and repeat that process as many times as I want. Then I have to record how many times each roll (the 4 dice added up) happened, and make a table.
What I am basically struggling with is how to loop my code so that it can repeat the roll as many times as I want, keeping track of the numerical value of each roll. Here is my code so far:
This is my program for the Die:
import java.util.Random;

public class Die
{
   private Random generator;
   private int sides;
   public Die (int s)
   {
      sides = s;
      generator = new Random();
   }

   public int cast()
   {
      return 1 + generator.nextInt(sides);
   }
}

And this is my Die Simulator program:
import java.util.Scanner;
import java.util.Random;

public class DieSimulator
{
   public static void main(String[] args)
   {
      Die d1 = new Die(6);
      Die d2 = new Die(6);
      Die d3 = new Die(6);
      Die d4 = new Die(6);
      final int TRIES = 1;
      for (int i = 1; i <= TRIES; TRIES +)
      {
         int n1 = d1.cast();
         //System.out.print(n1 + "");
         int n2 = d2.cast();
         //System.out.print(n2 + "");
         int n3 = d3.cast();
         //System.out.print(n3 + "");
         int n4 = d4.cast();
         System.out.print(n4 + n3 + n2 + n1);
         n = n4 + n3 + n2 + n1

      }
      System.out.println();
   }
}

The commented section of the Die simulator program was just me trying to figure out how to post the numerical values of the roll.
any help would be appreciated

A: You can create a new class which deals with the four dice:
public class Dice {
    private Die[] dice;
    public Dice(int noOfDice, int maxValueOfDice) {
        dice = new Die[noOfDice];
        for( int i = 0; i < dice.length; ++i){
            dice[i] = new Die(maxValueOfDice);
        }
    }
    public int cast(){
        int sum = 0;
        for( Die d : dice){
            sum += d.cast();
        }
        return sum;
    }
}

Keeping track of the values rolled is possible by using a map or an array:
import java.util.HashMap;
import java.util.Map;

public class Statistics {
    static int TRIES = 1000;
    public static void main(String[] args)
    {
        Dice dice = new Dice(4, 6);
        Map<Integer,Integer> map = new HashMap<>();
        // roll TRIES times
        for (int i = 1; i <= TRIES; ++i){
            int value = dice.cast();
            if( map.containsKey(value)){
                map.put(value, map.get(value)+1);
            } else {
                map.put(value,1);
            }
        }
        // print all results:
        for( Integer key : map.keySet()){
            System.out.println("Value " + key + " rolled " + map.get(key) + " times");
        }
    }
}

A: I really like the structure of your program, but i think it would be much simple if you didn't bother with another Class.
The easiest way to keep track of each individual roll is:
**int [][] results = new int[nDices][nRolls];**

You iterate through each throw easily by:
Random r = new Random();
int currSum=0;
int oneRollSum=0;
for(int i=0; i<nRolls;i++){
    for(int j=0; j<nDices; j++){
       results[j][i]= r.nextInt(6)+1;
       oneRollSum=oneRollSum+results[j][i];
       currSum=results[j][i]+currSum;
    }
    oneRollSum=0;

}


text:
Q: PHP announcements system errors I want to make a simple announcements system where you just type announcements in a box and it can be viewed by others. I get this error when I submit the form:
Edit:
Thanks, the php_announce.php now works, it does everything it's supposed to do, this is the new code :
<?php
// MySQL
$servername = "localhost";
$username = "testuser";
$password = "testpass";
$dbname = "testbase";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
// Content
$content = $conn->real_escape_string($_POST['content']);
$query="INSERT INTO announcements (content) VALUES ('$content')";
$conn->query($query)
?>

Edit: Thanks for the help I fixed the code like this:
after creating connection it does this:
$result=$conn->query("SELECT * FROM announcements");
#print_r($result);
while($row = $result->fetch_array(MYSQLI_ASSOC)){

echo $row['content']. "

 ". "Posted by: You";
echo "
";
}

A: In the first case, you need to provide a list of columns that correspond to the values you're trying to insert. e.g:
$query="INSERT INTO announcements (content) VALUES ('$content')";
Replace content with the name of the column in your table.
For the second one, the error message doesn't appear to correspond with the code you posted, but I'm guessing you forgot a semicolon on the preceding statement. Additionally, there's a missing ; in your last echo statement, although I'm not sure if that's what's causing the specific message you posted. Please repost the latest code from announce_out.php and I'll try to help.
There are some other issues with this approach in general. You're mixing mysqli and the older mysql, which is going to cause you additional errors. Instead of calling mysql_query(), you should be using $conn->query($query) so that you're actually using the connection you are establishing with new mysqli(). Additionally, to prevent injection attacks, you should escape your $content variable in this way:
$content = $conn->real_escape_string($_POST['content']);
This is a pretty basic way to escape strings and there are better methods like prepared statements that mysqli provides. I recommend checking out the page in the PHP manual: http://php.net/manual/en/mysqli.quickstart.php

A: The immediate answer to your problem is:
You need to escape the content and let the function quote it for you.
$content= mysql_real_escape_string($_POST['content'], $conn);
$query="INSERT INTO announcements VALUES ($content)";

and you need a missing semicolon at the end of the echo statement.
echo $row['content']. "

 ". "Posted by: You";

The long term answer is you should really look into a database abstraction layers which help you avoid incredibly dangerous errors you're likely to make (like incorrectly escaping content). See php manual for some basic ones: http://php.net/manual/en/refs.database.abstract.php
But I also highly recommend using a higher level framework like Doctrine http://www.doctrine-project.org/.


text:
Q: Answering a duplicate question Is it wrong to answer a question and also mark it as a duplicate?
I came across a question which I feel was duplicate so marked it so, but also posted an answer to the question. The reason I answered is I may have been able to remove a step for the question asker (they don't need to follow the link to the duplicate question) and I also just picked out the information they were specifically asking from the duplicate answer. However I worry I could be encouraging bad habits, as people feel they don't need to bother searching as they will get an answer regardless of whether their question is a duplicate.

A: Fundamentally yes, as it splits the answers to the problem up and future visitors will have to look in two (or more) places to check all the possible solutions to their problem. Duplicates are OK (different wordings, problem statement etc.) but they should all point to the one place where the answers live.
However, that said, it might not be apparent that the question is a duplicate a first sight and you only might realise later. In this case there's a couple of things you can do.

*

*Delete your answer and repost it on the duplicate target (assuming it adds new information).

*If there are other answers on the question you answered then flag then flag it for moderator attention with the "other" option asking for the questions to be merged. NOTE: This is only really done if the questions are exact duplicates so might not happen.


text:
Q: Limit of a quotient involving the gamma function This is a continuation of another question I asked. It seems only incidentally related to statistics, so I figured it would be better separate.  (Also, I'm not able to make nearly as much progress on this one.)
Let
$$c=\frac{\sqrt{n-1}\Gamma\left(\frac{n-1}{2}\right)}{\sqrt{2}\Gamma\left(\frac{n}{2}\right)}$$
What is the limit of $c$ as $n \rightarrow \infty$?
My TI-83 blows up around $n=100$, and convergence there seems pretty slow, so I can't say for sure. But it looks as though the answer could be $1$.
As for showing that... I've tried breaking it up into two cases:  one where $n$ is odd and one where it's even. More accurately, I got something for odd $n$ and didn't see much point in exploring the even case, since it would probably look just as inscrutable.
If $n$ is the $k$th odd number — i.e., $n = 2k - 1$, then $\Gamma\left(\frac{n-1}{2}\right)=\Gamma(k-1)=(k-2)!$ and
$$\Gamma(n/2)=\left[\prod_{i=1}^{k-1} (2i-1)\right]\frac{\sqrt{\pi}}{2^{k-1}}$$
This can be rewritten as
$$\frac{\sqrt{\pi}}{2^{k-1}}\cdot\frac{[2(k-1)]!}{(k-1)!2^{k-1}}$$
The ratio of the two gamma functions, then, can be written as
$$\frac{[(k-1)!]^2 2^{2k-2}}{\sqrt{\pi}[2(k-1)]!(k-2)}$$
Without getting into specifics, I could kinda see a lot of the terms on top being absorbed by those in the bottom, but then I guess if I'm saying it converges to $1$, I wouldn't want them to be absorbed too much.
If anyone can offer ideas for the next step, I'd very much appreciate it.

A: The $\Gamma$ function is a log-convex function as a consequence of its definition through the Bohr-Mollerup theorem or the integral version of the Cauchy-Schwarz inequality:
$$ \Gamma\left(\frac{\alpha+\beta}{2}\right)^2 = \left(\int_{0}^{+\infty}x^{\alpha+\beta}\frac{e^{-x}\,dx}{x}\right)^2\leq \Gamma(\alpha)\,\Gamma(\beta). $$
A nice consequence of the log-convexity is Gautschi's inequality:
$$ x^{1-s} \leq \frac{\Gamma(x+1)}{\Gamma(x+s)}\leq (1+x)^{1-s} $$
that easily proves that your limit is $\color{red}{\large 1}$ by squeezing.


text:
Q: Can you use DBeaver without connecting to a database? I would like to develop a ER diagram using DBeaver (Eclipse plugin) for a database that doesn't yet exist. Also, the database server doesn't exist.
Can DBeaver be used to develop a ER diagram without connecting to an existing database server? I can only find documentation for working with an existing database or connecting to an existing database server.

A: Nope, sorry.
DBeaver tools are always associated with the current connection.
For example, in the ERD when adding tables, DBeaver often sends requests to the database of foreign keys.
You can use standard sample SQLite database in DBeaver for experiments.


text:
Q: How to get chromedriver working on android? java example? I would like to be able to do testing using chromedriver on Android device. How is it possible?
I have rooted an Android device and cannot get the Chrome tests to work.
I tried to follow this guide: https://sites.google.com/a/chromium.org/chromedriver/getting-started/getting-started---android
I cannot find which Chromedriver version I should install on Android device.
Does anyone have an example or step by step guide for this?

A: You don't need to install chromedriver on a phone, only your local machine you want to run tests from. I actually set this up couple weeks ago. This is basic set up you need:
public WebDriver getMobileChromeDriver() {
    ChromeOptions chromeOptions = new ChromeOptions();
    chromeOptions.setExperimentalOption("androidPackage", "com.android.chrome");
    chromeOptions.setExperimentalOption("androidDeviceSerial", deviceId);
    return new ChromeDriver(chromeOptions);
}
deviceId variable contains uuid taken from adb for particular device. If you don't provide it chromedriver will run on first available node.
One more thing you need to do before running tests is start adb server.
On linux based machines it would be something like:
adb start-server
(assuming you have adb in your path)
If you have problem with determining which chromedriver you need for your local machine let me know.
If you are using Windows machine you probably need to add one more line of code to point to your chrome binary:
System.setProperty("webdriver.chrome.driver", "<path_to_your_chrome_binary>");

A: For me, the previous answer works but with Chrome version 66 and chrome driver 37.
System.setProperty("webdriver.chrome.driver", "<path_to_your_chrome_binary>");

Even if system property is "webdriver.chrome.driver", you have to set the path of chrome on the device like "/data/app/com.android.chrome-1.apk"


text:
Q: characteristic polynomial and eigenvalues Find the characteristic polynomial and eigenvalues of
$A=\left[\begin{matrix} 3 & 1 & 1 \\
0 & 5 & 0 \\
-2 & 0 & 7\end{matrix}\right]$
$$
\begin{align*}
\det(A-\lambda I) &=
\begin{vmatrix}
3-x & 1 & 1 \\
0 & 5-x & 0 \\
-2 & 0 & 7-x
\end{vmatrix}\\
&=
(3-x)
\begin{vmatrix}
 5-x & 0 \\
   0 & 7-x
\end{vmatrix}
+1(-1)
\begin{vmatrix}
 0 & 0 \\
-2 & 7-x
\end{vmatrix}
+1\begin{vmatrix}
 0 & 5-x  \\
-2 & 0
\end{vmatrix}\\
&=(3-x)(5-x)(7-x)+1[0-(-2(5-x))]\\
&=(3-x)(35-5x-7x-x^2)+1(0-(-10+2x))\\
&=(3-x)(35-5x-7x-x^2)+1(0+10-2x))\\
&=(3-x)(35-5x-7x-x^2)+11-2x\\
&=105-36x+3x^2-35x+12x^2-x^3+11-2x\\
&=116-73x+15x^2-x^3\\
&=-x^3 +15x^2 -73x +116 = 0\\
\end{align*}
$$

A: Hint:
As there are a number of $0$s, compute $\det(A-\lambda I)$ using the rule of Sarrus. You'll have at once $\lambda -5\,$ factored out in the determinant, and you'll only have to solve a quadratic equation to find the remaining eigenvalues.

A: Using Laplace expansion for the second row we get:
$\begin{vmatrix}
  3-x & 1 & 1 \\
  0 & 5-x & 0 \\
  -2 & 0 & 7-x
\end{vmatrix}=
(5-x)\begin{vmatrix}
  3-x  & 1 \\
  -2 & 7-x
\end{vmatrix}=
(5-x)(x^2-10x+23)$
(We used second row, because two elements of that row are zero, so the expansion has only one non-zero term.)
Can you find roots (eigenvalues) from there?
You can check your results on WA:
http://www.wolframalpha.com/input/?i=%5B%5B3%2C1%2C1%5D%2C%5B0%2C5%2C0%5D%2C%5B-2%2C0%2C7%5D%5D
http://www.wolframalpha.com/input/?i=x%5E2-10x%2B23%3D0

Two comments on your attempted solution (which was posted in the original version of your post and then several times removed or added back - see the revision history):

*

*You made a mistake that when you replaced $1(10-2x)$ by $11-2x$.

*If you notice that all summands contain the common fact $5-x$, you could get the result in simpler form.


text:
Q: soft delete from an array of objects using mongoose I am trying to soft delete an object from array using mongoose-delete lib
I Have a schema like that :
const mongooseDelete = require('mongoose-delete');

const number = new Schema({
    allocation_date: { type: Date, required: true, default: Date.now() },
    number: { type: String, required: true },
    virtual_number: { type: String, required: true },
    virtual_number_id: { type: Number, required: true, unique: true },

});

const schema = new Schema(
    {
        allocation_id: { type: String, required: true, unique: true },
        numbers: { type: [number], required: true },
    },
    {
        timestamps: true,
    },
);

number.plugin(mongooseDelete, { deletedAt : true });

exemple data :
   {
      "_id": "5f7c14f9388ee9ebc0b28abc",
      "allocation_id": "5_2_9387323_1"
      "numbers": [
        {
          "allocation_date": "2020-10-06T06:55:41.197Z",
          "_id": "5f7c14f997d996f7988fe8cf",
          "number": "*********",
          "virtual_number": "**********",
          "virtual_number_id": *******,
        },
        {
          "allocation_date": "2020-10-06T06:59:41.197Z",
          "_id": "5f7c14f997d996f7988fe8cf",
          "number": "*********",
          "virtual_number": "**********",
          "virtual_number_id": *******
        }
      ],
      "createdAt": "2020-10-06T06:55:53.367Z",
      "updatedAt": "2020-10-06T06:55:53.367Z",
    }

When I tried to use the delete method as follow  :
const deleteNumber = await VirtualNumberAllocation.findOne(
        {
            'numbers.virtual_number': virtualNumber.virtualNumber,
            allocation_id: virtualNumber.allocationID,
        });

const activeVirtualNumber = deleteNumber.numbers.filter(
            (number) => number.virtual_number==virtualNumber.virtualNumber,
        );

await activeVirtualNumber[0].delete();

I'm getting this error in console:
mongoose: calling `save()` on a subdoc does **not** save the document to MongoDB, it only runs save middleware. Use `subdoc.save({ suppressWarning: true })` to hide this warning if you're sure this behavior is right for your app.

Does anyone have experience with soft deleting from an array using the library?


text:
Q: wordpress wp_insert_attachment() url has wrong file directory i have following code:
$wp_filetype = wp_check_filetype( basename( $image_url ), null );
$wp_upload_dir = wp_upload_dir();
$attachment = array(
    'guid' => $wp_upload_dir['url']. '/' . basename( $image_url ),
    'post_mime_type' => $wp_filetype['type'],
    'post_title' => preg_replace('/\.[^.]+$/', '', basename($image_url)),
    'post_content' => '',
    'post_status' => 'publish'
);

$attach_id = wp_insert_attachment( $attachment, $image_url );

everything works fine, but the attached img tag has a different url than expected in its src attribute. ( wp-contents/uploads  instead of wp-contents/uploads/2013/03/ )

A: Try changing $wp_upload_dir['url'] to $wp_upload_dir['path'], or $uploads['baseurl'] . $uploads['subdir'].


text:
Q: How to apply filter on recent N Outlook.Items and get Outlook.Items after filtering? I want to use the following code to filter out Unread outlook mails,but I want to apply this Restriction on recent N Outlook.Items.But I could not find any such method.
Outlook.Explorer currExplorer = null;
Outlook.Folder currFolder = null;
Outlook.Items folderItems = null;
Outlook.Items restrictedItems = null;
Outlook.MailItem mail = null;
Outlook.Attachments attachments = null;
int attachmentCount = 0;

try
{

    currExplorer = OutlookApp.ActiveExplorer();
    currFolder = currExplorer.CurrentFolder as Outlook.Folder;
    if (currFolder.DefaultItemType == Outlook.OlItemType.olMailItem)
    {
        folderItems = currFolder.Items;
        restrictedItems = folderItems.Restrict("[Unread]=true");

        for (int i = 1; i <= restrictedItems.Count; i++)
        {
            mail = restrictedItems[i] as Outlook.MailItem;
            if (mail != null)
            {
                attachments = mail.Attachments;
                attachmentCount += attachments.Count;
                Marshal.ReleaseComObject(attachments);
                Marshal.ReleaseComObject(mail);
            }
        }

    }

}

A: You need to use the Restrict method twice - first for getting the recent N items and second for getting unread items between them. There is no query to get the N items in the collection, but you can use the time and time range for filtering items, see Enumerating, Searching, and Filtering Items in a Folder  for more information.
You may find the following articles helpful:

*

*How To: Use Restrict method to retrieve Outlook mail items from a folder

*How To: Use Find and FindNext methods to retrieve Outlook mail items from a folder (C#, VB.NET)


text:
Q: Custom DynamoDBMapper with spring-data-dynamodb Let's say I have a case when I need to use different DynamoDb tables with different environments.
For example, I want to have DevTable on dev and ProdTable on prod.
So, is there any way to use custom DynamoDBMapper with spring-data repositories?

A: DynamoDBMapperConfig provides a way to override the TableName specified on the Entity object using @DynamoDBTable annotation, through TableNameOverride class.
You can define a TableNameOverride bean that modifies the table name at runtime, in your spring-data based application. See https://github.com/derjust/spring-data-dynamodb/wiki/Alter-table-name-during-runtime.


text:
Q: How to input a time into firebase with AngularFire? I'd like a user to be able to submit a time into the firebase database by selecting a time from the input box.
I know how to have the user enter text into firebase based on the firebase documentation, but not how the user can enter in a time into firebase.
When I add "type="time"' to the input box (as below), the below code can no longer submit input to firebase. When it's removed, it goes back to normal.
HTML

        <input ng-model="message.text" ng-change="messages.$save(message)" />

        <button ng-click="messages.$remove(message)">Delete Message</button>

    <form ng-submit="addMessage()">
      <input type="time" ng-model="newMessageText" />
      <button type="submit">Add Time</button>
    </form>

AngularJS
var app = angular.module("sampleApp", ["firebase"]);

app.controller("SampleCtrl", function($scope, $firebaseArray) {
  var ref = new Firebase("https://frontier.firebaseio.com/messages");
  $scope.messages = $firebaseArray(ref);

  $scope.addMessage = function() {
    $scope.messages.$add({
      text: $scope.newMessageText
    });
  };

});

How do you submit a time into firebase?
See my codepen here

A: A few things are going on here:

*

*An input of type text (the default type for an input) will return a string

*An input of type time will return a Date object

*Firebase stores JSON data

*There is no JSON data type for Date objects

So you will have to convert the time you get into a supported type, before passing it to Firebase.
$scope.addMessage = function() {
  $scope.messages.$add({
    text: $scope.newMessageText.toString()
  });
};

Note that storing a date as a string is great if you want to only display the date. But if you want to also manipulate it (e.g. filter based on the date), you will probably want to store it as a timestamp:
$scope.addMessage = function() {
  $scope.messages.$add({
    text: $scope.newMessageText.toString(),
    timestamp: $scope.newMessageText.getTime(),
  });
};


text:
Q: OpenGL ES 1.1 - texture support (Power of two) I am just about to release a wallpaper app that's going to use user's own images... which may be non power of 2 size. Textures of all size seems to be supported on my Nexus 2013 tab and Moto X 2013 in Open GL ES 1.1.
My question is:

*

*Does the OpenGL ES 1.1 have power or two limitation in some devices/android versions?

*If there is a limitation, can I over-ride it somehow to choose textures of any size?

A:
Does the OpenGL ES 1.1 have power or two limitation in some
  devices/android versions?

NO ES 1.x does not support non pow 2 textures, it started supporting it in ES 2

If there is a limitation, can I over-ride it somehow to choose
  textures of any size

either change your Opengl profile to ES 2 if you can't then you have to convert your texture to a pow of 2 one
EDIT
there is some kind of workaround maybe to try out see here

A: OpenGL ES 1.1 does not support non power of two textures. There are extensions like GL_OES_texture_npot that add the support, but possibly with limitations to texture wrapping. OpenGL ES 2.0 does support npot textures, but still only with GL_CLAMP_TO_EDGE wrapping, so texture repeating might not work with npot textures.
Usually best option to avoid texture size restrictions is to use a texture atlas i.e. a large power of two texture that contains multiple non power of two textures inside.
EDIT:
Here are couple of examples of reports of devices not working with non power of two textures: Galaxy Player, Ouya.
Here is a list of some devices' GL extensions. The ones without GL_OES_texture_npot or GL_ARB_texture_non_power_of_two extensions should not work with non power of two textures.
An alternative to texture atlases is to pad the texture with black to the nearest power of two dimensions, but it will waste texture memory. You can store your textures in non power of two dimensions and do the padding programmatically.

A: I would not rely on support for NPOT textures, even with OpenGL-ES 2.0. Power of two texture, even if they aren't mandatory, are always better for performance reasons.
To overcome this issue, try using texture coordinates correctly. For example:
Let's say your original image is 300x500. The closest Po2 size for this texture is 512x512. We take the original 300x500 bitmap, and paint it on a 512x512 bitmap and create a texture from that. We don't scale when we create the larger bitmap, so the larger bitmap will appear to have blank edges on the right and bottom.
Normally, your texture coordinates (for a flat square model) would look something like this:
float[] textureCoords = new float[] {
    0, 0,
    1, 0,
    1, 1,
    0, 1
};

The 0 in each coordinate indicates the "beginning" edge of your texture, whereas the 1 in each coordinate indicates the "end" edge of your texture.
Now we want to "trick" the system to not render the whole texture, since any pixel greater than 300 horizontally or 500 vertically is blank. So, instead of using "1" as the end value, we use the ratio of the two images:
float w = 300f / 512f;
float h = 500f / 512f;

float[] textureCoords = new float[] {
    0, 0,
    w, 0,
    w, h,
    0, h
};

With these texture coordinates, only the relevant part of the texture will be drawn.
As JanneK pointed out, you can use this method to create 1 large texture which contains all the other textures you need, and then use texture coordinate mapping to only extract the parts you want from that texture. This will allow you to optimise your textures rather than just waste that "empty space" in the PO2 texture.
Hope this helps.


text:
Q: Storing and "replaying" flask requests I have a flask system that will redirect users to a login page if they are not logged in.  However, after logging them in, I'd like to send them right back to whatever request they were making before I interrupted them with the login page.
For GET requests, this is relatively trivial, since all the important information is in the URL. But for a POST request, it's not so trivial, as there are a number of different properties one might want to access from the request proxy.
I would like to know whether I can somehow store/save a request (e.g., in a before_request function) before sending them to the login page, and essentially "replay" their original request again after they log in.
My current strategy has been to JSONify as much of the original Request object as I could, store it in a cookie, and then modify the request proxy in before_request to give it the properties of the previous request.
Although I can modify the request properties via something like request.endpoint = "index", I can't seem to use setattr(request, "endpoint", "index") to set the values programmatically.
Does anybody know how to do that? Or, how one might get around this problem?


text:
Q: Google API and wrong result from its own function directionService I' m having this problem , when I load my page and insert Origin and Destination, after clicking the button "locate" it doesn't show anything in the google map, because it says Response is not an object , so I tried to stamp it with console.log and it says Response=null , but if I reload the page and click fast on Locate , then it draws the route.
Here's the code
function init(){
    var latlng = new google.maps.LatLng(40.635636, 17.942414);
    var mapOptions = { zoom: 12, center: latlng  };
    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}

function updateMap(){
    init();

    var originGeocoder = new google.maps.Geocoder();
    var destinationGeocoder = new google.maps.Geocoder();

    var origin = document.getElementById( "origin" ).value + " Brindisi 72100";
    var destination = document.getElementById( "destination" ).value + " Brindisi 72100";

    var directionsService2 = new google.maps.DirectionsService();

    originGeocoder.geocode( { 'address': origin }, function(results, status) {
        if ( status == google.maps.GeocoderStatus.OK ) {
            var startLatLng = results[0].geometry.location;
            var oLat = startLatLng.lat();
            var oLng = startLatLng.lng();
            document.getElementById('cStart').innerHTML = oLat + " " + oLng;
        }
        else{
            alert("Geocode was not successful for the following reason: " + status);
        }
    });

    //Chiamata asincrona alle API per ottenere Lat e Lng dell' indirizzo di destinazione
    destinationGeocoder.geocode( { 'address': destination }, function(results, status) {
        if ( status == google.maps.GeocoderStatus.OK ) {
            var destLatLng = results[0].geometry.location;
            var dLat = destLatLng.lat();
            var dLng = destLatLng.lng();
            document.getElementById('cDestination').innerHTML = typeof dLat;
            document.getElementById('cDestination').innerHTML = dLat + " " + dLng;
        }
        else{
            alert("Geocode was not successful for the following reason: " + status);
        }
    });

    //Salva in req[] le varie distanze tra le paline e la destinazione
    singleObjToStop(origin,destination,function(paline,req,reqO){
        console.log("1");
        //Trova la palina più vicina alla destinazione
        calcSingleDis(paline,req,reqO,function(w2,w1){
            console.log("2");
            //Disegna i waypoints(?)
            reqEnd(origin,destination,w1,w2,function(request){
                console.log("3");
                directionsService2.route(request, function(response, status) {
                    console.log("4");
                    console.log(response);
                    if (status == google.maps.DirectionsStatus.OK) {
                        directionsDisplay.setDirections(response);
                        var route = response.routes[0];
                        var summaryPanel = document.getElementById("distance");
                        summaryPanel.innerHTML = "";
                        // For each route, display summary information.
                        for (var i = 0; i < route.legs.length; i++) {
                            var routeSegment = i + 1;
                            summaryPanel.innerHTML += "Route Segment: " + routeSegment + "
";
                            summaryPanel.innerHTML += route.legs[i].start_address + " to ";
                            summaryPanel.innerHTML += route.legs[i].end_address + "
";
                            summaryPanel.innerHTML += route.legs[i].distance.text + " ";
                            summaryPanel.innerHTML += route.legs[i].duration.text +  "

" ;
                        }
                        computeTotalDistance(response);
                    }
                    else{
                        console.log("ENTRA QUA STRONZO");
                        console.log("Fermata partenza = " + w1);
                        console.log("Fermata arrivo = " + w2);
                    }
                });
                directionsDisplay.setMap(map);
            });
        });
    });
}

function singleObjToStop(origin,destination,callback){
    var data=<?php echo $data; ?>;
    var a,b,i=0;
    var paline = new Array();
    var req = new Array();
    var reqO = new Array();
    var num = <?php echo $n; ?>;
    $.each(data, function(fieldName, fieldValue) {
        a=fieldValue.geoLat;
        b=fieldValue.geoLong;
        a=parseFloat(a);
        b=parseFloat(b);
        paline[i]=new google.maps.LatLng(a,b);

        req[i] = {
            origin:paline[i],
            destination:destination,
            travelMode: google.maps.TravelMode.WALKING
        };

        reqO[i] = {
            origin:origin,
            destination:paline[i],
            travelMode: google.maps.TravelMode.WALKING
        };

        i++;
        if(i==num){
            callback(paline,req,reqO);
        }
    });
}

function calcSingleDis(paline, req, reqO, callback) {
    var directionsService = new google.maps.DirectionsService();
    var c = 10000000;
    var w2 = new google.maps.LatLng(0, 0);
    var w1 = new google.maps.LatLng(0, 0);
    var num = <?php echo $n; ?>;
    var j = (num - 1);
    var t;

    var cO = 10000000;
    var numO = <?php echo $n; ?>;
    var jO = 0;
    for (j = 0; j < num; j++) {
        t = 0;
        directionsService.route(req[j], function(response, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                //directionsDisplay.setDirections(response);
                var troute = response.routes[0];
                var dis = parseFloat((troute.legs[0].distance.text).replace(",", "."));

                document.getElementById('test').innerHTML = dis;

                //se distanza minore di quella minore trovata fin ora la cambia
                if (dis < c) {
                    w2 = paline[j - num];
                    c = dis;
                }

                if (t == (num - 1)) {
                    console.log("QUA ENTRA LOL");

                    for (jO = 0; jO < numO; jO++) {
                        console.log("E NON ENTRA MANNAC");
                        t = 0;
                        directionsService.route(reqO[jO], function(response, status) {
                            if (status == google.maps.DirectionsStatus.OK) {
                                console.log("E NON ENTRA MANNAC22222");
                                //directionsDisplay.setDirections(response);
                                var troute = response.routes[0];
                                var disO = parseFloat((troute.legs[0].distance.text).replace(",", "."));

                                document.getElementById('test').innerHTML = dis;

                                //se distanza minore di quella minore trovata fin ora la cambia
                                if (disO < cO) {
                                    w1 = paline[jO - numO];
                                    cO = disO;
                                }

                                if (t == (numO - 1)) {
                                    console.log("W1 = " + w1);
                                    console.log(response);
                                    callback(w2, w1);

                                }
                            }
                            jO++;
                            t++;
                        });
                    }

                }
            }
            j++;
            t++;
        });
    }
}

function reqEnd(origin,destination,w1,w2,callback){
    var request = {
        origin:origin,
        destination:destination,
          waypoints: [{location: w1} , {location: w2}],
          //waypoints: [{location: w2}],
          optimizeWaypoints: true,
        travelMode: google.maps.DirectionsTravelMode.WALKING
    };
    callback(request);
}

function computeTotalDistance(result) {
    var totalDist = 0;
    var totalTime = 0;
    var myroute = result.routes[0];
    for (i = 0; i < myroute.legs.length; i++) {
        totalDist += myroute.legs[i].distance.value;
        totalTime += myroute.legs[i].duration.value;
    }
    totalDist = totalDist / 1000.
    document.getElementById("total").innerHTML = "total distance is: "+ totalDist + " km
total time is: " + (totalTime / 60).toFixed(2) + " minutes";
}

google.maps.event.addDomListener( window, 'load', init );

A: The problem is related to the limit of query that you can use with Google Maps API v3.
You can take a look here: https://developers.google.com/maps/documentation/business/faq#google_maps_api_services
You probably do lots of requests to the API with your program, while you have quite restrictive limits as you can see from google Q&A.

Applications should throttle requests to avoid exceeding usage limits,
  bearing in mind these apply to each client ID regardless of how many
  IP addresses the requests are sent from.
You can throttle requests by putting them through a queue that keeps
  track of when are requests sent. With a rate limit or 10 QPS (queries
  per second), on sending the 11th request your application should check
  the timestamp of the first request and wait until 1 second has passed.
  The same should be applied to daily limits.
Even if throttling is implemented correctly applications should watch
  out for responses with status code OVER_QUERY_LIMIT. If such response
  is received, use the pause-and-retry mechanism explained in the Usage
  limits exceeded section above to detect which limit has been exceeded.

You could find useful: How do I Geocode 20 addresses without receiving an OVER_QUERY_LIMIT response?

A: The Google Maps API provides a geocoder class for geocoding and reverse geocoding dynamically from user input. read more check Geolocation demo here and more HTML5 Geolocation to check here


text:
Q: Bootstrap input group not showing For some reason my log in page turned into a mess. Just a few hours ago everything seemed normal but I'm not sure what I did but now its showing like this:

I am using Firefox to run.
This is my HTML code:

                Username
                <asp:TextBox runat="server" ID="txtUserId"
CssClass="form-control" aria-describedby="sizing-addon1"></asp:TextBox>

                Password
                <asp:TextBox runat="server" ID="txtPassword"
CssClass="form-control" aria-describedby="sizing-addon1" TextMode="Password"></asp:TextBox>

<asp:Button ID="btnLogin" runat="server" CssClass="btn btn-danger btn-lg
 col-md-2 col-xs-offset-5" Text="Login" OnClick="btnLogin_Click" />


text:
Q: Django - syncdb: table has more than one primary key I am trying to add my model to my database however am unsure why I am getting the following error.
"sqlite3.OperationalError: table "device_registration_device" has more than one primary key"
My model is
from django.contrib.auth.models import User
from django.db import models

class Device(models.Model):
    owner = models.ForeignKey(User)
    device_key = models.CharField(max_length=32, primary_key=True)
    device_type = models.CharField(max_length=32)

I thought I only have one primary_key specified here (device_key)?
[EDIT] Ok, I think this may have something to do with the fact I am trying to use a serializer with this model..?
class DeviceSerializer(serializers.ModelSerializer):

    class Meta:
        model = Device
        fields = ('device_key')

A: From the primary_key documentation:

primary_key
Field.primary_key If True, this field is the primary key for the
  model.
If you don't specify primary_key=True for any field in your model,
  Django will automatically add an AutoField to hold the primary key, so
  you don't need to set primary_key=True on any of your fields unless
  you want to override the default primary-key behavior. For more, see
  Automatic primary key fields.
primary_key=True implies null=False and unique=True. Only one primary
  key is allowed on an object.

One reason you would get this error is if you first created the model (and migration), applied the migration with the default primary key added by django.
Next, you decided to set a different field as the primary key, and create the migration and now when you are trying to apply it, you are receiving this error.
It does not have to do with serialization as the error is at the database level.
You have a few ways to solve this problem:

*

*Delete (or manually adjust) your migrations so that there is only one primary key for your model.

*Keep the default primary key, and add change device_key to enforce unique-ness and (optionally) create an index on it:
device_key = models.CharField(max_length=32,
                              unique=True, null=False, db_index=True)


text:
Q: How to make the distance between nodes depend on the value in d3.js? I am using the following code and example here to make a force directed graph: https://bl.ocks.org/heybignick/3faf257bbbbc7743bb72310d03b86ee8
(both code and json input file are provided in the above link)
I would like this graph to result in a clustering of similar nodes based on the value of the json data. At the moment, this value determines the width of the links, rather than the distance between nodes.
In the example by heybignick, the distances are defined as shown below. How can I exactly adapt this so that the distance between each node depends on the value between source and target ?
segment of javascript code from heybignick:
var simulation = d3.forceSimulation()
    .force("link", d3.forceLink().id(function(d) { return d.id; }))//.distance(function(d,i){return 1*i}))
    .force("charge", d3.forceManyBody())
    .force("center", d3.forceCenter(width / 2, height / 2));

d3.json("miserables.json", function(error, graph) {
  if (error) throw error;

  var link = svg.append("g")
      .attr("class", "links")
    .selectAll("line")
    .data(graph.links)
    .enter().append("line")
      .attr("stroke-width", function(d) { return Math.sqrt(d.value); });

  var node = svg.append("g")
      .attr("class", "nodes")
    .selectAll("g")
    .data(graph.nodes)
    .enter().append("g")

fyi: I am inexperienced with javascript

A: You can use the .distance method of link forces.
From the documentation:

link.distance([distance])
If distance is specified, sets the distance accessor to the specified number or function, re-evaluates the distance accessor for each link, and returns this force. If distance is not specified, returns the current distance accessor, which defaults to:

function distance() {
  return 30;
}

The distance accessor is invoked for each link, being passed the link and its zero-based index [...].

So, if the distance of a link between nodes depends on attributes in the source and target nodes, you can define:
function distance(link) {
  return myDistanceFunction(link.source, link.target);
}

Where myDistanceFunction is responsible for taking the source and target nodes and converting them to a pixel distance. Then pass the distance function to the force:
const simulation = d3.forceSimulation(nodes)
  .force("link", d3.forceLink(links)
    .id(d => d.id)
    .distance(distance)
  )


text:
Q: How to find asymptotic variance for mle with ln I have $X_1,...,X_n$ that are iid random variables with density function $$f(x) = {\alpha}x^{\alpha-1}$$
where $0<x<1$ and ${\alpha}$ is an unknown parameter.
The MLE estimator I got was $\frac{-n}{ln(n)+ln(\overline{X})}$. How do I find this MLE's asymptotic variance? I am especially stuck because of the ln function with the X bar.

A: The asymptotic variance of the MLE is given by $I(\alpha)^{-1}$ where $I(\alpha)$ is the Fisher information, namely,
$$
I(\alpha)=-nE\left(\frac{d^2}{d\alpha^2}\log f(X;\alpha)\right)=-nE(-\alpha^{-2})=\frac{n}{\alpha^2}
$$
It follows that the asymptiotic variance is
$$
\frac{\alpha^2}{n}.
$$


text:
Q: Redux update state array object property I have the following function that takes an action type and returns a new state, however since I didnt like the "slice" method I thought I would use the concat method instead. The commented out code was the original "slice" solution to update the state with the newly updated object. However, it doesn't work and and I am not even getting an error.
My approach is to join the existing state with the n
function posts(state = [], action) {
    switch(action.type) {
        case 'INCREMENT_LIKES':
            const i = action.index;

            //console.log(newState);
            // let newState =  [
            //  // ...state.slice(0, i),
            //  // {...state[i], likes: state[i].likes + 1},
            //  // ...state.slice(i + 1),
            // ]
            // console.log(newState);
            return state.concat([{...state[i], likes: state.likes +1}]);
        default:
            return state;
    }
}

export default posts;

A: This line will always append new element at the end of the state return state.concat([{...state[i], likes: state[i].likes +1}]);
According to commented code you need to update ith element. You could do it using map.
return state.map((item, i) => (
  i === action.index ? {...item, likes: item.likes + 1} : item)
);


text:
Q: Error in passing parameters to stored procedure in C# I have a stored procedure that I am calling which has three parameters, but for the life of me I do not see what is wrong with my syntax in C#:
var _accountREFCurrrent = new SqlParameter("@AccountRef", SqlDbType.NVarChar);
    _accountREFCurrrent.Value = account.ACCOUNT_REF;

var _SortOrder = new SqlParameter("@SortOrder", SqlDbType.Int);
     _SortOrder.Value = first.SORT_ORDER;

var _CATEGORY = new SqlParameter("@CATEGORY", SqlDbType.Int);
     _CATEGORY.Value = first.CATEGORY;

var result = db.Database.SqlQuery<sp_sumbalances_Result>("sp_sumbalances_Result
@AccountRef @SortOrder @CATEGORY", new object[] { _accountREFCurrrent,
_CATEGORY  ,_SortOrder }).ToList();

It is probably something stupid. I now it's correct as it returns data in SQL Server Management Studio:

Data being return from above in SQL Server Management Studio.

You will see the error I am getting in .NET:

A: There are commas missing between the parameters and the variables order is wrong:
var result = db.Database.SqlQuery<sp_sumbalances_Result>("sp_sumbalances_Result
@AccountRef @SortOrder @CATEGORY", new object[] { _accountREFCurrrent,
_CATEGORY  ,_SortOrder }).ToList();

Should be:
var result = db.Database.SqlQuery<sp_sumbalances_Result>("sp_sumbalances_Result
@AccountRef, @SortOrder, @CATEGORY", new object[] { _accountREFCurrrent, _SortOrder,
_CATEGORY}).ToList();


text:
Q: What does the fragment in android-code mean? could someone explain what the following code mean ?
What does           FragmentManager.BackStackEntry backEntry = fragmentManager.getBackStackEntryAt(fragmentManager
                    .getBackStackEntryCount() - 1) ; mean ?
What does the
fragmentTransaction
                .setCustomAnimations(R.anim.right_in, R.anim.right_out, R.anim.left_in, R.anim.left_out)
                .replace(R.id.mainMainFragmentLayout, newFragment)
                .addToBackStack(newFragment.getClass().getName()).commit() ;

mean ?
public static void addFragment(Fragment originalFragment, Fragment newFragment) {

    FragmentManager fragmentManager = originalFragment.getActivity().getFragmentManager() ;

    if (fragmentManager.getBackStackEntryCount() > 0) {

        FragmentManager.BackStackEntry backEntry = fragmentManager.getBackStackEntryAt(fragmentManager
                .getBackStackEntryCount() - 1) ;

        if (backEntry != null && backEntry.getName().equals(newFragment.getClass().getName()))
            return ;
    }

    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction() ;

    fragmentTransaction
            .setCustomAnimations(R.anim.right_in, R.anim.right_out, R.anim.left_in, R.anim.left_out)
            .replace(R.id.mainMainFragmentLayout, newFragment)
            .addToBackStack(newFragment.getClass().getName()).commit() ;
    fragmentManager.executePendingTransactions() ;
}

I have google for fragment , but I still can not understand...
Thanks in advance.

A: It will return the total number of fragments added into the stack.
You can use getName() method of FragmentManager.BackStackEntry which is introduced in API level 14 and it will return a string which you can check as the string stored in addTobackStack(str) method during fragment transaction.
 FragmentManager.BackStackEntry backEntry = fragmentManager.getBackStackEntryAt(fragmentManager
            .getBackStackEntryCount() - 1) ;

Fragment fragment=getFragmentManager().findFragmentByTag(backEntry.getName());

But to get the Fragment name you first need to add fragment into the stack as below with the specific name.
  fragmentTrans.addToBackStack("MyFragment");