Q: How to link/nest 2 dropdowns in a form in Adalo I have 2 collections:
collection 1 is called “Category” with almost 10 records.
collection 2 is called “Subcategory” with almost 100 records.
these 2 collections are currently linked.
I have a form that allow user to create a profile, the form has 2 drop downs, one for Category and one for sub-category.

i want when user pick a category from the first dropdown, it only shows the relevant sub-category of that item in the second drop down. at the moment both drop downs show full list and there’s no way i can filter either of them.

the select filter for subcategory drop down doesn’t give me an option to filter that based on the content of category dropdown:

i chose other component but it takes you the chain of pages with no end


Q: Add TabBar on SearchDelegate Flutter I am trying to add a tab bar on Search Delegate. I want to show the results of products and user's profiles on the same search screen. I was trying to get a controller from the parent class and implement in delegate class but nothing happend(I wasn't getting any error)
Currently, my problem is I want to rebuild the build suggestion widget but I don't have any idea how to do that. Because the tab button widget has a different build context I can't rebuild the Suggestion widget.
hope you understand please ignore my grammar mistakes
class CustomSearchDelegate extends SearchDelegate {
  final TabController tabController;
  CustomSearchDelegate(this.tabController);

  var currentIndex = 0;
  List<Widget> tabs = [Text("Tab 1"), Text("Tab 2")];

  @override
  List<Widget> buildActions(BuildContext context) {
    return [
      Icon(Icons.clear),
    ];
    // TODO: implement buildActions
    throw UnimplementedError();
  }

  @override
  Widget buildLeading(BuildContext context) {
    return Container();
    // TODO: implement buildLeading
    throw UnimplementedError();
  }

  @override
  Widget buildResults(BuildContext context) {
    return Container();
    // TODO: implement buildResults
    throw UnimplementedError();
  }

  @override
  PreferredSizeWidget buildBottom(BuildContext context) {
    return PreferredSize(
        preferredSize: const Size.fromHeight(50.0),
        child: StatefulBuilder(
          builder: (context, setState) => DefaultTabController(
            length: 2,
            child: TabBar(
              onTap: (index) {
                setState(() {
                  currentIndex = index;
                });
              },
              indicatorColor: Colors.red,
              tabs: [
                Padding(
                  padding: const EdgeInsets.symmetric(vertical: 15),
                  child: Text(
                    "Products",
                    style: Theme.of(context).textTheme.headline6,
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.symmetric(vertical: 15),
                  child: Text(
                    "Users",
                    style: Theme.of(context).textTheme.headline6,
                  ),
                ),
              ],
            ),
          ),
        ));
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    final categoriesList =
        Provider.of<PopularServiceList>(context).dummy.where((element) {
      return element.title.toLowerCase().contains(query.toLowerCase());
    });
    return StatefulBuilder(
      builder: (context, setState) {
        return tabs[currentIndex];
      },
    );
    throw UnimplementedError();
  }
}


Q: Combining echo and cat on Unix Really simple question, how do I combine echo and cat in the shell, I'm trying to write the contents of a file into another file with a prepended string?
If /tmp/file looks like this:
this is a test

I want to run this:
echo "PREPENDED STRING"
cat /tmp/file | sed 's/test/test2/g' > /tmp/result

so that /tmp/result looks like this:
PREPENDED STRINGthis is a test2

Thanks.

A: This should work:
echo "PREPENDED STRING" | cat - /tmp/file | sed 's/test/test2/g' > /tmp/result

A: Or just use only sed
  sed -e 's/test/test2/g
s/^/PREPEND STRING/' /tmp/file > /tmp/result

A: Or also:
{ echo "PREPENDED STRING" ; cat /tmp/file | sed 's/test/test2/g' } > /tmp/result

A: Try:
(printf "%s" "PREPENDED STRING"; sed 's/test/test2/g' /tmp/file) >/tmp/result

The parentheses run the command(s) inside a subshell, so that the output looks like a single stream for the >/tmp/result redirect.

A: If this is ever for sending an e-mail, remember to use CRLF line-endings, like so:
echo -e 'To: cookimonster@kibo.org\r' | cat - body-of-message \
| sed 's/test/test2/g' | sendmail -t

Notice the -e-flag and the \r inside the string.
Setting To: this way in a loop gives you the world's simplest bulk-mailer.

A: Another option:  assuming the prepended string should only appear once and not for every line:
gawk 'BEGIN {printf("%s","PREPEND STRING")} {gsub(/test/, "&2")} 1' in > out


Q: How do I use Json.NET to parse json in PowerShell? I want to parse JSON in PowerShell but I can't use the new v3 functions that are available in PowerShell. My first thought was to load the JSON.Net assembly and use that to parse the JSON string but it doesn't work as I expect it to.
I have this JSON:
$json = "{""Name"": ""Apple"",
           ""Price"": 3.99,
            ""Sizes"": [
                 ""Small"",
                 ""Medium"",
                 ""Large""]}"

