问:
How do I implement a "phonetical"-like search
Currently I'm trying to enhance my search algorithm.

For better understanding, here's the current logic behind it:

we have objects with attached n keywords in db. in database this is solved via 2 tables (Object, Keyword) where the Keyword-table has a FK to Object. When i'm building my searchtrees I create a line-value (ad: remove umlauts, convert to lower-case, ...) of all keywords of an object. the same convertion-routine (NormalizeSearchPattern()) is done with the search-patterns. I'm supporting AND-search and keywords with minimum length of 2 characters only!

The search-algorithm is currently a variant of fast-reverse-search (this example is not optimized):

```<code>bool IsMatch(string source, string searchPattern)
{
    // example:
    // source: "hello world"
    // searchPattern: "hello you freaky funky world"
    // patterns[]: { "hello", "you", "freaky", "funky", "world" }

    searchPattern = NormalizeSearchPattern(searchPattern);
    var patterns = MagicMethodToSplitPatternIntoPatterns(searchPattern);
    foreach (var pattern in patterns)
    {
        var success = false;
        var patternLength = pattern.Length;
        var firstChar = pattern[0];
        var secondChar = pattern[1];

        var lengthDifference = input.Length - patternLength;
        while (lengthDifference >= 0)
        {
            if (source[lengthDifference--] != firstChar)
            {
                continue;
            }
            if (source[lengthDifference + 2] != secondChar)
            {
                continue;
            }

            var l = lengthDifference + 3;
            var m = 2;
            while (m < patternLength)
            {
                if (input[l] != pattern[m])
                {
                    break;
                }
                l++;
                m++;
            }

            if (m == patternLength)
            {
                success = true;
            }
        }
        if (!success)
        {
            return false;
        }
    }
    return true;
}
</code>```

Normalization is done with (this example is not optimized)

```<code>    string RemoveTooShortKeywords(string keywords)
    {
        while (Regex.IsMatch(keywords, TooShortKeywordPattern, RegexOptions.Compiled | RegexOptions.Singleline))
        {
            keywords = Regex.Replace(keywords, TooShortKeywordPattern, " ", RegexOptions.Compiled | RegexOptions.Singleline);
        }

        return keywords;
    }

    string RemoveNonAlphaDigits(string value)
    {
        value = value.ToLower();
        value = value.Replace("ä", "ae");
        value = value.Replace("ö", "oe");
        value = value.Replace("ü", "ue");
        value = value.Replace("ß", "ss");

        return Regex.Replace(value, "[^a-z 0-9]", " ", RegexOptions.Compiled | RegexOptions.Singleline);
    }

    string NormalizeSearchPattern(string searchPattern)
    {
        var resultNonAlphaDigits = RemoveNonAlphaDigits(searchPattern);
        var resultTrimmed = RemoveTooShortKeywords(resultNonAlphaDigits);
        return resultTrimmed;
    }
</code>```

So this is pretty straight forward, thus it's obvious, that I can only cope with variants of source and searchPattern which I've implemented in NormalizeSearchPattern() (as mentioned above: umlauts, case-differences, …).

But how should I enhance the algorithm (or NormalizeSearchPattern()) to be non-sensitive when it comes down to:

singular/plural

misstyping (eg. "hauserr" <-> "hauser")

...

Just to know more about the design:

This app is done in c#, it stores the searchtrees and objects in a static variable (to query the database only once at init), the performance has to be outstanding (currently 500.000 lineValues are queried within less than 300msec).

答:
Try looking at something called levenstein distance it computes how many changes is required to change one word into another.

Few changes indicates very simliar words.

For plural matching you could also use alias tables if the plural form is vastly different from singular but you still want them to match. I assume Google uses some form of alias lists for their suggestions of alternate questions.

Body:
Currently I'm trying to enhance my search algorithm.

For better understanding, here's the current logic behind it:

we have objects with attached n keywords in db. in database this is solved via 2 tables (Object, Keyword) where the Keyword-table has a FK to Object. When i'm building my searchtrees I create a line-value (ad: remove umlauts, convert to lower-case, ...) of all keywords of an object. the same convertion-routine (NormalizeSearchPattern()) is done with the search-patterns. I'm supporting AND-search and keywords with minimum length of 2 characters only!

The search-algorithm is currently a variant of fast-reverse-search (this example is not optimized):

bool IsMatch(string source, string searchPattern)
{
    // example:
    // source: "hello world"
    // searchPattern: "hello you freaky funky world"
    // patterns[]: { "hello", "you", "freaky", "funky", "world" }

    searchPattern = NormalizeSearchPattern(searchPattern);
    var patterns = MagicMethodToSplitPatternIntoPatterns(searchPattern);
    foreach (var pattern in patterns)
    {
        var success = false;
        var patternLength = pattern.Length;
        var firstChar = pattern[0];
        var secondChar = pattern[1];

        var lengthDifference = input.Length - patternLength;
        while (lengthDifference >= 0)
        {
            if (source[lengthDifference--] != firstChar)
            {
                continue;
            }
            if (source[lengthDifference + 2] != secondChar)
            {
                continue;
            }

            var l = lengthDifference + 3;
            var m = 2;
            while (m < patternLength)
            {
                if (input[l] != pattern[m])
                {
                    break;
                }
                l++;
                m++;
            }

            if (m == patternLength)
            {
                success = true;
            }
        }
        if (!success)
        {
            return false;
        }
    }
    return true;
}

Normalization is done with (this example is not optimized)

    string RemoveTooShortKeywords(string keywords)
    {
        while (Regex.IsMatch(keywords, TooShortKeywordPattern, RegexOptions.Compiled | RegexOptions.Singleline))
        {
            keywords = Regex.Replace(keywords, TooShortKeywordPattern, " ", RegexOptions.Compiled | RegexOptions.Singleline);
        }

        return keywords;
    }

    string RemoveNonAlphaDigits(string value)
    {
        value = value.ToLower();
        value = value.Replace("ä", "ae");
        value = value.Replace("ö", "oe");
        value = value.Replace("ü", "ue");
        value = value.Replace("ß", "ss");

        return Regex.Replace(value, "[^a-z 0-9]", " ", RegexOptions.Compiled | RegexOptions.Singleline);
    }

    string NormalizeSearchPattern(string searchPattern)
    {
        var resultNonAlphaDigits = RemoveNonAlphaDigits(searchPattern);
        var resultTrimmed = RemoveTooShortKeywords(resultNonAlphaDigits);
        return resultTrimmed;
    }

So this is pretty straight forward, thus it's obvious, that I can only cope with variants of source and searchPattern which I've implemented in NormalizeSearchPattern() (as mentioned above: umlauts, case-differences, …).

But how should I enhance the algorithm (or NormalizeSearchPattern()) to be non-sensitive when it comes down to:

singular/plural

misstyping (eg. "hauserr" <-> "hauser")

...

Just to know more about the design:

This app is done in c#, it stores the searchtrees and objects in a static variable (to query the database only once at init), the performance has to be outstanding (currently 500.000 lineValues are queried within less than 300msec).


来源: stackexchange

问:
How to set absolute position of the widgets in qt
I am using QT to develop a rich UI application.

I need to position widgets at absolute positions

I should be able to put the widget in background / foreground to add a few effects.

Simple example would be, I have to show a boiler with the water level inside the feed tank.

Take a feed tank image and embed in a label.

Position a progress bar in the center of the feedtank to display water level.

Now in this case the progress bar would be in the foreground and the label in the background.

Regards,

答:
I do it by creating a class based on Qwidget put its position in the constructor

ex:
QPointer  a = new QWidget (0, posx, posy, width, height)

in the constructor of this Qwidgetclass add these integrers posx, posy, width, height and then do
this.move(posx,posy);
this.resize(width,height);

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
How to execute powershell script from FAKE - F#MAKE
I am migrating MSBuild code to FAKE - and I am not able to execute powershell script from fake ,below is the code of MSBuild file to be written in FAKE :

```<code><Target Name="VersionConfig">
    <Exec IgnoreExitCode="false" LogStandardErrorAsError="true" StandardErrorImportance="high" Command="powershell -File "$(BuildRoot)\DeployScripts\scripts\AdminScripts\VersionUpdateFile.ps1"  -path "$(BuildSolutionVersioningConfig)" -majorVersion "$(BuildNumberMajor)" -minor "$(BuildNumberMinor)" -build "$(BuildNumber)" -revision "$(BuildNumberRevision)""/>
</Target>
</code>```

How to write this in FAKE , I'm new to FAKE and have not used F# much, so forgive me if this should be obvious.

If anyone can help , that would be really helpful.

Thank You .

答:
You can create a Powershell pipeline in any .NET application with the classes of the System.Management.Automation namespace. You can use that pipeline to execute commands locally or on a remote machine.

The following target retrieves the list of processes and prints them. It's the F# equivalent of the documentation example for the PowerShell class:

```<code>Target "ProcTest" (fun _ ->
    PowerShell.Create()
            .AddCommand("get-process")
            .Invoke()
            |> Seq.map(fun result->(  result.Properties.["ProcessName"].Value,
                                      result.Properties.["ID"].Value))
            |> Seq.iter (fun (name,id)->printfn "%-24O %O" name id)
)
</code>```

The is a quick & dirty module I use to execute commands (specifically chocolatey commands) on a remote server. The only thing you need to make it work on the local machine is to remove the ComputerName parameter:

```<code>#r "System.Management.Automation"

module MyPowershell =

    let InvokeRemote server command =
        let block = ScriptBlock.Create(command)
        let pipe=PowerShell.Create()
                .AddCommand("invoke-command")
        pipe.AddParameter("ComputerName", server)
            .AddParameter("ScriptBlock", block)
            .Invoke()
            |> Seq.map (sprintf  "%O")
            |> Seq.iter (fun line ->
                                let tracer=if line.Contains("not installed") then
                                                traceError
                                        else
                                                trace
                                tracer line)
        pipe.Streams.Error |> Seq.iter (traceError << sprintf "%O" )
</code>```

The pipeline is represented by the PowerShell class. The steps to construct it are :

Create a PowerShell pipeline with PowerShell.Create()

