text:
Q: Execution failed for task ':app:compileDebugJavaWithJavac'. after android studio update I recently just formatted my computer and i reinstalled android studio and after running my application which i was working in it gave me a Execution failed for task ':app:compileDebugJavaWithJavac'. I ran a stack trace and this is what it shows:
    * Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:compileDebugJavaWithJavac'.
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:100)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:70)
    at org.gradle.api.internal.tasks.execution.OutputDirectoryCreatingTaskExecuter.execute(OutputDirectoryCreatingTaskExecuter.java:51)
    at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:62)
    at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:60)
    at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:97)
    at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:87)
    at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:52)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
    at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.run(DefaultTaskGraphExecuter.java:248)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:241)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:230)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.processTask(DefaultTaskPlanExecutor.java:123)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.access$200(DefaultTaskPlanExecutor.java:79)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:104)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:98)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.execute(DefaultTaskExecutionPlan.java:626)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.executeWithTask(DefaultTaskExecutionPlan.java:581)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.run(DefaultTaskPlanExecutor.java:98)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
Caused by: org.gradle.api.internal.tasks.compile.CompilationFailedException: Compilation failed; see the compiler error output for details.
    at org.gradle.api.internal.tasks.compile.JdkJavaCompiler.execute(JdkJavaCompiler.java:50)
    at org.gradle.api.internal.tasks.compile.JdkJavaCompiler.execute(JdkJavaCompiler.java:35)
    at org.gradle.api.internal.tasks.compile.NormalizingJavaCompiler.delegateAndHandleErrors(NormalizingJavaCompiler.java:98)
    at org.gradle.api.internal.tasks.compile.NormalizingJavaCompiler.execute(NormalizingJavaCompiler.java:51)
    at org.gradle.api.internal.tasks.compile.NormalizingJavaCompiler.execute(NormalizingJavaCompiler.java:37)
    at org.gradle.api.internal.tasks.compile.CleaningJavaCompilerSupport.execute(CleaningJavaCompilerSupport.java:35)
    at org.gradle.api.internal.tasks.compile.CleaningJavaCompilerSupport.execute(CleaningJavaCompilerSupport.java:25)
    at org.gradle.api.internal.tasks.compile.incremental.IncrementalCompilationFinalizer.execute(IncrementalCompilationFinalizer.java:39)
    at org.gradle.api.internal.tasks.compile.incremental.IncrementalCompilationFinalizer.execute(IncrementalCompilationFinalizer.java:24)
    at org.gradle.api.tasks.compile.JavaCompile.performCompilation(JavaCompile.java:207)
    at org.gradle.api.tasks.compile.JavaCompile.compile(JavaCompile.java:133)
    at com.android.build.gradle.tasks.factory.AndroidJavaCompile.compile(AndroidJavaCompile.java:125)
    at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
    at org.gradle.api.internal.project.taskfactory.IncrementalTaskAction.doExecute(IncrementalTaskAction.java:46)
    at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:39)
    at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:26)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.run(ExecuteActionsTaskExecuter.java:121)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:110)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:92)
    ... 29 more

Here is my gradle file:
    apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    buildToolsVersion '27.0.3'
    defaultConfig {
        applicationId "Calculator.curtainclub"
        minSdkVersion 23
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation 'com.android.support:wear:27.1.0'
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:appcompat-v7:27.1.0'
    compile 'com.android.support:design:27.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
    compile project(':jtds-1.3.1')
    androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2'
    androidTestCompile 'com.android.support.test:runner:0.5'
    androidTestCompile 'com.android.support:support-annotations:23.1.1'
    compile files('libs/mail.jar')
    compile files('libs/additionnal.jar')
    compile files('libs/activation.jar')

    compile 'com.android.support:recyclerview-v7:27.1.0'
    api 'de.codecrafters.tableview:tableview:2.2.0'

}

A: I had to disable my instant run and it started working again

A: Make sure that your java paths are propertly sets on the system. Link related Environment variables for java installation

A: One possible solution, if you are using Google Services plug-in, was to make sure that
dependencies {
    classpath 'com.google.gms:google-services:4.1.0'
}

is updated to the latest version in your project's build.gradle file.
I snag the latest release number from here Google Services Gradle Plugin
It may not necessarily solve anyone's particular problem but this has caused problems for me the last two AS updates.


text:
Q: How can I split an image URL into two columns (date and name) in excel? I'm terrible with excel, and I'm currently looking to organise a list of different images based on dates. I have, for example:
/2019/08/JRP0004-50x50.jpg"
in one column. I want to split it so it appears like this:
/2019/08/
and
JRP0004-50x50.jpg"
in their own columns.

A: Typically the way this works is you show us what you tried first, so you can get help troubleshooting it, but I just did something like this so here's what worked for me.
Assuming your data is in cell A1, you can put this in Cell B1
=LEFT(A1,9)

And put this in cell C1
=SUBSTITUTE(A1;B1;"")

then just drag the formulas down as far as you need

A: In case you have folder names that aren't simply ####/##, you can search for the / delimiter and work from there.
If your text is in A1, you can use this in B1 to get the folder names:
=LEFT(A1,FIND("~",SUBSTITUTE(A1,"/","~",3)))

and this in C1 for the filename:
=MID(A1,SEARCH(B1,A1)+LEN(B1),LEN(A1)-SEARCH(B1,A1)+LEN(B1))

redpajama_set_name: RedPajamaStackExchange


text:
Q: Return RSS feed in .NET Core API How can I create service that returns RSS from .NET Core API Controller.
I've seen some articles using Rss20FeedFormatter but it's not supported in Core.
Found this library too https://github.com/dotnet/SyndicationFeedReaderWriter, but it doesn't tell anything about APIs and proper returning of the RSSFeed as XML with rss type.
Any suggestions ?

A: As show in this answer https://stackoverflow.com/a/38332687/4990859
Decided to use this https://github.com/shawnwildermuth/RssSyndication which easily parses the XML to string and return it inside Content with type text/xml;


text:
Q: Copy table1 to new table and change field INSERT INTO `table2` SELECT * FROM `table1`;

how to insert all the fields from table1 to table 2 and modify the year,
sample is the "year" from 2016 to 2017
dr_year
 2016

change it to all records with 2016 year to table2..
dr_year
 2017


text:
Q: Android widget not showing up on the list after developed I'm upgrading my app with widget. It's not the first widget I've done. I was always encountering weird issues, but the widget was shwoing up on the list eventually.
Here is what I've done so far:

*

*Created widget_layout.xml

*Created widget_info.xml

<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    android:minWidth="110dp"
    android:minHeight="30dp"
    android:updatePeriodMillis="86400000"
    android:initialLayout="@layout/widget_layout"
    android:resizeMode="none">
</appwidget-provider>

*

*Created WidgetProvider class

*Added widget to manifest in the <application> section (for some reason can't paste manifest fragment here, it's just not showing, see the code here)

Still, can't find widget on the widgets list. I'm debugging the app on real device. I'm using library project, but the widget files but all in the project I run directly. What could be happening here?

A: The problem was android:installLocation="preferExternal"
It somehow causes problem with widget list if the app is installed on SD

A: I tried every possible solution and nothing worked for me...
And finally I solved it.
In my case the problem was overthinking: I believed that in meta-data tag we need to define a unique name for provider (eg: "com.example.myprovider") as well as link to the xml resource.
Wrong:
<meta-data
      android:name="com.example.myprovider"
      android:resource="@xml/widget_info" />

Right:
<meta-data
  android:name="android.appwidget.provider"
  android:resource="@xml/widget_info" />

A: You need to register a BroadcastReceiver in the manifest file. For example:
<receiver
   android:icon="@drawable/icon"
   android:label="Example Widget"
   android:name="MyWidgetProvider" >
   <intent-filter >
        <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
   </intent-filter>

   <meta-data
      android:name="android.appwidget.provider"
      android:resource="@xml/widget_info" />
</receiver>

I borrowed this code from http://www.vogella.com/articles/AndroidWidgets/article.html
See the link for a full tutorial

A: Ran across similar issues and this is what happened for me. The below Widget never showed up in the Widget drawer till minResizeHeight was added. Weird, but may be that is required for resizable widget. Could have been more friendly.
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:initialLayout="@layout/pmt_schedule_scroll_widget"
android:minHeight="146dip"
android:minResizeHeight="73dp"
android:minWidth="146dip"
android:resizeMode="vertical"
android:updatePeriodMillis="0" />

A: This kind of issue can happen with 2 scenarios. Both are answered above and this is a complete answer and I have faced both the scenarios and resolved both of them.
Scenario1
If the application specifies android:installLocation="preferExternal" parameter in manifest, App will be installed in external memory and it will not show in the widget list. Also if you have made your phone to install all the apps on sd card, this will also happen.
solution
Go to Settings->Apps->YourApp
Then "move to phone". This will move the app to your phone memory and now you can see the widget in your widget list
Scenario2
If the above fix did not solve your issue, then you may have a device with android 4.X.X version.
Then you have to set at least following parameters in widget_info.xml file
solution2
android:minHeight="XXXdp"
android:minWidth="XXXdp"

A: after hours of searching and failing to resolve, I decided to open a sample project of a widget that works and go comparing item by item to see what was wrong, in the end, I solve added the following lines on my res/xml/widget_info.xml:
android:minHeight="XXXdp"
android:minResizeHeight="XXXdp"
android:minResizeWidth="XXXdp"
android:minWidth="XXXdp"

where XXX is some value.

A: In my case, the issue was in the intent-filter within the receiver.
Wrong:
<intent-filter>
    <action android:name="APPWIDGET_UPDATE" />
</intent-filter>

Correct:
<intent-filter>
    <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>

A: In my case, it was the minWidth, it was too large, just put a smaller dp, it works also with a minHeight too height as well!


text:
Q: How/Where do I drag an mp3 file from my pc to iphone? The only folder I see in internal storage for Apple iPhone is DCIM which leads to 100APPLE, which has all my pictures and videos, and I can't drag the mp3 file there?

A: You need iTunes to copy music from your computer to your iPhone.


text:
Q: Insert html code after element I have a html document which looks like this:
...html code...

...html code...

Using javascript I want to insert the html code below inside the document, immediately after
 :

Some text

So far I have this, but not the expected results. Please, what am I doing wrong?
var para1 = document.createElement("li");
var para2 = document.createElement("span");
var node = document.createTextNode("Some text");
para2.appendChild(node);
var para3 = document.createElement("ul");
var element = document.getElementById("my_ul");
element.appendChild(para1);
element.appendChild(para2);
element.appendChild(para3);

A: Like this:

var ul = document.getElementById("my_ul");

var li   = document.createElement("li");
var span = document.createElement("span");
var text = document.createTextNode("Some text");
span.appendChild(text);
li.appendChild(span);
ul.appendChild(li);

A: If you want shorter code without creating objects for each html elements just do this:
var element = document.getElementById("my_ul");
var html = '
Some text
';
element.innerHTML = html + element.innerHTML;