I load the JSON.NET assembly with this code:
[Reflection.Assembly]::LoadFile("$currentPath\Newtonsoft.Json.dll”)

And tries to parse it with
$result = [Newtonsoft.Json.JsonConvert]::DeserializeObject($json)

Now I expect that $result["Name"] is Apple but I get nothing there. Any ideas?
The code ´$result.ContainsKey("Name")returnsTruebut$result.GetValue("Name")returnsnull`.

A: If you get here and are using Powershell 5.0, it's available in the powershell gallery
Install-Module Newtonsoft.Json
Import-Module Newtonsoft.Json

$json = '{"test":1}'
[Newtonsoft.Json.Linq.JObject]::Parse($json)

A: maybe this is what you're after :
http://poshcode.org/2930
    function Convert-JsonToXml {
PARAM([Parameter(ValueFromPipeline=$true)][string[]]$json)
BEGIN {
   $mStream = New-Object System.IO.MemoryStream
}
PROCESS {
   $json | Write-Stream -Stream $mStream
}
END {
   $mStream.Position = 0
   try
   {
      $jsonReader = [System.Runtime.Serialization.Json.JsonReaderWriterFactory]::CreateJsonReader($mStream,[System.Xml.XmlDictionaryReaderQuotas]::Max)
      $xml = New-Object Xml.XmlDocument
      $xml.Load($jsonReader)
      $xml
   }
   finally
   {
      $jsonReader.Close()
      $mStream.Dispose()
   }
}
}

function Write-Stream {
PARAM(
   [Parameter(Position=0)]$stream,
   [Parameter(ValueFromPipeline=$true)]$string
)
PROCESS {
  $bytes = $utf8.GetBytes($string)
  $stream.Write( $bytes, 0, $bytes.Length )
}
}

$json = '{
    "Name": "Apple",
    "Expiry": 1230422400000,
    "Price": 3.99,
    "Sizes": [
        "Small",
        "Medium",
        "Large"
    ]
}'

Add-Type -AssemblyName System.ServiceModel.Web, System.Runtime.Serialization
$utf8 = [System.Text.Encoding]::UTF8
(convert-jsonToXml $json).innerXML

Output :
<root type="object"><Name type="string">Apple</Name><Expiry type="number">1230422
400000</Expiry><Price type="number">3.99</Price><Sizes type="array"><item type="s
tring">Small</item><item type="string">Medium</item><item type="string">Large</it
em></Sizes></root>

If you want the name node :
$j=(convert-jsonToXml $json)
$j.SelectNodes("/root/Name")

or
$j |Select-Xml -XPath "/root/Name" |select -ExpandProperty node

A: Ok, so here is how I did it so it works down to at least PowerShell v2 on Windows 2008.
First, load the Json.NET assembly for the version you would like to use, I took the .NET 3.5 version:
[Reflection.Assembly]::LoadFile("Newtonsoft.Json.dll")

I had the JSON in a file since it was used in a deployment configuration I wrote, so I needed to read the file and then parse the json
$json = (Get-Content $FileName | Out-String) # read file
$config = [Newtonsoft.Json.Linq.JObject]::Parse($json) # parse string

Now to get values from the config you need to to use the Item method which seems defined by PowerShell on hashtables/dictionaries. So to get an item that is a simple string you would write:
Write-Host $config.Item("SomeStringKeyInJson").ToString()

If you had an array of things you would need to do something like
$config.Item("SomeKeyToAnArray") | ForEach-Object { Write-Host $_.Item("SomeKeyInArrayItem").ToString() }

To access nested items you write
$config.Item("SomeItem").Item("NestedItem")

That's how I solved parsing JSON with Json.NET in PowerShell.

A: None of the answers here so far made it straightforward to deserialize, edit, and serialize without Token PropertyName in state ArrayStart would result in an invalid JSON object errors.  This is what ended up working for me.
Assuming $json contains a valid json string this deserializes to a hashtable:
$config = [Newtonsoft.Json.JsonConvert]::DeserializeAnonymousType($json, @{})

Or, if you need to maintain key order:
$config = [Newtonsoft.Json.JsonConvert]::DeserializeAnonymousType($json, [ordered]@{})

Then you can work with the data as a normal hashtable, and serialize it again.
$sb = [System.Text.StringBuilder]::new()
$sw = [System.IO.StringWriter]::new($sb)
$jw = [Newtonsoft.Json.JsonTextWriter]::new($sw)
$jw.Formatting = [Newtonsoft.Json.Formatting]::Indented
$s = [Newtonsoft.Json.JsonSerializer]::new()

$s.Serialize($jw, $config)
$json = $sb.ToString()


Q: Change style of Google Play Services AccountPicker dialog I am showing the AccountPicker dialog from Google Play Services with this code:
    String[] accountTypes = new String[]{"com.google"};
    Intent intent = AccountPicker.newChooseAccountIntent(null, null,
            accountTypes, false, null, null, null, null);
    startActivityForResult(intent, REQUEST_CODE_PICK_ACCOUNT);

It appears as a dark themed dialog even though I am using AppCompat v21 with Theme.AppCompat.Light.
Is it possible to style the dialog? Preferably as a Material dialog on Lollipop but at least make it a light dialog to match my app.

A: I think, no need to "hack". It can be achieved easier:
    ...
    String[] accountTypes = new String[]{GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE};
    Intent intent = AccountPicker.newChooseAccountIntent(null, null, accountTypes, false, description, null, null, null);

    // set the style
    if ( isItDarkTheme ) {
        intent.putExtra("overrideTheme", 0);
    } else {
        intent.putExtra("overrideTheme", 1);
    }
    intent.putExtra("overrideCustomTheme", 0);

    try {
        startActivityForResult(intent, YOUR_REQUEST_CODE_PICK_ACCOUNT);
    } catch (ActivityNotFoundException e) {
        ...
    }

    ...

A: I had the same problem, but I finally found the solution. Take a look to AccountPicker.class, where are methods: newChooseAccountIntent() and zza();
You have to change
    AccountPicker.newChooseAccountIntent(null, null,
accountTypes, false, null, null, null, null);

to
    AccountPicker.zza(null, null,
accountTypes, false, null, null, null, null, false, 1, 0);

Last two arguments are for "overrideTheme" and "overrideCustomTheme". So set the first one to 1 and it will override the theme to light. :-)
Hope it helps.

A: My solution is
Intent intent = AccountPicker.a(null, null,accountTypes, true, null, null, null, null, false, 1, 0);


Q: gnuplot unable to run in XCode 4.3.1 Im trying to get gnuplot up running for C++ environment in XCode.
Im using following tutorial to archieve my result:
http://www.calozgroup.org/Shulabh/MediaWikiS/index.php5?title=Gnuplot_in_C%2B%2B_using_XCode

*

*I have created the libgnuplot.a and imported this along with the gnuplot_i.h into my project.

*Copied /opt/local/bin/gnuplot into /usr/local/bin

*I have created the ~/MacOSX/environment.plist file with following content:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DT$
<plist version="1.0">
<dict>
        <key>GNUTERM</key>
        <string>aqua</string>
        <key>PATH</key>
        <string>/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin</string>
</dict>
</plist>

The error occurs when compiling following sample code:
char myStr[] = "text";
char myEqu[] = "sin(x)";

gnuplot_ctrl *h;
h = gnuplot_init();
gnuplot_plot_equation(h, myEqu, myStr);
gnuplot_close(h);

Error:
cannot find gnuplot in your PATH(lldb)

Furthermore i was getting following compiler warnings:
Conversion from string literal to 'char *' is deprecated
gnuplot_setstyle(handle, "lines");

I tried to modify these to:
char line_string[] = "lines";
gnuplot_setstyle(handle, line_string);

A: I'm no expert on these things, but try adding:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DT$
<plist version="1.0">
<dict>
        <key>GNUTERM</key>
        <string>aqua</string>
        <key>PATH</key>
        <string>/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/local/bin</string>
</dict>
</plist>

(added /opt/local/bin to PATH)

A: I reinstalled gnuplot and it suddenly worked.

A: I had the same problem. gnuplot worked from the terminal, but not from c++.
The c++ code called getenv("PATH") and searched for "gnuplot" throwing an exception when it could not be found. After copying /opt/local/bin/gnuplot into /usr/local/bin, it didn't work as in your case.
But then I decided to also copy it into /usr/bin and this seems to work.
labjunky


Q: Check time changing automatic There is a streaming channel which displays for 24 hours per day and I want to display that for certain hours of day in my website. I use a code as bellow:
$now = date('G',time());
$start = 13;
$end = 14;
if($now >= $start && $now <= $end){
    echo "streaming video";
}
else{
echo "image";
}

It works when I do refresh/load page. But I want this program to check the time and do reactions without it is needed to do reload the page. So, when the time comes up to 14:00 the video will not being displayed anymore but the image instead of video and when the time comes to 13:00 to display video instead of image. Can be done with php or it is needed ajax or something else?
Waiting for some help.

A: Create a javascript function that performs an ajax call to a time function which can decide to set the stream or an image:

setInterval(function() {
    $.ajax({
        url : "/gettime.php",
        type: 'GET',
        success: function(data){
        //check time, if correct, set video to the div #stream-content otherwise, set an image as the content
        }
    });
}, 1000);


Q: How to change checkbox to required html format in pdfmake? I want to change the below html to required format as in below image,

        Recommendation:

                    {{recommendation.listTypeValueName}}

                        {{recommendation.listTypeValueName}}

Required Format

What I am getting from above html


Q: As imagens da minha conversão do FlowDocument para FixedDocument deixaram de aparecer Achei uma conversão de FlowDocument que passa para XPS e depois o coloca no meu FixedDocument para eu poder visualizar e imprimir, estava funcionando perfeitamente.
Porem agora as imagens não aparecem mais na impressão o que poderia ser?
            FlowDocument doc = new FlowDocument(); //FlowDocument com a imagem

            var paginator = ((IDocumentPaginatorSource)doc).DocumentPaginator;
            var package = Package.Open(new MemoryStream(), FileMode.Create, FileAccess.ReadWrite);
            var packUri = new Uri("pack://temp.xps");
            PackageStore.RemovePackage(packUri);
            PackageStore.AddPackage(packUri, package);
            var xps = new XpsDocument(package, CompressionOption.NotCompressed, packUri.ToString());
            XpsDocument.CreateXpsDocumentWriter(xps).Write(paginator);
            FixedDocument TESTE = xps.GetFixedDocumentSequence().References[0].GetDocument(true);

Desde já agradeço toda a ajuda.


Q: Apply Folder Icon Change I am attempting to change the icon of a folder. The code below does all what I found online says to do but the icon never changes. Am I maybe not "Applying" the change?
string createdFile = Path.Combine(@"C:\Users\np\Desktop\PUTEST", "desktop.ini");
if (File.Exists(createdFile))
{
    var di = new DirectoryInfo(createdFile);
    di.Attributes &= ~FileAttributes.ReadOnly;

    File.Delete(createdFile);
    File.Create(createdFile).Dispose();
}
else
{
    File.Create(createdFile).Dispose();
}

//string iconPath = @"%SystemRoot%\system32\SHELL32.dll";
string iconPath = Environment.ExpandEnvironmentVariables(@"%SystemRoot%\system32\SHELL32.dll");
string iconIndex = "-183";
using (TextWriter tw = new StreamWriter(createdFile))
{
    tw.WriteLine("[.ShellClassInfo]");
    tw.WriteLine("IconResource=" + iconPath + "," + iconIndex);
    //tw.WriteLine("IconFile=" + iconPath);
    //tw.WriteLine("IconIndex=" + iconIndex);

}

File.SetAttributes(createdFile, System.IO.FileAttributes.ReadOnly);
File.SetAttributes(createdFile, System.IO.FileAttributes.System);
File.SetAttributes(createdFile, System.IO.FileAttributes.Hidden);

A: When crafting a file like this it's always good to do so using Explorer or Notepad first, then write/adjust your code to match whatever was produced.  Otherwise, it's harder to figure out if the problem is with your file or your code.
I believe the minimum requirements to make this work is Desktop.ini must be marked System and the parent directory must be marked ReadOnly (System may work there as well, but I know ReadOnly definitely does).  So, your code is working with the right attributes, but there are still a few problems.
Your if ... else ... block is saying "If a file exists at this path, create a directory at that path, then delete the file at that path, then create a file at that path."  Of course, the directory should not and cannot have the same path as the file.  I assume you are deleting and recreating the file to clear the contents when it already exists, however File.Create() overwrites (truncates) existing files, making the calls to both File.Delete() and File.Exists() unnecessary.
More importantly is this line...
di.Attributes &= ~FileAttributes.ReadOnly;

...with which there are two problems.  First, you are ANDing the directory's attributes with the negation of ReadOnly, which has the effect of removing ReadOnly and keeping the other attributes the same.  You want to ensure ReadOnly is set on the directory, so you want to do the opposite of the code you used: OR the directory's attributes with ReadOnly (not negated)...
di.Attributes |= FileAttributes.ReadOnly;

Also, you need that attribute set regardless of whether you created the directory or not, so that line should be moved outside of the if ... else ....
Another issue is the successive calls to File.SetAttributes().  After those three calls the file's attributes will be only Hidden, since that was the value of the last call.  Instead, you need to combine (bitwise OR) those attributes in a single call.
A couple of other minor tweaks...

*

*As you know since you are calling Dispose() on it, File.Create() returns a FileStream to that file.  Instead of throwing it away, you could use it to create your StreamWriter, which will have to create one, anyways, under the covers.  Better yet, call File.CreateText() instead and it will create the StreamWriter for you.

*Environment variables are supported in Desktop.ini files, so you don't have to expand them yourself.  This would make the file portable between systems if, say, you copied it from one system to another, or the directory is on a network share accessed by multiple systems with different %SystemRoot% values.

Incorporating all of the above changes your code becomes...
// Create a new directory, or get the existing one if it exists
DirectoryInfo directory = Directory.CreateDirectory(@"C:\Users\np\Desktop\PUTEST");
directory.Attributes |= FileAttributes.ReadOnly;

string filePath = Path.Combine(directory.FullName, "desktop.ini");
string iconPath = @"%SystemRoot%\system32\SHELL32.dll";
string iconIndex = "-183";

using (TextWriter tw = File.CreateText(filePath))
{
    tw.WriteLine("[.ShellClassInfo]");
    tw.WriteLine("IconResource=" + iconPath + "," + iconIndex);
    //tw.WriteLine("IconFile=" + iconPath);
    //tw.WriteLine("IconIndex=" + iconIndex);
}

File.SetAttributes(filePath, FileAttributes.ReadOnly | FileAttributes.System | FileAttributes.Hidden);

One catch is that the above code throws an exception if you run it twice in succession.  This is because the File.Create*() methods fail if the input file is Hidden or ReadOnly.  We could use new FileStream() as an alternative, but that still throws an exception if the file is ReadOnly.  Instead, we'll just have to remove those attributes from any existing input file before opening it...
// Create a new directory, or get the existing one if it exists
DirectoryInfo directory = Directory.CreateDirectory(@"C:\Users\np\Desktop\PUTEST");
directory.Attributes |= FileAttributes.ReadOnly;

string filePath = Path.Combine(directory.FullName, "desktop.ini");
FileInfo file = new FileInfo(filePath);

try
{
    // Remove the Hidden and ReadOnly attributes so file.Create*() will succeed
    file.Attributes = FileAttributes.Normal;
}
catch (FileNotFoundException)
{
    // The file does not yet exist; no extra handling needed
}

string iconPath = @"%SystemRoot%\system32\SHELL32.dll";
string iconIndex = "-183";

using (TextWriter tw = file.CreateText())
{
    tw.WriteLine("[.ShellClassInfo]");
    tw.WriteLine("IconResource=" + iconPath + "," + iconIndex);
    //tw.WriteLine("IconFile=" + iconPath);
    //tw.WriteLine("IconIndex=" + iconIndex);
}

file.Attributes = FileAttributes.ReadOnly | FileAttributes.System | FileAttributes.Hidden;

I changed from using File to FileInfo since that makes this a little easier.


Q: python script to convert shapefiles in a folder to .kmz's with the SAME shapefile name Pretty new at working with python and am Stuck...I have a "for" Loop that looks in a folder and, based on a criteria (Homes valued over 500k), creates .kmz's with symbology for each of the .shp files in the folder. The script effectively creates the layers based on criteria and  applies symbology.  However I need help carrying the Name (fNAME) into the kmz's.  Can anyone help me complete this script?
Regards
Script:
~~~~~~~~~~~~~~~~~
import arcpy

from arcpy import env

# Variables
env.workspace = r"C:\Work\TEST\HOMES"

fcs = arcpy.ListFeatureClasses("D*", "Point")

HOMES_Lyr = r"C:\Work\TEST\HOMES\LAYER\HOMES.lyr"

arcpy.env.overwriteOutput=True

for fc in fcs:

    fNAME = arcpy.Describe(fc).basename+"_Green"
    arcpy.MakeFeatureLayer_management(fc,fNAME,"\"PRICE\" > 500000","","")
    arcpy.arcpy.ApplySymbologyFromLayer_management(fNAME,HOMES_Lyr)
    arcpy.LayerToKML_conversion(fNAME, ????.kmz, "12000", "false", "DEFAULT", "1024", "96", "CLAMPED_TO_GROUND")

~~~~~~~~~~~~~

A: You can do the following to name the kmz file and place it in the folder you want:
arcpy.LayerToKML_conversion(fNAME, "c:\\temp\\" + str(fNAME) + ".kmz", "12000", .....

or in the env.workspace but a new subfoler - if it exists:
arcpy.LayerToKML_conversion(fNAME, "KMZ\\" + str(fNAME) + ".kmz", "12000", .....


Q: Dealing with character variables containing semicolons in CSV files I have a file separated by semicolons in which one of the variables of type character contains semicolon inside it. The readr::read_csv2 function splits the contents of those variables that have semicolons into more columns, messing up the formatting of the file.
For example, when using read_csv2 to open the file below, Bill's age column will show jogging, not 41.
File:
name;hobbies;age
Jon;cooking;38
Bill;karate;jogging;41
Maria;fishing;32

Considering that the original file doesn't contain quotes around the character type variables, how can I import the file so that karate and jogging belong in the hobbies column?

A: read.csv()
You can use the read.csv() function. But there would be some warning messages (or use suppressWarnings() to wrap around the read.csv() function). If you wish to avoid warning messages, using the scan() method in the next section.
library(dplyr)

read.csv("./path/to/your/file.csv", sep = ";",
         col.names = c("name", "hobbies", "age", "X4")) %>%
  mutate(hobbies = ifelse(is.na(X4), hobbies, paste0(hobbies, ";" ,age)),
         age = ifelse(is.na(X4), age, X4)) %>%
  select(-X4)

scan() file
You can first scan() the CSV file as a character vector first, then split the string with pattern ; and change it into a dataframe. After that, do some mutate() to identify your target column and remove unnecessary columns. Finally, use the first row as the column name.
library(tidyverse)
library(janitor)

semicolon_file <- scan(file = "./path/to/your/file.csv", character())

semicolon_df <- data.frame(str_split(semicolon_file, ";", simplify = T))

semicolon_df %>%
  mutate(X4 = na_if(X4, ""),
         X2 = ifelse(is.na(X4), X2, paste0(X2, ";" ,X3)),
         X3 = ifelse(is.na(X4), X3, X4)) %>%
  select(-X4) %>%
  janitor::row_to_names(row_number = 1)

Output
   name        hobbies age
2   Jon        cooking  38
3  Bill karate;jogging  41
4 Maria        fishing  32

A: Assuming that you have the columns name and age with a single entry per observation and hobbies with possible multiple entries the following approach works:

*

*read in the file line by line instead of treating  it as a table:

tmp <- readLines(con <- file("table.csv"))
close(con)

*Find the position of the separator in every row. The entry before the first separator is the name the entry after the last is the age:

separator_pos <- gregexpr(";", tmp)
name <- character(length(tmp) - 1)
age <- integer(length(tmp) - 1)
hobbies <- vector(length=length(tmp) - 1, "list")

*fill the three elements using a for loop:

# the first line are the colnames
for(line in 2:length(tmp)){
     # from the beginning of the row to the first";"
     name[line-1] <- strtrim(tmp[line], separator_pos[[line]][1] -1)
     # between the first ";" and the last ";".
     # Every ";" is a different elemet of the list
     hobbies[line-1] <- strsplit(substr(tmp[line], separator_pos[[line]][1] +1,
                                        separator_pos[[line]][length(separator_pos[[line]])]-1),";")
     #after the last ";", must be an integer
     age[line-1] <- as.integer(substr(tmp[line],separator_pos[[line]][length(separator_pos[[line]])]+1,
                               nchar(tmp[line])))
}

*Create a separate matrix to hold the hobbies and fill it rowwise:

hobbies_matrix <- matrix(NA_character_, nrow = length(hobbies), ncol = max(lengths(hobbies)))
for(line in 1:length(hobbies))
    hobbies_matrix[line,1:length(hobbies[[line]])] <-  hobbies[[line]]

*Add all variable to a data.frame:

df <- data.frame(name = name, hobbies = hobbies_matrix, age = age)
> df
   name hobbies.1 hobbies.2 age
1   Jon   cooking      <NA>  38
2  Bill    karate   jogging  41
3 Maria   fishing      <NA>  32

A: You could also do:
read.csv(text=gsub('(^[^;]+);|;([^;]+$)', '\\1,\\2', readLines('file.csv')))

   name        hobbies age
1   Jon        cooking  38
2  Bill karate;jogging  41
3 Maria        fishing  32

A: Ideally you'd ask whoever generated the file to do it properly next time :) but of course this is not always possible.
Easiest way is probably to read the lines from the file into a character vector, then clean up and make a data frame by string matching.
library(readr)
library(dplyr)
library(stringr)

# skip header, add it later
dataset <- read_lines("your_file.csv", skip = 1)

dataset_df <- data.frame(name = str_match(dataset, "^(.*?);")[, 2],
                         hobbies = str_match(dataset, ";(.*?);\\d")[, 2],
                         age = as.numeric(str_match(dataset, ";(\\d+)$")[, 2]))

Result:
   name        hobbies age
1   Jon        cooking  38
2  Bill karate;jogging  41
3 Maria        fishing  32

A: Using the file created in the Note at the end
1) read.pattern can read this by specifying the pattern as a regular expression with the portions within parentheses representing the fields.
library(gsubfn)
read.pattern("hobbies.csv", pattern = '^(.*?);(.*);(.*)$', header = TRUE)
##    name        hobbies age
## 1   Jon        cooking  38
## 2  Bill karate;jogging  41
## 3 Maria        fishing  32

2) Base R Using base R we can read in the lines, put quotes around the middle field and then read it in normally.
L <- "hobbies.csv" |>
  readLines() |>
  sub(pattern = ';(.*);', replacement = ';"\\1";')
read.csv2(text = L)
##    name        hobbies age
## 1   Jon        cooking  38
## 2  Bill karate;jogging  41
## 3 Maria        fishing  32

Note
Lines <- "name;hobbies;age
Jon;cooking;38
Bill;karate;jogging;41
Maria;fishing;32
"
cat(Lines, file = "hobbies.csv")


Q: Can we treat proper classes in a well-defined way that has them behave as ordinal numbers? (1) Can we treat proper classes in a well-defined way that has them behave as ordinal numbers, where we can have arithmetic and some new notion of cardinality unique to proper classes, going higher and higher? (2) Can we do such within surreal numbers as a proper class? (3) If so, can we, like we do with ordinals, imagine infinitely more proper classes, that might aid in realizing the scope of how far we can make extendable the surreals, and proper classes themselves for that matter, indefinitely, beyond a notion of proper class?

A: A set theorist may have more to say, but here's my understanding:
(1) The only proper class that's like an ordinal would be the class of all ordinals. And then you can't take the successor. If you wanted to define cardinality as "the least ordinal such that..." then you only get one more "cardinality" for proper classes from this.
If you have something like the axiom of limitation of size then that one new cardinality is enough for all the proper classes. But if you don't have such an axiom, then you could end up with proper classes that the class of all ordinals doesn't "count", even if you had the axiom of choice at the level of sets.
(2) I'm not sure what you mean, but you could put the ordinals (as surreals) in the left position to form a "gap" greater than all surreals.
(3) As in the answer to (1), it doesn't really make sense to go any farther.

A: To complete Mark S.' answer, there are (say in NBG set theory) proper classes equipped with a well-ordering, which contain a proper initial segment isomorphic to the class $\mathbf{On}$ of ordinals.
For instance take the class $\mathbf{On}\times \mathbf{On}$ of ordered pairs of ordinals, with the lexicographic order. So $\mathbf{On} \times \{0\}$ is an initial segment of $\mathbf{On}\times \mathbf{On}$.
But since $\mathbf{On}$ cannot lie in a class (because classes only contain sets), there is no "generalized" ordinal which is isomorphic the class $\mathbf{On}\times \mathbf{On}$.
I don't know if there are ways to generalize the notion of ordinals so that for instance there exist a unique ordinal isomorphic to $\mathbf{On} \times \mathbf{On}$ as previously defined.

A: A 'solution' to the problem nombre pointed out is to just define an ordinal as a set or class with a well-order, and then we can define equivalence, and the ordinal operations. The downside of this approach is that every ordinal has multiple representations, and the standard solution "let an ordinal be an equivalence class" doesn't work, because classes can't contain other classes. However, this approach allows one to define more ordinals, such as $\mathrm{On}^2$.
Another approach, which isn't obvious and I haven't seen before, is to use not a class theory, but Tarski-Grothendieck set theory. If we let $V$ be a Grothendieck universe, then $P(V)$ (I think) is a model of NBG, and thus $\{x\in V:x\text{ is an ordinal}\}$ behaves like $\mathrm{On}$. This approach allows defining generalized ordinals even further. For example, there isn't even a bijection from the ordinal $\{x\in P(V):x\text{ is an ordinal}\}$ to $\{x\in V:x\text{ is an ordinal}\}$. And then there's always a Grothendieck universe containing $V$...


Q: Implementing Tree Structure in a UITableView I want to implement a tree structure in a UITableView something like
 Item-1
     subItem-1
     subItem-2
 Item-2
 Item-3
     subItem-1
     subItem-2

but I don't want to use custom cells for this.
I have done lot of Googling for this but I got one link which said I would have to use custom cells.
If anyone has any ideas please can you shared them with me.
Thanks in advance.

A: A table view isn't really designed to display hierarchical views. What's supposed to happen is that you drill down (push a new view controller on the stack) to get to the next level of the hierarchy.
However, if your hierarchy is only as deep as you suggest, then you could have your items as headers and subitems as rows. If you don't want to create a custom view (why not?) you'd be limited to just text for your top level items.


Q: Can spacetime be thought as a field associated with gravitons? Researching, I found that gravitational waves are generated by the changing in time of the quadrupole moment of mass of a system - source.
They travel at speed of light, and they perturbate the spacetime where they are. But the spacetime is statically deformed when a mass is present in it, even if the mass has not a time-varying quadrupole moment.
These characteristics are very similar to that of an electric field which can be static if in presence of a non-moving charged particle and has perturbations whenever a charge is accelerated.
Can spacetime be thought as a field exerted by mass and perturbated by gravitons?

A: Actually it seems so. There is this theory done by M. Novello and R. P. Neves which gives a solid structure to this idea, differently from the attempt Gravitation book. It is quite recent, march 2018, and this is the link to the article.


Q: Make Horizontal Indeterminate ProgressBar a Fixed Width I currently have a horizontal ProgressBar defined in XML as below, that I am using to show the progress of an item loading:
<ProgressBar
    android:id="@+id/loading_progressbar"
    style="@style/Widget.AppCompat.ProgressBar.Horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:indeterminate="true"
    android:indeterminateBehavior="repeat"
    android:indeterminateDuration="1000"
 android:indeterminateDrawable="@drawable/custom_loading_progressbar" />

Here is the custom drawable to allow me to colour the ProgessBar how I wish:
<?xml version="1.0" encoding="UTF-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@android:id/background">
        <shape android:shape="rectangle">
            <solid android:color="@color/black" />
            <size android:height="2dp" />
        </shape>
    </item>
    <item android:id="@android:id/secondaryProgress">
        <clip>
            <shape android:shape="rectangle">
                <solid android:color="@color/black" />
                <size android:height="2dp" />
            </shape>
        </clip>
    </item>
    <item android:id="@android:id/progress">
        <clip>
            <shape android:shape="rectangle">
                <solid android:color="@color/white" />
                <size android:height="2dp" />
            </shape>
        </clip>
    </item>
</layer-list>

The issue I have with the current indeterminate implementation is that it pulses between being a small width and a larger width. This can be seen in the second ProgressBar at this link:
https://materialdoc.com/images/linear-progress-1.gif
I purely want to be able to specify a width of 100dp and allow it to keep cycling through its repeats until complete.
Is there any way to set a fixed width for an indeterminate ProgressBar?


Q: SharePoint Foundation 2010  in a multiple forest environments of Active Directory Domain Services? Can i set up a SPF 2010 to use 2 active directory domain? If yes how to?
Regarding user and groups will it populate users from both ADs?
Will i  be able to select users from both ADs for permission purposes.
Thanks in advance

A: This TechNet article gives a good introduction to the subject:
http://technet.microsoft.com/en-us/library/dd279546.aspx


Q: Cant Download anything I am currently on ubuntu 14.04 and I am trying to download steam launcher but when I try I get a screen that reads.
"The package system is broken
 Check if you are using third party repositories. If so disable them, since they are a common source of problems.
Furthermore run the following command in a Terminal: apt-get install -f"

and when I open details it reads.
"The following packages have unmet dependencies:

linux-image-extra-3.13.0-73-generic: Depends: linux-image-3.13.0-73-generic but it is not installed
linux-image-generic: Depends: linux-image-3.13.0-73-generic but it is not installed"

Please Help Thank You.
Filesystem                          Size  Used Avail Use% Mounted on
udev                                914M  4.0K  914M   1% /dev
tmpfs                               185M  940K  184M   1% /run
/dev/mapper/ubuntu--kylin--vg-root  292G   43G  235G  16% /
none                                4.0K     0  4.0K   0% /sys/fs/cgroup
none                                5.0M     0  5.0M   0% /run/lock
none                                924M  184K  924M   1% /run/shm
none                                100M   44K  100M   1% /run/user
/dev/sda1                           236M  236M     0 100% /boot
izzy-22@Randys-PC:~$

A: It looks like your problem is that some of your packages depend on other ones and this is causing apt to get stuck. I'd say open terminal and run sudo apt install linux-image-3.13.0.73-generic, because that package is not installed and seems to be the cause of the problems. Just install that package and then report back whether it worked. It should resolve that dependency error.
Now looking at edits in the question, your /boot is full, so try running,
sudo apt-get autoremove
to remove old kernels and initrds stored there. Then run
sudo apt-get install linux-image-3.13.0.73-generic.
This should fix the dependency problems


Q: Why does no one use the notation $f(x)^2$? It seems to me that "$f(x)^2$" couldn't mean anything other than "$[f(x)]^2$", so there shouldn't be any ambiguity involved, but people always tend to put an extra pair of brackets around the "$f(x)$" everywhere I see it squared. Is there a reason for this?

A: The primary concern is that the parenthesized quantity will be viewed as squared, rather than the function. There can be ambiguity when you're unsure of whether the person is being sloppy by considering the argument as squared and just leaving off the brackets around $(x)^2$.


Q: How to validate click one per browser? How can i reduce raiting to be able to rate only once per browser?
I need to make validation for raiting component in React where client can rate only once per browser.
Here is example of the rating component:
export default function App() {
  const [value, setValue] = React.useState(0);
  return (

      <Box component="fieldset" mb={3} borderColor="transparent">
        <Typography component="legend">Rate</Typography>
        <Rating
          name="pristine"
          value={value}
          onClick={(e) => setValue(e.target.value)}
        />
      </Box>

  );
}

Here is sandbox link of the component  sandbox link

A: One possible solution you could think of is to use localStorage
For every user, who has already rate, you then store a boolean to the local storage.
Then next time, it will be validated first
Something like this:
export default function App() {
  const [value, setValue] = React.useState(0);
  const hasRated = localStorage.getItem("hasRated");

  const handleRate = (e) => {
    setValue(e.target.value);
    localStorage.setItem("hasRated", true);
  };
  return (

      <Box component="fieldset" mb={3} borderColor="transparent">
        <Typography component="legend">Rate</Typography>
        <Rating
          disabled={hasRated}
          name="pristine"
          value={value}
          onClick={handleRate}
        />
      </Box>

  );
}

Please note, that this is only a demonstrated example, so it supposes that you will need to have some improvement based on your needs
Sanbox Example:


Q: Predicting images Jupyter notebook For my first Machine Learning experience i have a basic classification to do.
I have 3 different folders :
train_path = './dataset/pneumonia/train/'
test_path = './dataset/pneumonia/test/'
val_path = './dataset/pneumonia/val/

each folders :
os.listdir(train_path)

returns
['NORMAL', 'PNEUMONIA']

In each sets :

*

*Training set:

*

*Normal:  949

*Pneumonia:  949

*Test set:

*

*Normal:  317

*Pneumonia:  317

*Validation set:

*

*Normal:  317

*Pneumonia:  317

I use tensorflow :
from tensorflow.keras.preprocessing.image import ImageDataGenerator
image_gen = ImageDataGenerator(
    rotation_range=10,        # rotate the image 10 degrees
    width_shift_range=0.10,   # Shift the pic width by a max of 5%
    height_shift_range=0.10,  # Shift the pic height by a max of 5%
    rescale=1/255,            # Rescale the image by normalzing it.
    shear_range=0.1,          # Shear means cutting away part of the image (max 10%)
    zoom_range=0.1,           # Zoom in by 10% max
    horizontal_flip=True,     # Allow horizontal flipping
    fill_mode='nearest'       # Fill in missing pixels with the nearest filled value
)

image_gen.flow_from_directory(train_path)
image_gen.flow_from_directory(test_path)

I create a model (basic model) :
model = Sequential()

model.add(Conv2D(32, (3, 3), input_shape=(image_width, image_height, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(64, (3, 3), input_shape=(image_width, image_height, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(128, (3, 3), input_shape=(image_width, image_height, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(256, (3, 3), input_shape=(image_width, image_height, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(512, (3, 3), input_shape=(image_width, image_height, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Flatten())
model.add(Dense(512, activation='relu'))

# Dropouts help reduce overfitting by randomly turning neurons off during training.
# Here we say randomly turn off 50% of neurons.
model.add(Dropout(0.5))

# Last layer, remember its binary so we use sigmoid
model.add(Dense(1, activation='sigmoid'))

model.compile(loss='binary_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])

Then I train it :
train_image_gen = image_gen.flow_from_directory(
    train_path,
    target_size=image_shape[:2],
    color_mode='rgb',
    batch_size=batch_size,
    class_mode='binary'
)

results = model.fit_generator(train_image_gen,epochs=20,
                              validation_data=test_image_gen,
                             callbacks=[early_stop, board])

So far so good results are correct :
pred_probabilities = model.predict_generator(test_image_gen)
predictions = pred_probabilities > 0.5
confusion_matrix(test_image_gen.classes,predictions)

I obtain rather good results :

My issue is when I want to predict images it returns results which are far from being correct:
val_image_gen = image_gen.flow_from_directory(
    val_path,
    target_size=image_shape[:2],
    color_mode='rgb',
    class_mode='binary',
)

pred_probabilities = model.predict_generator(val_image_gen)
predictions = pred_probabilities > 0.5

Here are some output I obtain :
              precision    recall  f1-score   support

           0       0.51      0.57      0.53       317
           1       0.51      0.44      0.47       317

    accuracy                           0.51       634
   macro avg       0.51      0.51      0.50       634
weighted avg       0.51      0.51      0.50       634

THe confusion matrix on this data set is the following :
[[180 137]
 [176 141]]

A: A few issues with your code:

*

*You are using test set for validation and validation set for testing.
This may be a problem or not, depending on your data and how it was
split.

*Augmentation should be applied only to training set. Use    separate
instance of ImageDataGenerator(rescale=1/255) for testing    and
validation.

Your test results look like they were got from untrained model. Check if the model object you are running test on is the same one you were training. You may want to use model.save() and load_model() functions to preserve model weights after training.

A: I replaced :
val_image_gen = image_gen.flow_from_directory(
    val_path,
    target_size=image_shape[:2],
    color_mode='rgb',
    class_mode='binary',
)

by:
val_image_gen = image_gen.flow_from_directory(
    val_path,
    target_size=image_shape[:2],
    color_mode='rgb',
    batch_size=batch_size,
    class_mode='binary',
    shuffle=False
)

I obtain nice results :
[[269  48]
[  3 314]]


Q: Differentiable limit theorem of a Continuous nowhere differentiable function I am looking at Abbott's second edition of Understanding Analysis, and I am unsure if my answer is accurate.
Exercise:
The function $g(x) =\sum_{n=0}^{\infty} \frac{\cos (2^{n}x)}{2^{n}}$
has been used as an example of a continuous nowhere differentiable function. What happens if we try to use the Differentiable Limit Theorem to explore whether g is differentiable?
My solution:
$g(x) =\sum_{n=0}^{\infty} \frac{\cos (2^{n}x)}{2^{n}}$
$g'(x) =\frac{d}{dx}\sum_{n=0}^{\infty} \frac{\cos (2^{n}x)}{2^{n}}=\sum_{n=0}^{\infty}\frac{d}{dx} \frac{\cos (2^{n}x)}{2^{n}}$
Consider the nth term
$y =\frac{\cos (2^{n}x)}{2^{n}}$
Let $\Delta x$ be a small increment given to $x$, and $\Delta y$ the corresponding increment in $ y.$
$\Delta y=\frac{\cos (2^{n}(x+\Delta x))}{2^{n}}-\frac{\cos (2^{n}x)}{2^{n}}$
$=\frac{1}{2^n}(-2 \sin 2^{n-1}(2x+\Delta x) \sin 2^{n-1}\Delta x)$
Divide by $\Delta x$
$\frac{\Delta y}{\Delta x}=\frac{1}{\Delta x}\frac{1}{2^n}(-2 \sin 2^{n-1}(2x+\Delta x) \sin 2^{n-1}\Delta x)$
As $\Delta x$ tends to $0$, $\frac{\sin \Delta x}{\Delta x}$ tends to $1$
$=\frac{\Delta y}{\Delta x}=\frac{1}{2^n}(-2 \sin 2^{n-1}(2x+\Delta x))2^{n-1}$
$= (-2 \sin 2^{n-1}(2x))$
Thus it gives some answer for derivative of nth term

A: The Relevant Thm, "Term-by-term differentiability thm" (6.4.3), can't be used to justify interchanging the infinite sum and derivative.
In the setup of the theorem, you have $$f_n(x)=\frac{\cos (2^n x)}{2^n}, \text{ for }n=0,1,...$$
A key hypothesis of the theorem is that $\sum_{n=0}^\infty f_n '(x)=- \sum_{n=0}^\infty \sin(2^n x)$ converges uniformly on an interval [a,b] that you're interested in, but in fact it doesn't even converge pointwise on any interval.


Q: want to change the cursor on mouse move on JTree listed elements I want to change the cursor to hand cursor on mouse move over JTree component when the cursor is on listed elements only, not for the whole component.
The below code is for Jlist Component. I want same for the JTree, but JTree does not have getCellBound().  Is there any other way?
final JList list = new JList(new String[] {"a","b","c"});
list.addMouseMotionListener(new MouseMotionListener() {
@Override
public void mouseMoved(MouseEvent e) {
    final int x = e.getX();
    final int y = e.getY();
    // only display a hand if the cursor is over the items
    final Rectangle cellBounds = list.getCellBounds(0, list.getModel().getSize() - 1);
    if (cellBounds != null && cellBounds.contains(x, y)) {
        list.setCursor(new Cursor(Cursor.HAND_CURSOR));
    } else {
        list.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
    }
}

@Override
public void mouseDragged(MouseEvent e) {
}
});

A: You are looking for something like this, I guess:
import java.awt.Cursor;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;

public class TestTreeSelection {

    protected void initUI() {
        final DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
        fillTree(root, 5, "Some tree label");
        final DefaultTreeModel model = new DefaultTreeModel(root);
        final JTree tree = new JTree(model);
        tree.addMouseMotionListener(new MouseAdapter() {
            @Override
            public void mouseMoved(MouseEvent e) {
                boolean inside = false;
                TreePath path = tree.getPathForLocation(e.getX(), e.getY());
                if (path != null) {
                    Rectangle pathBounds = tree.getPathBounds(path);
                    inside = pathBounds.contains(e.getPoint());
                }
                if (inside) {
                    tree.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                } else {
                    tree.setCursor(Cursor.getDefaultCursor());
                }
            }
        });
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(new JScrollPane(tree));
        f.setSize(400, 600);
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    private void fillTree(DefaultMutableTreeNode parent, int level, String label) {
        for (int i = 0; i < 5; i++) {
            DefaultMutableTreeNode node = new DefaultMutableTreeNode(label + " " + i);
            parent.add(node);
            if (level > 0) {
                fillTree(node, level - 1, label);
            }
        }
    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new TestTreeSelection().initUI();
            }
        });
    }

}

A: This code works:
        tree_object.addMouseMotionListener(new MouseMotionListener() {

                @Override
                public void mouseDragged(MouseEvent e) {

                }

                @Override
                public void mouseMoved(MouseEvent e) {
                    TreePath tp = ((JTree)e.getSource()).getPathForLocation(e.getX(), e.getY());

                    if(tp != null)
                    {
                        ((JTree)e.getSource()).setCursor(new Cursor(Cursor.HAND_CURSOR));
                    }
                    else
                    {
                        ((JTree)e.getSource()).setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
                    }
                }
         });


Q: Flutter Web: Divider color not showing when scrolling page In my flutter project, the Divider widget color is not showing when scrolling.
The issue exists only in flutter web project.

A: Since last two years I have been using this divider code below. It working well for all platforms. To fix your issue, provide your code.
Widget commonDividerWidget(Color color) {
  return Divider(
    thickness: 1.0,
    color: color,
  );
}


Q: Scala how to convert Map to varargs of tuples? In the context of Scala Play 2.2.x testing I have a Map[String, String] which I need to pass to a function that accepts (String, String)* i.e. a varargs of (String, String) tuple.
e.g.
val data : Map[String, String] = Map("value" -> "25", "id" -> "", "columnName" -> "trades")
route(FakeRequest(POST, "/whatever/do").withFormUrlEncodedBody(data))

but this gives a type mismatch because withFormUrlEncodedBody accepts only a (String, String)* type.

A: Simply:
def foo(names: (String, String)*) = names.foreach(println)
val folks = Map("john" -> "smith", "queen" -> "mary")
foo(folks.toSeq:_*)
// (john,smith)
// (queen,mary)

Where _* is a hint to compiler.

A: Oh found the answer e.g.
route(FakeRequest(POST, "/wharever/do").withFormUrlEncodedBody(data.toList: _*))

or
route(FakeRequest(POST, "/wharever/do").withFormUrlEncodedBody(data.toSeq: _*))

or
route(FakeRequest(POST, "/wharever/do").withFormUrlEncodedBody(data.toArray: _*))


Q: javascript showing old events I am having some trouble with javascript event handling. In my application I have an event which makes external xml requests and gives a responce to my event listener. This is allowed to happen many times to the same event listener. My event listener is repeating functions for old copies of my event and repeating all of my functions on each of them.
Here is my code:
    document.addEventListener("data", getRemoteDataEvent, false);

    function getRemoteDataEvent(event){
    console.log(event);
    if(event.success===false){
        console.log(event);
        alert("error obtaining remote data");
    } else if(event.response != "<query_result></query_result>"){
        var xml = $.parseXML(event.response);
        parseThis(xml);
    }  else if(event.response == "<query_result></query_result>"){
        console.log(event.response);
        alert("Sorry, we have not yet come to your area");
    }
}

has anyone else run into this issue before?
edit: to show the remaining bits of my function. noting too important here, however do you see me missing a step in handling this?

A: You're probably adding the event listener each time you send the request. If you do, you should remove the listener when it finally runs, or just add it once.


Q: Guidance for the math used in phys My goal is to be become a physicist but I am concerned about my math skills (i am pretty decent in maths) ,i know the computational part but I'm not good in geometric or intuitive part of it,so i decided that i must be thorough in both the numbers and the concepts that govern them ,but I don't know where to start,like from which chapter do i need to understand in an intuitive way,can someone suggest a hierarchy/order for learning maths in intuitive way from basics to advanced?,it would be helpful....


Q: load page at anchor, less 175px When loading a page from a link using an anchor (ie, website.com/#midPage), I need the anchor to actually load 175px below the top of the page. Is there a convenient way to to do this? Javascript or JQUERY is fine by me, but I don't know what method to use.


Q: Call two relational tables in a singe id in Laravel. (check photos) I am trying to combine the below responses into a single entry

Here i got two keys but how i will make it in a single key.

In my controller i specified id for two different resources for author and authorprofile. But how can i use with single resourse because author and author profile is in relationship tables.

The resource attributes in the screenshot please check.

A: Hey its better to use Eloquent Relation like if you have Author Model and AuthorProfile Model so you put below method in Author model
public function Authorprofile(){
return $this->belongsTo(AuthorProfile::class, 'authorprofile_id');
}

then use in Controller like.
public function show($id){
 $author = Author::with('Authorprofile')->find($id)
}

Hope it mights help


Q: ValueError: could not broadcast input array from shape in python 2.7 I'm a newbie in using python 2.7.
I run this command
python plot_bands_gnu.py

but get
Traceback (most recent call last):
  File "plot_bands_gnu.py", line 16, in <module>
    ebands [:,ib] = databands[idx1:idx2,1]
ValueError: could not broadcast input array from shape (50) into shape (60)

How to solve this?


Q: Show Currency Symbol after values I am using CultureInfo methods to successfully format all different currencies into their correct format.
But on some exceptions, such as EUR and SEK currencies I need to be able to add them after the value. At the moment my CultureInfo is formatting them in the following way: "SEK 1.00,00" when it needs to be "1.00,00 SEK".
Any help is appreciated.

A: All you need is to change the NumberFormatInfo.CurrencyPositivePattern and NumberFormatInfo.CurrencyNegativePattern properties for the culture.
Just clone the original culture:
CultureInfo swedish = new CultureInfo("sv-SE");
swedish = (CultureInfo)swedish.Clone();
swedish.NumberFormat.CurrencyPositivePattern = 3;
swedish.NumberFormat.CurrencyNegativePattern = 3;

and then
var value = 123.99M;
var result = value.ToString("C", swedish);

should give you desired result. This should get you:

123,99 kr

A: Be careful about the CurrencyNegativePattern
This code
CultureInfo swedish = new CultureInfo("sv-SE");
swedish = (CultureInfo)swedish.Clone();
swedish.NumberFormat.CurrencyPositivePattern = 3;
swedish.NumberFormat.CurrencyNegativePattern = 3;

Will give you

134,99 kr.
kr.134,99kr.-

Changing CurrencyNegativePattern to 8
swedish.NumberFormat.CurrencyNegativePattern = 8;

Will give you

134,99 kr.
-134,99 kr.

More info https://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.currencynegativepattern(v=vs.110).aspx

A: string.Format(CultureInfo.CurrentCulture, "{0:C}", moneyValue.DataAmount)


Q: Ajax doesn't work in IE if URL contains Arabic character In my Blogger website I load posts from JSON feed, The JSON link looks like this.
    http://technopress-demo.blogspot.com/feeds/posts/default/-/LABEL NAME?alt=json-in-script&max-results=5

This is the code that I use to get posts from the URL above.
    $.ajax({url:""+window.location.protocol+"//"+window.location.host
    +"/feeds/posts/default/-/"+LABEL NAME
    +"?alt=json-in-script&max-results=5",
    type:'get',dataType:"jsonp",success:function(data){}

The problem is that when I change 'LABEL NAME' with an Arabic label the posts didn't load. I tested it with English label and it's working fine, but I have problem with Arabic ones. I have tried this to decode URL but it's not working.
    $.ajax({url:""+window.location.protocol+"//"+window.location.host
    +"/feeds/posts/default/-/"+encodeURIComponent(LABEL NAME)
    +"?alt=json-in-script&max-results=5",
    type:'get',dataType:"jsonp",success:function(data){}

This is a live demo of the problem.

A: IE has problems with not properly encoded URLS, it has also problems with simple <a href containing unencoded chars.
LABEL%20NAME instead of LABEL NAME should work.
With JSONP, jQuery generates a <script src="http://technopress-demo.blogspot.com/feeds/posts/default/-/LABEL NAME?alt=json-in-script&max-results=5"> which has the unencoded char in it.
Instead of encodeURIComponent(LABEL NAME), use quotation marks:
encodeURIComponent("LABEL NAME")

Important: Save your files UTF-8 encoded.
 (pic from blog.flow.info)
Example which works in IE  (copied from Firefox+Firebug):

A: In your live demo, removing
.shortext {
    text-indent: -9999px;
}

From the css makes it look OK in IE for me. The div with id="recent" and class="recent shortext" seems to have different markup in FF.


Q: My code is freezing and using to much CPU power. (Python) I am attempting to make a sort of AI like script which will figure out your phrase. It is still a work in progress and is not yet complete.
Each guess should print the following info:
The text produced: ......... The string generated by the script.
The length of the text: ... The length of the previously mentioned string.
The score of the text: ..... The script will score the text based on how long it is and what letters are in it.
The target text: ................. The text it is trying to produce.
For some reason, after the first string the code freezes. I am hoping anyone can help, Thanks in advance!
import random

posAlpha = ["a", "b", "c", "d", "e", "f", "g", "h",
            "i", "j", "k", "l", "m", "n", "o", "p",
            "q", "r", "s", "t", "u", "v", "w", "x",
            "y", "z", "A", "B", "C", "D", "E", "F",
            "G", "H", "I", "J", "K", "L", "M", "N",
            "O", "P", "Q", "R", "S", "T", "U", "V",
            "W", "X", "Y", "Z", "!", "?", ",", ".",
            " ", "&", "0", "1", "2", "3",
            "4", "5", "6", "7", "8", "9"]

def scoreText(input, goal):
    output = 0-abs(len(input)-len(goal))
    for i in range(len(min(input, goal, key=len))):
        if not (input[i] in goal):
            output+=0
        elif not (input[i] == goal[i]):
            output += 1
        else:
            output += 2
    if output < 1:
        return 1
    else:
        return output

goal = input("Target phrase: ")
score = 0
Ai=""
for i in range(random.randrange(round(len(goal)*0.5), len(goal)*2)):
    Ai = Ai+ random.choice(posAlpha)

score = scoreText(Ai, goal)
print("Result:        " + Ai)
print("Result Length: " + str(len(Ai)))
print("Goal:          " + goal)
print("Score:         " + str(score))
print()

while True:
    oldAi = Ai
    Ai = ""
    for i in range(len(Ai)-1):
        if (score == 1 or random.randrange(1, score) == 1):
            Ai = Ai+random.choice(posAlpha)
        else:
            Ai = Ai+oldAi[i]
    while True:
        lenVariation=random.randrange(-4, 4)
        if not (len(Ai)+lenVariation > len(goal)*2 or len(Ai)+lenVariation<round(len(goal)*0.5)):
            if lenVariation > 0:
                for i in range(lenVariation):
                    Ai = Ai+ random.choice(posAlpha)
                    break
            elif lenVariation < 0:
                for i in range(lenVariation):
                    AI=Ai[:-1]
                    break
    score = scoreText(Ai, goal)
    print("Result:        " + Ai)
    print("Result Length: " + str(len(Ai)))
    print("Goal:          " + goal)
    print("Score:         " + str(score))
    print()
input("Goal Achived!!")

A: It is because the execution is stuck in the second infinite loop. The condition (len(Ai)+lenVariation > len(goal)*2 or len(Ai)+lenVariation<round(len(goal)*0.5)) is met every time after the first execution so the if statement is never evaluated to True and the while loop is never exited.
Also, note that your break statements only exist the for loop and not the while loop so statements after the second break are never executed.


Q: Netstat -b shows open connections for an old (not used) project from totally unrelated apps See screenshot below:

In netstat -b output I always see open connections to an old project I developed 2 years ago. They also show when I open new applications (you see totally unrelated apps listening to the connection, like viber). How do I get rid of these "ghost" (to me) connections and why does this happen?
Thank you!


Q: Voice profile in Google Assistant Does Google Assistant provide individual voice identification, just like voice profile of Alexa?
Thank you

A: The Google Assistant does not provide user recognition as a core part of the platform or as part of the Assistant SDK.


Q: Java - gov.nasa.jpf.jvm.Verify Pathfinder Package Doesn't Exist I am attempting use Java Pathfinder and I have pathfinder working.
import gov.nasa.jpf.jvm.Verify;

user.java:2: package gov.nasa.jpf.jvm does not exist
import gov.nasa.jpf.jvm.Verify;

I need to use the Verify.random function. Can anyone tell me how to resolve this problem? I don't really understand how the importation of what I am assuming is a URL works.

A: Having used Java Pathfinder some time back, I know that its not an applet as the other answer worries.
You are getting this error because the Java Pathfinder jar files are not on your classpath. Here is a complete Java Pathfinder Getting Started tutorial that could help others coming to this old thread.

A: It's not a URL at all (except in the case of applets, and you didn't mention an applet). You need to put the Pathfinder jar in the classpath when compiling and running, via -cp to javac and java.
If it's an applet, it's more complex.


Q: sed line matching with exclamation I am trying to understand this sed line matching part.  What does it do exactly.  The patters is supposed to match comment lines starting with ## and attempt to remove the comment characterrs at the front of the line.
  pn_ere="^[[:space:]]*([#;!]+|@c|${cmt})[[:space:]]+"

  sed -E -n "
    /$beg_ere/ {
      :L1
      n
      /$end_ere/z
      /$pn_ere/!z
      s/// ; p
      tL1
    }
  "


Q: railflow cli command ignores the cucumber steps with data table. and only shows one line we just started using testrail with railflow and I am using railflow cli command to create test cases that are written in cucumber/gherkin style. Test results are converted into json files and railflow cli reads those json files and create test cases in test rail. up to this point, everything works fine. However, recently realized that test scenarios where I use data table are not being transferred to my test case in test rail. Anyone had similar issue or suggesting any solution for this?
Here is cucumber step:
Then I verify "abc" table column headers to be
| columnName  |
| Subject     |
| Report Data |
| Action      |
| ER Type     |
in test rail, it only includes the header which is " Then I verify "abc" table column headers to be
"
any suggestion is appreciated.

A: we are constantly improving Railflow and reports handling, so we are more than happy to add support for the cucumber data tables.
Please contact the support team via our website
Update: This is now implemented and available in Railflow NPM CLI v. 2.1.12


Q: Does google map geo location require secure ssl connection? I am using google map geo location api. I have first tested it on local, its working file on both firefox and chrome. When it moved it to live site (that is not https), its working fine for firefox but not working on chrome. Getting this error:

Geocoder failed

Here is my code:
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>

<script type="text/javascript">
    var geocoder;

    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
    }
    //Get the latitude and the longitude;
    function successFunction(position) {
        var lat = position.coords.latitude;
        var lng = position.coords.longitude;
    }

    function errorFunction() {
        alert("Geocoder failed");
    }
</script>

Does chrome need secure ssl connection for geo location??

A: For Chrome version >= 50, Geolocation API requires secured origin. But, it should work fine on your localhost.
Secured origins are origins that match the following (scheme, host, port) patterns:

*

*(https, *, *)

*(wss, *, *)

*(*, localhost, *)

*(*, 127/8, *)

*(*, ::1/128, *)

*(file, *, —)

*(chrome-extension, *, —)

You can read more about it here.
Update: Firefox, iOS Safari, Chrome Android, and Samsung Internet now also require secured contexts.


Q: Rails/coffeescript/datatables, after changing views, need to refresh to reload I'm sorry for asking this here as I typically find everything I need to ask, but I think my problem is I do not know really WHAT to search for to get the answer.   Here goes.   I am playing with datatables to provide sorted/ajaxified/searchable tables.   Everything loads correctly when I hit the site.   It is fine after I add data to the table or sort or search.
But, if I navigate from the page, say back to the home page, and then back to the page with the table, the table is still there, but the datatables stuff is gone.   I assume this is a matter of me JUST starting to work with JS/Ajax and the like for my Rails app and I probably am just in need of something very simple.
The specific code I'm using is:
$ ->
$("#customers").dataTable
sDom: "<'row-fluid'<'span6'l><'span6'f>r>t<'row-fluid'<'span6'i><'span6'p>>"
sPaginationType: "bootstrap"

If I watch the page load, I think I see the issue.   When it loads initially, or any time I send it back after adding a new customer, I see all the JS and CSS files load.  But, when I hit back, it's a cached call and it's not loading any of those again, so, I'm assuming I'm not "initializing" the JS again.
Any help would be appreciated.

A: So, my problem was really not knowing enough to know exactly what to ask.   The problem here wasn't dataTables or JS or Ajax or any of that.   It was Turbolinks in Rails 4.   Because it caches to make things seem fast, whenever I'd leave the page and come back to it, I'd have to refresh to get the underlying javascript to initialize.
Turbolinks has an option you can pass into your script to make a document ready on page:restore.  That worked.  If anyone else runs into this maybe they'll find this helpful.


Q: Centrally manage thumbs.db for multiple clients on a CIFS share I have a multimedia archive viewable read-only by multiple Windows 7 clients. Each time the clients browse the directory in Windows Explorer, the thumbnails are re-created. They're useful, but they take 10s of minutes on directories with 1000s of photographs and videos. The recreation process also adds load to the file server.
To solve this, I would like to maintain thumbs.db in each media directory on the Linux machine hosting the shares.
Is it possible, using Linux, to create a thumbs.db that can be consumed by all clients? If not, are there problems with creating thumbs.db on one of the clients and copying it to the share?


Q: struct with member function as parameter I am a beginner in C++ and stack exchange. I am working on an Interface class that gets keyboard input and checks to see whether it is correct through looping through an array of structs which contains strings to compare to and strings to output depending if it is equal to the compare string or not. If the input is correct, it will print the string within the struct and a function within the structure is called and does some action.
interface.hpp
#include <string>
class Input_Interface {
    struct command_output {
    std::string command;
    std::string success_string;
    std::string failure_string;
    void output_function();
    }

    bool stop_loop = false;
    void Clear();
    void Quit_loop();

};

interface.cpp
#include <iostream>
void Input_Interface::Quit_loop() {
   stop_loop = true;
   // ends loop and closes program
}

void Input_Interface::clear() {
   // does some action
}

Input_Interface::command_output clear_output{"CLEAR", "CLEARED", "", Input_Interface::Clear()};
Input_Interface::command_output quit_output{"QUIT", "GOODBYE", "", Input_Interface::Quit_loop()};
Input_Interface::command_output output_arr[]{clear_output, quit_output};

void Input_Interface::begin() {
while (stop_loop == false) {
    Input_Interface::get_input(); //stores input into var called input_str shown later
    this->compare_input();
    }
}

void Input_Interface::compare_input() {
for (unsigned int i=0; i<2; i++) {
    if (this->input_str == output_arr[i].command) {
        std::cout << output_arr[i].success_string << std::endl;
        output_arr[i].output_function();
        break;
        }
    }
    // ... goes through else for failure printing invalid if it did not match any of the command string in the command_output struct array

My issue is with these lines
Input_Interface::command_output clear_output{"CLEAR", "CLEARED", "", Input_Interface::Clear()};
//error: call to non-static function without an object argument

Input_Interface::command_output quit_output{"QUIT", "GOODBYE", "", Input_Interface::Quit_loop()};
//error: call to non-static function without an object argument

I know this is passed through member functions of the class but I don't know how to go about fixing this problem. I'm not really sure if the problem is the scope resolution operator inside the struct object or not because I can use it outside of parameters just fine.
Any help would be greatly appreciated.

A: You should do something as shown below:
#include <string>
struct Input_Interface {
    struct command_output {
      std::string command;
      void (*output_function)();
    };

    static void Clear();
    static void Quit_loop();
};

int main() {
    Input_Interface::command_output t = {"CLEAR", Input_Interface::Clear};
    return 0;
}

Live example here
Although I would suggest using a functor object over function pointer.


Q: Packages incompatible with tensorflow and keras I am running mask-rcnn github repository , I have installed the packages as per his repository requirements but if I import keras , it gives me error. My installed packages on the notebook are shown below:
ipykernel==5.5.3
ipyparallel==6.3.0
ipython==7.16.1
ipython-genutils==0.2.0
ipywidgets==6.0.0
jedi==0.18.0
Jinja2==2.10
joblib==1.0.1
jupyterlab-pygments==0.1.2
Keras==2.2.5
Keras-Applications==1.0.8
keras-nightly==2.5.0.dev2021032900
Keras-Preprocessing==1.1.2
keyring==10.6.0
keyrings.alt==3.0
opencv-python==4.5.2.54
Pillow==8.2.0
prometheus-client==0.11.0
prompt-toolkit==3.0.18
protobuf==3.17.2
ptyprocess==0.7.0
system-service==0.3
systemd-python==234
tensorboard==2.5.0
tensorboard-data-server==0.6.1
tensorboard-plugin-wit==1.8.0
tensorflow==2.5.0
tensorflow-estimator==2.5.0
termcolor==1.1.0
terminado==0.10.0

Code:
import keras
keras.__version__

Output:
AttributeError: module 'tensorflow.compat.v2.__internal__' has no attribute 'tf2'

Mask RCNN Repository link
https://github.com/matterport/Mask_RCNN


Q: How stream a response from a Twisted server? Issue
My problem is that I can't write a server that streams the response that my application sends back.
The response are not retrieved chunk by chunk, but from a single block when the iterator has finished iterating.
Approach
When I write the response with the write method of Request, it understands well that it is a chunk that we send.
I checked if there was a buffer size used by Twisted, but the message size check seems to be done in the doWrite.
After spending some time debugging, it seems that the reactor only reads and writes at the end.
If I understood correctly how a reactor works with Twisted, it writes and reads when the file descriptor is available.
What is a file descriptor in Twisted ?
Why is it not available after writing the response ?
Example
I have written a minimal script of what I would like my server to look like.
It's a "ASGI-like" server that runs an application, iterates over a function that returns a very large string:
# async_stream_server.py
import asyncio
from twisted.internet import asyncioreactor

twisted_loop = asyncio.new_event_loop()
asyncioreactor.install(twisted_loop)

import time
from sys import stdout

from twisted.web import http
from twisted.python.log import startLogging
from twisted.internet import reactor, endpoints

CHUNK_SIZE = 2**16

def async_partial(async_fn, *partial_args):
    async def wrapped(*args):
        return await async_fn(*partial_args, *args)
    return wrapped

def iterable_content():
    for _ in range(5):
        time.sleep(1)
        yield b"a" * CHUNK_SIZE

async def application(send):
    for part in iterable_content():
        await send(
            {
                "body": part,
                "more_body": True,
            }
        )
    await send({"more_body": False})

class Dummy(http.Request):
    def process(self):
        asyncio.ensure_future(
            application(send=async_partial(self.handle_reply)),
            loop=asyncio.get_event_loop()
        )

    async def handle_reply(self, message):
        http.Request.write(self, message.get("body", b""))
        if not message.get("more_body", False):
            http.Request.finish(self)
        print('HTTP response chunk')

class DummyFactory(http.HTTPFactory):
    def buildProtocol(self, addr):
        protocol = http.HTTPFactory.buildProtocol(self, addr)
        protocol.requestFactory = Dummy
        return protocol

startLogging(stdout)
endpoints.serverFromString(reactor, "tcp:1234").listen(DummyFactory())
asyncio.set_event_loop(reactor._asyncioEventloop)
reactor.run()

To execute this example:

*

*in a terminal, run:

python async_stream_server.py

*

*in another terminal, run:

curl http://localhost:1234/

You will have to wait a while before you see the whole message.
Details
$ python --version
Python 3.10.4
$ pip list
Package           Version Editable project location
----------------- ------- --------------------------------------------------
asgiref           3.5.0
Twisted           22.4.0

A: You just need to sprinkle some more async over it.
As written, the iterable_content generator blocks the reactor until it finishes generating content.  This is why you see no results until it is done.  The reactor does not get control of execution back until it finishes.
That's only because you used time.sleep to insert a delay into it.  time.sleep blocks.  This -- and everything else in the "asynchronous" application -- is really synchronous and keeps control of execution until it is done.
If you replace iterable_content with something that's really asynchronous, like an asynchronous generator:
async def iterable_content():
    for _ in range(5):
        await asyncio.sleep(1)
        yield b"a" * CHUNK_SIZE

and then iterate over it asynchronously with async for:
async def application(send):
    async for part in iterable_content():
        await send(
            {
                "body": part,
                "more_body": True,
            }
        )
    await send({"more_body": False})

then the reactor has a chance to run in between iterations and the server begins to produce output chunk by chunk.


Q: How to transfer score from Game Scene to GameViewController I created share button for share my score in Facebook , twitter and more.
the button created in GameViewController and my score and high score i created in Game Scene.
I did share score but i don't know how to transfer my score from GameScene to GameViewController.
The Score and High Score in Game Scene :
func addPointsLabels() {

        pointsLabel = MLPointsLabel(num: 0)
        pointsLabel.fontColor = UIColor.whiteColor()
        pointsLabel.fontName = "Avenir Next Bold"
        pointsLabel.fontSize = 40.0
        pointsLabel.position = CGPointMake(self.view!.frame.size.width/2, self.view!.frame.size.height/2 + 180)
        pointsLabel.name = "pointsLabel"
        addChild(pointsLabel)

        highscoreLabel = MLPointsLabel(num: 0)
        highscoreLabel.fontColor = UIColor(red: 0.0/255.0, green: 161.0/255.0, blue: 156.0/255.0, alpha: 1.0)
        highscoreLabel.name = "highscoreLabel"
        highscoreLabel.fontSize = 25.0
        highscoreLabel.fontName = "Avenir Next Bold"
        highscoreLabel.position = CGPointMake(self.view!.frame.size.width/2 + 90, self.view!.frame.size.height/2  + 100)
        addChild(highscoreLabel)

    }

GameViewController :
     class scene: SKScene {
        var currentScore: Int = 0
        var highScore: Int = 0

        func updateScore(withScore score: Int) {
            currentScore = score
            highScore = currentScore > score ? currentScore : score
        }
    }

    class GameViewController: UIViewController , MyGameDelegate {

        var scene: GameScene!
        var ShareButton = UIButton()
        var myDelegate : MyGameDelegate!

        override func viewDidLoad() {
            super.viewDidLoad()

            // Configure the view
            let skView = view as! SKView
            //skView.multipleTouchEnabled = false
            // Create and configure the scene
            scene = GameScene(size: skView.bounds.size)
            scene.scaleMode = .AspectFill

    //        NSLog("width: %f", skView.bounds.size.width)
    //        NSLog("height: %f", skView.bounds.size.height)

            // Present the scenee
            skView.presentScene(scene)

        }

        func addShareButton() {
            ShareButton.hidden = false
        }

        override func viewDidLayoutSubviews() {
            super.viewDidLayoutSubviews()

    //        //create Share Button
            ShareButton = UIButton.init(frame: CGRectMake(self.view!.frame.size.width/2 - 80, self.view!.frame.size.height/2 + 60, 60, 60))
            ShareButton.setImage(UIImage(named: "ShareButton.png"), forState: UIControlState.Normal)
            ShareButton.addTarget(self, action: "pressedShareButton:", forControlEvents: .TouchUpInside)

            self.view!.addSubview(ShareButton)
        }

func pressedShareButton(sender: UIButton!) {

        // Now you can get your score and high score like this:
        let currentScore = scene.pointsLabel
        let highScore = scene.highscoreLabel

        UIGraphicsBeginImageContextWithOptions(view!.frame.size, false, 0.0)
        view!.drawViewHierarchyInRect(view!.frame, afterScreenUpdates: true)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext();

        let myText = "WOW! I made \(currentScore) points playing #RushSamurai! Can you beat my score? https://itunes.apple.com/us/app/rush-samurai/id1020813520?ls=1&mt=8"

        let activityVC:UIActivityViewController = UIActivityViewController(activityItems: [myText,image], applicationActivities: nil)

        //New Excluded Activities Code
        if #available(iOS 9.0, *) {
            activityVC.excludedActivityTypes = [UIActivityTypeAirDrop, UIActivityTypeAddToReadingList, UIActivityTypeAssignToContact, UIActivityTypeCopyToPasteboard, UIActivityTypeMail, UIActivityTypeMessage, UIActivityTypeOpenInIBooks, UIActivityTypePostToTencentWeibo, UIActivityTypePostToVimeo, UIActivityTypePostToWeibo, UIActivityTypePrint]
        } else {
            // Fallback on earlier versions
            activityVC.excludedActivityTypes = [UIActivityTypeAirDrop, UIActivityTypeAddToReadingList, UIActivityTypeAssignToContact, UIActivityTypeCopyToPasteboard, UIActivityTypeMail, UIActivityTypeMessage, UIActivityTypePostToTencentWeibo, UIActivityTypePostToVimeo, UIActivityTypePostToWeibo, UIActivityTypePrint ]
        }

        activityVC.popoverPresentationController?.sourceView = view
        activityVC.popoverPresentationController?.sourceRect = ShareButton.frame
        presentViewController(activityVC, animated: true, completion: nil)
    }

MLPointsLable :
class MLPointsLabel: SKLabelNode {

    var number = 0

    //var gameoverscore = 0

    init(num: Int) {
        super.init()

        fontColor = UIColor.whiteColor()
        fontName = "Avenir Heavy"
        fontSize = 24.0

        number = num
        text = "\(num)"
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func increment() {
        number++
        text = "\(number)"

    }

    func setTo(num: Int) {
        self.number = num
        text = "\(self.number)"

}

A: Since your GameViewController is presenting your GameScene you can just hold a reference to it and get the score and high score from properties in your GameScene.
Something like this:
class GameViewController: UIViewController {
    var gameScene: GameScene!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Hold a reference to your GameScene after initializing it.
        gameScene = SKScene(...)
    }
}

class GameScene: SKScene {
    var currentScore: Int = 0
    var highScore: Int = 0

    func updateScore(withScore score: Int) {
        currentScore = score
        highScore = currentScore > score ? currentScore : score
    }
}

Update:
You could use this values in your pressedShareButton like this:
func pressedShareButton(sender: UIButton!) {
    let currentScore = scene.currentScore
    let highScore = scene.highScore
    ...
    let myText = "WOW! I made \(currentScore) points playing #RushSamurai! Can you beat my score? https://itunes.apple.com/us/app/rush-samurai/id1020813520?ls=1&mt=8"
    ...

}


Q: Form data autosuggestion I have a button( Add More) which adds new row in my form/table. I want to add data autosuggestion in INPUT form. so i've tried the below codes. It's working but only for first row. It's not working for the next rows. can anyone correct me what i a doing wrong? You can check it in my jsFiddle too .

 <INPUT type="text" id="tags" />

<button type="button" class="btn btn-primary" value="Add Row" onclick="addRow('dataTable')">Add More</button>

/*** Form autosuggestion **/
$(function() {
 var availableTags = [
  "ActionScript",
  "AppleScript",
  "Asp",
  "BASIC",
  "C",
  "C++",
  "Clojure",
  "COBOL",
  "ColdFusion",
  ];
  $( "#tags" ).autocomplete({
    source: availableTags
  });
});

/*** Adding new row **/
function addRow(tableID) {
 var table = document.getElementById(tableID);
 var rowCount = table.rows.length;
 var row = table.insertRow(rowCount);
 var colCount = table.rows[0].cells.length;

    for(var i=0; i<colCount; i++) {
        var newcell = row.insertCell(i);
        if(i==1){newcell.innerHTML = (rowCount+1)}
        else{
        newcell.innerHTML = table.rows[0].cells[i].innerHTML;
           }
        switch(newcell.childNodes[0].type) {
            case "text":
                    newcell.childNodes[0].value = "";
                    break;
            case "test":
                    newcell.childNodes[0].value="";
                    break;
            case "checkbox":
                    newcell.childNodes[0].checked = false;
                    break;
            case "select-one":
                    newcell.childNodes[0].selectedIndex = 0;
                    break;
        }
    }
}

A: The reason behind this is not working is because you have passed same id for two text fields, and in HTML you can't have duplicate ids as it doesn't make sense.
here you can do two things

*

*Give class to new element and get element from class

*Or when you create an element at that time create a autosuggest object for that field

Here is a fiddle for you
HTML CODE:

    <INPUT type="text" id="tags" class="autosuggest" />

<button type="button" class="btn btn-primary" value="Add Row" onclick="addRow('dataTable')">
    Add More
</button>

JAVASCRIPT CODE:
 function createAutoSuggest(element) { // Created a common function for you
   var availableTags = [
     "ActionScript",
     "AppleScript",
     "Asp",
     "BASIC",
     "C",
     "C++",
     "Clojure",
     "COBOL",
     "ColdFusion",
   ];
   $(element).autocomplete({
     source: availableTags
   });
 }
 $(function() {

   createAutoSuggest($(".autosuggest"));
 });

 function addRow(tableID) {
   var table = document.getElementById(tableID);
   var rowCount = table.rows.length;
   var row = table.insertRow(rowCount);
   var colCount = table.rows[0].cells.length;

   for (var i = 0; i < colCount; i++) {
     var newcell = row.insertCell(i);
     if (i == 1) {
       newcell.innerHTML = (rowCount + 1)
     } else {
       newcell.innerHTML = table.rows[0].cells[i].innerHTML;
     }

     switch (newcell.childNodes[0].type) {
       case "text":
         newcell.childNodes[0].value = "";
         break;
       case "test":
         newcell.childNodes[0].value = "";
         break;
       case "checkbox":
         newcell.childNodes[0].checked = false;
         break;
       case "select-one":
         newcell.childNodes[0].selectedIndex = 0;
         break;
     }

     if ($(newcell).find('.autosuggest').length > 0) {
       createAutoSuggest($(newcell).find('.autosuggest'));// This is the change you basically need
     }
   }
 }

A: You can use live to attach events to dynamically created textboxes.

Here is the example


Q: Change mouseover colour of all controls globally WPF Buttons, column headers, comboboxes etc. all go a nice Microsoft blue when you mouseover them.
I'd much rather they went a nice shade of my corporate green.

Is there any way to change this colour either globally for my application or by window.
Failing that, will I have to change this for each individual control type?

A: You have to have to define a Style for each control. This is because the visuals and visual states are defined by the internal ControlTemplate of each control.
But you can significantly reduce the amount of work by reusing templates and cascading styles.
To allow easy color theming and centralized customization, you should create a resource that defines all relevant colors of your theme:
ColorResources.xaml
<ResourceDictionary>

  <!-- Colors -->
  <Color x:Key="HighlightColor">DarkOrange</Color>
  <Color x:Key="DefaultControlColor">LightSeaGreen</Color>
  <Color x:Key="ControlDisabledTextColor">Gray</Color>
  <Color x:Key="BorderColor">DarkGray</Color>
  <Color x:Key="MouseOverColor">LightSteelBlue</Color>

  <!-- Brushes -->
  <SolidColorBrush x:Key="HighlightBrush" Color="{StaticResource HighlightColor}" />
  <SolidColorBrush x:Key="ControlDisabledTextBrush" Color="{StaticResource ControlDisabledColor}" />
  <SolidColorBrush x:Key="BorderBrush" Color="{StaticResource BorderColor}" />
  <SolidColorBrush x:Key="MouseOverBrush" Color="{StaticResource MouseOverColor}" />
</ResourceDictionary>

You may add the following styles an templates to the App.xaml file:
App.xaml
<Application>
  <Application.Resources>
    <ResourceDictionary>
      <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="/File/Path/To/ColorResources.xaml" />
      </ResourceDictionary.MergedDictionaries>

      ...
    </ResourceDictionary>
  </Application.Resources>
</Application>

To override the color of the selected row in a GridView or DataGrid you simply need to override the default brush SystemColors.HighlightBrush used by these controls:
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}"
                 Color="{StaticResource HighlightColor}" />

To override the default color of controls like the column headers of  e.g DatGrid you simply need to override the default brush SystemColors.ControlBrush used by these controls:
<SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}"
                 Color="{StaticResource DefaultControlColor}" />

For simple ContentControls like Button or ListBoxItem you can share a common ControlTemplate. This shared ControlTemplate will harmonize the visual states:
<ControlTemplate x:Key="BaseContentControlTemplate"
                 TargetType="ContentControl">
  <Border BorderBrush="{TemplateBinding BorderBrush}"
          BorderThickness="{TemplateBinding BorderThickness}"
          Background="{TemplateBinding Background}">
    <ContentPresenter/>
  </Border>

  <ControlTemplate.Triggers>
    <Trigger Property="IsEnabled" Value="False">
      <Setter Property="Foreground" Value="{StaticResource ControlDisabledTextBrush}" />
    </Trigger>
    <Trigger Property="IsMouseOver" Value="True">
      <Setter Property="Opacity" Value="0.7" />
      <Setter Property="Background" Value="{StaticResource MouseOverBrush}" />
    </Trigger>
  </ControlTemplate.Triggers>
</ControlTemplate>

This base template will be applied using base styles. This allows simple chaining (style inheritance) and reuse of the BaseContentControlTemplate for different controls like Button or ListBoxItem:
<Style x:Key="BaseContentControlStyle"
       TargetType="ContentControl">
  <Setter Property="Template" Value="{StaticResource BaseContentControlTemplate}" />
</Style>

Some ContentControl like a Button might need additional states like Pressed. You can extend additional basic visual states by creating a base style that e.g., targets ButtonBase and can be used with any control that derives from ButtonBase:
<Style x:Key="BaseButtonStyle"
       TargetType="ButtonBase"
       BasedOn="{StaticResource BaseContentControlStyle}">
  <Style.Triggers>
    <Trigger Property="IsPressed" Value="True">
      <Setter Property="Background" Value="{StaticResource HighlightBrush}" />
    </Trigger>
  </Style.Triggers>
</Style>

To apply this base styles you have to target the controls explicitly. You use this styles to add more specific visual states or layout e.g., ListBoxItem.IsSelcted, ToggleButton.IsChecked or DataGridColumnHeader:
<!-- Buttons -->
<Style TargetType="Button" BasedOn="{StaticResource BaseButtonStyle}" />

<Style TargetType="ToggleButton" BasedOn="{StaticResource BaseButtonStyle}">
  <Style.Triggers>
    <Trigger Property="IsChecked" Value="True">
      <Setter Property="Background" Value="{StaticResource HighlightBrush}" />
    </Trigger>
  </Style.Triggers>
</Style>

<!- ListBox -->
<Style TargetType="ListBoxItem" BasedOn="{StaticResource BaseContentControlStyle}">
  <Style.Triggers>
    <Trigger Property="IsSelected" Value="True">
      <Setter Property="Background" Value="{StaticResource HighlightBrush}" />
    </Trigger>
  </Style.Triggers>
</Style>

<!-- ListView -->
<Style TargetType="ListViewItem" BasedOn="{StaticResource {x:Type ListBoxItem}}" />

<!--
  GridView
  Since GridViewColumnHeader is also a ButtonBase we can extend existing style
-->
<Style TargetType="GridViewColumnHeader" BasedOn="{StaticResource BaseButtonStyle}" />

<Style x:Key="BaseGridViewStyle" TargetType="ListViewItem">
  <Style.Triggers>
    <Trigger Property="IsSelected" Value="True">
      <Setter Property="Background" Value="{StaticResource HighlightBrush}" />
    </Trigger>
    <Trigger Property="IsMouseOver" Value="True">
      <Setter Property="Background" Value="{StaticResource {x:Static SystemColors.HighlightBrushKey}}" />
    </Trigger>
  </Style.Triggers>
</Style>

<!--
  DataGrid
  Since DataGridColumnHeader is also a ButtonBase we can extend existing style
-->
<Style TargetType="DataGridColumnHeader"
       BasedOn="{StaticResource BaseButtonStyle}">
  <Setter Property="BorderThickness" Value="1,0" />
  <Setter Property="BorderBrush" Value="{StaticResource BorderBrush}" />
</Style>

Other more complex composed controls like ComboBox, TreeView or MenuItem require to override the control's template individually. Since these controls are composed of other controls, you usually have to override the styles for this controls too. E.g., ComboBox is composed of a TextBox, ToggleButton an Popup.
You can find their styles at Microsoft Docs: Control Styles and Templates.
This is a very simple and basic way to add theming to your application. Knowledge of the inheritance tree of the controls helps to create reusable base styles. Reusing styles helps to reduce the effort to target and customize each control.
Having all visual resources like colors or icons defined in one place makes it easy to modify them without having to know/modify each control individually.

A: If you have a look at the default styles (https://learn.microsoft.com/en-us/dotnet/framework/wpf/controls/button-styles-and-templates), you will find out, that each style uses static resources for declaring the colors.
So to achieve your project you would have to overwrite these static resources where the colors are stored.
Unfortunately, this is not possible in WPF (was already asked before: Override a static resource in WPF).
So your only solution would be to write a separate Style for each control and to re-declare the colors.


Q: Why is there an NumberFormatException? I keep on running into a problem with NumberFormatException. There is a problem with the readLine since I am reading the wrong line at the wrong time. I am writing a program which takes in that amount of money a person has and then calculates how much they will have after they gift some money to other people.
The entire problems can be found at the link below.
http://train.usaco.org/usacoprob2?a=RX1a1QYsOyX&S=gift1
    BufferedReader f = new BufferedReader(new FileReader("gift1.in"));
    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("gift1.out")));

    int ppl = Integer.parseInt(f.readLine());
    out.println(ppl);

    HashMap<String, Integer> name = new HashMap<String, Integer>();
    String[] names = new String[ppl];
    for(int i = 0; i < ppl; i++ ){
        String n = f.readLine();
        names[i] = n;
        name.put(n, 0);

    }
    for (int i = 0; i < ppl; i++){
        String person = f.readLine();

        StringTokenizer st = new StringTokenizer(f.readLine());
            int mon_lost = Integer.parseInt(st.nextToken());
            int ppl_given = Integer.parseInt(st.nextToken());

        name.put(person, (mon_lost%ppl_given)-mon_lost);

        for(int j =0; j< ppl_given-1; i++){
            name.put(f.readLine(), mon_lost/ppl_given);
        }

    }
    for(int i = 0; i < ppl; i++){

        out.println(names[i] +" "+ name.get(names[i]));
    }
    f.close();
    out.close();

A: It isn't the BufferedReader. You can read millions of lines per second with BufferedReader.readLine(). It's your code.
For example, the f.read() calls are not correct. They will deliver character values, not digit values, and from the next line, without consuming the line terminator, so you will get a blank line next readLine(), so you will be totally out of sync with your input.
Basically your code doesn't even work yet, so timing it now is futile.

A: Your first for-loop is probably testing with the wrong value.
Instead of :
for(int i = 0; i < ppl-1; ++i ) {

try using:
for(int i = 0; i < ppl; ++i ) {

[UPDATE]
Since you are looping too few times in this loop, the subsequent loop will be using the remaining input data inappropriately. For example, ppl_given would be some garbage number, which could be very big.


Q: How to pluralise an acronym?
Possible Duplicate:
What is the correct way to pluralize an acronym?

How would you make the plural form of an acronym? For example, if you have two of Nintendo's game console, the DS.
Would you say, "I have two DSes," "I have two DSs," or something else?


Q: project xxxx is associated to an unknown SonarQube server(). Please fix project association or add server in SonarQube plugin perfrences When I open any java class in eclipse editor it is showing below popup message.

A: Right click your project and choose SonarQube. then click on Remove the SonarQube server nature
EDIT
Another option is to go to Windows -> Preferences -> SonarQube -> Server and to remove or fix your server here.

A: Another solution:
I had two Sonar-PlugIns (SonarQube and SonarLint). The first posted solution has't worked for me. But the following had worked: in eclipse installation directory, open the file:
<yourEclipseInstallDirectory>\configuration\customization.ini

And delete what is after the = sign.
org.sonar.ide.eclipse.core/servers/default/url=<deleteWhatIsHere>