Create a ScriptBlock with the command you want to execute. You don't need a ScriptBlock for all commands. In this case, ScriptBlock contains the script I want to execute remotely.

Add what you want to execute. In my case, I want to run a single invoke-command command

Add parameters. In this case, it's -ComputerName myServer and -ScriptBlock ... with the block to execute.

Run the pipeline with PowerShell.Invoke()

Parse the results for possible warning messages that didn't make it to the Error stream

PowerShell errors are sent to the Error stream, which makes error handling easier.

Executing a command on the local machine can be a lot simpler:

```<code>let InvokeRemote command =
    let pipe=PowerShell.Create()
            .AddCommand(command)
    pipe.Invoke()
        |> Seq.map (sprintf  "%O")
        |> Seq.iter (fun line ->
                            let tracer=if line.Contains("not installed") then
                                            traceError
                                    else
                                            trace
                            tracer line)
    pipe.Streams.Error |> Seq.iter (traceError << sprintf "%O" )
</code>```

Body:
I am migrating MSBuild code to FAKE - and I am not able to execute powershell script from fake ,below is the code of MSBuild file to be written in FAKE :

<Target Name="VersionConfig">
    <Exec IgnoreExitCode="false" LogStandardErrorAsError="true" StandardErrorImportance="high" Command="powershell -File "$(BuildRoot)\DeployScripts\scripts\AdminScripts\VersionUpdateFile.ps1"  -path "$(BuildSolutionVersioningConfig)" -majorVersion "$(BuildNumberMajor)" -minor "$(BuildNumberMinor)" -build "$(BuildNumber)" -revision "$(BuildNumberRevision)""/>
</Target>

How to write this in FAKE , I'm new to FAKE and have not used F# much, so forgive me if this should be obvious.

If anyone can help , that would be really helpful.

Thank You .

Body:
You can create a Powershell pipeline in any .NET application with the classes of the System.Management.Automation namespace. You can use that pipeline to execute commands locally or on a remote machine.

The following target retrieves the list of processes and prints them. It's the F# equivalent of the documentation example for the PowerShell class:

Target "ProcTest" (fun _ ->
    PowerShell.Create()
            .AddCommand("get-process")
            .Invoke()
            |> Seq.map(fun result->(  result.Properties.["ProcessName"].Value,
                                      result.Properties.["ID"].Value))
            |> Seq.iter (fun (name,id)->printfn "%-24O %O" name id)
)

The is a quick & dirty module I use to execute commands (specifically chocolatey commands) on a remote server. The only thing you need to make it work on the local machine is to remove the ComputerName parameter:

#r "System.Management.Automation"

module MyPowershell =

    let InvokeRemote server command =
        let block = ScriptBlock.Create(command)
        let pipe=PowerShell.Create()
                .AddCommand("invoke-command")
        pipe.AddParameter("ComputerName", server)
            .AddParameter("ScriptBlock", block)
            .Invoke()
            |> Seq.map (sprintf  "%O")
            |> Seq.iter (fun line ->
                                let tracer=if line.Contains("not installed") then
                                                traceError
                                        else
                                                trace
                                tracer line)
        pipe.Streams.Error |> Seq.iter (traceError << sprintf "%O" )

The pipeline is represented by the PowerShell class. The steps to construct it are :

Create a PowerShell pipeline with PowerShell.Create()

Create a ScriptBlock with the command you want to execute. You don't need a ScriptBlock for all commands. In this case, ScriptBlock contains the script I want to execute remotely.

Add what you want to execute. In my case, I want to run a single invoke-command command

Add parameters. In this case, it's -ComputerName myServer and -ScriptBlock ... with the block to execute.

Run the pipeline with PowerShell.Invoke()

Parse the results for possible warning messages that didn't make it to the Error stream

PowerShell errors are sent to the Error stream, which makes error handling easier.

Executing a command on the local machine can be a lot simpler:

let InvokeRemote command =
    let pipe=PowerShell.Create()
            .AddCommand(command)
    pipe.Invoke()
        |> Seq.map (sprintf  "%O")
        |> Seq.iter (fun line ->
                            let tracer=if line.Contains("not installed") then
                                            traceError
                                    else
                                            trace
                            tracer line)
    pipe.Streams.Error |> Seq.iter (traceError << sprintf "%O" )


问:
Server is not pinging without domain name
I am having a server in a VPN network (cannot tell the network name) and I was able to ping it from my system through command prompt like below:

```<code>c:\> ping servername
</code>```

After a few days, it stopped pinging from my system and later I had to add the domain name to ping the server like below:

```<code>c:\> ping servername.na.ex.com
</code>```

(na and ex are just sample domain names).

I am not sure why the server stopped pinging just with server name. Any help / idea / inputs on this?

答: Probably when you connect on the first time the DNS Suffix (na.ex.com) was passed with the DHCP and now it doesn't that why you have to ping the complete name instead of the servername.</p>

Body:
I am having a server in a VPN network (cannot tell the network name) and I was able to ping it from my system through command prompt like below:

c:\> ping servername

After a few days, it stopped pinging from my system and later I had to add the domain name to ping the server like below:

c:\> ping servername.na.ex.com

(na and ex are just sample domain names).

I am not sure why the server stopped pinging just with server name. Any help / idea / inputs on this?


问:
git add, commit and push commands in one?
Is there any way to use these three commands in one?

```<code>git add .
git commit -a -m "commit" (do not need commit message either)
git push
</code>```

Sometimes I'm changing only one letter, CSS padding or something. Still, I have to write all three commands to push the changes. There are many projects where I'm only one pusher, so this command would be awesome!

答:
I did this .sh script for command </p>

```<code>#!/bin/sh
cd LOCALDIRECTORYNAME/
git config --global user.email "YOURMAILADDRESS"
git config --global user.name "YOURUSERNAME"
git init
git status
git add -A && git commit -m "MASSAGEFORCOMMITS"
git push origin master
</code>```

Body:
Is there any way to use these three commands in one?

git add .
git commit -a -m "commit" (do not need commit message either)
git push

Sometimes I'm changing only one letter, CSS padding or something. Still, I have to write all three commands to push the changes. There are many projects where I'm only one pusher, so this command would be awesome!

Body:
I did this .sh script for command

#!/bin/sh
cd LOCALDIRECTORYNAME/
git config --global user.email "YOURMAILADDRESS"
git config --global user.name "YOURUSERNAME"
git init
git status
git add -A && git commit -m "MASSAGEFORCOMMITS"
git push origin master


问:
join to all rows of a table even without values sql server
I have a date table that I use to determine week of the year (our year is not calendar year based right now.).  I have a union query that creates a table that I am going to use in a table valued function.  I can create the table in the union query but it only produces the 40 weeks that have actual data.  I need it to show the weeks regardless of whether data exists or not.

I have tried to left outer join on the week table but I still get only records where the week has data associated with it.

```<code>    left outer join [dbo].[LOOKUP_WEEK_NUMBER] w on
(p.[Program_Year_ID] = w.[Program_Year_Nbr]) and
(p.[Installation_Complete_Date] between w.[Week_Start] and w.[Week_End])
</code>```

LOOKUP_WEEK_NUMBER table has all the weeks of the year and a start and end date for each week.  The p table contains the project data.  What I am doing is bucketing the projects into weeks for reporting purposes.

Can anyone point me in the right direction?  Thanks in advance.

答:
change to a left join from your lookup table instead of to your lookup table, or use a right join to your lookup table.

```<code>from  [dbo].[LOOKUP_WEEK_NUMBER] w
  left join ... p
    on (p.[Program_Year_ID] = w.[Program_Year_Nbr])
   and (p.[Installation_Complete_Date] between w.[Week_Start] and w.[Week_End])
</code>```

Body:
I have a date table that I use to determine week of the year (our year is not calendar year based right now.).  I have a union query that creates a table that I am going to use in a table valued function.  I can create the table in the union query but it only produces the 40 weeks that have actual data.  I need it to show the weeks regardless of whether data exists or not.

I have tried to left outer join on the week table but I still get only records where the week has data associated with it.

    left outer join [dbo].[LOOKUP_WEEK_NUMBER] w on
(p.[Program_Year_ID] = w.[Program_Year_Nbr]) and
(p.[Installation_Complete_Date] between w.[Week_Start] and w.[Week_End])

LOOKUP_WEEK_NUMBER table has all the weeks of the year and a start and end date for each week.  The p table contains the project data.  What I am doing is bucketing the projects into weeks for reporting purposes.

Can anyone point me in the right direction?  Thanks in advance.

Body:
change to a left join from your lookup table instead of to your lookup table, or use a right join to your lookup table.

from  [dbo].[LOOKUP_WEEK_NUMBER] w
  left join ... p
    on (p.[Program_Year_ID] = w.[Program_Year_Nbr])
   and (p.[Installation_Complete_Date] between w.[Week_Start] and w.[Week_End])


问:
Script for working out exponential limit within a set range

In the image above column B is multiples of A1 and column C is C = C + B (working down the rows)

I worked out that in order for C for be 50 in 20 rows A1 has to be 0.2631579 but I'd like to be able to simplify that to a function that will return a list: list = exp(50, 20).

I'm not sure about the terminology of such a script so researching beforehand didn't really bring anything up sorry.

答:
Well based on your problem statement, we know that:

Bn=(n-1)×a; and Cn=(n-1)×n×a/2 (here a is the value for A1).

So we only have to solve a for C20=50. Or more genic: Cn=m. This is simply: a = 2×m/(n×(n-1)).

So the function is simply:

```<code>def find_threshold(m,n):
    return 2.0*m/(n*(n-1))
</code>```

For your sample input, the lower bound is:

```<code>>>> find_threshold(50,20)
0.2631578947368421
</code>```

If you plug in this value in the Excel sheet, you will obtain 50 (although there can be small rounding errors). Given we assume calculations on the numbers are done in constant time, this script works in constant time as well (O(1)) so it is quite fast (even if the row number, etc. would be huge).

Body:
Well based on your problem statement, we know that:

Bn=(n-1)×a; and Cn=(n-1)×n×a/2 (here a is the value for A1).

So we only have to solve a for C20=50. Or more genic: Cn=m. This is simply: a = 2×m/(n×(n-1)).

