问:
Autosuggestbox doesn't display the suggestionlist when I set the property Grid.Row=0. How to expand the result list downwards?
```<code><ScrollViewer Name="scroll" VerticalScrollBarVisibility="Auto">
        <Grid Name="ggrid" Canvas.ZIndex="0" Background="{StaticResource bg_color}">
            <Grid.RowDefinitions>
                <RowDefinition Height="1*"/>
                <RowDefinition Height="1*"/>
                <RowDefinition Height="1*"/>
            </Grid.RowDefinitions>

            <AutoSuggestBox Name="suggestion_box" Grid.Row="0" TextChanged="suggestion_box_TextChanged" UpdateTextOnSelect="True"  QuerySubmitted="suggestion_box_QuerySubmitted"/>

        <StackPanel Grid.Row="1" Name="main_sp">
            <StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
                <StackPanel Name="datepanel" Orientation="Horizontal" HorizontalAlignment="Center" >
                    <TextBlock Text="Date:" VerticalAlignment="Center" Foreground="{StaticResource accent_color}" />
                    <TextBox VerticalAlignment="Center" TextAlignment="Center" Name="day_box" PlaceholderText="Day" />
                    <TextBox VerticalAlignment="Center" TextAlignment="Center" Name="month_box" PlaceholderText="Month" />
                    <TextBox VerticalAlignment="Center" TextAlignment="Center" Name="year_box" PlaceholderText="Year" />
                </StackPanel>
                <StackPanel Margin="30,0,0,0" Orientation="Horizontal" HorizontalAlignment="Center">
                    <TextBlock Text="Invoice No." Foreground="{StaticResource accent_color}" VerticalAlignment="Center"/>
                    <TextBox Name="Invoice_No" BorderThickness="0" Margin="10,0,10,0" PlaceholderText="2001" Foreground="{StaticResource accent_color}" />
                    <TextBlock Text="/" Margin="10,0,10,0" VerticalAlignment="Center" Foreground="{StaticResource accent_color}"/>
                    <StackPanel Orientation="Horizontal">
                        <TextBox Name="Year1" BorderThickness="0" Margin="10,0,10,0" PlaceholderText="17" Foreground="{StaticResource accent_color}"/>
                        <TextBlock Text="-" VerticalAlignment="Center" Foreground="{StaticResource accent_color}" />
                        <TextBlock Name="Year2" Text="18" VerticalAlignment="Center" Foreground="{StaticResource accent_color}" />
                    </StackPanel>
                </StackPanel>
            </StackPanel>

            <StackPanel Name="challan_sp" Orientation="Vertical">
                <Button Name="Challan_Add_button" Margin="10" Content="Add Challan" FontWeight="Light" Foreground="{StaticResource accent_color}" FontSize="32" HorizontalAlignment="Stretch" Click="Challan_Add_button_Click" Style="{StaticResource ButtonStyle1}"/>
            </StackPanel>
        </StackPanel>

             <Button Grid.Row="2" Name="Save_button" HorizontalAlignment="Center" Content="Save" FontWeight="Light" Foreground="{StaticResource accent_color}" FontSize="32"  Click="Save_button_Click" Style="{StaticResource ButtonStyle1}"/>

    </Grid>

</ScrollViewer>
</code>```

When I set the Row.Grid="0" for the autosuggestbox, it doesn't display the suggestionlist. But, when I set the Row.Grid="3", it displays the suggestionlist.

It would be helpful if I would be able to expand the list downwards while setting the Row.Grid="0".

答:
Have you tried to set main grid (ggrid) properties :
VerticalAligment = "Strench" HorizontalAligment = "Strench"

EDIT

Checked your code , is running perfect on my PC. I suppose this scrollviewer is child of other control

Body:
<ScrollViewer Name="scroll" VerticalScrollBarVisibility="Auto">
        <Grid Name="ggrid" Canvas.ZIndex="0" Background="{StaticResource bg_color}">
            <Grid.RowDefinitions>
                <RowDefinition Height="1*"/>
                <RowDefinition Height="1*"/>
                <RowDefinition Height="1*"/>
            </Grid.RowDefinitions>

            <AutoSuggestBox Name="suggestion_box" Grid.Row="0" TextChanged="suggestion_box_TextChanged" UpdateTextOnSelect="True"  QuerySubmitted="suggestion_box_QuerySubmitted"/>

        <StackPanel Grid.Row="1" Name="main_sp">
            <StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
                <StackPanel Name="datepanel" Orientation="Horizontal" HorizontalAlignment="Center" >
                    <TextBlock Text="Date:" VerticalAlignment="Center" Foreground="{StaticResource accent_color}" />
                    <TextBox VerticalAlignment="Center" TextAlignment="Center" Name="day_box" PlaceholderText="Day" />
                    <TextBox VerticalAlignment="Center" TextAlignment="Center" Name="month_box" PlaceholderText="Month" />
                    <TextBox VerticalAlignment="Center" TextAlignment="Center" Name="year_box" PlaceholderText="Year" />
                </StackPanel>
                <StackPanel Margin="30,0,0,0" Orientation="Horizontal" HorizontalAlignment="Center">
                    <TextBlock Text="Invoice No." Foreground="{StaticResource accent_color}" VerticalAlignment="Center"/>
                    <TextBox Name="Invoice_No" BorderThickness="0" Margin="10,0,10,0" PlaceholderText="2001" Foreground="{StaticResource accent_color}" />
                    <TextBlock Text="/" Margin="10,0,10,0" VerticalAlignment="Center" Foreground="{StaticResource accent_color}"/>
                    <StackPanel Orientation="Horizontal">
                        <TextBox Name="Year1" BorderThickness="0" Margin="10,0,10,0" PlaceholderText="17" Foreground="{StaticResource accent_color}"/>
                        <TextBlock Text="-" VerticalAlignment="Center" Foreground="{StaticResource accent_color}" />
                        <TextBlock Name="Year2" Text="18" VerticalAlignment="Center" Foreground="{StaticResource accent_color}" />
                    </StackPanel>
                </StackPanel>
            </StackPanel>

            <StackPanel Name="challan_sp" Orientation="Vertical">
                <Button Name="Challan_Add_button" Margin="10" Content="Add Challan" FontWeight="Light" Foreground="{StaticResource accent_color}" FontSize="32" HorizontalAlignment="Stretch" Click="Challan_Add_button_Click" Style="{StaticResource ButtonStyle1}"/>
            </StackPanel>
        </StackPanel>

             <Button Grid.Row="2" Name="Save_button" HorizontalAlignment="Center" Content="Save" FontWeight="Light" Foreground="{StaticResource accent_color}" FontSize="32"  Click="Save_button_Click" Style="{StaticResource ButtonStyle1}"/>

    </Grid>

</ScrollViewer>

When I set the Row.Grid="0" for the autosuggestbox, it doesn't display the suggestionlist. But, when I set the Row.Grid="3", it displays the suggestionlist.

It would be helpful if I would be able to expand the list downwards while setting the Row.Grid="0".


来源: stackexchange

问:
How do I close a connection early?
I'm attempting to do an AJAX call (via JQuery) that will initiate a fairly long process. I'd like the script to simply send a response indicating that the process has started, but JQuery won't return the response until the PHP script is done running.

I've tried this with a "close" header (below), and also with output buffering; neither seems to work. Any guesses? or is this something I need to do in JQuery?

```<code><?php

echo( "We'll email you as soon as this is done." );

header( "Connection: Close" );

// do some stuff that will take a while

mail( 'dude@thatplace.com', "okay I'm done", 'Yup, all done.' );

?>
</code>```

答:
TL;DR Answer:

```<code>ignore_user_abort(true); //Safety measure so that the user doesn't stop the script too early.

$content = 'Hello World!'; //The content that will be sent to the browser.

header('Content-Length: ' . strlen($content)); //The browser will close the connection when the size of the content reaches "Content-Length", in this case, immediately.

ob_start(); //Content past this point...

echo $content;

//...will be sent to the browser (the output buffer gets flushed) when this code executes.
ob_end_flush();
ob_flush();
flush();

if(session_id())
{
    session_write_close(); //Closes writing to the output buffer.
}

//Anything past this point will be ran without involving the browser.
</code>```

Function Answer:

```<code>ignore_user_abort(true);

function sendAndAbort($content)
{
    header('Content-Length: ' . strlen($content));

    ob_start();

    echo $content;

    ob_end_flush();
    ob_flush();
    flush();
}

sendAndAbort('Hello World!');

//Anything past this point will be ran without involving the browser.
</code>```

ContentLicense: CC BY-SA 4.0

Title: How do I close a connection early?

Body:
I'm attempting to do an AJAX call (via JQuery) that will initiate a fairly long process. I'd like the script to simply send a response indicating that the process has started, but JQuery won't return the response until the PHP script is done running.

I've tried this with a "close" header (below), and also with output buffering; neither seems to work. Any guesses? or is this something I need to do in JQuery?

<?php

echo( "We'll email you as soon as this is done." );

header( "Connection: Close" );

// do some stuff that will take a while

mail( 'dude@thatplace.com', "okay I'm done", 'Yup, all done.' );

?>

Body:
TL;DR Answer:

ignore_user_abort(true); //Safety measure so that the user doesn't stop the script too early.

$content = 'Hello World!'; //The content that will be sent to the browser.

header('Content-Length: ' . strlen($content)); //The browser will close the connection when the size of the content reaches "Content-Length", in this case, immediately.

ob_start(); //Content past this point...

echo $content;

//...will be sent to the browser (the output buffer gets flushed) when this code executes.
ob_end_flush();
ob_flush();
flush();

if(session_id())
{
    session_write_close(); //Closes writing to the output buffer.
}

//Anything past this point will be ran without involving the browser.

Function Answer:

ignore_user_abort(true);

function sendAndAbort($content)
{
    header('Content-Length: ' . strlen($content));

    ob_start();

    echo $content;

    ob_end_flush();
    ob_flush();
    flush();
}

sendAndAbort('Hello World!');

//Anything past this point will be ran without involving the browser.

ContentLicense: CC BY-SA 3.0


问:
Help with C# HttpWebRequest URI losing its encoding
Having a problem with HttpWebRequest decoding my encoded URL.

