text:
Q: y-axis scale limits not working when using ggplot() in R I have two ggplot() graphs p1 and p2 that I'm displaying next to each other. For that reason, I would like both to have the same ylim(). Here's the script I'm using for p1:
p1<-ggplot(data = dfnew, aes(x = Time, y = Proportion, group=linegroup)) +
  geom_point(aes(shape = as.character(Collar)), size = 4, stroke = 0,
             position = myjit)+
  geom_line(aes(group = linegroup),linetype = "dotted",size=1, position = myjit) +
  theme(axis.text=element_text(size=15),
        axis.title=element_text(size=20)) +
  geom_errorbar(aes(ymin = Lower, ymax = Upper), width=0.3, size=1,
                position = myjit) + scale_shape_manual(values=c("41361´"=19,"41366´"=15)) +
  scale_color_manual(values = c("Day" = "black",
                                "Night" = "black")) +
  labs(shape="Collar ID") +
  ylim(0.05, 0.4) + theme(legend.position = "none")+
  scale_y_continuous(breaks = scales::pretty_breaks(n = 5))+
  ggtitle("Feeding")

And here's the script I'm using for p2:
p2<-ggplot(data = dfnew, aes(x = Area, y = Proportion,colour=Area, group=linegroup)) +
  geom_point(aes(shape = as.character(Collar)), size = 4, stroke = 0,
             position = myjit)+
  geom_line(aes(group = linegroup),linetype = "dotted",size=1, position = myjit) +
  theme(axis.text=element_text(size=15),
        axis.title=element_text(size=20)) +
  geom_errorbar(aes(ymin = Lower, ymax = Upper), width=0.3, size=1,
                position = myjit) + scale_shape_manual(values=c("41361´"=19,"41365´"=17)) + scale_size_manual(values=c(2,2)) +
  scale_color_manual(values = c("SNP" = "brown",
                                "LGCA" = "darkgoldenrod2")) + labs(shape="Collar ID") +
  ylim(0.05, 0.4) +
  theme(legend.text=element_text(size=18))+
  theme(legend.title = element_text(size=18)) +
  scale_y_continuous(breaks = scales::pretty_breaks(n = 5))+
  ggtitle(" ") + theme(legend.position = "none")

However, as seen on the image below, y axis don't match. Not only that, but even when specifying scale_y_continuous(breaks = scales::pretty_breaks(n = 5)) I don't get the same number of tick in both y axis:

Hope at least somebody can set me on the right track, in case this is fixable. If it helps, I used the following data for p1:
> dput(dfnew)
structure(list(Proportion = c(0.242, 0.216, 0.29, 0.256), Lower = c(0.173,
0.152, 0.214, 0.186), Upper = c(0.329, 0.296, 0.381, 0.342),
    Time = c("Day", "Night", "Day", "Night"), Collar = c("41361´",
    "41361´", "41366´", "41366´"), ymin = c(0.069, 0.064, 0.076,
    0.07), ymax = c(0.571, 0.512, 0.671, 0.598), linegroup = c("Day 41361´",
    "Night 41361´", "Day 41366´", "Night 41366´")), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -4L))

and for p2:
> dput(dfnew)
structure(list(Proportion = c(0.181, 0.289, 0.099, 0.224), Lower = c(0.148,
0.242, 0.096, 0.217), Upper = c(0.219, 0.341, 0.104, 0.232),
    Area = c("LGCA", "SNP", "LGCA", "SNP"), Collar = c("41361´",
    "41361´", "41365´", "41365´"), ymin = c(0.033, 0.047, 0.003,
    0.00700000000000001), ymax = c(0.4, 0.63, 0.203, 0.456),
    linegroup = c("LGCA 41361´", "SNP 41361´", "LGCA 41365´",
    "SNP 41365´")), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
-4L))

A: You can fix this by instead of ylim()using coord_cartesianlike this: +coord_cartesian(ylim = c(0.05, 0.4), expand = TRUE)


text:
Q: php, mb_substr kills unicode characters I know mb_ is for dealing with utf8 characters, still it wont solve my problem.
So I have this string:

óóóóóóóóóóóóóóóóóóóóóóóóóóóóóóó

mb_substr ($oooo, 0,17, 'UTF-8');

óóóóóóóóóóóóóóóóó&oac

so the last character damages.

A: Your string is not actually
$str = 'óóóóóóóóóóóóóóóóóóóóóóóóóóóóóóó';

Your string is actually:
$str = 'óóóóóóóó...';

When looked at in the browser, the browser will of course render "ó", but that's of no interest to PHP.
The best solution is to get your content into the actually UTF-8 encoded characters "óóóóóóóóóóóóóó", then use your code as is. To make this work on your current string, you need to decode the HTML entities first:
$str = 'óóóóóóóó...';
$str = html_entity_decode($str, ENT_COMPAT, 'UTF-8');
echo mb_substr($str, 0, 17, 'UTF-8');

You'll then of course need to take care of the output encoding, since you're now outputting actual UTF-8 which the browser needs to understand. See UTF-8 all the way through.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Java : relational database vs static variable I have a web application in which I'm maintaining many static Maps to store my relevant information. Since the application is deployed on a server. Each and every hit to the server side java uses these maps to match the key and get appropriate result and send back to the client side. My code contains a rank and retrieval feature so I have to read the entire keySet of each of these Maps.
My question is:
1. Is working with static variables better than storing this data in a local embedded DB like Apache Derby and then using it?
2. The use of this data is very frequent. So if I use database will that be faster approach? Since I read the full keyset the where clause may not come handy in many operations.
3. How does the server's memory gets impacted on holding data in static variables?
My no. of maps are fixed but the size of the Maps keeps increasing? Please suggest the better solution.

A: If you want the data to be saved regularly an embedded database like H2 makes sense. You then also have snapshots of the data, and development, structural changes are a bit more safe.
A real database also has an incredible power behind it: concurrency, caching and so on. An embedded (when file based) database less so.
The problem with maps is that the data extraction can become several indirections. It is more versatile to have SQL queries with joins on the tables.
So SQL is more abstract (does not prescribe the actual query implementation), and easier to test. SQL for instance releases the developer of programming reports.
So go for a database IMHO, when you are really doing hard work.

A: What you might want to consider is to store the data searched in map when it's searched.
For instance, if a user searches for something specific, that something is stored in the map so that the next user who searches for that gets the data directly from the map rather than the database.
There are some downsides though, as you need to make sure that if the data is changed on the database, the hashmap/cache should be cleared or updated with the new data, as to prevent feeding outdated data to the user.
As for the impact on the server's memory, it depends on the size of the data you're storing. It's hard to give you a precise answer, but you can however test that on your own:
long memoryBefore = Runtime.getRuntime().freeMemory();
// populate your map
long memoryAfter = Runtime.getRuntime().freeMemory();
System.out.println(memoryBefore - memoryAfter);

That should give you the amount of bytes used (more or less, depending on the operations you run between memoryBefore and memoryAfter, as you may have instantiated other classes/variables unrelated to the hashmap)


text:
Q: Java, Play2.0,')' expected but '=' found play I follow the "Common template use cases" in play2.0 document, when I try to create a tag.
@(level: String = "error")(body: (String) => Html)

@level match {

  case "success" => {

      @body("green")

  }

  case "warning" => {

      @body("orange")

  }

  case "error" => {

      @body("red")

  }

}