So the function is simply:

def find_threshold(m,n):
    return 2.0*m/(n*(n-1))

For your sample input, the lower bound is:

>>> find_threshold(50,20)
0.2631578947368421

If you plug in this value in the Excel sheet, you will obtain 50 (although there can be small rounding errors). Given we assume calculations on the numbers are done in constant time, this script works in constant time as well (O(1)) so it is quite fast (even if the row number, etc. would be huge).


问:
Mysql repeatable read-your-own-write behavior
If my isolation level is repeatable read, and I have a transaction with 3 statements:

SELECT * FROM table1 WHERE id = 1;       (Read the row)

UPDATE table1 SET ... WHERE id = 1;     (Modify the row)

SELECT * FROM table1 WHERE id = 1;       (Read the row again)

Will the last select statement see the change made by the second statement?

答: Yes, of course! All transactions always see its own changes, no matter which isolation level they have.</p>


问:
No values in POST method's parameters
I have REST web services POST method:

```<code>public string Post([FromBody]string value1 )
{
    return "a";
}
</code>```

I have placed breakpoint inside of it. I have sent POST:

```<code>localhost/RESTServer/api/Person/?value1=1
</code>```

I get null in value1 inside of Post method. What I do wrong?

答:
```<code>public string Post([FromBody]string value1 )
</code>```

should be

```<code>public string Post([QueryString]string value1 )
</code>```

(that is ... because your request is a GET and has no body... pure guess)

Title: No values in POST method's parameters

Body:
I have REST web services POST method:

public string Post([FromBody]string value1 )
{
    return "a";
}

I have placed breakpoint inside of it. I have sent POST:

localhost/RESTServer/api/Person/?value1=1

I get null in value1 inside of Post method. What I do wrong?

Body:
public string Post([FromBody]string value1 )

should be

public string Post([QueryString]string value1 )

(that is ... because your request is a GET and has no body... pure guess)


问:
On your very first program, which construct hooked you on programming?
To me it was the If statement, I'm psyched up, since then I believed that computers are very intelligent, or I can at least make it appear intelligent because of it.</p>

答: For Loops + Arrays did it for me. Once I realized that I could loop through an arbitrarily large set of things and do something to each of them, it all started to come together.</p>

OwnerDisplayName: Michael Buen

LastEditorDisplayName: Triptych

OwnerDisplayName: EndangeredMassa


问:
React-Navigation with Login Screen
I am trying to use react-navigation to create an initial LOGIN screen that has no tabbar and header, and once the user has been successfully authenticated will navigate to another screen called LISTRECORD which has a  tabbar, header and no back button option. Anyone has experience in this and can share?

In summary, what I'm trying to achieve with react-navigation is described below...

Screen 1: Login Screen (No Header & Tabbar)

Authenticated...

Screen 2: LISTRECORD (Header, Tabbar and No Back Button)

The tabbar contains other tabs too for navigation to Screen 3, Screen 4...

答:
Although what Manjeet suggests will work, it is not a good navigational structure.

What you should do is take a step back and handle everything on another level.

Top level navigator should be a stack navigator that renders a login screen.  Another screen within this top-most navigator should be your app's Main-Navigator.  When your login state is satisfied, you reset the main stack to just the Main-Navigator.

The reason for this structure is:

A-  What if you need to add on-boarding information before the Login the future?

B-  What if you need to navigate outside of the Main-Navigation environment (eg: your main nav is tabs and you want a non-tab view)?

If your top-most navigator is a Stack-Navigator that presents Login screens and other Navigators, then your app's navigation structure can properly scale.

I do not believe the conditional rendering of a login screen or stack navigator, as suggested above, is a good idea....trust me...I've gone down that road.

ContentLicense: CC BY-SA 4.0

Title: React-Navigation with Login Screen


问:
How to set date field in join query ruby on rails
I have below query in which I want to check the date.

The actual working query is like:

```<code>Quiz.joins(lesson_plan: [private_class: [private_school:
:joined_private_schools]]).where(joined_private_schools: {user_id: 73},
lesson_plans: {is_publish: true})
</code>```

But when I try to set date field it says:

query:

```<code>Quiz.joins(lesson_plan: [private_class: [private_school:
:joined_private_schools]]).where(joined_private_schools: {user_id: 73},
lesson_plans: {"is_publish = ?, available_due_date_time > ?", true,
Time.zone.now})
</code>```

Error:

```<code>SyntaxError: (irb):82: syntax error, unexpected ',', expecting =>
 available_due_date_time > ?", true, Time.zone.now})
                              ^
(irb):82: Can't assign to true
able_due_date_time > ?", true, Time.zone.now})
                              ^
(irb):82: syntax error, unexpected '}', expecting &. or :: or '[' or '.'
ime > ?", true, Time.zone.now})
                              ^
</code>```

Update:

I tried:

query:

```<code>Quiz.joins(lesson_plan: [private_class: [private_school:
:joined_private_schools]]).where(joined_private_schools: {user_id: 73},
lesson_plans: {"is_publish = ? AND available_due_date_time > ?", true,
Time.zone.now})
</code>```

But still the error is same.

How to set date in these type of query? Any source for learning are also recommended.

答:
You can pass an array to the .where clause as mentioned in the ActiveRecord documentation.

If an array is passed, then the first element of the array is treated
  as a template, and the remaining elements are inserted into the
  template to generate the condition.

Plus, you can use the table name in the joined query.

If the relation is the result of a join, you may create a condition
  which uses any of the tables in the join. For string and array
  conditions, use the table name in the condition.

The solution:

```<code>Quiz.joins(lesson_plan: [private_class: [private_school: :joined_private_schools]])
    .where(joined_private_schools: { user_id: 73 })
    .where(["lesson_plans.is_publish = ? AND lesson_plans.available_due_date_time > ?", true, Time.zone.now])
</code>```

Body:
I have below query in which I want to check the date.

The actual working query is like:

Quiz.joins(lesson_plan: [private_class: [private_school:
:joined_private_schools]]).where(joined_private_schools: {user_id: 73},
lesson_plans: {is_publish: true})

But when I try to set date field it says:

query:

Quiz.joins(lesson_plan: [private_class: [private_school:
:joined_private_schools]]).where(joined_private_schools: {user_id: 73},
lesson_plans: {"is_publish = ?, available_due_date_time > ?", true,
Time.zone.now})

Error:

SyntaxError: (irb):82: syntax error, unexpected ',', expecting =>
 available_due_date_time > ?", true, Time.zone.now})
                              ^
(irb):82: Can't assign to true
able_due_date_time > ?", true, Time.zone.now})
                              ^
(irb):82: syntax error, unexpected '}', expecting &. or :: or '[' or '.'
ime > ?", true, Time.zone.now})
                              ^

Update:

I tried:

query:

Quiz.joins(lesson_plan: [private_class: [private_school:
:joined_private_schools]]).where(joined_private_schools: {user_id: 73},
lesson_plans: {"is_publish = ? AND available_due_date_time > ?", true,
Time.zone.now})

But still the error is same.

How to set date in these type of query? Any source for learning are also recommended.

Body:
You can pass an array to the .where clause as mentioned in the ActiveRecord documentation.

If an array is passed, then the first element of the array is treated
  as a template, and the remaining elements are inserted into the
  template to generate the condition.

Plus, you can use the table name in the joined query.

If the relation is the result of a join, you may create a condition
  which uses any of the tables in the join. For string and array
  conditions, use the table name in the condition.

The solution:

Quiz.joins(lesson_plan: [private_class: [private_school: :joined_private_schools]])
    .where(joined_private_schools: { user_id: 73 })
    .where(["lesson_plans.is_publish = ? AND lesson_plans.available_due_date_time > ?", true, Time.zone.now])


问:
Get first key in a (possibly) associative array?
What's the best way to determine the first key in a possibly associative array? My first thought it to just foreach the array and then immediately breaking it, like this:

```<code>foreach ($an_array as $key => $val) break;
</code>```

Thus having $key contain the first key, but this seems inefficient. Does anyone have a better solution?

答:
This is the easier way I had ever found. Fast and only two lines of code :-D</p>

```<code>$keys = array_keys($array);
echo $array[$keys[0]];
</code>```

Body:
What's the best way to determine the first key in a possibly associative array? My first thought it to just foreach the array and then immediately breaking it, like this:

foreach ($an_array as $key => $val) break;

Thus having $key contain the first key, but this seems inefficient. Does anyone have a better solution?

Body:
This is the easier way I had ever found. Fast and only two lines of code :-D

$keys = array_keys($array);
echo $array[$keys[0]];


问:
Serializiation with Protocol Buffers in a Schemaless Database
We're using MySQL to store schemaless data (see: Using a Relational Database for Schemaless Data for the solution inspired by how FriendFeed uses MySQL to store schemaless data).

One big table holds all entities for our application:

```<code>CREATE TABLE entities (
  added_id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY
, id BINARY(16) NOT NULL
, body MEDIUMBLOB
, UNIQUE KEY (id)
) ENGINE=InnoDB ;
</code>```

A few details:

The only required property of stored entities is id, a 16-byte UUID. The rest of the entity is opaque to the database. We can change the "schema" simply by storing new properties in the body.

The added_id column is present because InnoDB stores data rows physically in primary key order. The AUTO_INCREMENT primary key ensures new entities are written sequentially on disk after old entities, which helps for read/write locality (new entities are read more frequently than old entities).

Our database stores our schemaless data in the body. <- This is the topic of this question.

Plenty of other interesting details, like "reaching into" the body data to build asynchronous materialized views (indexes are just tables that are built offline), but they're not relevant to the current discussion...

How should we be serializing the structured data (key-value pairs) in the body?

JSON or BSON would be simple, since the field names are repeated for each row. This gives it an advantage in flexibility but also a big disadvantage in space efficiency (a per-row overhead for field names in the serialized data). We're trying to keep things in memory, and minimizing both memory and network footprint is important here. The more records we can fit in the same space, the faster our queries will be. We prefer relatively long, descriptive field names, and shortening them to make my database faster is wrong!

In the end, JSON/BSON is unworkable for our purposes, unless we get more complex and map small keys to more descriptive keys in the application driver that talks to the database. Which got us thinking...