```<code>var requestUrl = "https://www.google.com/webmasters/tools/feeds/http%3A%2F%2Fwww%2example%2Ecom%2F/crawlissues/";
var request = (HttpWebRequest)WebRequest.Create(requestUrl);
</code>```

When looking at end request URL is becomes:

https://www.google.com/webmasters/tools/feeds/http://www.example.com//crawlissues/

Which of course returns a 400 Bad request. I am guessing it is something todo with the URI class rather than HttpWebRequest. How do I stop this from happening?

答: Try to change the Request method from POST to GET</p>

ContentLicense: CC BY-SA 2.5

Body:
Having a problem with HttpWebRequest decoding my encoded URL.

var requestUrl = "https://www.google.com/webmasters/tools/feeds/http%3A%2F%2Fwww%2example%2Ecom%2F/crawlissues/";
var request = (HttpWebRequest)WebRequest.Create(requestUrl);

When looking at end request URL is becomes:

https://www.google.com/webmasters/tools/feeds/http://www.example.com//crawlissues/

Which of course returns a 400 Bad request. I am guessing it is something todo with the URI class rather than HttpWebRequest. How do I stop this from happening?


问:
Compare two tables in Oracle
I have two tables in oracle 10g (table1, table2), with the same columns (A, B, C), but different data, and I want to compare the column A and B from table1 with column And B from table2, if A and B are similar I need to update the column C of table1 with the column C from table2, if they are not similar, I just insert the new row, what should I use?

I tried with normal SQL code, didn't work when I have more than 1 similar row, what should I use to go through the whole tables?

答:
(Posted on behalf of the OP).

Solution number1: Merge statement

```<code>merge into table1 A
using table2 B
on (A.A = B.A and A.B = B.B)
when matched then
update set A.C = B.C
when not matched then
insert (A,B,C) values(B.A,B.B,B.C);
</code>```

Solution number2: cursor and for loop

```<code>cursor cur is select * from table2;
Begin

For rec in cur Loop

Update table1 Set c = rec.c Where a = rec.a and b= rec.b;

If sql%rowcount = 0 then
insert into table1(a,b,c) values(rec.a,rec.b,rec.c);

End if;

End loop;
end;
</code>```

Title: Compare two tables in Oracle

Body:
(Posted on behalf of the OP).

Solution number1: Merge statement

merge into table1 A
using table2 B
on (A.A = B.A and A.B = B.B)
when matched then
update set A.C = B.C
when not matched then
insert (A,B,C) values(B.A,B.B,B.C);

Solution number2: cursor and for loop

cursor cur is select * from table2;
Begin

For rec in cur Loop

Update table1 Set c = rec.c Where a = rec.a and b= rec.b;

If sql%rowcount = 0 then
insert into table1(a,b,c) values(rec.a,rec.b,rec.c);

End if;

End loop;
end;


问:
Ionic - ANDROID_HOME not found in linux/ubuntu
I am very new in ionic.
I have a problem that build android platform from ionic.

I have set up the environment variable for ANDROID_HOME in .bashrc file.

```<code>ANDROID_HOME=/home/lukyuxuan/Desktop/android-sdk-linux
export ANDROID_HOME
export ANDROID_TOOLS=$ANDROID_HOME/tools
export ANDROID_PLATFORM_TOOLS=$ANDROID_HOME/platform-tools
PATH=$PATH:$ANDROID_HOME:$ANDROID_TOOLS:$ANDROID_PLATFORM_TOOLS
</code>```

In the terminal:

I try to print out the ANDROID_HOME (echo "$ANDROID_HOME"), it is work return the path

But when I try to build the android platform like this:

```<code>$ sudo ionic build android
</code>```

There's still occur this error. I also many answer for google, but no any one work for my situation.

Error: Failed to find 'ANDROID_HOME' environment variable. Try setting setting it manually.
Failed to find 'android' command in your 'PATH'. Try update your 'PATH' to include path to valid SDK directory.

答:
By default sudo will drop most unknown env variables.

I don't see why sudo is necessary here though.

Body:
I am very new in ionic.
I have a problem that build android platform from ionic.

I have set up the environment variable for ANDROID_HOME in .bashrc file.

ANDROID_HOME=/home/lukyuxuan/Desktop/android-sdk-linux
export ANDROID_HOME
export ANDROID_TOOLS=$ANDROID_HOME/tools
export ANDROID_PLATFORM_TOOLS=$ANDROID_HOME/platform-tools
PATH=$PATH:$ANDROID_HOME:$ANDROID_TOOLS:$ANDROID_PLATFORM_TOOLS

In the terminal:

I try to print out the ANDROID_HOME (echo "$ANDROID_HOME"), it is work return the path

But when I try to build the android platform like this:

$ sudo ionic build android

There's still occur this error. I also many answer for google, but no any one work for my situation.

Error: Failed to find 'ANDROID_HOME' environment variable. Try setting setting it manually.
Failed to find 'android' command in your 'PATH'. Try update your 'PATH' to include path to valid SDK directory.


问:
How to filter an nested ICollection List in c# with Linq
Consider following class structure:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    public class ItemSet
    {
        public Guid ID { get; set; }
        public ICollection<Item> Items { get; set; }
    }

    public class Item
    {
        public Guid ID { get; set; }
        public string Type { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            getItemSet("B2");
        }

        static public ItemSet generateCompleteItemSet()
        {
            Item item1 = new Item();
            item1.ID = new Guid();
            item1.Type = "A1";
            Item item2 = new Item();
            item2.ID = new Guid();
            item2.Type = "B2";
            Item item3 = new Item();
            item3.ID = new Guid();
            item3.Type = "B2";

            ICollection<Item> items = new List<Item>();
            items.Add(item1);
            items.Add(item2);
            items.Add(item3);

            ItemSet itemSet = new ItemSet();
            itemSet.ID = new Guid();
            itemSet.Items = items;

            return itemSet;
        }

        static public void getItemSet(string type)
        {
            ItemSet completeItemSet = generateCompleteItemSet();
            ItemSet filteredItemSet = completeItemSet;
            filteredItemSet.Items = completeItemSet.Items.Where(item => item.Type == type);
        }

    }
}
</code>```

Tested with:

Visual Studio 2017 Community Edition

Console app (.NET Framework) Template

Questions:

How can i get an result ItemSet with all Items that have a specified 'Type' Attribute within the 'getItemSet' function?

The 'getItemSet' will not compile because "where" delivers an IEnumerable but i need an ICollection.

答:
you can do it like this:

(EDIT - added both all items and filtered items as List<Item>)

```<code>//test data
List<Item> itemsList = new List<Item>();
itemsList.Add(new Item() { ID = Guid.NewGuid(), Type = "a" });
itemsList.Add(new Item() { ID = Guid.NewGuid(), Type = "a" });
itemsList.Add(new Item() { ID = Guid.NewGuid(), Type = "b" });
itemsList.Add(new Item() { ID = Guid.NewGuid(), Type = "c" });

List<ItemSet> itemSetList = new List<ItemSet>();
itemSetList.Add(new ItemSet() { ID = Guid.NewGuid(), Items = itemsList });

//select all items
var allItems = itemSetList.SelectMany(i => i.Items).ToList();
//filter items by type
var filteredItems = itemSetList.SelectMany(i => i.Items.Where(x => x.Type == "a")).ToList();
</code>```

Body:
Consider following class structure:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    public class ItemSet
    {
        public Guid ID { get; set; }
        public ICollection<Item> Items { get; set; }
    }

    public class Item
    {
        public Guid ID { get; set; }
        public string Type { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            getItemSet("B2");
        }

        static public ItemSet generateCompleteItemSet()
        {
            Item item1 = new Item();
            item1.ID = new Guid();
            item1.Type = "A1";
            Item item2 = new Item();
            item2.ID = new Guid();
            item2.Type = "B2";
            Item item3 = new Item();
            item3.ID = new Guid();
            item3.Type = "B2";

            ICollection<Item> items = new List<Item>();
            items.Add(item1);
            items.Add(item2);
            items.Add(item3);

            ItemSet itemSet = new ItemSet();
            itemSet.ID = new Guid();
            itemSet.Items = items;

            return itemSet;
        }

        static public void getItemSet(string type)
        {
            ItemSet completeItemSet = generateCompleteItemSet();
            ItemSet filteredItemSet = completeItemSet;
            filteredItemSet.Items = completeItemSet.Items.Where(item => item.Type == type);
        }

    }
}

Tested with:

Visual Studio 2017 Community Edition

Console app (.NET Framework) Template

Questions:

How can i get an result ItemSet with all Items that have a specified 'Type' Attribute within the 'getItemSet' function?

The 'getItemSet' will not compile because "where" delivers an IEnumerable but i need an ICollection.

Body:
you can do it like this:

(EDIT - added both all items and filtered items as List<Item>)

//test data
List<Item> itemsList = new List<Item>();
itemsList.Add(new Item() { ID = Guid.NewGuid(), Type = "a" });
itemsList.Add(new Item() { ID = Guid.NewGuid(), Type = "a" });
itemsList.Add(new Item() { ID = Guid.NewGuid(), Type = "b" });
itemsList.Add(new Item() { ID = Guid.NewGuid(), Type = "c" });

List<ItemSet> itemSetList = new List<ItemSet>();
itemSetList.Add(new ItemSet() { ID = Guid.NewGuid(), Items = itemsList });

//select all items
var allItems = itemSetList.SelectMany(i => i.Items).ToList();
//filter items by type
var filteredItems = itemSetList.SelectMany(i => i.Items.Where(x => x.Type == "a")).ToList();


问:
how can i access value outside the if condition in c#
How can I use this 'download' outside the if condition?

```<code>if (rblFinancialYear.Checked)
{
  var download = (from appraisals in dbClientContext.PmsAppraisalActivityMasters
                    select new
                    {
                      appraisalActivityMasteId = appraisals.AppraisalActivityMasterID,
                      empId = appraisals.EmpID,
                    })
                    Where(r => r.kpiStartDate >= dtFYStart && r.kpiStartDate <= dtFYEnd).ToList();
}
</code>```

If I return using return type means which datatypes I use here.

答:
You should create separate class like this:

```<code>public class MyDTO
{
   public int appraisalActivityMasteId {get; set;}
   public int empId {get; set;}
}
</code>```

Maby you should use different property types. And then use it in code like this:

```<code>List<MyDTO> download  = new List<MyDTO>();
if (rblFinancialYear.Checked)
{
   download = (from appraisals in dbClientContext.PmsAppraisalActivityMasters
                    select new MyDTO //note this
                    {
                      appraisalActivityMasteId = appraisals.AppraisalActivityMasterID,
                      empId = appraisals.EmpID,
                    })
                    .Where(r => r.kpiStartDate >= dtFYStart
                       && r.kpiStartDate <= dtFYEnd).ToList();
}
</code>```

Body:
How can I use this 'download' outside the if condition?

if (rblFinancialYear.Checked)
{
  var download = (from appraisals in dbClientContext.PmsAppraisalActivityMasters
                    select new
                    {
                      appraisalActivityMasteId = appraisals.AppraisalActivityMasterID,
                      empId = appraisals.EmpID,
                    })
                    Where(r => r.kpiStartDate >= dtFYStart && r.kpiStartDate <= dtFYEnd).ToList();
}

If I return using return type means which datatypes I use here.

Body:
You should create separate class like this:

public class MyDTO
{
   public int appraisalActivityMasteId {get; set;}
   public int empId {get; set;}
}

Maby you should use different property types. And then use it in code like this:

List<MyDTO> download  = new List<MyDTO>();
if (rblFinancialYear.Checked)
{
   download = (from appraisals in dbClientContext.PmsAppraisalActivityMasters
                    select new MyDTO //note this
                    {
                      appraisalActivityMasteId = appraisals.AppraisalActivityMasterID,
                      empId = appraisals.EmpID,
                    })
                    .Where(r => r.kpiStartDate >= dtFYStart
                       && r.kpiStartDate <= dtFYEnd).ToList();
}


问:
compass utf-8 Chinese encoding
I have a legacy compass over sass setup.
I need to add some Chinese fonts. And when compass is compiling .scss to .css it does not encode correctly Chinese characters.
e.g. for "微軟正黑體" I get "σ╛«Φ╗ƒµ¡úΘ╗æΘ½ö".

What I have already done:
1. Addded @charset "UTF-8" to the roof of scss.
2. Added Encoding.default_external = 'utf-8' and encoding = 'utf-8' to config.rb.

Did not help. Anybody had this problem before?
Thank you,

答:
Answer to accept

Usually when you copy-paste string to file that is non-utf-8 encoded it gets wrongly re-coded to source encoding.

So as you say - you copy utf8 string and paste it to ANSII encoded file, so utf8 is magically converted to ANSII by editor and non-Latin symbols gets ruined

Title: compass utf-8 Chinese encoding


问:
Trying to understand extern in C
By the answer given here, I am trying to construct a working example and try to understand behavior of the extern linkage.

Here is my example:

extern.h

```<code>extern int global_counter;

