text:
Q: How to usage Obx() with getx in flutter? On my UI screen, I have 2 textfields in a column. If textFormFieldEntr is empty, hide textFormFiel. If there is a value in the textFormFieldEntr, let the other textfield be visible. After I set the bool active variable to false in the Controller class, I checked the value in the textFormFieldEntr in the showText class. I'm wrong using obx on the UI screen. The textfields are listed in the _formTextField method. Can you answer by explaining the correct obx usage on the code I shared?
class WordController extends GetxController {
  TextEditingController controllerInput1 = TextEditingController();
  TextEditingController controllerInput2 = TextEditingController();
  bool active = false.obs();

  final translator = GoogleTranslator();
  RxList data = [].obs;

  @override
  void onInit() {
    getir();
    super.onInit();
  }

  void showText() {
    if (!controllerInput1.text.isEmpty) {
      active = true;
    }
  }

  ekle(Word word) async {
    var val = await WordRepo().add(word);
    showDilog("Kayıt Başarılı");
    update();
    return val;
  }

  updateWord(Word word) async {
    var val = await WordRepo().update(word);
    showDilog("Kayıt Başarılı");
    return val;
  }

  deleteWord(int? id) async {
    var val = await WordRepo().deleteById(id!);
    return val;
  }

  getir() async {
    //here read all data from database
    data.value = await WordRepo().getAll();
    print(data);
    return data;
  }

  translateLanguage(String newValue) async {
    if (newValue == null || newValue.length == 0) {
      return;
    }
    List list = ["I", "i"];
    if (newValue.length == 1 && !list.contains(newValue)) {
      return;
    }

    var translate = await translator.translate(newValue, from: 'en', to: 'tr');

    controllerInput2.text = translate.toString();
    //addNote();
    return translate;
  }

  showDilog(String message) {
    Get.defaultDialog(title: "Bilgi", middleText: message);
  }

  addNote() async {
    var word =
    Word(wordEn: controllerInput1.text, wordTr: controllerInput2.text);
    await ekle(word);
    getir();
    clear();
  }

  clear() {
    controllerInput2.clear();
    controllerInput1.clear();
  }

  updateNote() async {
    var word =
    Word(wordEn: controllerInput1.text, wordTr: controllerInput2.text);
    await updateWord(word);
    await getir();
    update();
  }
}

UI:
class MainPage extends StatelessWidget {
  bool _active=false.obs();
  String _firstLanguage = "English";
  String _secondLanguage = "Turkish";
  WordController controller = Get.put(WordController());
  final _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    controller.getir();
    return Scaffold(
      drawer: _drawer,
      backgroundColor: Colors.blueAccent,
      appBar: _appbar,
      body: _bodyScaffold,
      floatingActionButton: _floattingActionButton,
    );
  }

  SingleChildScrollView get _bodyScaffold {
    return SingleChildScrollView(
      child: Column(
        children: [
          chooseLanguage,
          translateTextView,
        ],
      ),
    );
  }

  AppBar get _appbar {
    return AppBar(
      backgroundColor: Colors.blueAccent,
      centerTitle: true,
      title: Text("TRANSLATE"),
      elevation: 0.0,
    );
  }

  get chooseLanguage => Container(
        height: 55.0,
        decoration: buildBoxDecoration,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            firstChooseLanguage,
            changeLanguageButton,
            secondChooseLanguage,
          ],
        ),
      );

  get buildBoxDecoration {
    return BoxDecoration(
      color: Colors.white,
      border: Border(
        bottom: BorderSide(
          width: 3.5,
          color: Colors.grey,
        ),
      ),
    );
  }

  refreshList() {
    controller.getir();
  }

  get changeLanguageButton {
    return Material(
      color: Colors.white,
      child: IconButton(
        icon: Icon(
          Icons.wifi_protected_setup_rounded,
          color: Colors.indigo,
          size: 30.0,
        ),
        onPressed: () {},
      ),
    );
  }

  get secondChooseLanguage {
    return Expanded(
      child: Material(
        color: Colors.white,
        child: InkWell(
          onTap: () {},
          child: Center(
            child: Text(
              this._secondLanguage,
              style: TextStyle(
                color: Colors.blue[600],
                fontSize: 22.0,
              ),
            ),
          ),
        ),
      ),
    );
  }

  get firstChooseLanguage {
    return Expanded(
      child: Material(
        color: Colors.white,
        child: InkWell(
          onTap: () {},
          child: Center(
            child: Text(
              this._firstLanguage,
              style: TextStyle(
                color: Colors.blue[600],
                fontSize: 22.0,
              ),
            ),
          ),
        ),
      ),
    );
  }

  get translateTextView => Column(
        children: [
          Card(
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.all(Radius.circular(8.0)),
            ),
            margin: EdgeInsets.only(left: 2.0, right: 2.0, top: 2.0),
            child: _formTextField,
          ),
          Container(
            height: Get.height/1.6,
            child: Obx(() {
              return ListView.builder(
                itemCount: controller.data.length,
                itemBuilder: (context, index) {
                  return Card(
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.all(Radius.circular(5.0)),
                    ),
                    margin: EdgeInsets.only(left: 2.0, right: 2.0, top: 0.8),
                    child: Container(
                      color: Colors.white30,
                      height: 70.0,
                      padding:
                          EdgeInsets.only(left: 8.0, top: 8.0, bottom: 8.0),
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisAlignment: MainAxisAlignment.spaceAround,
                            children: [
                              firstText(controller.data, index),
                              secondText(controller.data, index),
                            ],
                          ),
                          historyIconbutton,
                        ],
                      ),
                    ),
                  );
                },
              );
            }),
          )
        ],
      );

  get _formTextField {
    return Form(
      key: _formKey,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Container(
            color: Colors.white30,
            height: 120.0,
            padding: EdgeInsets.only(left: 16.0, top: 8.0, bottom: 8.0),
            child: Row(

              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                textFormFieldEntr,
                favoriIconButton,
              ],
            ),
          ),
          textFormField //burası kapandı
        ],
      ),
    );
  }

  get textFormFieldEntr {
    return Flexible(
      child: Container(
        child: TextFormField(
          onTap: () {
            showMaterialBanner();
          },
          // onChanged: (text) {
          //   controller.translateLanguage(text);
          // },
          controller: controller.controllerInput1,
          maxLines: 6,
          validator: (controllerInput1) {
            if (controllerInput1!.isEmpty) {
              return "lütfen bir değer giriniz";
            } else if (controllerInput1.length > 22) {
              return "en fazla 22 karakter girebilirsiniz";
            }
            return null;
          },
          decoration: InputDecoration(
            hintText: "Enter",
            contentPadding: const EdgeInsets.symmetric(vertical: 5.0),
          ),
        ),
      ),
    );
  }

  void showMaterialBanner() {
    ScaffoldMessenger.of(Get.context!).showMaterialBanner(MaterialBanner(
        backgroundColor: Colors.red,
        content: Padding(
          padding: const EdgeInsets.only(top: 30.0),
          child: Column(
            children: [
              TextFormField(
                controller: controller.controllerInput1,
                maxLines: 6,

                onChanged: (text) {
                  controller.translateLanguage(text);
                  controller.showText();
                },
                validator: (controllerInput2) {
                  if (controllerInput2!.length > 22) {
                    return "en fazla 22 karakter girebilirsiniz";
                  }
                  return null;
                },
                decoration: InputDecoration(
                  suffixIcon: IconButton(onPressed: () {
                    FocusScope.of(Get.context!).unfocus();
                    closeBanner();
                  }, icon: Icon(Icons.clear),),
                  contentPadding: const EdgeInsets.symmetric(vertical: 5.0),
                ),
              ),
              SizedBox(height: 80.0),
              TextFormField(
                controller: controller.controllerInput2,
                maxLines: 6,
                validator: (controllerInput2) {
                  if (controllerInput2!.length > 22) {
                    return "en fazla 22 karakter girebilirsiniz";
                  }
                  return null;
                },
                decoration: InputDecoration(
                  contentPadding: const EdgeInsets.symmetric(vertical: 5.0),
                ),
              ),
            ],
          ),
        ),
        actions: [
          IconButton(
            onPressed: () {

              closeBanner();
            },
            icon: Icon(
              Icons.arrow_forward_outlined,
              color: Colors.indigo,
              size: 36,
            ),
          ),
        ]));
  }

  void closeBanner() {
    ScaffoldMessenger.of(Get.context!).hideCurrentMaterialBanner();
  }

// }  controller.controllerInput1.text==""?_active=false: _active=true;

  get textFormField {
    return Visibility(
      visible: controller.active,
      child: Container(
        color: Colors.white30,
        height: 120.0,
        padding: EdgeInsets.only(left: 16.0, right: 42.0, top: 8.0, bottom: 8.0),
        child: Container(
          child: TextFormField(
            controller: controller.controllerInput2,
            maxLines: 6,
            validator: (controllerInput2) {
              if (controllerInput2!.length > 22) {
                return "en fazla 22 karakter girebilirsiniz";
              }
              return null;
            },
            decoration: InputDecoration(
              contentPadding: const EdgeInsets.symmetric(vertical: 5.0),
            ),
          ),
        ),
      ),
    );
  }

  FutureBuilder<dynamic> get historyWordList {
    return FutureBuilder(
      future: controller.getir(),
      builder: (context, AsyncSnapshot snapShot) {
        if (snapShot.hasData) {
          var wordList = snapShot.data;
          return ListView.builder(
            itemCount: wordList.length,
            itemBuilder: (context, index) {
              return Card(
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.all(Radius.circular(5.0)),
                ),
                margin: EdgeInsets.only(left: 8.0, right: 8.0, top: 0.8),
                child: Container(
                  color: Colors.white30,
                  height: 70.0,
                  padding: EdgeInsets.only(left: 8.0, top: 8.0, bottom: 8.0),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.spaceAround,
                        children: [
                          firstText(wordList, index),
                          secondText(wordList, index),
                        ],
                      ),
                      historyIconbutton,
                    ],
                  ),
                ),
              );
            },
          );
        } else {
          return Center();
        }
      },
    );
  }

  IconButton get historyIconbutton {
    return IconButton(
      onPressed: () {},
      icon: Icon(Icons.history),
      iconSize: 30.0,
    );
  }

  Text firstText(wordList, int index) {
    return Text(
      "İngilizce: ${wordList[index].wordEn ?? ""}",
      style: TextStyle(
        fontWeight: FontWeight.w600,
      ),
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
    );
  }

  Text secondText(wordList, int index) {
    return Text(
      "Türkçe: ${wordList[index].wordTr ?? ""}",
      style: TextStyle(
        fontWeight: FontWeight.w400,
      ),
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
    );
  }

  get favoriIconButton {
    return IconButton(
      alignment: Alignment.topRight,
      onPressed: () async {
        bool validatorKontrol = _formKey.currentState!.validate();
        if (validatorKontrol) {
          String val1 = controller.controllerInput1.text;
          String val2 = controller.controllerInput2.text;
          print("$val1 $val2");
          await controller.addNote();
          await refreshList();
        }
        await Obx(() => textFormField(
              controller: controller.controllerInput2,
            ));
        await Obx(() => textFormField(
              controller: controller.controllerInput1,
            ));
      },
      icon: Icon(
        Icons.forward,
        color: Colors.blueGrey,
        size: 36.0,
      ),
    );
  }

  FloatingActionButton get _floattingActionButton {
    return FloatingActionButton(
      onPressed: () {
        Get.to(WordListPage());
      },
      child: Icon(
        Icons.app_registration,
        size: 30,
      ),
    );
  }

  Drawer get _drawer {
    return Drawer(
      child: ListView(
        // Important: Remove any padding from the ListView.
        padding: EdgeInsets.zero,
        children: <Widget>[
          userAccountsDrawerHeader,
          drawerFavorilerim,
          drawersettings,
          drawerContacts,
        ],
      ),
    );
  }

  ListTile get drawerContacts {
    return ListTile(
      leading: Icon(Icons.contacts),
      title: Text("Contact Us"),
      onTap: () {
        Get.back();
      },
    );
  }

  ListTile get drawersettings {
    return ListTile(
      leading: Icon(Icons.settings),
      title: Text("Settings"),
      onTap: () {
        Get.back();
      },
    );
  }

  ListTile get drawerFavorilerim {
    return ListTile(
      leading: Icon(
        Icons.star,
        color: Colors.yellow,
      ),
      title: Text("Favorilerim"),
      onTap: () {
        Get.to(FavoriListPage());
      },
    );
  }

  UserAccountsDrawerHeader get userAccountsDrawerHeader {
    return UserAccountsDrawerHeader(
      accountName: Text("UserName"),
      accountEmail: Text("E-mail"),
      currentAccountPicture: CircleAvatar(
        backgroundColor: Colors.grey,
        child: Text(
          "",
          style: TextStyle(fontSize: 40.0),
        ),
      ),
    );
  }
}