Although our database is schemaless, in reality: 1) there aren't too many different kinds of entities, 2) versions of the same kind of entity don't change often, and 3) when they do change, it's usually just to add another field. JSON/BSON have no native support for versioning.

Protocol Buffers and Thrift are much more sophisticated when it comes to versioning and data definition changes. Both Thrift and Protocol Buffers are great candidates for serializing data into databases, and Thrift is designed so that the encoding format is extensible.

Protocol Buffers look like a great choice for serializing data in a schemaless database.

CouchDB and MongoDB (the two most popular schemaless databases?) use JSON and BSON respectively, but we can't find anything about using something more advanced, like Protocol Buffers, as a serialization format for storing schemaless data. There are products that store a specific language's version of objects (ie. storing Java's Externalizable objects in a datagrid, or doing NoSQL with MySQL in Ruby), but these are a pain (try accessing them from other platforms, or even from MySQL itself, and forget about versioning).

Is anyone storing the more interoperable Protocol Buffers in their database, or some other advanced serialization format in their schemaless database? This is a question of whether there are other options besides straightforward per-row serialization of JSON/BSON/XML, or serializing a specific language's objects. Is it even feasible? Are we missing something? sorry for the stream of consciousness style narrative!

答:
I'll refer you to an answer I put forward a few months back on a sort-of similar topic. We use MySQL and a custom text format which proved faster than XML or JSON formats:

What scalability problems have you encountered using a NoSQL data store?

Working well for us. Didn't try Protocol Buffers though.

Body:
We're using MySQL to store schemaless data (see: Using a Relational Database for Schemaless Data for the solution inspired by how FriendFeed uses MySQL to store schemaless data).

One big table holds all entities for our application:

CREATE TABLE entities (
  added_id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY
, id BINARY(16) NOT NULL
, body MEDIUMBLOB
, UNIQUE KEY (id)
) ENGINE=InnoDB ;

A few details:

The only required property of stored entities is id, a 16-byte UUID. The rest of the entity is opaque to the database. We can change the "schema" simply by storing new properties in the body.

The added_id column is present because InnoDB stores data rows physically in primary key order. The AUTO_INCREMENT primary key ensures new entities are written sequentially on disk after old entities, which helps for read/write locality (new entities are read more frequently than old entities).

Our database stores our schemaless data in the body. <- This is the topic of this question.

Plenty of other interesting details, like "reaching into" the body data to build asynchronous materialized views (indexes are just tables that are built offline), but they're not relevant to the current discussion...

How should we be serializing the structured data (key-value pairs) in the body?

JSON or BSON would be simple, since the field names are repeated for each row. This gives it an advantage in flexibility but also a big disadvantage in space efficiency (a per-row overhead for field names in the serialized data). We're trying to keep things in memory, and minimizing both memory and network footprint is important here. The more records we can fit in the same space, the faster our queries will be. We prefer relatively long, descriptive field names, and shortening them to make my database faster is wrong!

In the end, JSON/BSON is unworkable for our purposes, unless we get more complex and map small keys to more descriptive keys in the application driver that talks to the database. Which got us thinking...

Although our database is schemaless, in reality: 1) there aren't too many different kinds of entities, 2) versions of the same kind of entity don't change often, and 3) when they do change, it's usually just to add another field. JSON/BSON have no native support for versioning.

Protocol Buffers and Thrift are much more sophisticated when it comes to versioning and data definition changes. Both Thrift and Protocol Buffers are great candidates for serializing data into databases, and Thrift is designed so that the encoding format is extensible.

Protocol Buffers look like a great choice for serializing data in a schemaless database.