int file_counter;
</code>```

extern.c

```<code>#include "extern.h"

int global_counter = 5;
</code>```

incrementor1.c

```<code>#include "extern.h"
#include <stdio.h>

void incrementor1_global()
{
    global_counter++;
    printf("From Incrementor1...\n");
    printf("Global counter is: %d\n", global_counter);
}

void incrementor1_local()
{
    file_counter++;
    printf("From Incrementor1...\n");
    printf("File counter is: %d\n", file_counter);
}
</code>```

incrementor2.c

```<code>#include "extern.h"
#include <stdio.h>

void incrementor2_global()
{
    global_counter++;
    printf("From Incrementor2...\n");
    printf("Global counter is: %d\n", global_counter);
}

void incrementor2_local()
{
    file_counter++;
    printf("From Incrementor2...\n");
    printf("File counter is: %d\n", file_counter);
}
</code>```

You can yourself put these into separate files as depicted. Here is my main.c now:

main.c

```<code>void incrementor1_global();
void incrementor1_local();

void incrementor2_global();
void incrementor2_local();

int main(char argc, char* argv[])
{
    incrementor1_global();
    incrementor2_global();

    incrementor1_local();
    incrementor2_local();
}
</code>```

Since I link .o files to my main, I am just declaring the functions and since they are extern by default, they are linked by the linker as I understood. And lastly, here is a makefile if you want to try it yourself.

```<code>CC=gcc

CFLAGS=-I.

DEPS = extern.h

OBJ = main.o extern.o incrementor1.o incrementor2.o

%.o: %.c $(DEPS)
    $(CC) -c -o $@ $< $(CFLAGS)

main: $(OBJ)
    gcc -o $@ $^ $(CFLAGS)

.PHONY: clean

clean:
    rm -f *.o
</code>```

So by the answer linked above, I think global_counter should be shared by all translation units while each should have their own copy of file_counter. But the output I get is:

```<code>From Incrementor1...
Global counter is: 6
From Incrementor2...
Global counter is: 7
From Incrementor1...
File counter is: 1
From Incrementor2...
File counter is: 2
</code>```

So, I think both incrementor have a one copy of file_counter and that is a global variable. But now I don't know how I can replicate the answer given and make them have their own copy. Any suggestions?

By the way, If I want to give a definition to file_counter in extern.h, since it is included in both incrementors I am getting multiple definitions error. This confuses me further on how could I make them have a shared copy.

答:
Each of your compilation units that includes extern.h declares a variable called file_counter at global scope. That means that each one declares the variable and some storage for it, but the variable is theoretically visible at link time to other compilation units.

When the linker comes along, it sees these global variables and allocates them to a segment of storage and, in your case, it coalesces them into one instance, I'm not sure if this is mandated by the C standard or not, I'm too lazy to check, but it's probably an example of undefined behaviour.

What you need is to make the variable file-counter be visible only in the compilation unit in which it is declared (the .c file that included the .h) and for that, you use the static modifier

```<code>static int file_counter;
</code>```

As a rule, it should also be removed from the header and placed in the .c file where it is going to be used. It's OK for your toy example that demonstrates the difference between extern and static but in pretty much every real scenario, you do not want a new static variable in every single .c file that includes the header.

Title: Trying to understand extern in C

Body:
By the answer given here, I am trying to construct a working example and try to understand behavior of the extern linkage.

Here is my example:

extern.h

extern int global_counter;

int file_counter;

extern.c

#include "extern.h"

int global_counter = 5;

incrementor1.c

#include "extern.h"
#include <stdio.h>

void incrementor1_global()
{
    global_counter++;
    printf("From Incrementor1...\n");
    printf("Global counter is: %d\n", global_counter);
}

void incrementor1_local()
{
    file_counter++;
    printf("From Incrementor1...\n");
    printf("File counter is: %d\n", file_counter);
}

incrementor2.c

#include "extern.h"
#include <stdio.h>

void incrementor2_global()
{
    global_counter++;
    printf("From Incrementor2...\n");
    printf("Global counter is: %d\n", global_counter);
}

void incrementor2_local()
{
    file_counter++;
    printf("From Incrementor2...\n");
    printf("File counter is: %d\n", file_counter);
}

You can yourself put these into separate files as depicted. Here is my main.c now:

main.c

void incrementor1_global();
void incrementor1_local();

void incrementor2_global();
void incrementor2_local();

int main(char argc, char* argv[])
{
    incrementor1_global();
    incrementor2_global();

    incrementor1_local();
    incrementor2_local();
}

Since I link .o files to my main, I am just declaring the functions and since they are extern by default, they are linked by the linker as I understood. And lastly, here is a makefile if you want to try it yourself.

CC=gcc

CFLAGS=-I.

DEPS = extern.h

OBJ = main.o extern.o incrementor1.o incrementor2.o

%.o: %.c $(DEPS)
    $(CC) -c -o $@ $< $(CFLAGS)

main: $(OBJ)
    gcc -o $@ $^ $(CFLAGS)

.PHONY: clean

clean:
    rm -f *.o

So by the answer linked above, I think global_counter should be shared by all translation units while each should have their own copy of file_counter. But the output I get is:

From Incrementor1...
Global counter is: 6
From Incrementor2...
Global counter is: 7
From Incrementor1...
File counter is: 1
From Incrementor2...
File counter is: 2

So, I think both incrementor have a one copy of file_counter and that is a global variable. But now I don't know how I can replicate the answer given and make them have their own copy. Any suggestions?

By the way, If I want to give a definition to file_counter in extern.h, since it is included in both incrementors I am getting multiple definitions error. This confuses me further on how could I make them have a shared copy.

Body:
Each of your compilation units that includes extern.h declares a variable called file_counter at global scope. That means that each one declares the variable and some storage for it, but the variable is theoretically visible at link time to other compilation units.

When the linker comes along, it sees these global variables and allocates them to a segment of storage and, in your case, it coalesces them into one instance, I'm not sure if this is mandated by the C standard or not, I'm too lazy to check, but it's probably an example of undefined behaviour.

What you need is to make the variable file-counter be visible only in the compilation unit in which it is declared (the .c file that included the .h) and for that, you use the static modifier

static int file_counter;

As a rule, it should also be removed from the header and placed in the .c file where it is going to be used. It's OK for your toy example that demonstrates the difference between extern and static but in pretty much every real scenario, you do not want a new static variable in every single .c file that includes the header.


问:
How to achieve Asynchrony instead of Parallelism in F#
(Sticking to a common example with async fetch of many web pages)

How would I spin off multiple (hundreds) of web page requests asynchronously, and then wait for all requests to complete before going to the next step?  Async.AsParallel processes a few requests at a time, controlled by number of cores on the CPU.  Grabbing a web page is not a CPU-bound operation.  Not satisfied with the speedup of Async.AsParallel, I am looking for alternatives.

I tried to connect the dots between Async.StartAsTask and Task[].WaitAll.  Instinctively, I wrote the following code, but it does not compile.

```<code>let processItemsConcurrently (items : int seq) =
  let tasks = items |> Seq.map (fun item -> Async.StartAsTask(fetchAsync item))
  Tasks.Task.WaitAll(tasks)