A: You can simple do it like this
class ControllerSample extends GetxController{

 final active = false.obs

 functionPass(){
   active(!active.value);
  }

}

on page
 final sampleController = Get.put(ControllerSample());

 Obx(
 ()=> Form(
   key: yourkeyState,
   child: Column(
     children: [
       TextFormField(
        //some other needed
        //put the function on onChanged
        onChanged:(value){
              if(value.isEmpty){
                sampleController.functionPass();
              }else{
              sampleController.functionPass();
         }
             }
        ),
       Visibility(
        visible: sampleController.active.value,
        child: TextFormField(
          //some other info
          )
        ),
     ]
   )
  )
)


text:
Q: How does a router setup as a dumb switch work? If you disable DHCP on a router ("router A") and connect an ethernet cable to one of its ports (from another router, "router b"), router A becomes a dumb switch.
But how does this work? How does the router now know where to send its packets?

A: If you only use the switch ports and disable DHCP, no TCP/IP packets will be sent by clients to the address of the router.
You can think of your router as containing several separated devices that operate somewhat independently

A typical SOHO "router" incoroporates a 4-port ethernet switch. This works in the usual way a dumb ethernet switch works even when all the other parts of the box are sitting idle with nothing to do.
A router only does routing if it receives an ethernet packet that has a destination MAC address matching the router's MAC address and where the ethernet packet encapsulates an IP-packet with an off-LAN IP-address.
Two PCs communicating with each other via the ethernet-switch part will only create ethernet packets with each-others MAC address as the destination, not with the routers MAC address as destination.

A: If the router is now acting as switch, think of it like a surge protector. You can plug multiple devices needing power into it, but it still only draws power from 1 source.
Well a switch is like that, lets assume your router b was the modem from isp, well unless its strictly a modem and not a modem/router combo box, it will have 1 ethernet port. Also lets assume you don't need routing functions such as NAT as all you want to do is just connect them to the internet but don't care about having a device helping you communicate with the other devices. A switch has a bunch of ethernet ports to connect the systems to it, and then 1 ethernet port, to connect a cable to the modem.
Now you have effectively multiplied the modems ethernet port to more than 1. That is the function of the switch, and the reason the switch will work, has to do with how devices on any network communicate with each other without knowing each other. There is a reason why all network interfaces have Mac addresses. This Mac address is very useful in getting packets to the right device. So instead of router A doing routing, Router B does the routing instead as all router A is doing, is just forwarding the packets according to destination MAC.
Also to clarify, just because you disable DHCP, doesn't mean it becomes a switch automatically therefore it can still do routing functions without DHCP. All that means, is now any device connected to that router, will not obtain IP Address configuration automatically and would need to input those configurations manually on the systems connected to Router A.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to undo the merging of my remote branch into master I just start learning gitlab and git.
I merged my personal work branch into the master by mistake. I want to undo this action, what should I do? Thank you so much.


text:
Q: how to automatically add rows in flask html table I'd like to automatically add a row for everytime a new "to-do" item is added.
Here's how it currently looks like,

Here's how I want it to look like - under the "CARD_1"

I have an idea of where I am going wrong with this, from my code we can see that the for loop re-iterates under one row. I'd like to have it add a row automatically whenver my Trello card is updated.
my code:

To-do list

                        Agenda
                        Not Started
                        In Progress
                        Complete

                            {%for item in todo_items%}
                            {{item.name}}
                            <input type="checkbox" id="id" name="Tick" value="{{item.id}}">
                            <input type="checkbox" id="id" name="Tick" value="{{item.id}}">
                            <input type="checkbox" id="id" name="Tick" value="{{item.id}}">
                            {%endfor%}

                        {% for row in todo_items%}

                            {%for rwo in cell%}
                            {{cell}}
                            {%endfor%}

                        {%endfor%}

A: You can move the "tr" tag inside the loop:

   {%for item in todo_items%}

        {{item.name}}
        <input type="checkbox" id="id" name="Tick" value="{{item.id}}">
        <input type="checkbox" id="id" name="Tick" value="{{item.id}}">
        <input type="checkbox" id="id" name="Tick" value="{{item.id}}">

    {%endfor%}

as it's "tr" that defines new table row.
P.s. what are you trying to achieve with this?
{% for row in todo_items%}

    {%for rwo in cell%}
      {{cell}}
    {%endfor%}

{%endfor%}


text:
Q: How to sample a pixel from a framebuffer texture in OpenGL? I am creating a color picker OpenGL application for images with ImGUI. I have managed to load an image by loading the image into a glTexImage2D and using ImGUI::Image().
Now I would like to implement a method, which can determine the color of the pixel in case of a left mouse click.
Here is the method I loading the texture, then assigning it to a framebuffer:
bool LoadTextureFromFile(const char *filename, GLuint *out_texture, int *out_width, int *out_height,ImVec2 mousePosition ) {

    // Reading the image into a GL_TEXTURE_2D
    int image_width = 0;
    int image_height = 0;
    unsigned char *image_data = stbi_load(filename, &image_width, &image_height, NULL, 4);
    if (image_data == NULL)
        return false;

    GLuint image_texture;
    glGenTextures(1, &image_texture);
    glBindTexture(GL_TEXTURE_2D, image_texture);

    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image_width, image_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image_data);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    stbi_image_free(image_data);
    glBindTexture(GL_TEXTURE_2D, 0);

    *out_texture = image_texture;
    *out_width = image_width;
    *out_height = image_height;

    // Assigning texture to Frame Buffer
    unsigned int fbo;
    glGenFramebuffers(1, &fbo);
    glBindFramebuffer(GL_FRAMEBUFFER, fbo);
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, image_texture, 0); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, image_texture, 0);

    if(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE){
        std::cout<< "Frame buffer is done."<< std::endl;
    }
    return true;
}

Unfortunately, the above code results in a completely blank screen. I guess, there is something I missed during setting the framebuffer.
Here is the method, where I would like to sample the framebuffer texture by using the mouse coordinates:
    void readPixelFromImage(ImVec2 mousePosition) {
        unsigned char pixels[4];
        glReadBuffer(GL_COLOR_ATTACHMENT0);
        glReadPixels(GLint(mousePosition.x), GLint(mousePosition.y), 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, pixels);

        std::cout << "r: " << static_cast<int>(pixels[0]) << '\n';
        std::cout << "g: " << static_cast<int>(pixels[1]) << '\n';
        std::cout << "b: " << static_cast<int>(pixels[2]) << '\n';
        std::cout << "a: " << static_cast<int>(pixels[3]) << '\n' << std::endl;
    }

Any help is appreciated!

A: There is indeed something missing in your code:
You set up a new Framebuffer that contains just a single texture buffer. This is okay, so the glCheckFramebufferStatus equals GL_FRAMEBUFFER_COMPLETE. But there is no render buffer attached to your framebuffer. If you want your image rendered on screen, you should use the default framebuffer. This framebuffer is created from your GL context.
However, the documentation says: Default framebuffers cannot change their buffer attachments, [...] https://www.khronos.org/opengl/wiki/Framebuffer. So attaching a texture or renderbuffer to the default FB is certainly not possible. You could, however, generate a new FB as you did, render to it, and finally render the outcome (or blit the buffers) to your default FB. Maybe a good starting point for this technique is https://learnopengl.com/Advanced-Lighting/Deferred-Shading
Moreover, if you intend to just read back rendered values from your GPU, it is more performant to use a renderbuffer instead of a texture. You can even have multiple renderbuffers attached to your framebuffer (as in deferred shading). Example: you could use a second renderbuffer to render an object/instance id (so, the renderbuffer will be single channel integer), and your first renderbuffer will be used for normal drawing. Reading the second renderbuffer with glReadPixels you can directly read which instance was drawn at e.g. the mouse position. This way, you can enable mouse picking very efficiently.


text:
Q: HTML5 manifest and chrome I am seeing this error in my console for chrome.
Application Cache Error event: Failed to commit new cache to storage, would exceed quota

it means what it seems to mean right?  That my app is trying to cache too much data?
Is there anything that can be done about it?
Same site works in FF no issues.

A: The error can also occur when your system drive is running low on disk space, so freeing up disk space can resolve this in this situation.