CouchDB and MongoDB (the two most popular schemaless databases?) use JSON and BSON respectively, but we can't find anything about using something more advanced, like Protocol Buffers, as a serialization format for storing schemaless data. There are products that store a specific language's version of objects (ie. storing Java's Externalizable objects in a datagrid, or doing NoSQL with MySQL in Ruby), but these are a pain (try accessing them from other platforms, or even from MySQL itself, and forget about versioning).

Is anyone storing the more interoperable Protocol Buffers in their database, or some other advanced serialization format in their schemaless database? This is a question of whether there are other options besides straightforward per-row serialization of JSON/BSON/XML, or serializing a specific language's objects. Is it even feasible? Are we missing something? sorry for the stream of consciousness style narrative!


问:
How to load one page from another on select of option from drop down?
I have a drop down list on click of the option I want to redirect to another page in same tab according to type selected.

I want to redirect to, like if user selects ssgt then need to go to ssgt.php if selects tsgt then tsgt.php and like that for msgt.

Is it can be done with link inside? I tried but did not work.

```<code><!doctype html>
<html>
<head>
   <meta charset="utf-8">
   <title>MCQ Questions</title>
</head>
<body>
   <form method="post" enctype="multipart/form-data">
      Select rank :
      <select name="type" id="type" onchange="this.form.submit()">
         <option value="1">SSgt</option>
         <option value="2">TSgt</option>
         <option value="3">MSgt</option>
      </select>
      <br><br>
      <?php
         if(isset($_POST['type'])) {
            if(strcmp($_POST['type'],"1") == 0) {
            }
         }
      ?>
   </form>
</body>
</html>
</code>```

Please help.. Thank you.

EDIT:

```<code>   <!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>MCQ Questions</title>

</head>
<body>

<form method="post" action="mcq.php" enctype="multipart/form-data">
    <?php
    if(isset($_POST['type']))
    {

        if(strcmp($_POST['type'],"1") == 0)
        {
            header("Location: ssgt.php");
        }
        elseif(strcmp($_POST['type'],"2" == 0))
        {
            header("Location: tsgt.php");
        }
        elseif(strcmp($_POST['type'],"3" == 0))
        {
            header("Location: msgt.php");
        }
    }

    ?>

    <h2>Lets add a question, Select a rank for which you want to add a question.</h2>
<br><br>
Select rank :

<select name="type" id="type"  onchange="this.form.submit()">

    <option value="1">SSgt</option>
<option value="2">TSgt</option>
<option value="3">MSgt</option>
</select>

</form>
</body>
</html>
</code>```

I tried this way so for ssgt, and tsgt respective pages are getting open but for msgt the page of tsgt.php is getting open.

答:
In your code, in line
<option value="1">SSgt</option>
the "value" attribute will be submitted. You shuould submit name of the page you want to redirect. So change all your options as
 <option value="SSgt">SSgt</option>

your final code will be

```<code><?php
if (isset($_POST['type'])) {
    $location = strtolower($_POST['type']) . '.php'; // Will convert SSgt to ssgt.php
    header("Location: " . $location);
}
?>
<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>MCQ Questions</title>
    </head>
    <body>
        <form method="post" enctype="multipart/form-data">
            Select rank :
            <select name="type" id="type" onchange="this.form.submit()">
                <option value="SSgt">SSgt</option>
                <option value="TSgt">TSgt</option>
                <option value="MSgt">MSgt</option>
            </select>
            <br><br>
        </form>
    </body>
</html>
</code>```

Body:
I have a drop down list on click of the option I want to redirect to another page in same tab according to type selected.

I want to redirect to, like if user selects ssgt then need to go to ssgt.php if selects tsgt then tsgt.php and like that for msgt.

Is it can be done with link inside? I tried but did not work.

<!doctype html>

   <meta charset="utf-8">
   <title>MCQ Questions</title>

   <form method="post" enctype="multipart/form-data">
      Select rank :
      <select name="type" id="type" onchange="this.form.submit()">
         <option value="1">SSgt</option>
         <option value="2">TSgt</option>
         <option value="3">MSgt</option>
      </select>

      <?php
         if(isset($_POST['type'])) {
            if(strcmp($_POST['type'],"1") == 0) {
            }
         }
      ?>
   </form>

Please help.. Thank you.

EDIT:

   <!doctype html>

<meta charset="utf-8">
<title>MCQ Questions</title>

<form method="post" action="mcq.php" enctype="multipart/form-data">
    <?php
    if(isset($_POST['type']))
    {

        if(strcmp($_POST['type'],"1") == 0)
        {
            header("Location: ssgt.php");
        }
        elseif(strcmp($_POST['type'],"2" == 0))
        {
            header("Location: tsgt.php");
        }
        elseif(strcmp($_POST['type'],"3" == 0))
        {
            header("Location: msgt.php");
        }
    }

    ?>

Lets add a question, Select a rank for which you want to add a question.

Select rank :

<select name="type" id="type"  onchange="this.form.submit()">

    <option value="1">SSgt</option>
<option value="2">TSgt</option>
<option value="3">MSgt</option>
</select>

</form>

I tried this way so for ssgt, and tsgt respective pages are getting open but for msgt the page of tsgt.php is getting open.

Body:
In your code, in line
<option value="1">SSgt</option>
the "value" attribute will be submitted. You shuould submit name of the page you want to redirect. So change all your options as
 <option value="SSgt">SSgt</option>

your final code will be

<?php
if (isset($_POST['type'])) {
    $location = strtolower($_POST['type']) . '.php'; // Will convert SSgt to ssgt.php
    header("Location: " . $location);
}
?>
<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>MCQ Questions</title>
    </head>
    <body>
        <form method="post" enctype="multipart/form-data">
            Select rank :
            <select name="type" id="type" onchange="this.form.submit()">
                <option value="SSgt">SSgt</option>
                <option value="TSgt">TSgt</option>
                <option value="MSgt">MSgt</option>
            </select>
            <br><br>
        </form>
    </body>
</html>


问:
I have two tables Table1 and Table2 :I want to swap name column value From Table1 to Table2 and Table2 to Table1
[Below are two tables Table1 and Table2][1]

Table1:Column names id,name
Table2:Column names id,name

After the swap ,the name column data of Table1 will reflect in Table2 and name of Table2 will reflect in Table1.

I tried to resolve the issue using below query:

```<code>update table1 t set t.name=replace(t.name,(select name from T1 where T1.id=t.id),(select name from T2 where T2.id = t.id));
update table2 t set t.name=replace(t.name,(select name from T2 where T2.id=t.id),(select name from T1 where T1.id = t.id));
</code>```

But,it is not giving correct result.

答:
A little modification in your query and it worked.

create table temp1 as select * from table1;

update table1 set name = (select name from table2 where table2.id = table1.id);

update table2 set name = (select name from temp1 where temp1.id = table2.id);

Thanks,
Vinita Singh

Body:
[Below are two tables Table1 and Table2][1]

Table1:Column names id,name
Table2:Column names id,name

After the swap ,the name column data of Table1 will reflect in Table2 and name of Table2 will reflect in Table1.

I tried to resolve the issue using below query:

update table1 t set t.name=replace(t.name,(select name from T1 where T1.id=t.id),(select name from T2 where T2.id = t.id));
update table2 t set t.name=replace(t.name,(select name from T2 where T2.id=t.id),(select name from T1 where T1.id = t.id));

But,it is not giving correct result.


问:
C# Inheritance misconception
Let's say that we have 2 classes. The first one is Person

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

    namespace People
    {
        class Person
        {
            public string FirstName { get; set; }
            public string LastName { get; set; }
        }
    }
</code>```

The second one is Teacher

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

namespace People
{
    class Teacher:Person
    {
        public string Position { get; set; }
    }
}
</code>```

And I want to make a teacher object using this syntax Person teacher = new Teacher(); When I make it and I try to refer to the Position property, I can't... Why does this happen? I can instead use this syntax Person teacher = new Teacher() {Position="boss" }; but even though, after that I can't refer to the teacher position using "teacher.Position".

答:
Doing this:

```<code>Person teacher = new Teacher();
</code>```

You create object of type Teacher but your reference type(teacher) is of type Person - it means that using this reference you can access only all members of type Person.

To access Teacher members you should either create reference of type Teacher:

```<code>Teacher teacher = new Teacher();
var position = teacher.Position;
</code>```

or you should cast your reference to Teacher type:

```<code>Person teacher = new Teacher();
var position = ((Teacher)teacher).Position;
</code>```

Title: C# Inheritance misconception

Body:
Let's say that we have 2 classes. The first one is Person

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

    namespace People
    {
        class Person
        {
            public string FirstName { get; set; }
            public string LastName { get; set; }
        }
    }

The second one is Teacher

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

namespace People
{
    class Teacher:Person
    {
        public string Position { get; set; }
    }
}

And I want to make a teacher object using this syntax Person teacher = new Teacher(); When I make it and I try to refer to the Position property, I can't... Why does this happen? I can instead use this syntax Person teacher = new Teacher() {Position="boss" }; but even though, after that I can't refer to the teacher position using "teacher.Position".

Body:
Doing this:

Person teacher = new Teacher();

You create object of type Teacher but your reference type(teacher) is of type Person - it means that using this reference you can access only all members of type Person.

To access Teacher members you should either create reference of type Teacher:

Teacher teacher = new Teacher();
var position = teacher.Position;

or you should cast your reference to Teacher type:

Person teacher = new Teacher();
var position = ((Teacher)teacher).Position;


问:
Changing the prefab an object is associated with in Unity
I want to change the prefab my object playerPawn is associated with. I tried to do it with this code:

```<code>int i = 0;

PrefabUtility.DisconnectPrefabInstance(this.playerPawn);
PrefabUtility.ConnectGameObjectToPrefab (this.playerPawn, this.playerPawnPrefabs [i]);

Debug.Log(this.playerPawnPrefabs[i]);

PrefabUtility.ResetToPrefabState(this.playerPawn);
</code>```

However, the last line is throwing this error:

MissingReferenceException: The object of type 'GameObject' has been
  destroyed but you are still trying to access it. Your script should
  either check if it is null or you should not destroy the object.

The Debug.Log() showed me that this.playerPawnPrefabs[i] contains the GameObject I'm expecting, so I don't understand where that error comes from.

答:
Maybe you can try to reassign the return of ConnectGameObjectToPrefab method to your playerPawn object:

```<code>this.playerPawn = PrefabUtility.ConnectGameObjectToPrefab (this.playerPawn, this.playerPawnPrefabs [i]);
</code>```

Then you can call ResetToPrefabState method.

Body:
I want to change the prefab my object playerPawn is associated with. I tried to do it with this code:

int i = 0;

PrefabUtility.DisconnectPrefabInstance(this.playerPawn);
PrefabUtility.ConnectGameObjectToPrefab (this.playerPawn, this.playerPawnPrefabs [i]);

Debug.Log(this.playerPawnPrefabs[i]);

PrefabUtility.ResetToPrefabState(this.playerPawn);

However, the last line is throwing this error:

MissingReferenceException: The object of type 'GameObject' has been
  destroyed but you are still trying to access it. Your script should
  either check if it is null or you should not destroy the object.

The Debug.Log() showed me that this.playerPawnPrefabs[i] contains the GameObject I'm expecting, so I don't understand where that error comes from.

Body:
Maybe you can try to reassign the return of ConnectGameObjectToPrefab method to your playerPawn object:

this.playerPawn = PrefabUtility.ConnectGameObjectToPrefab (this.playerPawn, this.playerPawnPrefabs [i]);

Then you can call ResetToPrefabState method.


问:
How to apply different policies to service and proxy service?
I have a mule service, named IS, deployed on mule runtime and proxied on API gateway. I'd like to set up different policies to the IS and its proxy service. How can I do it?

My environment:

Mule runtime: 3.7.4

Mule API gateway: 2.1.1

答:
We can create endpoint with a proxy or select Basic endpoint if you create your API outside API Manager, for example, you created the API using Mule ESB. You don’t need a proxy in this case. So policies will be applied to API. For more details go through the link.
https://docs.mulesoft.com/api-manager/setting-up-an-api-proxy</p>


问:
HIbernate @DynamicUpdate not working with JPA Entitymanager
I am trying to update an entity, but when I call EntityManager.merge(), it is updating all the columns of the table. But my requirement is to update only those column which are modified. I searched on the Internet and stack overflow and the solution I got is to use @SelectBeforeUpdate and @DynamicUpdate. I tried with these annotation, but its not working. When I tried to update some specific column, all other columns are also updated.

Entity

```<code>@Entity
@SelectBeforeUpdate(value=true)
@DynamicUpdate(value=true)
@DynamicInsert(value=true)
@Table(name="Employee")
public class Employee implements Serializable{

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id")
    private int ID;

    @Column(name="_first_name")
    private String firstName;

    @Column(name="_last_name")
    private String lastName;

    @Column(name="_contact")
    private Long contact;

    @Column(name="_email")
    private String email;

    @Column(name="_date_birth")
    private Date dob;

    @Column(name="_joining_date")
    private Date doj;

    @Column(name="_salary")
    private Integer Salary;
}
</code>```

DAO

```<code>    logger.debug("Update method dao :");
    logger.debug(manager.getTransaction());
    Employee emp = form.getEmployee();
    logger.debug(emp);
    manager.find(Employee.class,emp.getID());
    manager.merge(emp);
</code>```

In debugging it is updating all the columns

答:
In my knowledge it is not possible in easy way, I faced this problem a years ago, the solution is accurate, but the only problem is performance(I doubt).
First of all you are doing little mistake in your dao part you have to use new Employee object when the EntityManager find any by ID i.e.

```<code>Employee employee = manager.find(Employee.class,emp.getID());
</code>```

And remember you have to check and merge this employee object not emp.

Now the solution is to check both the Employee object's (i.e. emp and employee) field/property value with each other and if employee field value does not matched then change its field value and the merge it. You can use java reflection for this here is the code

```<code>logger.debug("Update method dao :");
Employee emp = form.getEmployee();
Employee employee = manager.find(Employee.class, emp.getID());

Field[] empField = emp.getClass().getDeclaredFields();
Field[] employeeField = employee.getClass().getDeclaredFields();

for (int i = 0; i < empField.length; i++) {
 empField[i].setAccessible(true);
 employeeField[i].setAccessible(true);

 try {
  if (empField[i].get(emp) != null && !empField[i].get(emp).equals(employeeField[i].get(employee))) {
   employeeField[i].set(employee, empField[i].get(emp));
  }
 } catch (IllegalArgumentException e) {
  e.printStackTrace();
 } catch (IllegalAccessException e) {
  e.printStackTrace();
 }

}

employee.setUser(form.getUser());
manager.merge(employee);
manager.flush();
}
</code>```

Hope this will help!

Body:
I am trying to update an entity, but when I call EntityManager.merge(), it is updating all the columns of the table. But my requirement is to update only those column which are modified. I searched on the Internet and stack overflow and the solution I got is to use @SelectBeforeUpdate and @DynamicUpdate. I tried with these annotation, but its not working. When I tried to update some specific column, all other columns are also updated.

Entity

@Entity
@SelectBeforeUpdate(value=true)
@DynamicUpdate(value=true)
@DynamicInsert(value=true)
@Table(name="Employee")
public class Employee implements Serializable{

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id")
    private int ID;

    @Column(name="_first_name")
    private String firstName;

    @Column(name="_last_name")
    private String lastName;

    @Column(name="_contact")
    private Long contact;

    @Column(name="_email")
    private String email;

    @Column(name="_date_birth")
    private Date dob;

    @Column(name="_joining_date")
    private Date doj;

    @Column(name="_salary")
    private Integer Salary;
}

DAO

    logger.debug("Update method dao :");
    logger.debug(manager.getTransaction());
    Employee emp = form.getEmployee();
    logger.debug(emp);
    manager.find(Employee.class,emp.getID());
    manager.merge(emp);

In debugging it is updating all the columns

Body:
In my knowledge it is not possible in easy way, I faced this problem a years ago, the solution is accurate, but the only problem is performance(I doubt).
First of all you are doing little mistake in your dao part you have to use new Employee object when the EntityManager find any by ID i.e.

Employee employee = manager.find(Employee.class,emp.getID());

And remember you have to check and merge this employee object not emp.

Now the solution is to check both the Employee object's (i.e. emp and employee) field/property value with each other and if employee field value does not matched then change its field value and the merge it. You can use java reflection for this here is the code

logger.debug("Update method dao :");
Employee emp = form.getEmployee();
Employee employee = manager.find(Employee.class, emp.getID());

Field[] empField = emp.getClass().getDeclaredFields();
Field[] employeeField = employee.getClass().getDeclaredFields();

for (int i = 0; i < empField.length; i++) {
 empField[i].setAccessible(true);
 employeeField[i].setAccessible(true);

 try {
  if (empField[i].get(emp) != null && !empField[i].get(emp).equals(employeeField[i].get(employee))) {
   employeeField[i].set(employee, empField[i].get(emp));
  }
 } catch (IllegalArgumentException e) {
  e.printStackTrace();
 } catch (IllegalAccessException e) {
  e.printStackTrace();
 }

}

employee.setUser(form.getUser());
manager.merge(employee);
manager.flush();
}