</code>```

How would you approach this?

答:
Async.Parallel is almost definitely right here.  Not sure what you're not happy with; the strength of F# asyncs lies more in async computing than in task-parallel CPU-bound stuff (which is more tailored to Tasks and the .NET 4.0 TPL).  Here's a full example:

```<code>open System.Diagnostics
open System.IO
open System.Net
open Microsoft.FSharp.Control.WebExtensions

let sites = [|
    "http://bing.com"
    "http://google.com"
    "http://cnn.com"
    "http://stackoverflow.com"
    "http://yahoo.com"
    "http://msdn.com"
    "http://microsoft.com"
    "http://apple.com"
    "http://nfl.com"
    "http://amazon.com"
    "http://ebay.com"
    "http://expedia.com"
    "http://twitter.com"
    "http://reddit.com"
    "http://hulu.com"
    "http://youtube.com"
    "http://wikipedia.org"
    "http://live.com"
    "http://msn.com"
    "http://wordpress.com"
    |]

let print s =
    // careful, don't create a synchronization bottleneck by printing
    //printf "%s" s
    ()

let printSummary info fullTimeMs =
    Array.sortInPlaceBy (fun (i,_,_) -> i) info
//  for i, size, time in info do
//      printfn "%2d  %7d  %5d" i size time
    let longest = info |> Array.map (fun (_,_,time) -> time) |> Array.max
    printfn "longest request took %dms" longest
    let bytes = info |> Array.sumBy (fun (_,size,_) -> float size)
    let seconds = float fullTimeMs / 1000.
    printfn "sucked down %7.2f KB/s" (bytes / 1024.0 / seconds)

let FetchAllSync() =
    let allsw = Stopwatch.StartNew()
    let info = sites |> Array.mapi (fun i url ->
        let sw = Stopwatch.StartNew()
        print "S"
        let req = WebRequest.Create(url)
        use resp = req.GetResponse()
        use stream = resp.GetResponseStream()
        use reader = new StreamReader(stream,
                            System.Text.Encoding.UTF8, true, 4096)
        print "-"
        let contents = reader.ReadToEnd()
        print "r"
        i, contents.Length, sw.ElapsedMilliseconds)
    let time = allsw.ElapsedMilliseconds
    printSummary info time
    time, info |> Array.sumBy (fun (_,size,_) -> size)

let FetchAllAsync() =
    let allsw = Stopwatch.StartNew()
    let info = sites |> Array.mapi (fun i url -> async {
        let sw = Stopwatch.StartNew()
        print "S"
        let req = WebRequest.Create(url)
        use! resp = req.AsyncGetResponse()
        use stream = resp.GetResponseStream()
        use reader = new AsyncStreamReader(stream, // F# PowerPack
                           System.Text.Encoding.UTF8, true, 4096)
        print "-"
        let! contents = reader.ReadToEnd()  // in F# PowerPack
        print "r"
        return i, contents.Length, sw.ElapsedMilliseconds })
                    |> Async.Parallel
                    |> Async.RunSynchronously
    let time = allsw.ElapsedMilliseconds
    printSummary info time
    time, info |> Array.sumBy (fun (_,size,_) -> size)

// By default, I think .NET limits you to 2 open connections at once
ServicePointManager.DefaultConnectionLimit <- sites.Length

for i in 1..3 do // to warmup and show variance
    let time1,r1 = FetchAllSync()
    printfn "Sync took %dms, result was %d" time1 r1
    let time2,r2 = FetchAllAsync()
    printfn "Async took %dms, result was %d  (speedup=%2.2f)"
        time2 r2 (float time1/ float time2)
    printfn ""
</code>```

On my 4-core box, this consistently gives a nearly 4x speedup.

EDIT

In reply to your comment, I've updated the code.  You're right in that I've added more sites and am not seeing the expected speedup (still holding steady around 4x).  I've started adding a little debugging output above, will continue investigating to see if something else is throttling the connections...

EDIT

Editted the code again.  Well, I found what might be the bottleneck.  Here's the implementation of AsyncReadToEnd in the PowerPack:

```<code>type System.IO.StreamReader with
   member s.AsyncReadToEnd () =
       FileExtensions.UnblockViaNewThread (fun () -> s.ReadToEnd())