A: Is this what you want to do?
Demo: Fiddle
var para1 = document.createElement("li");
var para2 = document.createElement("span");
var node = document.createTextNode("Some text");
para2.appendChild(node);
para1.appendChild(para2);
element = document.getElementById("my_ul");
element.appendChild(para1);

A: Your code does this:

element.appendChild(para1);

Make the list item a child of the original list

element.appendChild(para2);

Make the span a child of the original list

element.appendChild(para3);

Make the new list a child of the original list

You need to append each element to the element you want to be its parent instead of appending everything to the original list.
Replace element with the appropriate variable.

A:

$(document).ready(function(){

var para1 = document.createElement("li");
var para2 = document.createElement("span");
var node = document.createTextNode("Some text");
para2.appendChild(node);

var element = document.getElementById("my_ul");
element.appendChild(para1);
para1.appendChild(para2);
});

A: var ul = document.getElementById("my_ul");
var li = document.createElement("li");
var span = document.createElement("span");
var textNode = document.createTextNode("Some text");
span.appendChild(textNode);
li.appendChild(span);
ul.appendChild(li);


text:
Q: Create relative path and being OS independent How can I get my script's file name as a relative path to cwd and it being OS independent?
e.g if I'm in linux it should return "./script.py" and if I'm in windows it should return ".\\script.py"
I tried with os.path.join and os.path.basename(__file__) but it returns absolute path.

A: import os
import platform

path = os.path.basename(__file__)
run_on=platform.system()
if run_on=='Windows': path=f'.\\{path}'
elif run_on=='Linux': path=f'./{path}'

print(f'path is {path}')

A: Why not simply let os handle that for you?
path = os.path.normcase(os.path.join('.', os.path.relpath(__file__)))


text:
Q: Efficient approach to draw circles for all positions of a line renderer I am building a (2D) plotting application using Unity.
The data is generated (and updated in real time) from an outside library. I am using a LineRenderer to display the data.
This is working really well, but now I am trying to also add points/circles at the positions of the LineRenderer.
Because the LineRenderer contains a lot of points (which are also updated every frame), instantiating/pooling GameObjects at the LineRenderer positions is of course extremly laggy.
What would be a good solution to my problem?
Right now I am thinking there are two possibilities:

*

*Pass the LineRenderer data as a 2D array to a vertex shader every frame

*Draw a texture every frame that contains the positions of the LineRenderer

Is one of the two approaches superior in terms of performance? Also, is there another approach that I am not aware of?
Thank you very much!


text:
Q: R: passing a formula into an function as the first input library(RSSL)
set.seed(1)
df <- generateSlicedCookie(1000,expected=FALSE) %>%
  add_missinglabels_mar(Class~.,0.98)
class_erlr <- EntropyRegularizedLogisticRegression(Class ~., df, lambda=0.01,lambda_entropy = 100)

In the EntropyRegularizedLogisticRegression function from the RSSL package, the example in the documentation passed in the formula Class ~. as the input. I was looking at the source code, and these are the parameters for the function
function (X, y, X_u = NULL, lambda = 0, lambda_entropy = 1, intercept = TRUE,
          init = NA, scale = FALSE, x_center = FALSE)

I tried manually defining what X, y, X_u are based on the df I generated. But running the following gives me an error with the optimization:
y <- df$Class
X <- df[, -1]
ids <- which(is.na(y))
X_u <- X[ids, ]
class_erlr_manual <- EntropyRegularizedLogisticRegression(X = X, y = y, X_u = X_u, lambda=0.01,lambda_entropy = 100)

The error reads:
Error in optim(w, fn = loss_erlr, gr = grad_erlr, X, y, X_u, lambda = lambda,  :
  initial value in 'vmmin' is not finite

Why does changing the formula input Class ~. into X=X, y =y, X_u = X_u result in an error? Can anyone point me to where in the source code the formula input is being used?


text:
Q: не выводится ответ

void __fastcall TForm1::Button1Click(TObject *Sender)
{
    double x,b,F,s,f;
    int k=0;
    x=StrToFloat(Edit1->Text);
    b=StrToFloat(Edit2->Text);

    if (RadioButton1->Checked==true)
    {
        F=sin(x);
        k=1;
    }

    if (RadioButton2->Checked==true)
    {
        F=pow(x,2);
        k=2;
    }

    if (RadioButton3->Checked==true)
    {
        F=exp(x);
        k=3;
    }

    if ((x*b)>1 && (x*b)<10)
        s=exp(f);

    if ((x*b)>=12 && (x*b)<40)
        s=sqrt((abs(f+(4*b))));
    else
        s=b*pow(f,2);

    if(k==1)
        Memo1->Lines->Add("sin(x)="+FloatToStrF(s,ffFixed,8,6));

    if(k==2)
        Memo1->Lines->Add("x^2="+FloatToStrF(s,ffFixed,8,6));

    if(k==3)
        Memo1->Lines->Add("e^x="+FloatToStrF(s,ffFixed,8,6));
}

A: У Вас явно нет понимания того, что это такое и как это работает. Из разных программ надёргали? Вначале присваиваем значение F, а потом про него забываем и используем неинициализированное f. Да и проверка условий неверная. Нужно как-то так:
double x, b, F, s;

// ...

if ((x*b)>1 && (x*b)<10)
    s=exp(F);
else if ((x*b)>=12 && (x*b)<40)
    s=sqrt((abs(F+(4*b))));
else
    s=b*pow(F,2);

P.S. А за конструкцию pow(x,2) в приличном обществе бьют канделябром и пишут x*x.


text:
Q: configuring app.yaml for Google AppEngine to serve ajax requests for PHP I've a simple folder structure,
main
 |__core
      |__start.php
      |__bootstrap.php
js
 |__file.js

css
 |__file.css

index.php

Now, this file.js makes xhr request to start.php for which I'm getting a 500 error.
This is my app.yaml:
runtime: php55
api_version: 1

handlers:
- url: /
  script: index.php

- url: /js
  static_dir: js

- url: /css
  static_dir: css

Now I'm not sure if I'm also suppose to do this:
- url: /main/core/.*
  script: start.php

Which, by the way, doesn't seem entirely legit to me.


text:
Q: Excel - Freezing Top row shows duplicate top row This is no programming question, at least I wouldn't put it that way unless I needed VBA for that.
The issue I have is the following:

*

*When I freeze the top row 1:1 with Excel Ribbon Freeze Row command, it does freeze the top row when I scroll down and it works as expected. However, when I scroll back top again, I see the row 1:1 froze, and below it I see again row 1:1 , thus seeing the same row twice.

*It should be like this: having the row 1:1 froze, and when scrolled all the way to top, show the frozen 1:1 and the next row would be 2:2 and not 1:1 and it is now.
I'm using Excel 2016 on Mac; I'm not sure if this is a problem of this version or it always happens, I've searched a lot about this and found no one with the similar issue. It's not a big problem, it is just annoying to the the same row twice
Visualization of the issue:

My interest lies in solving the problem and I just noticed that maybe this question is more suited for the superuser forum of stack exchange, so I'm going to ask there the exact same question; in the meanwhile if someone has any tip please let me know, even if it requires VBA to solve this strange problem.

A: https://excel.uservoice.com/forums/304933-excel-for-mac/suggestions/12428436-freeze-panes-broken-in-15-19-1

This is fixed in the next version (15.20) that will make it to you all in March. In the meantime, you can "snap" the frozen content back into the freeze pane by clicking in any of the duplicated rows or columns.


text:
Q: python converting .tif to .png without changing mode from cmyk to rgb I want to convert .tif to .png. Simple solution I found was
import Image

im = Image.open('39.tif')
im.save('39.png')

This didn't work and gave me following error :
Traceback (most recent call last):
  File "C:/Users/Marijus/Desktop/templates/rename.py", line 8, in <module>
    im.save('Foto.png')
  File "C:\Python27\lib\site-packages\PIL\Image.py", line 1441, in save
    save_handler(self, fp, filename)
  File "C:\Python27\lib\site-packages\PIL\PngImagePlugin.py", line 506, in _save
    raise IOError, "cannot write mode %s as PNG" % mode
IOError: cannot write mode CMYK as PNG

After a little bit of googling I found out that if I wanted this to work, I had to change mode from CMYK to RGB
if im.mode == "CMYK":
    im = im.convert("RGB")

And it worked, however it changed colours. How can I convert from .tif to .png without changing mode from cmyk to rgb ?

A: PNG-Files have only the modes Indexed, Gray, RGB and RGBA. That's the file format, so if you need CMYK use another file format, e.g. TIF.

A: I use next code for work with tiff
    from PIL import Image, ImageSequence

    image = Image.open(content)

    for i, page in enumerate(ImageSequence.Iterator(image), 1):
        filename = os.path.splitext(file_info.filename)
        page_name = "{}_{}{}".format(filename[0], i, ".png")
        page_bytes_io = io.BytesIO()
        page = page.convert("RGB")
        page.save(page_bytes_io, "png")
        page_bytes_io.seek(0)
        yield page_name, page_bytes_io, page


text:
Q: How to sort the filemanager array by creation date I have written code that retrieves CSV paths in the documents directory and loads them into a tableview. I am trying to sort the files by creation date so that they list from newest to oldest in the tableview. Anyone got any advice on how to accomplish this?
I've not tried anything yet, because I am a little stuck
override func viewDidLoad() {
        super.viewDidLoad()

        csvFiles = listCsvs()

        tblViewDataCSV.dataSource = self
        tblViewDataCSV.delegate = self

    }

    func listCsvs() -> [URL] {
        let fileManager = FileManager.default
        let documentDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]

        let files = try? fileManager.contentsOfDirectory(
            at: documentDirectory,
            includingPropertiesForKeys: nil,
            options: [.skipsSubdirectoryDescendants, .skipsHiddenFiles]
            ).filter {
                $0.lastPathComponent.hasSuffix(".csv")
        }

        print(files as Any)

        return files ?? []

    }

I need the array sorted by .creationdate and not alphanumerically. Many thanks for your help.

A: You need to declare a struct that has a URL (or filename String) and a Date. Populate an array of this struct from the files (and their creation dates) you query from FileManager.
Use that array of struct as your data model for the table view. You can sort the array on filename or date (or any other attributes you might add in the future).
You can get the creation date of each file by first adding [.creationDateKey] to the includingPropertiesForKeys parameter of contentsOfDirectory. Then access the creation date using resourceValues on each URL. See How can I get the file creation date using URL resourceValues method in Swift 3? for more details on getting the creation date.
It may help to use the enumerator method of FileManager instead of contentsOfDirectory. This will make it easier to get the needs URL attributes and populate the array of struct.

A: You can build a struct like the below:
struct yourStruct {
    var path:URL
    var filedate:Date
}

For each file in folder, append your struct into array.
let s = yourStruct(
           path: csvUrl,
           filedate: csvFileDate)
myArray.append(s)

At this point, you have an array with your files and filedates.
And finally sort the array with:
let newArr = myArray.sorted { $0.filedate < $1.filedate }


text:
Q: Right settings for the voltage ripple measurement? Background:
I have been assigned to monitor the signals related to TPS61091 boost regulator section. I am particularly keen with respect measuring the ripple on the 3.3 V output voltage. I have Lecroy 20Gs/s oscilloscope.
Until now my search on the internet has yielded the below information.