then refresh the page http://localhost:9000, get an error say:
')' expected but '=' found.
In foo/app/views/tags/notice.scala.html at line 4.
1#{extends 'main.html' /}
2#{set title:'notice.scala.html' /}
3
4@(level: String="error")(body: (String) => Html)
5
6@level match {
7
8  case "success" => {

since I am newbie in both play2.0 and scala, cloud someone tell me why?

A: It doesn't really make sense to have a defaulting argument in an argument group of its own:
@(level: String = "error")(body: (String) => Html)

Notice how the example "moreScripts and moreStyles" at Scala templates common use cases puts the defaulted argument with another argument:
@(title: String, scripts: Html = Html(""))(content: Html)

You can do the same:
@(body: (String) => Html, level: String = "error")

Side note: it isn't a very good idea to rely on Strings to distinguish between success/warning/error. Strings are fragile and subject to typos, which will hide bugs in annoying ways. Instead, look for a data type, or create your own, to represent this: that way typos become a compiler error.
class ResultType
case object Success                 extends ResultType
case class Warning(message: String) extends ResultType
case class Error(message: String)   extends ResultType

A: I think you should try
@(level: (String) => "error")(body: (String) => Html)

@level match {

  case "success" => {

      @body("green")

  }

  case "warning" => {

      @body("orange")

  }

  case "error" => {

      @body("red")

  }

}


text:
Q: Is there a Python function that can rearrange column values into a specific column using CSV data? I have this column in our DataFrame that is separated by ';'. I managed to separate them but I was wondering if there was a way to put specific values into one column. For example, I would like to put Wayne State in one column, Oakland University in one column, etc. If this question has been answered already or if there is a similar post/question, please provide the link. I have looked and so far, I have not come across with the same problem.
school_applied column
school_applied column separated


text:
Q: Get string with listGetAt delimiter I have this string supplier_id ~|(~ '3422' ~)|~supplier_name ~|(~ 'WD Ltd.' ~)|~project_personnel ~|(~ 'Yaya Toure (temp)' ~)|~lt_project_code ~|(~ '013-7718321' ~)|~ id ~|(~ '668'
and I need to get content inside ~|(~data~)|~. I use listGetAt with delimiter. The problem is some data inside delimiter contain bracket ( which ruin the search. For example with Yaya Toure (temp) that contain bracket.
<cfoutput>
<cfset test = "supplier_id ~|(~ '3422' ~)|~supplier_name ~|(~ 'WD Ltd.' ~)|~project_personnel ~|(~ 'Yaya Toure (temp)' ~)|~lt_project_code ~|(~ '013-7718321' ~)|~ id ~|(~ '668'">

#test#
<cfset count_column = ListLen(test, "~)|~")>

<cfset column_name = ''>
<cfloop index="i" from="1" to=8 >
    <cfif i mod 2 EQ 0>
        <cfset column_name = ListAppend(column_name,listGetAt(test, i, "~|(~~)|~" ),",")>
    </cfif>
</cfloop>

Result : #column_name#
</cfoutput>

Output : Result : '3422' , 'WD Ltd.' , 'Yaya Toure ,'
My expected result is : '3422' , 'WD Ltd.' , 'Yaya Toure (temp)' , '013-7718321'. It will work if I removed (temp) from the string. Please assist me with this and thanks in advance.
iddle : https://cffiddle.org/app/file?filepath=ab77d723-1b04-46d6-8d80-fb765b881768/5c8c9eed-a16a-4f3a-b40b-fd7479fdc5ea/dae87d17-2826-4c63-b54c-55a57a8e4398.cfm

A: Option 1: Use a CF list function that supports multi-character delimiters, like listToArray.
<cfscript>
    // split on first delimiter get "name->value" string
    nameValuePairs = test.listToArray("~)|~" , false, true);

    columnValues = [];
    nameValuePairs.each(function(pair, index) {
        // split on second delimiter to extract value
        local.data = pair.listToArray("~|(~", false, true);
        columnValues.append( local.data[ 2 ] );
    });

    writeDump( "Result 1: "& columnValues.toList() );
</cfscript>

Option 2: If you can identify a single character that's never present within the values, perhaps a non-printable character, just replace the existing delimiters, and loop as usual.
<cfscript>
      // 31 == Unit separator
      delim     = chr(31);
      newString = test.replace( "~)|~", delim, "all")
                    .replace( "~|(~", delim, "all");

      columnValues = [];
      newString.listToArray( delim ).each(function( elem, index) {
          if (index mod 2 == 0) {
              columnValues.append( elem );
          }
      });

      WriteOutput( "
Result 2: "&  columnValues.toList()  );
</cfscript>

TryCF Examples
Update

problem though for this string supp~|(~lier_isd ~|(~ '3422' ~)|~supplier_name ~|(~ 'WD Ltd.' ~)|~project_personnel ~|(~ 'Yaya Toure (temp)' ~)|~lt_project_code ~|(~ '013-7718321' ~)|~ id ~|(~ '668' I was expecting lier_isd ~|(~ '3422', 'WD Ltd.', 'Yaya Toure (temp)', '013-7718321'

The initial string appeared to use the format name ~|(~ value ~)|~. However, if the value itself can contain one of the list delimiters  ~|(~, you won't be able to use list functions, because the function can't differentiate between when ~|(~ is acting as a delimiter and when it's part of a value. You'll need to use a regex instead. That's not my forte, but something like this should work
TryCF Example
  values = [];
  // Find groups of "~|(~ value ~)|~"
  matches = reMatch( "~\|\(~(.+?)(?=~\)\|~)", test);
  matches.each( function(item, index) {
    // remove text up to and including the first "~|(~"
    local.str = reReplace( item, ".*?~\|\(~", "");
    values.append( local.str );
  });

  WriteOutput( "Result 1: "& values.toList() );

Explanation
     ~        Find tilde "~"
     \|       Find pipe "|"
     \(       Find open parenthesis "("
     ~        Find tilde "~"

     (.+?)    One ore more characters, non-greedy

     (?=      Followed by (Non-capturing lookahead)
     ~        tilde "~"
     \)       close parenthesis "("
     \|       pipe "|"
     ~        tilde "~"
     )        End lookahead

     .*?      Zero or more characters
     ~        Find tilde "~"
     \|       Find pipe "|"
     \(       Find open parenthesis "("
     ~        Find tilde "~"


text:
Q: Linking to Python import library in Visual Studio 2005 I have a C++ application that has embedded Python. I'm building with Visual Studio 2005. When I try to link to python26.lib, I get a number of unresolved symbols, all of which begin with "__imp":
error LNK2019: unresolved external symbol __imp__Py_Initialize referenced in function _main
python26.lib is an import library (installed by the Python 2.6 installer). What do I have to do to resolve these symbols? They do exist in the import library (dumpbin /all shows them). Thanks.

A: Try to include C:\WINDOWS\system32\python26.dll in your references. python26.lib contains the symbol names for the main DLL.

A: Looks like I was trying to link a 64-bit Python library to a 32-bit application. I wish the linker would tell me something other than "unresolved symbol." Linking to the 32-bit library fixes the problem.


text:
Q: Can't change JProgressBar color in Mac OS look and feel I know this question has been answered before, but it's just not working for me. I followed the instructions from here: How to change JProgressBar color?
import javax.swing.*;
import java.awt.*;

public class ProgressBarTest extends JFrame {

    public static void main(String args[]) {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        UIManager.put("ProgressBar.background", Color.orange);
        UIManager.put("ProgressBar.foreground", Color.black);
        UIManager.put("ProgressBar.selectionBackground", Color.red);
        UIManager.put("ProgressBar.selectionForeground", Color.green);
        JProgressBar progressBar = new JProgressBar(0,100);
        progressBar.setValue(50);
        f.add(progressBar, BorderLayout.PAGE_END);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

}

All I am getting is the same old colors.

I'm using Mac OS X 10.7.3 and Java 1.6. I tried the CrossPlatformLookAndFeel and it works with the new colors. However I want this in the default look and feel. How can I do this?

A: To override Look & Feel defaults, make the change before constructing the GUI on the event  dispatch thread, as shown below.
On the com.apple.laf.AquaLookAndFeel, the progress bar's UI delegate is an instance of com.apple.laf.AquaProgressBarUI. As you have found, it ignores many defaults in favor of the native component. If a novel color scheme is required, consider supplying your own UI delegate, as shown here.
AquaProgressBarUI:

CustomProgressUI:

ProgressBar UI Defaults:

ProgressBar.background: com.apple.laf.AquaNativeResources$CColorPaintUIResource[r=238,g=238,b=238]
ProgressBar.border: javax.swing.plaf.BorderUIResource@47f08ed8
ProgressBar.cellLength: 1
ProgressBar.cellSpacing: 0
ProgressBar.cycleTime: 3000
ProgressBar.font: sun.swing.SwingLazyValue@6446d228
ProgressBar.foreground: javax.swing.plaf.ColorUIResource[r=0,g=0,b=0]
ProgressBar.horizontalSize: javax.swing.plaf.DimensionUIResource[width=146,height=12]
ProgressBar.repaintInterval: 20
ProgressBar.selectionBackground: javax.swing.plaf.ColorUIResource[r=255,g=255,b=255]
ProgressBar.selectionForeground: javax.swing.plaf.ColorUIResource[r=0,g=0,b=0]
ProgressBar.verticalSize: javax.swing.plaf.DimensionUIResource[width=12,height=146]
ProgressBarUI: com.apple.laf.AquaProgressBarUI

SSCCE:
import java.awt.*;
import javax.swing.*;

public class ProgressBarTest extends JFrame {

    public static void main(String args[]) {
        UIManager.put("ProgressBar.repaintInterval", 100);
        UIManager.put("ProgressBar.border",
            BorderFactory.createLineBorder(Color.blue, 2));
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                JFrame f = new JFrame();
                f.setLayout(new GridLayout(0, 1, 5 , 5));
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                f.add(createBar());
                f.add(createBar());
                f.add(createBar());
                f.pack();
                f.setLocationRelativeTo(null);
                f.setVisible(true);
            }

            private JProgressBar createBar() {
                JProgressBar progressBar = new JProgressBar(0, 100);
                progressBar.setValue(50);
                return progressBar;
            }
        });
    }
}


text:
Q: run java thread continously after it ends I have a class that runs as a thread, and I would like to run in again once it finishes executing, and possibly, maintain two-three threads of the same class running at the same time (ie. if a thread finishes executing but two are running, only one is run again, and so on).
The code I tried is this:
ExecutorService pool = Executors.newFixedThreadPool( 3 );
while( true )
    pool.submit( new MyThread() );

Any feedback on how this can be achieved?
Update: the class MyThread is actually MyRunnable!
Many thanks,
Vlad

A: try
    final ExecutorService pool = Executors.newFixedThreadPool(3);
    pool.submit(new Runnable() {
        public void run() {
            System.out.println("running1");
            pool.submit(this);
        }
    });

    pool.submit(new Runnable() {
        public void run() {
            System.out.println("running2");
            pool.submit(this);
        }
    });

A: Use ExecutorCompletionService:
ExecutorService executor = Executors.newFixedThreadPool(3);
CompletionService<Void> compService = new ExecutorCompletionService<Void>(executor);

for(int i = 0; i < 3; i++) compService.submit(new Task(), null);

while(true)
{
    compService.take(); // wait until one of the threads finishes its task
    compService.submit(new Task(), null);
}


text:
Q: Add div between element I have 2 paragraph and in between, I'll call a function. This function is to create a new div between the paragraph.

lorem ipsum

lorem ipsum

lorem ipsum

I've seen append(), but it need a target to append. I want to add the div automatically every time I call the function.
Also, document.write() but this will clear the paragraph.
There's multiple paragraph on the same page, and I can't add id or class to these paragraph. I don't have control over them.

A: I'll start off by saying, what you're trying to do is extremely ugly. Given your constraints, it's very likely there is something else fundamentally wrong with your app's structure. I even feel a bit dirty giving you this solution.
Regardless, to answer your question literally with the code examples and requirements you specified, you would likely need to keep a global counter of your script injection tags so you could append to its previous sibling. Here's an example that should do what you want w/ a fiddle (http://jsfiddle.net/h5qttvx5/3/).
Given HTML

lorem ipsum

lorem ipsum

lorem ipsum

And JS (in head)
var scripts = 0;
function createDiv() {
    $("#container > script").eq(scripts).prev().after("
HI
");
    scripts++;
}

A: Try this : remove script call and assign id to first paragraph, then use .after() to append div

lorem ipsum

lorem ipsum

Note : -  You can use class attribute for first p element instead of id and modify your jQuery selector as per like $('.className')
Use .after()
$(function(){
  $('#firstP').after('
Your div
');
});

A: First create a function and give it a name createDiv:

Them call the function where you want put the new div:

lorem ipsum

lorem ipsum

OBS: The script must be in the HEAD.

A: If you append inside the p tag:
 $('p').append('
xyz
');

If you append in between to p tag as sibling:
 $('
xyz
').insertAfter('p:first');

A: change your markup to

lorem ipsum

lorem ipsum

and call $("#thediv").append("
append div
");
DEMO FIDDLE
OR
  $('#lorem').after('
append div
');

DEMO FIDDLE

A:

$("p:first").after("
Hello World
");

lorem ipsum

lorem ipsum

A: This code should work fine, if I understand your problem well enough.

lorem ipsum

lorem ipsum

A: since you have the div container with an id you can target that and work your way down. Try the following:
$('#container > p:first').after('
hello
');

This will target the first p tag in the container div and add a div right after it.
Performance wise you may want to use the first() method instead of the pseudo class :first.
$('#container > p').first().after('
hello
');

This Stackoverflow question has answers that show tests for both cases:
jQuery :first vs. .first()


text:
Q: Symfony 3 asset install output folder name for bundle Is there any way to define output folder name which will be generated for symfony/src/mybundle/Resources/public directory content ?
Right now it auto generates web/bundles/mybundlename/css folder, but i need to have
web/bundles/custome_name/css
PS: i searched in google did not found anything about this ...

A: If you are using Webpack and Encore as the documentation recomends you can edit the arguments in
Encore
// directory where compiled assets will be stored
.setOutputPath('web/bundles/yourcustomname/')
// public path used by the web server to access the output path
.setPublicPath('/yourcustomname')


text:
Q: How do I generalize this Ecto/Elixir function? I've got the following, which applies a WHERE statement to an ecto query if platform exists.
  defp maybe_platform(queryable, false), do: queryable
  defp maybe_platform(queryable, platform) do
      queryable
      |> where([c], c.platform == ^platform)
  end

How can I generalise this code for any variable (instead of just platform)? (it's the c.platform bit I'm struggling with)

A: You need to use Ecto field https://hexdocs.pm/ecto/Ecto.Query.API.html#field/2
Your function would look something like this
defp maybe_field(queryable, field_name, field_value) do
    queryable
    |> where([c], field(c, ^field_name) == ^field_value)
end

and then
(from m in MyModel)
|> maybe_field(:platform, "platform_name_or_variable")
|> maybe_field(:another_field, "some value")
|> maybe_field(:is_platform_enabled, true)
|> Repo.all

A: You can use keywords as filter. Have a look at Ecto.Query#where/3:
from(c in City, where: c.country == "Sweden")
from(c in City, where: [country: "Sweden"])

A: Ecto.Query.where/3 accepts keyword list as filters. Elixir keyword list is just a wrapper around Erlang lists of tuples of two elements each. That said, somewhat like that would do:
defp maybe_where(queryable, _param, false), do: queryable
defp maybe_where(queryable, param, value) do
  filters = [{param, value}]
  where(queryable, ^filters)
end


text:
Q: Membership authentication on windows azure ASP.NET MVC 3 - couldn't find column I've try to migrate my ASP.NET MVC 3 project (with CodeFirst) to Windows Azure. Offcurse I changed the Providers.I've check the azure sql db and there are new tables like: Applications, Memberships, Profiles,Roles,Users
but now I got error:
[SqlException (0x80131904): Invalid column name 'ApplicationId'.
Invalid column name 'UserName'.
Invalid column name 'UserId'.
Invalid column name 'ApplicationId'.
Invalid column name 'UserName'.
Invalid column name 'IsAnonymous'.
Invalid column name 'LastActivityDate'.]
   System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) +2091750
   System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +5103168
   System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning() +260
   System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +2294
   System.Data.SqlClient.SqlDataReader.ConsumeMetaData() +33
   System.Data.SqlClient.SqlDataReader.get_MetaData() +86
   System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +311
   System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) +987
   System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) +162
   System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +32
   System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +141
   System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) +12
   System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) +10
   System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior) +443

[EntityCommandExecutionException: An error occurred while executing the command definition. See the inner exception for details.]
   System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior) +479
   System.Data.Objects.Internal.ObjectQueryExecutionPlan.Execute(ObjectContext context, ObjectParameterCollection parameterValues) +736
   System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption) +149
   System.Data.Objects.ObjectQuery`1.System.Collections.Generic.IEnumerable<T>.GetEnumerator() +44
   System.Linq.Enumerable.FirstOrDefault(IEnumerable`1 source) +182
   System.Data.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__1(IEnumerable`1 sequence) +41
   System.Data.Objects.ELinq.ObjectQueryProvider.ExecuteSingle(IEnumerable`1 query, Expression queryRoot) +59
   System.Data.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute(Expression expression) +150
   System.Data.Entity.Internal.Linq.DbQueryProvider.Execute(Expression expression) +87
   System.Linq.Queryable.FirstOrDefault(IQueryable`1 source) +265
   System.Web.Providers.QueryHelper.GetUser(MembershipContext ctx, String userName, String applicationName) +2104
   System.Web.Providers.DefaultMembershipProvider.Membership_CreateUser(String applicationName, String userName, String password, String salt, String email, String passwordQuestion, String passwordAnswer, Boolean isApproved, DateTime& createDate, Boolean uniqueEmail, Int32 passwordFormat, Object& providerUserKey) +151
   System.Web.Providers.DefaultMembershipProvider.CreateUser(String username, String password, String email, String passwordQuestion, String passwordAnswer, Boolean isApproved, Object providerUserKey, MembershipCreateStatus& status) +836
   System.Web.Security.Membership.CreateUser(String username, String password, String email, String passwordQuestion, String passwordAnswer, Boolean isApproved, Object providerUserKey, MembershipCreateStatus& status) +207
   GameiDemo.Controllers.HomeController.Index(User model) +99
   lambda_method(Closure , ControllerBase , Object[] ) +108
   System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +17
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +208
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
   System.Web.Mvc.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12() +55
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +263
   System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +19
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +191
   System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +343
   System.Web.Mvc.Controller.ExecuteCore() +116
   System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +97
   System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10
   System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +37
   System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +21
   System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +12
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
   System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +50
   System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
   System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8969201
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184

Web.config:
    <?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=152368
  -->
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>

    <!--
    <add name="ApplicationServices"
         connectionString="data source=mssql01\sql01;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
         providerName="System.Data.SqlClient" />
         -->
    <!--<add name="ApplicationServices" connectionString="Server=tcp:...database.windows.net,1433;Database=...;User ID=...@...;Password={your_password_here};Trusted_Connection=False;Encrypt=True;Connection Timeout=30;" providerName="System.Data.SqlClient" />-->
    <!--<add name="DBConnection" connectionString="Server=tcp:....database.windows.net,1433;Database=...;User ID=...@...;Password={your_password_here};Trusted_Connection=False;Encrypt=True;Connection Timeout=30;" providerName="System.Data.SqlClient" />/-->

    <!--
    <add name="DBConnection" connectionString="data source=.\SQLEXPRESS;initial catalog=GameiDemo;integrated security=True;multipleactiveresultsets=True;" providerName="System.Data.SqlClient" />
    -->
    <!--<add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
      providerName="System.Data.SqlClient" />//-->
    <add name="DefaultConnection" providerName="System.Data.SqlClient"
         connectionString="Data Source=tcp:....database.windows.net,1433;Initial Catalog=gamei_db;User Id=...@...;Password=123aba321!;Trusted_Connection=False;Encrypt=True;Connection Timeout=130;**MultipleActiveResultSets=True**" />
     </connectionStrings>

  <appSettings>
    <add key="webpages:Version" value="1.0.0.0" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.0">
      <assemblies>
        <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      </assemblies>
    </compilation>
    <authentication mode="Forms">
      <forms loginUrl="~/Account/LogOn" timeout="2880" />
    </authentication>

    <membership defaultProvider="DefaultMembershipProvider">
      <providers>
        <clear />
        <!-- <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" /> //-->
        <add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
      </providers>
    </membership>
    <profile defaultProvider="DefaultProfileProvider">
      <providers>
        <clear />
        <!-- <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/" /> //-->
        <add name="DefaultProfileProvider" type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />

      </providers>
    </profile>
    <roleManager enabled="false" defaultProvider="DefaultRoleProvider">
      <providers>
        <clear />
        <!--<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />-->

        <add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
        <add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
      </providers>
    </roleManager>
    <pages>
      <namespaces>
        <add namespace="System.Web.Helpers" />
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.WebPages" />
      </namespaces>
    </pages>
    <sessionState mode="InProc" customProvider="DefaultSessionProvider">
      <providers>
        <add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" />
      </providers>
    </sessionState>
  </system.web>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <modules runAllManagedModulesForAllRequests="true" />
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <system.web>
    <customErrors mode="Off" />
  </system.web>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
  </entityFramework>
</configuration>

I change username and serwer adres with "..." :)

A: I found what was wrong. One table form my model was named Users -> this cause that User table from System.Web.Providers does create.


text:
Q: Xcode label causes line break in middle of word I've been working with a label on a storyboard and can't seem to get it to behave correctly.  I have my lines set to 0 because I display a couple different things in the label, depending on what the user clicked before.  3 or 4 words will display fine and on multiple lines, but when I get to a larger single word it will break the word in half.  I don't won't it to do this, I just want it to resize and stay on a single line if it's only one word.  Any ideas how to do this?  I already have it working so that it will auto resize long text to fit there, the only problem is this.

A: If a UILabel is too small in its width, it cuts off the last part of the text or breaks its content into another line. As one word does not break into half automatically it can't be displayed entirely and therefore is cut off at its end.
In order to solve your problem I have some suggestions:

*

*Change the number of lines to at least 1

*Update your frames

*Resize the UILabel so it can display the entire word.

*Take a look at your constraints, as they might force the UILabel to resize under certain conditions.

I hope this might help you.


text:
Q: JwtModule doesn't add Authorization header On a Angular 7+ project, I tried to use the @auth0/angular-jwt module to add a Bearer token as Authorization header before sending request to a protected rest api.
I sent a request on the whitelisted URL and got a 401 exception, then I checked the Network (using fiddler) which header was transmited, the Authorization header was not there.
I followed all of the readme indication, and even checked If I included only once the HttpClientModule.
app.module.ts :
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { JwtModule } from '@auth0/angular-jwt';
import { tokenGetter } from './environment';

import { AppComponent } from './app.component';
// ... other components

@NgModule({
  declarations: [
    AppComponent
    // ... other components
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    HttpClientModule,
    JwtModule.forRoot({
      config: {
        tokenGetter: tokenGetter,
        whitelistedDomains: ["localhost:8080"]
      }
    })
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

environment.ts :
export function tokenGetter() {
    return localStorage.getItem('access_token');
}

A: I am on Angular 9 and this code snippet worked for JwtModule in the app.module.ts file. It's no longer whitelistedomains and blacklisteddomains anymore it's allowedDomains and disallowedRoutes in the latest version now.  Hope this helps the official doc is here
https://github.com/auth0/angular2-jwt
    JwtModule.forRoot({
  config: {
    tokenGetter: () => {
      return localStorage.getItem('token');
    },
    allowedDomains: ['localhost:5000'],
    disallowedRoutes: ['localhost:5000/api/auth']
  }
})

]
You can also do export function as well for the tokenGetter, but I just wanted to show how it would work in one code snippet. Happy coding!
package.json:
    "@auth0/angular-jwt": "^5.0.1",

app.module.ts import code:
import { HttpClientModule } from '@angular/common/http';
import { JwtModule } from '@auth0/angular-jwt';

Complete imports code:
  imports: [
BrowserModule,
HttpClientModule,
FormsModule,
BrowserAnimationsModule,
BsDropdownModule.forRoot(),
NgxGalleryModule,
TabsModule.forRoot(),
RouterModule.forRoot(appRoutes),
JwtModule.forRoot({
  config: {
    tokenGetter: () => {
      return localStorage.getItem('token');
    },
    allowedDomains: ['localhost:5000'],
    disallowedRoutes: ['localhost:5000/api/auth']
  }
})

],
techjunkieblog


text:
Q: Http post to server from Android app does not work I have an Android app that sends a http post to a remote server:
 protected Void doInBackground(Void... params) {
        // Get the message from the intent
        Intent intent = getIntent();
        String message = intent.getStringExtra(MapsActivity.EXTRA_MESSAGE);
        double longitude = intent.getDoubleExtra(MapsActivity.EXTRA_LONGITUDE, 0.0);
        double latitude = intent.getDoubleExtra(MapsActivity.EXTRA_LATITUDE, 0.0);
        Log.d("doInBackground", message);
        Log.d("doInBackground", String.valueOf(longitude));
        Log.d("doInBackground", String.valueOf(latitude));
        URL url = null;
        HttpURLConnection client = null;
        try {
            // Establish http connection
            url = new URL("http://******.com/");
            client = (HttpURLConnection) url.openConnection();
            client.setDoOutput(true);
            client.setDoInput(true);
            client.setRequestMethod("POST");
            client.connect();
            OutputStreamWriter writer = new OutputStreamWriter(client.getOutputStream());
            String output;
            output = URLEncoder.encode("message", "UTF-8")
                    + "=" + URLEncoder.encode(message, "UTF-8");

            output += "&" + URLEncoder.encode("longitude", "UTF-8") + "="
                    + URLEncoder.encode(String.valueOf(longitude), "UTF-8");

            output += "&" + URLEncoder.encode("latitude", "UTF-8") + "="
                    + URLEncoder.encode(String.valueOf(latitude), "UTF-8");
            Log.d("doInBackground(output)", output);
            Log.d("doInBackground(code)", String.valueOf(client.getResponseCode()));  // Return 200
            writer.write(output);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            client.disconnect();
        }
        return null;
    }

In the server, I have:
    <?php
      $m = urldecode($_POST['message']);
      $long = urldecode($_POST['longitude']);
      $lat = urldecode($_POST['latitude']);
      print " ==== POST DATA =====
      Message  : $m
      Longitude : $long
      Latitude  : $lat";
?>

client.getResponseCode() returns 200, I think that means my connection was successful? But the website still shows nothing. What might cause the problem?
I got
E/GMPM: getGoogleAppId failed with status: 10
E/GMPM: Uploading is not possible. App measurement disabled

might this be the problem?

A: What do you mean by the website doesn't show anything? You cannot see the print when you reload the web site because you are not saving it anywhere, you are simply printing out the values on that one single request. To debug you can write the post params to a file instead to see if they are coming through or better yet log the returned object on the android side.


text:
Q: How can I make Android application data persistent? I am new to Android development and am creating a "ToDoList" app in Android.
I used a SQLlite database to save the list in a database table, and
it saved data perfectly.
I don't have an Android phone, so I can check my application
only using an emulator.
After saving tasks in the database, if a user restarts the phone then will my task list in database be deleted or not? If it will be deleted then how can I make the data in the table persistent?

A: The table definitely stays if the user simply reboots the phone. Off the top of my head, I think the only way to get rid of the table completely is to either:

*

*Delete it (programmatically or via the sql command line)

*Uninstall the application

Simply upgrading your application to a new version will not delete your existing tables (so long as you use the same keystore when making the APK.)
-- Dan

A: For saving persistent application data Android offers various options.
A comparison between SQLite and SharedPreferences for storing persistent data.
Considering you are developing a ToDoList app for Android, I would recommend sticking to SQLite.


text:
Q: Is $\mathcal{F}_\infty$ a $\sigma$-algebra? (Chung Theorem 9.4.8.) We let $\mathcal{F}_\infty=\bigvee_n\mathcal{F}_n$. (What does $\bigvee$ usually denote? Is $\bigvee$ different from $\cup$? Can't find it in the text.)
The theorem tells us when we have $\lim_n E(Y|\mathcal{F}_n)=E(Y|\mathcal{F}_\infty)$.
I'd like to know:

*

*Is $\mathcal{F}_\infty$ a $\sigma$-algebra?

*Is it true that $A\in\mathcal{F}_\infty$ implies $A\in\mathcal{F}_n$ for some $n$?

It seems the answer to the former (assuming the latter is true) is no: If $A\in \mathcal{F}_1$ and $B\in\mathcal{F}_2$, then $A\cup B$ need not be an element of $\mathcal{F_n}$ for any $n$.
But then $E(Y|\mathcal{F}_\infty)$ is nonsensical, since conditional expectation (as a random variable) is defined using $\sigma$-algebras.

A: $\bigvee_n \mathcal{F}_n$ is the $\sigma$-algebra generated by $\bigcup_n \mathcal{F}_n$ (i.e., smallest $\sigma$-algebra containing $\bigcup_n \mathcal{F}_n$).
This is needed because in general, $\bigcup_n \mathcal{F}_n$ might not be a $\sigma$-algebra.
See here for an easy example.
See here for an example where the sequence is nested, i.e. $\mathcal{F}_1 \subseteq \mathcal{F}_2 \subseteq \cdots$.
So, by definition $\mathcal{F}_\infty$ is a $\sigma$-algebra. For your second bullet-point, I think the answer is no.


text:
Q: Azure Function startup's Configure not being called I'm trying to create non-static functions in my Azure Function projet in .NET 5 (VS 2022) and the Startup Configure method is not being called.
Here's my start up class
[assembly: FunctionsStartup(typeof(AuthenticationGateway.Functions.Startup))]
namespace AuthenticationGateway.Functions
{
    class Startup : FunctionsStartup //public or not, still does not get called.
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {

            //break point here never gets hit...

        }

    }

}

And here's the function in question:
namespace AuthenticationGateway.Functions
{
    public class CreationConnection
    {
        private AuthenticationGatewayContext Context { get; set; }

        public CreationConnection(AuthenticationGatewayContext context)
        {
            Context = context;
        }

        [Function("CreationConnection")]
        public HttpResponseData Run([HttpTrigger(AuthorizationLevel.Function, "get")] HttpRequestData req,
            FunctionContext executionContext)
        {

            var response = req.CreateResponse(HttpStatusCode.OK);

            return response;
        }
    }
}

I've tried commenting all of the code in Configure just in case it was a problem with it, not working either. Also tried marking the startup class as public too, no go.
Here are the dependencies for the projet in question

They are not the default dependencies the projet has when creating an Azure Function projet but as I tried other solutions to fix the issue, it lead me to plug those in.
Here's what the console is saying when starting the project:

Azure Functions Core Tools Core Tools Version:       3.0.3904 Commit
hash: c345f7140a8f968c5dbc621f8a8374d8e3234206  (64-bit) Function
Runtime Version: 3.3.1.0

Anything I missed ?
EDIT: I have reverted to the following dependencies as the previous ones made it so no functions would be found in the project.

On this page here it says those following dependencies have to be installed:
Microsoft.Azure.Functions.Extensions
Microsoft.NET.Sdk.Functions package version 1.0.28 or later
Microsoft.Extensions.DependencyInjection (currently, only version 3.x and earlier supported)

I have done so, except the last one because it is incompatible with .NET 5 it seems. Also, the project is now unbuildable:
error MSB4062: The "GenerateFunctionMetadata" task could not be loaded from the assembly

A: I have tried to reproduce the same issue which you got by following the below steps:

*

*Created the Azure Functions (Stack: .Net5-v3) in VS2022.

*Before adding Microsoft.Net.Sdk.functions to the project, it was built successfully.

*After adding Microsoft.Net.Sdk.functions to the project, it has run to the same issue MSB4062 error as below:

By referencing these SO Thread1 and Thread2, removing Microsoft.Net.Sdk.functions will solve the compile issue.


text:
Q: How to detect other language except english in string php? How to detect other language except english in string php ?
I use this code for detect other language beside english.
i want to know how can i reduce my code for short and cover all language.
<?PHP
$utf8_str = "xxxxxxxxxxxxxxx";
$Common = preg_match("/\p{Common}+/u", $utf8_str);
$Arabic = preg_match("/\p{Arabic}+/u", $utf8_str);
$Armenian = preg_match("/\p{Armenian}+/u", $utf8_str);
$Bengali = preg_match("/\p{Bengali}+/u", $utf8_str);
$Bopomofo = preg_match("/\p{Bopomofo}+/u", $utf8_str);
$Braille = preg_match("/\p{Braille}+/u", $utf8_str);
$Buhid = preg_match("/\p{Buhid}+/u", $utf8_str);
$Canadian_Aboriginal = preg_match("/\p{Canadian_Aboriginal}+/u", $utf8_str);
$Cherokee = preg_match("/\p{Cherokee}+/u", $utf8_str);
$Cyrillic = preg_match("/\p{Cyrillic}+/u", $utf8_str);
$Devanagari = preg_match("/\p{Devanagari}+/u", $utf8_str);
$Ethiopic = preg_match("/\p{Ethiopic}+/u", $utf8_str);
$Georgian = preg_match("/\p{Georgian}+/u", $utf8_str);
$Greek = preg_match("/\p{Greek}+/u", $utf8_str);
$Gujarati = preg_match("/\p{Gujarati}+/u", $utf8_str);

if(($Common != '0') OR ($Arabic != '0') OR ($Armenian != '0') OR ($Bengali != '0') OR ($Bopomofo != '0') OR ($Braille != '0') OR ($Buhid != '0') OR ($Canadian_Aboriginal!= '0') OR ($Cherokee != '0') OR ($Cyrillic != '0') OR ($Devanagari != '0') OR ($Ethiopic != '0') OR ($Georgian != '0') OR ($Greek != '0') OR ($Gujarati != '0'))
{
    echo "have other language";
}
else
{
    echo "Only english";
}
?>

A: Internationalization is something that takes much more time than a simple regex. Check this out, https://lingohub.com/blog/2013/07/internationalization-how-to-5-most-popular-php-frameworks/


text:
Q: how can i populate array elements from an external file var a1=[[]];

jQuery.get('file.txt', function(data) {
  a1=data;
  console.log(a1);
});

//file.txt contains data as follows
[[0,'IN',2],[1,'142',3]]
now my question is   a1=data in above code is not an array like var a=[[0,'IN,2],[2,'142'3]];how can i populate array elements from a text file???

A: Use JSON.parse. You don't need any external library to parse JSON.

The JSON.parse() method parses a string as JSON, optionally
  transforming the value produced by parsing.

jQuery.get('file.txt', function(data) {
  a1=JSON.parse(data);
  console.log(a1);
});


text:
Q: why is netbase removing some services? I shared another query a while ago. @StephenKitt shared and I quote

there's no reason for it to recommend networking tools (considering
  recommendations as defined in Debian Policy), and removing the
  recommendation is safe because default installations still end up with
  ifupdown installed. Cleaning such dependencies up will simplify
  possible future switches to other default tools. -Stephen Kitt

Now while I can understand that, what is needed to know are possible replacements. For instance it has removed three services which are essential to me. I do understand that they will be installed as default but still -

*

*services: removed ssh (22/udp).

*services: removed http (80/udp), https (443/udp).

from /usr/share/doc/netbase
While we do hope that web server providers will make https a default offering either with tying up with multiple certificate providers at low-cost or something, as of now it's upto the site creator to do the way s/he wants to set up. Don't see that changing soon.
Similarly I don't know anything better than ssh ?
[$] ssh -v localhost

OpenSSH_7.3p1 Debian-5, OpenSSL 1.0.2j  26 Sep 2016

I am ok with the changes being proposed, just need to know what changes (if any) are going to become defaults so I can work that out.

A: The removals are only removals of service definitions from /etc/services. The definitions were removed because they were obsolete or unused:

*

*SSH over UDP isn't used (this still leaves a service definition for SSH over TCP)

*HTTP and HTTPS over UDP aren't used (leaving HTTP and HTTPS over TCP)

etc. (read the git log for details of all the changes).
This only affects short-hand service definitions, and even then only unused service definitions, nothing else. It doesn't affect dependencies, the availability of services (which are provided by other packages anyway), your ability to provide services, etc.


text:
Q: A counterexample of induction on integers? What could be an example of a property $P(n)$ pertaining to an integer $n$ such that $P(0)$ is true, and that $P(n)$ implies $P(n++)$ for all integers $n$, but that $P(n)$ is not true for all integers $n$?
(Reference: http://www.math.ucla.edu/~tao/resource/general/131ah.1.03w/week1.pdf, Page 33, The paragraph after lemma 18).

A: Any property that satisfy exactly the integers contained in some interval $[a,\infty)$, where $a\le 0$. For example:

*

*To have a real square root.

*To satisfy the inequality $x^3+100>0$.

*To be non-negative.

Etc.


text:
Q: Relative linking (RoR) I have some static error pages under /public, in which I have linked a stylesheet called errors.min.css in the following manner:
<link rel="stylesheet" href="errors.min.css">

However, while I'm on a path except the root (/abc/non-existent-url), the pages don't render properly as the CSS file is not found (since its under a different path now.) I tried setting the URL to:
/public/errors.min.css

but it doesn't seem to work. Is there something I can do (except making the CSS inline, which I don't want to do)?

A: You should not use static stylsheet linking in Rails. Try the following:
<%= stylesheet_link_tag "errors.min.css" %>

This assumes that the stylesheet is in the app/assets/stylesheets/ directory.
Also your static pages would have to end with .html.erb for this to work.

P.S. Static pages should also be made using a controller. See this tutorial on static pages.


text:
Q: Setting up NGINX / Linux development environment with Vagrant and Chef (Solo) As a disclaimer I am rather new to Linux after recently moving the Microsoft .NET IIS stack
The problem: I am having difficulty provisioning a ready made environment to develop against using the following...

*

*Vagrant

*Chef

*VirtualBox

*Apt (cookbook)

*Apache2 (cookbook)

The error I am receiving is (when hitting the hostname or IP of the virtual machine)
ERR_NAME_NOT_RESOLVED
There is a lot of code so, I will just post my vagrant file and role...
Vagrantfile
-----------------

Vagrant.configure(2) do |config|

    config.vm.box = "hashicorp/precise32"
    config.vm.network :forwarded_port, guest: 80, host: 4567
    config.vm.host_name = "www.example.vm"

    config.vm.provision "chef_solo" do |chef|
        chef.cookbooks_path = "cookbooks"
      end
end

vagrant-test-boc.rb
-----------------

# Name of the role should match the name of the file
name "vagrant-test-box"

# Run list function we mentioned earlier
run_list(
    "recipe[apt]",
    "recipe[apache2]"
)

Any suggestions, guidelines examples would be most welcome!
Thanks!
Additional Edit: I have been advised to look into setting up an NGINX server using similar techniques, would this be another question or would it be valid along this thread?
My main resources have been....
https://adamcod.es/2013/01/15/vagrant-is-easy-chef-is-hard-part2.html
https://docs.vagrantup.com/v2/provisioning/chef_solo.html

A: If I understand correctly, you're trying to access the server www.example.vm (on port 4567) from your host ?
If that's the case, then the issue is probably that you've not told your host that www.example.vm is really an alias to your own host (localhost). Otherwise your host has no way of knowing that it shouldn't do a dns lookup and attempt to send a request to this host over the internet.
On a Unix / OSX box, you can edit your /etc/hosts, where you can add your fake domain name to the localhost line, like so:

127.0.0.1   localhost www.example.vm

Hope this helps!  ; )


text:
Q: How to set the path of the folder to be created in uwp in C# For example: C:\Users\gabriel\Desktop\
There it creates the folder on the desktop
I do not have code, and I have no idea how to do it. And I do not want to use FolderPicker, I want to define in the folder path code

A: Generally speaking, UWP applications are sand-boxed for security, so you might not be able to interact with the filesystem in the way that you want.
If you have enough control over the target machine, you might be able to ensure that some console app or windows service is also running on the machine, and you can send http requests to that app so that it can do things that your UWP app can't.


text:
Q: TypeError: Cannot read properties of undefined (reading 'init') || Flutter web I have recently upgraded my flutter project from Flutter Beta to Flutter Stable 3.3.8.
after upgrading, I also upgraded all the firebase packages to the latest version.
Due to this upgrade on my config function, there is a new parameter of navigatorKey.
So I included that like this
class NavKey{
    static final navKey =  GlobalKey<NavigatorState>();
    }

static final Config config = Config(
  navigatorKey: NavKey.navKey,          //new parameter of navigatorKey
  tenant: "xx-3066-xx-xx-xx",
  clientId: "xx-ad66-xx-a6e6-xx",
  scope: "api://xx-xx-422a-a6e6-xx/xx",
  redirectUri:
      "xx://com.example.xx/xx%xx%3D");

Now If I run my project and enter my email id and hit enter it shows this error
TypeError: Cannot read properties of undefined (reading 'init')

on my void main() I have included all my Firebase initialize like this
Future<void> main() async {
  // await dotenv.load();
  WidgetsFlutterBinding.ensureInitialized();

  await Firebase.initializeApp(
      options: const FirebaseOptions(
          apiKey: "xxx-xx",
          authDomain: "xx-xxx.firebaseapp.com",
          databaseURL: "https://xxx-xx-default-xxx.xx.com",
          projectId: "xxx-xxx",
          storageBucket: "xxx-xx.appspot.com",
          messagingSenderId: "xxx",
          appId: "1:xx:web:xxx3d75b63xxxxe9",
          measurementId: "G-xxxx")
          );

  runApp(const MyApp()
      /* MaterialApp(//
  home: MyApp())*/
      );
}

on my index.html I have also included this script as I am running my project on flutter web
<script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-storage.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-messaging.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-analytics.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-functions.js"></script>

These are my all errors

A: Well, I am not able to find the solution for the latest package.
That's why I rolled back my aad_oauth from ^0.4.0 to ^0.3.0 where it doesn't asked for navigatorKey
Config(
    navigatorKey: NavKey.navKey,)


text:
Q: Woocommerce content layout issues So I have entered the correct code into my custom theme to be able to make it compatible with woo commerce, however, I'm unsure on how to style the content i.e. the product page wth all the products in columns. It's essentially in an unstyled ugly list. Can anyone assist in helping me setup woocommerce so that I can style it as I want?
Thank you!

A: You'll need to copy the templates from within the woocomerce default theme to your theme's directory and modify them to suit your needs.


text:
Q: Why does `:=` work as an infix operator? Why does the following work in R?
> `:=` <- function(x, y) x + y
> 1 := 2
[1] 3

My understanding was that % was required for user-defined infix operators.  Are there other (possibly easier to type) options available?

A: This is because := is, like <- or <<-, defined as LEFT_ASSIGN for the parser of R.
See http://svn.r-project.org/R/trunk/src/main/gram.y
This means that := is a special case and you may as well not expect that any other options are available.


text:
Q: How to enable CORS on a Wordpress Subdomain? I have a wordpress page using ajax (a room booking system), and also a wordpress subdomain which is pointing to the page.
The main section of the page will not load when using the subdomain. The console error is
XMLHttpRequest cannot load http://mysite.co.uk/wp-admin/admin-ajax.php. Origin http://meetingroom.mysite.co.uk is not allowed by Access-Control-Allow-Origin.

I have tried to enable CORS for the subdomain but failed. In the subdomain folder on the server I have an index.php file to point to the room booking page. The code is as follows:-
<?php

$_GET['page_id']=2250;

define('WP_USE_THEMES', true);

require('../httpdocs/wp-blog-header.php');

The subdomain works very well except for the Access-Control-Allow-Origin error.
Can somebody help me to fix it? Thank you!


text:
Q: Writing functions that can convert types in pyopencl I'm trying to write some additional functions for the COMPLEX (cfloat_t) type in pyopencl. I have practically no experience with OpenCL and am getting a bit bogged down by syntax. I'd like to write a few basic functions that could take in REAL inputs (floats in this case) and convert them to the COMPLEX type. For example Euler's formula e^ix = cos(x) + isin(x) with x as a REAL input
I thought this would be something like
#include <pyopencl-complex.h>
#define REAL      float
#define COMPLEX   cfloat_t
COMPLEX c_exp_i(REAL x)        {return (COMPLEX)(cos(x), sin(x));}

But when I attempt to run this I see an error message
error: cast to union type from type 'float' not present in union

A: After reading pyopencl-complex.h, I've realized there is a cfloat_new() function which solves everything
COMPLEX c_exp_i(REAL x)     {return cfloat_new(cos(x), sin(x));}


text:
Q: Shrink leaflet map's bounds by some padding or ratio I'd like to shrink a Leaflet map's bounds by some factor (say 50px or 5%).
I've tried the following:
marginPoint = new L.Point(50, 50);
bounds = map.getPixelBounds();
bottomLeft = bounds.getBottomLeft();
topRight = bounds.getTopRight();

bounds = new L.LatLngBounds(
  map.unproject(bottomLeft.subtract(marginPoint)),
  map.unproject(topRight.subtract(marginPoint))
);

However, this does not shrink the map, it just moves/translates the current box / current map's bounds.

A: Since you subtract the same amount to both map containers' corners, the result is that you just shift the map view to the South West (bottom left).
If you are trying to "zoom in" (i.e. the map displays a smaller portion of geographic area, but within the same container dimensions), you would add some pixels to your bottom left corners, and remove some to your top left.
But be noted that you could also simply use the latLngBounds.pad() method (with a negative bufferRatio argument) to achieve the same result.


text:
Q: Transforming non-structured data (concatenated strings of text) into consumable, readable format / extracting datapoints from strings I'm trying to extract specific datapoints from string of text and have a hard time figuring out how to do so.

What I need to achieve is to extract dates from a specific string.
The string structure is as follows:
Product: XX1, Made by: WWW ZZZ, Date: YYYY-MM-DD; and it can be repeated multiple times (see the screenshot below). There are three different product types (lets say: Car_VW, Car_Tesla, Car_PS - there are no records with other product types) and date has to be extracted separately for each one of them.
Moreover, one product type can appear few times (up to three times) in this string so the date needs to be stored separately for each instance of its appearing.

Columns E - M show what I need to achieve based on data in column C
I came up following formula:
=IFERROR(IF(AND(FIND(LEFT(E$3,6),$C4,1)>0,FIND("Product",$C4,1)=1),MID(MID($C4,FIND(LEFT(E$3,6),$C4,1),LEN($C4)-FIND(LEFT(E$3,6),$C4,1)),FIND("Date: ",MID($C4,FIND(LEFT(E$3,6),$C4,1),LEN($C4)-FIND(LEFT(E$3,6),$C4,1)),1)+6,10),"no go"),"")

Which works only for first "iterations" of each product.

Looking at how the data in column C is formatted, do you guys think it's possible to write something that would return correct values for each iteration/loop? If so, a little help would be much appreciated. If anyone knows a better way to do it, please let me know. Would using VBA be a better approach?

A: Not sure it's a better approach but it will handle any number of products/appearances and creates corresponding row 3 headings as well as a temporary table of normalized data.
Option Explicit

Sub normalize()

    Const COL_TEXT = 3
    Const RE_PATTERN = "Product: ?([^,]+), Made.*?Date: ?([\d-]+)"

    ' use a regular expression for pattern matching
    Dim Regex As Object
    Set Regex = CreateObject("vbscript.regexp")

    With Regex
        .Global = True
        .MultiLine = True
        .IgnoreCase = True
        .Pattern = "(" & RE_PATTERN & ")"
    End With

    ' Us dictionary to count dates for each Product
    Dim dict As Object
    Set dict = CreateObject("Scripting.Dictionary")

    Dim wb As Workbook, ws As Worksheet, wsTmp As Worksheet, iTmp As Long
    Set wb = ThisWorkbook
    Set ws = wb.Sheets("Sheet1")

    ' create temp sheet to store table
    Set wsTmp = wb.Sheets.Add
    iTmp = 0

    ' scan sheet
    Dim iRow As Long, iLastRow As Long
    Dim sText As String, sProduct As String, sDate As String
    Dim matches As Object, match As Object, key As Variant
    Dim n As Long, r As Long, c As Long
    Dim iBlocks As Long, t0 as single
    t0 = Timer

    iLastRow = ws.Cells(Rows.count, COL_TEXT).End(xlUp).Row
    'Debug.Print iLastRow

    ' scan sheet with text
    For iRow = 4 To iLastRow
        sText = ws.Cells(iRow, COL_TEXT) ' text in  C
        'Debug.Print s

        ' extract product and date
        If Regex.test(sText) Then
            Set matches = Regex.Execute(sText)
            For Each match In matches

                sProduct = match.submatches(1)
                sDate = match.submatches(2)

                ' update dictionary
                If dict.exists(sProduct) Then
                    dict(sProduct) = dict(sProduct) + 1
                Else
                    dict.Add sProduct, 1
                End If

                ' store result temporarily
                iTmp = iTmp + 1
                wsTmp.Cells(iTmp, 1) = iRow
                wsTmp.Cells(iTmp, 2) = sProduct
                wsTmp.Cells(iTmp, 3) = dict(sProduct)
                wsTmp.Cells(iTmp, 4) = sDate
            Next
        End If

        ' increase no of blocks if required
        For Each key In dict.keys
           If dict(key) > iBlocks Then
               iBlocks = dict(key)
           End If
           dict(key) = 0
        Next
    Next

    ' create headings in row 3 for each block/product
    c = 5 ' start in E
    For n = 1 To iBlocks
       For Each key In dict.keys
          If n = 1 Then dict(key) = c ' reuse dict for column no
          ws.Cells(3, c) = key & " Loop" & n
          c = c + 1
       Next
    Next

    ' scan down temp result sheet
    For iRow = 1 To iTmp
        r = wsTmp.Cells(iRow, 1)
        sProduct = wsTmp.Cells(iRow, 2)
        n = wsTmp.Cells(iRow, 3)
        sDate = wsTmp.Cells(iRow, 4)

        ' fill in correct cell on original
        c = dict(sProduct) ' start column
        ws.Cells(r, c + (n - 1) * dict.count) = sDate
    Next
    wsTmp.Delete

    ' end
    ws.Activate
    ws.Cells(3, 3).Select
    MsgBox iTmp & " Product/Dates Extracted in " & int(Timer - t0) & " secs"

End Sub

A: I've completed the formula. Here goes this abomination:
=IFERROR(MID(MID($C4,FIND("XXX",SUBSTITUTE($C4,LEFT(E$3,6),"XXX",RIGHT(E$3,1))),LEN($C4)-FIND(LEFT(E$3,6),$C4,1)),FIND("Date: ",MID($C4,FIND("XXX",SUBSTITUTE($C4,LEFT(E$3,6),"XXX",RIGHT(E$3,1))),LEN($C4)-FIND("XXX",SUBSTITUTE($C4,LEFT(E$3,6),"XXX",RIGHT(E$3,1)))),1)+6,10),"")

^works for a table structured like the one in the initial post


text:
Q: Command Line looking wrong My command line looks like this:
|system||system|ruby 2.0.0p645 (system) User_name-MacBook-Air in ~

Can someone tell me how to edit this down to:
User_name-MacBook-Air in

I have a feeling it has to do with a recent RVM issue I was having, but any help on cutting down
|system||system|ruby 2.0.0p645 (system)


text:
Q: Using Generics as Parameters I'm still pretty new to both Java and Android and I'm working on an Android RSS reader project. I'm writing the reader that runs as an AsyncTask, and would like to keep it as reuse-able as possible. I'm using a SAX parser in the reader, and would like it to accept a handler of any type that extends DefaultHandler. However, when I try to call the parse method of the SAXParser, it doesn't understand the handler parameter.
cannot resolve method 'parse(org.xml.sax.InputSource,java.lang.Class<capture<? extends org.xml.sax.helpers.DefaultHandler>>)'

Is this the correct way to go about this problem in terms of passing a generic handler, or is there something I should be doing differently?
public class RSSFeeder extends AsyncTask<Void, Void, Void>{

private Class<? extends DefaultHandler> handler;
private String feedURL;

public RSSFeeder(Class<? extends DefaultHandler> handler, String feedURL) {
    this.handler = handler;
    this.feedURL = feedURL;
}

@Override
protected Void doInBackground(Void... params) {
    URL feedLocation = null;
    try {
        feedLocation = new URL(feedURL);
        BufferedReader in = new BufferedReader(new InputStreamReader(feedLocation.openStream()));

        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();

        sp.parse(new InputSource(in), handler);

    } catch (MalformedURLException murlex) {
        Log.d(this.getClass().getName(), "The supplied URL is not valid " + murlex.getMessage());
    } catch (IOException iox) {
        Log.d(this.getClass().getName(), "Could not read data from the supplied URL: " + feedLocation.toString() + " " + iox.getMessage());
    } catch (ParserConfigurationException pcex) {
        Log.d(this.getClass().getName(), "Could not configure new parser. " + pcex.getMessage());
    } catch (SAXException saxex) {
        Log.d(this.getClass().getName(), "Could not create new sax parser. " + saxex.getMessage());
    }

    return null;
}

A: handler is a variable of type java.lang.Class, not DefaultHandler (or any of its subtypes). The second argument for the method SAXParser#parse() must be of type DefaultHandler. You can try declaring your class as a generic class with the type parameter extending DefaultHandler:
public class RSSFeeder<T extends DefaultHandler> extends AsyncTask<Void, Void, Void>{
   private T handler;

   public RSSFeeder(T handler, String feedURL) {
      this.handler = handler;
      this.feedURL = feedURL;
   }
   ...

}


text:
Q: send wav file in HTTP POST request(using mongoose embedded web server) I Am trying to send Wav file using mongoose http server. Basically,I am forming POST request and sending with
struct mg_connection *mg_connect_http(struct mg_mgr *mgr,
                                      mg_event_handler_t ev_handler,
                                      const char *url,
                                      const char *extra_headers,
                                      const char *post_data)
API,This API expect const char *post_data in visible ascii string format but my wav file is raw data, as there are 0x00(null) characters in raw wav file , whole content of file is not sent. Is there any conversation I need to perform on wav file before I send it to server?

A: I think you should try chunked encoding.
I.e. you should not send raw data in mg_connect_http, but use mg_send_http_chunk and Co.

A: Another solution you might try is:
c = mg_connect();
mg_set_protocol_http_websocket(c);
mg_printf(c, "POST /my_uri HTTP/1.0\r\n");
mg_printf(c, "Content-Length: %lu\r\n\r\n", (unsigned long) post_len);
mg_send(c, post, post_len);

Note this will buffer the whole WAV file in memory before sending.


text:
Q: MOSFET H-Bridge with PWM for motor control - will this circuit work?
I designed an H-Bridge circuit that I will use to drive a 12V wiper motor that can draw 6A. Will this work? Should I just use relays? I want to be able to control speed as well. I will be controlling the PWM and the switching through an Arduino.

A: We can't say whether this will "work" because you haven't specified the desired operation, what controls parts like the two switches, where the tops of D2 and D3 are connected, etc.  In short, this is a documentation mess.
There are also some obvious problems.  There is nothing limiting current when Q3 is on, and Q9 is turned on by "PWM", just to name one.
Step back, create a proper spec for what you want a circuit to accomplish, how it will be controlled, etc, then maybe ask about details of various parts.

A: This is not going to work with PWM, because when BJT will cut off, gate capacitance with resistors will not shut the MOSFET fast enough. Use gate driver instead all this complicated stuff around the bridge.

A: There is nothing wrong with the circuit with a few caveats:
1. As @Gregory Kornblum has pointed out, a little more gate drive current might be beneficial to discharge the gates on Q1 and Q3.  Otherwise you will have to keep the PWM frequency pretty low.
2. Assuming only one switch is on at a time for motor direction, it would still be nice to add some type of current sense circuitry, because if the motor stalls you will be driving the motor winding resistance only.  You can use the PWM to limit motor current, but you need to sense it somewhere.  12v Batteries can produce 100's of amperes.
3. You will need a heat sink at 6 amps for the FETS.  For instance, Q2 has an on resistance of 0.3 ohms so at 6 amps you are more than 10 Watts, and RDS(on) increases with temperature.  Since the Junction-to-ambient temperature rise is 62C per watt, you will overheat and blow them right away.
Good luck!


text:
Q: How to redirect in Xamarin.Forms I use Xamarin and debug on an Android device.
How to redirect an url in Xamarin.Forms?
I'm trying this in default page load.

A: You can use Device.OpenUri to open the URL in the mobile browser:
Device.OpenUri(new Uri("http://xamarin.com"));

Here is a sample implementation:
using System;
using Xamarin.Forms;

namespace Example
{
    class MyPage : ContentPage
    {

        public MyPage()
        {
            Button button = new Button
            {
                Text = "Open URL",
                Font = Font.SystemFontOfSize(NamedSize.Large),
                BorderWidth = 1,
                HorizontalOptions = LayoutOptions.Center,
                VerticalOptions = LayoutOptions.CenterAndExpand
            };
            button.Clicked += OnButtonClicked;

            this.Content = new StackLayout
            {
                Children = {
                    button
                }
            };
        }

        void OnButtonClicked(object sender, EventArgs e)
        {
            Device.OpenUri(new Uri("http://xamarin.com"));
        }
    }
}


text:
Q: Ie css hack star What are the different ways of writing css hacks for ie?
I have seen html >, *..
but it is all very confusing..
Are there hacks to target specific ie versions like ie7, ie8 ?

A: I would recommend splitting IE "hacks" into a separate stylesheet so than can be dropped in the future as support for those browsers is dropped.
With this approach, you can use conditional comments to add the appropriate stylesheet for the appropriate version on IE.
Here's a good post on conditional comments:
http://css-tricks.com/132-how-to-create-an-ie-only-stylesheet/

A: There plenty of such topics. But to be constructive, here is the topic of IE CSS hacks explained (below conditional statements).


text:
Q: Angular displaying correct array item in buttons I have an array with 4 items, and 4 buttons on a dashboard.  I want to assign item1 with button1, and item2 with button2 etc.  Right now it displays 4 buttons for each "hero" for a total of 16 buttons.  I tried {{hero.name[2]}} and similar things but that just grabs letters and not the actual array items.  I would appreciate any help.
dashboard.component.html

Calibrations

    <button style ="min-height: 70px" (click)="gotoClick(1)">{{hero.name}}</button>
    <button style ="min-height: 70px" (click)="gotoClick(2)">{{hero.name}}</button>
    <button style ="min-height: 70px" (click)="gotoClick(3)">{{hero.name}}</button>
    <button style ="min-height: 70px" (click)="gotoClick(4)">{{hero.name}}</button>

dashboard.component.ts
import { Component, OnInit } from '@angular/core';
import { Hero } from '../hero.class';
import { HeroService } from '../hero.service';
import { StepService } from '../step.service';
@Component({
  moduleId: module.id,
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
  heroes: Hero[] = [];

  constructor(private heroService: HeroService, private _stepService: StepService, private _teststepService: StepService) { }

  ngOnInit() {
    this.heroService.getHeroes().subscribe(heroes => this.heroes = heroes);
  }

  private test: number;
  gotoClick(value: number){
    this._stepService.setTest(value);
    this._teststepService.apiURL();
  }
}

hero.service.ts
import { Injectable }    from '@angular/core';
import { Headers, Http, Response } from '@angular/http';
import { Hero } from './hero.class';
import { Observable } from "rxjs/Rx";

@Injectable()
export class HeroService {

  private headers = new Headers({'Content-Type': 'application/json'});
  private heroesUrl = 'api/heroes';  // URL to web api

  constructor(private http: Http){ }

  getHeroes(): Observable<Hero[]> {
    return this.http.get(this.heroesUrl)
               .map(response => response.json().data as Hero[]);
  }

  getHero(id: number): Observable<Hero> {
    const url = `${this.heroesUrl}/${id}`;
    return this.http.get(url)
      .map(response => response.json().data as Hero);
  }
}

A: You can use the built-in index property of *ngFor:

    <button style ="min-height: 70px" (click)="gotoClick(i)">{{hero?.name}</button>

Documentation: https://angular.io/docs/ts/latest/api/common/index/NgFor-directive.html


text:
Q: Send post-request from dockerized jar to local python-service I am running a dockerized jar and a local flask-service on my Mac. The jar represents a web-app for a musical catalogue and the flask-service transforms musical notes into a xml-based music-encoding format. The service is called when the user has clicked on the download button.
Starting the application through PyCharm and IntelliJ works fine, but within the container I get:
  2019-11-30 19:36:14.504 ERROR 1 --- [nio-8080-exec-1] o.a.c.c.C.[.[.
  [/].[dispatcherServlet]    : Servlet.service() for servlet
  [dispatcherServlet] in context with path [] threw exception [Request
  processing failed; nested exception is
  org.springframework.web.client.ResourceAccessException: I/O error on
  POST request for "http://0.0.0.0:5000/test": Connection refused
  (Connection refused); nested exception is java.net.ConnectException:
  Connection refused (Connection refused)] with root cause

  java.net.ConnectException: Connection refused (Connection refused)
at java.base/java.net.PlainSocketImpl.socketConnect(Native Method) ~[na:na]
at java.base/java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:399) ~[na:na]
at java.base/java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:242) ~[na:na]
at java.base/java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:224) ~[na:na]
at java.base/java.net.Socket.connect(Socket.java:591) ~[na:na]
at java.base/java.net.Socket.connect(Socket.java:540) ~[na:na]
at java.base/sun.net.NetworkClient.doConnect(NetworkClient.java:182) ~[na:na]
at java.base/sun.net.www.http.HttpClient.openServer(HttpClient.java:474) ~[na:na]
at java.base/sun.net.www.http.HttpClient.openServer(HttpClient.java:569) ~[na:na]
at java.base/sun.net.www.http.HttpClient.<init>(HttpClient.java:242) ~[na:na]
at java.base/sun.net.www.http.HttpClient.New(HttpClient.java:341) ~[na:na]
at java.base/sun.net.www.http.HttpClient.New(HttpClient.java:362) ~[na:na]
at java.base/sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:1248) ~[na:na]
at java.base/sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1187) ~[na:na]
at java.base/sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1081) ~[na:na]
at java.base/sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:1015) ~[na:na]
at org.springframework.http.client.SimpleBufferingClientHttpRequest.executeInternal(SimpleBufferingClientHttpRequest.java:76) ~[spring-web-5.1.9.RELEASE.jar!/:5.1.9.RELEASE]
at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48) ~[spring-web-5.1.9.RELEASE.jar!/:5.1.9.RELEASE]
at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:53) ~[spring-web-5.1.9.RELEASE.jar!/:5.1.9.RELEASE]
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:735) ~[spring-web-5.1.9.RELEASE.jar!/:5.1.9.RELEASE]
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:670) ~[spring-web-5.1.9.RELEASE.jar!/:5.1.9.RELEASE]
at org.springframework.web.client.RestTemplate.postForObject(RestTemplate.java:414) ~[spring-web-5.1.9.RELEASE.jar!/:5.1.9.RELEASE]
at com.masterarbeit.wolfganggabrielvz.adapter.userRoles.MEIAdapter.getData(MEIAdapter.java:51) ~[classes!/:0.0.1-SNAPSHOT]
at com.masterarbeit.wolfganggabrielvz.adapter.controller.IncipitController.getMei(IncipitController.java:51) ~[classes!/:0.0.1-SNAPSHOT]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190) ~[spring-web-5.1.9.RELEASE.jar!/:5.1.9.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.1.9.RELEASE.jar!/:5.1.9.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) ~[spring-webmvc-5.1.9.RELEASE.jar!/:5.1.9.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:892) ~[spring-webmvc-5.1.9.RELEASE.jar!/:5.1.9.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797) ~[spring-webmvc-5.1.9.RELEASE.jar!/:5.1.9.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.1.9.RELEASE.jar!/:5.1.9.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1039) ~[spring-webmvc-5.1.9.RELEASE.jar!/:5.1.9.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942) ~[spring-webmvc-5.1.9.RELEASE.jar!/:5.1.9.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005) ~[spring-webmvc-5.1.9.RELEASE.jar!/:5.1.9.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:908) ~[spring-webmvc-5.1.9.RELEASE.jar!/:5.1.9.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:660) ~[tomcat-embed-core-9.0.22.jar!/:9.0.22]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882) ~[spring-webmvc-5.1.9.RELEASE.jar!/:5.1.9.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) ~[tomcat-embed-core-9.0.22.jar!/:9.0.22]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.22.jar!/:9.0.22]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.22.jar!/:9.0.22]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.22.jar!/:9.0.22]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.22.jar!/:9.0.22]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.22.jar!/:9.0.22]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-5.1.9.RELEASE.jar!/:5.1.9.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:118) ~[spring-web-5.1.9.RELEASE.jar!/:5.1.9.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.22.jar!/:9.0.22]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.22.jar!/:9.0.22]
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92) ~[spring-web-5.1.9.RELEASE.jar!/:5.1.9.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:118) ~[spring-web-5.1.9.RELEASE.jar!/:5.1.9.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.22.jar!/:9.0.22]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.22.jar!/:9.0.22]
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) ~[spring-web-5.1.9.RELEASE.jar!/:5.1.9.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:118) ~[spring-web-5.1.9.RELEASE.jar!/:5.1.9.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.22.jar!/:9.0.22]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.22.jar!/:9.0.22]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) ~[spring-web-5.1.9.RELEASE.jar!/:5.1.9.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:118) ~[spring-web-5.1.9.RELEASE.jar!/:5.1.9.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.22.jar!/:9.0.22]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.22.jar!/:9.0.22]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.22.jar!/:9.0.22]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) ~[tomcat-embed-core-9.0.22.jar!/:9.0.22]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490) ~[tomcat-embed-core-9.0.22.jar!/:9.0.22]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) ~[tomcat-embed-core-9.0.22.jar!/:9.0.22]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.22.jar!/:9.0.22]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) ~[tomcat-embed-core-9.0.22.jar!/:9.0.22]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) ~[tomcat-embed-core-9.0.22.jar!/:9.0.22]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408) ~[tomcat-embed-core-9.0.22.jar!/:9.0.22]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) ~[tomcat-embed-core-9.0.22.jar!/:9.0.22]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:853) ~[tomcat-embed-core-9.0.22.jar!/:9.0.22]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1587) ~[tomcat-embed-core-9.0.22.jar!/:9.0.22]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.22.jar!/:9.0.22]
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.22.jar!/:9.0.22]
at java.base/java.lang.Thread.run(Thread.java:834) ~[na:na]

This is the dockerfile from the Spring-Boot app:
FROM amazoncorretto:11
ADD target/springbootapp-0.0.1-SNAPSHOT.jar springbootapp-
0.0.1-SNAPSHOT.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar","springbootapp-0.0.1-SNAPSHOT.jar"]

How I built the image:
docker build -f Dockerfile -t catalogue_image .

I load the image and linked it with the mysql-db
docker run --name catalogue_image -p 8080:8080 -d --link catalogueDB:mysql catalogue_image

The network-settings of the running container:
"NetworkSettings": {
        "Bridge": "",
        "SandboxID": "56bd5ecdaab28c726711b368f0fa73a1d181d66605056cdfbecce0188bd7c1f5",
        "HairpinMode": false,
        "LinkLocalIPv6Address": "",
        "LinkLocalIPv6PrefixLen": 0,
        "Ports": {
            "8080/tcp": [
                {
                    "HostIp": "0.0.0.0",
                    "HostPort": "8080"
                }
            ]
        },
        "SandboxKey": "/var/run/docker/netns/56bd5ecdaab2",
        "SecondaryIPAddresses": null,
        "SecondaryIPv6Addresses": null,
        "EndpointID": "b0366c7e1b934208f7eb748d58cc18dac76a94d5da3e09184761d6da38c52373",
        "Gateway": "172.17.0.1",
        "GlobalIPv6Address": "",
        "GlobalIPv6PrefixLen": 0,
        "IPAddress": "172.17.0.2",
        "IPPrefixLen": 16,
        "IPv6Gateway": "",
        "MacAddress": "02:42:ac:11:00:02",
        "Networks": {
            "bridge": {
                "IPAMConfig": null,
                "Links": null,
                "Aliases": null,
                "NetworkID": "eda38ae3c3fc27a3990e3761dc7f35ddd98f04e9f6e55cce46e191557df688d8",
                "EndpointID": "b0366c7e1b934208f7eb748d58cc18dac76a94d5da3e09184761d6da38c52373",
                "Gateway": "172.17.0.1",
                "IPAddress": "172.17.0.2",
                "IPPrefixLen": 16,
                "IPv6Gateway": "",
                "GlobalIPv6Address": "",
                "GlobalIPv6PrefixLen": 0,
                "MacAddress": "02:42:ac:11:00:02",
                "DriverOpts": null
            }
        }

Flask runs on my local-machine. It does not return any Error-Code after a service-call fails:
      python3 gateway.py
    ['/usr/local/lib/python3.7/site-packages', '/Users/max/PycharmProjects/flaskmicroservice/app',         '/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python37.zip',             '/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python3.7',               '/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-             dynload', '/Users/max/Library/Python/3.7/lib/python/site-packages',                                     '/usr/local/lib/python3.7/site-packages', '/usr/local/lib/python3.7/site-packages/verovio-             2.0.0-py3.7-macosx-10.13-x86_64.egg']
    * Serving Flask app "gateway" (lazy loading)
    * Environment: production
    WARNING: This is a development server. Do not use it in a production deployment.
    Use a production WSGI server instead.
    * Debug mode: off
    * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)

Before, I got a FileNotFound-Exception but I could already fix it by changing the resources path. I also entered the container and added localhost under etc/hosts but it did not work. I read all the other solutions about accessing a local service from inside a container but in did not solve my problem.
I would be grateful for every help!
EDIT:
I am using a docker-compose file now
version: "3"
services:
db:
   image: mysql:latest
  environment:
    - MYSQL_ROOT_PASSWORD=crescendo
    - MYSQL_USER=root
    - MYSQL_PASSWORD=crescendo
    - MYSQL_DATABASE=wolfgang_gabriel_db
  ports:
     - 3306:3306

web:
  image: gabriel_verzeichnis
  depends_on:
    - db

  ports:
    - 8080:8080
  domainname: localhost
  network_mode: "host"
  environment:
    - DATABASE_HOST=db
    - DATABASE_USER=root
    - DATABASE_PASSWORD=crescendo
    - DATABASE_NAME=wolfgang_gabriel_db
    - DATABASE_PORT=3306

  links:
    - db:3306

Regarding the answer, I tried to set the network_mode as host in order to get access to my local machine, but it did not work. Have I done something wrong?

A: Ok, the problem here is that you're running your client in a docker container and your server on your host machine, and you haven't arranged to route traffic between them.
By default, a container is its own localhost. So when you access 0.0.0.0 it maps back to the container you're accessing it from. You want to reference the host so that you can access a service there. This is not a great idea but is possible using --network host flag. This is such a bad idea that I will offer you an alternative.
A good solution is to also run flask in a container and have its address passed as an environment variable to the client container. You can do this in any number of ways (including as a flag on the command-line for the client), but one of the easiest is to use docker-compose and put both services in the compose file, then your url would reference the hostname of the flask service, rather than an IP address, and docker will ensure that traffic is correctly routed.


text:
Q: Modify colletion using entityframework In my project I have bellow Entity class
public partial class Movie
{
public Movie()
{
this.MovieCategories = new HashSet<MovieCategory>();
}

public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public virtual ICollection<MovieCategory> MovieCategories { get; set; }
}

public partial class MovieCategory
{
public int Id { get; set; }
public int CategoryId { get; set; }
public int MovieId { get; set; }
public virtual Category Category { get; set; }
public virtual Movie Movie{ get; set; }
}

public partial class Category
{
public Category()
{
    this.MovieCategories = new HashSet<MovieCategory>();
}
public int Id { get; set; }
public string Category1 { get; set; }
public virtual ICollection<MovieCategory> MovieCategories { get; set; }

}
I have view where I can add or remove "MovieCategories" using listbox.
Bellow is how I am trying to update my movie object using entityframework.
    _movieReviewEntities.Movies.Attach(movie);
    _movieReviewEntities.Entry(movie).State = EntityState.Modified;
    _movieReviewEntities.SaveChanges();

This is updating "Id", "Name" & "Description" properties but not updating my colletion "MovieCategories"
How can I update "MovieCategories" also ?

A: For example you have a new MovieCategory and you want to update a Movie with this new MovieCategory.
Please take note that I didn't test this.
MovieCategory newCategory = new MovieCategory
{
   "Action Movie"
};

movie.MovieCategories.Add(newCategory);

_movieReviewEntities.Movies.Attach(movie);
_movieReviewEntities.Entry(movie).State = EntityState.Modified;
_movieReviewEntities.SaveChanges();

This should also add the new movie category.
In case your category exists in your table
var existingCategory = _movieReviewEntities.MovieCategories.Where(m => m.Name == "Action Movie")
.Select(m => m).FirstOrDefault();

if(existingCategory != null)
{
   movie.MovieCategories.Add(existingCategory);
}

If you have for a example a ListBox that contains the selected movie categories.
//From ListBox
var fromSelection = new List<string>("Comedy", "Drama");

//Fetch from table
var categoryListToAdd = movie.MovieCategories.Where(x => fromSelection.Contains(x.Name)).Select(x => x).ToList();

if(categoryListToAdd.Count > 0)
{
    //Existing categories of the movie.
    var categoryList = movie.MovieCategories.Select(x => x).ToList();

    //Remove the related records.
    if(categoryList.Count > 0)
       categoryList.ForEach(x => _movieReviewEntities.MovieCategories.Remove(x));

    //Then add the selected categories.
    categoryListToAdd.ForEach(x => _movieReviewEntities.Add(x));
}

Again, this is not tested. Hope you get the idea.

A: To modify relation in EF context, both related objects should be tracked by the context. It means that you must attach both Movie and MovieCategory objects to a context to modify a relation between them.
By the way, if you load entities, they remain attached in context. Here's a simple example how you can load a movie with it's categories and clear all categories and add a new one:
using (var context = new MovieContext())
{
    var movie = context.Movies.Include(m => m.MovieCategories).First(m => m.Name == "Green Elephant");
    movie.MovieCategories.Clear();
    var newCategory = context.MovieCategories.Create();
    newCategory.Name = "Trash";
    movie.MovieCategories.Add(newCategory);
    context.SaveChanges();
}