</code>```

In other words, it just blocks a threadpool thread and reads synchronously.  Argh!!!  Let me see if I can work around that.

EDIT

Ok, the AsyncStreamReader in the PowerPack does the right thing, and I'm using that now.

However, the key issue seems to be variance.

When you hit, say, cnn.com, a lot of the time the result will come back in like 500ms.  But every once in a while you get that one request that takes 4s, and this of course potentially kills the apparent async perf, since the overall time is the time of the unluckiest request.

Running the program above, I see speedups from about 2.5x to 9x on my 2-core box at home.  It is very highly variable, though.  It's still possible there's some bottleneck in the program that I've missed, but I think the variance-of-the-web may account for all of what I'm seeing at this point.

Body:
(Sticking to a common example with async fetch of many web pages)

How would I spin off multiple (hundreds) of web page requests asynchronously, and then wait for all requests to complete before going to the next step?  Async.AsParallel processes a few requests at a time, controlled by number of cores on the CPU.  Grabbing a web page is not a CPU-bound operation.  Not satisfied with the speedup of Async.AsParallel, I am looking for alternatives.

I tried to connect the dots between Async.StartAsTask and Task[].WaitAll.  Instinctively, I wrote the following code, but it does not compile.

let processItemsConcurrently (items : int seq) =
  let tasks = items |> Seq.map (fun item -> Async.StartAsTask(fetchAsync item))
  Tasks.Task.WaitAll(tasks)

How would you approach this?

Body:
Async.Parallel is almost definitely right here.  Not sure what you're not happy with; the strength of F# asyncs lies more in async computing than in task-parallel CPU-bound stuff (which is more tailored to Tasks and the .NET 4.0 TPL).  Here's a full example:

open System.Diagnostics
open System.IO
open System.Net
open Microsoft.FSharp.Control.WebExtensions

let sites = [|
    "http://bing.com"
    "http://google.com"
    "http://cnn.com"
    "http://stackoverflow.com"
    "http://yahoo.com"
    "http://msdn.com"
    "http://microsoft.com"
    "http://apple.com"
    "http://nfl.com"
    "http://amazon.com"
    "http://ebay.com"
    "http://expedia.com"
    "http://twitter.com"
    "http://reddit.com"
    "http://hulu.com"
    "http://youtube.com"
    "http://wikipedia.org"
    "http://live.com"
    "http://msn.com"
    "http://wordpress.com"
    |]

let print s =
    // careful, don't create a synchronization bottleneck by printing
    //printf "%s" s
    ()

let printSummary info fullTimeMs =
    Array.sortInPlaceBy (fun (i,_,_) -> i) info
//  for i, size, time in info do
//      printfn "%2d  %7d  %5d" i size time
    let longest = info |> Array.map (fun (_,_,time) -> time) |> Array.max
    printfn "longest request took %dms" longest
    let bytes = info |> Array.sumBy (fun (_,size,_) -> float size)
    let seconds = float fullTimeMs / 1000.
    printfn "sucked down %7.2f KB/s" (bytes / 1024.0 / seconds)

let FetchAllSync() =
    let allsw = Stopwatch.StartNew()
    let info = sites |> Array.mapi (fun i url ->
        let sw = Stopwatch.StartNew()
        print "S"
        let req = WebRequest.Create(url)
        use resp = req.GetResponse()
        use stream = resp.GetResponseStream()
        use reader = new StreamReader(stream,
                            System.Text.Encoding.UTF8, true, 4096)
        print "-"
        let contents = reader.ReadToEnd()
        print "r"
        i, contents.Length, sw.ElapsedMilliseconds)
    let time = allsw.ElapsedMilliseconds
    printSummary info time
    time, info |> Array.sumBy (fun (_,size,_) -> size)

let FetchAllAsync() =
    let allsw = Stopwatch.StartNew()
    let info = sites |> Array.mapi (fun i url -> async {
        let sw = Stopwatch.StartNew()
        print "S"
        let req = WebRequest.Create(url)
        use! resp = req.AsyncGetResponse()
        use stream = resp.GetResponseStream()
        use reader = new AsyncStreamReader(stream, // F# PowerPack
                           System.Text.Encoding.UTF8, true, 4096)
        print "-"
        let! contents = reader.ReadToEnd()  // in F# PowerPack
        print "r"
        return i, contents.Length, sw.ElapsedMilliseconds })
                    |> Async.Parallel
                    |> Async.RunSynchronously
    let time = allsw.ElapsedMilliseconds
    printSummary info time
    time, info |> Array.sumBy (fun (_,size,_) -> size)

// By default, I think .NET limits you to 2 open connections at once
ServicePointManager.DefaultConnectionLimit <- sites.Length

for i in 1..3 do // to warmup and show variance
    let time1,r1 = FetchAllSync()
    printfn "Sync took %dms, result was %d" time1 r1
    let time2,r2 = FetchAllAsync()
    printfn "Async took %dms, result was %d  (speedup=%2.2f)"
        time2 r2 (float time1/ float time2)
    printfn ""

On my 4-core box, this consistently gives a nearly 4x speedup.

EDIT

In reply to your comment, I've updated the code.  You're right in that I've added more sites and am not seeing the expected speedup (still holding steady around 4x).  I've started adding a little debugging output above, will continue investigating to see if something else is throttling the connections...

EDIT

Editted the code again.  Well, I found what might be the bottleneck.  Here's the implementation of AsyncReadToEnd in the PowerPack:

type System.IO.StreamReader with
   member s.AsyncReadToEnd () =
       FileExtensions.UnblockViaNewThread (fun () -> s.ReadToEnd())

In other words, it just blocks a threadpool thread and reads synchronously.  Argh!!!  Let me see if I can work around that.

EDIT

Ok, the AsyncStreamReader in the PowerPack does the right thing, and I'm using that now.

However, the key issue seems to be variance.

When you hit, say, cnn.com, a lot of the time the result will come back in like 500ms.  But every once in a while you get that one request that takes 4s, and this of course potentially kills the apparent async perf, since the overall time is the time of the unluckiest request.

Running the program above, I see speedups from about 2.5x to 9x on my 2-core box at home.  It is very highly variable, though.  It's still possible there's some bottleneck in the program that I've missed, but I think the variance-of-the-web may account for all of what I'm seeing at this point.


问:
Find the most frequent items among the arrays - PHP
I have 3 arrays in my code.

```<code>array1 = ['apple', 'orange', 'banana', 'guava', 'grapes'];
array2 = ['apple', 'jackfruits', 'banana', 'malta'];
array3 = ['banana', 'grapes, 'apple'];
</code>```

Now i want to get one array from high frequency to low frequency repetation in arrays.

like the result would be

```<code>array_result = ['apple', 'banana', 'grapes', 'orange', 'malta', 'jackfrouits'];
</code>```

答:
```<code>$array1 = ['apple', 'orange', 'banana', 'guava', 'grapes'];
$array2 = ['apple', 'jackfruits', 'banana', 'malta'];
$array3 = ['banana', 'grapes', 'apple'];

$arr = array_count_values(explode(',',implode(',',array_values($array1)).",".implode(',',array_values($array2)).",".implode(',',array_values($array3))));
arsort($arr);
print_r(array_keys($arr));
</code>```

Body:
I have 3 arrays in my code.

array1 = ['apple', 'orange', 'banana', 'guava', 'grapes'];
array2 = ['apple', 'jackfruits', 'banana', 'malta'];
array3 = ['banana', 'grapes, 'apple'];

Now i want to get one array from high frequency to low frequency repetation in arrays.

like the result would be

array_result = ['apple', 'banana', 'grapes', 'orange', 'malta', 'jackfrouits'];


问:
Find name using like operator in SQL Server
I have table with columns

```<code>surname    forename
Dane jr    Carlo
Dane Br    Carlo
Daniel     Gerard
</code>```

forename should be same and surname partially same (means string before space  should be same after space should not same)

Output like

```<code>surname    forename
Dane jr    Carlo
Dane Br    Carlo
</code>```

答:
This should work, please test it with a larger dataset though. It will return any rows where the names appear more than once. It matches rows based on the forename and the first part of the surname (before the space, if one exists).

```<code>CREATE TABLE #names
    (
      surname NVARCHAR(50) ,
      forename NVARCHAR(50)
    );

INSERT  INTO #names
        ( surname, forename )
VALUES  ( 'Dane jr', 'Carlo' ),
        ( 'Dane Br', 'Carlo' ),
        ( 'Daniel', 'Gerard' );

SELECT  surname ,
        n1.forename
FROM    #names n1
        INNER JOIN ( SELECT LEFT(surname, CHARINDEX(' ', surname)) FirstPartSurname ,
                            forename
                     FROM   #names
                   ) n2 ON n2.forename = n1.forename
                           AND n1.surname LIKE n2.FirstPartSurname + '%'
GROUP BY n1.surname ,
        n1.forename
HAVING  COUNT(1) > 1;

DROP TABLE #names;
</code>```

Produces:

```<code>surname  forename
Dane Br  Carlo
Dane jr  Carlo
</code>```

Body:
I have table with columns

surname    forename
Dane jr    Carlo
Dane Br    Carlo
Daniel     Gerard

forename should be same and surname partially same (means string before space  should be same after space should not same)

Output like

surname    forename
Dane jr    Carlo
Dane Br    Carlo

Body:
This should work, please test it with a larger dataset though. It will return any rows where the names appear more than once. It matches rows based on the forename and the first part of the surname (before the space, if one exists).

CREATE TABLE #names
    (
      surname NVARCHAR(50) ,
      forename NVARCHAR(50)
    );

INSERT  INTO #names
        ( surname, forename )
VALUES  ( 'Dane jr', 'Carlo' ),
        ( 'Dane Br', 'Carlo' ),
        ( 'Daniel', 'Gerard' );

SELECT  surname ,
        n1.forename
FROM    #names n1
        INNER JOIN ( SELECT LEFT(surname, CHARINDEX(' ', surname)) FirstPartSurname ,
                            forename
                     FROM   #names
                   ) n2 ON n2.forename = n1.forename
                           AND n1.surname LIKE n2.FirstPartSurname + '%'
GROUP BY n1.surname ,
        n1.forename
HAVING  COUNT(1) > 1;

DROP TABLE #names;

Produces:

surname  forename
Dane Br  Carlo
Dane jr  Carlo


问:
OSError: [WinError 10038] An operation was attempted on something that is not a socket
I was testing out a client-side scheme here

server and client use same port 9009 to connect

somehow the following code gives me OSError as wrote in the titile:

```<code>import sys
import socket
import select

def chat_client():
    if(len(sys.argv) < 3) :
        print ('Usage : python chat_client.py hostname port')
        sys.exit()

    host = sys.argv[1]
    port = int(sys.argv[2])

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(2)

    # connect to remote host
    try :
        s.connect((host, port))
    except :
        print ('Unable to connect')
        sys.exit()

    print ('Connected to remote host. You can start sending messages')
    sys.stdout.write('[Me] '); sys.stdout.flush()

    while 1:
        socket_list = [sys.stdin, s]

        # Get the list sockets which are readable
        ready_to_read,ready_to_write,in_error = select.select(socket_list,[],[])
        # the timeout argument is omitted in above code,so chat_client blocks until a fd is ready
        for sock in ready_to_read:
            if sock == s:
                # incoming message from remote server, s
                data = sock.recv(4096)   # sock.recv argument is buffsize, recommend 4096
                if not data :            # if not (data is not none), data is empty
                    print ('\nDisconnected from chat server')
                    sys.exit()
                else :                   # data has something
                    #print data
                    sys.stdout.write(data)   # write something to standard output buffer
                    sys.stdout.write('[Me] '); sys.stdout.flush() # write everything to terminal from buffer

            else :     # sock ! = s
                # user entered a message
                msg = sys.stdin.readline()    # readline pick up everything from stdin
                s.send(msg)
                sys.stdout.write('[Me] '); sys.stdout.flush()

if __name__ == "__main__":

  sys.exit(chat_client())
</code>```

Any one can give me some tips on this ?  :)

答:
```<code>        socket_list = [sys.stdin, s]

        # Get the list sockets which are readable
        ready_to_read,ready_to_write,in_error = select.select(socket_list,[],[])
</code>```

Python »   Documentation » The Python Standard Library » 16. Optional Operating System Services » 16.1. select — Waiting for I/O completion:

… Note that on Windows, it only works for sockets; on other operating
  systems, it also works for other file types …

So, unlike on a sane OS, we cannot use sys.stdin here.

Body:
I was testing out a client-side scheme here

server and client use same port 9009 to connect

somehow the following code gives me OSError as wrote in the titile:

import sys
import socket
import select

def chat_client():
    if(len(sys.argv) < 3) :
        print ('Usage : python chat_client.py hostname port')
        sys.exit()

    host = sys.argv[1]
    port = int(sys.argv[2])

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(2)

    # connect to remote host
    try :
        s.connect((host, port))
    except :
        print ('Unable to connect')
        sys.exit()

    print ('Connected to remote host. You can start sending messages')
    sys.stdout.write('[Me] '); sys.stdout.flush()

    while 1:
        socket_list = [sys.stdin, s]

        # Get the list sockets which are readable
        ready_to_read,ready_to_write,in_error = select.select(socket_list,[],[])
        # the timeout argument is omitted in above code,so chat_client blocks until a fd is ready
        for sock in ready_to_read:
            if sock == s:
                # incoming message from remote server, s
                data = sock.recv(4096)   # sock.recv argument is buffsize, recommend 4096
                if not data :            # if not (data is not none), data is empty
                    print ('\nDisconnected from chat server')
                    sys.exit()
                else :                   # data has something
                    #print data
                    sys.stdout.write(data)   # write something to standard output buffer
                    sys.stdout.write('[Me] '); sys.stdout.flush() # write everything to terminal from buffer

            else :     # sock ! = s
                # user entered a message
                msg = sys.stdin.readline()    # readline pick up everything from stdin
                s.send(msg)
                sys.stdout.write('[Me] '); sys.stdout.flush()

if __name__ == "__main__":

  sys.exit(chat_client())

Any one can give me some tips on this ?  :)

Body:
        socket_list = [sys.stdin, s]

        # Get the list sockets which are readable
        ready_to_read,ready_to_write,in_error = select.select(socket_list,[],[])

Python »   Documentation » The Python Standard Library » 16. Optional Operating System Services » 16.1. select — Waiting for I/O completion:

… Note that on Windows, it only works for sockets; on other operating
  systems, it also works for other file types …

So, unlike on a sane OS, we cannot use sys.stdin here.


问:
Javascript question: about variable definition
I have no idea why it didn't work if I specify a variable with 'var':
like this:

```<code>var mytool = function(){
      return {
         method: function(){}
     }
}();
</code>```

And later I use it in the same template: mytool.method. This will output mytool was not defined.

But if I define it like this:

```<code>     mytool = function(){
          return {
             method: function(){}
         }
    }();
</code>```

Then it works.

答:
The reason why you are getting variable undefined errors is because when you use var, the declared variable is scoped to the surrounding context, meaning that the variable's lifetime is limited to the lifetime of the surrounding context (function, block, whathaveyou).

If you don't use var however, you are effectively declaring a variable tied to global scope. (Usually a Very Bad Idea).

So, in your code, the reason why you are able to access the mytool variable somewhere else in your template is because you tied it to global scope, where in the case of using var, the variable went out of scope because it must have been declared within a function.

Body:
I have no idea why it didn't work if I specify a variable with 'var':
like this:

var mytool = function(){
      return {
         method: function(){}
     }
}();

And later I use it in the same template: mytool.method. This will output mytool was not defined.

But if I define it like this:

     mytool = function(){
          return {
             method: function(){}
         }
    }();

Then it works.


问:
Android Schedule Task when internet connection available
I have implemented an android application which retrieves data from database hosted outside and save it locally on the device.

What I need to do is check every day for changes in the hosted database and based on changes the application will update the local SQLite database.

My question: I need to check in background any changes on database daily, at the moment when the job starts and there is an internet connection it will check and stop and rerun the next day, if there is currently no internet connection the job must check every 10 min until an internet connection is available.
 Also I need the job to not to be effected if the device reboots.

If someone can provide me with small demonstration code since I am a beginner in android development this will highly appreciated.

答:
You can use Job schedule in Android, pre Lollipop there is Firebase job schedule, this save data, time and battery you can check more here

https://developer.android.com/reference/android/app/job/JobScheduler.html


问:
convert vector of char to an int
I need to convert a part of vectors of chars to an int.

If I have

```<code>std::vector<char> // which contains something like asdf1234dsdsd
</code>```

and I want to take characters from the 4th till 7th position and convert it into an int.

The positions are always known.

How do I do it the fastest way ?

I tried to use global copy and got a weird answer. Instead of 2 I got 48.

答:
```<code>long res = 0;

for(int i=0; i<vec.size(); i++)
{
     res += vec[i] * pow (2, 8*(vec.size() - i - 1)); // 8 means number of bits in byte
}
</code>```

Title: convert vector of char to an int

Body:
I need to convert a part of vectors of chars to an int.

If I have

std::vector<char> // which contains something like asdf1234dsdsd

and I want to take characters from the 4th till 7th position and convert it into an int.

The positions are always known.

How do I do it the fastest way ?

I tried to use global copy and got a weird answer. Instead of 2 I got 48.


问:
How to prevent blogger from converting my c++ source code snippet in compose view?
Say I write the following at the "Compose" tab of a blog post:

```<code>a->x(100)
</code>```

I publish the post.

If I view the post, it is what I want, basically the above code.

The problem is when I come to the post to edit it again, it is changed:

```<code>a->x(100)
</code>```

This is frustrating.

I am not a HTML geek, any straightforward solution?

[UPDATE]
I guess there is no simple solution here for people like me not willing to mess around HTML. A workaround is, when I have a blog with code snippet, I just write it in google doc and reference it in the blog.

答:
This happens because the XML parser that Blogger uses escapes certain characters (Refer to this answer for more information).A way to stop the content from getting escaped is by enclosing it within -

```<code><![CDATA[
 ... Your code ...
]]>
</code>```

But Blogger only honors this when the content is present in script or noscript tag. Therefore, something that will work -

```<code><noscript>
  <![CDATA[
    a->x(100)
  ]]>
</noscript>
</code>```

But the noscript tag isn't rendered by the browser, so you will have to use a bit of JavaScript to make it show up

document.querySelector('noscript').insertAdjacentHTML('beforebegin','```<code>'+document.querySelector('noscript').textContent.replace("<![CDATA[","").replace("]]>","")+'</code>```');```
<pre class="snippet-code-html lang-html prettyprint-override"><code><noscript>
  <![CDATA[
    a->x(100)
  ]]>
</noscript></code>```

The above javascript snippet will render the content present inside the noscript tag. If you have multiple noscript tags in a page, then it will to be adapted to loop over them.

Body:
Say I write the following at the "Compose" tab of a blog post:

a->x(100)

I publish the post.

If I view the post, it is what I want, basically the above code.

The problem is when I come to the post to edit it again, it is changed:

a->x(100)

This is frustrating.

I am not a HTML geek, any straightforward solution?

[UPDATE]
I guess there is no simple solution here for people like me not willing to mess around HTML. A workaround is, when I have a blog with code snippet, I just write it in google doc and reference it in the blog.

Body:
This happens because the XML parser that Blogger uses escapes certain characters (Refer to this answer for more information).A way to stop the content from getting escaped is by enclosing it within -

<![CDATA[
 ... Your code ...
]]>

But Blogger only honors this when the content is present in script or noscript tag. Therefore, something that will work -

<noscript>
  <![CDATA[
    a->x(100)
  ]]>
</noscript>

But the noscript tag isn't rendered by the browser, so you will have to use a bit of JavaScript to make it show up

document.querySelector('noscript').insertAdjacentHTML('beforebegin','<pre><code>'+document.querySelector('noscript').textContent.replace("<![CDATA[","").replace("]]>","")+'</code></pre>');

<noscript>
  <![CDATA[
    a->x(100)
  ]]>
</noscript>

The above javascript snippet will render the content present inside the noscript tag. If you have multiple noscript tags in a page, then it will to be adapted to loop over them.


问:
How to add custom form element fckeditor in zend framework
I want to use fckeditor in my website using zend framework.

Can any one explain how can we add custom form elements with zend framework ?

答:
It is not the "good practice" here - to give a link, but I don't think this question can be answered better without copy-paste:

http://www.leftcolumn.net/2009/03/10/zend-framework-how-to-add-fckeditor-to-a-zend_form/

http://www.zfsnippets.com/snippets/view/id/55

ps: I'm curious, why did not you google for first http://www.google.ru/search?q=zend+form+fckeditor+&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:ru:official&client=firefox ?


问:
row number based on unique column value in oralce?
I do need to implement a oracle sql to have row number defined as below:

```<code>row_num, column1, column2, cloumn3
1, ABC, 123, a1
1, ABC, 125, a2
2, ABD, 123, a3
2, ABD, 124, a4
2, ABD, 125, a5
3, ABE, 123, a1
</code>```

Here I defined row number based on unique value of column1.

Can any one help me to write oracle sql to define row number in this way?

Thanks
Venkat

答:
You need the DENSE_RANK() analytic function:

```<code>WITH your_table AS (SELECT 'ABC' col1, 123 col2, 'a1' col3 FROM dual UNION ALL
                    SELECT 'ABC' col1, 125 col2, 'a2' col3 FROM dual UNION ALL
                    SELECT 'ABD' col1, 123 col2, 'a3' col3 FROM dual UNION ALL
                    SELECT 'ABD' col1, 124 col2, 'a4' col3 FROM dual UNION ALL
                    SELECT 'ABD' col1, 125 col2, 'a5' col3 FROM dual UNION ALL
                    SELECT 'ABE' col1, 123 col2, 'a1' col3 FROM dual)
  -- end of subquery mimicking your_table with data in; See SQL below:
SELECT dense_rank() OVER (ORDER BY col1) row_num,
       col1,
       col2,
       col3
FROM   your_table
ORDER BY col1, col2, col3;

   ROW_NUM COL1       COL2 COL3
---------- ---- ---------- ----
         1 ABC         123 a1
         1 ABC         125 a2
         2 ABD         123 a3
         2 ABD         124 a4
         2 ABD         125 a5
         3 ABE         123 a1
</code>```

DENSE_RANK() is similar to RANK() in that it will assign tied rows the same rank (that is, rows that have the same values in the columns being ordered - in your case, col1), but unlike RANK(), DENSE_RANK() won't skip rank numbers.

Body:
I do need to implement a oracle sql to have row number defined as below:

row_num, column1, column2, cloumn3
1, ABC, 123, a1
1, ABC, 125, a2
2, ABD, 123, a3
2, ABD, 124, a4
2, ABD, 125, a5
3, ABE, 123, a1

Here I defined row number based on unique value of column1.

Can any one help me to write oracle sql to define row number in this way?

Thanks
Venkat

Body:
You need the DENSE_RANK() analytic function:

WITH your_table AS (SELECT 'ABC' col1, 123 col2, 'a1' col3 FROM dual UNION ALL
                    SELECT 'ABC' col1, 125 col2, 'a2' col3 FROM dual UNION ALL
                    SELECT 'ABD' col1, 123 col2, 'a3' col3 FROM dual UNION ALL
                    SELECT 'ABD' col1, 124 col2, 'a4' col3 FROM dual UNION ALL
                    SELECT 'ABD' col1, 125 col2, 'a5' col3 FROM dual UNION ALL
                    SELECT 'ABE' col1, 123 col2, 'a1' col3 FROM dual)
  -- end of subquery mimicking your_table with data in; See SQL below:
SELECT dense_rank() OVER (ORDER BY col1) row_num,
       col1,
       col2,
       col3
FROM   your_table
ORDER BY col1, col2, col3;

   ROW_NUM COL1       COL2 COL3
---------- ---- ---------- ----
         1 ABC         123 a1
         1 ABC         125 a2
         2 ABD         123 a3
         2 ABD         124 a4
         2 ABD         125 a5
         3 ABE         123 a1

DENSE_RANK() is similar to RANK() in that it will assign tied rows the same rank (that is, rows that have the same values in the columns being ordered - in your case, col1), but unlike RANK(), DENSE_RANK() won't skip rank numbers.


问:
Regarding Messages in Veins
I want to send a message as soon as the vehicle starts. For this I am using the self-message technique. I send a self-message and in the handleMessage method after receiving the self-message I send the WaveShortMessage which I want to send.

Is this the correct way to send the message?

Also I want to know the difference between a cMessage and a WaveShortMessage.

答:
Yes, this is the correct way of doing it as you can see for example in BaseWaveApplLayer.

A cMessage is OMNeT++' base class for messages whereas a WaveShortMessage is a special message type for the WAVE-Stack which inherits from cMessage when the corresponding header file is generated.

Title: Regarding Messages in Veins


问:
ldap server is unavailable
I'm totally new to this

I've tried to connect to an ldap server using the following code.

```<code>PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, "abcdef", "OU=abcdef,DC=avengers,DC=net");
</code>```

I'm getting an "LDAP server is unavailable" exception.

I've looked up other posts which recommended adding username and password to it but I wanted to use this specific overloaded method which takes in Context.Domain, Domain and Container parameters only.

Any suggestions would be appreciated.

答:
I think you are not using Active Directory.

PrincipalContext works well with AD only.
If your directory is OpenLDAP/ any other, then try below code

```<code> public static void Main(String[] rags)
    {
        //If you are not sure about username and password, leave below 2 variables as it is
        String username="";        //Change to your username, if you have any
        String passwd="";           //Change to your Password, if you have any

        DirectoryEntry entry = new DirectoryEntry("LDAP://abcedf/OU=abcdef,DC=avengers,DC=net", username, passwd, AuthenticationTypes.None);
        DirectorySearcher ds = new DirectorySearcher(entry,"ObjectClass=*");

        // Below statement will list all entries immediately below your BaseDN
        foreach (DirectoryEntry c in entry.Children)
        {
            Console.WriteLine("{0}", c.Path);
        }
     }