*

*To use the shortest possible probe length. I have the small ground spring with my probe, so i can use it

*Measure voltage right across the source: for this, I am planning to probe the voltage directly across the output capacitor.

*Probe settings to 1x: this I picked up from a TI application note. I cannot do this  probe settings to 10x, because the probes are fixed 10x ones.

My questions:.

*

*Is point number 3 above still has any work around?

*Are there any better practices I have missed out to measure the ripple accurately?

A: Don't worry about the 10x vs 1x probe, you can make good measurements with either.
Here's a technique that I recommend:  Wind some bare wire around the barrel and tip of your scope probe to make a "socket" for the probe as shown below.  Solder the two ends right across the output capacitor.  If you have a diff probe you can try that as well for comparison, but this technique has always worked well for me.  Try also comparing with your short spring ground clip and you'll likely note that this method gives a better measurement.


text:
Q: Explanation of a deduction in "On $L^{\infty}$ norms of holomorphic cusp forms" I am reading the article On $L^{\infty}$ norms of holomorphic cusp forms. I am particularly interested to the following :

I don't see how we can get from
$$ |y^k f(z)|     \ll \frac{y^k k^\epsilon(4\pi)^{k-1/2}}{\sqrt{\Gamma(2k)}(2\pi y)^{k-1/2}}\sum_{n\ge 1}(2\pi ny)^{k-1/2+\epsilon}e^{-2\pi ny}$$
that  : $|y^kf(z)|\ll k^{{1/4}+\epsilon}$ for $y\gg k.$
Can someone clarify to me it ?

A: In the article, the author shows how to go from the sum in
$$ |y^k f(z)|     \ll \frac{y^k k^\epsilon(4\pi)^{k-1/2}}{\sqrt{\Gamma(2k)}(2\pi y)^{k-1/2}}\sum_{n\ge 1}(2\pi ny)^{k-1/2+\epsilon}e^{-2\pi ny} $$
to the integral equation in the image. So I suppose you are having trouble with the integral. We can do that here. I drop all epsilons as they're annoying and don't matter to convey how this is seen.
We consider
$$ \frac{y^{1/2} 2^k}{\sqrt{\Gamma(2k)}} \frac{1}{y} \int_0^\infty t^{k - \frac{1}{2}}e^{-t} dt = \frac{y^{1/2} 2^k}{\sqrt{\Gamma(2k)}} \frac{1}{y}\int_0^\infty t^{k + \frac{1}{2}}e^{-t} \frac{dt}{t} = \frac{y^{1/2} 2^k}{\sqrt{\Gamma(2k)}} \frac{1}{y}\Gamma(k + \tfrac{1}{2}). \tag{1}$$
We now make ample use of Stirling's approximation
$$\Gamma(z) \sim \sqrt{\frac{2\pi}{z}} \left(\frac{z}{e}\right)^z.$$
Then $(1)$ becomes
$$ \begin{align}
y^{-1/2} 2^k &\sqrt{\frac{2\pi}{k + \frac{1}{2}}} \left(\frac{k + \frac{1}{2}}{e}\right)^{k + \frac{1}{2}} \left( \sqrt{\frac{2k}{2\pi}} \left( \frac{e}{2k} \right)^{2k} \right)^{1/2} \\
&= y^{-1/2} 2^k (2\pi)^{1/4} \frac{(2k)^{1/4}}{(k + \frac{1}{2})^{1/2}}\left(\frac{k + \frac{1}{2}}{e}\right)^{k + \frac{1}{2}} \left( \frac{e}{2k} \right)^k \\ &= y^{-1/2} (2\pi)^{1/4} (2k)^{1/4} e^{-1/2} \left( \frac{k + \frac{1}{2}}{k}\right)^k. \tag{2}
\end{align}$$
Nothing fancy happened at any step --- it's just a lot of rearrangement and simplification. Notice that
$$ \left( \frac{k+\frac{1}{2}}{k}\right)^k = \left( 1 + \frac{1}{2k} \right)^k \leq 2e^{-1/2}$$
(and is well-approximated by $e^{-1/2}$ for large $k$). Then $(2)$ is bounded by
$$ y^{-1/2} (2\pi)^{1/4} (2k)^{1/4} 2 e^{-1} \ll \frac{k^{1/4}}{y^{1/2}}.$$
As $y \gg k$, it's clear that this term is at most $k^{1/4}$ as claimed.
The other term from approximating the sum is the first summand, given by [again dropping all epsilons]
$$2^k (2\pi y)^k e^{-2\pi y} / \sqrt{\Gamma(2k)} = (4\pi y)^k e^{-2\pi y} / \sqrt{\Gamma(2k)}. \tag{3}$$
As you've included in your question, this is maximized at $y = k/2\pi$.
By Stirling's approximation again, we write
$$ \sqrt{\Gamma(2k)} \sim \left(\frac{2\pi}{2k}\right)^{1/4} \left(\frac{2k}{e} \right)^{k}. $$
Using this in $(3)$, and substituting $y = k/2\pi$, we have
$$(2k)^k e^{-k} \left( \frac{k}{\pi} \right)^{1/4} e^k (2k)^{-k} = \left( \frac{k}{\pi} \right)^{1/4}.$$
This completes the derivation.

In summary, you use Stirling's approximation on every gamma function in sight, and follow it up with algebraic manipulations.


text:
Q: Evaluate limit $\lim_{x \rightarrow 0}\left (\frac 1x- \frac 1{\sin x} \right )$ Can someone provide me with some hint how to evaluate this limit?
$$
\lim_{x \rightarrow 0}\left (\frac 1x- \frac 1{\sin x} \right )
$$
I tried l'hopital's rule but it didn't work.

A: The limit would be $\infty-\infty$ when $x\to0$.
As Amzoti have said in the comment, we can combine the fractions and get:
\begin{align}
\lim_{x\to0}\frac{1}{x}-\frac{1}{\sin x}&=\lim_{x\to0}\frac{\sin x-x}{x\sin x},\text{now we can apply L'Hospital's Rule since the limit would be }\frac{0}{0} \\ \\
&=\lim_{x\to0}\frac{\cos x-1}{\sin x+x\cos x}\\ \\
&=\lim_{x\to0}\frac{-\sin x}{\cos x+\cos x-x\sin x}\\ \\
&=\boxed{0}
\end{align}

A: Rewrite the difference as (after Maclaurin series expansion and some algebra)
$$
\frac{\sin x-x}{x \sin x}=\frac{x+O(x^3)-x}{x(x+O(x^3))}
=\frac{O(x)}{1+O(x^2)}$$
which tends to $0$.


text:
Q: JavaScript Undefined index / Incorrect array length Getting something very odd happening with an array in my code. I have made a JS fiddle to demonstrate (you will have to open up your browsers console to see the logs).
I have also provided an image high lighting whats happening.
I would like some explanation as to why this might be happening.
Basically, an array of size 3 only shows 2 of the elements within the array. When i console log the array.length, it shows as 3, however upon opening the object only 2 elements are visible, something doesn't seem right here to me.
EDIT: I used the console log simply to show what was happening. My real issue is I cant access this 3rd element in the code, and I need to.
Please see the JS fiddle & image attached.
https://jsfiddle.net/ysf2o39f/
console.log('Init');
var arr = []; // Array of objects
var obj = {}; // Dummy object
// Fill array
arr.push(obj);
arr.push(obj);
arr.push(obj);
// Log
console.log('Before pop: ');
console.log(arr);
console.log('Length: ' + arr.length);
// Pop array
arr.pop();
// Log
console.log('After pop: ');
console.log(arr);
console.log('Length: ' + arr.length);


text:
Q: How to play videos in vitamio player from vimeo and facebook? I use vitamio player in my android app. But it cant play videos from facebook or vimeo with links (for example) :
https://player.vimeo.com/video/91775232
or
http://www.facebook.com/plugins/video.php?href=http%3A%2F%2Fwww.facebook.com%2F151536738227392%2Fvideos%2F173954162652254%2F&show_text=0&width=400
It always says, that "Sorry, this video cannt be played".
Help me please, i really need to play this videos by links in app. I tried to use webview, but it was bad idea - webview cant play that videos in all android deviced and all android versions. So, is there a way to play this videos in vitamio player?

A: You can try webview with setWebChromeClient or try chrome custom tabs then your videos should play.


text:
Q: Line passing through vertex of triangle and intersection of diagonals trapezoid formed by base and a parallel line divides both into two equal parts. Tl;Dr : Prove that line passing through a vertex of triangle and intersection of diagonals of trapezoid formed by base and a parallel line divides both segments into two equal parts.