A: if you just want to change the size of your cache, start chrome with "--disk-cache-size=N".
If you want to see whats in your cache, just type about:cache or about:appcache-internals in the Omnibar.
For a reference file: DOMApplicationCache Class Reference or google "A Beginner's Guide to Using the Application Cache" (I may not post more links, I'm sorry)


text:
Q: How to loop through multiple Azure subscriptions on Azure Pipelines Yaml? I have a yaml pipeline that's simply used to run a script on a subscription. I use the AzurePowerShell@5 task for this.
The problem is I have 22 other subscriptions I need to run the same script on using the exact same script parameters. Only thing different will be the target azureSubscription field. Instead of having 22 blocks of the same task with different subscription names, is there a faster way? Can I throw the names of the 22 subscriptions in an array in the variables section and loop through them somehow? Please advise
stages:

- stage: Deploy
  displayName: 'Deploy Pipeline - Access Worker'

  jobs:
  - job: AccessWorker
    displayName: 'Access Worker'

    steps:
    - download: current
      artifact: 'AccessWorker'

    - task: AzurePowerShell@5
      displayName: 'Access Worker'
      inputs:
        azurePowerShellVersion: LatestVersion
        azureSubscription: 'My Azure Subscription 1'
        scriptPath: '$(Pipeline.Workspace)/AccessWorker/.src/Access_Worker/access_worker.ps1'
        scriptArguments: >
          -RoleDefinitionName 'Reader'
          -TagName 'Owner'

    - task: AzurePowerShell@5
      displayName: 'Access Worker'
      inputs:
        azurePowerShellVersion: LatestVersion
        azureSubscription: 'My Azure Subscription 2'
        scriptPath: '$(Pipeline.Workspace)/AccessWorker/.src/Access_Worker/access_worker.ps1'
        scriptArguments: >
          -RoleDefinitionName 'Reader'
          -TagName 'Owner'

    - task: AzurePowerShell@5
      displayName: 'Access Worker'
      inputs:
        azurePowerShellVersion: LatestVersion
        azureSubscription: 'My Azure Subscription 3'
        scriptPath: '$(Pipeline.Workspace)/AccessWorker/.src/Access_Worker/access_worker.ps1'
        scriptArguments: >
          -RoleDefinitionName 'Reader'
          -TagName 'Owner'

A: I figured it out - it was pretty easy. Here's the solution:
parameters:
  - name: subscriptions
    type: object
    default:
      - 'My Azure Subscription 1'
      - 'My Azure Subscription 2'
      - 'My Azure Subscription 3'

stages:
  - stage: Deploy
    displayName: "Deploy Pipeline - Get Resource Count"

    jobs:
      - job: ResourceCount
        displayName: "Subscription Loop Test"

        steps:
          - ${{ each subscription in parameters.subscriptions }}:
            - task: AzurePowerShell@5
              displayName: "Get Resource Count"
              inputs:
                azurePowerShellVersion: LatestVersion
                azureSubscription: ${{ subscription }}
                scriptType: InlineScript
                Inline: |
                  Write-Host "Subscription Name: $((Get-AzContext).Subscription.Name)"
                  Write-Host "Resource Count: $((Get-AzResource).Count)"


text:
Q: Android Touch Movement I want to know how to move an object Left or Right by touching. Something like:
public float speed;

void FixedUpdate ()
{
    float LeftRight = Input.GetAxis ("Horizontal");

    Vector3 Movement = new Vector3 ( LeftRight, 0, 0);

    rigidbody.AddForce(Movement * speed);
}

But just for touching the screen. The first half of screen for left and the other for right.

A: For input type of touch in android or ios, use Input.GetTouch.
The idea is to get the position of the touch then decide if it's touching the left or the right side of the screen by getting the screen width using Screen.width.
public float speed;

void FixedUpdate ()
{
    float LeftRight = 0;

    if(Input.touchCount > 0){
        // touch x position is bigger than half of the screen, moving right
        if(Input.GetTouch(0).position.x > Screen.width / 2)
            LeftRight = 1;
        // touch x position is smaller than half of the screen, moving left
        else if(Input.GetTouch(0).position.x < Screen.width / 2)
            LeftRight = -1;
    }

    Vector3 Movement = new Vector3 ( LeftRight, 0, 0);

    rigidbody.AddForce(Movement * speed);
}


text:
Q: Best practices for Android + GWT + Server side + IDE I am developing a Java app with Google App Engine and GWT (with RPC), using Eclipse and now I would like to start creating Android apps using existing shared code between projects.
I have several questions regarding design patterns / best practices:

*

*IDE - I know now that developing Android apps in Eclipse has been deprecated for some time and is no longer possible (in favor of Android Studio), so what would the best practice be if I need to share code (models, java beans, utility methods) between server side (servlets), GWT and Android client side and to test?

*client-server communication - for now, I am using GWT-RPC, but I've been meaning to change that. What would a good solution be to call actions on server side and use java beans (generic objects also)?
I don't mind using different communication types at the beginning (I can use RPC for GWT at start)

Some tutorials / links or other pointers would be very nice. Thank you!

A: For IDE Eclipse does work. But I would recommend using IntelliJ (professional edition since this has GWT support)
Client-server communication. Just use JSON. I use jackson for both Android and GWT (gwt-jackson for GWT). I would strongly recommend to not use GWT-RPC. This will get you in all kind of difficult positions for Android. And since you need to make a JSON interface anyway, use it for both Android and GWT.


text:
Q: Office.Interop.Word SaveAs says Invalid filename Using Microsoft.Interop.Word I try to save a Word file (docx). In most cases it saves fine, but just occasionally it doesn't. And I can't figure out what specifically causes the error.
The file and path is generated, based on current related data. In this (failing) example the output file path (_fullpath in the c# code further down) is

G:\Red Group\Varme\Tilbud_tilbudsprogram\108472_Test-Customer A_S
  Projektafregning Kun til HE Pro Kolding \108472_Test-Customer
  A_S Projektafregning Kun til HE Pro Kolding _201802062146.docx

The error message is "Invalid filename..."
The exception is:

at Microsoft.Office.Interop.Word.DocumentClass.SaveAs2(Object&
  FileName, Object& FileFormat, Object& LockComments, Object& Password,
  Object& AddToRecentFiles, Object& WritePassword, Object&
  ReadOnlyRecommended, Object& EmbedTrueTypeFonts, Object&
  SaveNativePictureFormat, Object& SaveFormsData, Object&
  SaveAsAOCELetter, Object& Encoding, Object& InsertLineBreaks, Object&
  AllowSubstitutions, Object& LineEnding, Object& AddBiDiMarks, Object&
  CompatibilityMode)     at Quotation.Word.OpenAndShow(String MergeFile,
  String OutPath) in F:\dbConsult\Kunder\Danfoss\Quotation 2017\Danfoss
  Quotation\Danfoss Quotation\Classes\WordMerge.cs:line 333

Line 333 is the wordDoc.SaveAs() line. That part of the code looks like this:
wordDoc.Activate();
wordApp.Visible = true;
wordApp.Activate();

try
    {
        wordDoc.SaveAs(_fullpath);
    }
catch (Exception ex)
{
    using (StreamWriter sw = File.CreateText(_fullpath))
    {
        sw.WriteLine("Hey");
    }
    Helper.Log(ex.Message, ex.StackTrace, "WordMerge.OpenAndShow()");
    return false;
}

The "using" part in my catch is for test. If I use the StreamWriter the file is created as it should. So, with this is mind I take that it is a flaw in the SaveAs() mehtod. Does that conclusion seem right? And if so: any clue what to do?
Best regards
Morten

A: Resolved by replacing space characters: Replace(" ", "-").
I cannot figure out exactly what triggers this, because I have plenty of successful saves without error occurring - and where I have spaces.
Also, all failed saves works well with StreamWriter. So it seems to be some internal flaw in the Word.Interop.
BR


text:
Q: Syntax Error: Adding div class to php variable that will be outputted I'm trying to create a variable in my .php file that will contain a simple  class from CSS.  However the style is not showing up in my output.
CSS
#cost_class {
  color:#427120;
}

PHP
while($r=mysql_fetch_array($x)){
$id = $r["id"]; //ID OF CONTENT
$content = $r["content"]; //CONTENT ITSELF
$cost = $r["Cost"]; // COST
$address = $r["address"]; // ADDRESS

$m .= '
'.$content.'

';

include "variables.php"; //FILE WITH THE PERCENTAGES, BUTTON IMAGE URLS, AND WHETHER USER HAS RATED

$m .= '
' .$cost. " " .$address. '

';
}

echo $m;

I know this is a syntax issue that is preventing the CSS from being displayed.

A: change your css
.cost_class {
  color:#427120;
}

A: Your CSS is asking for an element with id cost_class. For a class, it should be:
.cost_class {
  color:#427120;
}

A period signifies classes in CSS; a hash IDs.


text:
Q: How to unpack the columns of a pandas DataFrame to multiple variables Lists or numpy arrays can be unpacked to multiple variables if the dimensions match. For a 3xN array, the following will work:
import numpy as np
a,b =          [[1,2,3],[4,5,6]]
a,b = np.array([[1,2,3],[4,5,6]])
# result: a=[1,2,3],   b=[4,5,6]

How can I achieve a similar behaviour for the columns of a pandas DataFrame? Extending the above example:
import pandas as pd
df = pd.DataFrame([[1,2,3],[4,5,6]])
df.columns = ['A','B','C']    # Rename cols and
df.index = ['i', 'ii']        # rows for clarity

The following does not work as expected:
a,b = df.T
# result: a='i',   b='ii'
a,b,c = df
# result: a='A',   b='B',   c='C'

However, what I would like to get is the following:
a,b,c = unpack(df)
result: a=df['A'], b=df['B'], c=df['C']

Is the function unpack already available in pandas? Or can it be mimicked in an easy way?

A: I just figured that the following works, which is already close to what I try to achieve:
a,b,c = df.T.values        # Common
a,b,c = df.T.to_numpy()    # Recommended
# a,b,c = df.T.as_matrix() # Deprecated

Details: As always, things are a little more complicated than one thinks. Note that a pd.DataFrame stores columns separately in Series. Calling df.values (or better: df.to_numpy()) is potentially expensive, as it combines the columns in a single ndarray, which likely involves copying actions and type conversions. Also, the resulting container has a single dtype able to accommodate all data in the data frame.
In summary, the above approach loses the per-column dtype information and is potentially expensive. It is technically cleaner to iterate the columns in one of the following ways (there are more options):
# The following alternatives create VIEWS!
a,b,c = (v for _,v in df.items())      # returns pd.Series
a,b,c = (df[c] for c in df)            # returns pd.Series

Note that the above creates views! Modifying the data likely will trigger a SettingWithCopyWarning.
a.iloc[0] = "blabla"    # raises SettingWithCopyWarning

If you want to modify the unpacked variables, you have to copy the columns.
# The following alternatives create COPIES!
a,b,c = (v.copy() for _,v in df.items())      # returns pd.Series
a,b,c = (df[c].copy() for c in df)            # returns pd.Series
a,b,c = (df[c].to_numpy() for c in df)        # returns np.ndarray

While this is cleaner, it requires more characters. I personally do not recommend the above approach for production code. But to avoid typing (e.g., in interactive shell sessions), it is still a fair option...
# More verbose and explicit alternatives
a,b,c = df["the first col"], df["the second col"], df["the third col"]
a,b,c = df.iloc[:,0], df.iloc[:,1], df.iloc[:,2]

A: The dataframe.values shown method is indeed a good solution, but it involves building a numpy array.
In the case you want to access pandas series methods after unpacking, I personally use a different approach.
For the people like me that use a lot of chained methods, I have a solution by adding a custom unpacking method to pandas. Note that this may not be very good for production pipelines, but it is very handy in ad-hoc data analyses.
df = pd.DataFrame({
    "lat": [30, 40],
    "lon": [0, 1],
})

This approach involves returning a generator on a .unpack() call.
from typing import Tuple

def unpack(self: pd.DataFrame) -> Tuple[pd.Series]:
    return (
        self[col]
        for col in self.columns
    )

pd.DataFrame.unpack = unpack

This can be used in two major ways.
Either directly as a solution to your problem:
lat, lon = df.unpack()

Or, can be used in a method chaining.
Imagine a geo function which has to take a latitude serie in the first arg and a longitude in the second arg, named do_something_geographical(lat, lon)
df_result = (
    df
        .(...some method chaining...)
        .assign(
            geographic_result=lambda dataframe: do_something_geographical(dataframe[["lat", "lon"]].unpack())
        )
        .(...some method chaining...)
)


text:
Q: Merge csv files with conditions I have 2 CSV files for each date (csv_2014_4_15 and csv_2014_4_16) , with basic structure and couple of unique columns as below.
id,name,created_at,updated_at,other columns

12, joe, 2013-1-1 18:30, 2014-2-1 12:00
56, bob, datetime, datetime

I want to merge the 2 csv files based on these these conditions. My code so far is as below.
if (csv_date_x.id == csv_date_x+1.id)
{
   if(csv_date_x.updated_at < csv_date_x.updated_at)
         add csv_date_x+1 row into out.csv
}
else {
   if(csv_date_x+1.created_at == TODAY (yyyy-mm-dd)
         add csv_date_x+1 row into out.csv
}

A: Try this:
$ awk -F',' -v t="$(date +"%Y-%-m-%-d")" '
    FNR == NR {
        u[$1] = $4;
        next;
    }
    $4 > u[$1] {
        print;
        next;
    }
    t ~ $3
' file_1 file_2

Explanation

*

*We get today date, save it in variable t

*While reading file_1 FNR == NR, we save each updated time of each id in associative array u, key is id, value is updated time.

*While reading file_2:

*

*If update date of id, $4 greater than correspond id updated time save in array u ($4 > u[$1]), we print the line and skip to next line.

*If above condition false, we check if created date of current line is today, t ~ $3, i.e "2014-7-11" ~ "2014-7-11 12:00", if true print the line.

A: I assume that by csv_date_x you mean csv_2014_4_15 and csv_date_x+1 means csv_2014_4_16. But according to your pseudo-code you never use any lines from csv_date_x, so that's more a filter than a merge and you wind up with a subset of csv_2014_4_16.
This is a non-trivial programming task, but I can point you in a profitable direction.
This sort of thing can get hairy if you have to deal with escaped commas in the first two fields. I'll assume that you do not.
I'll also assume that you can compare these two files row-by-row, since you didn't specify.
You'll need to first normalize your csv files so that months and dates are always two digits (leading zeros). Then they can be compared textually, and this is pretty easy with awk. Something like:
sed 's/-\([1-9]\)/-0\1/'

(this assumes you have no hyphens in your names, ids, or "other columns", you'll need a different approach if so, probably matching more carefully on date patterns and possibly restricting to the 3rd and 4th fields).
Use the date program to generate today's date in the output format that matches your fields, and pass that in as a variable for awk to use:
awk -v Today=$(date +"%Y-%m-%d %H:%M") -v File1=csv_2014_4_15 -v File2=csv_2014_4_16 '
{ getline line1 < File1;
  getline line2 < File2;
  split(line1, f1, ",");
  split(line2, f2, ",");
}
f1[1] == f2[1] { ...; next } # compare IDs this is your first 'if' clause
{ ... } # this is your else clause since the previous ended with "next"

You're in pretty good shape at that point. f1 contains the fields of the line from File1, and f2 contains the fields of the line from File2. You can compare ids (e.g. f1[1] and f2[1]) and dates (e.g. f1[2] for create f1[3] for update). and print the lines you want. You can compare against Today for today's date.
Note that you could get fancier and do your date-format normalization within awk by splitting the 3rd and 4th fields on - but I'd find it easier with a sed pass first.
Also note that Today contains both date and time. If you just want to compare the date, you can drop that from the date command specification, but you'll also need to split the csv field to strip the time before comparing.


text:
Q: Changing sprite after mouse click on collider (working with many colliders and many different sprites) I won't hide that I am new to the Unity and C#. I am trying to make mini escape game.
My problem: Changing sprites using colliders works only on one object. After clicking second object it works one time and then either the first and the second object don't work.
Description:
On the main screen I will have many items that are "clickable" and some that are "pickable". I created 2 scripts- one that close up to the clicked item, and second that return to the main view.
Main view looks like that: they are 3 colliders and each one close-up to different view. Colliders are the children of the Background. After close-up I don't want the child colliders of background to be working. Only the collider of the close-up should work.
So the question: Am I doing anything wrong? Is there any better method to change sprites after mouse click?

My code:
First script:
public class GetCloser : MonoBehaviour // shows close-up of clicked object
{
    public GameObject Actual, Background;

    void OnMouseDown()
    {

            RaycastHit2D hit = Physics2D.Raycast(transform.position, -Vector2.up);

            if (hit.collider != null)
            {
                Background.SetActive(false);

                Actual.GetComponent<Collider2D>().enabled = true;
                Actual.GetComponent<SpriteRenderer>().enabled = true;
            }

    }

}

Second script:
public class ReturnTo : MonoBehaviour //hide the close-up image and return to the background
{
    public GameObject Actual, Background;

 void OnMouseDown()
    {

            RaycastHit2D hit = Physics2D.Raycast(transform.position, -Vector2.up);

            if (hit.collider != null)
            {

                Background.SetActive(true);
                Actual.GetComponent<Collider2D>().enabled = false;
                Actual.GetComponent<SpriteRenderer>().enabled = false;
            }

    }

}

Last script:
public class PickUp : MonoBehaviour { //hide clicked object- works every time

    // Use this for initialization
    void Start () {
        gameObject.GetComponent<SpriteRenderer>().enabled = true;
    }

    // Update is called once per frame
    void OnMouseDown()
    {

            RaycastHit2D hit = Physics2D.Raycast(transform.position, -Vector2.up);

            if (hit == true && hit.collider != null)
            {
                hit.collider.gameObject.GetComponent<SpriteRenderer>().enabled = false;
                Destroy(hit.collider);

            }

    }
}

A: So if the issue is the colliders for your main screen still being active after zoom that's simply adding in your first script "zoom script" deactivating the colliders for all background or even just simply turning the gameobjects in the background off, then when you zoom back out simply turn the objects back on or colliders back on depending on which you decided to turn off.
Wait I just reread and realize after you click the first object you are no longer able to get the other objects to react any longer.  Looking over your code it is probably because you are destroying the collider in your third script therefore you are no longer able to "hit" the other objects to trigger the code of a collision.


text:
Q: Multiple pre-auth filters in Spring Security? I have a need to have multiple PRE_AUTH Spring Security filters.  In particular I need to use a PRE_AUTH filter in addition to the two filters configured as PRE_AUTH in the SAML extension to Spring Security 3.0.  The existing SAML configuration follows.
<security:http entry-point-ref="samlEntryPoint">
    <!-- snip intercepts -->
    <security:custom-filter after="BASIC_AUTH_FILTER" ref="samlProcessingFilter"/>
    <security:custom-filter before="PRE_AUTH_FILTER" ref="samlEntryPoint"/>
    <security:custom-filter position="PRE_AUTH_FILTER" ref="metadataFilter"/>
    <security:custom-filter after="LOGOUT_FILTER" ref="samlLogoutFilter"/>
    <security:custom-filter before="LOGOUT_FILTER" ref="samlLogoutProcessingFilter"/>
</security:http>

The additional PRE_AUTH filter would need to be checked before either of the existing filters (ie: a user authenticated with this authentication method should not be given the opportunity to use SAML.
I considered changing it the following way.
<!-- snip -->
<security:custom-filter before="PRE_AUTH_FILTER" ref="newPreAuthFilter"/>
<security:custom-filter position="PRE_AUTH_FILTER" ref="samlEntryPoint"/>
<security:custom-filter after="PRE_AUTH_FILTER" ref="metadataFilter"/>
<!-- snip -->

Would this work, or is a more complicated solution required.

A: Very old question, but still relevant. Use the composite filter from spring:
<security:custom-filter before="PRE_AUTH_FILTER" ref="compositeAuthFilter"/>

<bean id="compositeAuthFilter" class="org.springframework.web.filter.CompositeFilter">
    <property name="filters">
        <list>
            <ref bean="airlockAuthFilter"/>
            <ref bean="samlEntryPoint"/>
            <ref bean="metadataFilter"/>
        </list>
    </property>
</bean>


text:
Q: what does the last block mean? and what is unittest.main()? the is the function I want to set a test for, and it is in the .py file name_function.py
def get_formatted_name(first, last):
    """generate a neatly formatted full name"""
    fullname = f"{first} {last}"
    return fullname.title()

The main programe:
import unittest
from name_function import get_formatted_name as gfn

class NamesTestCase(unittest.TestCase):
    """Test For 'name_function.py'."""
    def test_first_last_name(self):
        """Do names like 'Janis Joplin' work?"""
        formatted_name = gfn('janis', 'joplin')
        self.assertEqual(formatted_name, 'Janis Joplin')

I don't understand the block below
if __name__ == '__main__':
    unittest.main()


text:
Q: Datagridview cell value change update database I have retrieved data from Mysql database into a DataGridView1. Let us suppose I am in Row 0. When I change the contents of Row 0, Cell 1 and press enter key or a button, the Update query should modify that row, but I am unable to modify the value of the cell. The cell maintains its previous value when i reload data and the database is not modified. For example, if I change the contents of a cell under column Client_Name  from "Acs" to "Gmt", how can I change the value of the cell from "Acs" to "Gmt"? and to have it updated into Mysql database, I am using c# in Vs 2012. below is my code that retrieves my database into datagridview1 any help is welcomed thanks.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data;
using MySql.Data.MySqlClient;
using System.Configuration;
using System.Data.SqlClient;

namespace PI.Gen
{
    public partial class frmMain : Form
    {
        MySqlConnection Conn;

        public frmMain()
        {
            InitializeComponent();
            btnDisconnect.Enabled = true;
            btnLoadData.Enabled = false;
            btnLoadClients.Enabled = false;

        }

        private void btnConnect_Click(object sender, EventArgs e)
        {

            string strConnect = "server=" + txtServer.Text + ";uid=" + txtUsername.Text + ";pwd=" + txtPassword.Text + ";database=" + txtDatabase.Text;
            try
            {
                if (txtServer.TextLength <= 0 || txtUsername.TextLength <= 0 || txtDatabase.TextLength <= 0)
                {
                    MessageBox.Show("You have an empty database connection field. Please supply a valid value.");
                    return;
                }

                Conn = new MySqlConnection(strConnect);
                Conn.Open();

                if (Conn.State.ToString() != "Open")
                {
                    MessageBox.Show("Could not open database connection");
                    return;
                }
                btnDisconnect.Enabled = true;
                btnConnect.Enabled = false;
                btnLoadData.Enabled = true;
                btnLoadClients.Enabled = true;
                //  btnSubmitClient.Enabled = true;
            }
            catch (Exception ex)  // catch on general exceptions, not specific
            {
                MessageBox.Show(ex.Message);
                return;
            }
        }

        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (Conn != null)
            {
                Conn.Close();
            }
        }

        private void btnDisconnect_Click(object sender, EventArgs e)
        {
            try
            {
                Conn.Close();
                Conn = null;
                btnDisconnect.Enabled = false;
                btnConnect.Enabled = true;
                btnLoadData.Enabled = false;
                btnLoadClients.Enabled = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
        }

        private void btnLoadData_Click(object sender, EventArgs e)
        {
            try
            {
                string CmdString = "SELECT * FROM t_receipients";
                MySqlDataAdapter sda = new MySqlDataAdapter(CmdString, Conn);
                DataSet ds = new DataSet();

                sda.Fill(ds);
                dataGridView1.DataSource = ds.Tables[0].DefaultView;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }

         }

        private void btnLoadClients_Click(object sender, EventArgs e)
        {
            try
            {

                string CmdString = "SELECT * FROM t_clients";
                MySqlDataAdapter sda = new MySqlDataAdapter(CmdString, Conn);

                DataSet ds = new DataSet();
                sda.Fill(ds);
                dataGridView1.DataSource = ds.Tables[0].DefaultView;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }

        }

A: After series of trials and error, i finally found what i was looking for, thus being able to update database from datagridview below is my worked around code which works 100% hope it helps someone in future, and thanks @RageComplex for helping out, but one more thing does anyone know how to implement that i mean instead of hitting the enter button to take changes in the datagridview you rather click on a button ty
   private void dataGridView1_RowValidated(object sender, DataGridViewCellEventArgs e)
    {
        try
        {
            DataTable changes = ((DataTable)dataGridView1.DataSource).GetChanges();
            if (changes != null)
            {
                MySqlCommandBuilder mcb = new MySqlCommandBuilder(mySqlDataAdapter);
                mySqlDataAdapter.UpdateCommand = mcb.GetUpdateCommand();
                mySqlDataAdapter.Update(changes);
                ((DataTable)dataGridView1.DataSource).AcceptChanges();

                MessageBox.Show("Cell Updated");
                return;
            }

        }

        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

    }

A: You are not updateing your changes to the database. While you keep your connection open doesn't mean that this will automatically update your data.
First of all, don't keep your connection open. In your app you have a connect button which is good for testing but not for really keeping the connection open, not with databases in my opinion.
The way you load data is correct.
You give the datagridview an DataSource which is a table from your DataSet. So changes made in the datagridview ARE saved to your DataSet but not to your database.
This is how you update your database
   public void UpdateTable(DataSet ds)
    {
        using (MySqlConnection connect = new MySqlConnection(ConnString))
        {
            connect.Open();
            MySqlDataAdapter adapt = new MySqlDataAdapter();
            MySqlCommandBuilder commbuilder = new MySqlCommandBuilder(adapt);
            adapt.SelectCommand = new MySqlCommand("SELECT * FROM t_receipients", connect);
            adapt.Update(ds.Tables[0]);
        }
    }

Make sure, before you Update your database, you use datagridview1.EndEdit()
Also, you using, this will ensure a connection is closed again after completing that code, best is to always have it in a try-except.
You had struggles with connecting the database as it appears to be in the commends.
I've also forgot to include MySqlDataAdapter above, I used an adapter globally in that case.
I didn't want to report this question as duplicated, but now it kinda does look like this answer.

A: I would like to give code which I have tested in my application.I used it for button click event.
private void button3_Click(object sender, EventArgs e)
    {
        string StrQuery;
        try
        {
            string MyConnection2 = "server=localhost;user id=root;password=;database=k";
            using (MySqlConnection conn = new MySqlConnection(MyConnection2))
            {
                using (MySqlCommand comm = new MySqlCommand())
                {
                    comm.Connection = conn;
                    conn.Open();
                    for (int i = 0; i < dataGridView3.Rows.Count; i++)
                    {
                        StrQuery = @"update s set  Quantity='" + dataGridView3.Rows[i].Cells["Quantity"].Value.ToString() + "' where No='" + dataGridView3.Rows[i].Cells["Item No"].Value.ToString() + "';";

                        comm.CommandText = StrQuery;
                        comm.ExecuteNonQuery();
                    }
                }
            }
        }
        catch
        {
        }
    }

I think it may help you


text:
Q: confirm alert coming twice called when onbeforeload event I have a confirm box on beforeload event - the code is as follows:
window.onbeforeunload = function(){
            //alert('leaving ... ' + is_edited );

            if (is_edited == true) {
                return confirm('Are you sure you want to navigate away from this page? \n\n Press OK to continue, or Cancel to stay on the current page.');
            }

        };

The problem is that - the confirm alert is showing twice. I have searched on stackoverflow and got many questions about this issue. But mine is somewhat different. It is not the same confirm alert showing twice. For FF the message is same but for Crome in second confirm box the message is false.
Thanks in advance.

A: The "onbeforeunload" handler is supposed to return a string. Whether the string will be shown to the user or not is up to the browser.
Your function returns the result of the "confirm()" call, a boolean. Firefox 4 does not show the returned string from the "beforeunload" handler, while other browsers still do. Thus your function puts up a "Confirm" box, gets the result, and returns it. The browser then puts up the "beforeunload" confirmation, which in the case of some browsers will include the stringified value returned from your handler (either "true" or "false").
Here is the Mozilla documentation for the event and its handler.

A: It's better for you to use jQuery here for cross browser functionality.
jQuery UI Dialog OnBeforeUnload


text:
Q: Python Tkinter canvas.scale() does not scale images while running I am new with Tkinter, and could not find any answers on why the scaling does not work.
I have a script that moves and zooms on an image while the window is running. The movement works perfectly, although canvas.scale() doesn't do anything.
Here is a snippet:
def GetAttrPositions(char, attrs):
    global pos
    pos = [10,10,1]
    root = tk.Tk()
    root.title('Getting Attribute Positions')
    root.geometry(f"{char_base.size[0]}x{char_base.size[1]}")

    canvas = tk.Canvas(root, width=2000, height=2000)
    canvas.pack()

    char = tk.PhotoImage(file=f"assets/Chars/{char}.png")
    char_image = canvas.create_image(0,0, anchor=tk.NW, image=char)
    attr = tk.PhotoImage(file=f"assets/Attr/{attrs[0]['Type']}/{attrs[0]['Name']}.png")
    attr_image = canvas.create_image(pos[0], pos[1], anchor=tk.NW, image=attr)

    def move(event):
        global pos
        if event.char == "a":
            print('a')
            pos[0] -= 2
            canvas.move(attr_image, -2, 0)
        elif event.char == "d":
            print('d')
            pos[0] += 2
            canvas.move(attr_image, 2, 0)
        elif event.char == "w":
            print('w')
            pos[1] -= 2
            canvas.move(attr_image, 0, -2)
        elif event.char == "s":
            print('s')
            pos[1] += 2
            canvas.move(attr_image, 0, 2)
        elif event.char == "x":
            print('x')
            pos[2] = pos[2]*2
            canvas.scale(attr_image, pos[0], pos[1], 2, 2)
        elif event.char == "z":
            print('z')
            pos[2] = pos[2]/2
            canvas.scale(attr_image, pos[0], pos[1], 0.5, 0.5)

    root.bind("<Key>", move)
    root.mainloop()

P.S. I am sure that it is working, as if I put a wrong offset, then the image moves, but does not scale


text:
Q: Factorization of numbers What is the easiest and practical way of factoring numbers such as $62473207$ which are formed as a result of multiplication of two primes?

A: In general, this is a hard problem (cryptography is based on this after all). However, this time it's not so bad because you said it's the product of two primes. Assuming the two primes are not of different orders of magnitude, it's sensible to start looking around the square root. If you take the greatest integer not more than the square root of the number, you get $7903$. A very quick check around that number shows the factorisation should be $7901 \times 7907$.

A: The simplest algorithm for factoring is to just try everything; this is known as trial division.
In the general case, the fastest algorithms are the quadratic sieve and the general number field sieve. There are introductions to both in Carl Pomerance's A Tale of Two Sieves. This requires number theory to understand, and the GNFS requires algebraic number theory.
In specific cases, where you know things about the primes that multiplied to form your number, you might be able to use a different algorithm. Many are listed on Wikipedia. In addition, if you don't need a top-of-the-line algorithm (for instance, if you're factoring smaller numbers), you can use a simpler algorithm like Pollard's rho, or even trial division for numbers like those of the magnitude you gave.

A: If your question is about computer tools, this question might not belong here. That being said, you can plug it into Wolfram Alpha.
Also a number of that size is small enough to brute force. So create a file in notepad (or the like) called factor.html and drop in
<!DOCTYPE html>
<script>
    n = 62473207;
    for (i = 2; i < n; i++) {
    if (n % i == 0){
        alert(i + " " + (n/i));
        break;
    }
}
</script>

Open the file with the browser. I don't regard these two solutions as the "correct" way for a mathematician to solve the problem (which would be installing some tool like Mathematica or Pari/GP) but it is easy.


text:
Q: OpenGL related header not found after upgrade to Mac OX El Captitan I just recently upgraded to El Captitan. After the upgrade, the OpenGL related headers, like <OpenGL/gl.h>, can not be found. The problem does not exist before the upgrade. Anyone knows how to solve this problem?

A: I found the problem is because the Mac SDK version is not correctly set in Qt after system upgrade.
One can follow the asnswer in this post to change the mac os version to correct one.
But there is still one problem remaining, the compiler is not able to find the OpenGL framework when linking the executables. I found it is because the linker option -Wl,-syslibroot,/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk, which is automatically added by qmake. If I manually type it the linking command without the option, then it works. I haven't found out how to solve this problem yet.


text:
Q: How to auto-expand height of NSTextView in SwiftUI? How do I properly implement NSView constraints on the NSTextView below so it interacts with SwiftUI .frame()?
Goal
An NSTextView that, upon new lines, expands its frame vertically to force a SwiftUI parent view to render again (i.e., expand a background panel that's under the text + push down other content in VStack). The parent view is already wrapped in a ScrollView. Since the SwiftUI TextEditor is ugly and under-featured, I'm guessing several others new to MacOS will wonder how to do the same.
Update
@Asperi pointed out a sample for UIKit buried in another thread. I tried adapting that for AppKit, but there's some loop in the async recalculateHeight function. I'll look more at it with coffee tomorrow. Thanks Asperi. (Whoever you are, you are the SwiftUI SO daddy.)
Problem
The NSTextView implementation below edits merrily, but disobeys SwiftUI's vertical frame. Horizontally all is obeyed, but texts just continues down past the vertical height limit. Except, when switching focus away, the editor crops that extra text... until editing begins again.
What I've Tried
Sooo many posts as models. Below are a few. My shortfall I think is misunderstanding how to set constraints, how to use NSTextView objects, and perhaps overthinking things.

*

*I've tried implementing an NSTextContainer, NSLayoutManager, and NSTextStorage stack together in the code below, but no progress.

*I've played with GeometryReader inputs, no dice.

*I've printed LayoutManager and TextContainer variables on textdidChange(), but am not seeing dimensions change upon new lines. Also tried listening for .boundsDidChangeNotification / .frameDidChangeNotification.

*

*GitHub: unnamedd MacEditorTextView.swift <- Removed its ScrollView, but couldn't get text constraints right after doing so

*SO: Multiline editable text field in SwiftUI <- Helped me understand how to wrap, removed the ScrollView

*SO: Using a calculation by layoutManager <- My implementation didn't work

*Reddit: Wrap NSTextView in SwiftUI <- Tips seem spot on, but lack AppKit knowledge to follow

*SO: Autogrow height with intrinsicContentSize <- My implementation didn't work

*SO: Changing a ScrollView <- Couldn't figure out how to extrapolate

*SO: Cocoa tutorial on setting up an NSTextView

*Apple NSTextContainer Class

*Apple Tracking the Size of a Text View
ContentView.swift
import SwiftUI
import Combine

struct ContentView: View {
    @State var text = NSAttributedString(string: "Testing.... testing...")
    let nsFont: NSFont = .systemFont(ofSize: 20)

    var body: some View {
// ScrollView would go here
        VStack(alignment: .center) {
            GeometryReader { geometry in
                NSTextEditor(text: $text.didSet { text in react(to: text) },
                             nsFont: nsFont,
                             geometry: geometry)
                    .frame(width: 500, // Wraps to width
                           height: 300) // Disregards this during editing
                    .background(background)
            }
           Text("Editing text above should push this down.")
        }
    }

    var background: some View {
        ...
    }

    // Seeing how updates come back; I prefer setting them on textDidEndEditing to work with a database
    func react(to text: NSAttributedString) {
        print(#file, #line, #function, text)
    }

}

// Listening device into @State
extension Binding {

    func didSet(_ then: @escaping (Value) ->Void) -> Binding {
        return Binding(
            get: {
                return self.wrappedValue
            },
            set: {
                then($0)
                self.wrappedValue = $0
            }
        )
    }
}

NSTextEditor.swift

import SwiftUI

struct NSTextEditor: View, NSViewRepresentable {
    typealias Coordinator = NSTextEditorCoordinator
    typealias NSViewType = NSTextView

    @Binding var text: NSAttributedString
    let nsFont: NSFont
    var geometry: GeometryProxy

    func makeNSView(context: NSViewRepresentableContext<NSTextEditor>) -> NSTextEditor.NSViewType {
        return context.coordinator.textView
    }

    func updateNSView(_ nsView: NSTextView, context: NSViewRepresentableContext<NSTextEditor>) { }

    func makeCoordinator() -> NSTextEditorCoordinator {
        let coordinator =  NSTextEditorCoordinator(binding: $text,
                                                   nsFont: nsFont,
                                                   proxy: geometry)
        return coordinator
    }
}

class  NSTextEditorCoordinator : NSObject, NSTextViewDelegate {
    let textView: NSTextView
    var font: NSFont
    var geometry: GeometryProxy

    @Binding var text: NSAttributedString

    init(binding: Binding<NSAttributedString>,
         nsFont: NSFont,
         proxy: GeometryProxy) {
        _text = binding
        font = nsFont
        geometry = proxy

        textView = NSTextView(frame: .zero)
        textView.autoresizingMask = [.height, .width]
        textView.textColor = NSColor.textColor
        textView.drawsBackground = false
        textView.allowsUndo = true

        textView.isAutomaticLinkDetectionEnabled = true
        textView.displaysLinkToolTips = true
        textView.isAutomaticDataDetectionEnabled = true
        textView.isAutomaticTextReplacementEnabled = true
        textView.isAutomaticDashSubstitutionEnabled = true
        textView.isAutomaticSpellingCorrectionEnabled = true
        textView.isAutomaticQuoteSubstitutionEnabled = true
        textView.isAutomaticTextCompletionEnabled = true
        textView.isContinuousSpellCheckingEnabled = true
        textView.usesAdaptiveColorMappingForDarkAppearance = true

//        textView.importsGraphics = true // 100% size, layoutManger scale didn't fix
//        textView.allowsImageEditing = true // NSFileWrapper error
//        textView.isIncrementalSearchingEnabled = true
//        textView.usesFindBar = true
//        textView.isSelectable = true
//        textView.usesInspectorBar = true
        // Context Menu show styles crashes

        super.init()
        textView.textStorage?.setAttributedString($text.wrappedValue)
        textView.delegate = self
    }

//     Calls on every character stroke
    func textDidChange(_ notification: Notification) {
        switch notification.name {
        case NSText.boundsDidChangeNotification:
            print("bounds did change")
        case NSText.frameDidChangeNotification:
            print("frame did change")
        case NSTextView.frameDidChangeNotification:
            print("FRAME DID CHANGE")
        case NSTextView.boundsDidChangeNotification:
            print("BOUNDS DID CHANGE")
        default:
            return
        }
//        guard notification.name == NSText.didChangeNotification,
//              let update = (notification.object as? NSTextView)?.textStorage else { return }
//        text = update
    }

    // Calls only after focus change
    func textDidEndEditing(_ notification: Notification) {
        guard notification.name == NSText.didEndEditingNotification,
              let update = (notification.object as? NSTextView)?.textStorage else { return }
        text = update
    }
}

Quick Asperi's answer from a UIKit thread
Crash
*** Assertion failure in -[NSCGSWindow setSize:], NSCGSWindow.m:1458
[General] Invalid parameter not satisfying:
   size.width >= 0.0
&& size.width < (CGFloat)INT_MAX - (CGFloat)INT_MIN
&& size.height >= 0.0
&& size.height < (CGFloat)INT_MAX - (CGFloat)INT_MIN

import SwiftUI

struct AsperiMultiLineTextField: View {

    private var placeholder: String
    private var onCommit: (() -> Void)?

    @Binding private var text: NSAttributedString
    private var internalText: Binding<NSAttributedString> {
        Binding<NSAttributedString>(get: { self.text } ) {
            self.text = $0
            self.showingPlaceholder = $0.string.isEmpty
        }
    }

    @State private var dynamicHeight: CGFloat = 100
    @State private var showingPlaceholder = false

    init (_ placeholder: String = "", text: Binding<NSAttributedString>, onCommit: (() -> Void)? = nil) {
        self.placeholder = placeholder
        self.onCommit = onCommit
        self._text = text
        self._showingPlaceholder = State<Bool>(initialValue: self.text.string.isEmpty)
    }

    var body: some View {
        NSTextViewWrapper(text: self.internalText, calculatedHeight: $dynamicHeight, onDone: onCommit)
            .frame(minHeight: dynamicHeight, maxHeight: dynamicHeight)
            .background(placeholderView, alignment: .topLeading)
    }

    @ViewBuilder
    var placeholderView: some View {
            if showingPlaceholder {
                Text(placeholder).foregroundColor(.gray)
                    .padding(.leading, 4)
                    .padding(.top, 8)
            }
    }
}

fileprivate struct NSTextViewWrapper: NSViewRepresentable {
    typealias NSViewType = NSTextView

    @Binding var text: NSAttributedString
    @Binding var calculatedHeight: CGFloat
    var onDone: (() -> Void)?

    func makeNSView(context: NSViewRepresentableContext<NSTextViewWrapper>) -> NSTextView {
        let textField = NSTextView()
        textField.delegate = context.coordinator

        textField.isEditable = true
        textField.font = NSFont.preferredFont(forTextStyle: .body)
        textField.isSelectable = true
        textField.drawsBackground = false
        textField.allowsUndo = true
        /// Disabled these lines as not available/neeed/appropriate for AppKit
//        textField.isUserInteractionEnabled = true
//        textField.isScrollEnabled = false
//        if nil != onDone {
//            textField.returnKeyType = .done
//        }
        textField.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
        return textField
    }

    func makeCoordinator() -> Coordinator {
        return Coordinator(text: $text, height: $calculatedHeight, onDone: onDone)
    }

    func updateNSView(_ NSView: NSTextView, context: NSViewRepresentableContext<NSTextViewWrapper>) {
        NSTextViewWrapper.recalculateHeight(view: NSView, result: $calculatedHeight)
    }

    fileprivate static func recalculateHeight(view: NSView, result: Binding<CGFloat>) {
/// UIView.sizeThatFits is not available in AppKit. Tried substituting below, but there's a loop that crashes.
//        let newSize = view.sizeThatFits(CGSize(width: view.frame.size.width, height: CGFloat.greatestFiniteMagnitude))

// tried reportedSize = view.frame, view.intrinsicContentSize
        let reportedSize = view.fittingSize
        let newSize = CGSize(width: reportedSize.width, height: CGFloat.greatestFiniteMagnitude)
        if result.wrappedValue != newSize.height {
            DispatchQueue.main.async {
                result.wrappedValue = newSize.height // !! must be called asynchronously
            }
        }
    }

    final class Coordinator: NSObject, NSTextViewDelegate {
        var text: Binding<NSAttributedString>
        var calculatedHeight: Binding<CGFloat>
        var onDone: (() -> Void)?

        init(text: Binding<NSAttributedString>, height: Binding<CGFloat>, onDone: (() -> Void)? = nil) {
            self.text = text
            self.calculatedHeight = height
            self.onDone = onDone
        }

        func textDidChange(_ notification: Notification) {
            guard notification.name == NSText.didChangeNotification,
                  let textView = (notification.object as? NSTextView),
                  let latestText = textView.textStorage else { return }
            text.wrappedValue = latestText
            NSTextViewWrapper.recalculateHeight(view: textView, result: calculatedHeight)
        }

        func textView(_ textView: NSTextView, shouldChangeTextIn: NSRange, replacementString: String?) -> Bool {
            if let onDone = self.onDone, replacementString == "\n" {
                textView.resignFirstResponder()
                onDone()
                return false
            }
            return true
        }
    }

}

A: Solution thanks to @Asperi's tip to convert his UIKit code in this post. A few things had to change:

*

*NSView also lacks the view.sizeThatFits() for a proposed bounds change, so I found that the view's .visibleRect would work instead.

Bugs:

*

*There is a bobble on first render (from smaller vertically to the proper size). I thought it was caused by the recalculateHeight(), which would print out some smaller values initially. A gating statement there stopped those values, but the bobble is still there.

*Currently I set the placeholder text's inset by a magic number, which should be done based on the NSTextView's attributes, but I didn't find anything usable yet. If it has the same font I guess I could just add a space or two in front of the placeholder text and be done with it.

Hope this saves some others making SwiftUI Mac apps some time.
import SwiftUI

// Wraps the NSTextView in a frame that can interact with SwiftUI
struct MultilineTextField: View {

    private var placeholder: NSAttributedString
    @Binding private var text: NSAttributedString
    @State private var dynamicHeight: CGFloat // MARK TODO: - Find better way to stop initial view bobble (gets bigger)
    @State private var textIsEmpty: Bool
    @State private var textViewInset: CGFloat = 9 // MARK TODO: - Calculate insetad of magic number
    var nsFont: NSFont

    init (_ placeholder: NSAttributedString = NSAttributedString(string: ""),
          text: Binding<NSAttributedString>,
          nsFont: NSFont) {
        self.placeholder = placeholder
        self._text = text
        _textIsEmpty = State(wrappedValue: text.wrappedValue.string.isEmpty)
        self.nsFont = nsFont
        _dynamicHeight = State(initialValue: nsFont.pointSize)
    }

    var body: some View {
        ZStack {
            NSTextViewWrapper(text: $text,
                              dynamicHeight: $dynamicHeight,
                              textIsEmpty: $textIsEmpty,
                              textViewInset: $textViewInset,
                              nsFont: nsFont)
                .background(placeholderView, alignment: .topLeading)
                // Adaptive frame applied to this NSViewRepresentable
                .frame(minHeight: dynamicHeight, maxHeight: dynamicHeight)
        }
    }

    // Background placeholder text matched to default font provided to the NSViewRepresentable
    var placeholderView: some View {
        Text(placeholder.string)
            // Convert NSFont
            .font(.system(size: nsFont.pointSize))
            .opacity(textIsEmpty ? 0.3 : 0)
            .padding(.leading, textViewInset)
            .animation(.easeInOut(duration: 0.15))
    }
}

// Creates the NSTextView
fileprivate struct NSTextViewWrapper: NSViewRepresentable {

    @Binding var text: NSAttributedString
    @Binding var dynamicHeight: CGFloat
    @Binding var textIsEmpty: Bool
    // Hoping to get this from NSTextView,
    // but haven't found the right parameter yet
    @Binding var textViewInset: CGFloat
    var nsFont: NSFont

    func makeCoordinator() -> Coordinator {
        return Coordinator(text: $text,
                           height: $dynamicHeight,
                           textIsEmpty: $textIsEmpty,
                           nsFont: nsFont)
    }

    func makeNSView(context: NSViewRepresentableContext<NSTextViewWrapper>) -> NSTextView {
        return context.coordinator.textView
    }

    func updateNSView(_ textView: NSTextView, context: NSViewRepresentableContext<NSTextViewWrapper>) {
        NSTextViewWrapper.recalculateHeight(view: textView, result: $dynamicHeight, nsFont: nsFont)
    }

    fileprivate static func recalculateHeight(view: NSView, result: Binding<CGFloat>, nsFont: NSFont) {
        // Uses visibleRect as view.sizeThatFits(CGSize())
        // is not exposed in AppKit, except on NSControls.
        let latestSize = view.visibleRect
        if result.wrappedValue != latestSize.height &&
            // MARK TODO: - The view initially renders slightly smaller than needed, then resizes.
            // I thought the statement below would prevent the @State dynamicHeight, which
            // sets itself AFTER this view renders, from causing it. Unfortunately that's not
            // the right cause of that redawing bug.
            latestSize.height > (nsFont.pointSize + 1) {
            DispatchQueue.main.async {
                result.wrappedValue = latestSize.height
                print(#function, latestSize.height)
            }
        }
    }
}

// Maintains the NSTextView's persistence despite redraws
fileprivate final class Coordinator: NSObject, NSTextViewDelegate, NSControlTextEditingDelegate {
    var textView: NSTextView
    @Binding var text: NSAttributedString
    @Binding var dynamicHeight: CGFloat
    @Binding var textIsEmpty: Bool
    var nsFont: NSFont

    init(text: Binding<NSAttributedString>,
         height: Binding<CGFloat>,
         textIsEmpty: Binding<Bool>,
         nsFont: NSFont) {

        _text = text
       _dynamicHeight = height
        _textIsEmpty = textIsEmpty
        self.nsFont = nsFont

        textView = NSTextView(frame: .zero)
        textView.isEditable = true
        textView.isSelectable = true

        // Appearance
        textView.usesAdaptiveColorMappingForDarkAppearance = true
        textView.font = nsFont
        textView.textColor = NSColor.textColor
        textView.drawsBackground = false
        textView.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)

        // Functionality (more available)
        textView.allowsUndo = true
        textView.isAutomaticLinkDetectionEnabled = true
        textView.displaysLinkToolTips = true
        textView.isAutomaticDataDetectionEnabled = true
        textView.isAutomaticTextReplacementEnabled = true
        textView.isAutomaticDashSubstitutionEnabled = true
        textView.isAutomaticSpellingCorrectionEnabled = true
        textView.isAutomaticQuoteSubstitutionEnabled = true
        textView.isAutomaticTextCompletionEnabled = true
        textView.isContinuousSpellCheckingEnabled = true

        super.init()
        // Load data from binding and set font
        textView.textStorage?.setAttributedString(text.wrappedValue)
        textView.textStorage?.font = nsFont
        textView.delegate = self
    }

    func textDidChange(_ notification: Notification) {
        // Recalculate height after every input event
        NSTextViewWrapper.recalculateHeight(view: textView, result: $dynamicHeight, nsFont: nsFont)
        // If ever empty, trigger placeholder text visibility
        if let update = (notification.object as? NSTextView)?.string {
            textIsEmpty = update.isEmpty
        }
    }

    func textDidEndEditing(_ notification: Notification) {
        // Update binding only after editing ends; useful to gate NSManagedObjects
        $text.wrappedValue = textView.attributedString()
    }
}

A: I found nice gist code created by unnamedd.
https://gist.github.com/unnamedd/6e8c3fbc806b8deb60fa65d6b9affab0
Sample Usage:
MacEditorTextView(
   text: $text,
   isEditable: true,
   font: .monospacedSystemFont(ofSize: 12, weight: .regular)
)
.frame(minWidth: 300,
       maxWidth: .infinity,
       minHeight: 100,
       maxHeight: .infinity)
.padding(12)
.cornerRadius(8)


text:
Q: Make a app similar to quiz maker utilizing the local storage sample app I wanted to check with more experienced developers if this is a good approach. In simple terms I wish to make a cin for the question and a cin with a boolean for the answer. The user would be required to input both and then it would be saved elsewhere to be utilized in another page.

A: You can use "Applications Settings":
https://docs.nativescript.org/angular/ng-framework-modules/application-settings
The storage of a JavaScript object can be done with JSON.stringify() and you can recover it with JSON.parse().
Max length of a single value:

*

*Android: Shared Preferences - max length of a single value

*iOS: Is there any limit in storing values in NSUserDefaults?

A: I was doing well all this time. The only difference was the lack of displaying the variable in which the [text] HTML command did it  for me.


text:
Q: Como calcular o determinante de uma matriz em javascript? Ex.: det([-1, -2, 3], [3, 3, 1], [-1, 2, -3]) // retorna 22
Ex.: det([1, 2], [2, 5]) // retorna 1
Ex.: det([8]) // retorna 8

A: O cálculo direto do determinante pelos cofatores é didático mas bastante ineficiente se você quer usar matrizes grandes a sério.
Uma opção melhor seria calcular a decomposição LU. Como as matrizes L e U são triangulares, o determinante de cada uma é simplesmente a multiplicação dos elementos da diagonal principal. Se A=LU então |A|=|L||U|.
O melhor mesmo seria usar a biblioteca Sylvester.js http://sylvester.jcoglan.com/api/matrix.html#determinant

A: Eu criei a seguinte função em 2010, mas fiz algumas melhorias há pouco tempo:
function determinante(a) {
    var ordem = a.length;

    if (ordem === 1) {
        return a[0][0];
    }

    if (ordem === 2) {
        return a[0][0] * a[1][1] - a[0][1] * a[1][0];
    }

    var det = 0;

    for (var j = 0; j < ordem; j++) {
        det += a[0][j] * cofator(a, 0, j);
    }

    return det;
}

function cofator(a, linha, coluna) {
    var sub_matriz = [],
        ordem = a.length,
        m = 0;

    for (var i = 1; i < ordem; i++) {
        sub_matriz[m] = [];

        for (var j = 0; j < ordem; j++) {
            if (j !== coluna) {
                sub_matriz[m].push(a[i][j]);
            }
        }
        m++;
    }

    //return Math.pow(-1, linha + coluna) * determinante(sub_matriz);
    return (coluna % 2 ? -1 : 1) * determinante(sub_matriz);
}

A função determinante é recursiva indireta (A chama B, B chama A) e usa o Teorema de Laplace para calcular o determinante de uma matriz quadrada. O teorema é aplicado sempre na primeira linha da matriz e não na linha ou coluna com o maior número de zeros, como fazemos no papel.
Exemplos de uso:
determinante([[1,-2,8,4,-3,1], [-2,-9,3,1,4,-4], [3,0,8,7,0,2], [5,7,1,2,5,-1], [7,-8,-6,4,0,-5], [0,-2,-8,0,0,1]])
// Retorna 1560

Conferir em: http://www.wolframalpha.com/input/?i=det+%28%5B1%2C-2%2C8%2C4%2C-3%2C1%5D%2C+%5B-2%2C-9%2C3%2C1%2C4%2C-4%5D%2C+%5B3%2C0%2C8%2C7%2C0%2C2%5D%2C+%5B5%2C7%2C1%2C2%2C5%2C-1%5D%2C+%5B7%2C-8%2C-6%2C4%2C0%2C-5%5D%2C+%5B0%2C-2%2C-8%2C0%2C0%2C1%5D%29

determinante([[1,2,3], [4,5,6], [7,8,1]]);
// Retorna 24

Conferir em: http://www.wolframalpha.com/input/?i=+det+%28%5B1%2C2%2C3%5D%2C+%5B4%2C5%2C6%5D%2C+%5B7%2C8%2C1%5D%29

determinante([[-1,-2,3], [3,3,1], [-1,2,-3]]);
// Retorna 22

Conferir em: http://www.wolframalpha.com/input/?i=det%28%5B-1%2C-2%2C3%5D%2C+%5B3%2C3%2C1%5D%2C+%5B-1%2C2%2C-3%5D%29

determinante([[8]]);
// Retorna 8

determinante([
    [2, 1, 2, 3, 4, 5, 6, 7, 2, 3],
    [0, 2, 0, 0, 0, 0, 0, 2, 3, 2],
    [0, 0, 4, 5, 5, 5, 2, 3, 2, 1],
    [0, 0, 0, 2, 0, 2, 3, 2, 5, 2],
    [0, 0, 0, 0, 4, 3, 2, 0, 5, 3],
    [0, 0, 0, 0, 0, 1, 0, 0, 5, 4],
    [0, 0, 0, 0, 0, 0, 4, 0, 5, 5],
    [0, 0, 0, 0, 0, 0, 0, 2, 5, 6],
    [0, 0, 0, 0, 0, 0, 0, 0, 1, 7],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 2]
]);
// Retorna 2048

FIDDLE: http://jsfiddle.net/E9F4E/
Nota: de fato, a implementação usando o Teorema de Laplace não é a mais eficiente, mas é fácil de visualizar e funciona bem para matrizes relativamente pequenas (ordem < 11).
O jeito mais eficiente para calcular o determinante seria o método do escalonamento. Veja esse artigo. O único porém nesse método é uma pequena perda de precisão numérica. Por exemplo, em vez de 1560, a função retorna 1559.9999999999723.


text:
Q: g_hash_table_contains returns unexpected value I have a problem with this code. I can't get my expected answer. I searched for this, but I can't find anything. I can't find my mistake..
Here is my code working with g_hash_table
# include <stdio.h>
# include <glib.h>
# include <stdlib.h>

GHashTable *hash = NULL;

int check_sth_blacklist(char *sth)
{
    return g_hash_table_contains(hash,sth);
}

main()
{
    hash = g_hash_table_new(g_str_hash,g_str_equal);

    char *sth = (char*) malloc(32);

    scanf("%s",sth);
    g_hash_table_add(hash,sth);

    scanf("%s",sth);

    printf("%d\n",check_sth_blacklist(sth + sizeof(char)*2));

    free(sth);
}

in my input I'm writing:
cde
abcde

I think cde string will add to g_hash_table. then when I'm asking for string cde in abcde it returns me 0 value.

A: I believe when you pass your malloc'd string to a GHashTable under g_str_hash, you're turning over control of the string to the hash table -- it's up to it to free it when the time comes, etc.  I.e. you shouldn't use that space allocation again!
Create a new string for your comparison:
#include <stdio.h>
#include <glib.h>
#include <stdlib.h>
#include <string.h>

GHashTable *hash = NULL;

int check_sth_blacklist(char *sth)
{
    return g_hash_table_contains(hash, sth);
}

int main()
{
    hash = g_hash_table_new(g_str_hash, g_str_equal);

    char *sth = (char*) malloc(32);

    scanf("%s", sth);
    g_hash_table_add(hash, sth);

    char *nth = (char*) malloc(32);
    scanf("%s", nth);

    printf("%d\n", check_sth_blacklist(nth + 2));

    free(nth);

    g_hash_table_destroy(hash);

    return 0;
}

Let the hash manage any strings you put into it (key or value), all of which should be independent and freeable when the hash itself is destroyed.  When run, this gives me:
bash-3.2$ ./a.out
cde
abcde
1
bash-3.2$


text:
Q: Netbeans Cordova PushPlugin not working on iOS I'm building a Cordova project with Netbeans, that uses PushPlugin (https://github.com/phonegap-build/PushPlugin).
It works great on Android, but on iOS it doesn't register the device. It also doesn't give any errors.
What's also strange is that the plugin folder (com.phonegap.plugins.PushPlugin) is in the projects /plugins folder, but it's not being copied to platforms/ios/[appname]/Plugins on build.
I have this in my config.xml:
<feature name="PushPlugin">
  <param name="android-package" value="com.plugin.gcm.PushPlugin"/>
  <param name="ios-package" value="PushPlugin"/>
</feature>

And I work with the following JavaScript:

var pushNotification;

function onDeviceReady() {
  alert('ready');
  try {
    pushNotification = window.plugins.pushNotification;
    if (typeof device == 'undefined') {
      alert('device undefined');
    }
    if (device.platform == 'android' || device.platform == 'Android' || device.platform == 'amazon-fireos') {
      pushNotification.register(successHandler, errorHandler, {
        "senderID": "[senderid]",
        "ecb": "onNotification"
      });
    } else {
      alert('ios!');
      pushNotification.register(tokenHandler, errorHandler, {
        "badge": "true",
        "sound": "true",
        "alert": "true",
        "ecb": "onNotificationAPN"
      });
    }
  } catch (err) {
    txt = "There was an error on this page.\n\n";
    txt += "Error description: " + err.message + "\n\n";
    alert(txt);
  }
}

function onNotificationAPN(e) {
  // handles APNS notifications for iOS
  if (e.alert) {
    navigator.notification.alert(e.alert);
  }
  if (e.sound) {
    var snd = new Media(e.sound);
    snd.play();
  }
  if (e.badge) {
    pushNotification.setApplicationIconBadgeNumber(successHandler, e.badge);
  }
}

function onNotification(e) {
  //handles notifications for Android (left out)
}

function tokenHandler(result) {
  alert('device token = ' + result);
}

function successHandler(result) {
  alert('success = ' + result);
}

function errorHandler(error) {
  alert('error = ' + error);
}

document.addEventListener('deviceready', onDeviceReady, false);

I do see the 'ready' and 'ios!' alerts, but after that, nothing happens.

A: Problem solved! Turns out I had to copy the Plugin files and manually add them to the xcode project.


text:
Q: SQL Algorithm to Manipulate a string based on a Code Pattern My Sql Code is as  follows ,
Declare @text nvarchar(max) = 'America,Japan,Indonesia,London'
Declare @Pattern nvarchar(20) = '1001'

So For this Pattern  the sql function should return the string as 'America,London'
The String should be manipulated based on the pattern and the corresponding comma  seperated text should be removed if the pattern character is  0.
Expected Sample Output:
@Pattern           @Text
1100               'America,Japan'
1000               'America'
0100               'Japan'
1111               'America,Japan,Indonesia,London'

What is  the  Efficient way  to acheive this  results in SQL Server 2008

A: With the help of a Parse/Split Function
Declare @text nvarchar(max) = 'America,Japan,Indonesia,London'
Declare @Pattern nvarchar(20) = '1001'

Select NewString = Stuff((Select  ',' +RetVal
  From (Select A.RetSeq,A.RetVal
         From (Select * from [dbo].[udf-Str-Parse](@Text,',')) A
         Join (Select * from [dbo].[udf-Str-Parse](Stuff(Replace(Replace(@Pattern,'0',',0'),'1',',1'),1,1,''),',')) B
           on (A.RetSeq=B.RetSeq and B.RetVal=1)
     ) A
  For XML Path ('')),1,1,'')

Returns
NewString
America,London

The UDF if needed
CREATE FUNCTION [dbo].[udf-Str-Parse] (@String varchar(max),@Delimiter varchar(10))
Returns Table
As
Return (
    Select RetSeq = Row_Number() over (Order By (Select null))
          ,RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)')))
    From (Select x = Cast('<x>'+ Replace(@String,@Delimiter,'</x><x>')+'</x>' as xml).query('.')) as A
    Cross Apply x.nodes('x') AS B(i)
);
--Select * from [dbo].[udf-Str-Parse]('Dog,Cat,House,Car',',')
--Select * from [dbo].[udf-Str-Parse]('John Cappelletti was here',' ')


text:
Q: Fastest way to apply histcount on an array grouped by previous bin result I have 2 large numpy arrays which I need to bin according to some bin values. The first array needs to be binned with the data1Bins values. Then the data in the second array needs to be grouped by the result of the bins on the first array. When this grouping is done, the amount of values in each bin needs to be counted.
This counted result needs to be added as a row to a data frame and in the end the total sum of the data frames needs to be calculated so each element can be divided by the total sum value.
Despite my working solution, I'm wondering if there isn't a more elegant or faster solution. Time is a very important thing since this function will be executed many times.
So that all said I'm always happy hear possible improvements regarding this small piece of code. The current timing is 0.009527206420898438 s.
Current solution:
import pandas as pd
import numpy as np
import time

data1 = np.random.uniform(low=0, high=25, size=(50,))
data2 = np.random.uniform(low=0, high=25, size=(50,))

data1Bins = [0, *np.arange(1.5, 25, 1), 100]
data2Bins = [0, *np.arange(7.5, 360, 15), 360]

# Speed up from here ->
start = time.time()
inds = np.digitize(data1, data1Bins)

df = pd.DataFrame()

# 25 bins
for i in range(0, len(data1Bins)):
    binned_data = data2[np.asarray(inds == i).nonzero()[0].tolist()]
    count, bin_edges = np.histogram(binned_data, bins=data2Bins)
    count = np.array([(count[0] + count[-1]), *count[1:-1]])

    df = pd.concat([df, pd.DataFrame(count.reshape(-1, len(count)))])

# Set index
df = df.reset_index(drop=True)

# Get total sum
total_sum = df.sum().sum()

# Devide each element by total sum
df = df/ total_sum

df['Name'] = 'abc'
df['Id'] = 'def'
df['Nr'] = np.arange(df.shape[0])

print(time.time() - start)

print(df)

End result:
        0         1         2    3    4    5    6    7    8    9   10   11   12   13   14   15   16   17   18   19   20   21   22   23   24 Name   Id  Nr
0   0.000000  0.000000  0.000000  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  abc  def   0
1   0.020408  0.020408  0.000000  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  abc  def   1
2   0.020408  0.000000  0.000000  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  abc  def   2
3   0.020408  0.000000  0.000000  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  abc  def   3
4   0.000000  0.020408  0.000000  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  abc  def   4
5   0.000000  0.020408  0.000000  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  abc  def   5
6   0.061224  0.040816  0.020408  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  abc  def   6
7   0.000000  0.000000  0.000000  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  abc  def   7
8   0.020408  0.081633  0.000000  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  abc  def   8
9   0.000000  0.040816  0.000000  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  abc  def   9
10  0.081633  0.000000  0.000000  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  abc  def  10
11  0.000000  0.040816  0.000000  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  abc  def  11
12  0.000000  0.020408  0.020408  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  abc  def  12
13  0.000000  0.040816  0.000000  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  abc  def  13
14  0.000000  0.040816  0.000000  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  abc  def  14
15  0.000000  0.020408  0.000000  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  abc  def  15
16  0.000000  0.000000  0.020408  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  abc  def  16
17  0.000000  0.020408  0.000000  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  abc  def  17
18  0.020408  0.000000  0.000000  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  abc  def  18
19  0.040816  0.000000  0.000000  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  abc  def  19
20  0.000000  0.020408  0.000000  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  abc  def  20
21  0.020408  0.000000  0.000000  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  abc  def  21
22  0.020408  0.040816  0.000000  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  abc  def  22
23  0.020408  0.020408  0.020408  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  abc  def  23
24  0.000000  0.081633  0.000000  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  abc  def  24

A: First, here is the baseline timing I have on my machine when executing the code after the # Speed up from here comment :
5.02 ms ± 134 µs per loop (mean ± std. dev. of 10 runs, 1,000 loops each)

You will save time by appending values to a list and then creating a dataframe, rather than using pd.concat().
# [...]

data = []

for i in range(0, len(data1Bins)):
    binned_data = data2[np.asarray(inds == i).nonzero()[0].tolist()]
    count, bin_edges = np.histogram(binned_data, bins=data2Bins)
    count = np.array([(count[0] + count[-1]), *count[1:-1]])
    data.append(count)

df = pd.DataFrame(data)

# [...]

1.97 ms ± 36.5 µs per loop (mean ± std. dev. of 10 runs, 1,000 loops each)

Here are also a few improvements that will save non-significant time, but will make your code cleaner
for i in range(0, len(data1Bins)):
    # cleaner way to get binned_data
    binned_data = data2[np.where(inds == i)]
    count, bin_edges = np.histogram(binned_data, bins=data2Bins)

    # cleaner way to get the values added to the dataframe
    values = np.concatenate(([count[0] + count[-1]], count[1:-1]))
    data.append(values)

1.93 ms ± 45.4 µs per loop (mean ± std. dev. of 10 runs, 1,000 loops each)