text:
Q: How to get ProcessStartInfo with arguments from a java process By using C#? I am trying to get a java Process object by using C#.
The thing is i have several java Processes running on my computer.
Following is the way i chose to get Processes:
Process[] processes = Process.GetProcessesByName("java");
foreach(Process proc in processes){
    //I need a filter here to get the correct process.
}

The java Process is also controlled by my C# program as below:
 ProcessStartInfo startInfo = new ProcessStartInfo();
 startInfo.FileName = javahome + "\\bin\\java.exe";
 startInfo.Arguments = "-jar Example.jar port=88888";
 startInfo.WorkingDirectory = "\\testFolder";
 startInfo.UseShellExecute = false;
 startInfo.CreateNoWindow = true;
 Process proc = new Process();
 proc.StartInfo = startInfo;
 proc.Start();

What i want is go through the array of Process to check which one has the same Arguments with the Process object that i started in another program.
But the problem is when i did like this:
 Console.WriteLine(proc.StartInfo.Arguments);

I found there is nothing in it, even i know it is the process that i started in another program. This confused me a lot.
Does anyone know this issue?

A: You can't do it that way. When you start a process keep the handler for that process in a dictionary where the value is the process arguments, that's the only way I see for you to archive that.
        Dictionary<IntPtr, string> processArguments = new Dictionary<IntPtr,string>();

        ProcessStartInfo startInfo = new ProcessStartInfo();
        startInfo.FileName = javahome + "\\bin\\java.exe";
        startInfo.Arguments = "-jar Example.jar port=88888";
        startInfo.WorkingDirectory = "\\testFolder";
        startInfo.UseShellExecute = false;
        startInfo.CreateNoWindow = true;
        Process proc = new Process();
        proc.StartInfo = startInfo;
        proc.Start();

        processArguments.Add(proc.Handle, javahome + "\\bin\\java.exe");

....

        Process[] processes = Process.GetProcessesByName("java");
        foreach (Process proc in processes)
        {
            var arguments = processArguments.Where(x => x.Key.Equals(proc.Handle)).FirstOrDefault().Value;
        }

A: You can try like this by using LINQ as below :
Process[] processes = Process.GetProcessesByName("java");
var fileteredProcess = from pro in processes
                        where (pro.StartInfo.WorkingDirectory == "workingDIR") &&
                        (pro.StartInfo.Arguments == "Arguments")
                        select pro;

foreach (var proc in fileteredProcess)
{

}

A: Here is an alternative solution using WMI:
Process[] processes;
Process selectedProc = null;
int selectedProcId = 0;

//  http://wutils.com/wmi/
//  using System.Management;
ManagementScope scope = new ManagementScope("\\\\.\\ROOT\\cimv2");
ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_Process "
                                  + "WHERE Name = 'java.exe'");
ManagementObjectSearcher searcher =
        new ManagementObjectSearcher(scope, query);
ManagementObjectCollection queryCollection = searcher.Get();

foreach (ManagementObject m in queryCollection)
{
        // access properties of the WMI object
        Console.WriteLine("CommandLine : {0}", m["CommandLine"]);
        Console.WriteLine("ProcessId : {0}", m["ProcessId"]);

        if (m["CommandLine"].ToString().Contains("my pattern"))
        {
            selectedProcId = int.Parse(m["ProcessId"].ToString());
            selectedProc = Process.GetProcessById(selectedProcId);
            break;
        }
}

if (selectedProc != null)
{
        Console.WriteLine("Proc title {0}", selectedProc.MainWindowTitle);
}


text:
Q: Spark RDD fault tolerance my question is " Does fault tolerance in Spark RDD happens automatically or do we need to replay the transformation on the lost partitions ? "

A: Spark will recompute lost partitions automatically.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Clickable text in /tellraw Here's the command:
/tellraw @p ["",{"text":"[HINT]","color":"dark_green","bold":true,"clickEvent":{"action":"run_command","value":"/tellraw @p {\"text\":\"This pickaxe cannot break lit glowstone lamps.\",\"color\":\"light_purple\"]"},"hoverEvent":{"action":"show_text","value":{"text":"","extra":[{"text":"Click For Hint"}]}}}]

That brings up [HINT], which is bold and dark green, and when you hover over it, it says "Click For Hint". The problem is that when you click it, it should activate a tellraw command, however when I click it, I get:
Invalid json: Unterminated object at line 1 column 81

This JSON is flawless (or so I thought). What is wrong?

A: I was an idiot, and made 1 small mistake that changed everything. Here was the full command:
/tellraw @p ["",{"text":"This map is based off of 1.9 features such as detecting when you pick up items,","color":"green"},{"text":" [HINT] ","color":"dark_green","bold":true,"clickEvent":{"action":"run_command","value":"/tellraw @p {\"text\":\"This pickaxe cannot break lit glowstone lamps.\",\"color\":\"light_purple\"}"},"hoverEvent":{"action":"show_text","value":{"text":"","extra":[{"text":"Click For Hint"}]}}},{"text":"so you may need to think outside of the box for some levels. good Luck!","color":"green"}]

If you will notice, light_purple had a ] after it instead of }. My bad...

A: I have figured it out! try this:
/tellraw @p [{"text":"[HINT]","color":"dark_green","bold":"true","clickEvent":{"action":"run_command","value":"/tellraw @p [{\"text\":\"This pickaxe cannot break lit glowstone lamps.\",\"color\":\"light_purple\"}]"},"hoverEvent":{"action":"show_text","value":{"text":"","extra":[{"text":"Click For Hint"}]}}}]

the true in bold:true was missing the quotes, I had to remove one "}" at the very end because there was one too many and I took out the two quotes at the beginning because they didn't seem like they would do anything. I also switched some of the "}" and "]" in the tellraw command containing the hint.

A: Your command is missing some brackets and braces.  Try this instead:
/tellraw @p ["",{"text":"[HINT]","color":"dark_green","bold":true,"clickEvent":{"action":"run_command","value":"/tellraw @p {[\"text\":\"This pickaxe cannot break lit glowstone lamps.\",\"color\":\"light_purple\"]"},"hoverEvent":{"action":"show_text","value":{"text":"","extra":[{"text":"Click For Hint"}]}}}}]

I can't verify that it'll do exactly what you want, but I'm fairly certain I've fixed the syntax error.


text:
Q: Wrong results from THD calculation in MATLAB I have measured signals (grid voltages and currents at 50Hz) of which I want to calculate the THD in MATLAB. However, using thd(signalVector, samplingFrequency, numberOfHarmonics) gives completely wrong results.
See the attached screenshot: The measured signal is on the left, the middle plot shows the FFT, on the right there is a closeup view of the FFT. As you can see, the THD is calculated to be too high at 86%:

Looking at the thd() itself, it obviously mismatches the FFT:

I used both fft() and thd() like in the MATLAB examples.
For FFT I use:
NFFT = 2^nextpow2(L);
Y = fft(signal_vector,NFFT)/(samples_vector);
f = sampling_frequency/2*linspace(0,1,NFFT/2+1);
y_fft = 2*abs(Y(1:NFFT/2+1));
plot(f,y_fft)

For THD up to the 40. harmonic I simply use:
thd(signal_vector,sampling_frequency,40)

where sampling frequency is 40kHz.
I guess I am doing something essentially wrong. Where is the flaw?
Do you need additional information? Any help is appreciated (I hope this is the right place for my question)
EDIT: Using a THD function from the Matlab File Exchange I get a THD of 1.78%, but I do not know if this is correct, but seems realistic.


text:
Q: sbackup fails to connect via ssh when run via sudo I prefer to run sbackup via sudo to be able to backup other things than my normal user has access to. But sbackup fails to connect to the specified host via ssh when it is run via sudo. It says

Unable to mount host

Still I have no problem to ssh into the specified host with my normal user. Is there any way to fix this?

A: Since you run sbackup via sudo you need to add the specified host to the local root account. To do this run invoke ssh via sudo to login with your normal user, i.e. if your normal user is nn:
sudo ssh -l nn <address to specified host>

You will then see something like
The authenticity of host [...] can't be established.
ECDSA key fingerprint is [...]
Are you sure you want to continue connecting (yes/no)?

Choose yes here and you are done (you do not actually have to log in).


text:
Q: Few questions... ModelState.IsValid and Grouped CheckBox Values Using ASP.NET MVC when I create my model, then a controller based on the model with CRUD operations, the CRUD views are generated. I added some code using Fluent API to require certain fields but for some reason the ModelState.IsValid passes even when these fields are not completed. What determines whether this passes or not? I thought it was based on your model property data types and other things like being required or maxlength, etc....
Also, I have manually added code to grab a list of Categories from the database and generate a checkbox for each one in the View. This is a navigation property for the Project model where there is a many-many relationship. To get the group of checked values in the Create(Project project) method in the controller I use:
var selected = Request["categories"].Split(',');

This however, throws the classic Object reference not set to an instance of an object error if no values are checked. So what I want to know is, how can I determine that this does not have any values so I can do something else once detected?

A:
I added some code using Fluent API to require certain fields but for
  some reason the ModelState.IsValid passes even when these fields are
  not completed.

ASP.NET MVC doesn't know anything about the Fluent API of Entity Framework and doesn't evaluate this configuration. You only can use the data annotations which MVC will recognize:
[Required]
public string SomeProperty { get; set; }

...how can I determine that this does not have any values so I can do
  something else once detected?

Not sure if I understand it correctly but I'd say:
var categories = Request["categories"];
if (categories != null)
{
    var selected = categories.Split(',');
    // ...
}
else
{
    // do something else
}


text:
Q: How to avoid loading from chunk in webpack? [Angular] [inline js] I am trying to bundle a angular project into a single file (js, css and html). I've managed to get the html and css working and js is also inline now (using HtmlWebpackInlineSourcePlugin). The js files generated after minification are like below:

The vendor, main and polyfill are inline in the index.html. But I see that the generated js for main and vendor js are trying to load from the chunk 3.js (this has the actual js that's written for the app).

I want this chunk also to be inline, but can't seem to find a way to do it. Even if I did manage to make it inline, how do I avoid vendor/main js from loading this chunk. The webpack config is below.
'use strict';

const webpackMerge         = require('webpack-merge');
const ngw                  = require('@ngtools/webpack');
const HtmlWebpackPlugin    = require('html-webpack-plugin');
var HtmlWebpackInlineSourcePlugin = require('html-webpack-inline-source-plugin');
const isDev                = process.env.NODE_ENV !== 'production';

//just a wrapper for path
const helpers              = require('./helpers');

module.exports = {
    mode: 'production',

    output: {
        path: helpers.root('dist'),
        filename: '[name].js',
    },

    resolveLoader: {
        modules: [helpers.root('node_modules')]
    },

    entry: {
        vendor: './src/vendor.ts',
        polyfills: './src/polyfills.ts',
        main: './src/main.ts'
    },

    resolve: {
        extensions: ['.ts', '.js', '.scss']
    },

    module: {
        rules: [
            {
                test: /\.html$/,
                loader: 'html-loader'
            },
            {
                test: /\.(scss|sass)$/,
                use: [
                    { loader: 'style-loader', options: { sourceMap: isDev } },
                    { loader: 'css-loader', options: { sourceMap: isDev } },
                    { loader: 'sass-loader', options: { sourceMap: isDev } }
                ],
                include: helpers.root('src', 'assets')
            },
            {
                test: /\.(scss|sass)$/,
                use: [
                    'to-string-loader',
                    { loader: 'css-loader', options: { sourceMap: isDev } },
                    { loader: 'sass-loader', options: { sourceMap: isDev } }
                ],
                include: helpers.root('src', 'app')
            },
            {
                test: /(?:\.ngfactory\.js|\.ngstyle\.js|\.ts)$/,
                loader: '@ngtools/webpack'
            }
        ]
    },

    plugins: [
        new ngw.AngularCompilerPlugin({
            tsConfigPath: helpers.root('tsconfig.json'),
            entryModule: helpers.root('src', 'app', 'app.module#AppModule')
        }),
        new HtmlWebpackPlugin({
            template: 'src/index.html',
            inlineSource: '.(js|css)$',
        }),
        new HtmlWebpackInlineSourcePlugin(HtmlWebpackPlugin),
       // new InlineChunkHtmlPlugin(HtmlWebpackPlugin, [/chunk/])
    ]
};

FYI - I want it to be a single inline file because I need to use in google apps script (editor add on).

A: I ended up solving this using libraryTarget in webpack to compile to umd.
output: {
    path: helpers.root('dist'),
    publicPath: '/',
    filename: '[name].js',
    libraryTarget: "umd",
    globalObject: 'this'
}


text:
Q: How to combine the below the update querys into one, Update multiple rows with multiple values for same column and the rest of data with other value here i want to change the date for 9 rows
1.
UPDATE forum_topic_resume
SET _When_Updated = (now() -INTERVAL 6 day)
WHERE _id IN (96250, 69081, 69555)

*

UPDATE forum_topic_resume
SET _When_Updated = (now() -INTERVAL 8 day)
WHERE _id IN (70494, 68612, 69564, 69660, 72437, 80498)

The change the status
3.
UPDATE forum_topic_resume
SET _Status = 1224
WHERE _id IN (96250, 69081, 69555)

*

UPDATE forum_topic_resume
SET _Status_Is = 1228
WHERE _id IN (70494, 68612, 69564)

*

UPDATE forum_topic_resume
SET _Status_Is = 1229
WHERE _id IN (69660, 72437, 80498)

There are about 52 more Ids for whom I was to set the status to a different value which would look like below.
6.
UPDATE forum_topic_resume
SET _Status_Is = 1250
WHERE _id IN (for the rest of the ids)

A: One way is using multiple case conditions:
UPDATE forum_topic_resume
SET  _When_Updated  =  CASE
                        WHEN _id IN (96250, 69081, 69555) THEN (now() -INTERVAL 6 day)
                        WHEN _id IN (70494, 68612, 69564, 69660, 72437, 80498) THEN (now() -INTERVAL 8 day)
                        other id conditions  .............
                        END,
_Status  = CASE
             WHEN _id IN (96250, 69081, 69555) THEN 1224
             WHEN _id IN (70494, 68612, 69564) 1228
                         ......
             END,
_Status_Is = CASE
              WHEN _id IN (96250, 69081, 69555) THEN 1224
              WHEN _id IN (70494, 68612, 69564) 1228
                         ......
              END;

A: Use multiple-table UPDATE.
UPDATE forum_topic_resume
LEFT JOIN (
    SELECT 96250                  AS _id,
           now() - INTERVAL 6 day AS _When_Updated,
           1224                   AS _Status
  UNION ALL
    SELECT 70494, now() -INTERVAL 8 day, 1228
  UNION ALL
    ...
) data_for_update USING (_id)
SET forum_topic_resume._When_Updated = COALESCE(data_for_update._When_Updated,
                                                forum_topic_resume._When_Updated),
    forum_topic_resume._Status= COALESCE(data_for_update._Status,
                                         1250);

data_for_update contains all data needed for definite updating.
COALESCE provides storing _When_Updated value and setting definite _Status value for the rows with _id values which are not listed in data_for_update.
You may add some WHERE conditions when not all rows in forum_topic_resume not listed in data_for_update must be updated with new _Status value.
Of course the query text will be long, but the execution will be fast enough.


text:
Q: PHP file_put_contents get file extension/type It's possible to get extension of a file with file_put_contents in PHP?
I want to download files from a server using php with cycle, but each file has a different type and I want to know if there is a way to understand the extension of each file?
Code sample:
<?php

  $url = 'http://www.domain.com/file/123';
  $fopen = fopen($url, 'r');
  file_put_contents("filename", $fopen);
  fclose($fopen);

?>

How can I find out what type of a file, because if I put it with only the name becomes impractical?

A: I understand that you problems is that you do not know what extension to put for this file. Once you have saved the file then you can detect the mime type and extension like this
$fi = new finfo(FILEINFO_MIME,'/path/filename');
$mime_type = $fi->buffer(file_get_contents($file));

Once you have found the mime type then you can rename it. Of course bear in mind that this needs extra IO from your HDD.

A: maybe try smth like this:
get_headers ( $url )

http://php.net/manual/en/function.get-headers.php

A: A file transferred via HTTP may have a name in the Content-Disposition HTTP header. If it doesn't, there should be a Content-Type HTTP header which at least tells you the MIME type of the file; you can map that to a file extension and need to make up some filename yourself. If neither are present, you're on your own.
The first step is to read the HTTP headers before downloading the HTTP body. The curl extension can do that, get_headers could do it (though requires an additional roundtrip), or other socket based HTTP libraries could do it (I'd recommend this one, you want to make one HTTP request, get access to the headers, but not read the entire file into memory). Look around for a library that can do this for you, this is a bit of a broad topic.


text:
Q: for loop in folders with \n character in their names I have some folders with \n character it their names.
for example:
$ ls
''$'\n''Test'

Thats refer to a folder with Test name and a empty line before its name.
So when I run some scripts like this, in its parent directory:
while IFS= read -r d; do
    rmdir $d
done < <(find * -type d)

It shows:
rmdir: failed to remove '': No such file or directory
rmdir: failed to remove 'Test': No such file or directory

Because it runs twice, once on \n and the another on Test, because the folder name has two lines.
So how can I solve this issue such that, script knows \nTest is just one folder?

A: Both answers written so far call rmdir once per directory, but as rmdir can take multiple arguments I wonder: Isn't there a more efficient way?
One could simply do
rmdir */

and that's definitely the easiest and most efficient way, but it may throw an error in the case of many directories (see What is the maximum length of command line arguments in gnome-terminal?). If you want this approach to work recursively, enable the globstar shell option with shopt -s globstar and use **/*/ instead of */.
With GNU find (and if we don't just want to use -delete), we could do
find -depth -type d -exec rmdir {} +

which builts the command line "in much the same way that xargs builds its command lines" (man find). Substitute -depth for -maxdepth 1 if you don't want it to work recursively.
A third and IMO brilliant way is explained by steeldriver in this answer:
printf '%s\0' */ | xargs -0 rmdir

This uses the shell builtin printf to build a zero-delimited argument list, this list is then piped to xargs which calls rmdir exactly as often as necessary. You can make it work recursively with shopt -s globstar and **/*/ instead of */ as above.

A: You've only single command there, so it's sufficient to call find with -exec flag calling rmdir:
find -depth -type d -exec rmdir {} \;

Or use the -delete option as in  find -type d -delete, but it won't work with non-empty directories. For that you will also need -empty flag. Note also, -delete implies -depth so that may be skipped. Thus another viable alternative that keeps everything as one process:
find -type d -empty -delete

If the directory not empty, use rm -rf {} \;. To isolate only directories with \n in filename we can combine bash's ANSI-C quoting $'...' with -name opption:
find  -type d -name $'*\n*' -empty -delete

POSIX-ly, we could handle it this way:
find -depth  -type d -name "$(printf '*\n*' )" -exec rmdir {} \;

It is worth mentioning that if your goal is removal of directories, then -delete is sufficient, however if you want to execute a command on directory then -exec is most appropriate.
See also

*

*How to delete directories based on find output?

*find -delete does not delete non-empty directories

A: You could use shell globs instead of find:
for d in */ ; do
    rmdir "$d"
done

The shell glob */ matches all folders in the current directory. This for-loop construction takes care of correct word splitting automatically.
Note that depending on your shell options, this might ignore hidden folders (name starting with a .). That behaviour can be changed to match all files for the current session using the command shopt -s dotglob.
Also don't forget to always quote your variables.


text:
Q: deploy c# application to linux instance amazon ec2 I have written a winform c# application, how can i deploy it in a linux instance on amazon ec2?

A: You have to install mono on your linux ec2 instance in order to run a winforms app.
You can find information about deploying on a mono machine here: http://www.mono-project.com/Guidelines:Application_Deployment
Is this what you would like to do?


text:
Q: cruisecontrol.net email On CruiseControl.net there is a link called "NUnit Details".   When you click on this it gives a lot of details including  a summary section that looks similar to this…
Summary
Assemblies tested:  2
Tests executed: 56
Passes: 54
Fails:  2
Ignored:    2
I would like the summary emailed to me on every build.   Any tips would be great.

A: The format of the e-mail is configured in the ccnet.exe.config or ccservice.exe.config (in C:\Program Files\CruiseControl.NET\server) if you are running ccnet a service.
I believe the file that you want to include is tests.xml as that includes a detailed listing of the nunit test results. Modify the xslFiles section of the configuration file to include this stylesheet. It will look something like this.
<!-- Specifies the stylesheets that are used to transform the build results when using the EmailPublisher -->
<xslFiles>
    <file name="xsl\header.xsl"/>
    <file name="xsl\compile.xsl"/>
    ...
    <!-- add tests.xsl here... -->
    <file name="xsl\tests.xsl"/>
</xslFiles>


text:
Q: generating an array out of another array by using a unique key I have an array that contains 3 products with attributes of "color" and "size" and the products are identified by a number ( ['code'] ).
My problem is that when i pull the data from the database I get this array that is in 6 pieces because "color" and "size" get stored in separate arrays.
My question is, how do I generate the data into an array of these 3 products with all their data in the same array.
Array(

   [0] => Array
       (
        [code] => 123
        [name] => box
        [stock] => 2.00
        [price] => 10.00
        [color] => brown
    )

[1] => Array
    (
        [code] => 123
        [name] => box
        [stock] => 2.00
        [price] => 10.00
        [size] => L
    )

[2] => Array
    (
        [code] => 1234
        [name] => box
        [stock] => 3.00
        [price] => 11.00
        [color] => brown
    )

[3] => Array
    (
        [code] => 1234
        [name] => box
        [stock] => 3.00
        [price] => 11.00
        [size] => XL
    )

[4] => Array
    (
        [code] => 12345
        [name] => box
        [stock] => 4.00
        [price] => 12.00
        [size] => XL
    )

[5] => Array
    (
        [code] => 12345
        [name] => box
        [stock] => 4.00
        [price] => 12.00
        [color] => gray
    )

)
Expected output:
[0] => Array
    (
    [code] => 123
    [name] => box
    [stock] => 4.00
    [price] => 12.00
    [color] => gray
    [size] => XL
)

What i'm looking to do is just combine the doubled array into one. Dont want to mess with SQL anymore - it gets attribute name in one table, attribute values from another table, code,stock,price from another table, name from another table. I know something can be done with just this array even if it will be just a temporary solution.

A: You can do this:
assuming your array is $products
$merged = array();

foreach($products as $product) {
    if (!isset($sorted[$product['code']])) {
        $merged[$product['code']] = $product;
    } else {
        $merged[$product['code']] = array_merge($sorted[$product['code']], $product);
    }
}

Use the product code as array key and then merge the array.

A: If the two rows are always direct successors, with the first one holding the color field, while the latter holes the size field, you can make it easily by iterating over them in a for loop:
$maxCount = count($array);
for ($i = 1; $i < $maxCount; $i += 2) {
    $array[$i - 1]['size'] = $array[$i]['size'];
    unset($array[i]);
}

This will iterate over each second element of the array and add the size field to the preceding field.
If you need to have succeeding array keys afterwards you can call $arry = array_values($array);.

In case the the associated rows might not be successors you need to map them based on their code field (in case thats the primary key). You can use array_reduce() for that:
$desiredOutput = array_reduce($array, function($output, $element) {
    if (!array_key_exists($element['code'], $output)) {
        $output[$element['code']] = $element;
    } elseif (array_key_exists('size', $element)) {
        $output[$element['code']]['size'] = $element['size'];
    } elseif (array_key_exists('color', $element)) {
        $output[$element['code']]['color'] = $element['color'];
    }
    return $output;
}, []);


text:
Q: Microsoft Access Form To Query for Multi Value Field I am trying to write an Microsoft Access query from a form with a multi value field being the criteria. The field I am trying to use is called Population and the field is represented in my database as a List Box that allows multiple values and it is in the Building table.  The values it allows are the following:
"Singles";"Familes";"Families with Children";"Youth/Young Adults";"Veterans";

The form that I am creating is called HousingSearch.
I am trying to create a form which uses this field, so someone could use the list box and check off the values they want and click on the button which would open a query.  I know having done this with single value fields the criteria in the query looks something like
[forms]![HousingSearch]![Building]![Population]

but if you try the same thing for a multi value field nothing is returned for the query.  Any help would be appreciated.

A: From the information you have provided it seems that the phrase [Forms]![HousingSearch]![Building]![Population] are combining a request that starts with a form and then jumps to a table.
You are asking access to find data in a form but the information you're most likely trying to access is in a table.  I don't quite understand what you're end result is but I think that you most likely want to refer to your information this way [Building]![Population].  Referring to your data this way makes access look at the table of [Building] and then into the field of [Population].
It's been a while since you posted, if you haven't cleared things up already I hope this helps.


text:
Q: INSERT VALUES from another table and ADD NEW VALUES TOO into a table I am trying to insert values into a table called charterFlight. What I'm trying to do is copy the aircraft_id, crew_id and customer_id from another table AND add/insert the remaining values as well.
INSERT INTO charterflight
    (aircraft_id, crew_id, customer_id, flight_time, flight_date,destination)
SELECT
     aircraft_id, crew_id, customer_id --(and the remaining values here)
FROM aircraft, crew, customer

Running the code above doesn't produce any error, however it doesn't insert any rows as well!!!!

A: Based on this comment...
@Ollie Error starting at line 1 in command:
INSERT INTO charterflight (aircraft_id, crew_id, customer_id, flight_time, flight_date,destination)
SELECT aircraft_id, crew_id, customer_id
FROM aircraft, crew, customer
Error at Command Line:1 Column:12 Error report: SQL Error: ORA-00947: not enough values 00947. 00000 - "not enough values" *Cause: *Action:

You're trying to insert three values into a table that has 6 fields.
The number of fields in INSERT INTO table (...) must match the fields in the table.  And then the number fields in SELECT ... FROM must match those fields too.
Any mis-match causes the error you refer to.

EDIT : Reply to your comments
As best I can suggest, you insert every combination of Aircraft, Crew and Customer with the following...
INSERT INTO charterflight (aircraft_id, crew_id, customer_id, flight_time, flight_date, destination)
SELECT aircraft_id, crew_id, customer_id, NULL, NULL, NULL
FROM aircraft, crew, customer

Then you can replace the NULL values by hand separately another time.

If you don't want the NULL values for flight_time, flight_date, destination, then you could just copy the results of SELECT into EXCEL, and write a formular in Excel that makes your inster statement for you.

Beyond these two approaches I have to confess that I'm not actually sure what you want to happen.

A: In case of php we can do it like this,
<?php
$var1='';   //some value
$var2='';   //some value
$var3='';   //some value

 $qry = "INSERT INTO charterflight
    (aircraft_id, crew_id, customer_id, flight_time, flight_date,destination)
SELECT
     aircraft_id, crew_id, customer_id ,$var1,$var2,$var3
FROM aircraft, crew, customer";
?>

We can pass the variables after the column names of the selected table for inserting.


text:
Q: How do I use a promise to chain several setTimeout functions? I have several setTimeout functions in my applications being called at different times (and some being called at the same time after page load)
I am trying to figure out a way to compress and enhance this code. Below is an example of 3 setTimeout functions I am calling, there are in-fact a lot more in my application:
  setTimeout(function () {
    $('.itemOne').css({
      'visibility': 'visible'
    }).addClass('animated slideInRight animate-duration-100');
  }, 1000);

  setTimeout(function () {
    $('.itemTwo').css({
      'background-color': 'rgba(0, 27, 53, 0.8)',
    });
  }, 1200);

  setTimeout(function () {
    $('.itemThree').css({
      'background-color': 'rgba(136, 211, 192, 0.25)',
    });
  }, 1200);

Is the best way to chain these to use a promise chain to make this code compact and neater? Or is there another way?

A: Not sure if that's what you wanted. I have created a factory wrapping your logic along with a callback triggered once all promises resolve. Let me know if you need further assistance! Cheers!
function createCssPromise($target, styleObj, timeout) {
  const { newStyle, newClass } = styleObj;

  return new Promise((resolve) => {
    setTimeout(() => {
      if (newStyle) {
        $target.css(newStyle);
      }
      if (newClass) {
        $target.addClass(newClass);
      }

      resolve();
     }, timeout);
  });
}

const targetObj = $('.itemOne');
const styleObj = {
  newStyle: { 'visibility': 'visible'},
  newClass: 'animated slideInRight animate-duration-100',
};
const timeout = 1000;

const firstPromise = new createCssPromise(targetObj, styleObj, timeout);
const secondPromise... //follow the pattern
const thirdPromise...  // follow the pattern

Promise.all([firstPromise, secondPromise, thirdPromise]
  .then(() => console.log('done!'));

*Promise.all is not natively supported in <= IE11.

A: Please note that this doesn't answer the exact question about using promises, but inside the question you ask about making the code more compact and neater. You could refactor this quite easily into the following, making all of your calls to timeout one liners:
function applyCssWithTimeout($target, cssToApply, timeout, classesToAdd) {
  setTimeout(function() {
    $target.css(cssToApply).addClass(classesToAdd);
  }, timeout);
}

applyCssWithTimeout($('.itemOne'), { 'visibility': 'visible' }, 1000, 'animated slideInRight animate-duration-100');
applyCssWithTimeout($('.itemTwo'), { 'background-color': 'rgba(0, 27, 53, 0.8)' }, 1200);
applyCssWithTimeout($('.itemThree'), { 'background-color': 'rgba(136, 211, 192, 0.25)' }, 1200);


text:
Q: Adding new forms to a Django formset based on POST data I am trying to populate a Django formset using data from a POST request.  I am able to display the formset properly and instantiate it again mostly alright, but I'm having an issue where the formset is ending up with 2 blank rows at the end, which is undesirable.  Below is the function we've been using in views.py:
forms.py
class DepositForm(forms.Form):
    InsID = forms.IntegerField()
    DepositTypeID = forms.IntegerField()
    DepositAmount = forms.IntegerField()
    Account = forms.IntegerField()

DepositFormSet = formset_factory(DepositForm, extra=1)

views.py
def _DepositEditor(request, c):
    if request.POST.has_key('form-0-InsID'):
        formset = DepositFormSet(request.POST)
        if formset.is_valid():
            formset = DepositFormSet(initial=formset.cleaned_data)
    else:
        formset = DepositFormSet()
    c['formset'] = formset

    return render_to_response('deposits/dep.html', c)

dep.html
<form action="" method="post">

{{formset.management_form}}
{% for form in formset.forms %}
    {{form.errors }}
    {% for field in form %}
        {{field.label}}: {{field}}
    {% endfor %}
  <br />
{% endfor %}

<input type="submit" name="add" value="Add Deposit"></input>

</form>

That should be all the relevant code.  Anyway, the template displays the whole formset, which should include a blank row (or, in the case of an error, no blank rows but error messages above the last row).  The problem is occurring when you click "Add" with the last row blank.  In the code, this still passes formset.is_valid(), so it then creates the new formset with an extra field.  If you click add here, it returns with errors, but still allows you to fill out all but the last row and make a valid formset.  Is there a way to tell my formset that blank forms should fail validation?  Or alternatively is there better way to do this?  The page eventually is planned to integrate some jquery stuff, so while that is not ideal, if there is a good way to solve this problem using jquery tools that would probably be good enough.  Thanks a lot!

A: In your views.py:
-            formset = DepositFormSet(initial=formset.cleaned_data)
+            data = formset.cleaned_data
+            if data[-1]=={}:
+                data=data[:-1]
+            formset = DepositFormSet(initial=data)

It looks pretty much like a feature than like a bug ;)

A: I've not done this myself, but if you wanted to actually make it invalid with a blank entry, perhaps you'd consider putting it in the clean method:
http://docs.djangoproject.com/en/dev/topics/forms/formsets/#custom-formset-validation


text:
Q: What is optimal algorithm to check if a given integer is equal to sum of two elements of an int array? def check_set(S, k):
S2 = k - S
set_from_S2=set(S2.flatten())
for x in S:
    if(x in set_from_S2):
        return True
return False

I have a given integer k. I want to check if k is equal to sum of two element of array S.
S = np.array([1,2,3,4])
k = 8

It should return False in this case because there are no two elements of S having sum of 8. The above code work like 8 = 4 + 4 so it returned True
I can't find an algorithm to solve this problem with complexity of O(n).
Can someone help me?

A: You have to account for multiple instances of the same item, so set is not good choice here.
Instead you can exploit dictionary with value_field = number_of_keys (as variant - from collections import Counter)
A = [3,1,2,3,4]
Cntr = {}
for x in A:
    if x in Cntr:
        Cntr[x] += 1
    else:
        Cntr[x] = 1

#k = 11
k = 8
ans = False
for x in A:
    if (k-x) in Cntr:
        if k == 2 * x:
            if Cntr[k-x] > 1:
                ans = True
                break
        else:
            ans = True
            break
print(ans)

Returns True for k=5,6 (I added one more 3) and False for k=8,11

A: Adding onto MBo's answer.
"Optimal" can be an ambiguous term in terms of algorithmics, as there is often a compromise between how fast the algorithm runs and how memory-efficient it is. Sometimes we may also be interested in either worst-case resource consumption or in average resource consumption. We'll loop at worst-case here because it's simpler and roughly equivalent to average in our scenario.
Let's call n the length of our array, and let's consider 3 examples.
Example 1
We start with a very naive algorithm for our problem, with two nested loops that iterate over the array, and check for every two items of different indices if they sum to the target number.

*

*Time complexity: worst-case scenario (where the answer is False or where it's True but that we find it on the last pair of items we check) has n^2 loop iterations. If you're familiar with the big-O notation, we'll say the algorithm's time complexity is O(n^2), which basically means that in terms of our input size n, the time it takes to solve the algorithm grows more or less like n^2 with multiplicative factor (well, technically the notation means "at most like n^2 with a multiplicative factor, but it's a generalized abuse of language to use it as "more or less like" instead).

*Space complexity (memory consumption): we only store an array, plus a fixed set of objects whose sizes do not depend on n (everything Python needs to run, the call stack, maybe two iterators and/or some temporary variables). The part of the memory consumption that grows with n is therefore just the size of the array, which is n times the amount of memory required to store an integer in an array (let's call that sizeof(int)).
Conclusion: Time is O(n^2), Memory is n*sizeof(int) (+O(1), that is, up to an additional constant factor, which doesn't matter to us, and which we'll ignore from now on).
Example 2
Let's consider the algorithm in MBo's answer.

*

*Time complexity: much, much better than in Example 1. We start by creating a dictionary. This is done in a loop over n. Setting keys in a dictionary is a constant-time operation in proper conditions, so that the time taken by each step of that first loop does not depend on n. Therefore, for now we've used O(n) in terms of time complexity. Now we only have one remaining loop over n. The time spent accessing elements our dictionary is independent of n, so once again, the total complexity is O(n). Combining our two loops together, since they both grow like n up to a multiplicative factor, so does their sum (up to a different multiplicative factor). Total: O(n).

*Memory: Basically the same as before, plus a dictionary of n elements. For the sake of simplicity, let's consider that these elements are integers (we could have used booleans), and forget about some of the aspects of dictionaries to only count the size used to store the keys and the values. There are n integer keys and n integer values to store, which uses 2*n*sizeof(int) in terms of memory. Add to that what we had before and we have a total of 3*n*sizeof(int).
Conclusion: Time is O(n), Memory is 3*n*sizeof(int). The algorithm is considerably faster when n grows, but uses three times more memory than example 1. In some weird scenarios where almost no memory is available (embedded systems maybe), this 3*n*sizeof(int) might simply be too much, and you might not be able to use this algorithm (admittedly, it's probably never going to be a real issue).
Example 3
Can we find a trade-off between Example 1 and Example 2?
One way to do that is to replicate the same kind of nested loop structure as in Example 1, but with some pre-processing to replace the inner loop with something faster. To do that, we sort the initial array, in place. Done with well-chosen algorithms, this has a time-complexity of O(n*log(n)) and negligible memory usage.
Once we have sorted our array, we write our outer loop (which is a regular loop over the whole array), and then inside that outer loop, use dichotomy to search for the number we're missing to reach our target k. This dichotomy approach would have a memory consumption of O(log(n)), and its time complexity would be O(log(n)) as well.

*

*Time complexity: The pre-processing sort is O(n*log(n)). Then in the main part of the algorithm, we have n calls to our O(log(n)) dichotomy search, which totals to O(n*log(n)). So, overall, O(n*log(n)).

*Memory: Ignoring the constant parts, we have the memory for our array (n*sizeof(int)) plus the memory for our call stack in the dichotomy search (O(log(n))). Total: n*sizeof(int) + O(log(n)).
Conclusion: Time is O(n*log(n)), Memory is n*sizeof(int) + O(log(n)). Memory is almost as small as in Example 1. Time complexity is slightly more than in Example 2. In scenarios where the Example 2 cannot be used because we lack memory, the next best thing in terms of speed would realistically be Example 3, which is almost as fast as Example 2 and probably has enough room to run if the very slow Example 1 does.
Overall conclusion
This answer was just to show that "optimal" is context-dependent in algorithmics. It's very unlikely that in this particular example, one would choose to implement Example 3. In general, you'd see either Example 1 if n is so small that one would choose whatever is simplest to design and fastest to code, or Example 2 if n is a bit larger and we want speed. But if you look at the wikipedia page I linked for sorting algorithms, you'll see that none of them is best at everything. They all have scenarios where they could be replaced with something better.


text:
Q: Standard deck of 52 playing cards in curated data? I am not sure how to find out what all is included as curated data. For example, are the individual images of each of the 52 cards in a standard deck of playing cards included?
If not, is there a way to systematically access these from web images?

A: Did you see Mathematica Package for Texas Hold'em from Sal Mangano. It's a Poker Simulation Library in Mathematica from http://www.mathematicacookbook.com. The code covers parsing cards, monte carlo simulation, a game engine as well as visual interface with cards. You can access also the images of cards from this link of same library.

*

*Demo Videos

*The code for Texas Hold'em

A: In versions 11.3+, you can use Jon McLoone's ResourceFunction["PlayingCardGraphic"]
playingcardgraphic = ResourceFunction["PlayingCardGraphic"];

SeedRandom[777]
playingcardgraphic[RandomSample[Range @ 52, 5]]

Multicolumn[playingcardgraphic /@ Range[52], 13,
  Appearance -> "Horizontal", Spacings -> {0, 0}]

A: You can get some nice vector playing cards from this site, licensed under GNU LGPL (read more here). Download this folder to your computer and then try the following:
(* replace with your download dir *)
files = Flatten@With[{dir = "~/Downloads/Chrome/mma/SVG_and_EPS_Vector_Playing_Cards_Version_1.3/EPS_Vector_Playing_Cards_Version_1.3/52-Individual-Vector-Playing-Cards-1.2_(EPS-Format)/"},
    FileNames["*.eps", dir, 2]];

Clear@CardData
SetAttributes[CardData, Listable]
StringCases[Last@FileNameSplit@#, card__ ~~ ".eps" :>
    (CardData[card] = ImageCrop@Import@#)] & /@ files;

You can then use this like any other curated data:
GraphicsRow[CardData@{"2C", "KH", "AS", "QD", "JC"}]

Random hand generator:
You can extend this further and also create a random hand generator using Mathematica as follows:
deck = Flatten@With[
    {
        ranks = CharacterRange["2", "9"] ~Join~ {"10", "J", "Q", "K", "A"},
        suits = {"C", "S", "H", "D"}
    },
    Outer[StringJoin, ranks, suits]
];
dealHand[n_Integer] /; 1 ≤ n ≤ 52 := CardData@RandomSample[deck, n]

Use this to deal a hand as dealHand[5], for instance. You'll have to modify this a bit to deal randomly and exhaust the deck at the same time (as you would in a game). There was a question on this previously on this site and I gave an answer based on Internal`Bag[] that will be useful here (along with some of the other answers there).

A: Not super high quality, but this might do for some purposes:
cards = Join[
  Table[ToString[k], {k, 2, 10}],
  {"Jack", "Queen", "King", "Ace"}];
suits = {"hearts", "diamonds", "clubs", "spades"};
deck = Flatten[Outer[#2 <> " of " <> #1 &, suits, cards]];
images = Table[
  WolframAlpha[card, {{"Image", 1}, "Content"}], {card, deck}];
Grid[Partition[images, 13]]

In terms of your real question, namely "how to find out what all is included as curated data", I had no clue if playing card images were included or not.  I simply asked Wolfram Alpha via a query like so:

Choosing "Subpod content" as shown, I learned that the command to access the image is
WolframAlpha["4 of clubs", {{"Image", 1}, "Content"}]

I couldn't figure out how to access the whole deck at once, but from here I was able to put the whole thing together programmatically.

A: I don't know if this question is specifically asking about finding images in MMA's data, but if the end goal is to get playing card images, then using an online image and partition seems to work great.  Link to image
ImagePartition[
     Import["http://www.milefoot.com/math/discrete/counting/images/cards.png"],{73, 98}] // Grid

Edit: The lack of a top outline over the third row of cards is an artifact of the pdf I saved the image as, not the actual MMA output.  Also, the slightly thicker right side outline is a property of the image, which is supposed to have a shadow.  This can be removed programmatically if needed.
Finally, I suppose that the way I went about extracting the individual card images from the imported image could have been more elegant than what I did, but I don't think there's an issue with trial and error for finding the card dimensions if it's just as effective as whatever the more elegant code is.

A: It is not entirely clear to me whether the playing cards in your question are just an example of what you want to find or the actual target. Since the other answers already provide you with the latter I'll provide a way to explore ExampleData.
The following two lines of code will build a complete overview of what's hidden in there. Running it may take a bit of time as most of the data will have to be transfered from the Wolfram server to your local paclet store for the first time.
switchedDisplay[stuff_] :=
   DynamicModule[{x=False},
       Row[{"Show:  ", Checkbox[Dynamic[x]], "    ",
             Dynamic[If[x, ExampleData@stuff, stuff], SynchronousUpdating -> False]}]
   ]
TabView[# -> TabView[switchedDisplay /@ ExampleData[#]] & /@ ExampleData[]]

MacOS
MacOs doesn't seem to like long TabViews, so the code may have to be changed a little bit.
This adds another layer of TabViews where necessary:
MacMax = 30;
TabView[# ->
    TabView[If[Length@ExampleData[#] > MacMax,
      TabView /@ Partition[switchedDisplay /@ ExampleData[#], MacMax],
       switchedDisplay /@ ExampleData[#]]] & /@ ExampleData[]]

MacOS user MarkMcClure reports that ControlPlacement -> {Top, Left} in TabView also prevents problems from occurring.


text:
Q: Expandable div that's rotated with css I am trying to create a page layout with a rectangular div on the left side that's rotated 10 degrees, expands with the size of the browser, and doesn't show its edge on the top, left, and bottom. Meaning, the page should appear to be split in the middle on a slant.
My code so far creates the div properly, but when I expand the page you begin to see the edges.
http://jsfiddle.net/jpQvL/1/
HTML

CSS
html, body {
   margin: 0;
   padding: 0;
   height: 100%;
 }

#wrapper {
    position:relative;
    height: 100%;
   }

#right {
    background: #000;
    transition: all 0.5s ease-in-out 0s;
    width: 50%;
    position: fixed;
    min-height: 110%;
    transform: rotate(10deg);
    top: -73px;
}

A: The problem is that the tranform property needs render prefixes. You have to add these lines:
-webkit-transform: rotate(10deg);
-moz-transform: rotate(10deg);
-o-transform: rotate(10deg);
-ms-transform: rotate(10deg);
transform: rotate(10deg);

take a look at this
or use one of many prefix-free scripts like this one


text:
Q: How do I make my Apple earphone's play button not launch iTunes and instead pause/play a video on YouTube? What the title says. I already have BeardedSpice for my media keys, but I wanted to know if there was a way to make the earbuds' play button not launch iTunes every time I press it.

A: Taken from here: The short answer is that you can't select which media app has priority since they're all equally treated, but if there's nothing playing iTunes takes preference.
The linked answer also pointed to a patch for the Remote Control Daemon at https://github.com/thebitguru/play-button-itunes-patch, which might be what you were looking for. It's a 1 MB download and you will need at least El Capitan (OS 10.11). On that page it says:

This is a patch for removing the default OS X behavior of always starting iTunes when the play button on the keyboard is pressed. This feature can be useful for a lot of users, but it can also be annoying if you are using VLC, Nightingale or other similar programs that support the media keys.
The application will patch the Remote Control Daemon to prevent it from starting iTunes whenever you press the play button on the keyboard or an external remote control. This will only prevent iTunes from starting, all other functions (like play/pause while iTunes is running) will continue to work as before. The original file is backed up in case you would like to restore the original functionality.

It's unfortunately not a straight forward installation. You find the instructions and download on https://thebitguru.com/projects/itunes-patch.


text:
Q: Getting position of the annotation relative to screen I'd like to acquire the position (not map coordinates) of the annotation relative to the screen.
For example, for an annotation on the map, I'd like to know how far that particular pin is from the top left corner (0,0).
I've looked at the documentations, and it does not provide information on its absolute or relative location.
I'll look further into the quartz framework before possibly sub-classing and overriding the rendering methods as a last resort.
Any ideas?

A: Given an MKAnnotation, you can get the MKAnnocationView using [MKMapView viewForAnnoation]. You can use that to the get the center of the view in window coordinates:
CGPoint windowPoint = [annView convertPoint:[annView center] toView:window]

The main UIWindow is generally available through your AppDelegate.


text:
Q: adding values from two columns tied to two other columns (where values repeat) in python I'm trying to figure out the top team scorer in a df.
But how do I add values of columns "home_score" and "away_score" for teams with same names in the columns "home_team" and "away_team". Note: the team names repeat in the rows in both team columns. I've looked at dictionary, concatenate, sum... and now i'm just confused.
home_team    away_team    home_score    away_score
  A            D            3          5
  B            C            1          0
  C            B            2          1
  D            A            3          5
  A            B            3          5

In the above example, the output should be team A with 11 (3+3+5). How would I find an answer in a df?

A: Get all score data.
import collections

score_data = collections.defaultdict(int)
for _, row in df.iterrows():
    score_data[row[0]] += row[2]
    score_data[row[1]] += row[3]

To get the highest achiever, you may do the following trick for finding maximum.
top_team, top_score = max((t, s) for s, t in score_data.items())


text:
Q: optaplanner-examples: Unmarshalling of solverConfigResource I cloned from git the optaplanner-examples to learn how I can implement the library for my problem case.
I modify the example PassionAdmissionSchedule and I want only the code without swing. When I want to start the solver, I get the fllowing error message.
Exception in thread "main" java.lang.IllegalArgumentException: Unmarshalling of solverConfigResource (test/patientAdmissionScheduleSolverConfig.xml) fails.
at org.optaplanner.core.impl.solver.XStreamXmlSolverFactory.configure(XStreamXmlSolverFactory.java:114)
at org.optaplanner.core.api.solver.SolverFactory.createFromXmlResource(SolverFactory.java:90)
at test.PatientAdmissionScheduleApp.init(PatientAdmissionScheduleApp.java:29)
at test.PatientAdmissionScheduleApp.main(PatientAdmissionScheduleApp.java:24)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: com.thoughtworks.xstream.converters.ConversionException: Cannot load java class
                test.BedDesignationPillarPartSwapMoveFactory

---- Debugging information ----
message             : Cannot load java class
test.BedDesignationPillarPartSwapMoveFactory

class               : java.lang.Class
required-type       : java.lang.Class
converter-type      : com.thoughtworks.xstream.converters.SingleValueConverterWrapper
wrapped-converter   : com.thoughtworks.xstream.converters.extended.JavaClassConverter
line number         : 25
class[1]            : org.optaplanner.core.config.heuristic.selector.move.factory.MoveListFactoryConfig
converter-type[1]   : com.thoughtworks.xstream.converters.reflection.ReflectionConverter
class[2]            : org.optaplanner.core.config.heuristic.selector.move.composite.UnionMoveSelect    orConfig
class[3]            : org.optaplanner.core.config.localsearch.LocalSearchPhaseConfig
class[4]            : org.optaplanner.core.config.solver.SolverConfig
version             : 1.4.9
-------------------------------

The solver config is the same.
<?xml version="1.0" encoding="UTF-8"?>
<solver>
<!--<environmentMode>FAST_ASSERT</environmentMode>-->
<solutionClass>test.PatientAdmissionSchedule</solutionClass>
<entityClass>test.BedDesignation</entityClass>

<scoreDirectorFactory>
    <scoreDrl>patientAdmissionScheduleScoreRules.drl</scoreDrl>
</scoreDirectorFactory>

<termination>
    <secondsSpentLimit>300</secondsSpentLimit>
</termination>
<constructionHeuristic>
    <constructionHeuristicType>WEAKEST_FIT_DECREASING</constructionHeuristicType>
</constructionHeuristic>
<localSearch>
    <unionMoveSelector>
        <changeMoveSelector/>
        <!--<swapMoveSelector/>-->
        <!--<pillarSwapMoveSelector/>-->
        <moveListFactory>
            <moveListFactoryClass>
                test.BedDesignationPillarPartSwapMoveFactory
            </moveListFactoryClass>
        </moveListFactory>
    </unionMoveSelector>
    <acceptor>
        <entityTabuSize>7</entityTabuSize>
    </acceptor>
    <forager>
        <acceptedCountLimit>1000</acceptedCountLimit>
    </forager>
</localSearch>

The error message says, that java can't load the class BedDesignationPillarSwapMoveFactory, but why?

A:
line number         : 25

Check line number 25 of your solver config XML.
This is not valid:
        <moveListFactoryClass>
            test.BedDesignationPillarPartSwapMoveFactory
        </moveListFactoryClass>

This is valid:
        <moveListFactoryClass>test.BedDesignationPillarPartSwapMoveFactory</moveListFactoryClass>

Presume that there is a java package test with that class in that package.


text:
Q: Geodesic Curvature of a curve on a surface with a metric This is a problem from a past comprehensive exam:

Find the geodesic curvature of the curve $\alpha(t) = (t,y_0)$ on a geometric surface endowed with a metric $ds^2 = f^2(x,y)(dx^2+dy^2)$ and the standard orientation

The definitions of geodesic curvature I'm familiar with are either as $||\nabla_{\alpha'}\alpha'||$ or $k_g = \frac{d\varphi}{ds}+\omega_{12}(\alpha')$ where $\varphi$ is the angle between $\alpha'$ and $E_1$ along $\alpha$.
Here's what I have so far: Using the metric we can define a frame field: $E_1 = \frac{1}{f}\frac{\partial}{\partial x}$, $E_2 = \frac{1}{f}\frac{\partial}{\partial y}$, we can write $\alpha'$ in this metric as follows: $$\alpha'(t) = (1,0) = \frac{\partial}{\partial x} = fE_1$$
Here's where I come to a crossroads: Using the definition $||\nabla_{\alpha'}\alpha'||$ I believe that $k_g$ would be zero. The norm $||\alpha'|| = |f|$, so $\frac{d\frac{\alpha'}{||\alpha'||}}{dt} = 0$, yet if I try the other method I get a different answer.
I can compute $\theta_1 = f dx, \theta_2 = fdy$, so I found $\omega_{12} = \frac{-f_y}{f}dx+ \frac{f_x}{f}dy$, and the angle $\varphi$ between $\alpha' = fE_1$ and $E_1$ should just be zero, so $k_g = \omega_{12}(\alpha')\frac{dt}{ds} $ to rescale with the metric.
I'm not sure which one produces the right answer, and I'm a bit confused which one I slipped up on, does anyone see a flaw in either approach or perhaps have an easier way of doing this problem?
Edit: Fully written out let $s$ denote arc length parameterization along $\alpha$, by the chain rule 1= $||\frac{d\alpha}{ds} || = ||\frac{d\alpha}{dt} |||\frac{dt}{ds} |$, so $\frac{dt}{ds} = 1/f$. Now I want to compute \frac{d\frac{\alpha'}{||\alpha'||}}{dt}:
\begin{align}
\frac{d\frac{\alpha'}{||\alpha'||}}{ds}  &= \frac{d\frac{\alpha'}{||\alpha'||}}{dt} \frac{dt}{ds}\\
&= (E_1)'\frac{dt}{ds}
\end{align}
And the derivative should just be 0, since I'm taking the derivative of a constant: 1.


text:
Q: String UTF-8 encoding with cyrillic in H2O I load csv file of utf-8 encoding with cyrillic strings. After parsing in Flow interface - i see not cyrillic, but not readable symbols like "пїўпѕЂпѕ™пїђпѕ" How can i use utf-8 cyrillic strings in H2O?

A: This appears to be a bug in the Flow interface, but only in the setupParse command. If you continue through and do the import, the data gets imported correctly.
I've reported the bug, with test data and screenshots (taken in Firefox) here:
https://0xdata.atlassian.net/browse/PUBDEV-4640
So if you have additional information, or the bug is behaving differently for you, it'd be good to add it to that bug report.

A: check your csv file in text and binary presentation to find how Cyrillic text is encoded, if it is UTF-8 it should look like this:
Привет
for the word
Привет


text:
Q: dynamic usage of attribute in recipe I am trying to increment the value and use in another resource dynamically in recipe but still failing to do that.
Chef::Log.info("I am in #{cookbook_name}::#{recipe_name} and current disk count #{node[:oracle][:asm][:test]}")

bash "beforeTest" do

  code lazy{ echo #{node[:oracle][:asm][:test]} }

end

ruby_block "test current disk count" do
  block do
    node.set[:oracle][:asm][:test] = "#{node[:oracle][:asm][:test]}".to_i+1
  end
end

bash "test" do
  code lazy{ echo #{node[:oracle][:asm][:test]} }
end

However I'm still getting the error bellow:
NoMethodError ------------- undefined method echo' for Chef::Resource::Bash

Cookbook Trace: ---------------
/var/chef/cache/cookbooks/Oracle11G/recipes/testSplit.rb:3:in block (2 levels) in from_file'
Resource Declaration: ---------------------
# In /var/chef/cache/cookbooks/Oracle11G/recipes/testSplit.rb
1: bash "beforeTest" do
2: code lazy{
3: echo "#{node[:oracle][:asm][:test]}"
4: }
5: end

Please can you help how lazy should be used in bash? If not lazy is there any other option?

A: bash "beforeTest" do
  code lazy { "echo #{node[:oracle][:asm][:test]}" }
end

You should quote the command for the interpolation to work; if not, ruby would search for an echo command, which is unknown in ruby context (thus the error you get in log).
Warning: lazy has to be for the whole resource attribute; something like this WON'T work:
bash "beforeTest" do
  code "echo node asm test is: #{lazy { node[:oracle][:asm][:test]} }"
end

The lazy evaluation takes a block of ruby code, as decribed here
You may have a better result with the log resource like this:
log "print before" do
  message lazy { "node asm test is #{node[:oracle][:asm][:test]}" }
end

A: I've been drilling my head solving this problem until I came up with lambda expressions. But yet just using lambda didn't help me at all. So I thought of using both lambda and lazy evaluation. Though lambda is already lazy loading, when compiling chef recipe's, the resource where you call the lambda expression is still being evaluated. So to prevent it to being evaluated (somehow), I've put it inside a lazy evaluation string.
The lambda expression
app_version = lambda{`cat version`}

then the resource block
file 'tmp/validate.version' do
    user 'user'
    group 'user_group'
    content lazy { app_version.call }
    mode '0755'
end

Hope this can help others too :) or if you have some better solution please do let me know :)


text:
Q: What values folder should I use for Galaxy S8+/S9+ I'm currently making a mobile application but I haven't managed to have my layout correctly displayed on S8+/S9+
I've used xxxhdpi folder but it didn't work
What should I do ?
Edit : I tried
<meta-data android:name="android.max_aspect" android:value="2.1" />
but it didn't works either

A: Samsung S8+/S9+ have 18:9 aspect ratio. To support these displays you don't need to create separate layout folders for that but set the aspect ratio in AndroidManifest.xml file under <application> element like below:
<meta-data android:name="android.max_aspect" android:value="2.1" />

This will inform to Android OS that your app can support maximum aspect ratio i.e. 18.5:9 which is almost same as Samsung S8+/S9+.
For more information check this official blog.
Update:
Create separate layout folder i.e. layout-swNNNdp for Galaxy S8+/S9+. Here NNN is screen resolution of Galaxy S8+/S9+ devices (maybe layout-sw1440dp but please confirm). Copy your current layout xml file into layout-swNNNdp and modify it to fit on Galaxy S8+/S9+ devices.
For more info check Providing alternative resources
Note:
xxxhdpi is for drawable resources not for layouts.

A: On my experience on S8+ you can use drawable-xxhdpi folder for your asset.
Cheers


text:
Q: How to access functions inside struct in C# class Program
{
   public  struct course
   {
        public string name;
        public int elecode;
        public int credit;

        public static void getdetails()
        {
            Console.WriteLine("Enter your Name");
           Ele.name = Console.ReadLine();

        }
   }

    static void Main(string[] args)
    {

        course ele;
        ele.getdetails();

    }
}

A: *

*Your method getdetails should not be static

*Remove Ele. inside getdetails

*Initialize course ele variable

Your code:
class Program
{
   public  struct course
   {
        public string name;
        public void getdetails()
        {
            Console.WriteLine("Enter your Name");
            name = Console.ReadLine();
        }
   }

    static void Main(string[] args)
    {
        course ele = new course();
        ele.getdetails();
    }
}

As was mentioned by @DavidHeffernan in comment about poor design, you have to know where to use class instead of struct to escape problems, when a value type gives you a COPY of the value

A: You can not call static method with instance. You have static method so call it with struct instead of calling it with the instance of struct.
course.getdetails();

The static member is callable on a class even when no instance of the
  class has been created. The static member is always accessed by the
  class name, not the instance name

Read more about static on this MSDN article Static Classes and Static Class Members (C# Programming Guide).


text:
Q: Repeated messages in R Console from Antidote (French Dictionary) Software Me: R version 3.50, Mac OS X 10.13.4
I'm not sure why my French spelling and grammar checker is getting involved with R at all, and I'm assuming that's what's causing the problem.
Specifically, I use Antidote (https://www.antidote.info/en) as a spelling and grammar checker for when I'm writing in French. It has several plugins that you'd expect: Safari, Chrome, Word, etc. It's also available from an icon in the right side of the menu bar. Shouldn't affect R at all.
However, when I start R.app, I get the following in my console without interruption:

.
.
.
    2018-06-05 00:20:53.998 R[40909:2097800] Antidote - Texteurs: Module texteur installé dans /Applications/R.app (org.R-project.R)
2018-06-05 00:21:04.089 R[40909:2097800] Antidote - Texteurs: Module texteur installé dans /Applications/R.app (org.R-project.R)
2018-06-05 00:21:14.117 R[40909:2097800] Antidote - Texteurs: Module texteur installé dans /Applications/R.app (org.R-project.R)
2018-06-05 00:21:24.162 R[40909:2097800] Antidote - Texteurs: Module texteur installé dans /Applications/R.app (org.R-project.R)
2018-06-05 00:21:34.288 R[40909:2097800] Antidote - Texteurs: Module texteur installé dans /Applications/R.app (org.R-project.R)
.
.
.

It started before what you see above and continues well after.
I did notice one other red warning in the console amidst a hundred of these:
objc[40909]: Class FIFinderSyncExtensionHost is implemented in both /System/Library/PrivateFrameworks/FinderKit.framework/Versions/A/FinderKit (0x7fff8d061c90) and /System/Library/PrivateFrameworks/FileProvider.framework/OverrideBundles/FinderSyncCollaborationFileProviderOverride.bundle/Contents/MacOS/FinderSyncCollaborationFileProviderOverride (0x11a502cd8). One of the two will be used. Which one is undefined.

...but I think that's unrelated.
Any ideas?

A: Here is the solution:

*

*Quit R

*Launch Antidote

*Click on the Antidote 9 menu, then on Preferences

*In the left column, click on Context menu

*In the right pane, click on the Options... button

*Click on the little + sign

*Navigate to your Applications folder and Choose R

*Confirm


text:
Q: Fetch image inside description tag RSS Reader/Android I am trying to build a simple RSS reader app, but i cannot fetch the image (img src) which is inside description tag of the rss feed. Do you have any suggestions?
         <description><![CDATA[

       	Призма - 12:16 24/03

       Пет години откако Македонија, Хрватска, Црна Гора и Србија потпишаа договори за екстрадиција на сопствените државјани, уапсен е човекот кој важеше за најбогатиот кумановец. Тој свое засолниште во последнава деценија најде во Белград, откако во ...

Капитал: Драган Даравелски е уапсен во Србија и тече постапка за негова екстрадиција

МКД: Во Србија е уапсен Драган Даравелски, се чека на негова екстрадиција во Македонија

Вест: Македоснката полиција потврди дека во Србија е уапсен Драган Даравелски

45 поврзани вести »

]]></description>
         <category>Македонија</category>
      </item>

Here's my method:
private void ProcessXml(Document data) {
        if (data != null) {
            feedItems=new ArrayList<>();
            Element root = data.getDocumentElement();
            Node channel = root.getChildNodes().item(1);
            NodeList items = channel.getChildNodes();
            for (int i = 0; i < items.getLength(); i++) {
                Node cureentchild = items.item(i);
                if (cureentchild.getNodeName().equalsIgnoreCase("item")) {
                    FeedItem item=new FeedItem();
                    NodeList itemchilds = cureentchild.getChildNodes();
                    for (int j = 0; j < itemchilds.getLength(); j++) {
                        Node cureent = itemchilds.item(j);
                        if (cureent.getNodeName().equalsIgnoreCase("title")){
                            item.setTitle(cureent.getTextContent());
                        }else if (cureent.getNodeName().equalsIgnoreCase("description")){
                            item.setDescription(cureent.getTextContent());
                        }else if (cureent.getNodeName().equalsIgnoreCase("pubDate")){
                            item.setPubDate(cureent.getTextContent());
                        }else if (cureent.getNodeName().equalsIgnoreCase("link")){
                            item.setLink(cureent.getTextContent());
                        }
//Here i want to process the image from the description tag
                    }
                    feedItems.add(item);
                }
            }
        }
    }

For example this rss feed:


text:
Q: Getting window.location.href to return page name and extension if URL ends with a / slash When using window.location.href on a page that ends with a / (a default.aspx lets say) the result is simply returning:
http://localhost/

I've been looking everywhere, but how can I get it to actually return the true URL?
http://localhost/default.aspx
Looking at the window.location object, the only options I see are:
hash: ""
host: "localhost"
hostname: "localhost"
href: "http://localhost/"
origin: "http://localhost"
pathname: "/"
port: ""
protocol: "http:"

A: That is the true URL; even if there is another URL that gives you the same information, (/my-page/ and /my-page/index.html) they're all JavaScript will know about. So unfortunately you can't sniff the server side tech that way.
Of course if you were desperate to know if /my-page/default.aspx was the same as /my-page/ you could call it asynchronously and if you get a 200 back, you could compare it's contents. That's definitely not something I'd recommend though.

A: This is not possible. Default document is set sever-side and the name is not accessible via JavaScript.
A workaround might be to get the name of the page server-side and pass it to the client (e.g. in a hidden field or JS variable).


text:
Q: Prove that in the union of two trees there exist a vertex with degree of at most $3$
Let $T_1=(V, E_1), T_2=(V,E_2)$ be trees on the same set of vertices, and let $G=(V,E_1 \cup E_2)$ be the graph resulting from the union of the two trees. Prove that there exist a vertex with degree of at most $3$.

My attempt, suppose that for all $v\in G, d(v)>3$, so the easy cases are if $G$ is a tree or has leafs.
Trying to show that there is a vertex such that $d(v)=2$, since both $T_{1,2}$ are trees, that means they must have leafs, if we have a connection between a leaf in $T_1$ to any point in $T_2$, then that leaf has a degree of $2$ in $G$.
I can't find a way prove that there's a vertex with a degree $3$ though...
Also, I just saw this: Prove that in two trees with same vertices there exists a vertex that the sum of its' degree in both trees is maximum $3$
I don't understand why $\sum d(v)\ge 4n$? shouldn't that be $2n$?

A: In the answer to the earlier question TheNotMe is using the hypothesis that $d_G(v)>3$ for each $v\in V$. Thus, $d_G(v)\ge 4$ for each $v\in V$, and $\sum_{v\in V}d_G(v)\ge 4n$, since $|V|=n$.


text:
Q: Replace previously printed lines in python I am struggling to replace the print lines in windows CMD
for i in range(10):
    print ("Range: ", i)
    print ("Loading... ")
    sys.stdout.write("\033[F"*2)
    sys.stdout.write("\033[K")

The issue is visible here:
Screenshot in python 3
I want to replace the first line Range: 1 so how can I do it in python 3.x


text:
Q: Wubi installer hangs on expanding I downloaded wubi installer for 12.04 LTS (64-bit) after deciding to re install Ubuntu, but every time I try it freezes on expanding. i have also tried using a bootable USB but after I choose install within windows it restarts and doesn't install. Is my computer not compatible or am I missing something.
p.s. I know there is already questions like this asked but I already exhausted their advice too.
envy 6-1040ca, windows 7 64bit
Specs (double checked):
http://h10010.www1.hp.com/wwpc/ca/en/ho/WF06b/321957-321957-3329744-5269150-5269150-5269347-5284416.html?dnr=1
log: http://paste.ubuntu.com/5665675/
Edit: I did run chkdsk and no diffrence

A: The reason you only get "Install inside Windows" and then it reboots is this: Why don't I have the option ''Install Ubuntu alongside with them''
What you can do about it is this: My disk already has 4 primary partitions, how can I install Ubuntu?
Why Wubi is freezing on expanding the image? I don't know, but if you want Wubi then you will have to provide the output of the Wubi log from the %temp% directory i.e. wubi-12.04.2-rev272.log. Also I recommend running chkdsk /f first and possibly defragmenting. If it worked before and stopped working then there could be some NTFS filesystem corruptiong that is causing problems.
After reviewing your log file, the only thing I can guess is that it's tripping over the space in your Windows user name. I've already seen cases where an apostrophe causes issues, but there's no diagnostic output in your case that shows why it is failing. I will take a look at the code to see.
You can do one of two things:

*

*Run it under a different windows account where the user name doesn't have a space

*Run Wubi with the 12.04.2 desktop ISO. This doesn't use the diskimage and doesn't need to expand anything so likely won't be affected. Note that to do this, you'll have to save the 12.04.2 desktop ISO in the same folder as Wubi, but you need to use a patched wubi (see Is there wubi.exe that can support ubuntu-12.04.2-desktop-amd64?
Either way, remember to use nomodeset to boot.


text:
Q: TomeEE Java Version 5 I installed TomEE plus version 1.5.1. It has Tomcat version 7. Can TomEE be used with Tomcat 6? It is possible?
Having a quick search on Google, doesn't give anything back.

A: Consider OpenEJB instead of TomEE.

*

*Manual Installation


text:
Q: Bootstrap and Panel Heading Color in SCSS for rails tutorial Fledgling programmer working through the onemontrails tutorials.  Its providing me with a crash course in Ruby, Rails, and some CSS.  I'm working with Devise and Panels to make my app look presentable.  Outside of the tutorial, I tried changing the default colors to make my site look different.  I'm storing the changes in a SCSS file.  Using a combination of the tutorial, google, and bootstrap documentation, I have been able to change the coloring for most everything, EXCEPT the panel header and footer.
If I follow some of the previous examples I have done for the jumbotron element, I successfully changed the panels bg color, but not the heading color;
$panel-bg: #E87E04;
$panel-heading-bg: #E87E04;

Bootstrap documentation for other CSS elements had how to change the color for headings, but I'm just not seeing it for panel headers.  Most of the googling I'm doing is providing me with information I am not clear on how to use with my SCSS file. I found many references to use
.panel-title

Just not sure how to relate that to my SCSS.  Can someone provide me with an example to what I am trying to accomplish, or links to the documentation I can't seem to find?

A: I believe you need to recompile the .scss into .css so that your changes are taken into effect.
You will have to use SASS and in terminal, cd to where your files are and then
sass --update input.scss:output.css
if you do not recompile then the css will not be updated, thus missing declarations.


text:
Q: Oxyplot throw exception when I add so many graphs I want to drow so many graphs with OxyPlot Library.
And I'm testing now that I can add how many graphs with dynamic (but I'll not add graphs over 10000 graphs because it's max graphs in real application).
However when I'll add over 200 graphs, the Oxyplot throw exception.
Exception message is "This PlotModel is already in use by some other PlotView control.".
There are all of my code. (In code, I add graph with dynamic and I add values to the all graphs each 5 second in other thread.)
//Xaml -- MainView
<Window x:Class="OxyplotStressTest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:oxy="clr-namespace:OxyPlot.Wpf;assembly=OxyPlot.Wpf"
    xmlns:local="clr-namespace:OxyplotStressTest"
    mc:Ignorable="d"
    Title="MainWindow" Height="550" Width="725">
<Grid>
    <Button Content="Add 100" HorizontalAlignment="Left" Height="32" Margin="20,23,0,0" VerticalAlignment="Top" Width="65" Click="Button_Click100"/>
    <Button Content="Add 50" HorizontalAlignment="Left" Height="32" Margin="102,23,0,0" VerticalAlignment="Top" Width="65" Click="Button_Click50"/>
    <Button Content="Add 10" HorizontalAlignment="Left" Height="32" Margin="189,23,0,0" VerticalAlignment="Top" Width="65" Click="Button_Click10"/>
    <Button Content="Add 1" HorizontalAlignment="Left" Height="32" Margin="274,23,0,0" VerticalAlignment="Top" Width="65" Click="Button_Click1"/>

    <Grid Margin="20,65,19,10">
        <ScrollViewer>
            <ItemsControl ItemsSource="{Binding List}">
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <StackPanel>
                            <Label Content="{Binding Tag}"/>
                            <oxy:PlotView HorizontalAlignment="Left" Height="130" Margin="20,23,0,0" VerticalAlignment="Top" Width="600"
                      Model="{Binding Chart}" IsMouseWheelEnabled="False" IsManipulationEnabled="False" />
                        </StackPanel>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>
        </ScrollViewer>
    </Grid>
</Grid>

//C# -- MainWindow.cs
public partial class MainWindow : Window
{
    private MainWindowViewModel mMainWindowViewModel = null;

    public MainWindow()
    {
        InitializeComponent();
        MainWindowViewModel mainWindowViewModel = new MainWindowViewModel();
        this.DataContext = mainWindowViewModel;
        mMainWindowViewModel = mainWindowViewModel;
        Thread thread = new Thread(new ParameterizedThreadStart(reloadGraph));
        thread.Start();
    }

    private void Button_Click100(object sender, RoutedEventArgs e)
    {
        AddGraph addGraph = new AddGraph(mMainWindowViewModel);
        addGraph.addGraph(100);
    }

    private void Button_Click50(object sender, RoutedEventArgs e)
    {
        AddGraph addGraph = new AddGraph(mMainWindowViewModel);
        addGraph.addGraph(50);
    }

    private void Button_Click10(object sender, RoutedEventArgs e)
    {
        AddGraph addGraph = new AddGraph(mMainWindowViewModel);
        addGraph.addGraph(10);
    }

    private void Button_Click1(object sender, RoutedEventArgs e)
    {
        AddGraph addGraph = new AddGraph(mMainWindowViewModel);
        addGraph.addGraph(1);
    }

    private void reloadGraph(object param)
    {
        while (true)
        {
            Thread.Sleep(5000);

            if (mMainWindowViewModel.List.Count > 0)
            {
                AddGraph addGraph = new AddGraph(mMainWindowViewModel);
                addGraph.reloadGraph();
            }

            Console.WriteLine(Environment.WorkingSet.ToString());
        }
    }
}

//C# -- MainViewModel
    public MainWindowViewModel()
    {
        listVal = new ObservableCollection<Items>();
        BindingOperations.EnableCollectionSynchronization(this.listVal, new object());
    }

    private ObservableCollection<Items> listVal = new ObservableCollection<Items>();
    public ObservableCollection<Items> List
    {
        get
        {
            return listVal;
        }
        set
        {
            listVal = value;
            NotifyPropertyChanged("List");
        }
    }

public class Items
{
    public string Tag { get; set; }
    private PlotModel chartVal = new PlotModel();
    public PlotModel Chart
    {
        get
        {
            return chartVal;
        }
        set
        {
            chartVal = value;
        }
    }
}

public class ViewModelBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    protected void NotifyPropertyChanged(String info)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(info));
        }
    }
}

//C# -- Model Class
class AddGraph
{
    private MainWindowViewModel mMainWindowViewModel = null;

    public AddGraph(MainWindowViewModel pMainWindowViewModel)
    {
        mMainWindowViewModel = pMainWindowViewModel;
    }

    public void addGraph(int pCount)
    {
        try
        {
            for (int i = 0; i < pCount; i++)
            {
                Random random = new Random();
                long data = random.Next(100);

                ColumnSeries column = new ColumnSeries();
                column.FillColor = OxyColors.SkyBlue;
                column.Items.Add(new ColumnItem() { Value = data });
                data *= random.Next(50);
                column.Items.Add(new ColumnItem() { Value = data });

                Items items = new Items();
                items.Tag = mMainWindowViewModel.List.Count.ToString();
                items.Chart.Series.Add(column);
                items.Chart.InvalidatePlot(true);

                mMainWindowViewModel.List.Add(items);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }

    public void reloadGraph()
    {
        try
        {
            List<Items> newList = new List<Items>();

            foreach (Items listItem in mMainWindowViewModel.List)
            {
                string tag = listItem.Tag;
                PlotModel plotModel = listItem.Chart;

                ColumnSeries oldGraph = (ColumnSeries)plotModel.Series[0];

                ColumnSeries newGraph = new ColumnSeries();
                newGraph.FillColor = OxyColors.SkyBlue;

                for (int i = 0; i < oldGraph.Items.Count; i++)
                {
                    if (oldGraph.Items.Count == 30 && i == 0)
                    {
                        continue;
                    }

                    newGraph.Items.Add(new ColumnItem() { Value = oldGraph.Items[i].Value });
                }

                Random random = new Random();
                long val = random.Next(500);
                val *= random.Next(50);

                newGraph.Items.Add(new ColumnItem() { Value = val });

                Items items = new Items();
                items.Tag = tag;
                items.Chart.Series.Add(newGraph);
                items.Chart.InvalidatePlot(true);

                newList.Add(items);
            }
#region   //there are my solution and it shows good performance
            int index = 0;

            foreach (var addItem in newList)
            {
                mMainWindowViewModel.List[index] = addItem;
                index++;
            }
#endregion

#region  //there are my first code and it has problem
            mMainWindowViewModel.List.Clear();

            foreach (var addItem in newList)
            {
                mMainWindowViewModel.List.Add(addItem);
            }
#endregion
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }
}

Maybe my code is bad, but I don't know where is the bad code because it dosen't stop on BreakPoint.
If you give me a advice, I'm so glad.

A: I think you may need to rebuild it a little using idea from OxyPlot Example: https://github.com/oxyplot/oxyplot/tree/develop/Source/Examples/WPF/WpfExamples
When i were working last months with oxyplots i found out that this official examples are well done with they ideas, they solution with Performance Demo using this virtualization may helps with performance:
            <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <VirtualizingStackPanel IsVirtualizing="True" IsItemsHost="True" />
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>

The problem may cause using NotifyPropertyChange as refreshing UI as adding new chart maybe you should somehow Unbind List > Notify > Bind New List.
Check more in the link and try to mash-ups they solution to make your own :)
I glad if i have helped some :)


text:
Q: cannot select/unselect angular-ui bootstrap checkbox I am using angular-ui bootstrap in my project. I use navigation bar, carousel, dropdowns etc. without problem. However checkbox html code doesn't work. I cannot click on checkbox to select/unselect. I am using bootstrap v3.3.6 and angularjs v1.5.5
<div class="checkbox">
   <label class="pull-left">
      <input type="checkbox" ng-model="accept"> I Accept Terms&Conditions
   </label>
</div>

If I remove class="checkbox" from div checkbox works fine.


text:
Q: Having issues Manifest merger failed with multiple errors Warning uses-permission#android.permission.ACCESS_BACKGROUND_LOCATION was tagged at AndroidManifest.xml:16 to remove other declarations but no other declaration present
  <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.CALL_PHONE" />
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission
        android:name="android.permission.ACCESS_BACKGROUND_LOCATION"
        tools:node="remove" />

here is my buildgradle:
android {
    compileSdkVersion 28
    buildToolsVersion '28.0.3'
    defaultConfig {
        applicationId "xxx"
        minSdkVersion 19
        targetSdkVersion 28
        versionCode 56
        versionName "1.1.6"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
    }
}


text:
Q: Use of Progressbar I have created an app where i have 5 buttons for streaming 5 different live channels. Along with 5 buttons i have a progressbar(ring). Iam using progress bar since the videos are taking time to load. I have written the main code in onBackground() of AsyncTask which returns some value which is called in the click event of the button. Since all 5 buttons have different url assigned, how can i use the same onBackground() for all 5 buttons? What to do in this case?Can anyone please provide me with a good example .

A: onBackground() is part of AsyncTask. It got nothing common with buttons or other UI elements. If you want to reuse the code simply pass your UI as argument to AsyncTask constructor and then use it when needed.

A: Video Path

private static String file_url = "url";
  in your activity

new DownloadFileFromURL().execute(file_url);
@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case progress_bar_type: // we set this to 0
        pDialog = new ProgressDialog(this);
        pDialog.setMessage("Downloading file. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setMax(100);
        pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pDialog.setCancelable(true);
        pDialog.show();
        return pDialog;
    default:
        return null;
    }
}

Background Async Task to download file

/**
     * Background Async Task to download file
     * */
    class DownloadFileFromURL extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Bar Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showDialog(progress_bar_type);
        }

        /**
         * Downloading file in background thread
         * */
        @Override
        protected String doInBackground(String... f_url) {
            int count;
            try {
                URL url = new URL(f_url[0]);
                URLConnection conection = url.openConnection();
                conection.connect();

                // this will be useful so that you can show a tipical 0-100%
                // progress bar
                int lenghtOfFile = conection.getContentLength();

                // download the file
                InputStream input = new BufferedInputStream(url.openStream(),
                        8192);

                // Output stream
                OutputStream output = new FileOutputStream(Environment
                        .getExternalStorageDirectory().toString()
                        + "/demo.mp4");

                byte data[] = new byte[1024];

                long total = 0;

                while ((count = input.read(data)) != -1) {
                    total += count;
                    // publishing the progress....
                    // After this onProgressUpdate will be called
                    publishProgress("" + (int) ((total * 100) / lenghtOfFile));

                    // writing data to file
                    output.write(data, 0, count);
                }

                // flushing output
                output.flush();

                // closing streams
                output.close();
                input.close();

            } catch (Exception e) {
                Log.e("Error: ", e.getMessage());
            }

            return null;
        }

        /**
         * Updating progress bar
         * */
        protected void onProgressUpdate(String... progress) {
            // setting progress percentage
            pDialog.setProgress(Integer.parseInt(progress[0]));
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        @Override
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after the file was downloaded
            dismissDialog(progress_bar_type);

            // Displaying downloaded video into video view
            // Reading image path from sdcard
            String videopath = Environment.getExternalStorageDirectory()
                    .toString() + "/demo.mp4";
            // setting downloaded into image view

        }

    }