I was reading about Jewish(or Coffin) problems, (Link: https://arxiv.org/abs/1110.1556). I am not able to understand the solution of problem 16. I am putting the problem and the solution here.
Problem:
You are given two parallel segments. Using a straightedge, divide one
of them into six equal parts.

Solution:
Given a segment and a parallel line we can always divide the segment
into two equal parts. Take two points on the parallel line. Together
with the ends of the segment the points form a trapezoid. Continue the
sides to form a triangle. The segment passing through the third vertex
of the triangle and the intersection of the diagonals of the trapezoid
divides both parallel segments into two equal parts.

Using the division method above, divide one of the segments into eight
equal parts. Pick six of these parts consecutively. Then perform a
homothety mapping their union onto the other segment. The center of the
homothety is the intersection of the other sides of the trapezoid
formed by the six segments and the target segment.

The part I am unable to understand is:
The segment passing through the third vertex of the triangle and the
intersection of the diagonals of the trapezoid divides both parallel
segments into two equal parts.

I tried to prove this but am unable to. I don't even know where to begin. Please help me in proving this.

A: Trapezoid $ABCD$, whose sides $AC$ and $BD$ extended intersect at $E$, and diagonals intersect at $F$. Prove that the line drawn from $E$ through $F$, cutting $CD$ at $H$ and $AB$ at $G$, makes $AG=GB$ and $CH=HD$. Since they share base $CD$ and lie between parallels, $$\triangle ACD=\triangle BCD$$Adding triangle CDE to both$$\triangle ADE=\triangle BCE$$Subtracting quadrilateral $ECFD$ from both$$\triangle AFC=\triangle BFD$$and since they have equal angles at $F$,$$\frac{CF}{FB}=\frac{DF}{FA}$$(If equal triangles have one angle equal, the sides about the equal angles are reciprocally proportional.) Or compounding$$\frac{CB}{FB}=\frac{DA}{FA}$$ Further$$\frac{CF}{FB}=\frac{\triangle ECF}{\triangle EFB}$$or compounding$$\frac{CB}{FB}=\frac{\triangle ECB}{\triangle EFB}$$Similarly$$\frac{DF}{FA}=\frac{\triangle EDF}{\triangle EFA}$$or compounding$$\frac{DA}{FA}=\frac{\triangle EDA}{\triangle EFA}$$Therefore$$\frac{\triangle ECB}{\triangle EFB}=\frac{\triangle EDA}{\triangle EFA}$$And since $\triangle ECB=\triangle EDA$, therefore$$\triangle EFB=\triangle EFA$$And since they are equal and on common base $EF$, triangles $EFB$ and $EFA$ must lie between parallels through $A$ and $B$ that are equidistant from $EF$. But triangles $AFG$ and $BFG$ lie between those same parallels and share base $FG$. Therefore triangles $FGA$ and $FGB$ are equal. Adding these to equal triangles $EFA$ and $EFB$, the whole triangles $EGA$ and $EGB$ are equal. And since they have a common altitude, their bases are equal$$AG=GB$$And by similar triangles$$CH=HD$$


text:
Q: set different colums size and number for each different row in plotly graph object subplots I wonder if is possible to make a sublot with different columns size and number per each row USING PLOTLY.GRAPH_OBJECTS and PLOTLY.SUBPLOTS. like the photoes (sry for the hand made).
[img 1 row 1 has 2 cols, row 2 has 4 cols: (https://i.stack.imgur.com/g6XVm.jpg)]
[img 2 row 1 has 3 cols, 2 of the same width and 1 of different width, row 2 has 4 cols egual to col 3 of row: (https://i.stack.imgur.com/2efPQ.jpg)]
it is everything a lot cofused but I hope that you all understand and could give me an answear.
I can set different cols size but this must be egual for each row. I would need different set per row.

A: Yes, is possible.
For example here, shape gives 4 columns and row, and loc identify the position of each ax.
Colspan allow you to make a plot of 1 column or 2 columns.
fig, (axe1) = plt.subplots(1,1,  sharex=False, sharey=False)
ax1  = plt.subplot2grid (shape=(4, 4), loc=(0, 0), colspan=1)
ax2  = plt.subplot2grid (shape=(4, 4), loc=(0, 1), colspan=1)
ax3  = plt.subplot2grid (shape=(4, 4), loc=(1, 0), colspan=1)
ax4  = plt.subplot2grid (shape=(4, 4), loc=(1, 1), colspan=1)


text:
Q: Subspace of a normed vector space equal to It? If $E$ is a normed vector space and $F$ a subspace of $E$. I'm trying to prove that if F contains $B(x,r)$ then it also contains $B(0,r)$ and $F=E$.
I started by writing the definition: $B(x,r)=\{y: \Vert y-x \Vert<r\}=\{x+v: \Vert v\Vert<r\}$
So $F $contains $x  \; \text{and} \;  x+v$ then it contains their difference which is $v$ so $F$ contains $B(0,r)$.
Can i just say that F being a subspace contains $0_E$ and
 $B(0,r)= \{v: \Vert v \Vert < r\}$ which is just a subspace of $B(x,r)$ ?
But i'm stuck with the second part, proving F=E, i don't know where to begin.

A: The fact that $F$ is a subspace implies two things:
1) It is closed under addition (and contains zero).
2) It is closed under multiplication.
Now, suppose that $B(x,r) \subset F$. This means that $x \in F$, and by closure under scalar multiplication, $(-1)x = -x \in F$.
Now, let $v \in B(0,r)$, then $v +x \subset B(x,r)$, right? So we can say that $v +x =y$ for some $y \in B(x,r)$. But the, $v=y-x$, and $F$ is closed under addition, therefore $v \in F$, because $y \in B(x;r) \subset F$ and $-x \in F$.
This shows that because we did not assume anything about $v$ other than $v \in B(0,r)$, it follows that $B(0,r) \subset B(x,r)$.
To show that $E=F$, let $w \in E$ be a vector. If $w=0$, then it is already in $F$, so we will assume it is non-zero, hence has norm non-zero as well.Then, let $c = \frac{2||w||}r$ (so $c \neq 0$). Note that the vector $\frac 1c w$, has norm exactly equal to $\frac r2$, hence is in $B(0,r)$, hence in $F$. But, by closure under scalar multiplication, $(c)(\frac 1c w)$ is also in $F$, but this is equal to $w$, so $w \in F$. Since we did not assume anything about $w$ other than the fact that it is in $E$, it follows that $E \subset F$. But then $E$ already contains $F$, so $E=F$.
Your second point is wrong: in fact, $B(0;r)$ and $B(x ; r)$ need not even intersect! Furthermore, none of them are vector spaces, they aren't closed under scalar multiplication or addition, and $B(x;r)$ may not even contain zero. Hence, this approach is used in the problem.


text:
Q: What counts towards demo scene size restrictions? So I wanna make a small (64k) demo--nothing super impressive, just for the coding experience. I've been wondering, what exactly counts towards a byte count? For example, I could embed Lua as a scripting language once I have a simple demo engine running, but since python comes on pretty much every *nix computer, can I use its interpreter at no cost?
Some might argue that it's not in the spirit of the demo scene, but I do think it counts as milking every last byte. Plus, Lua is 50k and I don't want to write a smaller, custom interpreter (which will be buggy).

A: The general spirit of the thing is that, as a piece of art, any random person ought to be able to download and view your demo.  So it's the base default install of the platform that you're concerned with.  This is why most of the best demos target Windows; DirectX is universally available, and the ability to use those libraries dramatically reduces the amount of code in the demo executable.
The same is true of OSX, but other Linux/UNIX variants are really problematic, because there's often no such thing as a standard install.  And good luck as far as drivers for hardware-accelerated 3D go.
That said, it's really up to the individual group or competition that you plan to submit your demo to.  You'd be best off contacting one of the members or organizers to see what their rules are.  If you're just doing this for yourself, to post on the web, then you get to decide what seems fair.  The more restrictions you place on yourself, the more impressive the demo ends up being.
If you're really serious about a 64k demo, though, you'll use assembly, not an interpreted language.  You only benefit from something like Python if you can get short text to expand into a very complicated function in the stdlib.  Most of the places where that matters for a demo are related to graphics and sound, and Python's stdlib doesn't provide much (nor should it) in either regard.


text:
Q: Draw Lines in canvas I'm trying to draw lines on a canvas object. When the width of the Canvas is less that the width of the line, it draws outside the Canvas over other elements. I read about this problem and I try to resolve using a inner Canvas with a longer height so a scrollbar appears.
But I also read that this problem can be correct using a mask but I do not know what is the better way. Which do you recommend?
<mx:Canvas id="panelContentECG" width="100%" height="400" backgroundAlpha="0.5" styleName="miCanvas" borderStyle="solid" cornerRadius="20" borderColor="0xFCFE00" horizontalScrollPolicy="off">
   <mx:Canvas id="panelDrawECG" width="100%" height="600" >
   </mx:Canvas>
</mx:Canvas>

Is there another way to get draw in a Canvas? Any suggestions??
Thanks in advance,
Alicia

A: try using clipContent="true" on your canvas and you can disable the scrollbars if you don't want them showing


text:
Q: Task.Run() not working as expected - "cannot implicitly convert type void to object" I have a method I need to call on a separate thread in a "fire and forget" fashion, that is, I just start it and move on, without waiting for a result. I'm using Task.Run() to achieve this. From what examples I've seen, this should work. However when I run this I get a

"cannot implicitly convert type void to object" exception.

The part that gets highlighted in VS is PollForPaymentStatus(request, regulator), i.e. the method call. The method itself doesn't seem to get called. What am I doing wrong?
        public void StartPollingForPaymentStatus(dynamic request, Regulator regulator)
        {
            Task.Run(() => PollForPaymentStatus(request, regulator));
        }

        // Run this in a separate thread!
        private void PollForPaymentStatus(dynamic request, Regulator regulator)
        {
            int attemptNumber = 0;
            while (attemptNumber < _maximumPollingAttempts)
            {
               attemptNumber++;

                var response = SendGet(_paymentUrl + "/" + request.Id, regulator);
                if(response.status == 'Success'){
                 // do stuff and return
                }
                Thread.Sleep(pollingInterval);
            }
        }

Edit:
I managed to make it work by putting the call to PollForPaymentStatus inside an anonymous method body, rather than calling it directly.
           public void StartPollingForPaymentStatus(dynamic request, Regulator regulator)
            {
                Task.Run(() =>
               {
              PollForPaymentStatus(request, regulator)
               };
            );
        }

Does anyone know what the key difference between these two approaches is? Why does one work and not the other?

A: Your latter code is clear that nothing is returned (since there is no return). Your former code is not the same as the latter code.
Since at compile time it isn't clear whether something is returned (due to use of dynamic).
The former code is equivalent to
public void StartPollingForPaymentStatus(dynamic request, Regulator regulator)
{
    Task.Run(() =>
    {
      return PollForPaymentStatus(request, regulator)
    });
}

You can validate this by putting var g =  before the Task.Run and then hovering over g. The former code has g as Task<dynamic>. The latter code has g as Task (which is what you want).
Alas, at runtime something isn't returned - so BOOM.


text:
Q: I need to prove the E[aX+b], var[aX+b] given below BY using matlab Using sample group of 10000 samples, verify the followings using simulations
I have to show that is correct by using matlab.

*

*E[aX+b] = aE[x] + b

*var[aX+b] = a2var[X]

I find this code and by using this, I want to proof 1,2 is true
sum1=0;
for i=1:length(A)
  sum1=sum1+A(i);
end
M=sum1/length(A); %the mean

sum2=0;
for i=1:length(A)
    sum2=sum2+ (A(i)-M)^2;
end
V=sum2/length(A); %Varaince

A: you can calculate the mean of a vector simply by mean(A) and you can sum a vector by using sum(A), and the variance is var(A) or std(A)^2...
Remember that not all coders are familiar with notation of mathematics -- in particluar not if they are written so cryptic with no signs of multiplication or power. The expecation E() of a vector X is its mean (which is a scalar and therefore usually written as lower case letter) E(X):x = mean(X). So what you want to proof is
% create random numbers
X = rand(10000,1);
a = rand(1);
b = rand(1);

% 1: E[aX+b] = aE[x] + b
assert( mean(a*X+b) == a*mean(X)+b ,'1 failed!')

% 2: var[aX+b] = a2var[X]
assert( var(a*X+b) == a^2*var(X) ,'2 failed!')

The function assert throws an error if its input is not true. Note that equality is a hard condition in numerical computation. It would be better to define a threshold when it can be sondered almost equal
TH = 1e-10;
lg = abs( mean(a*X+b) - a*mean(X)+b ) < TH
assert( lg ,'1 failed!')


text:
Q: LIME Library in R throwing "Error: Response is constant across permutations. Please check your model" Looking for a kind soul to help me solve this error in R with my current RF model:
Error: Response is constant across permutations. Please check your model
Here are the files needed to run the code: link
Here is my code:
library("lime")
library("randomForest")
RF <- readRDS("RF_classifier4sRNA.rds") # Load the model

origTrainingData <- read.csv( "training_combined.csv", header = TRUE, sep = ",") # load Orig Training data

origTrainingDataLabels <- read.csv( "training_combined_labels.csv", header = TRUE, sep = "," )
                                                        # load Orig Training data labes
Classification <- origTrainingDataLabels$Class
origTrainingDataWithLabels <- cbind(origTrainingData, Classification)

# instances to explain ----
inputFile <- "FeatureTable.tsv"
testData <- read.table( inputFile, sep = "\t", header = TRUE)
class(testData)

testDataPredictions <- predict(RF, testData, type="prob")
testDataPre
# randomForest
# RF <- readRDS("RF_classifier4sRNA.rds")
# pred <- predict(RF, data, type = "prob")

predict_model.randomForest <- function(x, newdata, type, ...) {
  res <- predict(x, newdata = newdata, ...)
  switch(
    type,
    raw = data.frame(Response = res$class, stringsAsFactors = FALSE),
    prob = as.data.frame(res["posterior"], check.names = FALSE)
  )
}

model_type.randomForest <- function(x, ...) 'classification'

?lime()
lime_explainer <- lime( origTrainingData,      # Original training data
                        RF,                    # The model to explain
                        bin_continuous = TRUE, # Should continuous variables be binned
                                               # when making the explanation
                        n_bins = 5,           # The number of bins for continuous variables
                                               # if bin_continuous = TRUE
                        quantile_bins = FALSE  # Should the bins be based on n_bins quantiles
                                               # or spread evenly over the range of the training data
                        )
lime_explanations <- explain( testData,           # Data to explain
                              lime_explainer,     # Explainer to use
                              n_labels = 7,
                              n_features = 7,
                              n_permutations = 10,
                              feature_select = "none"
                            )
lime_explanations

To be fair, I'm not the author of the original Random Forest model, which can be found here: github
and the full documentation and all other related files can be found (here)[https://peerj.com/articles/6304/]
I'm just trying to apply lime to that model.

A: Ultimately, my professor was able to help me out :D
So, here's how the functions should actually be for LIME to work in my particular use case:
predict_model.randomForest <- function(x, newdata, type, ...) {
  res <- predict(x, newdata = newdata, ...)
  switch(
    type,
    raw = data.frame(Response = ifelse(res[,2] > 0.5, "sRNA", "notSRNA"),
                     stringsAsFactors = FALSE
    ),
    prob = res
  )
  print(class(res))
  print(dim(res))
  print(res)
}

model_type.randomForest <- function(x, ...) 'classification'


text:
Q: When page is opened with window.open, how can the opened page allow the opener to access its contents? Is it possible for a page opened with window.open to allow itself to be examined by a cross-origin opener? (This is for use in internal applications, so security is not a significant concern.) And if so, how?  I've tried replacing all of the CORS and Same-Origin policies I can find and I still get Access Denied on all properties for a child window.
In particular I am trying to use Internet Explorer 11
Headers
These are all of the headers I've tried so far
Access-Control-Allow-Origin: http://web1.corp.local
Access-Control-Allow-Credentials: true
Access-Control-Expose-Headers: Cache-Control,Content-Language,Content-Type,Expires,Last-Modified,Pragma
Access-Control-Expose-Methods: GET,POST,OPTION,PUT,DELETE,HEAD
X-Content-Security-Policy: default-src *;script-src *
Content-Security-Policy: default-src *;script-src *
X-XSS-Protection: 0
X-Permitted-Cross-Domain-Policies: all

What I'm trying to do...
I want web1.corp.local to execute some JavaScript on a page on web2.corp.local. I control both domains; I just some way for web2 to tell the browser its okay for web1 to read and execute things on web2.
Request on http://web1.corp.local
I'm trying to call javascript functions on the opened window from the opener.
document.domain = "corp.local";
var web2 = window.open('http://web2.corp.local');
web2.document; //Throw "Access Denied"
web2.MyApp; // undefined

Javascript on http://web2.corp.local
document.domain = "corp.local";
var myapp = window.MyApp = {
    doWork: function() {
        alert('Hello World!');
    }
};

Note: I have a solution using an iframe proxy and window.postMessage but the app hosted on web2 doesn't work correctly from within an iframe.
Update: The issue was the two pages were not using the document.domain and I missed the exception on the opened window.

A: The issue was the document.domain.  The second site was not in the same domain as the first.  As soon as I changed the FQDN of web1 and used document.domain = corp.local the problem was solved.
I missed the exception being thrown by one of the javascript files on document.domain.

A: Apparently it is indeed broken in IE if it's cross-domain and between windows (not frames).
Have a look at this question: Is cross-origin postMessage broken in IE10?
Especially the answer by brunolau at the bottom looks promising and may be just what you need. There is hope in IE11, but they also mention an update breaking it again. It's strange to be honest, I can't see a security reason to make it not work with the constraints and considerations already worked out for frames.
On the other hand, I know it doesn't answer your question, but you may want to implement communication through the server anyway, which would remove dependence on browser pecularities (but that may be less of a concern for you if you only wanted to support IE 11).


text:
Q: randomizing html5-canvas elements Trying to make a scene using HTML5-canvas elements.
I want to generate 'ice_cell' objects with randomized positions inside the canvas, while also having each element of an 'ice_cell' object have a randomized radius, angles, etc.
Here is my (non-working) code:
var can = document.getElementsByTagName('canvas')[0];
if (can.getContext) {
var ctx = can.getContext('2d');

var  ice_cell = function () {

  var posX = Math.random()*can.width();
  var posY = Math.random()*can.height();
  $(this).css({
    "top": y + "px",
    "left": x + "px",
    "transform": "translateX(-50%) translateY(-50%)"
  });

  var radX = [5, 10, 30, 80, 100];
  var rand_radX = radX[Math.floor(radX.length *Math.random())];

  var radY = [5, 10, 30, 80, 100];
  var rand_radY = radY[Math.floor(radY.length *Math.random())];

  var rot = [5, 30, 200];
  var rand_rot = rot[Math.floor(rot.length * Math.random())];

  var start = [0, 2, 5, 10, 50];
  var rand_start = start[Math.floor(start.length * Math.random())];

  var end = [0, 2, 50, 10, 100];
  var rand_end = end[Math.floor(end.length * Math.random())];

  var tranz = [1, 3, 4, 5, 7, 10];
  var rand_tranz = tranz[Math.floor(tranz.length * Math.random())];

  ctx.translate(tranz, 0);

  ctx.ellipse(rand_posX, rand_posY, rand_radX, rand_radY, rand_rot * Math.PI/180, rand_start, rand_end * Math.PI);
};

var colorStroke = function (color, width) {
  ctx.strokeStyle = color;
  ctx.lineWidth = width;
  ctx.stroke();
};

var ice = function () {
  for(var i = 0; i<20;i++){
      colorStroke('cyan', 3);
      colorStroke('white', 1);
    };
  };
};

var degrees = 1;
  for(var i = 0; i < 50; i++){
  ice();
  ctx.rotate(degrees*Math.PI/180);
};

ctx.translate(can.width/2, can.height/2);

Unfortunately my Javascript knowledge is slim to none, so I have been almost guessing what goes where, syntax-wise.
Anyone able to pick out parts that I should just completely re-write?
Debugging using the console hasn't been getting me very far.
Thank you so so much!

A: Ellipse is missing from FireFox.  Here's a function to make ellipse but I'm not sure how it compares to the official implementation.  You're also missing the x and y for the css so I commented that out.

var can = document.getElementsByTagName('canvas')[0];
if (can.getContext) {
  var ctx = can.getContext('2d');

  function ellipse(x, y, rx, ry, rotate, startAng, endAng) {
    ctx.save();
    var w = rx * 2;
    var h = ry * 2;
    ctx.translate(x + w / 2, y + h / 2);
    ctx.scale(rx, ry);
    ctx.rotate(rotate);
    ctx.beginPath();
    ctx.arc(0, 0, 1, startAng, endAng, false);
    ctx.restore();
  }

  var ice_cell = function() {
    ctx.beginPath();
    var rand_posX = Math.random() * can.width;
    var rand_posY = Math.random() * can.height;
    /*
    $(this).css({
      "top": y + "px",
      "left": x + "px",
      "transform": "translateX(-50%) translateY(-50%)"
    });
    */
    var radX = [5, 10, 30, 80, 100];
    var rand_radX = radX[Math.floor(radX.length * Math.random())];

    var radY = [5, 10, 30, 80, 100];
    var rand_radY = radY[Math.floor(radY.length * Math.random())];

    var rot = [5, 30, 200];
    var rand_rot = rot[Math.floor(rot.length * Math.random())];

    var start = [0, 2, 5, 10, 50];
    var rand_start = start[Math.floor(start.length * Math.random())];

    var end = [0, 2, 50, 10, 100];
    var rand_end = end[Math.floor(end.length * Math.random())];

    var tranz = [1, 3, 4, 5, 7, 10];
    var rand_tranz = tranz[Math.floor(tranz.length * Math.random())];

    ctx.translate(tranz, 0);

    ellipse(rand_posX, rand_posY, rand_radX, rand_radY, rand_rot * Math.PI / 180, rand_start, rand_end * Math.PI);
  };

  var colorStroke = function(color, width) {
    ctx.strokeStyle = color;
    ctx.lineWidth = width;
    ctx.stroke();
  };

  var ice = function() {
    for (var i = 0; i < 20; i++) {
      colorStroke('cyan', 3);
      colorStroke('white', 1);
    };
  };
};

var degrees = 1;
for (var i = 0; i < 50; i++) {
  ice_cell();
  ice();
  ctx.rotate(degrees * Math.PI / 180);
};

ctx.translate(can.width / 2, can.height / 2);
<canvas></canvas>


text:
Q: Lua Equivalent for NumPy and SciPy? I'm thinking of learning lua, i learned that it is a smaller language compared to python and has an efficient JIT compiler implementation in the form LuaJIT.
I would like to know is it possible to use lua the way i use python with Numpy+Scipy.
further if Lua has numpy+scipy equivalent does it have a matplotlib equivalent?

A: there is something else, i found something similar to Scipy+matplotlib for Lua,i'm not sure how active development is last release was in January 2011, it is GSL-shell
it leverages the GSL library and has plotting capabilities , it is more like matlab than scipy+matplotlib.

A: There is numlua, but since it depends on BLAS/LAPACK, FFTW, and HDF5, LuaJIT will not buy you any performance gain with numlua per se.

A: I am authoring the Lunum project, which has no dependencies and can be used as a shared module or embedded in other C applications.
It's in active development, and used in serious physics research. It supports a good subset of the Numpy semantics. Array slicing will be ready in the next release.
https://github.com/jzrake/lunum

A: I would also have a look at SciLua:

A complete framework for numerical computing based on LuaJIT which combines the ease of use of scripting languages (MATLAB, R, ...) with the high performance of compiled languages (C/C++, Fortran, ...).


text:
Q: How to mention a instance of AWS DynamoDB in the resource ID while creating application auto scaling target I am setting up the creation of AWS resources in the AWS Cloud Formation template.
I set up my dynamoDb table resource such that with every new stack, it creates a unique instance of the DynamoDb Table, and it's not a fixed name.
I used the following code in the cloud formation template:
 DynamoDBTable:
    Type: AWS::DynamoDB::Table
    # Retain the table when deleting from CF Stack!
    DeletionPolicy: Retain
    Properties:
      #TableName: !Sub "abc-${ClientVar}-DB-${EnvVar}"
      #TableName: !Ref DbTableName
      TableName: TrackOreDB # This is just for the autoscaling group. I need to find a way to validate it in the autoscaling resource by making the name generic for multiple stacks.
      AttributeDefinitions:
        - AttributeName: Product_ID
          AttributeType: S

      KeySchema:
        - AttributeName: Product_ID
          KeyType: HASH

I am trying to set up an application auto-scaling target for this dynamo DB resource with this code. But i am not sure how to point it to the table created above.
  UserTableWriteCapacityScalableTarget:
    Type: AWS::ApplicationAutoScaling::ScalableTarget
    Properties:
      MaxCapacity: 100
      MinCapacity: 5
      ResourceId: !Sub table/'abc-%s-DB-%s' % (client, env)
      RoleARN: !Sub arn:aws:iam::${AWS::AccountId}:role/aws-service-role/dynamodb.application-autoscaling.amazonaws.com/AWSServiceRoleForApplicationAutoScaling_DynamoDBTable
      ScalableDimension: dynamodb:table:WriteCapacityUnits
      ServiceNamespace: dynamodb

At deployment, the auto-scaling resource is getting created before dynamo DB and thus cloud formation deployment is failing.
Please help.

A: If you reference the name of the DynamoDB table resource using !Ref or !Sub it will output the name of the table.
Cloudformation can detect if a resource is part of another resource definition when !Ref and !Sub are used and reference the names of other resources.  It will properly order the creation of the resources without requiring DependsOn to be explicitly defined.
Assuming this is a YAML Cloudformation template, the two resources in the template would look something like:
Resources:
  DynamoDBTable:
    Type: AWS::DynamoDB::Table
    DeletionPolicy: Retain
    Properties:
      TableName: !Sub "abc-${ClientVar}-DB-${EnvVar}"
      AttributeDefinitions:
        - AttributeName: Product_ID
          AttributeType: S
      KeySchema:
        - AttributeName: Product_ID
          KeyType: HASH

  UserTableWriteCapacityScalableTarget:
    Type: AWS::ApplicationAutoScaling::ScalableTarget
    Properties:
      MaxCapacity: 100
      MinCapacity: 5
      ResourceId: !Sub "table/${DynamoDBTable}"
      RoleARN: !Sub arn:aws:iam::${AWS::AccountId}:role/aws-service-role/dynamodb.application-autoscaling.amazonaws.com/AWSServiceRoleForApplicationAutoScaling_DynamoDBTable
      ScalableDimension: dynamodb:table:WriteCapacityUnits
      ServiceNamespace: dynamodb


text:
Q: Regex to match this: "Late Fee 81245 on 11/29/2014"? The Late Fee number is any integer and the Date will always be in that format.
Thanks in advance.

A: late fee \d+ on \d{2}\/\d{2}\/\d{4}

I always try mine out on http://regexper.com/

A: If you want to pick up the month, day, and year separately:
"^Late Fee (\d+) on (\d\d)/(\d\d)/(\d\d)$"

If you just want to pick up the date as a unit:
"^Late Fee (\d+) on (\d\d/\d\d/\d\d)$"

A: Late Fee \d+ on (0?[1-9]|1[0-2])/(0?[1-9]|[12][0-9]|3[01])/(19|20)\d\d

A: If the month and day could be 1 or 2 digits try this:
Late Fee \d+ on \d{1,2}\/\d{1,2}\/\d{4}


text:
Q: Unable to display piechart for Accounts per country in Visualforce page I am trying to pull number of Accounts for every country in a pie chart using Visualforce, but no results in the page -
Here is my code, any help is appreciated -
public class PieChartControllerTest1 {
public PieChartControllerTest1 ()
{
}

public List<AggregateResult> getAccountCountry()
{
    AggregateResult[] result = [SELECT COUNT(Name) cnt, BillingCountry FROM Account GROUP BY BillingCountry];
    return result;
}

}

visualforce page:
<apex:page controller="PieChartControllerTest1" title="Pie Chart">
<apex:pageBlock >
<apex:pageBlockSection title="Account By Country">
<apex:pageBlockSectionItem >
<apex:chart height="450" width="750" data="{!AccountCountry}">
<apex:pieSeries labelField="Count" dataField="cnt">
<apex:chartLabel display="rotate" field="cnt"/>
</apex:pieSeries>
</apex:chart>
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:page>

A:
Hi Pratibha, I think there are some account records with null value in
  BillingCountry in your org, so use a where clause so that only those
  records having some value in BillingCountry will be queried.

AggregateResult[] result = [SELECT COUNT(Name) cnt, BillingCountry FROM Account WHERE BillingCountry != null GROUP BY BillingCountry];

/*****In VF Page*****/
<apex:pieSeries labelField="BillingCountry" dataField="cnt">

Hope this may help.

A: Here is the updated Code!!
public class pieChartAccountCtrl {
    public pieChartAccountCtrl (){
    }

    public List<AggregateResult> getAccountCountry()
    {
        AggregateResult[] result = [SELECT COUNT(Name) cnt, BillingCountry FROM Account WHERE BillingCountry != null GROUP BY BillingCountry];
        return result;
    }

}

And Vf Page code is :
<apex:page controller="pieChartAccountCtrl" title="Pie Chart">
    <apex:pageBlock >
        <apex:pageBlockSection title="Account By Country">
            <apex:pageBlockSectionItem >
                <apex:chart height="450" width="750" data="{!AccountCountry}">
                    <apex:pieSeries labelField="BillingCountry" dataField="cnt">
                        <apex:chartLabel display="rotate" field="cnt"/>
                    </apex:pieSeries>
                </apex:chart>
            </apex:pageBlockSectionItem>
        </apex:pageBlockSection>
    </apex:pageBlock>
</apex:page>

Hope this will help you and if it is then don't forget to mark it as correct answer ;)

A: In addition to Nebula's fix, you also need to ensure that both names in the apex:pieSeries match the names returned by the query. For the non-aggregated field you can just use the field name:
<apex:pieSeries labelField="BillingCountry" dataField="cnt">

For aggregated fields its best to use an alias as you already have done for "cnt".


text:
Q: multiple flexible array in a struct in C? I have multiple flexible arrays in s struct in c:
typedef struct
{
   int a;
   float b;
} Name;

typedef struct
{
   int c;
   int d;
   int e;
} NIM;

typedef struct
{
   int age;
   int time;
   Name name[1];
   NIM  nim[1];
} EthgenSig;

if we have need to allocate memory like this:
malloc(sizeof(EthgenSig) + sizeof(Name) * 10);

how the memory will be allocated and if we operator name array first and then we operate nim array later, then the nim[1] will overwrite the name array, then how to solve it?

A: You can't have more than one flexible-array member for the exact reason you pointed out.
At most, if you need your data to be kept all in the same memory block, you can make name and nim pointers and set where they point to the correct locations after allocation (making sure not to break any alignment constraint), but the simplest (and most sensible) thing is to just allocate separately the arrays for name and nim.

A: This is not so hard to do... the key is to realize that arrays and pointers in C both have very similar properties. In fact, array accessor notation has a direct correspondence to pointer notation:
a[b] == *(a + b);

Note that this has the effect of making the name of the array and the index interchangeable, so this is also true:
a[b] == b[a];

You can use this to achieve the result you want. First, declare a structure with two pointer elements. This provides two pointers that will store the base address of the two arrays:
struct two_blocks {
    int *x;
    int *y;
}

When you allocate this structure, you'll need to allocate extra space for the bodies of the two arrays:
#define X_SIZE 3
#define Y_SIZE 4

two_blocks *data = (two_blocks *)malloc(sizeof(two_blocks)
                                         + (sizeof(int) * X_SIZE)
                                         + (sizeof(int) * Y_SIZE));

And then the final step is to initialize the two array pointers. (These expressions use a lot of pointer type casting to ensure that the pointer arithmetic is done in single bytes. Pointer arithmetic is usually done in units of the size of the object being pointed to, to support the array/pointer equivalence I mentioned above.)
data->x = (int *)(((char *)data) + sizeof(two_blocks));
data->y = (int *)(((char *)data) + sizeof(two_blocks) + X_SIZE * sizeof(int));

From there, the arrays can be used like you'd expect:
 data->x[2] = 42;
 data->x[2] = 42;

A couple observations

*

*Like Matteo said, be careful with alignment. Using this technique is taking memory layout over from the compiler, which can cause unexpected problems.  If this caveat makes no sense to you, then you probably shouldn't use this technique.

*One of the rationales for using this technique is that it can simplify memory management by reducing the number of frees you need to manage. If you know that your two arrays, x and y, both have the same lifecycle as their enclosing structure, then this removes one potential type of memory leak. (As well as reduces the chance of memory fragmentation by reducing the number of memory blocks.)

A: Having an array of size 1 is the same as not having an array at all when it comes to the memory layout of this struct.
You may as well have this:
typedef struct
{
   int age;
   int time;
   Name name;
   NIM nim;
} EthgenSig;

But I'm assuming that is not what you want. It is pretty hard to tell what you actually want. But I'm assuming that you actually want this:
typedef struct
{
   int age;
   int time;
   Name* name;
   NIM* nim;
} EthgenSig;

foo = malloc(sizeof(EthgenSig);
foo.name = malloc(sizeof(Name)*10);
foo.nim = malloc(sizeof(Nim) * 10);


text:
Q: Instrumentation test fails after updating libraries I have these gradle dependencies for all my instrumentation tests:
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0'
    androidTestImplementation 'androidx.test.espresso:espresso-contrib:3.1.0'
    androidTestImplementation 'androidx.test.espresso:espresso-intents:3.1.0'
    androidTestImplementation 'androidx.test.espresso:espresso-accessibility:3.1.0'
    androidTestImplementation 'androidx.test.espresso:espresso-web:3.1.0'
    androidTestImplementation 'androidx.test.espresso.idling:idling-concurrent:3.1.0'
    implementation 'androidx.test.espresso:espresso-idling-resource:3.1.0'

    androidTestImplementation 'androidx.test:runner:1.1.0'
    androidTestImplementation 'androidx.test:rules:1.1.0'
    androidTestImplementation 'androidx.test.ext:junit:1.1.0'
    debugImplementation 'androidx.fragment:fragment-testing:1.2.0-alpha01'
    implementation 'androidx.fragment:fragment:1.1.0-alpha01'
    androidTestImplementation 'org.mockito:mockito-android:2.24.5'

Once i update them to:
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-contrib:3.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-intents:3.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-accessibility:3.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-web:3.2.0'
    androidTestImplementation 'androidx.test.espresso.idling:idling-concurrent:3.2.0'
    implementation 'androidx.test.espresso:espresso-idling-resource:3.2.0'

    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation 'androidx.test:rules:1.2.0'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    debugImplementation 'androidx.fragment:fragment-testing:1.2.0-alpha01'
    implementation 'androidx.fragment:fragment:1.2.0-alpha01'
    androidTestImplementation 'org.mockito:mockito-android:2.24.5'

And run the test, I get the following error:

Cannot find a version of 'androidx.test:core' that satisfies the
  version constraints:
Dependency path 'my_package_name:app:unspecified' -->
  'androidx.test.espresso:espresso-intents:3.2.0' -->
  'androidx.test:core:1.2.0'

.... and so one with lots of lines
How do I resolve this? Why does it happen?

A: Why this happens?
This happens because of a version conflict for androidx.test:core:1.2.0:
Dependency androidx.test.espresso:espresso-intents:3.2.0 uses version 1.2.0 of the core library. While there is another dependency that uses another version of the same library, and that makes Gradle unhappy. If you keep reading through those lots of lines you will see what this another dependency is but I highly suspect it is androidx.fragment:fragment-testing:1.2.0-alpha01 which depends on version 1.1.1 of the core library.
How to resolve this:
Given you really need to upgrade your espresso, and assuming that the problematic library is fragment-testing, a simple workaround would be to change
debugImplementation 'androidx.fragment:fragment-testing:1.2.0-alpha01'

to
debugImplementation ("androidx.fragment:fragment-testing:1.2.0-alpha01", {exclude group: 'androidx.test', module: 'core' })


text:
Q: rand() not giving random numbers depending on modulo in xcode I have an array with 7 elements and I'm trying to get a random number between 0 - 6 so I can select an element in the array at random.
#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

class Color{

public:

    Color(){

        colors[0] = "red";
        colors[1] = "orange";
        colors[2] = "yellow";
        colors[3] = "green";
        colors[4] = "blue";
        colors[5] = "indigo";
        colors[6] = "violet";

    }

    void printColors()
    {
        for (int i = 0; i<sizeof(colors)/sizeof(colors[0]); ++i)
        {
            cout << colors[i] << endl;

        }
    }

    void printRandomColor()
    {

        int random_integer = rand() % 7;
        cout << random_integer << endl;

    }

private:

    string colors[7];

};

int main(int argc, const char * argv[]) {

    srand( static_cast<unsigned int>(time(0)));

    Color colorObject;

    colorObject.printRandomColor();

    return 0;
}

When I do rand() % 7 I keep getting 6, but if I do rand() % 6 I end up getting random numbers. What gives?
I call srand( static_cast<unsigned int>(time(0))); in my main()

A: I noticed the same behavior with the code shown in the question:
rand() % 7    // always shows 6
rand() % 14   // always shows 6 or 13
rand() % 21   // always shows 6, 13, or 20

The problem is peculiar and there seems to be a pattern involved. Based on the comments that some aren't able to reproduce it, I decided to compile the code, with gcc on a Linux based machine and clang on macOS; Linux seems to behave normally from what I can tell, however macOS does not. I even tried completely different code just make sure it wasn't something else, yet got the same result.
#include <cstdlib>
#include <iostream>
#include <ctime>

int main()
{
    int min = 1;
    int max = 7;

    std::srand(std::time(0)); // use current time as seed for random generator
    // int random_variable = std::rand() % max; // always returns 6
    // int random_variable = std::rand() % (max - min) + min; // produces 'predictable' numbers based on the time.
    int random_variable = RAND_MAX % std::rand() % (max-min) + min; // also returns predicate results based on the timing, except in reverse.

    std::cout << "Random value on [0 " << RAND_MAX << "]: "
              << random_variable << '\n';
}

The only way I was able to get seemingly random results from rand() was to do:

RAND_MAX % std::rand() % (max-min) + min; // predictable based on timing

The issue is odd, and might be a bug with Clang; I'm at a loss at to what exactly is at play here. I would probably recommend using something other than rand() such as the <random> library mentioned in the comments perhaps.
EDIT: After reporting this bug to Apple this was the response:

Apple Developer Relations July 27 2017, 11:27 AM
There are no plans to address this based on the following:
std::rand directly uses rand from the C library.  rand is known and
  documented to be broken (and is not going to change since people
  depend on its specific behavior).
From the man page: RAND(3) BSD Library Functions Manual
NAME
       rand, rand_r, srand, sranddev -- bad random number generator
DESCRIPTION
       These interfaces are obsoleted by arc4random(3).
For good pseudorandom numbers in C++, look at  from C++11.
  E.g.: http://en.cppreference.com/w/cpp/numeric/random

Based on this information RAND() is broken and won't be fixed — use an alternative random number generator.

A: rand() is terrible. rand() % range is worse. Don't use it. Use arc4random_uniform().
#include <iostream>
#include <cstdlib> // Needed for arc4random_uniform()

int main(int argc, char *argv[]) {
    // Random number between 0 and 6.
    std::cout << arc4random_uniform(7) << std::endl;
}

So in your case:
void printRandomColor()
{
    int random_integer = arc4random_uniform(7);
    cout << random_integer << endl;
}

If portability is desired, then here is a C++ standard example. To me, it's needlessly more complicated and runs slower, but hey… it's the C++ standard.
#include <iostream>
#include <random> // For std::random_device and std::uniform_int_distribution

int main() {
    std::random_device randomizer;
    std::uniform_int_distribution<int> distribution(0, 6);

    // Random number between 0 and 6.
    int random_integer = distribution(randomizer);
    std::cout << random_integer << std::endl;
}

A: I would like to point out, that you are using a Random (Rand) operator, then trying to find out if the result has a Remainder (%), the Result will be the Remainder, which is where your strange math comes from. This is known as the Modulo Operator or Modulus Operator if you desire to Google it, although you should know that it actually has a slightly different name in C#, there is a Post in StackTrace about it Here:
What does the '%' operator mean?
If you open the Calc.exe Windows Program it is listed in Scientific Mode (Alt+2)  as Mod.
Specifically, the way % operates is ((x - (x / y)) * y)
The above URL is a direct link to my answer where I point out specifically HOW it differs from standard / complete with a long drawn out example simulating all of the math step by step, the result returns a 0 for % and a 1 for / since the / Operand does roundUp() whilst % does roundDown() from what I've understood in the other Answers in that Post.
Update
I would at least like to have this answer here to provide reference for the Modulo Operator which is mentioned in the title of this question.
I didn't post this specifically as an answer per se, but more as reference material to avoid spam posts in the future.
If this is in fact a discovered bug, then this question is going to be picked apart letter by letter, symbol by symbol, and it's going to assist everybody involved to have this reference material here.
If I didn't know already it was named Modulo/Modulus in most languages, I would wonder what he meant by "Modulo" as he never explains anywhere that the % is named exactly that.
This answer addresses the fact that % uses roundDown() whereas / uses roundUp() complete with a referenced compile-able example written painstakingly in expanded step-by-step longhand which I then converted to C#.
I also would like to reiterate, as I mentioned in the comments, I have zero knowledge about xCode, I am somewhat familiar with C# and have provided this information in the C# context which this question is tagged with.


text:
Q: error: constructor FirebaseRecyclerAdapter in class FirebaseRecyclerAdapter cannot be applied to given types I have the following code for a recyclerview using Firebase. The Recycler View uses the following adapter.
FirebaseRecyclerAdapter<DownloadList,DownloadListFragment.DownloadViewHolder> recyclerAdapter= new FirebaseRecyclerAdapter<DownloadList, DownloadViewHolder>(
            DownloadList.class,
            R.layout.download_cardview,
            DownloadViewHolder.class,
            databaseReference
    ) {
        @Override
        protected void populateViewHolder(DownloadViewHolder viewHolder, DownloadList model, int position) {
            viewHolder.setTitle(model.gettitle());
            //viewHolder.setImage(model.getimage());
            viewHolder.setDate(model.getDate());
        }

        @Override
        public DownloadViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            DownloadViewHolder viewHolder = super.onCreateViewHolder(parent, viewType);
            viewHolder.setOnClickListener(new DownloadViewHolder.ClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    Toast.makeText(getActivity(), "Item click at " + arrayAdapter.getItem(position), Toast.LENGTH_SHORT).show();

                    DownloadImageFragment fragment = new DownloadImageFragment();
                    Bundle arguments = new Bundle();
                    arguments.putString( "Batch" , batchID);
                    arguments.putString( "Type" , typeID);
                    arguments.putString( "Url", arrayAdapter.getItem(position));
                    arguments.putString( "Title", (String) titleAdapter.getItem(position));

                    fragment.setArguments(arguments);
                    final FragmentTransaction ft = getFragmentManager().beginTransaction();
                    ft.replace(R.id.content, fragment , "Download List");
                    ft.commit();

                }

                @Override
                public void onItemLongClick(View view, int position) {
                    return ;
                }
            });

            return viewHolder;
        }
    };

    recyclerView.setAdapter(recyclerAdapter);

    return view;
}

public static class DownloadViewHolder extends RecyclerView.ViewHolder {
    View mView;
    TextView textView_Title;
    TextView textView_Date;
    TextView textView_Image;

    String simage,stitle;

    private static Context context;

    public DownloadViewHolder(View itemView) {
        super(itemView);
        mView = itemView;
        context = itemView.getContext();
        textView_Title = (TextView) itemView.findViewById(R.id.textView_download_title);
        textView_Image = (TextView) itemView.findViewById(R.id.textView_image_download);
        textView_Date = (TextView) itemView.findViewById(R.id.textView_download_date);

        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mClickListener.onItemClick(v, getAdapterPosition());

            }
        });
        itemView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                mClickListener.onItemLongClick(v, getAdapterPosition());
                return true;
            }
        });
    }