</code>```

Title: ldap server is unavailable

Body:
I'm totally new to this

I've tried to connect to an ldap server using the following code.

PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, "abcdef", "OU=abcdef,DC=avengers,DC=net");

I'm getting an "LDAP server is unavailable" exception.

I've looked up other posts which recommended adding username and password to it but I wanted to use this specific overloaded method which takes in Context.Domain, Domain and Container parameters only.

Any suggestions would be appreciated.

Body:
I think you are not using Active Directory.

PrincipalContext works well with AD only.
If your directory is OpenLDAP/ any other, then try below code

 public static void Main(String[] rags)
    {
        //If you are not sure about username and password, leave below 2 variables as it is
        String username="";        //Change to your username, if you have any
        String passwd="";           //Change to your Password, if you have any

        DirectoryEntry entry = new DirectoryEntry("LDAP://abcedf/OU=abcdef,DC=avengers,DC=net", username, passwd, AuthenticationTypes.None);
        DirectorySearcher ds = new DirectorySearcher(entry,"ObjectClass=*");

        // Below statement will list all entries immediately below your BaseDN
        foreach (DirectoryEntry c in entry.Children)
        {
            Console.WriteLine("{0}", c.Path);
        }
     }


问:
onClick() and AlertDialog onClick - Android Studio
i am a new programmer using Android studio and I have the following in one of my activity's code:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) { /* code */ }

@Override
public void onClick(View ButtonSelected)
{
   switch (ButtonSelected.getId())
   {
      case R.id.Button1:
      // code
      break;

      case R.id.Button2:
      // code
      break;

   }
}

public void GUIMessageBox()
{
    /* this function is called in the cases where a message box must appear
       to the user and he has to select either "Yes" or "No".
       the function initializes the AlertDialog.Builder and present it to the
       user*/

     new AlertDialog.Builder(this)
            .setTitle("Sample Title")
            .setMessage("Sample Message")
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            // code for Yes selection
        }
    })
            .setNegativeButton("No", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            // code for No selection
        }
    })
            .show();
}
</code>```