Hope this will help!


问:
Relation of c# name space and file
How is a C# namespace related to the physical representation of the program in files and folders?

When one uses a using directive, e.g.:

```<code>using MyNameSpace;
</code>```

Where does does the C# compiler look for that namespace? Is there some documentation which covers the relationship of logical entities like namespaces and classes with their physical representations?

My .csproj file just contains

```<code><Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp1.1</TargetFramework>
  </PropertyGroup>

</Project>
</code>```

Nevertheless it seems to compile all .cs files in the project. I am using Visual Studio Code and want to understand the magic that is going on.

答:
"Where does does the C# compiler look for that namespace?"
In every Reference added to the project. A lot of them are added Automatically. Keep in mind that using merely shields you from having to write the fully qualified name for every class in that namespace. It enabeles you to write "myClass1" instead of "MyNameSpace.myClass1" (Every. Single. Time). You may still ahve to write fully qualified names sometimes (like when you use more then one namespace with a timer class - there are 3 in .NET).

"Is there some documentation which covers the relationship of logical entities like namespaces and classes with their physical representations?"
You put some MSIL compiled code into your projeect reference. Then you can use all the namespaces defined in that compliation and all teh classes defined in those namespaces. Note that both .NET dll and .NET executeables are valid References. Internally a .NET execudetable is a .NET dll, with a manifest, bootstrap code and a "entry point" into the code.

Title: Relation of c# name space and file

Body:
How is a C# namespace related to the physical representation of the program in files and folders?

When one uses a using directive, e.g.:

using MyNameSpace;

Where does does the C# compiler look for that namespace? Is there some documentation which covers the relationship of logical entities like namespaces and classes with their physical representations?

My .csproj file just contains

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp1.1</TargetFramework>
  </PropertyGroup>

</Project>

Nevertheless it seems to compile all .cs files in the project. I am using Visual Studio Code and want to understand the magic that is going on.


问:
Hide element based on attribute value jquery
How can I hide child div based on the attribute value of parent div. I have following markup:

```<code><div class="offerContainer">
    <div class="Offers" producttype="CIP">
        <div class="buttons_wrap"></div>
    </div>
    <div class="Offers" producttype="P">
        <div class="buttons_wrap"></div>
    </div>
    <div class="Offers" producttype="CIP">
        <div class="buttons_wrap"></div>
    </div>
</div>
</code>```

And I want to hide buttons_wrap only when  atrribute value of producttype is "CIP".

Something like:

```<code>if($(obj).parents(".offersContainer").find('.Offers').attr('producttype').value == "CIP")
    $('.buttons_wrap').hide();
</code>```

答:
```<code>$('.buttons_wrap').each(function(){
    if($(this).parents('.Offers').attr('producttype') == "CIP"){
        $(this).hide();
    }
});
</code>```

JSFIDDLE Example:

https://jsfiddle.net/Panomosh/kL11m73L/

Body:
How can I hide child div based on the attribute value of parent div. I have following markup:

And I want to hide buttons_wrap only when  atrribute value of producttype is "CIP".

Something like:

if($(obj).parents(".offersContainer").find('.Offers').attr('producttype').value == "CIP")
    $('.buttons_wrap').hide();

Body:
$('.buttons_wrap').each(function(){
    if($(this).parents('.Offers').attr('producttype') == "CIP"){
        $(this).hide();
    }
});

JSFIDDLE Example:

https://jsfiddle.net/Panomosh/kL11m73L/


问:
Does the word "Webservice" imply a specific format?
When I talk to an developer from the Microsoft ASP.NET world and he uses the word "Webservice", does that word in every case imply a specific data format (XML? SOAP?)?

Or is it just anything you can call via http(s)?

答:
Personally I mean any HTTPHandler!

That means under ASP.NET, a page is a webservice that returns HTML.

WCF extends that concept, because by default, WCF service requests in ASP.NET are processed by Modules not Handlers.

So really any web request is a service.

Typically though ASP.NET developers will be refering to SOAP unless they prefix i.e. WCF Webservices,

OwnerDisplayName: BlaM

LastEditorDisplayName: Rich B


问:
getting selected row through AbstractTableModel
Is it possible to get the selected row index from my table model?

My object already knows about the table model. Instead of passing a reference to the table it self can i get the selected index using the model?

答:
You can get the index from the bound Table and then you can use it to manipulate the table model. For example, if I want to delete a Row in my table model:</p>

```<code>myTableModel.removeValueAt(myTable.getSelectedRow());
</code>```

Body:
You can get the index from the bound Table and then you can use it to manipulate the table model. For example, if I want to delete a Row in my table model:

myTableModel.removeValueAt(myTable.getSelectedRow());


问:
how to pass array of model from one actvtiy to another in android
```<code>public class DataModel implements Serializable, Parcelable {

    /**  */
    private static final long serialVersionUID = 4861597073026532544L;

    private String cid;
    private String name;

    /**
     * @return the cid
     */
    public String getCid() {
        return cid;
    }

    /**
     * @param cid
     *            the cid to set
     */
    public void setCid(String cid) {
        this.cid = cid;
    }

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name
     *            the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    public DataModel(Parcel in) {
        super();
        readFromParcel(in);
    }

    public static final Parcelable.Creator<DataModel> CREATOR = new Parcelable.Creator<DataModel>() {
        public DataModel createFromParcel(Parcel in) {
            return new DataModel(in);
        }

        public DataModel[] newArray(int size) {

            return new DataModel[size];
        }

    };

    public void readFromParcel(Parcel in) {
        String[] result = new String[23];
        in.readStringArray(result);

        this.cid = result[0];
        this.name = result[1];

    }

    public int describeContents() {
        return 0;
    }

    public void writeToParcel(Parcel dest, int flags) {
        dest.writeStringArray(new String[] { this.cid,
                this.name});

    }}
</code>```

this is my Datamodel:

```<code>public class MainActivity extends AppCompatActivity {

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

        DataModel _modeDataModel=new DataModel(MainActivity.this);
        _modeDataModel.setCid("1");
        _modeDataModel.setName("Anil");

        Bundle bundle = new Bundle();
        bundle.putParcelableArrayList("channel",(ArrayList<DataModel>) model);
        Intent intent = new Intent(MainActivity.this,SecondActivity.class);
        intent.putExtras(bundle);
        startActivity(intent);

    }

}
</code>```

main activtiy

```<code>public class SecondActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Bundle getBundle = this.getIntent().getExtras();
        List<DataModel> channelsList = getBundle.getParcelableArrayList("channel");
    }
}
</code>```

second actvity

i want to pass data between one activity to another activity from One List but i am unable to set value  model also unable to send one activity to another there is compile time Error is coming please suggest me where am doing mistake and ho to send data from one activity to another ,

答:
To send in first activity:

```<code>    Bundle bundle = new Bundle();
    bundle.putParcelable("channel", _modeDataModel);
    Intent intent = new Intent(MainActivity.this,SecondActivity.class);
    intent.putExtras(bundle);
    startActivity(intent);
</code>```

To retrieve in second activity:

```<code>    Bundle getBundle = this.getIntent().getExtras();
    DataModel model = getBundle.getParcelable("channel");
</code>```

Body:
public class DataModel implements Serializable, Parcelable {

    /**  */
    private static final long serialVersionUID = 4861597073026532544L;

    private String cid;
    private String name;

    /**
     * @return the cid
     */
    public String getCid() {
        return cid;
    }

    /**
     * @param cid
     *            the cid to set
     */
    public void setCid(String cid) {
        this.cid = cid;
    }

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name
     *            the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    public DataModel(Parcel in) {
        super();
        readFromParcel(in);
    }

    public static final Parcelable.Creator<DataModel> CREATOR = new Parcelable.Creator<DataModel>() {
        public DataModel createFromParcel(Parcel in) {
            return new DataModel(in);
        }

        public DataModel[] newArray(int size) {

            return new DataModel[size];
        }

    };

    public void readFromParcel(Parcel in) {
        String[] result = new String[23];
        in.readStringArray(result);

        this.cid = result[0];
        this.name = result[1];

    }

    public int describeContents() {
        return 0;
    }

    public void writeToParcel(Parcel dest, int flags) {
        dest.writeStringArray(new String[] { this.cid,
                this.name});

    }}

this is my Datamodel:

public class MainActivity extends AppCompatActivity {

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

        DataModel _modeDataModel=new DataModel(MainActivity.this);
        _modeDataModel.setCid("1");
        _modeDataModel.setName("Anil");

        Bundle bundle = new Bundle();
        bundle.putParcelableArrayList("channel",(ArrayList<DataModel>) model);
        Intent intent = new Intent(MainActivity.this,SecondActivity.class);
        intent.putExtras(bundle);
        startActivity(intent);

    }

}

main activtiy

public class SecondActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Bundle getBundle = this.getIntent().getExtras();
        List<DataModel> channelsList = getBundle.getParcelableArrayList("channel");
    }
}

second actvity

i want to pass data between one activity to another activity from One List but i am unable to set value  model also unable to send one activity to another there is compile time Error is coming please suggest me where am doing mistake and ho to send data from one activity to another ,

Body:
To send in first activity:

    Bundle bundle = new Bundle();
    bundle.putParcelable("channel", _modeDataModel);
    Intent intent = new Intent(MainActivity.this,SecondActivity.class);
    intent.putExtras(bundle);
    startActivity(intent);

To retrieve in second activity:

    Bundle getBundle = this.getIntent().getExtras();
    DataModel model = getBundle.getParcelable("channel");


