text:
Q: ASIHTTPRequest responseData null I'm working with ASIHTTPRequest but I have a responseData empty.
The response is supposed to be a JSON response and when I try to do this in the browser, it works perfectly.
Here is my code :
- (IBAction)simpleURLFetch {
    NSURL *url = [NSURL URLWithString:@"http://url/url/url"];
    ASIHTTPRequest* request = [ASIHTTPRequest requestWithURL:url];
    request.timeOutSeconds = 30;
    [request setDelegate:self]; // I correctly set the ASIHTTPRequestDelegate in my .h file
    [request startAsynchronous];
}

- (void)requestFinished:(ASIHTTPRequest *)azrequest {
    NSString *responseString = [azrequest responseString];
    NSData *responseData = [azrequest responseData];

    NSLog(@"repo : %@ / %@", responseData, responseString);
}

And the log displayed this : "repo : (null) / <> /"
Maybe, I'm not using the result with the good way.. Is there a solution to have my JSON response ?
Regards,
Sébastien ;)

A: The problem is that you're not getting data back, not that you're accessing the data incorrectly. The URL in your code is clearly invalid, and I suspect that's not the one you're using. Either way, the request fails to get any data, so there's nothing to log.

A: If you have implemented the delegate method:
-(void)request:(ASIHTTPRequest *)request didReceiveData:(NSData *)data
Then, responseData will be null. Because the API will handover the data handling to the application.


text:
Q: No signature of method: build_9to1cg5tnfrkz8e8n77tajtyd.android() is applicable for argument I am receiving an error on my flutter app.
Build file 'D:\Projects\friendlysoul\android\app\build.gradle' line: 29
A problem occurred evaluating project ':app'.

No signature of method: build_9to1cg5tnfrkz8e8n77tajtyd.android() is applicable for argument types: (build_9to1cg5tnfrkz8e8n77tajtyd$_run_closure2) values: [build_9to1cg5tnfrkz8e8n77tajtyd$_run_closure2@a4fb7d1]

It was working fine until yesterday but it showed error I am unable to find any solution on internet
    def localProperties = new Properties()
      def localPropertiesFile = rootProject.file('local.properties')
     if (localPropertiesFile.exists()) {
      localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
    }

        def flutterRoot = localProperties.getProperty('flutter.sdk')
     if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in
    the local.properties file.")
     }

      def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
      if (flutterVersionCode == null) {
    flutterVersionCode = '1'
    }

        def flutterVersionName = localProperties.getProperty('flutter.versionName')
      if (flutterVersionName == null) {
      flutterVersionName = '1.0'
     }

      apply plugin: 'com.android.application'
     apply plugin: 'kotlin-android'
    apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
     apply plugin: 'com.google.gms.google-services'

    android {
    compileSdkVersion flutter.compileSdkVersion

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = '1.8'
    }

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.example.friendlysoul"
        minSdkVersion flutter.minSdkVersion
        targetSdkVersion flutter.targetSdkVersion
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        minSdkVersion 19
        multiDexEnable true
    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
}

A: try adding ( ndkVersion "23.1.7779620" ) After compileSdkVersion flutter.compileSdkVersion
will be like this:
android {
    compileSdkVersion flutter.compileSdkVersion
    ndkVersion "23.1.7779620"

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

read more about ndk stable Version
Source: https://developer.android.com/ndk/downloads

redpajama_set_name: RedPajamaStackExchange


text:
Q: MVC 4 using jquery how to check if the model property has elements in it I'm passing in a view model that works with the CheckBoxListFor property and I would like to hide the checkbox section if when I repost to the page there are no check marks ticked. I can show and hide the check box section with no problem using:
$('div.KSearch').hide();

or
$('div.KSearch').show();

What I've been trying to do is check the view model which has a List which hold the information for the keyword model. Is there anyway to check if this list has element being passed in within jquery so that I can show or hide the section with something like:
if (('@Model.SelectedKeywords').length) {
    $('div.KSearch').show();
} else {
    $('div.KSearch').hide();
}

but this always shows the section. Any ideas?

A: Something like this?
var len = @Model.SelectedKeywords.Count;

if (len > 0) {
    $('div.KSearch').show();
} else {
    $('div.KSearch').hide();
}

('@Model.SelectedKeywords').length is treated as a string length in javascript, and it's always positive (and true) ;)

A:
Check MVC Model is null or not in jquery

<script type="text/javascript">

    var checkBoxCount = @(Model.SelectedKeywords != null ? Model.SelectedKeywords.Count : 0);
    if (checkBoxCount != 0) {
        $('div.KSearch').show();
    } else {
        $('div.KSearch').hide();
    }

</script>

I hope this will help.


text:
Q: Closing an android application ? Hi i want to know how to close an application in Android.
Actually i am having idea by using the finish() method we can close present activity..
But what i want is, the following code defines remaining...
Main.java
   Handler handle=new Handler();

    handle.postDelayed(new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            startActivity(new  Intent(ZzzzzProjActivity.this,Second.class));
        }
    }, 3000);

Second.java
/*** same above code***/

Third.java
   @Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    // TODO Auto-generated method stub
    if(keyCode == KeyEvent.KEYCODE_BACK)
    {
        Toast.makeText(getApplicationContext(), "backbutton", 30).show();
        finish();

    }
    return super.onKeyDown(keyCode, event);

}

As per the following code after coming to Third.java, when i click back button it is navigating back to Second.java page. But what i want is my applications needs to close totally. Can anyone help me with this....

A: you can create a dialog activity asking if the user wants to exit. in the intent you can set
Intent.FLAG_ACTIVITY_CLEAR_TOP

It will clear everything the stack and close you app. or you can do what @user1208720 has suggested.

A: for Achive that you should finish the current Activity when you call another Activity from Current one, like when you call second.class from first one you should finish first one and so on...,
i.e when you call another activity.class then you should finish the currentActivity.class by
like
CurrentActivity.this.finish();

A: Use that code to finish your application
Intent startMain = new Intent(Intent.ACTION_MAIN);
    startMain.addCategory(Intent.CATEGORY_HOME);
    startMain.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(startMain);

A: Finish each activity as you are leaving it. Like this whenever you click back, there are no previous activities so the application will exit.
Another way (that is usually not recommended for Android) is to use "System.exit(0);"


text:
Q: iOS universal app links working on simulator, not on real device I implemented universal deep links in my React Native app:
Linking.ts:
const config = {
  screens: {
    details: {
      path: "details",
    },
    menu: {
      path: "menu",
    },
    orders: {
      path: "orders",
    },
    share: {
      path: "share",
    },
  },
}

export const linking = {
  prefixes: ["https://getdad.co.uk", "dad://"],
  config,
}

apple-app-site-association:
{
    "applinks": {
        "apps": [],
        "details": [{
            "appID": "<TEAMID>.io.feastly.dad",
            "paths": [
                "/details",
                "/menu",
                "/order",
                "/share"
            ]
        }]
    }
}