When I run the app, the app works normally. When it is needed to present the message box I get the error "Unfortunately, App has stopped"

When i go back to my code the .setPositiveButton and .setNegativeButton look like:

```<code>  .setPositiveButton("Yes", (arg0, arg1) -> {

                        // code for "Yes" case
                })
</code>```

.setNegativeButton("No", (arg0, arg1) -> {
             // code for "No" case

})

I think is because there are more than one "onClick" functions.
I tried to avoid this but still did not managed to fix it.

Does anyone have a hint for this ?

Thank you :)

答:
Change "this" in

new AlertDialog.Builder(this)

to "nameClass.this" (ex. MainActivity.this) and change the "id" in both

public void onClick(DialogInterface dialog, int id)

to "which"

```<code>public void GUIMessageBox()
{
    /* this function is called in the cases where a message box must appear
       to the user and he has to select either "Yes" or "No".
       the function initializes the AlertDialog.Builder and present it to the
       user*/

     new AlertDialog.Builder(this)
            .setTitle("Sample Title")
            .setMessage("Sample Message")
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            // code for Yes selection
        }
    })
            .setNegativeButton("No", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            // code for No selection
        }
    })
            .show();
}
</code>```

That's how I have it in my code, hope it works

Body:
i am a new programmer using Android studio and I have the following in one of my activity's code:

@Override
protected void onCreate(Bundle savedInstanceState) { /* code */ }

@Override
public void onClick(View ButtonSelected)
{
   switch (ButtonSelected.getId())
   {
      case R.id.Button1:
      // code
      break;

      case R.id.Button2:
      // code
      break;

   }
}

public void GUIMessageBox()
{
    /* this function is called in the cases where a message box must appear
       to the user and he has to select either "Yes" or "No".
       the function initializes the AlertDialog.Builder and present it to the
       user*/

     new AlertDialog.Builder(this)
            .setTitle("Sample Title")
            .setMessage("Sample Message")
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            // code for Yes selection
        }
    })
            .setNegativeButton("No", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            // code for No selection
        }
    })
            .show();
}

When I run the app, the app works normally. When it is needed to present the message box I get the error "Unfortunately, App has stopped"

When i go back to my code the .setPositiveButton and .setNegativeButton look like:

  .setPositiveButton("Yes", (arg0, arg1) -> {

                        // code for "Yes" case
                })

.setNegativeButton("No", (arg0, arg1) -> {
             // code for "No" case

})

I think is because there are more than one "onClick" functions.
I tried to avoid this but still did not managed to fix it.

Does anyone have a hint for this ?

Thank you :)

Body:
Change "this" in

new AlertDialog.Builder(this)

to "nameClass.this" (ex. MainActivity.this) and change the "id" in both

public void onClick(DialogInterface dialog, int id)

to "which"

public void GUIMessageBox()
{
    /* this function is called in the cases where a message box must appear
       to the user and he has to select either "Yes" or "No".
       the function initializes the AlertDialog.Builder and present it to the
       user*/

     new AlertDialog.Builder(this)
            .setTitle("Sample Title")
            .setMessage("Sample Message")
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            // code for Yes selection
        }
    })
            .setNegativeButton("No", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            // code for No selection
        }
    })
            .show();
}

That's how I have it in my code, hope it works


问:
How to get data from promise to main function
I have function:

```<code>function find(id){

    var res = this.db.query(this.knex(this.table).where({id:id}).select().toString());

    var props = {};

    for(var c in res.rows[0]){
        if(res.rows[0].hasOwnProperty(c))
            props[c] = res.rows[0][c];
    }

    return this.newRecord(props);

}
</code>```

this.db here is pg.Client object from pg npm module. knex is an npm module too, it builds query to postgresql databse.
It returns promise, and I need to get data from this promise to main function, create object from this data and return it (newRecord function does it).

I have alredy tried installing node version 7 and using await, but that doesn't help because if function has async modifier, then it will return promise with object that comes after return, and I don't need this behaviour at all.

So, the question is how can I await for that promise to finish and get data from it, with or without async/await or any other es6 or es7 functionality?

答:
Pg Client Query method seems to be asynchronous function (since main function is not waiting for the query to return value to res and then proceed further). So, what you should do is pass a callback function to your query method as follow -

function find(id){
    var res;
   this.db.query(this.knex(this.table).where({id:id}).select().toString(), function(err, result) {
      if(!err){
        console.log("Result is - " + result);
        res = result //if its an array, use res = result.splice();

         var props = {};

      for(var c in res.rows[0]){
        if(res.rows[0].hasOwnProperty(c))
            props[c] = res.rows[0][c];
     }

     return this.newRecord(props);

      }
      else {
        console.error("Error occured -" + err);
      }
    }
    );

});```

Body:
I have function:

function find(id){

    var res = this.db.query(this.knex(this.table).where({id:id}).select().toString());

    var props = {};

    for(var c in res.rows[0]){
        if(res.rows[0].hasOwnProperty(c))
            props[c] = res.rows[0][c];
    }

    return this.newRecord(props);

}

this.db here is pg.Client object from pg npm module. knex is an npm module too, it builds query to postgresql databse.
It returns promise, and I need to get data from this promise to main function, create object from this data and return it (newRecord function does it).

I have alredy tried installing node version 7 and using await, but that doesn't help because if function has async modifier, then it will return promise with object that comes after return, and I don't need this behaviour at all.

So, the question is how can I await for that promise to finish and get data from it, with or without async/await or any other es6 or es7 functionality?


问:
how to get current time in AVAudioplayer in a label while playing
I tried to build an app to play the MP3 files. I want to get current time and duration to show it in 2 labels while playing.

I used this code:

```<code>let duration = Int((player1?.duration)!)
let minutes2 = duration/60
let seconds2 = duration - minutes2 * 60
durLabel.text = NSString(format: "%02d:%02d", minutes2,seconds2) as String

let currentTime1 = Int((player1?.currentTime)!)
let minutes = currentTime1/60
let seconds = currentTime1 - minutes * 60
curLabel.text = NSString(format: "%02d:%02d", minutes,seconds) as String
</code>```

In duration it shows the half time of the song.

For example:
If the duration of the song is 20 minutes and 40 seconds, it shows the half like that 10:20. But it did not make progress in the case of current time, it shows 00:00

Thanks at all.

答:
The player's current time will not automatically update. Instead, you have to periodically update the current time using a timer. Take a look at the following thread if you want more details.

check avaudioplayer's current playback time

Body:
I tried to build an app to play the MP3 files. I want to get current time and duration to show it in 2 labels while playing.

I used this code:

let duration = Int((player1?.duration)!)
let minutes2 = duration/60
let seconds2 = duration - minutes2 * 60
durLabel.text = NSString(format: "%02d:%02d", minutes2,seconds2) as String

let currentTime1 = Int((player1?.currentTime)!)
let minutes = currentTime1/60
let seconds = currentTime1 - minutes * 60
curLabel.text = NSString(format: "%02d:%02d", minutes,seconds) as String

In duration it shows the half time of the song.

For example:
If the duration of the song is 20 minutes and 40 seconds, it shows the half like that 10:20. But it did not make progress in the case of current time, it shows 00:00

Thanks at all.


问:
Conversion of long long to byte array and back in c++
I've written a test to try and figure out how conversion between char[] arrays and long long can work. Partially for my own understanding, I'm trying to figure out the bitwise method of doing so.

Conceptually, for a long long to a char[], the below feels right.  I'm shifting left, then AND-ing to limit to the right:

```<code>for (int i = 0; i < BUFFER_SIZE; i++)
{
    buffer[i] = ((value >> (8 * i)) & 0XFF);
}
</code>```

To convert back, shift left and sum over the buffer:

```<code>long long recoveredValue = 0;
for (int i = 0; i < BUFFER_SIZE; i++)
{
    auto byteVal = ((buffer[i]) << (8 * i));
    recoveredValue = recoveredValue + byteVal;
}
</code>```

Below is my whole test program.  It seems as though when I'm filling the doing the first step above (in IntToByteArray) the value of buffer[0] is repeated at `buffer[32]'.   I know there's a problem here, but I can't figure it out.