The getters and setters are defined as :
public class DownloadList {
private String date;
private String title;
private String image;

public DownloadList(){}

public DownloadList(String date, String title, String image){
    this.date = date;
    this.title = title;
    this.image = image;
}

public String getDate(){
    return date;
}

public void setDate(String date){
    this.date = date;
}

public String gettitle(){
    return title;
}

public void setTitle(String title){
    this.title = title;
}

public String getimage(){
    return image;
}

public void setimage(String description){
    this.image = image;
}
}

Now on building the apk the following error pops up

error: constructor FirebaseRecyclerAdapter in class
  FirebaseRecyclerAdapter cannot be applied to given types;
  required: FirebaseRecyclerOptions found:
  Class,int,Class,DatabaseReference
  reason: actual and formal argument lists differ in length where T,VH
  are type-variables: T extends Object declared in class
  FirebaseRecyclerAdapter VH extends ViewHolder declared in class
  FirebaseRecyclerAdapter

This was not there before the 3.1 update of the android studio(March 2018).
I have event tried changing the app:compatv7 version but it still doesn't work.
Also according to the documentation provided FirebaseUI for Realtime Database it says to use
Query query = FirebaseDatabase.getInstance()
    .getReference()
    .child("chats")
    .limitToLast(50);

and
FirebaseRecyclerOptions<Chat> options =
            new FirebaseRecyclerOptions.Builder<Chat>()
                    .setQuery(query, Chat.class)
                    .build();