They work fine on the Simulator (direct to the correct page, etc), but on a real device they only direct to the app (i.e. they open the app normally, they don't link to a specific screen)
I tested it in multiple ways on the Simulator (e.g safari, address book, from command line)
Any ideas?

A: Add http:// and the bare url to your linking file. https goes to safari on the iphone, don't know why, don't care, this works:
export const linking = {
  prefixes: [
    "https://getdad.co.uk",
    "http://getdad.co.uk",
    "getdad.co.uk",
    "dad://",
  ],
  config,
}


text:
Q: yii : how to get the post data? Status : created a form with items list by ajax. Adding new item into form is working fine. calculating is working fine. but can't get the added item at controller (create).
Q : How can I get the data at controller from view's post?
This is my view.

<?php $form=$this->beginWidget('CActiveForm', array(
    'id'=>'acc-recei-form',
    'enableAjaxValidation'=>false,
)); ?>

Fields with * are required.

    <?php echo $form->errorSummary($model); ?>
    <?php
    Yii::app()->clientScript->registerScript('add-item', "
        $('#add-item').click(function(){

            //console.log(item_template);
            $('#template .template_item').clone().appendTo('#item_list');
            $('#item_list .template_item').fadeIn();

            return false;
        });

        $('.item-name').live('change', function(){
            var itemID = $(this).val(),
                vNode  = $(this);
            $.ajax({
                url: 'getitem/'+itemID,
                dataType: 'json',
                success: function(data){
                    var target = $(vNode).parents('tr');
                    //console.log('target tr: ' + target);
                    $(target).find('.price').text(data.item_price);
                }
            });

        });

        $('.qty').live('keyup', function(){
          var vNode  = $(this);
          var vQty = $(this).val();
          var target = $(vNode).parents('tr');
          var vPrice = $(target).find('.price').text();

          //console.log($(target).find('.price').text());

          var vrowtotal = vQty * vPrice;
          $(target).find('.row_total').text('$ ' + vrowtotal);
           findTotals();
        });

        function findTotals() {

            var subTotal = '';
            $('#item_list tr.template_item').each(function() {

                //console.log($('.row_total').text());
                var row_total = 0,
                        price = Number($('.price',this).text());
                        qty   = Number($('.qty',this).val());

                    row_total = price*qty;
                    subTotal = Number(row_total) + Number(subTotal);
            });
            subTotal = Number(subTotal);
            $('#grandtotal').text('$ '+ subTotal);

        }
");

    ?>

    name
    price
    qty
    row_total

        <?php echo CHtml::link('Add Item','#',array('class'=>'btn btn-info', 'id'=>'add-item')); ?>

        <?php echo $form->labelEx($model,'acc_category_id'); ?>
        <?php
            echo $form->dropDownList($model,'acc_category_id', $acccategorieslist, array(
            'prompt'=>'Please select a category',
            'options'=>array("$model->acc_category_id"=>array('selected'=>'selected')),
            )
        );
        ?>
        <?php echo $form->error($model,'acc_category_id'); ?>

        <?php echo $form->labelEx($model,'customer_id'); ?>
        <?php echo $form->textField($model,'customer_id',array('size'=>11,'maxlength'=>11)); ?>
        <?php echo $form->error($model,'customer_id'); ?>

        <?php echo $form->labelEx($model,'job_id'); ?>
        <?php echo $form->textField($model,'job_id',array('size'=>11,'maxlength'=>11)); ?>
        <?php echo $form->error($model,'job_id'); ?>

        <?php echo $form->labelEx($model,'accmain_id'); ?>
        <?php echo $form->textField($model,'accmain_id',array('size'=>11,'maxlength'=>11)); ?>
        <?php echo $form->error($model,'accmain_id'); ?>

        <?php echo $form->labelEx($model,'date'); ?>

        <?php
            $this->widget('zii.widgets.jui.CJuiDatePicker', array(
                'name'=>'AccRecei[date]',
                'model'=>$model,
                'value' => $model->date,
                'options'=>array(
                    'showAnim'=>'fold',
                    'dateFormat' => 'dd-mm-yy',
                ),
                'htmlOptions'=>array(
                    'style'=>'height:20px;'
                ),
            ));
            ?>

 Expire Date should not be Current Date.

        <?php echo $form->error($model,'date'); ?>

        <?php echo $form->labelEx($model,'status'); ?>
        <?php echo $form->dropDownList($model,'status', $arr_status, array('prompt'=>'Please select a status')); ?>
        <?php echo $form->error($model,'status'); ?>

        <?php echo $form->labelEx($model,'description'); ?>
        <?php echo $form->textArea($model,'description',array('rows'=>6, 'cols'=>50)); ?>
        <?php echo $form->error($model,'description'); ?>

        <?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>

<?php $this->endWidget(); ?>

    <?php
            echo $form->dropDownList(
                $model,
                'item_name',
                $accitemslist,
                array(
                    'prompt'=>'Please select a category',
                    'options'=>array("$model->acc_category_id"=>array('selected'=>'selected')),
                    'class'=>'item-name',
                    )
                );
        ?>

    <input type="text" name="item_qty[]" class="qty" />

This is my controller
public function actionCreate()
    {
        $model=new AccRecei;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if(isset($_POST['AccRecei']))
        {
            //$model->attributes=$_POST['AccRecei'];
            //if($model->save())
                //$this->redirect(array('view','id'=>$model->id));

            var_dump($_POST['AccRecei']);
        }

        $records = AccCategory::model()->findAll();
        $acccategorieslist = CHtml::listData($records, 'id', 'name');

        $records = AccItem::model()->findAll();
        $accitemslist = CHtml::listData($records, 'id', 'name');

        $arr_status = array('Open'=>'Open', 'Close'=>'Close', 'Late'=>'Late', 'Draft'=>'Draft', 'Partial'=>'Partial');
        $this->render('create',array(
            'model' => $model,
            'acccategorieslist' => $acccategorieslist,
            'accitemslist'=>$accitemslist,
            'arr_status'=> $arr_status,
        ));
    }

A: at View

    <?php
            echo $form->dropDownList(
                $model,
                'item_name[]',
                $accitemslist,
                array(
                    'prompt'=>'Please select a category',
                    'options'=>array("$model->acc_category_id"=>array('selected'=>'selected')),
                    'class'=>'item-name',
                    )
                );
        ?>
    <input type="text" name="item_price[]" class="item-price" />
    <input type="text" name="item_qty[]" class="item-qty" />

at controller
for($i=0; $i < count($_POST['AccRecei']['item_name']); $i++)
            {
                echo    $_POST['AccRecei']['item_name'][$i] . " - " . $_POST['item_qty'][$i] . " - " . $_POST['item_price'][$i] . "
";
            }


text:
Q: Java Annotation - Restrict cardinality (occurrance) of annotation with same field element value I have below condition, which needs Java annotation with a specific field value to appear exactly once in any field of the class. Is it possible with Java 8?
My annotation
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD) //can use with fields only.
public @interface TestAnnotation{

    public String id();
}

the class using the annotation is like
@TestAnnotation(id="test")
private String testString;

@TestAnnotation(id="test1")
private String test1String;

@TestAnnotation(id="test2")
private String test2String;

All I want that to prevent programmer with something like
@TestAnnotation(id="test2")
private String test2String;

@TestAnnotation(id="test2")
private String test3String;

i.e. the same annotation with specific id @TestAnnotation(id="test2") cannot be used twice on fields. At least the id="..." should be unique across the @TestAnnotaion applied fields within a class.

A: As it seems you've figured out, this is possible with an annotation processor.
Here's an example:
package mcve.proc;

import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface IDExample {
    String id();
}

package mcve.proc;

import javax.annotation.processing.*;
import javax.lang.model.*;
import javax.lang.model.element.*;
import javax.lang.model.type.*;
import javax.lang.model.util.*;
import javax.tools.*;
import java.util.*;

@SupportedAnnotationTypes("mcve.proc.IDExample")
@SupportedSourceVersion(SourceVersion.RELEASE_8)
public class UniqueIDProcessor extends AbstractProcessor {
    @Override
    public boolean process(Set<? extends TypeElement> annotations,
                           RoundEnvironment roundEnv) {
        Elements elements = processingEnv.getElementUtils();
        Types    types    = processingEnv.getTypeUtils();
        Map<TypeElement, Set<VariableElement>> map = new HashMap<>();
        // Find each of the fields annotated with @IDExample.
        for (Element elem : roundEnv.getElementsAnnotatedWith(IDExample.class)) {
            if (elem.getKind() == ElementKind.FIELD) {
                VariableElement var  = (VariableElement) elem;
                TypeElement     decl = (TypeElement) var.getEnclosingElement();
                // Group them by declaring class.
                map.computeIfAbsent(decl, key -> new HashSet<>()).add(var);
            }
        }
        // Now for each set of fields annotated with @IDExample...
        for (Set<VariableElement> fields : map.values()) {
            Map<String, Set<VariableElement>> fieldsByID = new HashMap<>();
            // Group them by ID.
            for (VariableElement field : fields) {
                String id = field.getAnnotation(IDExample.class).id();
                fieldsByID.computeIfAbsent(id, key -> new HashSet<>()).add(field);
            }
            fieldsByID.forEach((String id, Set<VariableElement> fieldsWithID) -> {
                // For each set of fields which have duplicate IDs,
                // cause a compilation error on each annotation.
                if (fieldsWithID.size() > 1) {
                    for (VariableElement field : fieldsWithID) {
                        // This is all just finding the annotation mirror so
                        // the compilation error appears in the right place.
                        TypeMirror idExampleMirror =
                            elements.getTypeElement(IDExample.class.getName()).asType();
                        AnnotationMirror annotation =
                            field.getAnnotationMirrors().stream()
                                 .filter(mirror -> types.isSameType(idExampleMirror, mirror.getAnnotationType()))
                                 .findFirst().get();
                        AnnotationValue value =
                            annotation.getElementValues().entrySet().stream()
                                .filter(e -> e.getKey().getSimpleName().contentEquals("id"))
                                .map(e -> e.getValue())
                                .findFirst().get();
                        // Actually cause the compilation error.
                        String errorMessage = String.format("\"%s\" is a duplicate ID.", id);
                        processingEnv.getMessager()
                                     .printMessage(Diagnostic.Kind.ERROR,
                                                   errorMessage,
                                                   field,
                                                   annotation,
                                                   value);
                    }
                }
            });
        }
        return false;
    }
}

There's a tutorial for how to get annotation processing working here. For example, to get the above example processor working, you'd do roughly as follows (depending on your IDE, I assume):

*

*Create a project/separate jar for the two classes mcve.proc.IDExample and mcve.proc.UniqueIDProcessor.

*In that jar, create a directory META-INF/services.

*In that directory, create a text file named javax.annotation.processing.Processor (no file extension) whose content is the fully-qualified name of the annotation processor mcve.proc.UniqueIDProcessor.

*Import that project/jar into your main project as a library.

*Possibly add mcve.proc.UniqueIDProcessor as an annotation processor in e.g. your project properties if such a setting exists/is necessary. I know this is how Netbeans does it. I dunno about other IDEs.


text:
Q: How to test something rendered correctly? How does one test if an application rendered something correctly?
For example (2D example):
Microsoft Word 2007 http://img32.imageshack.us/img32/6197/37841144.png
How does one know that the shadow is placed correctly or the correct color / outline was rendered? Or if 3D effect renders correctly when one would rotate in a direction? Other things could be if the word art was re-sized, how does one measure its 'correctness'?

A: There are a few ways:

*

*If it's actually very precisely specified what should be rendered and in exactly which way, then you can just compare the pixels to a reference rendering.

*In case of things like SVG it's not so clearly specified. The usual approach here is to use reference renderings and compare them by hand. You can easily overlay both, subtract one from the other and spot glaring differences that way. It's not an automatic process, though.

*You can look at the data representing the drawn image instead of the image on screen directly. What gets drawn is (in your example) a vector graphic. That means there are several shapes which should have well-defined properties, shapes and colors and you can simply compare your shape data to a reference. That kind of things can be done automatically. I think Google uses a similar approach to compare Chrome's rendering with reference renderings of web pages; they don't compare pixel data, they compare the higher-level data what and how the browser would render.

A: There are two ways: The image and the rendering based one.
The image way: You must find a way to render the image to an internal pixel buffer (so you can run your tests "headless", i.e. without an actual UI popping up).
Then select a few pixels and make sure their colors are correct. In your example, select a couple of white pixels around the text to make sure the rendering doesn't leak. Helper methods like assertThatRectangleIs(area, color) will help cover some ground. The idea is to select specific areas (like the left vertical bar of the H) and not be too picky.
The rendering based way works with the assumption that your gfx library works. So what you do is you mock the actual rendering code with something like this:
public class MockGC extends GC {
    List<Op> ops = new ArrayList<Op> ();
    void drawLine (int x1, int y1, int x2, int y2) {
        ops.add(new Line(x1, y1, x2, y2, copyGC (gc)));
    }
}

so you just save the command and all relevant options in a data structure that is easy to compare. Or even:
public class MockGC extends GC {
    StringBuilder buffer = new StringBuilder ();

    void drawLine (int x1, int y1, int x2, int y2) {
        buffer.append("line "+x1+","+y1+" - "+x2+","+y2+", color="+foreground()+"\n");
    }
}

Later, you can then just verify that the correct rendering commands have been issued and that the GC (colors, font, rendering hints) was used.
The latter way is much faster and 100% precise but much more work to code.


text:
Q: Query shared fields on "Work Items and Direct Links" So I am trying to write a query that will show me completed bugs, of completed PBIs, that were handled within the same sprint. In other words, bugs we introduced with new functionality, but also closed before finishing the Iteration.
The issue is the hard reference to Iteration Path. What I would like is a variable like @ThisIteration, and I would place it both of the highlighted spots. This way I could return all of the Bugs and PBIs that were resolved with in the iteration for all time.
I assume this just doesn't exist within TFS Queries, so I am looking for work arounds, or clever solutions, like WIQL, etc.
Thanks,
Devin

A: Based on your requirement: "write a query that will show me completed bugs, of completed PBIs, that were handled within the same sprint"
The query you created should works.  For the Iteration Path we can only use the macro @CurrentIteration in on-premise TFS. In VSTS you can use the @CurrentIteration +/- n to  offset the iteration. Please see Query macros or variables and Query for items based on a sliding window of team iterations for details.

Note
Feature availability: The @CurrentIteration +/- n macro is supported
  for VSTS only, and only when run from the web portal.

Besides, you need to adjust/modify the query based on the Bugs working as.

*

*If Bugs are managed with requirements, then the Bugs and PBIs are
in the same level. So you can use Board Column field to filter...

*If Bugs are managed with tasks, then the Bugs and PBIs are not in the
same level. Filter by Board Column will not work. So you need to use State field to filter...

WIQL would be the same...


text:
Q: how to create language transformation that will correctly change the ProductLanguage property in Wix I have a MSI installer with some transform embed in it, I want to trigger this MSI with ProductLanguage property with multiply language like msiexec /i setup.msi TRANSFORM=1033, how to do it?
Thanks

A: Here is an approach which lets Windows Installer select the language automatically based on the target machine:
is it possible to create a multilanguage installer using WIX?
If you want to let the user select a language, the only solution is a custom EXE bootstrapper. This EXE should display a language selection dialog and apply the appropriate transform.


text:
Q: pymongo import errors in python3 flask application I have a python flask based app, which writes to mongo database.
I am using python 3 with the following requirements.txt
Flask
Jinja2
Werkzeug
certifi
chardet
gunicorn
requests
flask_restful
flask
pymongo

I run into this issue :
Traceback (most recent call last):
File "bin/app.py", line 4, in <module>
from helper import save_message_2_db
File "/app/bin/helper.py", line 1, in <module>
from database import DataAccess, MongoDB
File "/app/bin/database.py", line 1, in <module>
import pymongo
File "/app/.heroku/python/lib/python3.6/site-packages/pymongo/__init__.py", line 83, in <module>
from pymongo.collection import ReturnDocument
File "/app/.heroku/python/lib/python3.6/site-packages/pymongo/collection.py", line 21, in <module>
from bson.code import Code
File "/app/.heroku/python/lib/python3.6/site-packages/bson/code.py", line 19, in <module>
from bson.py3compat import string_type, PY3, text_type
ModuleNotFoundError: No module named 'bson.py3compat'

I am trying to understand why does this happen?
This section is what I am concerned with
File "/app/.heroku/python/lib/python3.6/site-packages/pymongo/__init__.py", line 83, in <module>
from pymongo.collection import ReturnDocument
File "/app/.heroku/python/lib/python3.6/site-packages/pymongo/collection.py", line 21, in <module>
from bson.code import Code
File "/app/.heroku/python/lib/python3.6/site-packages/bson/code.py", line 19, in <module>
from bson.py3compat import string_type, PY3, text_type
ModuleNotFoundError: No module named 'bson.py3compat'

Most of the internet blogs/links tell me bson and pymongo dont play well with eachother. pymongo has its own version of bson and i dont need it in my requirements.txt.
I am looking for help to see why this happens, and how to remidiate this.

Update #1
I was using pymongo-3.5.1, and thats where the problem persists. I just downgraded to pymongo-3.5.0 and the problem vanished.
This means I know the workaround to fix this, but the upstream code/package has some issues which needs fixing.

A: Try to uninstall both bson and pymongo:
sudo pip uninstall bson
sudo pip uninstall pymongo

and then reinstall pymongo using pip:
sudo pip install pymongo

A: Uninstall both bson and pymongo. Then, install bson first and pymongo second.

A: It might be some package misconfiguration going on. If the bson package is from
the mongo-python-driver, which is likely, since in line 19, the import statement from bson.py3compat import string_type, PY3, text_type is present.
However the file py3compat.py seems to be missing, which should be right next to code.py in the bson path.
Update
After the question's update letting us know a downgrade fixed the issue and inspecting the code changes between both versions, no relevant changes to the issue are identifiable. Therefore it even more so suggests there was something wrong with the modules, what exactly is hard to tell.

A: @bauman.space provided the most informative and useful explanation of this bson/ pymongo import issue in this thread:

pymongo>=2.7.1 directive overwrites your bson installation
from https://github.com/mongodb/mongo-python-driver
Do not install the "bson" package from pypi. PyMongo comes with its own bson package; doing easy_install bson or pip install bson installs a third-party package that is incompatible with PyMongo.
assuming you really want to use the 3rd party bson, you'll need to
pip uninstall bson (removes the overwritten bson that landed via pymongo package)
  pip install bson (reinstalls the py-bson package)
  or you could patch the pymongo install to remove the collections.abc line (evidently you don't really need it?), but messing with production packaged code is questionable.
pymongo module https://github.com/mongodb/mongo-python-driver/blob/master/bson/py3compat.py#L22-L25
py-bson module you are trying to use. https://github.com/py-bson/bson/blob/master/bson/py3compat.py#L22-L24


text:
Q: Calling a postgres stored procedure with psycopg2 - invalid transaction termination I'm trying to call a procedure with psycopg2 (from pg_partman run_maintenance_proc()).
I'm able to do a simple CALL partman.run_maintenance_proc(); from psql command line.
But when I attempt to do the same with psycopg2 I run into this error:
psycopg2.errors.InvalidTransactionTermination: invalid transaction termination
CONTEXT:  PL/pgSQL function partman.run_maintenance_proc(integer,boolean,boolean) line 43 at COMMIT

Here is my code :
dbconn = psycopg2.connect(t_dsn)
cursor = dbconn.cursor()
cursor.execute('CALL partman.run_maintenance_proc()')
results = cursor.fetchone()
cursor.close()
dbconn.close()

Do you have an idea what might be wrong ?
Edit : the procedure code
CREATE PROCEDURE @extschema@.run_maintenance_proc(p_wait int DEFAULT 0, p_analyze boolean DEFAULT NULL, p_jobmon boolean DEFAULT true)
    LANGUAGE plpgsql
    AS $$
DECLARE

v_adv_lock              boolean;
v_row                   record;
v_sql                   text;
v_tables_list_sql       text;

BEGIN

v_adv_lock := pg_try_advisory_lock(hashtext('pg_partman run_maintenance'));
IF v_adv_lock = false THEN
    RAISE NOTICE 'Partman maintenance already running or another session has not released its advisory lock.';
    RETURN;
END IF;

v_tables_list_sql := 'SELECT parent_table
            FROM @extschema@.part_config
            WHERE undo_in_progress = false
            AND automatic_maintenance = ''on''';

FOR v_row IN EXECUTE v_tables_list_sql
LOOP
/*
 * Run maintenance with a commit between each partition set
 * TODO - Once PG11 is more mainstream, see about more full conversion of run_maintenance function as well as turning
 *        create_partition* functions into procedures to commit after every child table is made. May need to wait
 *        for more PROCEDURE features as well (return values, search_path, etc).
 *      - Also see about swapping names so this is the main object to call for maintenance instead of a function.
 */
    v_sql := format('SELECT %I.run_maintenance(%L, p_jobmon := %L',
        '@extschema@', v_row.parent_table, p_jobmon);

    IF p_analyze IS NOT NULL THEN
        v_sql := v_sql || format(', p_analyze := %L', p_analyze);
    END IF;

    v_sql := v_sql || ')';

    RAISE DEBUG 'v_sql run_maintenance_proc: %', v_sql;

    EXECUTE v_sql;
    COMMIT;

    PERFORM pg_sleep(p_wait);

END LOOP;

PERFORM pg_advisory_unlock(hashtext('pg_partman run_maintenance'));
END
$$;

Note: I noticed there is a cursor.callproc method but it seems to execute a SELECT. The error I have if I use callproc : HINT: To call a procedure, use CALL.
Database : postgres 12.5
/ Psycog2 version: 2.9.1

A: If you're using psycopg2 for connecting, you can use

cursor.autocommit=1
cursor.execute('CALL partman.run_maintenance_proc()')

Can't use this if you're connected through sqlalchemy though,
For sqlalchemy: set autocommit to True while creating your engine
eg)

import sqlalchemy

engine = sqlalchemy.create_engine('postgresql://test',isolation_level="AUTOCOMMIT")

A: Aah I think I see the issue. From here Transaction control:

It is possible to set the connection in autocommit mode: this way all the commands executed will be immediately committed and no rollback is possible. A few commands (e.g. CREATE DATABASE, VACUUM, CALL on stored procedures using transaction control…) require to be run outside any transaction: in order to be able to run these commands from Psycopg, the connection must be in autocommit mode: you can use the autocommit property.


text:
Q: how to use class function in simple php file without including just like web.php file in laravel I know there is somewhere laravel including or requiring the Route class, that is why we are able to use Route::get() in routes/web.php. As a beginner I am curious how that is happening, as I am trying to build my own little mvc  :)

A: You need to look at PHP namespaces
W3 Schools
or here
PHP website
Once you namespace your files, you can the use the
use
keyword to the include the classes that you have namespaced. For example, in Laravel when we
use App\Models\User
We are basically saying the current class we are in, can access the functions and variables in the App\Models\User class based on the scope of the class or variable, that is "protected, private and public" access modifiers.
You need to check a bit more about OOP(Object Oriented Programming) techniques to grasp it easily.
All the best with building your MVC.


text:
Q: Changing a memory process with windbg? I would like to know if it is possible to inject a binary inside a memory process with windbg? Hooking windbg on the process to potentially replace the instructions of the original binary or add the other binary instructions to be run by the process? (as well as injecting the dlls?) Would it be possible to script this?
Basically I would like to know how much can be done with windbg to a process and how much of the process could be modified. (Could I technically use windbg to map a whole binary and its dlls into an existing process?)

A: With windbg to hook on process, you can modify almost all memory owned by that process, for example, the instruction, stack, heap memory etc.

A: I haven't tried that but in theory it is possible (at least some of what you've asked for).
You can store current instructions, rewrite them with a call to LoadLibrary and store your DLL name in the stack. After your DLL is loaded you need to restore rewritten instructions and execute them (or you can emulate them in windbg by doing manually what those instructions do).
Also you can write extensions to windbg to do complex stuff.

A: You probably don't even need WinDbg for this. You can do something along the lines of:

*

*Call OpenProcess to get a handle to the target process

*Allocate some memory in the target process using VirtualAlloc

*Write the code into the memory WriteProcessMemory

*Call CreateRemoteThread to execute the code


text:
Q: how to get links in UI through sitemap-generator in ruby on rails 2 How to get links in UI through sitemap_generator Gem.
actually, i added the sitemap_generator gem in application and then it generated one xml file also.but, I am not getting the thing that how to generate the links in the web site of application?


text:
Q: clearinterval slideshow not working I'm having some problems to clearInterval on a slideshow of pictures. i've been reading a lot but i found nothing that could help me. Here is my code:
<script>  //under are my pictures sliding every 6 seconds (working well)
  $(document).ready(function(){
    var interval1= setInterval (function(){$('#imgvoy1').show(0).delay(36000);
  },0);
  var interval2 = setInterval (function(){
    $('#imgvoy2').hide(0).delay(5000).fadeIn(1000).show(0).delay(5000).fadeOut(1000).hide(0).delay(24000)
  },0);
  var interval3 = setInterval (function(){
    $('#imgvoy3').hide(0).delay(11000).fadeIn(1000).show(0).delay(5000).fadeOut(1000).hide(0).delay(18000)
  },10);
  var interval4 = setInterval (function(){
    $('#imgvoy4').hide(0).delay(17000).fadeIn(1000).show(0).delay(5000).fadeOut(1000).hide(0).delay(12000)
  },0);
  var interval5 = setInterval (function(){
    $('#imgvoy5').hide(0).delay(23000).fadeIn(1000).show(0).delay(5000).fadeOut(1000).hide(0).delay(6000)
  },0);
  var interval6 = setInterval (function(){
    $('#imgvoy6').hide(0).delay(29000).fadeIn(1000).show(0).delay(5000).fadeOut(1000).hide(0).delay(0)
  },0);

  // and here is my code to make the slideshow stop when you click on #imagesprecsuiv element. Unfortunately, it does not work!
  $('#imagesprecsuiv').click(function(){
    clearInterval(interval1);
    clearInterval(interval2);
    clearInterval(interval3)
    clearInterval(interval4);
    clearInterval(interval5);
    clearInterval(interval6)
  });
</script>

Thank you in advance for your help!

A: clearInterval won't cancel any events that have been delayed using jQuery's .delay() function. These events can't be cancelled as you can read here (.delay()).

The .delay() method is best for delaying between queued jQuery effects. Because it is limited—it doesn't, for example, offer a way to cancel the delay—.delay() is not a replacement for JavaScript's native setTimeout function, which may be more appropriate for certain use cases.

Looking at your code the calls to setInterval aren't doing anything at all since you've given them a timeout of 0ms.
If you want each of these events to be cancellable then setTimeout and clearTimeout are probably your best bet (or setInterval but it's moderately evil), but you won't be able to chain all those things together which may also help make your code more legible.


text:
Q: I want use lower and upper case in the terminal for choosing I want use lower and upper case in the terminal for choosing
in all cases in this code i can just use upper case, but I want use both
                case 'S ':
                {
                    System.out.println("File status: "+partyPlaner.getFileStatus());
                    break;
                }
                case 'N':
                {
                    System.out.print("Enter new name for planner:");
                    String newName = keyboard.nextLine();
                    partyPlaner.setPlannerName(newName);
                    break;
                }

A: Cast the variable you are switching on to uppercase() for example.
So inside the switch statement, the variable will be in uppercase, and you only need to enter the uppercase "cases".
switch(s.toUpper()){...}


text:
Q: Using AWS Route 53 http redirect working, https times out Using the routing rules as mentioned here: Set up DNS based URL forwarding in Amazon Route53
<RoutingRules>
    <RoutingRule>
        <Redirect>
            <Protocol>https</Protocol>
            <HostName>dota2.becomethegamer.com</HostName>
            <HttpRedirectCode>301</HttpRedirectCode>
        </Redirect>
    </RoutingRule>
</RoutingRules>

I am able to see that http://becomethegamer.com properly redirect to https://dota2.becomethegamer.com but https://becomethegamer.com times out.
I thought it was the Protocol piece but realized that's the outbound rather than inbound.
This is in a bucked named becomethegamer.com and in Route 53 becomethegamer.com is an alias with the target as that bucket.
What could be causing https to not redirect?

A: No, it's this:

The website endpoints do not support https.
http://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteEndpoints.html

You can't redirect an https request without speaking https, and additionally, you need an SSL certificate that's valid for the hostname.
You can still do exactly what you're trying to do, but you'll need to use CloudFront in front and S3 in the back.  Your S3 redirection configuration stays the same, but you'll create a CloudFront distribution, configure your domain name as an alternative domain name there, load your SSL cert into CloudFront, use the bucket-name.s3-website-xx-xxxx-xx.amazonaws.com web site endpoint (from the S3 console) as the Origin server, and point Route 53 to CloudFront instead of S3.
http://docs.aws.amazon.com/gettingstarted/latest/swh/getting-started-create-cfdist.html


text:
Q: How to calculate CRC16-CCITT/KERMIT in both C# and C I am working on calculating a CRC16-CCITT/KERMIT so that I can check data integrity on transmissions of 64-byte data packets between a C# Winforms Application and a microcontroller (PSoC5LP/Arm Cortex-M3).  I'm close, but just not quite getting the CRC calculation to line up between the two and having a tough time figuring out why.  The example data packet I am calculating the CRC for is:

02 03 01 02 03 04 05 07 08 09 0A 0B 00 00 06 0E 0C 0D 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

The CRC for this packet comes out to 0x4D8C in both my Winforms application as well as for this online CRC calculator
Since these line up, I'm assuming the calculation in the C# calculation is legit.  Regardless, here's the code.  Pulled from this page with the only change being the I hardcoded the polynomial (0x8408):
public static class Crc16
{
    const ushort polynomial = 0x8408;
    static readonly ushort[] table = new ushort[256];

    public static ushort ComputeChecksum(byte[] bytes)
    {
        ushort crc = 0;
        for (int i = 0; i < bytes.Length; ++i)
        {
            byte index = (byte)(crc ^ bytes[i]);
            crc = (ushort)((crc >> 8) ^ table[index]);
        }
        return crc;
    }

    static Crc16()
    {
        ushort value;
        ushort temp;
        for (ushort i = 0; i < table.Length; ++i)
        {
            value = 0;
            temp = i;
            for (byte j = 0; j < 8; ++j)
            {
                if (((value ^ temp) & 0x0001) != 0)
                {
                    value = (ushort)((value >> 1) ^ polynomial);
                }
                else
                {
                    value >>= 1;
                }
                temp >>= 1;
            }
            table[i] = value;
        }
    }
}

Now the gotcha is getting a working CRC16-CCITT/KERMIT calculator function for the microcontroller that will generate the same CRC for this packet of data.
Here's what I currently have (pulled from this answer):
uint16_t crc16k(uint16_t crc, uint8_t *mem, uint8_t len) {
    uint8_t *data = mem;

    if (data == NULL){
        return 0;
    }

    crc = ~crc;
    crc &= 0xffff;

    while (len--) {
        crc ^= *data++;
        for (uint8_t k = 0; k < 8; k++)
            crc = crc & 1 ? (crc >> 1) ^ 0x8408 : crc >> 1;
    }

    crc ^= 0xFFFF;
    return crc;
}

I am calling this as such:
uint16_t crc_calc = crc16k(0x0000, message_in, 64);

Here's where I'm getting some funnies. that data packet is 64-bytes, but in actuality (for this packet), only the first 29 bytes are data I am using.  The rest is just padding out to meet 64 bytes.  When I calculate the CRC on the WinForms side, it looks like it is using all 64 bytes, including the padding.  When I do the same on the microcontroller side, I get a result of 0xE918.  What's weird is if I limit the length parameter to just the 29 bytes I'm interested in, I get 0x4C8B, which is perilously close to the 0x4D8C I'm looking for.  I also noticed that in the online calculator I used, it claims the XOR on the output should be 0x0000.  The C function I am using XORs 0xFFFF on the output.  Changing this to 0x0000 (and processing all 64 bytes) gives me 0x16E7.
So I'm not sure where the problem lies.  This is the first time I've worked with a CRC so I could be missing something obvious.  Any ideas?
Thank you in advance for the help!  Let me know if there's any additional information I should provide.

A: Of course I get it less than 10 minutes after posting the question (isn't that always how it goes?)
The C code I thought was for CRC-16/KERMIT looks to actually be CRC-16/X-25.  I think I got confused because the question I took the code from the answer of was asking about KERMIT, but the answer says it's X-25.
Removing the bitwise invert of crc at the start of the function:
crc = ~crc;

AS WELL AS removing
crc ^= 0xFFFF;

This leaves me with:
uint16_t crc16k(uint16_t crc, uint8_t *mem, uint8_t len) {
    uint8_t *data = mem;

    if (data == NULL){
        return 0;
    }

    while (len--) {
        crc ^= *data++;
        for (uint8_t k = 0; k < 8; k++)
            crc = crc & 1 ? (crc >> 1) ^ 0x8408 : crc >> 1;
    }

    return crc;
}

This seems to be working and the CRC matches up between my Winforms app and the PSoC5.  I suppose the "near match" I had earlier was just coincidence the numbers were similar?  I'd love to hear an explanation if someone has one.


text:
Q: Elasticsearch Query match_all I am using Elasticsearch 1.5.2. I have an index with 278 stored products. I check that they are stored in head plugin. When Run a query of match_all I get only 10 hits however the total is 278. I get this result:
{
   "took": 3,
   "timed_out": false,
   "_shards": {
      "total": 5,
      "successful": 5,
      "failed": 0
   },
   "hits": {
      "total": 278,
      "max_score": 1,
      "hits": [.................only 10 products.......]

I want that I get in hits all my 278 results.

A: You need to pass in a size parameter to your query, like this:
 POST /_search
 {
  "from" : 0, "size" : 300,
  "query" : {
      "match_all":{}
   }
 }

The default is just 10 documents.


text:
Q: Why is the FILESTREAM data not accessible, after AG listener is created? I'm having a hard time figuring out why my app can't access filestream data, after we enable AG listener.
Background info:
Initial environment:
APP Server
Web Server  IIS  Windows Server 2012 R2
DB Server
Windows Server 2012 R2
SQL Server N1 (named instance N1\SQL2016 port 1434) with DB (APP_DB) (with filestream data).
Filestream I/O enabled, filestream data was available to APP (web application (IIS)) - read write OK
Environment changes:
Add new server Node 2 (N2) installed same SQL Server version as default instance
Create failover cluster CL (N1 + N2)
Implemented Always On (DB replication working)
Problem:
When AG listener is created the filestream data is accessed over the VNN name  (equal to Listener name) (\VNN\filestream_share_name) and the app can't access the data over the new path.
When accessing N1 or N2 over file explorer \N1\ we can see the filestream share name, but when accessing the VNN name (\listener) in file explorer we can't see the sql server filestream share name.
I have tried to disable and disable / enable filestream I/O on both SQL Server nodes, to recreate the VNN\filestream share name, but no success.


text:
Q: Number of ways to get a flush from shuffled cards How many different ways are there to draw a flush from a well shuffled full deck of cards?
If correctly counting, I suppose the answer is $\frac{13\times 12\times 11 \times 10 \times 9}{1\times 2 \times 3 \times 4 \times 5}$, but would like to know your thoughts on it.

A: You can select $5$ cards from a suit in $\binom{13}5$ ways, and since there are $4$ suits, multiply it by $4$, which you did not.


text:
Q: Colors in my Google Chrome Browser I am using Ubuntu 20.04 and I've started to realize that my browser colours have kind of changed, for an example, when text is highlighted in search bars or what not, they are highlighted orange instead of blue, does anyone know how I could change it?
For more understanding I will attach image.

A: You are using Ubuntu. If you use the default theme, Yaru, then the accent color is orange. It appears that this selection color in Google Chrome now adheres to the default color theme of the desktop. As such, that is a good thing because it increases visual consistency across applications.
To change that, you must change your GTK theme. That change will affect all applications.


text:
Q: Can we derive a formula for the volume of revolution in polar coordinates. Can we derive a formula for the volume of revolution in polar coordinates?
My attempt was so consider a very small piece of a circle that is bounded by the counterclockwise angles $\theta$ and $\theta+d \theta$ in the $xy$ plane. Then the lines forming those angles are $y=(\tan \theta) x$ and $y=\tan (\theta+d \theta) x$. So I suppose to get the (approximate) volume obtained by rotating this little about the $x$ axis.  We should consider,
$$\int\limits_{0}^{r \cos \theta} (\tan (\theta+d \theta) x)^2-(\tan (\theta) x)^2 dx$$
This is a bit sloppy and even so, I'm not sure where to go from here.

A: Can't say I have seen it come up befor, but:
$V = \pi \int_{x_0}^{x_1} y^2 dx$
$y = r\sin\theta\\
x = r\cos\theta \\
dx = -r\sin\theta\  + \cos\theta \frac {dr}{d\theta}d\theta $
$v = \pi \int_{0}^{\pi} r^3\sin^3\theta\ - r^2\sin^2\theta\cos\theta \frac {dr}{d\theta} d\theta$
The limits of integration might not necessarily be $0$ to $\pi.$  But frequently enough it would be.


text:
Q: UITableView getting Initialized in the middle of viewDidLoad? I have a VC that I'm initializing, and in it is a View. In the View is a UITableView, UIButton, and UIImage.
I was messing with button attributes when all of a sudden, wham:
Assertion failure in -[UITableView _createPreparedCellForGlobalRow:withIndexPath:]

After further digging, it was because my code:
UINib *animCellNib = [UINib nibWithNibName:@"IoUISEAnimationDetailListingCell" bundle:nil];
[animationDetailsTableView registerNib:animCellNib forCellReuseIdentifier:@"AnimationDetailListingCell"];

was not getting executed. Further digging revealed in the top of my viewDidLoad method, it jumped into initializing the tableView. So from my method name trace, you can see that it starts with the numberOfSectionsInTableView. Though this only happens a few lines into my viewDidLoad
2011-10-12 15:43:42.113 io[5052:11903] <IoUISEAnimationDetailsViewController: 0x764c460> - initWithNibName:bundle:
2011-10-12 15:43:42.116 io[5052:11903] <IoUISEAnimationDetailsViewController: 0x764c460> - viewDidLoad
Current language:  auto; currently objective-c
2011-10-12 15:43:49.017 io[5052:11903] <IoUISEAnimationDetailsViewController: 0x764c460> - numberOfSectionsInTableView:
2011-10-12 15:43:49.017 io[5052:11903] <IoUISEAnimationDetailsViewController: 0x764c460> - tableView:titleForHeaderInSection:
2011-10-12 15:43:49.017 io[5052:11903] <IoUISEAnimationDetailsViewController: 0x764c460> - tableView:titleForFooterInSection:
2011-10-12 15:43:49.017 io[5052:11903] <IoUISEAnimationDetailsViewController: 0x764c460> - tableView:numberOfRowsInSection:
2011-10-12 15:43:49.017 io[5052:11903] <IoUISEAnimationDetailsViewController: 0x764c460> - tableView:cellForRowAtIndexPath:
2011-10-12 15:43:49.017 io[5052:11903] *** Assertion failure in -[UITableView _createPreparedCellForGlobalRow:withIndexPath:], /SourceCache/UIKit_Sim/UIKit-1912.3/UITableView.m:6072
2011-10-12 15:43:49.018 io[5052:11903] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath:'

In the viewDidLoad method, sometime after I set saveButton.titleLabel.lineBreakMode and before saveButton setBackgroundImage:newImage it jumps to the numberOfSectionsInTableView method.
Since my code for registerNib: forCellReuseIdentifier: is after the button code, the cell nib is not registered, thus causing my dequeueReusableCellWithIdentifier to return nil and crash.
Any tips on why this is happening?
Here is the code for viewDidLoad:
- (void)viewDidLoad {
if (IoUIDebug & IoUIDebugSelectorNames) {
    NSLog(@"%@ - %@", [self description], NSStringFromSelector(_cmd) );
}

[super viewDidLoad];

    // Create an Empty Tableview and steal its Background.
    //set our background to it
UITableView *tv = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStyleGrouped];
UIView *backgroundView = tv.backgroundView;
[self.view addSubview:backgroundView];
[tv release];
    // CGRect backgroundFrame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    //[backgroundView setFrame:backgroundFrame];
[self.view sendSubviewToBack:backgroundView];

saveButton.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
saveButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
saveButton.titleLabel.textAlignment = UITextAlignmentCenter;
saveButton.titleLabel.lineBreakMode = UILineBreakModeCharacterWrap;

[saveButton setTitle:NSLocalizedStringFromTable(@"Save Animation Label",@"ScreenEditor",@"Save Animation Label") forState:UIControlStateNormal];
[saveButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
saveButton.titleLabel.font = [UIFont boldSystemFontOfSize:17];

UIImage *newImage = [[UIImage imageNamed:@"BlueButtonSmall.png"] stretchableImageWithLeftCapWidth:12.0 topCapHeight:0.0];
[saveButton setBackgroundImage:newImage forState:UIControlStateNormal];

UIImage *newPressedImage = [[UIImage imageNamed:@"BlueButtonSmallPressed.png"] stretchableImageWithLeftCapWidth:12.0 topCapHeight:0.0];
[saveButton setBackgroundImage:newPressedImage forState:UIControlStateHighlighted];

    // in case the parent view draws with a custom color or gradient, use a transparent color
saveButton.backgroundColor = [UIColor clearColor];

if (UIAppDelegate.ioMainViewController.currentDeployment.readOnlyMode == NO) {                // Only setup for the long press if the deployment is editable..
    instructionLabel.text = NSLocalizedStringFromTable(@"Animation Details Instructions", @"ScreenEditor", @"");

} else {
    instructionLabel.text = NSLocalizedStringFromTable(@"Locked Message", @"Configuration",@"");
}

IoCDElementAnimation * currentAnimation = UIAppDelegate.ioMainViewController.currentElementAnimation;

if (currentAnimation) {
    newAnimation = currentAnimation;
    selectedSysCDAnimation =  currentAnimation.sysAnimation;
    selectedIoCDTag = currentAnimation.tag;
    animationSaved = YES;

} else {
    selectedSysCDAnimation  = nil;
    selectedIoCDTag = nil;
    animationSaved = NO;
}

UINib *animCellNib = [UINib nibWithNibName:@"IoUISEAnimationDetailListingCell" bundle:nil];

[animationDetailsTableView registerNib:animCellNib forCellReuseIdentifier:@"AnimationDetailListingCell"];

    //  set our TableView Background to clear so we can see our new background
[animationDetailsTableView setBackgroundView:nil];
[animationDetailsTableView setBackgroundColor:[UIColor clearColor]];

[self refreshContents:nil];

[self setupOrientation:[[UIApplication sharedApplication] statusBarOrientation]];
[self.view setNeedsLayout];
}

In this method, dequeueReusableCellWithIdentifier: returns nil. The AnimationDetailListingCell identifier cannot be found as the registerNib code in viewDidLoad has not yet run. It would seem like all of viewDidLoad should run before it breaks out to initialize the tableview, right?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if (IoUIDebug & IoUIDebugSelectorNames) {
    NSLog(@"%@ - %@", [self description], NSStringFromSelector(_cmd) );
}
UITableViewCell *cell;

cell = [animationDetailsTableView dequeueReusableCellWithIdentifier:@"AnimationDetailListingCell"];
// cell at this point in nil!

[self configureCell:cell atIndexPath:indexPath];

return cell;
}

A: I had the same error. I think it is because adjusting certain button properties means the view  (apparently lazily created) needs to be set up, which means the table needs to be ready to go, and it isn't yet, perhaps because its datasource hasn't been connected or something. Try moving your button adjustment to later in the viewDidLoad method; that worked for me.


text:
Q: React - Material UI - TextField controlled input with custom input component not working properly losing focus I am trying to implement custom input element for TextField component from Material UI
example :

export const InputsPage: React.FC = () => {
  const [value, setValue] = useState('');
  return (
    <Paper>
      <Box p={2}>
        <TextField
          value={value}
          onChange={(e) => {
            setValue(e.target.value);
          }}
          color='primary'
          label='FROM'
          placeholder='Placeholder'
          InputProps={{
            inputComponent: ({ inputRef, ...rest }) => <input ref={inputRef} {...rest} type='text' />,
          }}
        />
      </Box>
    </Paper>
  );
};

because i am using controlled input with my own state the input is not working properly ... each time ill trying to type some thing the input will loss focus so i need to type each char/number   and make a click on the input again to make a focus so i can continue typing
if ill use uncontrolled input it will work properly
here is an example what is happening : codeSandbox

A: The problem is that you are defining inline the component type for the inputComponent prop. This means that with each re-render it will be considered by React to be a new component type, so instead of just re-rendering, the element will be remounted (removed completely from the DOM and re-added) which results in focus being lost.
You can fix this by defining the component type (CustomInputComponent in the example) at the top-level as shown in the example below:
import React, { useState } from "react";
import "./styles.css";
import { TextField } from "@material-ui/core";
const CustomInputComponent = ({ inputRef, ...rest }) => (
  <input ref={inputRef} {...rest} type="text" />
);
export default function App() {
  const [value, setValue] = useState("");
  return (
    <div className="App">
      <TextField
        value={value}
        onChange={(e) => {
          setValue(e.target.value);
        }}
        color="primary"
        label="FROM"
        placeholder="Placeholder"
        InputProps={{
          inputComponent: CustomInputComponent
        }}
      />
    </div>
  );
}

A: If you want to use masked input with material ui and form library you could do this:
import React, { memo } from "react";
// MASKED INPUT
import MaskedInput from "react-text-mask";
// MATERIAL UI
import { Phone } from "@mui/icons-material";
import { InputAdornment, TextField } from "@mui/material";
interface MaskedPhoneInputProps {
  fieldRef: (ref: HTMLElement | null) => void;
  field: any;
  errors: any;
}
const MaskedPhoneInput = ({
  fieldRef,
  field,
  errors,
}: MaskedPhoneInputProps) => {
  return (
    <MaskedInput
      {...field}
      ref={(ref) => {
        fieldRef(ref ? ref.inputElement : null);
      }}
      mask={[
        "0",
        "(",
        /[1-9]/,
        /\d/,
        /\d/,
        ")",
        " ",
        /\d/,
        /\d/,
        /\d/,
        "-",
        /\d/,
        /\d/,
        /\d/,
        /\d/,
      ]}
      guide={false}
      keepCharPositions
      render={(ref, props) => (
        <TextField
          inputRef={ref}
          {...props}
          variant="outlined"
          label="Telefon Numarası"
          fullWidth
          size="small"
          placeholder="Telefon numaranızı giriniz"
          error={!!errors?.phone}
          helperText={errors?.phone?.message}
          InputProps={{
            startAdornment: (
              <InputAdornment position="start">
                <Phone sx={{ color: "text.disabled" }} />
              </InputAdornment>
            ),
          }}
        />
      )}
    />
  );
};

export default memo(MaskedPhoneInput);

Then you could use it in any controller (formik, react hook form) like this:
<Controller
              name="phone"
              control={control}
              rules={{ required: true }}
              render={({ field: { ref, ...rest } }) => (
                <MaskedPhoneInput fieldRef={ref} field={rest} errors={errors} />
              )}
            />

WARNING
ref={(ref) => {
        fieldRef(ref ? ref.inputElement : null);
      }}

Defining ref like it is important, if you don't define you may take error about focus like elm.focus is not a function in react hook form.


text:
Q: Map on premises domain.local to custom domain on azure AD Our on premises windows domain is not public, it is myDomain.local.
In Azure Active directory we have created a custom public domain publicDomain.com and we have the legacy domain publicDomain.onMicrosoft.com.
We want to sync users from myDomain.local to publicDomain.com but they are created inside publicDomain.onMicrosoft.com.
According to Microsoft support the only way to achieve this goal is to re-install Azure Connect and tell it to use a specific field to create new users in Azure AD. For example we can set user mail field to n.surname@publicDomain.com to create that user principal name in Azure AD.
I found this related post which says to put a DNS entry , but I cannot understand how it may work.
Is there another way to force Azure AD to map users from myDomain.local to azure custom domain publicDomain.com ?
Can the synchronization rules editor be used for this scope ?

A:
According to Microsoft support the only way to achieve this goal is to
re-install Azure Connect and tell it to use a specific field to create
new users in Azure AD.

I don't know where you read that, but it isn't correct. Here's what I'd suggest:
Here's what I'd suggest:
Reconfigure Azure AD Connect to sync an empty OU. This will put all of your AD accounts out of scope and will cause them to be deleted in Office 365. Note that this will only affect the user accounts that have been synced from on premises AD. It will not affect your existing Office 365 "cloud only" users.
Add your Office 365 verified domain as a UPN suffix in AD.
For one AD user account set the new UPN suffix on their user account. Make sure that the User Logon Name matches the Office 365 username for the existing Office 365 "cloud only" user (Username@VerifiedDomain.com). If it doesn't, change the AD User Logon Name to match the Office 365 username. This won't affect the AD users ability to logon to the domain, unless they're logging on with their User Logon Name.
Permanently delete the Office 365 account for this user. - https://practical365.com/permanently-remove-deleted-microsoft-365-users-from-azure-ad/
Move this user in AD to your empty OU and initiate an Azure AD Connect delta sync cycle. The user should now be synced to the existing Office 365 user account. If it is, then repeat the above for all of your AD users. If it isn't then open a support case in your Office 365 tenant.


text:
Q: Expectation Maximization Reestimation Typically, the re-estimation iterative procedure stops when lambda.bar - lambda is less than some epsilon value.
How exactly does one determine this epsilon value? I often only see is written as the general epsilon symbol in papers, and never the actual value used, which I assume would change depending on the data.
So, for instance, if the lambda value of my first iteration was 5*10^-22, second iteration was 1.3*10^-15, third was 8.45*10^-15, fourth was 1.65*10^-14, etc., how would I determine when the algorithm needed no more iteratons?
Moreover, what if I were to apply the same alogrithm to a different datset? would I need to change my epsilon definitions?
Sorry for the long question. Pretty puzzled by it... :)

A: "how would I determine when the algorithm needed no more iteratons?"
When you get a "good-enough" result within a reasonable amount of time. ;-)
"Moreover, what if I were to apply the same alogrithm to a different datset? would I need to
change my epsilon definitions?"
Yes, most probably.

A: If you can afford it, you can just let it iterate until the updated value <= the old value (it could be < due to floating point error). I would be inclined to go with this until I ran out of patience or cpu budget.


text:
Q: Extract values from H mn s format time in python I want to extract this kind of data from a time value with some regex:
1h 34mn 2s     >>> [1,34,2]
1h 4mn         >>> [1,4]
34mn 2s        >>> [34,2]
34s            >>> [34]

I tryed :
re.match(r'((.*)h)?((.*)mn)?((.*)s)?', '1h 34mn').groups()
('1h', '1', ' 34mn', ' 34', None, None)

Almost done but still not what I'm looking for.
Edit:
I need to extract total value in seconds 1h 34mn 2s >>> 1*3600+34*60+2

A: Well, if all you just want is seconds, and aren't too worried that hours precedes minutes, and minutes precedes seconds, as long as they're qualified (ie, '1s 9h 32m' is valid), you could use:
import re

mult = {'h': 60*60, 'mn': 60}
res = sum(int(num) * mult.get(val, 1) for num, val in re.findall('(\d+)(\w+)', '1h 34mn 2s'))
# 5642

A: If the data is as in your example, you can simply do:
In [171]: import re

In [172]: s='1h 34mn 2s'

In [173]: re.findall('\d+',s)
Out[173]: ['1', '34', '2']

or if you want int's:
In [175]: [int(i)for i in re.findall('\d+',s)]
Out[175]: [1, 34, 2]

A: Try this:
[in] regex = re.compile(r'^(?:(\d+)h)?(?: *)(?:(\d+)mn)?(?: *)(?:(\d+)s)?$')
[in] for x in ("1h 34mn 2s", "1h 4mn", "34mn 2s", "34s"):
[in]     hours, minutes, seconds = regex.match(x).groups()
[in]     total = 0
[in]     if hours:
[in]         total += int(hours) * 3600
[in]     if minutes:
[in]         total += int(minutes) * 60
[in]     if seconds:
[in]         total += int(seconds)
[in]     print total

[out] 5642
[out] 3840
[out] 2042
[out] 34

Just realized you weren't looking for a triple on every input.  Fixed now.

A: KISS
import re

a = ['1h 34mn 2s','1h 4mn','34mn 2s','34s']

def convert(s):
    if s:
        return int(s[0])
    else:
        return 0

def get_time(a):
    h = convert(re.findall('(\d*)h',a))
    m = convert(re.findall('(\d*)m',a))
    s = convert(re.findall('(\d*)s',a))
    return h,m,s

for i in a:
    print get_time(i)

Output:
(1, 34, 2)
(1, 4, 0)
(0, 34, 2)
(0, 0, 34)

EDIT. I just saw, that you want date in seconds. You simply edit the return line in get_time function  into:
return h*3600+m*60+s

Output:
5642
3840
2042
34


text:
Q: tkinter: add scrollbar to one frame while i use two in this code i try to add two frames one on the left and second on the right and i need to make the left frame fixed and add scrollbar on the right frame
from tkinter import *
from tkinter import ttk
from tkinter.ttk import *

win_width = 1200
win_hight = 720

root=Tk()
root.geometry("{}x{}".format(str(win_width),str(win_hight)))

frame_style = Style()
frame_style.configure('blue.TFrame', background='#1d96f4',highlightthickness=0)
frame_style.configure('white.TFrame', background='#FFFFFF',highlightthickness=0)

frame1 = ttk.Frame(root, style='blue.TFrame')
frame1.grid(row=0,column=0)
frame1.config(width=win_width*(50/100.0),height=win_hight, relief=RIDGE)
frame1.grid_propagate(0)

frame2 = ttk.Frame(root, style='white.TFrame')
frame2.grid(row=0,column=2)
frame2.config(width=win_width*(50/100.0),height=win_hight, relief=RIDGE)
frame2.grid_propagate(0)

my_canvas = Canvas(frame2, background="white",width=1100,height=720)
my_canvas.pack(side=LEFT,fill=Y)

my_scrollbar = ttk.Scrollbar(frame2, orient=VERTICAL , command=my_canvas.yview)
my_scrollbar.pack(side=RIGHT, fill=Y)

my_canvas.configure(yscrollcommand=my_scrollbar.set)
my_canvas.bind('<Configure>', lambda e: my_canvas.configure(scrollregion = my_canvas.bbox("all")))

second_frame = Frame(my_canvas)
my_canvas.create_window((1200,720), window=second_frame)

for i in range(0,50):
    title_label = Label(second_frame, text="Test",background='#1d96f4',foreground="#FFFFFF",font=('Helvetica', 22, 'bold'))
    title_label.place(x=20, y=40*i)

root.mainloop()

I have tried various methods but have not been able to set the look properly and I don't want to use "pack" at least inside the right frame


text:
Q: Get only gallery folder : Intent.ACTION_GET_CONTENT I would like to implement a Picture Chooser, since there's a bug with the Recent image foler and the Download Folder the Android app crashes when selecting an image from these two folders, I would like to hide them, or open directly the Gallery folder without showing the Folder chooser panel,
This is my actual code :
Intent intent = new Intent (Intent.ACTION_GET_CONTENT);
startActivityForResult (intent, 1000);

and in the on Result Method :
@Override
protected void onActivityResult (int requestCode, int resultCode, Intent intent) {

    super.onActivityResult (requestCode, resultCode, intent);

    String uri = intent.getDataString ();
    String absolutePath = getRealPathFromURI (uri);
    String compressedFilePath = compressImage (absolutePath);

    encodedResult = base64File (new File (compressedFilePath)); //String
}

protected String getRealPathFromURI (String contentURI, UIView uiView) {
    Uri contentUri = Uri.parse(contentURI);
    Cursor cursor = ((ContextWrapper) uiView).getContentResolver ().query(contentUri, null, null, null, null);
    if (cursor == null) {
        return contentUri.getPath();
    } else {
        cursor.moveToFirst();
        int index = cursor.getColumnIndex(MediaColumns.DATA);
        return cursor.getString(index);
    }
}

So when I select an image from a folder like : Gallery, Pictures etc... It works just fine. But for the 2 folders : Download and Recent it crashes and gives me :
java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow.  Make sure the Cursor is initialized correctly before accessing data from it.

Or maybe there is a more correct way of doing that which I'm not aware of it ?
Do you have any idea about this ? How can I achieve that ? Thanks.

A:
it crashes and gives me

That is because you are assuming that any Uri can be converted into a File. That has never been supported.
Use a ContentResolver and consume the Uri via openInputStream() (or openOutputStream(), if appropriate).


text:
Q: I have 2 issues with includes I am programming in CCS (based on Eclipse) to learn to use microcontrollers.
I'm having some problems with includes.

I have 4 files:
GPIO.h - macros and prototypes of GPIO functions
GPIO.c - implementation of GPIO functions declared in GPIO.h
main.c - main program
util.h - macros and typedefs essential to all other files

In each of the programs put the includes, I ctrl + c / ctrl + v of my code:
I really try with " ", I would like to make my code run, it would be rewarding.
GPIO.h - #include "util.h"

GPIO.c - #include "GPIO.h"

main.c - #include "GPIO.c"

util.h - (no includes)

As in eclipse all files are placed in the project folder. Already checked manually by accessing the folder, and they are there.
When I compile and run, there are 2 errors referring to include:
"../GPIO.c", Line 9: fatal error # 1965: Can not open source file "GPIO.h"

"../main.c", Line 1: fatal error # 1965: Can not open source file "GPIO.c"

I do not understand what's wrong!
I made the edit so that people understand that even with "" the error continues (@ mame98). I made it clear that I am using the CCS IDE based on Eclipse and now my suspicion is with the operating system. I will have the opportunity to test on Windows only now.

A: You should only include H files as Eugene Sh. Points out... Also, use #include "util.h" and #include "gpio.h" as they are local files and they are not in the default search path of your compiler. If you want to include 'global' headers (which are in the search path) you have to use #include <file.h>.
Maybe also note, that it is possible to add your local folder to the search path with using the -I. option for GCC (should work with other compilers too).
For more infos about the search path, see here.

A: <> is for libraries like #include <stdio.h>
"" is used for your own files #include "GPIO.h"
Be careful including .c! If GPIO.h is included in GPIO.c, too, you could get errors..(multiple inclusion protection is useful here!)


text:
Q: Unit testing messages I have a web page that shows different messages according to different conditions.
I want to unit test this so I configured my project to use MVVM and I'm testing my ViewModel.
My ViewModel now format different messages. How can I test this? I don't want to reproduce all strings, it seems dirty...
Now I'm doing this:
void test()
{
    string message = _viewModel.DoWork();
    Assert.AreEqual(message, Resource.MyResourceText);
}

But this is a simple case. Now I have dynamic strings containing system date and other variables.
How can I test this in an elegant way? Thanks!

A: If your concern is just reproducing strings in your test fixtures, put them all in an enum or class.
public static class StatusMessage
{
    public static readonly string SavedSuccessfully
        = "Item was successfully saved.";
    public static readonly string DuplicateRecord
        = "This record is a duplicate.";
    public static readonly string SubscriptionExpired
        = "Your subscription has expired; please renew now.");
}

Now your viewmodel can perform its logic and return one of the StatusMessages:
public class SomeViewModel
{
    ...

    public string Status
    {
        get { return StatusMessage.SavedSuccessfully; }
    }

    ...
}

In your test:
Assert.AreEqual(StatusMessage.SavedSuccessfully, viewmodel.Status);

A: I will go with what you are currently doing or may be what @Jay has suggested.
But, I really don't understand when you say,

Now I have dynamic strings containing
  system date and other variables.

The expected string always HAS to be hardcoded in order to unit test it. You should never ever use any calculation in unit test. You should set a scenario (date, any other vars) and then you know what your expected string will be. You will then hardcode it.
If you want to unit test the same method for different strings you can use TestCase attribute in nunit or RowTest attribute in MBUnit.

A: I resolved in this way:
class MyTestClass
{
    void test()
    {
        string message = _viewModel.DoWork();
        MyAssert.StringFormatConforms(message, Resource.MyResourceText);
    }
}

class MyAssert
{
    public static void StringFormatConforms(string stringToCheck, string format)
    {
        // replace {0}, {1} with .*
        string regex = "^" + Regex.Replace(format, "{[0-9]+}", ".*") + "$";
        bool conforms = Regex.IsMatch(stringToCheck, regex);
        if (!conforms)
            throw new AssertFailedException(String.Format("The string {0} does not conforms to format: {1}", stringToCheck, format));
    }
}

In this way I can check that my message "hi ric" must conform to "hi {0}"


text:
Q: Annihilators and principal ideals: a characterization for a property of an element Let $R$ be a commutative ring with identity and $a\in R$ has the property that for $b\in R$ if $\langle a\rangle\cap\langle b\rangle=\{0\}$, then $ann_R(a)+ann_R(b)=R$, where $ann_R(x) :=\{r\in R\mid rx=0 \}$ for $x\in R$. Is there any characterization for such an element?

A: This is just an extended comment:
If $Ra$ is essential in a direct summand of $R,$ then $a$ has this property.  To see this, fix some idempotent $e\in R$ such that $Ra$ is essential in $Re.$  Then if $b\in R$ satisfies $\langle a\rangle \cap \langle b\rangle=\{0\},$ we have $b\in R(1-e).$  Then $ann_R(a)+ann_R(b)\supseteq R(1-e)+Re=R.$
As a consequence, any element in an arbitrary direct product of chain rings and domains has this property.
In general, the equation $ann_R(a)+ann_R(b)=R$ is equivalent to the existence of some $s\in ann_R(a)$ such that $1-s\in ann_R(b).$ In other words, we just need some $s\in R$ such that $sa=0$ but $sb=b.$  This is a local condition, where $s$ might depend on $b.$
Let $F$ be a field, and consider the ring
$$
R=F[a,b_1,b_2,\ldots\, :\, ab_i=0,\, b_ib_j=b_i \text{ for }i<j].
$$
An easy argument, using degrees of monomials, shows that $R$ has only the trivial idempotents.  The set of those $b\in R$ with $\langle a\rangle \cap \langle b\rangle=\{0\}$ are the polynomials in $b_1,b_2,\ldots$ with zero constant term.  Given any such polynomial $b$, then for $n$ large enough we have $b_na=0$ and $b_nb=b,$ as wanted.  Thus, this element $a$ has the property you desire, in only a local manner.


text:
Q: Function App slot health check failing even when its running fine I have a script thats been used for a long time with no issues for checking the health status of a deployment slot
This is built into the deployment in dev ops
When I deploy the function via my release pipeline its fine, i.e. the slot starts and stays running with no errors
But the health check fails which in turn stops my deployment
The script is a standard ps template as shown below
param (
    [string]$URI,
    [string]$resultVarName,
    [string]$Method = 'GET',
    [string]$SuccessTextContent = 'Healthy',
    [string]$Retries = 1,
    [string]$SecondsDelay = 2,
    [string]$TimeoutSec = 120
)

Write-Host "$Method ""$URI"" Retries: $Retries, SecondsDelay $SecondsDelay, TimeoutSec $TimeoutSec";

Function Req {
    Param(
        [Parameter(Mandatory=$True)]
        [hashtable]$Params,
        [int]$Retries = 1,
        [int]$SecondsDelay = 2
    )

    $Params.Add('UserAgent', 'azagent powershell task')

    $method = $Params['Method']
    $url = $Params['Uri']

    $cmd = { Write-Host "$method $url..." -NoNewline; Invoke-WebRequest @Params }

    $retrycount = 0
    $completed = $false
    $response = $null

    while (-not $completed) {
        try {
            $response = Invoke-Command $cmd -ArgumentList $Params
            if ($response.StatusCode -ne 200) {
                throw "Expecting reponse code 200, was: $($response.StatusCode)"
            }
            $completed = $true
        } catch {
            Write-Output "$(Get-Date -Format G): Request to $url failed. $_"
            if ($retrycount -ge $Retries) {
                $completed = $true
                $totalCalls = $retrycount + 1
                Write-Warning "Request to $url failed $totalCalls times in total."
            } else {
                Write-Warning "Request to $url failed. Retrying in $SecondsDelay seconds."
                Start-Sleep $SecondsDelay
                $retrycount++
            }
        }
    }

    Write-Host "Status: ($($response.StatusCode))"
    return $response
}

$res = Req -Retries $Retries -SecondsDelay $SecondsDelay -Params @{ 'Method'=$Method;'Uri'=$URI;'TimeoutSec'=$TimeoutSec;'UseBasicParsing'=$true }

if($res.StatusCode -ne 200)
{
    echo "##vso[task.setvariable variable=$resultVarName]Unhealthy"
    Write-Error "Health check validation failure."
}
else
{
    echo "##vso[task.setvariable variable=$resultVarName]Healthy"
    Write-Host "Health check validation success."
}

Does anyone know how to fix this?
I get the error powershell-scripts\service-health-check.ps1 : [31;1mHealth check validation failure.


text:
Q: Invert a quasi isomorphism of chain complexes Is there an explicit way to invert a quasi-isomorphism of two chain complexes?
In case of homotopy algebras ($A_\infty$, $L_\infty$ ect.) there is an explicit way to invert any quasi isomorphism, if we are willing to work with infinity-morphisms. The inversion is then basically done by the homotopy transfer theorem.
Is something like this available for plain chain complexes?

A: Just think of $\Bbb Z/2 \Bbb Z$ and of $\Bbb Z \xrightarrow{\cdot 2} \Bbb Z$ as chain complexes, so that both only have non-vanishing homology in degree zero.
The the quotient map $\Bbb Z \to \Bbb Z/2 \Bbb Z$ induces a quasi isomorphism, but obviously there is no nontrivial map in the other direction.
Though what you could do is find some kind of projective resolution of the chain complexes and then the induced map you will get should have a quasi inverse. You could look for model categories(the projective model structure on chain complexes) cofibrant replacement and the Whitehead theorem.


text:
Q: NetBeans IDE 8.2 - no compatible JDK was found I've been trying to install NetBeans,but i get an error every time because netbeans can't find the folder with jdk.Even when i explicitly tell the netbeans where the jdk is installed,i am still getting the same error.I've checked all my system variables and they are fine - at least i think so.What's the problem?
Pic1(Netbeans installation) :

Pic2(Netbeans installation) :

Pic3(System variables) :

Pic4(Path variable) :

Pic5:

Pic6:

A: NetBeans 8.2 only supports Java 8.
But in order to run NetBeans you need a JDK, a JRE is not sufficient.
You need to remove the JRE and install the Java 8 JDK instead.


text:
Q: How to detect page overflow I know you can set the overflow property in CSS to determine what the page does on overflow, but I was wondering if there was any way to listen for page overflow using pure javascript or jQuery?

A: You can check by comparing offsetHeight and scrollHeight
var div = document.getElementById('main');
console.log(div.scrollHeight);
console.log(div.offsetHeight);

The element should have overflow: auto/scroll css property.
Working Fiddle    (add content in the div to check)

A: You can do it with jQuery
$("element").css("overflow");

or
$("element").css("overflow-x");

I recommend you the 2nd example, because it should work in most browsers.


text:
Q: The option to change mouse cursor in gnome tweak tool has become permanently inactive. How to make it active and functioning again? I tried to change the codes in /usr/share/icons/default/index.theme and i found that may be i deleted it somehow. is it the reason behind it? if so how can i restore it and make the option in gnome tweak tool active again?

A: I checked the packages for the directory /usr/share/icons, then I reinstalled the package x-cursor-themes by running
sudo apt install --reinstall xcursor-themes

and I got the file back.


text:
Q: Google App Maker How to Allow access to user to your App Instance who don't have Gsuite How do I allow a normal gmail user access to use on the Google App Maker apps I've made. Is this possible ?
If you have to have a separate gsuite account for each user using the app then how viable is it ?
Anyway any help would be much appreciated.
Many thanks
Samuel

A: I know this is an old question, but I just spent too much time to get the answer.
So here there is google's answer:

Can I share my apps with users outside my organization?
  No. Only users in your G Suite organization can use your app. For some apps,
  you can work around this limitation by using Google Forms to collect
  user input in Google Sheets, then import the data from the sheet.

I don't think that the form "hack" is going to help a lot of people, but it's nice they mentioned it.

A: As I understand it, you do need a GSuite business account ($10/month/user) to use an App Maker app.
I hope that Google is not primarily doing that to make money, but to initially have a smaller number of users and apps, and use the smaller user base to shake out issues and later open it up for the general public (ie for the Firebase platform). I don't see why this would be impossible or even difficult, but of course, hope is not a strategy.


text:
Q: How to find index of form from FormArray that contain error in angular? I am working with one complex form in angular and I need some help. let me explain my scenario in detail.
I have one formArray like this :
let slides = new FormArray([]);
slides.push(getNewSlide())
slides.push(getNewSlide())
slides.push(getNewSlide())
slides.push(getNewSlide())

function getNewSlide() {
  return new FormGroup({
    name: new FormControl("", [Validators.required]),
    image: new FormControl("", [Validators.required])
  })
}

Above form will look like this :
slides = [
  { name: "ram", image: "a.png" },
  { name: "shyam", image: "b.png" },
  { name: "", image: "c.png" },             <== here is error. name is required so index should be 2
  { name: "ghanshyam", image: "d.png" },
]

I want to find index of the form from FormArray that contain any error, But I don't know how to do that. One important thing is that, this form can be nested. like one FormGroup can contain another FormGroup or FormArray
anyone know about it to deep scan whole form and find index of first error place (index of form), then please answer here. I will appreciate your ideas.
Thank you.

A: You could loop through the formArray controls and check for errors. Like this:
findFirstInvalidControlInFormArray() {
    const index = (this.slides as FormArray).controls.findIndex(
      (control) => control.invalid
    );
    console.log(index);
  }

If the index is -1 it means, all controls are valid.


text:
Q: How can I stop the submit button from stacking under the text field on a bootstrap form? http://codepen.io/anon/pen/WQQpyg
On a larger screen this isn't a problem, but when I reduce the browser window, the submit button moves underneath the text field.
This is causing a problem when I try to add a background color to the form with css. Does anyone know how to prevent this?

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

      <form class="form-inline" role="form">

          <input type="email" class="form-control" id="email" placeholder="Enter Email Address">

        <button type="submit" class="btn btn-default">Submit</button>
      </form>

A: You could use a horizontal form with column sizing.

@import url("https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css");

.less-padding {
  padding: 0 2px;
}

      <form class="form-horizontal" role="form">

            <input type="email" class="form-control" id="email" placeholder="Enter Email Address">

            <button type="submit" class="btn btn-default">Submit</button>

      </form>

Another solution was mentioned.
Here is how it goes:

@import url("https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css");

@media (max-width: 768px) {
  .form-group {
    display: inline-block;
    vertical-align: top;
  }
}
<form class="form-inline" role="form">

    <input type="email" class="form-control" id="email" placeholder="Enter Email Address">

  <button type="submit" class="btn btn-default">Submit</button>
</form>

A: Is this what you are looking for? https://jsfiddle.net/DIRTY_SMITH/2zkwxm97/
Added col-xs-4 to

A: class .form-inline only applies to forms within viewports that are at least 768px wide.
Check Bootstrap Doc here
To achieve what you want, you shouldn't use it. You could do something like this:

  <form>

      <input type="email" class="form-control" id="email" placeholder="Enter Email Address">

    <button type="submit" class="btn btn-default">Submit</button>
  </form>

Check this demo

A: Looks like it uses a media query like this:
@media (min-width: 768px)

And anything narrower than that, the form-group will change to display:block instead of inline-block. So maybe override that back to inline-block, but not sure that is best way to solve your issue. Maybe let it stack like that and find another way to fix the background color issue.


text:
Q: Cannot shuffle list in Python This is my list:
biglist = [ {'title':'U2','link':'u2.com'}, {'title':'beatles','link':'beatles.com'} ]
print random.shuffle(biglist)

that doesn't work!  It returns none.

A: random.shuffle shuffles the list, it does not return a new list. So check biglist, not the result of random.shuffle.
Documentation for the random module: http://docs.python.org/library/random.html


text:
Q: Powershell cannot find file Consider the following PowerShell code:
IF(Test-Path -Path "C:\Windows\System32\File123")
{Remove-Item -Force -Path "C:\Windows\System32\File123"}

If the code was executed in the x86 PowerShell Console, the following error is raised Get-ChildItem : Cannot find path 'C:\Windows\System32\File123' because it does not exist.
However, when the code is run in an x64 Powershell console, the command behaves as expected.
Is there any scriptable method for working around this problem?

A: A hacky workaround would be to detect that the script is run with PowerShell x86 and invoke it with a x64 PowerShell by putting this snippet at the start of your script:
if ($env:Processor_Architecture -eq "x86")
{
    &"$env:windir\sysnative\WindowsPowerShell\v1.0\powershell.exe" -noprofile -file $myinvocation.Mycommand.path -executionpolicy bypass
    exit
}

A: Thanks for the great replies, I had some time to do a little searching and came up with the following.  I'm using Powershell v4.  You can put anything after the ps64 alias, a script for example or a function.  Credit for the alias goes to this page.  Also thanks to https://stackoverflow.com/a/19835164/4317867 for the [ScriptBlock]::Create("") tip, before doing this the Script block would not expand $server properly.
The goal of this is to remove Powershell's scheduled task/job file to allow it to be re-created.
Param(
 [Parameter(Mandatory=$true,
  HelpMessage="ServerName goes here")]
[string]$server,
 [Parameter(Mandatory=$true,
  HelpMessage="Enter a Date/Time 07-28-15 16:00 For July 28th, 2015 at 4:00 PM")]
  [ValidatePattern('\d{2}-\d{2}-\d{2}\s\d{2}[:]\d{2}')]
$date)

if($env:PROCESSOR_ARCHITECTURE -eq "x86")
{
 set-alias ps64 "$env:windir\sysnative\WindowsPowerShell\v1.0\powershell.exe"
 ps64 -command "IF(Test-Path -Path C:\Windows\System32\Tasks\Microsoft\Windows\PowerShell\ScheduledJobs\RebootOnce2){Remove-Item -Force -Path C:\Windows\System32\Tasks\Microsoft\Windows\PowerShell\ScheduledJobs\RebootOnce2}" #End 64 bit powershell.
}
Else{
 Get-ScheduledJob | Unregister-ScheduledJob
}
$user = Get-Credential -UserName $env:USERNAME -Message "UserName/password for scheduled Reboot"
$trigger = New-JobTrigger -once -at $date
$script = [ScriptBlock]::Create("D:\Scripts\Scheduled-Reboot-Single.ps1 -server $server | Out-File -Force \\LogServer\d$\scripts\$server-Reboot.log")
Register-ScheduledJob -Name RebootOnce2 -Credential $user -Trigger $trigger -ScriptBlock $script


text: Q: Получаю от телеграмм бота иероглифы вместо русских символов из JSON Пока бот хостился на моём ПК на винде всё было нормально но когда я закинул его на виртуальный сервер на ubuntu 18.04 то из базы данных которая хранится в JSON файле я получаю какую то чушь хотя я через файлзиллу проверил базу и там всё нормально и русский текст который прописан в самом коде, бот пишет нормально но вот символы из файла преобразуются в каракули вот такого вида:


text:
Q: '||' operators to be used between two enums in a switch statement I want to check if a function returns either of two enum values, each of the same enumeration type.
For simplicity's sake, I attempted to create a case as follows:
case EnumerationTypeExample.TypeA || EnumerationTypeExample.TypeB:

Unfortunately, this does not please C#, which says I cannot use an '||' operator despite them being of the same type; strange. Might there be a way this could be done otherwise? An if statement perhaps might work and I may retreat to that, however, I would much rather use a switch statement if possible.

A: A case statement must be constants, not a computation.
However you can use fall through in this case:
switch (something)
{
    case EnumerationTypeExample.TypeA:
    case EnumerationTypeExample.TypeB:
    {
        DoSomething();
        break;
    }
}

Now the code will run in both situations.


text:
Q: How to Fix Window Open Function i have code
aff_url = $(this).attr('data-aff-url');
current_url = $(this).attr('href');
window.open( aff_url, '_self');
window.open( current_url, '_blank');

but the window open function is not working chrome the popup blocker is blocking window open anyone can help me to make it work ?


text:
Q: Is there any way I can use mapping to avoid a SOQL Query here? For Trigger.New in an order trigger, I use the order's accountId field to query for 3 fields on the related account. As follows...
    for(Order o : Trigger.New)
    {
        Id theID = o.AccountId;
        Account thisAccount = [SELECT Household_Total__c, Household_Children__c FROM Account WHERE ID= :theId];

However, this trigger goes off with a process I'm developing called "Mass Order Create", and as you can tell from the name, I'm making a lot of orders at once. So, this one query in Trigger.new for the account with the given Order's accountID field is putting me over governor limits.
Is there any way to get the related account's fields without querying? If not, what might somebody suggest doing instead?
I found this somewhere that gets fields related to Account, but I don't think it's quite pulling information from a specific record, or if so, the person who provided the code left little explanation, so I don't know how to use it if it's there. (o is trigger.New)
        Id theID = o.AccountId;

        Schema.SObjectType token = theID.getSObjectType();
        Schema.DescribeSObjectResult dr = token.getDescribe();
        sObjFieldName = dr.Fields.getMap().keyset();

A: Yes, of course. The first step is to gather a collection of the Account ids.
Set<Id> accountIds = new Set<Id>();
for (Order order : trigger.new) accountIds.add(order.AccountId);

The next step is to query the Account records and put them in a Map:
Map<Id, Account> accounts = new Map<Id, Account>([
    SELECT Fields FROM Account WHERE Id IN :accountIds
]);

The last step is to retrieve them in your loop (without an additional query per):
for (Order order : trigger.new)
{
    Account thisAccount = accounts.get(order.AccountId);
    // do other stuff
}


text:
Q: I am unable to have a connection from my angular frontend to my C# backend. What is the reason for this? I'm writing an angular application. The main problem I have right now is that when I have to connect my frontend application with my backend server that it's unable to do so and that I get error 0. I have also uploaded another application that returns a similar error. Given that error 0 indicates that the problem could be literally anything I would like to know what causes the problem.
As far as I know the problem can't be there because of my backend not properly working. That's because my application runs with Swagger and Swagger doesn't have any notable problem with returning code that has been parsed in JSON.
Thus it must be my frontend. However that's also unlikely, because it works well until it has to connect to the backend. (In my code, that would be until class authentication.service.ts line 64 for checking the username and until authentication.service.ts line 40 for registering a user).
I've already asked my Norton antivirus to stop doing anything to see if my application is not working due to my antivirus, but it turns out that my antivirus wasn't doing anything to stop my frontend from connecting to my backend.
If some code is running wrong it has to be code in this method:
checkUserNameAvailability = (username: string): Observable<boolean> => {
    //    console.log(username);
    return this.http.get<boolean>(
      `${environment.apiUrl}/User/checkusername`,
      {
        params: { username }
      }
    ).pipe(catchError(err => {
      console.error(err);
      return of(null);
    }))
  }

This is code in authentication.service.ts from line 62 until line 73.
I'll link to my github repositories below:
Angular frontend: https://github.com/GuylianBollon/AngularFrontendWebIV
C# backend: https://github.com/GuylianBollon/CbackendWebIV
Here's another thing I found:
After I connect my angular frontend to my C# backend and directly after it check the connection on the command prompt the following is generated. (Note: 44392 is the SSL Port of my C# backend).
C:\Users\Hp>netstat -a -n | findstr 44392
  TCP    0.0.0.0:44392          0.0.0.0:0              LISTENING
  TCP    [::]:44392             [::]:0                 LISTENING
  TCP    [::1]:44392            [::1]:53942            ESTABLISHED
  TCP    [::1]:53942            [::1]:44392            ESTABLISHED

After I wait for about 1 minute the following is generated:
C:\Users\Hp>netstat -a -n | findstr 44392
  TCP    0.0.0.0:44392          0.0.0.0:0              LISTENING
  TCP    [::]:44392             [::]:0                 LISTENING
  TCP    [::1]:53942            [::1]:44392            TIME_WAIT

Not sure if this is normal or not, but I thought this was interesting.
Here's also the json of my proxy.conf.json file:
{
  "/api": {
    "target": {
      "host": "localhost",
      "protocol": "https",
      "port": 44392
    },
    "changeOrigin": true,
    "secure": false,
    "logLevel": "warn"
  }
}

When I open the browser after I connect my angular frontend to my C# backend, write something on the username field and wait 2 minutes the following is generated:
authentication.service.ts:70
1.  HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "/api/User/checkusername", ok: false, …}
1.  error: ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 0, total: 0, type: "error", …}
2.  headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, headers: Map(0)}
3.  message: "Http failure response for /api/User/checkusername: 0 Unknown Error"
4.  name: "HttpErrorResponse"
5.  ok: false
6.  status: 0
7.  statusText: "Unknown Error"
8.  url: "/api/User/checkusername"
9.  proto: HttpResponseBase
api/User/checkusername?username=abc:1
Failed to load resource: net::ERR_EMPTY_RESPONSE

A: There is a typo in your proxy configuration file, a fixed version:
{
  "/api": {
    "target": {
      "host": "localhost",
      "protocol": "https:",
      "port": 44392
    },
    "changeOrigin": true,
    "secure": false,
    "logLevel": "warn"
  }
}

Notice the colon (:) after https:, which is missing in your version.