问:
StorageException for azure blob with java
When i am trying create container for my storage i get StorageException.
1.I created azure account.
2.I created azure storage for blob
3.I wrotten simple test(below)
4.I made this code on local machine and got exception. What is wrong?

```<code>public class Test {
public static final String storageConnectionString =
        "DefaultEndpointsProtocol=https;" +
                "AccountName=my_account;" +
                "AccountKey=my_account_key";

public static void main(String[] args) throws StorageException, InvalidKeyException, URISyntaxException {

    pushControll();
</code>```

}

```<code>public static void pushControll() throws URISyntaxException, StorageException, InvalidKeyException {

        CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString);

        CloudBlobClient blobClient = storageAccount.createCloudBlobClient();

        CloudBlobContainer container = blobClient.getContainerReference("observer");

        container.create();

    }
}
</code>```

I get StorageException - >:

```<code>Exception in thread "main" com.microsoft.azure.storage.StorageException: Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.
at com.microsoft.azure.storage.StorageException.translateException(StorageException.java:89)
at com.microsoft.azure.storage.core.StorageRequest.materializeException(StorageRequest.java:307)
at com.microsoft.azure.storage.core.ExecutionEngine.executeWithRetry(ExecutionEngine.java:182)
at com.microsoft.azure.storage.blob.CloudBlobContainer.create(CloudBlobContainer.java:279)
at com.microsoft.azure.storage.blob.CloudBlobContainer.create(CloudBlobContainer.java:252)
at ru.marketirs.model.Test.pushControll(Test.java:40)
at ru.marketirs.model.Test.main(Test.java:25)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
</code>```

Process finished with exit code 1

What have i done wrong?

答:
To by pass the proxy then please use like below, it works as expected and same has been tested.

```<code>public class AzureUpload {

    // Define the connection-string with your values
    /*public static final String storageConnectionString =
        "DefaultEndpointsProtocol=http;" +
        "AccountName=your_storage_account;" +
        "AccountKey=your_storage_account_key";*/
    public static final String storageConnectionString =
            "DefaultEndpointsProtocol=http;" +
            "AccountName=test2rdrhgf62;" +
            "AccountKey=1gy3lpE7Du1j5ljKiupjhgjghjcbfgTGhbntjnRfr9Yi6GUQqVMQqGxd7/YThisv/OVVLfIOv9kQ==";

    // Define the path to a local file.
    static final String filePath = "D:\\Project\\Supporting Files\\Jar's\\Azure\\azure-storage-1.2.0.jar";
    static final String file_Path = "D:\\Project\\Healthcare\\Azcopy_To_Azure\\data";

    public static void main(String[] args) {
        try
        {
            // Retrieve storage account from connection-string.
            //String storageConnectionString = RoleEnvironment.getConfigurationSettings().get("StorageConnectionString");
            //Proxy httpProxy = new Proxy(Proxy.Type.HTTP,new InetSocketAddress("132.186.192.234",8080));
            System.setProperty("http.proxyHost", "102.122.15.234");
            System.setProperty("http.proxyPort", "80");
            System.setProperty("https.proxyUser", "ad001\\empid001");
            System.setProperty("https.proxyPassword", "pass!1");
            // Retrieve storage account from connection-string.
            CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString);

            // Create the blob client.
            CloudBlobClient blobClient = storageAccount.createCloudBlobClient();

            // Get a reference to a container.
            // The container name must be lower case
            CloudBlobContainer container = blobClient.getContainerReference("rpmsdatafromhospital");

            // Create the container if it does not exist.
            container.createIfNotExists();

            // Create a permissions object.
            BlobContainerPermissions containerPermissions = new BlobContainerPermissions();

            // Include public access in the permissions object.
            containerPermissions.setPublicAccess(BlobContainerPublicAccessType.CONTAINER);

            // Set the permissions on the container.
            container.uploadPermissions(containerPermissions);

            // Create or overwrite the new file to blob with contents from a local file.
            /*CloudBlockBlob blob = container.getBlockBlobReference("azure-storage-1.2.0.jar");
            File source = new File(filePath);
            blob.upload(new FileInputStream(source), source.length());*/

            String envFilePath = System.getenv("AZURE_FILE_PATH");

            //upload list of files/directory to blob storage
            File folder = new File(envFilePath);
            File[] listOfFiles = folder.listFiles();

            for (int i = 0; i < listOfFiles.length; i++) {
              if (listOfFiles[i].isFile()) {
                System.out.println("File " + listOfFiles[i].getName());

                CloudBlockBlob blob = container.getBlockBlobReference(listOfFiles[i].getName());
                File source = new File(envFilePath+"\\"+listOfFiles[i].getName());
                blob.upload(new FileInputStream(source), source.length());
                System.out.println("File " + listOfFiles[i].getName()+ " upload successful");

              }
              //directory upload
              /*else if (listOfFiles[i].isDirectory()) {
                System.out.println("Directory " + listOfFiles[i].getName());

                CloudBlockBlob blob = container.getBlockBlobReference(listOfFiles[i].getName());
                File source = new File(file_Path+"\\"+listOfFiles[i].getName());
                blob.upload(new FileInputStream(source), source.length());
              }*/
            }

        }catch (Exception e)
        {
            // Output the stack trace.
            e.printStackTrace();
        }
    }
}
</code>```

.Net or C# then please add below code to "App.config"

```<code><?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
    </startup>

    <system.net>
     <defaultProxy enabled="true" useDefaultCredentials="true">
       <proxy usesystemdefault="true" />
     </defaultProxy>
    </system.net>

</configuration>
</code>```

Body:
When i am trying create container for my storage i get StorageException.
1.I created azure account.
2.I created azure storage for blob
3.I wrotten simple test(below)
4.I made this code on local machine and got exception. What is wrong?

public class Test {
public static final String storageConnectionString =
        "DefaultEndpointsProtocol=https;" +
                "AccountName=my_account;" +
                "AccountKey=my_account_key";

public static void main(String[] args) throws StorageException, InvalidKeyException, URISyntaxException {

    pushControll();

}

public static void pushControll() throws URISyntaxException, StorageException, InvalidKeyException {

        CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString);

        CloudBlobClient blobClient = storageAccount.createCloudBlobClient();

        CloudBlobContainer container = blobClient.getContainerReference("observer");

        container.create();

    }
}

I get StorageException - >:

Exception in thread "main" com.microsoft.azure.storage.StorageException: Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.
at com.microsoft.azure.storage.StorageException.translateException(StorageException.java:89)
at com.microsoft.azure.storage.core.StorageRequest.materializeException(StorageRequest.java:307)
at com.microsoft.azure.storage.core.ExecutionEngine.executeWithRetry(ExecutionEngine.java:182)
at com.microsoft.azure.storage.blob.CloudBlobContainer.create(CloudBlobContainer.java:279)
at com.microsoft.azure.storage.blob.CloudBlobContainer.create(CloudBlobContainer.java:252)
at ru.marketirs.model.Test.pushControll(Test.java:40)
at ru.marketirs.model.Test.main(Test.java:25)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)

Process finished with exit code 1

What have i done wrong?

Body:
To by pass the proxy then please use like below, it works as expected and same has been tested.

public class AzureUpload {

    // Define the connection-string with your values
    /*public static final String storageConnectionString =
        "DefaultEndpointsProtocol=http;" +
        "AccountName=your_storage_account;" +
        "AccountKey=your_storage_account_key";*/
    public static final String storageConnectionString =
            "DefaultEndpointsProtocol=http;" +
            "AccountName=test2rdrhgf62;" +
            "AccountKey=1gy3lpE7Du1j5ljKiupjhgjghjcbfgTGhbntjnRfr9Yi6GUQqVMQqGxd7/YThisv/OVVLfIOv9kQ==";

    // Define the path to a local file.
    static final String filePath = "D:\\Project\\Supporting Files\\Jar's\\Azure\\azure-storage-1.2.0.jar";
    static final String file_Path = "D:\\Project\\Healthcare\\Azcopy_To_Azure\\data";

    public static void main(String[] args) {
        try
        {
            // Retrieve storage account from connection-string.
            //String storageConnectionString = RoleEnvironment.getConfigurationSettings().get("StorageConnectionString");
            //Proxy httpProxy = new Proxy(Proxy.Type.HTTP,new InetSocketAddress("132.186.192.234",8080));
            System.setProperty("http.proxyHost", "102.122.15.234");
            System.setProperty("http.proxyPort", "80");
            System.setProperty("https.proxyUser", "ad001\\empid001");
            System.setProperty("https.proxyPassword", "pass!1");
            // Retrieve storage account from connection-string.
            CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString);

            // Create the blob client.
            CloudBlobClient blobClient = storageAccount.createCloudBlobClient();

            // Get a reference to a container.
            // The container name must be lower case
            CloudBlobContainer container = blobClient.getContainerReference("rpmsdatafromhospital");

            // Create the container if it does not exist.
            container.createIfNotExists();

            // Create a permissions object.
            BlobContainerPermissions containerPermissions = new BlobContainerPermissions();

            // Include public access in the permissions object.
            containerPermissions.setPublicAccess(BlobContainerPublicAccessType.CONTAINER);

            // Set the permissions on the container.
            container.uploadPermissions(containerPermissions);

            // Create or overwrite the new file to blob with contents from a local file.
            /*CloudBlockBlob blob = container.getBlockBlobReference("azure-storage-1.2.0.jar");
            File source = new File(filePath);
            blob.upload(new FileInputStream(source), source.length());*/

            String envFilePath = System.getenv("AZURE_FILE_PATH");

            //upload list of files/directory to blob storage
            File folder = new File(envFilePath);
            File[] listOfFiles = folder.listFiles();

            for (int i = 0; i < listOfFiles.length; i++) {
              if (listOfFiles[i].isFile()) {
                System.out.println("File " + listOfFiles[i].getName());

                CloudBlockBlob blob = container.getBlockBlobReference(listOfFiles[i].getName());
                File source = new File(envFilePath+"\\"+listOfFiles[i].getName());
                blob.upload(new FileInputStream(source), source.length());
                System.out.println("File " + listOfFiles[i].getName()+ " upload successful");

              }
              //directory upload
              /*else if (listOfFiles[i].isDirectory()) {
                System.out.println("Directory " + listOfFiles[i].getName());

                CloudBlockBlob blob = container.getBlockBlobReference(listOfFiles[i].getName());
                File source = new File(file_Path+"\\"+listOfFiles[i].getName());
                blob.upload(new FileInputStream(source), source.length());
              }*/
            }

        }catch (Exception e)
        {
            // Output the stack trace.
            e.printStackTrace();
        }
    }
}