Now my question is since i have used the above recyclerView in 15 different places in the app so do i need to change this at all the 15 places or there is some other way around ? Also is there any surety that if I use query, the new code will be compatible ?
Github link for complete code

A: You could implement your own FirebaseRecyclerAdapter subclass that maps the old signature to the new signature. Something like:
class MyFirebaseRecyclerAdapter<T, VH extends RecyclerView.ViewHolder> :FirebaseRecyclerAdapter<T, VH> {
    public MyFirebaseRecyclerAdapter(Class pojoClass<T>, int layout, Class<VH> viewHolderClass, Query query) {
        super(new FirebaseRecyclerOptions.Builder<T>()
            .setQuery(query, pojoClass.class)
            .build());
        ...

You'll then still need to update all places to use the new MyFirebaseRecyclerAdapter, but at least the signature will be compatible after that.


text:
Q: Exception com.facebook.react.common.c: at com.facebook.react.modules.core.ExceptionsManagerModule.reportException (ExceptionsManagerModule.java) Got issue from crash report play console.
"react": "16.13.1",
"react-native": "0.63.3",


text:
Q: Is it possible to "manually" open your Facebook messages, "programmatically"? Is it possible to "manually" open your Facebook message inbox in-browser, programmatically?
(i.e., via the "native" code/functions that Facebook normally uses to do it -- without using Facebook's API, and without an actual mouse click or Tab-Enter of the icon)
On Facebook, when you put the mouse over your message-inbox icon and click -- the inbox drops down.
Would it possible to capture programmatically what's actually happening when this is clicked, thus making the inbox drop down as if the icon had been clicked (like a debugger catching function calls)?
And if so, would it be possible to manually "replay" this programmatic pull of the puppet-strings that a mouse-click would pull, to emulate this click and see the ensuing drop-down of the inbox, -- again without using the API or any kind of physical or automated clicking/tab-entering?
This doesn't necessarily have to be done through an entirely self-contained program. If it's possible to do in-browser, like via Javascript (Scratchpad)/Greasemonkey (sans FB API) -- all the better.

A: You probably can't do this with PHP.
Your best bet would be to use a browser automation tool that will record your actions and play them back. For example, but not necessarily, Selenium.
This will simulate the manual clicking of elements on the page, without using the Facebook API.


text:
Q: I'm having trouble getting this addition subroutine to work I am writing an addition program for my assembly language class in Easy68k but I keep having the same issue. Whenever I run the program it allows me to input up to 10 numbers (the allotted size of my array) and then it outputs the message saying it's calculating but then I just get an endless printout of y's with umlauts. Any issues you can see right off the bat with my program that would be causing it to do this?
I've searched for syntax on subroutines because I'm positive that is what I am doing wrong, but I cannot find anything.
ORG $2000
ARRAY   DS.W    10
ZDONE       DC.W    'Enter values. Zero when done.'
FULL        DC.W    'That is all the input allowed. Calculating sum now...'
OERROR      DC.W    'The values you entered caused an overflow condition.'
REPEAT      DC.W    'Do you want to repeat? [0=No, 1=Yes].'

START       ORG     $2800

MAIN    LEA         ZDONE,A1
        MOVE.B      #14,D0          ;
        TRAP        #15
        LEA         ARRAY,A0

        MOVE.B      #0,D3
INPUT   MOVE.B      #4,D0
        TRAP        #15
        MOVE.W      D1,(A0)+
        BEQ         SUB
        ADD.B       #1,D3
        CMPA        #$2012,A0
        BNE         INPUT
        LEA         FULL,A1
        MOVE.B      #14,D0           ; Outputs the FULL string
        TRAP        #15

SUB     SUB.W       A0,A0
        BSR         SUM              ; Begins to calculate sum

        CMP         #1,D0
        BNE         NoV
        LEA         OERROR,A1
        MOVE.B      #14,D0
        TRAP        #15
        BRA         AGAIN

NoV     LEA         $D1,A1
        MOVE.B      #14,D0
        TRAP        #15

AGAIN   LEA         REPEAT,A1
        MOVE.B      #14,D0
        TRAP        #15
        MOVE.B      #4,D0
        TRAP        #15
        MOVE.B      #1,D0
        CMP.B       D0,D1
        BEQ         START
        STOP        #$3800

        ORG         $3800
SUM     LEA         ARRAY,A0
        ADD.W       #$A0,D1
        BVC         NoV
        SUB.B       #1,D3
        BNE         SUM
        MOVE.B      #1,D0
        BRA         RETURN
        CLR.B       D0
RETURN  RTS
        END         START

A: The flood of ÿ comes from here:
NoV     LEA         $D1,A1
        MOVE.B      #14,D0
        TRAP        #15

You're loading an immediate value of 0xD1 into A1. That's what the $ is for: it means immediate addressing. Debuggers are useful here: if you run the program up to the MOVE.B line, you'll see that A1 has a value of 0x000000D1. This is the address of the string to print using TRAP, right? What's in memory at 0x000000D1? It's undefined; in this case, the emulator is initializing memory to 0xFF, which corresponds to the ÿ character.
This might be wrong:
SUB     SUB.W       A0,A0

You're subtracting A0 from A0, effectively setting A0 to 0.
I suspect this is wrong too:
SUM     LEA         ARRAY,A0
        ADD.W       #$A0,D1

The ADD is adding an immediate value of 0xA0 to register D1. You probably want a direct add instead:
        ADD.W       A0,D1

A couple more things:
You're loading ARRAY into A0 at the start of each loop in SUM. You should probably do it before the loop:
SUB     LEA         ARRAY,A0
        BSR         SUM

Inside of SUM, ignore what I said and use indirect addressing. This will take the actual value from the array and add it to the accumulator (I presume this is D1):
SUM     ADD.W       (A0)+,D1

NoV looks like it's displaying the current value of the accumulator, right? You're using a conditional branch to it: okay, you probably only want it to display once you've finished summing. But BVC isn't actually a sub branch! It won't save the return pointer. Instead, I would move it to the part of SUM that executes after the counter reaches 0, and I would use BSR:
SUM     ADD.W       (A0)+,D1
        SUB.B       #1,D3
        BNE         SUM
        BSR         NoV
        MOVE.B      #1,D0
        BRA         RETURN
        CLR.B       D0
RETURN  RTS

Note that you'll still get the overflow thing. I don't understand what you're doing there so I'll let you figure it out. Also note that since you're using an unconditional branch to RETURN, the CLR will never get executed and so it's impossible for SUM to return 0.
After this change, it's important to modify NoV to act like a subroutine by returning with RTS. Note that there's a TRAP value for displaying the integer value of D1 as a string, which is probably what you want:
NoV     MOVE.B      #3,D0
        TRAP        #15
        RTS

At this point I can get it to add numbers and display the result, but it always shows the overflow thing. Fix your subroutines, then re-evaluate the logic flow of your program.


text:
Q: Python unexpected character after line continuation character I am very new to Python. I am constructing a string that is nothing but a path to the network location as follows. But it outputs the error: "Python unexpected character after line continuation character". Please help. I saw this post but I am not sure if it applies to my scenario:
syntaxerror: "unexpected character after line continuation character in python" math
s_path_publish_folder = r"\\" + s_host + "\" + s_publish_folder "\" + s_release_name

A: One of your \ backslashes escapes the " double quote following it. The rest of the string then ends just before the next \ backslash, and that second backslash is seen as a line-continuation character. Because there's another " right after that you get your error:
s_path_publish_folder = r"\\" + s_host + "\" + s_publish_folder "\" + s_release_name
#                                         ^^ not end of string   ||
#                                        ^--- actual string  ---^||
#                                              line continuation /|
#                                                 extra character /

You need to double those backslashes:
s_path_publish_folder = r"\\" + s_host + "\\" + s_publish_folder "\\" + s_release_name

Better yet, use the os.path module here; for example, you could use os.path.join():
s_path_publish_folder = r"\\" + os.path.join(s_host, s_publish_folder, s_release_name)

or you could use string templating:
s_path_publish_folder = r"\\{}\{}\{}".format(s_host, s_publish_folder, s_release_name)


text:
Q: Simulink: read binary file from the 1st or from the 2nd bit I have a binary file, from which I read a bit sequence (for a Viterbi decoder). In one case I simply read the file from the beginning (from the zero bit), but in another case, I have to read a bit sequence from the 1st bit.
Below is a part of my scheme:

I cannot understand how it can be done.
It is also appropriate to me to delay the sequence for 1 bit (prepend one bit to the sequence), and tried do this using the elements Delay, Unit Delay, Tapped Delay. But I cannot undestand how to do it correctly.
What parameters I shall use for the Bibary File Reader and to the delays?
Now I use the Samples per frame parameter of the File Reader block equal to 262144, and Sample time is 1.

A: Solved by adding a Delay block with the following parameters:


text:
Q: ORA-00904: "ADDRESS_USAGES"."AUS_PRO_REFNO": invalid identifier I am trying to run a select statement from two tables, the data that I want to return takes on 3-4 joins to achieve. I am getting the error

ORA-00904: "ADDRESS_USAGES"."AUS_PRO_REFNO": invalid identifier

when both tables and columns exist. I have read the post relating to this error but given that I am just starting out I cant make head nor tail of them. Any suggestions (be gentle). SQL below TIA
select ins_srq_no, adr_line_all from inspections
    join properties
    on inspections.ins_pro_refno = properties.pro_propref
        join addresses
        on properties.pro_propref = address_usages.aus_pro_refno
            join address_usages
            on address_usages.aus_pro_refno = addresses.adr_refno
               where fsc.address_usages.end_date is null;

A: This on clause is incorrect, because you haven't yet joined to the address_usages table: on properties.pro_propref = address_usages.aus_pro_refno. This is causing Oracle to throw the error you're seeing; it's not about the table or column not existing, it's the fact that within that query, that identifier is invalid because you haven't yet joined to the table.
At a guess (I can't be 100% sure without seeing your table structures and foreign keys), you need to join addresses back to properties. If so, the query should look something like this:
select ins_srq_no, adr_line_all
from inspections
inner join properties
  on inspections.ins_pro_refno = properties.pro_propref
inner join addresses
  on properties.pro_propref = addresses.[column name of FK to properties]
inner join address_usages
  on address_usages.aus_pro_refno = addresses.adr_refno
where fsc.address_usages.end_date is null;


text:
Q: Can create a URL File in OneDrive Web UI but NOT correctly through Graph API I can easily create a URL File through the O365 OneDrive web UI.  Right click > New > Link.  Enter the URL and save. The new item appears in the UI and when clicked, it will take you directly to the new URL, let's say it's www.google.com.
I'm attempting to duplicate this with the Graph API.
GET /me/drive/items/{folderId}/children
with:
{ name:'www.google.com.url',
  file:{}
}

It creates what appears to be a link in the OneDrive UI but when clicked, it will not take you to the URL, it attempts to download a file.  I've tried creating it with and without the .url suffix.  The API looks pretty limited and there aren't many options to pass.  I've also tried the beta API, same issue.

A: Links are actually a file with a special syntax similar to an INI file. From the sample you included here, it looks like you're creating an empty (0 byte) file named "www.google.com.url". Since the empty file doesn't match the format expected for a .URL file, OneDrive doesn't know what to do with it and just downloads the file.
To create a link programmatically, you would need to make a request like this:
PUT https://graph.microsoft.com/v1.0/me/drive/root/children/ShortcutToBing.url/content
Content-Type: text/plain

[InternetShortcut]
URL=https://www.bing.com

This will create a file named ShortcutToBing.url, and fill the contents of the file with the text below the request, which is the contents of a .URL file, pointing to www.bing.com.