Note that for my application, I have a BUFFER_SIZE of 63, and my long long will be limited to below 2^63.  Also, if I restrict BUFFER_SIZE to below 32, it works.  I'm missing a subtlty regarding the 64 bit int aren't I?  But where, & how?

```<code>// Test_BitConversion.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <cmath>

#define BUFFER_SIZE 64
unsigned char buffer[BUFFER_SIZE] = { 0 };  // This is the buffer I have available

// useful alternative method for checking conversion
// can't use in production, because I'm moving between C++ & C#
union byteunion
{
    long long value;
    unsigned char arr[BUFFER_SIZE];
};

// Convert long long to byte array
void IntToByteArray(long long value)
{
    for (int i = 0; i < BUFFER_SIZE; i++)
    {
        buffer[i] = ((value >> (8 * i)) & 0XFF);
    }
}

// Convert byte array to long long
long long ByteArrayToInt()
{
    long long recoveredValue = 0;
    for (int i = 0; i < BUFFER_SIZE; i++)
    {
        auto byteVal = ((buffer[i]) << (8 * i));
        recoveredValue = recoveredValue + byteVal;
    }
    return recoveredValue;
}

// Test union can convert value both directions
bool TestUnion(long long value)
{
    byteunion originalUnion, recoveredUnion;
    originalUnion.value = value;

    for (int a = 0; a < BUFFER_SIZE; a++)
    {
        recoveredUnion.arr[a] = originalUnion.arr[a];
    }

    if (recoveredUnion.value != value)
    {
        printf("Union value failed");
        return false;
    }

    return true;
}

int main()
{

    long long originalValue = 2004293008363;
    originalValue = (long long)std::pow(2, 31);
    long long recoveredValue = 0;
    byteunion originalUnion;
    originalUnion.value = originalValue;

    // Loop to find failure point
    for (int i = 1; i < BUFFER_SIZE; i++)
    {
        originalValue = (long long)std::pow(2, i);

        // First check Union method
        bool unionTest = TestUnion(originalValue);
        if (!unionTest)
        {
            printf("Fail on Union at 2^%i", i);
            break; // this is never reached - union method works
        }

        // convert value to byte array
        IntToByteArray(originalValue);

        // now convert buffer back to long long
        recoveredValue = ByteArrayToInt();

        if (originalValue != recoveredValue)
        {
            printf("Fail recoving at 2^%i\n", i);
            break;  // this is reached when the original value is 2^31
        }

    }

    printf(" OriginalValue: %llu\n", originalValue);
    printf("RecoveredValue: %llu\n", recoveredValue);

    system("pause");

    return 0;
}
</code>```

答:
The problem is in converting the value back. Due to integer promotions, this expression

```<code>auto byteVal = ((buffer[i]) << (8 * i));
</code>```

has type int, not long long.

Add a cast to buffer[1] to fix the problem:

```<code>auto byteVal = (((long long)buffer[i]) << (8 * i));
</code>```

Although using + works fine, a more common approach in combining values is to use |:

```<code>recoveredValue |= byteVal;
</code>```

Body:
I've written a test to try and figure out how conversion between char[] arrays and long long can work. Partially for my own understanding, I'm trying to figure out the bitwise method of doing so.

Conceptually, for a long long to a char[], the below feels right.  I'm shifting left, then AND-ing to limit to the right:

for (int i = 0; i < BUFFER_SIZE; i++)
{
    buffer[i] = ((value >> (8 * i)) & 0XFF);
}

To convert back, shift left and sum over the buffer:

long long recoveredValue = 0;
for (int i = 0; i < BUFFER_SIZE; i++)
{
    auto byteVal = ((buffer[i]) << (8 * i));
    recoveredValue = recoveredValue + byteVal;
}

Below is my whole test program.  It seems as though when I'm filling the doing the first step above (in IntToByteArray) the value of buffer[0] is repeated at `buffer[32]'.   I know there's a problem here, but I can't figure it out.

Note that for my application, I have a BUFFER_SIZE of 63, and my long long will be limited to below 2^63.  Also, if I restrict BUFFER_SIZE to below 32, it works.  I'm missing a subtlty regarding the 64 bit int aren't I?  But where, & how?

// Test_BitConversion.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <cmath>

#define BUFFER_SIZE 64
unsigned char buffer[BUFFER_SIZE] = { 0 };  // This is the buffer I have available

// useful alternative method for checking conversion
// can't use in production, because I'm moving between C++ & C#
union byteunion
{
    long long value;
    unsigned char arr[BUFFER_SIZE];
};

// Convert long long to byte array
void IntToByteArray(long long value)
{
    for (int i = 0; i < BUFFER_SIZE; i++)
    {
        buffer[i] = ((value >> (8 * i)) & 0XFF);
    }
}

// Convert byte array to long long
long long ByteArrayToInt()
{
    long long recoveredValue = 0;
    for (int i = 0; i < BUFFER_SIZE; i++)
    {
        auto byteVal = ((buffer[i]) << (8 * i));
        recoveredValue = recoveredValue + byteVal;
    }
    return recoveredValue;
}

// Test union can convert value both directions
bool TestUnion(long long value)
{
    byteunion originalUnion, recoveredUnion;
    originalUnion.value = value;

    for (int a = 0; a < BUFFER_SIZE; a++)
    {
        recoveredUnion.arr[a] = originalUnion.arr[a];
    }

    if (recoveredUnion.value != value)
    {
        printf("Union value failed");
        return false;
    }

    return true;
}

int main()
{

    long long originalValue = 2004293008363;
    originalValue = (long long)std::pow(2, 31);
    long long recoveredValue = 0;
    byteunion originalUnion;
    originalUnion.value = originalValue;

    // Loop to find failure point
    for (int i = 1; i < BUFFER_SIZE; i++)
    {
        originalValue = (long long)std::pow(2, i);

        // First check Union method
        bool unionTest = TestUnion(originalValue);
        if (!unionTest)
        {
            printf("Fail on Union at 2^%i", i);
            break; // this is never reached - union method works
        }

        // convert value to byte array
        IntToByteArray(originalValue);

        // now convert buffer back to long long
        recoveredValue = ByteArrayToInt();

        if (originalValue != recoveredValue)
        {
            printf("Fail recoving at 2^%i\n", i);
            break;  // this is reached when the original value is 2^31
        }

    }

    printf(" OriginalValue: %llu\n", originalValue);
    printf("RecoveredValue: %llu\n", recoveredValue);

    system("pause");

    return 0;
}

Body:
The problem is in converting the value back. Due to integer promotions, this expression

auto byteVal = ((buffer[i]) << (8 * i));

has type int, not long long.

Add a cast to buffer[1] to fix the problem:

auto byteVal = (((long long)buffer[i]) << (8 * i));

Although using + works fine, a more common approach in combining values is to use |:

recoveredValue |= byteVal;


问:
Change project name on Android Studio
I want to change the name of my project and module. But if I try to rename them Android Studio notify me some errors...

e.g. I want to change the name from "MyApplication" to "AndroidApp" as shown in the image below.

In the first rectangle I want to change it in:

AndroidApp ("G:...\Android\AndroidApp).

In the second rectangle I want to change it in:

AndroidApp [AndroidApp-AndroidApp]

edit: This is the log:

Gradle: Project 'AndroidApp' not found in root project 'MyApplicationProject'.

build.gradle:

```<code>buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.5.+'
    }
}
apply plugin: 'android'

repositories {
    mavenCentral()
}

android {
    compileSdkVersion 18
    buildToolsVersion "18.0.1"

    defaultConfig {
        minSdkVersion 7
        targetSdkVersion 16
    }
}

dependencies {
    compile 'com.android.support:support-v4:18.0.0'
}
</code>```

settings.gradle:

```<code>include ':MyApplication'
</code>```

答:
These instructions below worked (first time) for me in Android Studio 2.3. They involve creating a new app in Android Studio, then closing it and doing all the work in a file explorer and a text editor.

Refactor and Rename a Android Studio Project or App

Note: Requires a text editor which can do a global search-and-replace in a directory structure. The instructions propose Sublime Text, which I easily installed and ran.

It produced a new app which installed and ran beside the existing app. It still had the same screen name, which was fixed by editing  Android:label="MyNewApp" in the manifest.

Title: Change project name on Android Studio

Body:
I want to change the name of my project and module. But if I try to rename them Android Studio notify me some errors...

e.g. I want to change the name from "MyApplication" to "AndroidApp" as shown in the image below.

In the first rectangle I want to change it in:

AndroidApp ("G:...\Android\AndroidApp).

In the second rectangle I want to change it in:

AndroidApp [AndroidApp-AndroidApp]

edit: This is the log:

Gradle: Project 'AndroidApp' not found in root project 'MyApplicationProject'.

build.gradle:

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.5.+'
    }
}
apply plugin: 'android'

repositories {
    mavenCentral()
}

android {
    compileSdkVersion 18
    buildToolsVersion "18.0.1"

    defaultConfig {
        minSdkVersion 7
        targetSdkVersion 16
    }
}

dependencies {
    compile 'com.android.support:support-v4:18.0.0'
}

settings.gradle:

include ':MyApplication'


问:
identifying the device for iPad iOS 4.2
I understood that iOS 4.2 is for iPad as well. The code below is the standard pattern which we all use for identifying the device. how will this change for the 4.2 iPad. Should i change the code to consider the device type rather than version ?</p>

```<code>#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 30200
    CGRect frame = [[UIScreen mainScreen] bounds];
    self.view.frame = frame;
#else
    CGRect frame = [self.view bounds];
#endif
</code>```

答:
You can try this also:</p>

```<code>#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 30200

if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
 {
     // type you code for iPad
 } else {
     // type you code for iPhone
 }

#endif
</code>```

Title: identifying the device for iPad iOS 4.2

Body:
I understood that iOS 4.2 is for iPad as well. The code below is the standard pattern which we all use for identifying the device. how will this change for the 4.2 iPad. Should i change the code to consider the device type rather than version ?

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 30200
    CGRect frame = [[UIScreen mainScreen] bounds];
    self.view.frame = frame;
#else
    CGRect frame = [self.view bounds];
#endif

Body:
You can try this also:

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 30200

if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
 {
     // type you code for iPad
 } else {
     // type you code for iPhone
 }

#endif