.Net or C# then please add below code to "App.config"

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
    </startup>

    <system.net>
     <defaultProxy enabled="true" useDefaultCredentials="true">
       <proxy usesystemdefault="true" />
     </defaultProxy>
    </system.net>

</configuration>


答:
read about Abstract Factory design pattern :)

That will answer your question.

Title: C# Inheritance misconception


问:
Laravel output single row from database
I am a beginner at Laravel, and I am stuck :)

I am building a simple CMS for a costumer with a rather simple website.
I have created a database for all the text throughout the site, which I want to be able to edit. All the CRUD is working, but I can't seem to output the content from the database, with blade, to the actual view, as I get the error that the variable doesnt exist.

I thought I would be doing something like this {{ $text->"insert specific id" }}
My table has strings for id's to identify the respective text-content thoughout the site.

I have a MainController and a TextController, which is the one dealing with the CRUD of the text-elements.

I am probably forgetting a simple thing, but I just can't seem to work it out.

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Text;
use Session;

class TextController extends Controller
{
/**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */
public function index()
{
    $texts = Text::all();

    return view('texts.index')->withTexts($texts);
}

/**
 * Show the form for creating a new resource.
 *
 * @return \Illuminate\Http\Response

/**
 * Store a newly created resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function store(Request $request)
{
    $this->validate($request, array(

        'content' => 'required'
        ));

    $text = new Text;
    $text->content = $request->content;
    $text->save();

    return redirect()->route('texts.index');
}

/**
 * Show the form for editing the specified resource.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function edit($id)
{
    $text = Text::find($id);
    return view('texts.edit')->withText($text);
}

/**
 * Update the specified resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function update(Request $request, $id)
{
    $text = Text::find($id);
    $this->validate($request, array(

        'content' => 'required'
        ));

    $text->content = $request->content;
    $text->save();

    Session::flash('success', 'Teksten blev ændret!');

    return redirect()->route('texts.index');
}

/**
 * Remove the specified resource from storage.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function destroy($id)
{
    //
}
</code>```

}

I would think that I am missing something in the MainController

```<code><?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Validator;
use Mail;
use Illuminate\Support\Facades\DB;
use Session;
use App\Text;

class MainController extends Controller
{
public function index(){

    return view('index');
}
</code>```

Could that be?

Thanks in advance!

答:
```<code>public function index()
{
    $texts = Text::all();

    return view('texts.index', compact('texts'));
}
</code>```

Then in your view:

```<code>@foreach ($texts as $text)
     {!! $text->content !!}
@endforeach
</code>```

also compact() accept an array. You can do something like this compact(['first', 'second', 'third'])

Title: Laravel output single row from database

Body:
I am a beginner at Laravel, and I am stuck :)

I am building a simple CMS for a costumer with a rather simple website.
I have created a database for all the text throughout the site, which I want to be able to edit. All the CRUD is working, but I can't seem to output the content from the database, with blade, to the actual view, as I get the error that the variable doesnt exist.

I thought I would be doing something like this {{ $text->"insert specific id" }}
My table has strings for id's to identify the respective text-content thoughout the site.

I have a MainController and a TextController, which is the one dealing with the CRUD of the text-elements.

I am probably forgetting a simple thing, but I just can't seem to work it out.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Text;
use Session;

class TextController extends Controller
{
/**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */
public function index()
{
    $texts = Text::all();

    return view('texts.index')->withTexts($texts);
}

/**
 * Show the form for creating a new resource.
 *
 * @return \Illuminate\Http\Response

/**
 * Store a newly created resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function store(Request $request)
{
    $this->validate($request, array(

        'content' => 'required'
        ));

    $text = new Text;
    $text->content = $request->content;
    $text->save();

    return redirect()->route('texts.index');
}

/**
 * Show the form for editing the specified resource.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function edit($id)
{
    $text = Text::find($id);
    return view('texts.edit')->withText($text);
}

/**
 * Update the specified resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function update(Request $request, $id)
{
    $text = Text::find($id);
    $this->validate($request, array(

        'content' => 'required'
        ));

    $text->content = $request->content;
    $text->save();

    Session::flash('success', 'Teksten blev ændret!');

    return redirect()->route('texts.index');
}

/**
 * Remove the specified resource from storage.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function destroy($id)
{
    //
}

}

I would think that I am missing something in the MainController

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Validator;
use Mail;
use Illuminate\Support\Facades\DB;
use Session;
use App\Text;

class MainController extends Controller
{
public function index(){

    return view('index');
}

Could that be?

Thanks in advance!

Body:
public function index()
{
    $texts = Text::all();

    return view('texts.index', compact('texts'));
}

Then in your view:

@foreach ($texts as $text)
     {!! $text->content !!}
@endforeach

also compact() accept an array. You can do something like this compact(['first', 'second', 'third'])


问:
Get bounding box from Candelsticks series using Combo Chart in Google Charts
I've just started to use Google Charts and it's just wonderful. Unfortunately (and surprisingly) it doesn't have a Box Plot in its repertory, so I decided to emulate it by adding a line on top of a Candlesticks chart (I'm using the Candlesticks as a series of a Combo Chart because I also need a Line Chart within the same plot).

Frustratingly I've tried to get the attributes of each box of the Candlesticks Chart by using the getBoundingBox(id) method, but I have no clue about how to specify the id.

The docs say

The format for id isn't yet documented (they're the return values of
  event handlers), [...]

but I can't find any signs of how the event handlers' output might be.

How can I specify the id so that a single box of the Candlesticks Chart is returned?

```<code>// relevant part of the code
function drawChart()
{
    var data = new google.visualization.arrayToDataTable([
        // data here
        ], true);

    var options = {
        vAxes: {
            0: {},
            1: {},
        },
        series: {
            0: {
                type: "candlesticks",
                targetAxisIndex: 0,
            },
            1: {
                type: "line",
                targetAxisIndex: 1,
            }
        }
    };

    var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));

    google.visualization.events.addListener(chart, 'ready', function()
    {
        var layout = chart.getChartLayoutInterface();
        var cries_in_the_corner = layout.getBoundingBox( /* useless attempt of id */ );

        console.log(cries_in_the_corner); // always 'null'
    });

    chart.draw(data, options);
}
</code>```

答:
you can use the chart's click event to find the 'id'

but it will look similar to this...

'candlestick#0#0'

where the first 0 is the series number, and the second 0 is the row number

see following working snippet, the properties of the chart element clicked will be displayed in the console...

google.charts.load('current', {
  callback: drawChart,
  packages:['corechart']
});

function drawChart() {
  var data = google.visualization.arrayToDataTable([
    ['Mon', 20, 28, 38, 45],
    ['Tue', 31, 38, 55, 66],
    ['Wed', 50, 55, 77, 80],
    ['Thu', 77, 77, 66, 50],
    ['Fri', 68, 66, 22, 15]
  ], true);

  var chart = new google.visualization.ChartWrapper({
    chartType: 'CandlestickChart',
    containerId: 'chart_div',
    dataTable: data
  });

  google.visualization.events.addOneTimeListener(chart, 'ready', function () {
    google.visualization.events.addListener(chart.getChart(), 'click', function (gglClick) {
      console.log(JSON.stringify(gglClick));
    });
  });

  $(window).resize(function() {
    chart.draw();
  });
  chart.draw();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div id="chart_div"></div></code>```

Body:
I've just started to use Google Charts and it's just wonderful. Unfortunately (and surprisingly) it doesn't have a Box Plot in its repertory, so I decided to emulate it by adding a line on top of a Candlesticks chart (I'm using the Candlesticks as a series of a Combo Chart because I also need a Line Chart within the same plot).

Frustratingly I've tried to get the attributes of each box of the Candlesticks Chart by using the getBoundingBox(id) method, but I have no clue about how to specify the id.

The docs say

The format for id isn't yet documented (they're the return values of
  event handlers), [...]

but I can't find any signs of how the event handlers' output might be.

How can I specify the id so that a single box of the Candlesticks Chart is returned?

// relevant part of the code
function drawChart()
{
    var data = new google.visualization.arrayToDataTable([
        // data here
        ], true);

    var options = {
        vAxes: {
            0: {},
            1: {},
        },
        series: {
            0: {
                type: "candlesticks",
                targetAxisIndex: 0,
            },
            1: {
                type: "line",
                targetAxisIndex: 1,
            }
        }
    };

    var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));

    google.visualization.events.addListener(chart, 'ready', function()
    {
        var layout = chart.getChartLayoutInterface();
        var cries_in_the_corner = layout.getBoundingBox( /* useless attempt of id */ );

        console.log(cries_in_the_corner); // always 'null'
    });

    chart.draw(data, options);
}

Body:
you can use the chart's click event to find the 'id'

but it will look similar to this...

'candlestick#0#0'

where the first 0 is the series number, and the second 0 is the row number

see following working snippet, the properties of the chart element clicked will be displayed in the console...

google.charts.load('current', {
  callback: drawChart,
  packages:['corechart']
});

function drawChart() {
  var data = google.visualization.arrayToDataTable([
    ['Mon', 20, 28, 38, 45],
    ['Tue', 31, 38, 55, 66],
    ['Wed', 50, 55, 77, 80],
    ['Thu', 77, 77, 66, 50],
    ['Fri', 68, 66, 22, 15]
  ], true);

  var chart = new google.visualization.ChartWrapper({
    chartType: 'CandlestickChart',
    containerId: 'chart_div',
    dataTable: data
  });

  google.visualization.events.addOneTimeListener(chart, 'ready', function () {
    google.visualization.events.addListener(chart.getChart(), 'click', function (gglClick) {
      console.log(JSON.stringify(gglClick));
    });
  });

  $(window).resize(function() {
    chart.draw();
  });
  chart.draw();
}

<script src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div id="chart_div"></div>