text:
Q: Execute .NET application (no-install) from webpage (intranet) and pass argument(s)? i built an intranet on .NET MVC. I'm also building a separate planning tool in Winforms (performance choice). I would now like to 'open' the planning tool from the intranet (IE7) and pass an argument (e.g. Workorder number) so I can display the planning for that specific item. Is this possible?
I have a .application file for the Winforms application. I'm also able to change everything on both the .NET MVC intranet and the Winforms planning tool.

A: Yes you can do it.
private string _output = "";

public string Execute()
{
   try
   {
        Process process = new Process();
        process.OutputDataReceived += new DataReceivedEventHandler(process_OutputDataReceived);
        process.StartInfo.FileName = "path to exe";
        process.StartInfo.Arguments = "here you can pass arguments to exe";
        process.StartInfo.UseShellExecute = false;
        process.StartInfo.RedirectStandardOutput = true;
        Process currentProcess = Process.GetCurrentProcess();
        process.StartInfo.UserName = currentProcess.StartInfo.UserName;
        process.StartInfo.Password = currentProcess.StartInfo.Password;
        process.Start();
        process.BeginOutputReadLine();
        process.WaitForExit();
        return _output;
    }
    catch (Exception error)
    {
        return "ERROR : " + error.Message;
    }
}
private void process_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
    if (e.Data != null)
    {
        _output += e.Data + Environment.NewLine;
    }
}

It's a simple example. You can use different threads to read output and errors from exe.

A: You can't simply call the application from the HTML; that would be a security hole. However, you can have the application register to be able to handle these requests via the registry. You say "no-install", so this might be a problem. Maybe your app could modify the registry on the first load.
Anyway, the app would register to handle a specific protocol (like when you click on an itunes:// or ftp:// link).
Instead you'd have something like:
View workflow #3472

which then launches your app with the argument specified.
See http://msdn.microsoft.com/en-us/library/aa767914(VS.85).aspx . You say IE7, but this should work with other browsers, too, once the protocol is registered.


text:
Q: Git checkout remote branch of a remote repository When git clone some repository then it retrieves all branches from it:
git clone https://github.com/android/platform_build.git build1
cd build1/ && git branch -a && cd ..

then, when I use build1 as a mirror and clone it, I do not see all its remote branches (I see only build1's local master branch)
git clone build1 build2
cd build2 && git branch -a && cd ..

How can I checkout remote of remote branches ?
I know that I can checkout all remote branches in build1 mirror with command
cd build1 && for remote in `git branch -r `; do git branch --track $remote; done

Track all remote git branches as local branches
but what if I do not have access to build1 directory ?
Also, there is git ls-remote origin command which shows all remote refs, but is there any elegant way to checkout those remote of remote branches ?

A: After you clone build1 to build2, build1 is build2's origin, and build2 knows nothing about https://github.com/android/platform_build.git , which is where the "remote" branches live.  One solution may be to add https://github.com/android/platform_build.git as a remote in the configuration of build2.  To add a remote called github:
git remote add github https://github.com/android/platform_build.git

Then run a fetch to get the remote branches:
git fetch github

Now, when you run git branch -a you should see branches prefixed with remotes/github/ that correspond with those prefixed with remotes/origin in build1.
On the other hand, build2 should have a remote branch for each local branch in build1, including those that are tracking remote branches from build1's perspective.  For example, if there is a branch named foo on github, it will show up as remotes/origin/foo in build1.  If you set up a local branch to track that remote branch in build1 also called foo, then build2 should have a remotes/origin/foo as well.  Then, when foo is updated in build1 by fetching/merging changes from github's foo, those changes should show up in build2 after a fetch/pull.

redpajama_set_name: RedPajamaStackExchange


text:
Q: DFT Name to be used in SSIS Event Manager I would like to know if there is any way to use the DFT Task Name (as a variable) inside the Event Handlers task?
But now when I use Systech:TaskName it displays the name of the OnError task and I would like to have the name of source DFT task used inside the OnError task.
Thanks!

A: In the OnError event handler, you have the @[System::SourceName] variable available to you that shows you the task that generated the error.

You also have SourceID available to you there in case you have nested Tasks with the same name


text:
Q: Parsing JSON before iOS5 Since it seems that NSJSONSerialization class is only available in iOS 5.0+ (NSJSONSerialization Class Reference), is there another option to parse JSON objects prior that version?
Thanks

A: SBJSON is great option, I have used in it two app store apps.

A: There are many options on github, for example SBJSON.

A: There was no JSON support prior to iOS 5. You can use third party code from here:
https://github.com/johnezang/JSONKit

A: Have a look at JSONKit.
I've used it prior to iOS5 and it has better performance, and is easier to use than SBJSON.


text:
Q: how to edit blueprint for automatically running a command in docker container run by cloudify I want to run a docker container of RYU controller in cloudify ways. I have written a blueprint file with which I can create relevant deployment and finally start the docker container.
The problem is, the controller (within the docker container) needs to implement a script to function but I don't know how to modify the blueprint file for automatically running the script. Every time, I have to type docker exec CONTAINER ryu-manager /path/simple_switch.py for the goal.
So does anyone know where the command should be put in the blueprint. I tried to include it in
interfaces:
  cloudify.interfaces.lifecycle:
    create:
      implementation: docker.docker_plugin.tasks.create_container
      inputs:
        params:
          ports:
            - { get_input: docker_port }
          stdin_open: true
          tty: true
          command: /bin/bash

    start:
      implementation: docker.docker_plugin.tasks.start
      inputs:
        params:
          port_bindings: { get_input: container_port_binding }
          command: docker exec ryu ryu-manager /ryu/ryu/app/simple_switch.py
          # here ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑

but received an error of unexpected parameter.
Thanks for your time and any opinions would be appreciated~

Or let me put in this way, if anyone knows, which part in the cloudify blueprint matches docker exec?

A: I use Cloudify a lot and I use Docker a lot. The Docker Plugin is kind of "nice to have", but it is really not necessary. You can just run commands like "docker exec" and "docker run" from inside of the the Cloudify Script plugin and get the same result, and you do not need to figure out a different interface for working  with Docker.
For example if I have this cloudify blueprint (simplified):
yaml
node_templates:
  my_app:
    type: cloudify.nodes.SoftwareComponent
    interfaces:
      cloudify.interfaces.lifecycle:
        create:
          implementation: scripts/create.sh
        start:
          implementation: scripts/start.sh
    relationships:
    - type: cloudify.relationships.depends_on
      target: vm

I can call such scripts:
scripts/create.sh:
docker run -d ryu
scripts/start.sh
docker exec -it ryu ryu-manager /ryu/ryu/app/simple_switch.py

A: Before I answer, I have no experience in cloudify, but I have looked at the documentation to see what is it all about. Here are my pointers to you.
First of all I looked at the docker plugin at below URL
https://github.com/cloudify-cosmo/cloudify-docker-plugin/blob/master/docker_plugin/tasks.py
And it doesn't have any execute statement as such. So you should remove the command from both your create and start lifecycles. Doing that would make sure the default image command runs.
Now your task is to execute an additional command inside the container. Since the docker plugin doesn't support that operation, your best bet is to get the container ID of the newly created container. This should be possible using some output parameter capturing
Now you want to execute a command on your local machine or the remote machine where docker is installed. This you can setup as another lifecycle which takes the ID from the created container and executes the docker exec <ID> ryu-manager /ryu/ryu/app/simple_switch.py command on that main docker host


text:
Q: How to write inside a panel box using a label? Here is the code for writing the letter G with * representation inside text box. Now I want to write this inside a panel using a label. How can I do it?
I have drawn label box inside panel and want to write inside label.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication31
{
  public partial class Form1 : Form {

    public Form1() {
      InitializeComponent();
    }

    private void A(object sender, EventArgs e) {
      int row, column;

      for (row = 0; row <= 6; row++) {
        for (column = 0; column <= 6; column++) {
          if ((column == 1 && row != 0 && row != 6) ||
              ((row == 0 || row == 6) && column > 1 && column < 5) ||
               (row == 3 && column > 2 && column < 6) ||
               (column == 5 && row != 0 && row != 2 && row != 6))
            textBox1.AppendText("*");
          else
            textBox1.AppendText(" ");
        }

        textBox1.AppendText(Environment.NewLine);
      }
      textBox1.AppendText(Environment.NewLine);
    }
  }
}

A: For a TextBox:
textBox1.AppendText(text);

For a Label:
label1.Text += text;

Build your text separately using a StringBuilder.
StringBuilder builder = new StringBuilder();

int row, column;

for (row = 0; row <= 6; row++)
{
    for (column = 0; column <= 6; column++)
    {
        if ((column == 1 && row != 0 && row != 6) ||
            ((row == 0 || row == 6) && column > 1 && column < 5) ||
                (row == 3 && column > 2 && column < 6) ||
                (column == 5 && row != 0 && row != 2 && row != 6))
            builder.Append("*");
        else
            builder.Append(" ");
    }

    builder.Append(Environment.NewLine);
}
builder.Append(Environment.NewLine);

string text = builder.ToString();

A: Assuming you are able to do your need using a textbox,
However, label controls are not meant to be multi-line by default. Textboxes can be made like that using the multiline attribute (Hence you need to check compatibility)
Refactor your code as
private string CreateGraphicString() {
     StringBuilder builder = new StringBuilder();
    int row, column;

  for (row = 0; row <= 6; row++) {
    for (column = 0; column <= 6; column++) {
      if ((column == 1 && row != 0 && row != 6) ||
          ((row == 0 || row == 6) && column > 1 && column < 5) ||
           (row == 3 && column > 2 && column < 6) ||
           (column == 5 && row != 0 && row != 2 && row != 6))
        builder.Append("*");
      else
        builder.Append(" ");
    }

    builder.AppendLine();
  }
  builder.AppendLine();
}
 return builder.ToString();
}

myLabel.Text = builder.AppendLine();
myTextbox.Text = builder.AppendLine();


text:
Q: Populate cells in Excel with text from another sheet I have a table in Excel with data
Type, Reason
===============
1, Some text
1, Other text
2, More text
2, Even more text

What I want is to extract the reasons based on the type. So in another sheet in my workbook, I want to select the type with a single cell, and then get the list of reasons (without any empty cells/rows).
I guess I would need =INDEX() to select the row numbers, but I don't know how to filter, so I only get those with e.g. type=2.
I know it is easy in VBA, but is it also possible with standard functions?


text:
Q: With powershell a Gitlab-ci job passed while failure occured My gitlab-ci.yml contains follwing Lint code
stages:
  - build

build:
  stage: build
  script:
  - exit 1

When running, the job doesn't fail!
Running with gitlab-runner 13.10.0 (54944146)
Preparing the "shell" executor
Using Shell executor...
Preparing environment
Getting source from Git repository
Fetching changes with git depth set to 50...
Reinitialized existing Git repository
Checking out b70613dd
git-lfs/2.13.2 (GitHub; windows amd64; go 1.14.13; git fc664697)
Skipping Git submodules setup
Executing "step_script" stage of the job script
00:03
$ exit 1
Cleaning up file based variables
00:03
Job succeeded

How to avoid having false successes while the job should fail.

A: PowerShell 5 (the Windows default PS instance) returns a false result. When using PowerShell Core, the problem no longer appears.


text:
Q: Android: tabs within tabs I'm currently trying to create an application according the customer's specs, and these include a double tab set.
Meaning that the user needs to click in a tab at the bottom, and for example in the first tab, he will also see a set of tabs at the top where he can click (but when clicking in these, only the ones at the top will change, while the tabs at the bottom will remain the same).
How could I perform this with Android?
So far I could only implement the normal tabs creating a root item 'TabHost' just like this:
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_alignParentTop="true" >
        </FrameLayout>

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true" />
    </RelativeLayout>

</TabHost>

Thanks a lot in advance!

A: I found this, thanks to the ActionBar (and SherlockActionBar for pre-Honeycomb devices):
http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/app/ActionBarTabs.html
and also this:
http://www.youtube.com/watch?v=gMu8XhxUBl8


text:
Q: How to lazy load a module from nrwl workspace libs folder? I have a main app named myapp. I have configured my routes as below:
const routes: Routes = [
  { path: 'home', loadChildren: 'libs/home/home.module#HomeModule'},
  { path: 'admin', loadChildren: 'libs/admin/admin.module#AdminModule' },

  { path: '', redirectTo: '/home', pathMatch: 'full' },
  { path: '**', component: PageNotFoundComponent }
];

My home and admin are modules with its own routing and are placed in libs. When I run my application my modules are not getting loaded. I guess this is simply a path issue.. can someone please guide me how to properly configure the lazy loading modules from the library folder in nrwl workspace?
Here is the error I get:
ERROR Error: Uncaught (in promise): Error: Cannot find module 'libs/home/home.module'.
Error: Cannot find module 'libs/home/home.module'.
    at eval (eval at ../../../../../apps/myapp/src/$$_lazy_route_resource lazy recursive (main.bundle.js:6), <anonymous>:5:9)
    at ZoneDelegate.invoke (webpack-internal:///../../../../zone.js/dist/zone.js:388)

Note: I updated my tsconfig.app.json and tslint.json as follows:
tslint.json
"nx-enforce-module-boundaries": [
      true,
      {
        "lazyLoad": [
          "home",
          "admin"
        ],
        "allow": []
      }
    ]

and tsconfig.app.json:
 "include": [
    "**/*.ts",
    /* add all lazy-loaded libraries here: "../../../libs/my-lib/index.ts" */
    "../../../libs/home/index.ts",
    "../../../libs/admin/index.ts"
  ],

thanks.

A: https://nrwl.io/nx/guide-nx-workspace#create-an-angular-module-lib
ng generate lib mymodule --routing
    --lazy --parentModule=apps/myapp/src/myapp.module.ts

A: With Angular v8 loading your lazy-loaded libraries works this way:
{ path: 'home', loadChildren: () => import('@yourprefix/home').then(m => m.HomeModule) },

A: I had a similar error. I didn't fully understand the reasons, so following are my assumptions:
For lazy loading you should do:

*

*Export all lazy modules in distinct index.ts files. You should
not import those files;

*Add references to those index.ts files in app-level tsconfig.app.json. Pay attention - not in root tsconfig.json, but in app/tsconfig.app.json;

*Perhaps you should do RouterModule.forChild(routes) in your lazy lib's lib.module.ts;

*Make sure you do not import lazy modules anywhere, and don't import index.ts that exports lazy modules;

A: If you had forgot add parameter --parentModule when create your lib, you can fix this by adding your lib into
apps/yourapp/tsconfig.app.json file into you app directory and add you module to
"include": ["**/*.ts", "../../libs/auth/src/index.ts", "../../libs/your-libname/src/index.ts"]

and in app.module.ts

{
path: 'mypath',
loadChildren: '@workspace/your-libname#YourLibnameModule'
}


text:
Q: Why is my mongodb connection not working , even though everything is installed? Homebrew, macos I've installed mongodb using homebrew and its running as a service,
[~]$ brew services list
Name              Status  User      File
mongodb-community started <User> ~/Library/LaunchAgents/homebrew.mxcl.mongodb-community.plist
postgresql        started <User> ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist

I can connect to the mongo shell and connect via compass, however when I connect via an application. using the local connection string I get the following,
error - MongoServerSelectionError: connect ECONNREFUSED ::1:27017

I've ran mongod for testing and I got the following,
{"t":{"$date":"2021-11-26T13:39:56.991+00:00"},"s":"I",  "c":"NETWORK",  "id":4915701, "ctx":"-","msg":"Initialized wire specification","attr":{"spec":{"incomingExternalClient":{"minWireVersion":0,"maxWireVersion":13},"incomingInternalClient":{"minWireVersion":0,"maxWireVersion":13},"outgoing":{"minWireVersion":0,"maxWireVersion":13},"isInternalClient":true}}}
{"t":{"$date":"2021-11-26T13:39:56.995+00:00"},"s":"I",  "c":"CONTROL",  "id":23285,   "ctx":"main","msg":"Automatically disabling TLS 1.0, to force-enable TLS 1.0 specify --sslDisabledProtocols 'none'"}
{"t":{"$date":"2021-11-26T13:39:56.995+00:00"},"s":"W",  "c":"ASIO",     "id":22601,   "ctx":"main","msg":"No TransportLayer configured during NetworkInterface startup"}
{"t":{"$date":"2021-11-26T13:39:56.995+00:00"},"s":"I",  "c":"NETWORK",  "id":4648602, "ctx":"main","msg":"Implicit TCP FastOpen in use."}
{"t":{"$date":"2021-11-26T13:39:56.996+00:00"},"s":"W",  "c":"ASIO",     "id":22601,   "ctx":"main","msg":"No TransportLayer configured during NetworkInterface startup"}
{"t":{"$date":"2021-11-26T13:39:56.997+00:00"},"s":"I",  "c":"REPL",     "id":5123008, "ctx":"main","msg":"Successfully registered PrimaryOnlyService","attr":{"service":"TenantMigrationDonorService","ns":"config.tenantMigrationDonors"}}
{"t":{"$date":"2021-11-26T13:39:56.997+00:00"},"s":"I",  "c":"REPL",     "id":5123008, "ctx":"main","msg":"Successfully registered PrimaryOnlyService","attr":{"service":"TenantMigrationRecipientService","ns":"config.tenantMigrationRecipients"}}
{"t":{"$date":"2021-11-26T13:39:56.997+00:00"},"s":"I",  "c":"CONTROL",  "id":4615611, "ctx":"initandlisten","msg":"MongoDB starting","attr":{"pid":6303,"port":27017,"dbPath":"/data/db","architecture":"64-bit","host":"Bens-MacBook-Pro.local"}}
{"t":{"$date":"2021-11-26T13:39:56.997+00:00"},"s":"I",  "c":"CONTROL",  "id":23351,   "ctx":"initandlisten","msg":"{sysctlName} unavailable","attr":{"sysctlName":"machdep.cpu.extfeatures"}}
{"t":{"$date":"2021-11-26T13:39:56.997+00:00"},"s":"I",  "c":"CONTROL",  "id":23403,   "ctx":"initandlisten","msg":"Build Info","attr":{"buildInfo":{"version":"5.0.3","gitVersion":"657fea5a61a74d7a79df7aff8e4bcf0bc742b748","modules":[],"allocator":"system","environment":{"distarch":"x86_64","target_arch":"x86_64"}}}}
{"t":{"$date":"2021-11-26T13:39:56.997+00:00"},"s":"I",  "c":"CONTROL",  "id":51765,   "ctx":"initandlisten","msg":"Operating System","attr":{"os":{"name":"Mac OS X","version":"21.1.0"}}}
{"t":{"$date":"2021-11-26T13:39:56.997+00:00"},"s":"I",  "c":"CONTROL",  "id":21951,   "ctx":"initandlisten","msg":"Options set by command line","attr":{"options":{}}}
{"t":{"$date":"2021-11-26T13:39:57.001+00:00"},"s":"E",  "c":"CONTROL",  "id":20568,   "ctx":"initandlisten","msg":"Error setting up listener","attr":{"error":{"code":9001,"codeName":"SocketException","errmsg":"Address already in use"}}}
{"t":{"$date":"2021-11-26T13:39:57.002+00:00"},"s":"I",  "c":"REPL",     "id":4784900, "ctx":"initandlisten","msg":"Stepping down the ReplicationCoordinator for shutdown","attr":{"waitTimeMillis":15000}}
{"t":{"$date":"2021-11-26T13:39:57.002+00:00"},"s":"I",  "c":"COMMAND",  "id":4784901, "ctx":"initandlisten","msg":"Shutting down the MirrorMaestro"}
{"t":{"$date":"2021-11-26T13:39:57.002+00:00"},"s":"I",  "c":"SHARDING", "id":4784902, "ctx":"initandlisten","msg":"Shutting down the WaitForMajorityService"}
{"t":{"$date":"2021-11-26T13:39:57.002+00:00"},"s":"I",  "c":"NETWORK",  "id":4784905, "ctx":"initandlisten","msg":"Shutting down the global connection pool"}
{"t":{"$date":"2021-11-26T13:39:57.002+00:00"},"s":"I",  "c":"NETWORK",  "id":4784918, "ctx":"initandlisten","msg":"Shutting down the ReplicaSetMonitor"}
{"t":{"$date":"2021-11-26T13:39:57.002+00:00"},"s":"I",  "c":"SHARDING", "id":4784921, "ctx":"initandlisten","msg":"Shutting down the MigrationUtilExecutor"}
{"t":{"$date":"2021-11-26T13:39:57.002+00:00"},"s":"I",  "c":"ASIO",     "id":22582,   "ctx":"MigrationUtil-TaskExecutor","msg":"Killing all outstanding egress activity."}
{"t":{"$date":"2021-11-26T13:39:57.003+00:00"},"s":"I",  "c":"COMMAND",  "id":4784923, "ctx":"initandlisten","msg":"Shutting down the ServiceEntryPoint"}
{"t":{"$date":"2021-11-26T13:39:57.003+00:00"},"s":"I",  "c":"CONTROL",  "id":4784925, "ctx":"initandlisten","msg":"Shutting down free monitoring"}
{"t":{"$date":"2021-11-26T13:39:57.003+00:00"},"s":"I",  "c":"CONTROL",  "id":4784927, "ctx":"initandlisten","msg":"Shutting down the HealthLog"}
{"t":{"$date":"2021-11-26T13:39:57.003+00:00"},"s":"I",  "c":"CONTROL",  "id":4784928, "ctx":"initandlisten","msg":"Shutting down the TTL monitor"}
{"t":{"$date":"2021-11-26T13:39:57.003+00:00"},"s":"I",  "c":"CONTROL",  "id":4784929, "ctx":"initandlisten","msg":"Acquiring the global lock for shutdown"}
{"t":{"$date":"2021-11-26T13:39:57.003+00:00"},"s":"I",  "c":"-",        "id":4784931, "ctx":"initandlisten","msg":"Dropping the scope cache for shutdown"}
{"t":{"$date":"2021-11-26T13:39:57.003+00:00"},"s":"I",  "c":"FTDC",     "id":4784926, "ctx":"initandlisten","msg":"Shutting down full-time data capture"}
{"t":{"$date":"2021-11-26T13:39:57.003+00:00"},"s":"I",  "c":"CONTROL",  "id":20565,   "ctx":"initandlisten","msg":"Now exiting"}
{"t":{"$date":"2021-11-26T13:39:57.003+00:00"},"s":"I",  "c":"CONTROL",  "id":23138,   "ctx":"initandlisten","msg":"Shutting down","attr":{"exitCode":48}}

from what I can tell everything mongodb wise is all setup so I'm not sure why I'm getting the error.
I'm using macos monterey and vscode.

A: @WernfriedDomscheit, got it working.
Had to change the config /opt/homebrew/etc/mongod.conf net block too.
net:
  ipv6: true
  port: 27017
  bindIpAll: true


text:
Q: python finding average fuzzy ratio of all lines I am trying a code to find the average fuzzyratio of all the lines in the file with the word good:
from fuzzywuzzy import fuzz
from collections import defaultdict
with open(qwer.txt, 'r') as my_file:
     for line in my_file:
        for part in line.split():
          a=line
          b='good'
          fuzziness = fuzz.ratio(a,b)
          filenames2fuzz[line].append(fuzziness)

    best_fuzziness_ratio = 0
    for k, v in filenames2fuzz.items():
        if max(v) > best_fuzziness_ratio:
            best_fuzzy_line = k
            best_fuzziness_line_ratio = max(v)
    average=v/n(v)#<-not sure
    print average

how to print the average fuzzyratio of all lines with the word good and print the average?
please help!answers would be appreciated!

A: For a memory-efficient solution, I would probably do something like that.
def good_ratio(a):
    return fuzz.ratio(a, 'good')

with open('qwer.txt', 'r') as my_file:
   my_sum, my_len = reduce(lambda a, b: (a[0]+b[0], a[1]+b[1]), ((good_ratio(i), 1) for i in my_file))
   print(my_sum/my_len)

Please note that this is a float division in python3 and you will need something like my_sum/(float)my_len in python2.
Also, you might want to filter the lines with 'good' (or maybe 'good ' or something else), for instance with ((good_ratio(i), 1) for i in my_file if 'good' in i).

A: I think you're shooting for something like this:
 div = 0
 ratio_total = 0
 for line in my_file:
     for word in line:
           ratio = fuzz.ratio(word, 'good') # might want to use partial_ratio instead
           if ratio > 0: # or some threshold:
                ratio_total += ratio
                div += 1

  print("Average ratio: %s" % (ratio_total/div,))

I think what you want to do is go through each word in a line and compare each word to "good".  This should get you close?


text:
Q: PHP query parsing couchdb I am new to php so, need any help for this issue
I tried to run query
localhost/ls-test/_design/app-views/_view/timestamp-measurement?descending=true&include_docs=true

and get json return something like this format:
{"total_rows":441740,"offset":0,"rows":[
{"id":"123","key":[2013,2],"value":["1","PowerConsumption","0.0"],"doc":{"_id":"5446691910660799","SourceType":"SENSOR","SourceId":"4294403072","Property":"PowerConsumption","value":"0.0","}},
{"id":"124","key":[2013,2],"value":["228224","Motion","false"],"doc":{"_id":"5446688472521031","SourceType":"SENSOR","SourceId":"228224","Property":"Motion","value":"false","timestamp":"2013-02-12 17:06:06.768"}}
...]}

so, how do I further query it in PHP that my result only displayed based on specific value e.g only list of documents with SourceId:228224

A: You would json_decode in PHP then work with your associative array.
http://php.net/manual/en/function.json-decode.php


text:
Q: ARM Assembly. How can I take both char and decimal input in the same line I have an output that says "Put in 1, 2, or 3 to continue, or press T to end"
Handling either just char, or just decimal is easy, but I can not figure out how to accept an input that can handle both.
My (poor) attempt so far looks like this.
*code to get input here, goes into r1*
cmp r1, #'T'
beq exit
cmp r1, #1
blt tryagain
cmp r3, #3
bgt tryagain

.data
.balign 4
numInput: .asciz "%d"

Of course I understand this isn't how you handle this situation, but I have no clue what to do


text:
Q: Magento sends too many confirmation emails I have a Magento store that apparently sends too many confirmations emails on an order. My theory is that the emails are resent all over again to the store admin when the customer tries to shop entering an inexistent email address.
How can I debug and/or fix this?
Thanks

A: Is the customer's email getting returned to sender? If so try setting the sender address to a blackhole, a mailbox that drops all messages. It's not uncommon for sites to have a "noreply@" address for this purpose.


text:
Q: How to use the ansible.runner module on Ubuntu 14.04.5? I tried to import ansible.runner in a Python script but I get the following error:

Traceback (most recent call last):
  File "./boot-device.py", line 5, in
    import ansible.runner
ImportError: No module named runner

When I search the ansible package, I can not find any file called runner.
I have installed ansible 2.1.1.0-1ppa~trust and python 2.7.5-5ubuntu3.
Which package I need to use Ansible's runner module?

A: There is an issue at Ansible's GitHub repository about this. The runner module does not exist anymore because of backward-incompatible changes in Ansible's Python API. You would have to change your script accordingly as detailed in Ansible's documentation about its Python API.
P.S.: I was considering providing actual code for the changes you need to make but that would seem out of scope for Ask Ubuntu and would fit in better at Stack Overflow. If you have questions about Ansible's Python API, you should ask them at Stack Overflow.


text:
Q: java script extract link from string so I have this code on string:
<html class="
no - js ie ie6 lt - ie9 lt - ie8 lt - ie7 search - context en_US " lang="
en - US "> <![endif]--><!--[if IE 7]>         <html class="
no - js ie ie7 lt - ie9 lt - ie8 search - context en_US " lang="
en - US "> <![endif]--><!--[if IE 8]>         <html class="
no - js ie ie8 lt - ie9 search - context en_US " lang="
en - US "> <![endif]--><!--[if IE 9]>         <html class="
no - js ie9 search - context en_US " lang="
en - US "> <![endif]--><!--[if gt IE 9]><!--> <html class="
no - js search - context en_US " lang="
en - US "> <!--<![endif]-->    <head><title>art anime | Tumblr</title><!--[if ie]><meta http-equiv="
X - UA - Compatible " content="
IE = Edge, chrome = 1 "/><![endif]--><meta http-equiv="
Content - Type " content="
text / html;
charset = utf - 8 ">    <meta http-equiv="
x - dns - prefetch - control " content="
off ">    <meta name="
application - name " content="
Tumblr ">    <meta name="
msapplication - TileColor " content="
#3645d">    <meta name= "msapplication-TileImage"
content = "https://assets.tumblr.com/images/msfavicon.png?_v=245323c5cb69e705ea213d9ed60e543a" > < link rel = "shortcut icon"
href = "https://assets.tumblr.com/images/favicons/favicon.ico?_v=8bfa6dd3e1249cd567350c606f8574dc"
type = "image/png" > < meta name = "p:domain_verify"
content = "d06c4fa470a9a6935c9a7b43d57eb7d2" > < link rel = "apple-touch-icon"
sizes = "57x57"
href = "https://assets.tumblr.com/images/apple-touch-icon-57x57.png?_v=81406f92242ce0166328bc17e4473e6e"
type = "image/png" > < link rel = "apple-touch-icon"
sizes = "60x60"
href = "https://assets.tumblr.com/images/apple-touch-icon-60x60.png?_v=20e3957f7027b72d5aa60085204ae63c"
type = "image/png" > < link rel = "apple-touch-icon"
sizes = "72x72"
href = "https://assets.tumblr.com/images/apple-touch-icon-72x72.png?_v=8df24181ba31066d8710f67c9a287241"
type = "image/png" > < link rel = "apple-touch-icon"
sizes = "76x76"
href = "https://assets.tumblr.com/images/apple-touch-icon-76x76.png?_v=455617cae13eff40acffac5e489bde50"
type = "image/png" > < link rel = "apple-touch-icon"
sizes = "120x120"
href = "https://assets.tumblr.com/images/apple-touch-icon-120x120.png?_v=5604f95b165810101ea055f2cb5206b9"
type = "image/png" > < link rel = "apple-touch-icon"
sizes = "128x128"
href = "https://assets.tumblr.com/images/apple-touch-icon-128x128.png?_v=fd39307925fa7f1ada28b08d67e93da1"
type = "image/png" > < link rel = "apple-touch-icon"
sizes = "144x144"
href = "https://assets.tumblr.com/images/apple-touch-icon-144x144.png?_v=dfd5b392d423c5f0278d9f498abda2fa"
type = "image/png" > < link rel = "apple-touch-icon"
sizes = "152x152"
href = "https://assets.tumblr.com/images/apple-touch-icon-152x152.png?_v=73c2019bf6a75f7e476e01ba136cebec"
type = "image/png" > < link rel = "apple-touch-icon"
sizes = "180x180"
href = "https://assets.tumblr.com/images/apple-touch-icon-180x180.png?_v=00127c0342d97d5f36cfd8aa6439ca10"
type = "image/png" > < link rel = "apple-touch-icon"
sizes = "195x195"
href = "https://assets.tumblr.com/images/apple-touch-icon-195x194.png?_v=0"
type = "image/png" > < link rel = "apple-touch-icon"
sizes = "196x196"
href = "https://assets.tumblr.com/images/apple-touch-icon-196x196.png?_v=bb4b7eef0ef8e28101acdf2f0c265cc7"
type = "image/png" > < link rel = "apple-touch-icon"
sizes = "228x228"
href = "https://assets.tumblr.com/images/apple-touch-icon-228x228.png?_v=0c7874da12e347c2bdf95e5baa3f396a"
type = "image/png" > < link rel = "canonical"
href = "https://www.tumblr.com/search/art%20anime/recent" > < meta name = "robots"
id = "robots"
content = "noodp,noydir" > < meta name = "description"
id = "description"
content = "Tumblr is a place to express yourself, discover yourself, and bond over the stuff you love. It's where your interests connect you with your people." > < meta name = "keywords"
id = "keywords"
content = "tumblelog, blog, tumblog, tumbler, tumblr, tlog, microblog" > < meta name = "viewport"
id = "viewport"
content = "width=960" > < meta name = "tumblr-form-key"
id = "tumblr_form_key"
content = "!1231553203788|mOZjoWSzPU6eNRkpuhEtzoBJmdA" > < meta name = "tumblr-gpop"
id = "tumblr_gpop"
content = "Tumblr" > < meta name = "og:title"
id = "og_title"
content = "art anime | Tumblr" > < meta name = "og:image"
id = "og_image"
content = "https://66.media.tumblr.com/06afadc2cafb6945065a4b10d61f3b45/tumblr_poqjiuUUGO1tvlw71o1_r1_500.jpg" > < script type = "application/ld+json" >

I want to get content="https://66.media.tumblr.com ... etc
link from this string and for you know the string is updating every hour
I try this way not working I result -1 and 0
on google script ( java script ) cods
function urll() { var response =
  UrlFetchApp.fetch("https://www.tumblr.com/search/art+anime/recent");
  var str = response.getContentText(); var m=str.search('is="og_image"
  content="(^"*)'); Logger.log(m);
}

A: Use jquery to grab it. Per your example above, there is a unique id of og_image, so use that to get the meta element, then narrow it down to the content attribute.
$("meta #og_image").attr("content");

Assuming you already have that whole mess in a single variable myString:
var regex = /66\.[^"]*/;
var myLink = myString.match(regex);

myLink[0] will be the url.
To make this answer a bit more useful for other similar situations rather than just this niche case, if you're trying to pull a link out of a long string like this that contains many, you can use:
var regex = /http[^"]*/g;
var links = myString.match(regex);

That will give you an array of all the links.
links[links.length-1];

Will be the last one, which is what you want in this case.

A: You can use regular expression like 'is="og_image" content="(^"*)' it will take every content url
If you need only last one, you can add the id parameter validation also


text:
Q: Neo4j Spring Data Neo4j 4 cascade delete In my Neo4j/SDN4 project I have a complex hierarchy of node entitles with a many linked object of a different types. I'm working on Like/Dislike functionality and every node in my system can have associated list of Like objects.
Right now I'm working on the delete query. The issue is that if I'm going to delete a root node of a big hierarchy, I have to find Like nodes associated with every type of the nodes in this structure and delete them separately.
So, I just wondering is there in Neo4j/SDN 4 an option.. something like cascade delete in RDBMS systems that can be used for this purpose in order to avoid a huge Cypher query ?

A: Cascade delete is not available at the moment in neoj4-ogm/SDN (March 2017).
See a feature request in github https://github.com/neo4j/neo4j-ogm/issues/273
Your best option with SDN is to create a custom repository query that will delete both Like nodes and the root node:
@Query("MATCH (e:Entity)-[r]-(like) " +
       "WHERE e.prop = {prop} " +
       "DELETE e,r,like"
void deleteEntity(@Param("prop") String prop);

A: In a similar case, we use apoc-triggers. For example:
Add trigger
CALL apoc.trigger.add('removeHierarchy','
  UNWIND {deletedRelationships} AS rs WITH rs WHERE type(rs) = "LIKE"
  MATCH (C:Node) WHERE C = endNode(rs)
  DETACH DELETE C
', {phase:'before'});

Initial tree
UNWIND RANGE(1,100) as cid
WITH cid,
     toInteger(rand()*cid) as pid
MERGE (P:Node {id: pid})
MERGE (C:Node {id: cid})
MERGE (P)-[:LIKE]->(C)

Delete root
MATCH (N:Node {id: 0}) DETACH DELETE N


text:
Q: HABTM association Im trying to create a HABTM association between my products and tags tables. I ran the automated migration in my terminal as:
rails generate migration create_products_tags_join_table

then
rake db:migrate

After I ran those commands I assumed that my migration file would look something like what I read on the http://guides.rubyonrails.org/association_basics.html But instead my migration file looks like this
class CreateProductsTagsJoinTable < ActiveRecord::Migration
  def up
  end

  def down
  end
end

Do I need to hard code in the migration within these methods and then run the rake db:migrate command again?

A: There are way's you can name your migration to get the migration auto generate definition tags but I just do these types of things manually.
In your Case you need 3 tables:

*

*products

*tags

*products_tags (alphabetical order matters here.  This is your join table).

Products Table Migration
class CreateProductsTable < ActiveRecord::Migration
  def change
    create_table :products do |t|
      # whatever you want here...
    end
  end
end

Tags Table Migration
class CreateTagsTable < ActiveRecord::Migration
  def change
    create_table :tags do |t|
      # whatever you want here...
    end
  end
end

Join Table Migration
class CreateProductsTagsJoinTable < ActiveRecord::Migration
  def change
    create_table :products_tags , :id => false, force: true do |t|
      t.integer :product_id
      t.integer :tag_id
    end
  end
end

A: Pretty sure if you want some stuff filled out, you'd need to generate a model, not a migration.
So, something like:
rails generate model productstags
That generates the following migration file:
20140930204336_create_productstags.rb
class CreateProductstags < ActiveRecord::Migration
  def change
    create_table :productstags do |t|
  t.timestamps
end

end
end
You'd need to define any fields either manually here or in the model generation.   But, if you generate a migration you have to define what you're doing.   Like, say I wanted to add a join_id field that is an integer to my new ProductsTags table.
rails g migration add_join_id_to_productstags join_id:integer
That generates the following.
class AddJoinIdToProductstags < ActiveRecord::Migration
  def change
    add_column :productstags, :join_id, :integer
  end
end
Pretty sure you just need to go that route.


text:
Q: Getting a hold of locals() from surrounding frame I'm trying to replace my Template(s).substitute("$a,$b", locals()) with something short like
sub("$a,$b")

However, I don't have access to locals of surrounding scope inside sub(), any idea how to get them?
One possible workaround I found is to throw an exception, catch it, and step along the frames to find the previous frame, but perhaps there's an easier way?
import traceback, sys, code
try:
  2/0
except Exception as e:
  type, value, tb = sys.exc_info()
  traceback.print_exc()
  last_frame = lambda tb=tb: last_frame(tb.tb_next) if tb.tb_next else tb
  frame = last_frame().tb_frame
  ns = dict(frame.f_globals)

A: Try using sys._current_frames() instead of raising exception.
Possible alternatives: sys._getframe(), inspect.currentframe(), inspect.stack()
I cant think of better solution, than analysing frames.

A: You can access it directly viasys._getframe(), although it's only guaranteed to work with CPython.
from string import Template
import sys

def sub(template):
    namespace = sys._getframe(1).f_locals  # caller's locals
    return Template(template).substitute(namespace)

a, b = 1, 42
print sub("$a,$b")  # -> 1,42


text:
Q: Flutter FFMPEG Increases in processing time based on size of video even when only cutting the same size I am by no means an expert with ffmpeg. But I'm finding it strange that the the time to create a gif and trim that section is increasing so much based on the size of the video since I am always grabbing only three seconds.
I am using flutter FFmpeg.
-ss 0:00:01.000000, -i /data/user/0/com.example.example/cache/image_picker1475407716366431469.mp4 -t, 0:00:03.000000 -avoid_negative_ts make_zero, -vf fps=10,scale=320:-1:flags=lanczos,split[s0][s1];[s0]palettegen[p];[s1][p]paletteuse, -loop 0
Is there a command to make sure that ffmpeg doesn't concentrate on the entire video, and only concentrates on the three seconds I am getting in -t, so that the time doesn't increase greatly based on the video size. Or is this just normal for ffmpeg. Does it have to parse the entire video, before creating the gif.

A: I found a solution for anyone else looking. For some reason its much faster to just trim the original video and then make a gif. So just running '-c:v copy ' on the original video and then running the above command cut the processing time on a 3 minute video down from 1 minute 40 seconds to 10 seconds.


text:
Q: Calculating Short Circuit Current when Nortonizing a Circuit My objective is to find v (voltage drop across 8 ohm) in the below circuit. I was able to thevenize the circuit successfully (V thevenin = 12 V and R thevenin = -2 ohm) and find v. But I find it difficult to apply Norton's Theorem in the below circuit.

simulate this circuit – Schematic created using CircuitLab
The Norton equivalent resistance is easy to find (-2 ohm). To find the short circuit current, I shorted the 8 ohm resistor. This will also short the 4A current source and will hence become redundant (No interaction with left side of circuit). This reduces to the following circuit:

simulate this circuit
From the above circuit I wrote the following:
\$i_{N}=-(10-i)=i-10\$
\$\Longrightarrow i=10+i_{N}\$
Applying KVL to the mesh:
\$-2i+4i=0\$
\$i=0\$
\$\Longrightarrow i_{N}=-10 A\$
This is not the same as:
\$\dfrac{V_{th}}{R_{th}}=-\dfrac{6}{7}A\$
What have I done wrong? Have I overlooked something?
Edit:
I will show here how I calculated R thevenin. I first detached the 8 ohm resistor from the circuit and nullified all independent sources.
Since the circuit has dependent sources, I attach a 1 V voltage source across the terminals AB.

simulate this circuit
\$R_{Th}\$ then becomes \$\dfrac{1}{i_{0}}\$. The idea is to find \$i_{0}\$ which is the same as \$i\$.
You can read more here:
https://www.allaboutcircuits.com/technical-articles/thevenin-theorem-dependent-source-circuits/

A: Guidances only:
1) Shorting the 8 Ohm resistor doesn't make the 4 amperes source redundant. 4 A is a part of the short circuit current. The rest comes from the controlled source.
2) Norton's theorem isn't a method how the equivalent should be calculated, Norton's theorem states that the equivalent current source with parallel resistor exists if the DC circuit is linear. It's possible that your teacher has declared "If I one day happen to order you to apply Norton's theorem to solve a certain voltage or current, then you should calculate the open circuit voltage and the short circuit current!". I do not believe such declaration really exists, but that's a belief.
3) when the circuit has controlled sources, you have a danger to use for ex. same i in different situations where the circuit is different due the needed opens and shorts to derive the equivalents. Your i is totally different when the circuit is the original, 8 Ohm is taken away or when 8 Ohm is replaced with a wire.
I recommend you to stop with equivalent circuits to keep every controlled current and voltage in unique state. You get 2 equations with 2 unknowns i and v easily. Simply write i=10A+4i and the other equation for the currents at the right end of your 4i source.  With Norton's or Thevenin's equivalent sources - when applied right - you often generate only new unknowns to a circuit which has controlled sources and you will not advance at all.


text:
Q: Why does temperature increase like this? My book makes the following claim: Suppose you drop a bunch of large and small ice cubes of  temperature $0$ degrees in a beaker of water, then you start heating the beaker, the temperature of the beaker will only increase after all the ice cubes have melted.
Why is this true? Intuitively energy should be used in breaking the bonds in the ice cubes, but why should all of it be used to break the bonds, it is almost as if the energy "knows" it has to break the bonds first…
I will offer a BOUNTY to anyone you gives me a sufficiently satisfactory answer.

A:
My book makes the following claim: Suppose you drop a bunch of large and small ice cubes of temperature 0 degrees in a beaker of water, then you start heating the beaker, the temperature of the beaker will only increase after all the ice cubes have melted.

When something changes phase from solid to liquid, or from liquid to gas, it takes energy to break the intermolecular interactions. These interactions between the water molecules are what make it solid. As far as I know, a finite amount of heat that is supplied to the ice at 0 degrees Celsius (~ 80 cal/g) is used up to convert the whole amount of ice in the beaker to water. This is called the latent heat of fusion. After the process is complete, the temperature again starts rising.

Why is this true? Intuitively energy should be used in breaking the bonds in the ice cubes, but why should all of it be used to break the bonds, it is almost as if the energy "knows" it has to break the bonds first…

Here, the noticeable fact is that the melting of ice is essentially a "bulk" phenomenon. Particles from the bulk (whole) of the ice change into water. So, in a way of saying, ice cubes won't "let" the heat energy supplied contribute to an increase in temperature until and unless all the bonds are broken. That's the way it is.


text:
Q: Difference between the cost function of a training sample and the cost function of a mini-batch Lets say that I have a neural network named 'NN' with 500 weights and biases (total parameters=500).
For one training sample: It's introduced through 'NN', it spits out an output (Out1), the output is compared to the training label, and with the backpropagation algorithm there is a small change(positive or negative) in every parameter of 'NN'. The cost function is represented by a vector of dimentions 1x500, with all the small modifications obtained by the backpropagation algorithm.
Lets say mini_batch_size=10
For one mini-batch: each and every one of the 10 training samples provide a cost function of dimensions 1x500.
In order to visualize and explain better, lets say that we create a matrix of 10x500 (called M), where every row is the cost function of every training sample.
Question: For the mini-batch training example, Is the final cost function of the minibatch the result of the average of all the column elements?
PD.
In case the question is not clear enough I left some code on what I exactly mean.
for j=1:500
Cost_mini_batch(j)=sum(M(:,j))/10
end

The dimensions of Cost_mini_batch are 1x500.

A: "Cost" refers to the loss, i.e. the error between Out1 and the training label.

The cost function is represented by a vector of dimentions 1x500, with all the small modifications obtained by the backpropagation algorithm.

This is called "gradient", not cost function.

Question: For the mini-batch training example, Is the final cost function of the minibatch the result of the average of all the column elements?

Yes, both gradient and cost function for a minibatch is the average of the gradients of each example in the minibatch.


text:
Q: Work done by force over curve Whew, gave this several shots. All attempts are wrong so here's where I'm at
$$F= ti + \frac{1}{8}j+k; C: r(t)=(e^{8t})i+(e^{8t})j+(-5t^2+t)k, -1\le{t}\le{1}$$
$$W=\int^b_a{\vec{f}\cdot\vec{dr}}$$
$$\frac{\vec{dr}}{dt}=(8e^{8t})i+(8e^{8t})j+(-10t+1)k$$
$$\vec{f}=ti+\frac{1}{8}j+k$$
$$\int^1_{-1}<t,\frac{1}{8},1>\cdot<8e^{8t},8e^{8t},(-10t+1)>dt$$
$$\int^1_{-1}8te^{8t}+e^{8t}-10t+1dt$$
$$8\int^1_{-1}te^{8t}dt+\int^1_{-1}e^{8t}dt+\int^1_{-1}-10tdt+\int^1_{-1}dt$$
$$\int{udv}=uv-\int{vdu}+C$$
$$u=t, dv=e^{8t}, du=1, v=\frac{e^{8t}}{8}$$
$$8\left[\frac{te^{8t}}{8}\Bigg|^1_{-1}-\int^1_{-1}{\frac{e^{8t}}{8}dt}\right]$$
$$8\left[\frac{te^{8t}}{8}\Bigg|^1_{-1}-\frac{1}{8}\int^1_{-1}{e^{8t}dt}\right]$$
$$8\left[\frac{te^{8t}}{8}-\frac{e^{8t}}{64}\Bigg|^1_{-1}\right]$$
$$8\left[\frac{te^{8t}}{8}-\frac{e^{8t}}{64}\Bigg|^1_{-1}=\frac{e^{8t}(8t-1)}{64}\Bigg|^1_{-1}\right]$$
$$8\left[\frac{e^{8t}(8t-1)}{64}\Bigg|^1_{-1}\right]+\int^1_{-1}e^{8t}dt+\int^1_{-1}-10tdt+\int^1_{-1}dt$$
$$\left[8\frac{e^{8t}(8t-1)}{64}+\frac{e^{8t}}{8}\right]\Bigg|^1_{-1}+\int^1_{-1}-10tdt+\int^1_{-1}dt$$
$$\left[8\frac{e^{8t}(8t-1)}{64}+\frac{e^{8t}}{8}+\frac{-10t^2}{2}\right]\Bigg|^1_{-1}+\int^1_{-1}dt$$
$$\left[8\frac{e^{8t}(8t-1)}{64}+\frac{e^{8t}}{8}+\frac{-10t^2}{2}+t\right]\Bigg|^1_{-1}$$
$$\left[\frac{e^{8t}(8t-1)}{8}+\frac{e^{8t}}{8}+\frac{-10t^2}{2}+t\right]\Bigg|^1_{-1}$$
$$\left[\frac{e^{8t}(8t-1)+e^{8t}}{8}+\frac{-10t^2}{2}+t\right]\Bigg|^1_{-1}$$
$$\left[\frac{e^{8t}(8t-1)+e^{8t}+4(-10t^2+2t)}{8}\right]\Bigg|^1_{-1}$$
The correct answer is:
$$W=e^8+e^{-8}+2$$

A: $$8\int^1_{-1}te^{8t}dt+\int^1_{-1}e^{8t}dt+\int^1_{-1}-10tdt+\int^1_{-1}dt\tag
 1$$
$$\int_{-1}^{1}te^{8t} = \frac{t}{8}e^{8t} - \frac{1}{8}\int_{-1}^{1}e^{8t}\tag 2$$
Put (2) in (1)
You get $=te^{8t}|_{-1}^{1} -\int_{-1}^{1}e^{8t}dt ++\int^1_{-1}e^{8t}dt -5t^2|_{-1}^{1} + 2$
Thus you get $$e^{8} + e^{-8}+2$$
The second term in the integration by parts cancels out with the second term of the overall integral and simplifies the process


text:
Q: How can I customize the display of a model using contenttypes in the admin? I have these models:
class App(models.Model):
  name = models.CharField(max_length=100)

class ProjectA(models.Model):
  name = models.CharField(max_length=100)
  app  = models.ForeignKey(App)

class ProjectB(ProjectA):
  pass

class Attachment(models.Model):
  content_type    = models.ForeignKey(ContentType)
  object_id       = models.PositiveIntegerField()
  project         = generic.GenericForeignKey("content_type","object_id")
  file            = models.FileField(upload_to=".")

I'm registering all the models for the admin, and I'm unregistering Group, User and Site. The thing is, when I access the Attachment in the admin, I see it rendered like this:

In the Content type select, I see this list:

The reason Attachment has a GenericForeignKey is because both ProjectA and ProjectB need to access it. I know that ProjectA and ProjectB are identical, but it's a requirement that they are stored in 2 separate tables. How could I made the Attachment class useable from the admin? I know how to use contenttypes from normal views, but from the admin not.
In the Attachment class I would only like to have a select for Project A or Project B, and then a list of all Project A's or all Project B's, followed by the file that I want to attach.
Is such a thing possible from the Admin? Will I need to show the user the Object Id column?

A: if I'm not wrong, you want this. http://code.google.com/p/django-genericadmin/
my advice will work differently. you will add a little more form in ProjectA, ProjectB as inline. in your admin.py
from django.contrib import admin
from django.contrib.contenttypes import generic

from myproject.myapp.models import Attachment, ProjectA, ProjectB

class Attachmentline(generic.GenericTabularInline): #or generic.GenericStackedInline, this has different visual layout.
    model = Attachment

class ProjectAdmin(admin.ModelAdmin):
    inlines = [
        Attachmentline,
    ]

admin.site.register(ProjectA, ProjectAdmin)
admin.site.register(ProjectB, ProjectAdmin)

go your ProjectA or ProjectB admin and see new admin.
this isn't what you want but it can help you. otherwise you need check first link.

A: You should notice that

" know that ProjectA and ProjectB are
  identical, but it's a requirement that
  they are stored in 2 separate tables"

is not really correct.  All the data is stored in your app_projecta table, and (only) some pointers are kept in table app_projectb.  If you are already going in this path, I would suggest starting with this instead:
class App(models.Model):
  name = models.CharField(max_length=100)

class Project(models.Model):
    name = models.CharField(max_length=100)
    app = models.ForeignKey(App)

class ProjectA(Project):
  pass

class ProjectB(Project):
  pass

class Attachment(models.Model):
  project = models.ForeignKey(Project)
  file = models.FileField(upload_to=".")

This already gets you a bit closer to where you want to get...


text:
Q: Icomparer for objects - or should I be using a SortedSet in the first place? I want to create a sorted list of objects which are rather like KeyValue pairs, where the Value is itself an Object (quite a complex one, and may be one of a number of subclasses of a base type). The Keys can be duplicated, and I don't mind in which order the Values are sorted - it doesn't even have to be deterministic.
SortedList won't work because of the duplicate keys, so I thought of SortedSet. But to get this to work it seems that I need a comparator which returns a non-zero value when the entries are distinct, so I need to include the Value as part of the comparison.
The need to traverse the list in sorted order happens quite often in the program, so the suggestion that I've seen elsewhere to use a List and sort it when needed is probably not going to work too well.
So my question is: how can I write an Icomparer which compares objects and only produces a 0 result when the objects are in fact the same?
Some fairly minimal VB.NET code follows.
  MustInherit Class Item

    Friend Name As String
' I'm not bothering to add the constructor - just assume that "name" gets set somehow
  End Class

  Public Class ItemA
    Inherits Item
  End Class

  Public Class ItemB
    Inherits Item
  End Class

  Class ListEntry
    Friend Key As Integer
    Friend Entry As Item
  End Class

  Class EntryComparer
    Implements IComparer(Of ListEntry)

    Public Function Compare(x As ListEntry, y As ListEntry) As Integer Implements IComparer(Of ListEntry).Compare
      If x.Key > y.Key Then
        Return 1
      ElseIf x.Key < y.Key Then
        Return -1
      Else
        If x.Entry is y.Entry Then
          Return 0
        End If
        '****************************
        ' what do I put in here to compare the Entry fields to ensure that it's only 0 when they're the same object?
        '****************************
      End If
    End Function

  End Class

A: I think this will work (not tested it yet, though):
Give the Item class a shared private field SerialNumber and a field SNo. When New is called, Copy SerialNumber into SNo and increment it. Use this as a secondary key for sorting.


text:
Q: File upload to ASP. NET MVC 6 not working The file upload component from a 3rd party vendor does not work with my MVC 6 project. Therefore I built a very simple upload mechanism with standard asp.net components:
<form method="post" asp-action="Index2" asp-controller="Data" enctype="multipart/form-data">
    <input type="file" name="files" multiple />
    <input type="submit" value="Upload" />
</form>

This upload works fine. I receive the uploaded file in my POST-Method in the controller. However if I start the full featured upload component (dxFileUploader from DevExpress) I don't receive the file. My method in the controller will be called but the file collection is empty. In order to compare the two upload requests I created a Fiddler for both. The requests are very similar. Has someone an idea what's the problematic difference between the two requests?

A: @Marco, I know this is old, however, ensure that the binding in your controller is correct, meaning the parameter to your action matches the name of the component. I am using the dxFileUploader (version 16.1) with the following action:
public async Task<IActionResult> UploadProducts([FromForm]IFormFileCollection files){...}

And the following in my view :
$("#file-uploader").dxFileUploader({
        selectButtonText: "Select Product File",
        labelText: "",
        accept: "text/csv",
        uploadMode: "useForm",
        name: "files"
    });

I hope this helps.


text:
Q: Example of a non-commutative rings with identity that do not contain non-trival ideals and are not division rings I'm looking for an example of a non-commutative ring, $R$, with identity s.t $R$ does not contain a non-trival 2 sided ideal and $R$ is not a division ring

A: If "ideal" means "two-sided ideal," then the Weyl algebra $\mathbb{C} \langle x, y \rangle / (xy - yx - 1)$ is an example.  So is $\mathcal{M}_n(R)$ for any division ring $R$ and $n \ge 2$.

A: If you mean two-sided ideals, you are looking for simple rings (that are not division rings):
http://en.wikipedia.org/wiki/Simple_ring
E.g. as in the wikipedia article, is the ring of matrices (of a certain size) over a field. Clearly this is not a division ring since not every matrix is invertible (matrices with zero determinants are not invertible).


text:
Q: Async.Parallel, grouping work of many works Is a pattern like:
seq[ workSeq, workSeq ..., workSeq, workSeq]
|> Seq.map( Async.Parallel )
|> Async.Parallel
|> Async.RunSynchronously

ok?, Or do i have to do:
seq[ workSeq, workSeq ..., workSeq, workSeq]
|> Seq.concat
|> Async.Parallel
|> Async.RunSynchronously

How do these two options behave differently ?
Thanks

A: One does a single fork-join among all the tiny pieces of work, whereas the other does a fork-join over a group of other fork-join batches.  Which behavior do you intend?  The former seems more likely to be useful to me... So I would probably do the concat.


text:
Q: How do you change AD password attempt count? Running a 2008 R2 Active Directory server. Users are allowed 5 bad login attempts before their account is locked.
One user for some reason has a login threshold of 1 (which I've verified by logging into our website using their name).
For the last week or so, every time they mistype their password even once, they come to me and I uncheck "Account is locked out" in the users properties.
I'm quite new to AD, and I can't find any microsoft documentation of why one users threshold is different than everyone else's.
Can someone explain to me why this is the case, and how to change their threshold back to 5?

A: The general documentation on AD password policy settings you seek is here.
The registry key in question is located at:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\RemoteAccess\Parameters\AccountLockout
And can be manipulated by Group Policy under:
Computer Configuration -> Windows Settings -> Security Settings -> Account Policies -> Account Lockout Policy
And, incidentally, the fact that this one client has a different value than the reset strongly suggests that he's either not receiving or not properly processing Group Policy, so you should look into why, with your standard group policy troubleshooting friends, rsop.msc and gpresult.

A: This sounds like a Group Policy issue. Check all the Group Policies that apply to your user accounts in AD. In my experience these are set in the Default Domain Policy. One of the policies should have something setting the:
Computer Configuration\Policies\Windows Settings\Security Settings\Account Policies\Account Lockout Policy
you can alter that value back up to 5 and run a gpupdate on the clients machine.


text:
Q: Error: Cannot find module 'renderer/utils/localStore' I am trying to call userDir function to get userdata folder path in the main/main.ts. I am using the electron-react-boilerplate
const electron = require('electron');
const path = require('path');
const fs = require('fs');

export function userDir() {
  return (electron.app || electron.remote.app).getPath('userData');
}

I am caling the userDir function in the main.ts file
import { userDir } from 'renderer/utils/localStore';

userDir()

Error:
Electron encountered an error
Error: Cannot find module 'renderer/utils/localStore'
Require stack:
- /home/prash/Projects/Electron/pomodoro/src/main/main.ts
- /home/prash/Projects/Electron/pomodoro/node_modules/.pnpm/electron@18.3.2/node_modules/electron/dist/resources/default_app.asar/main.js
-
    at Module._resolveFilename (node:internal/modules/cjs/loader:940:15)
    at Function.n._resolveFilename (node:electron/js2c/browser_init:245:1105)
    at Function.Module._resolveFilename.sharedData.moduleResolveFilenameHook.installedValue [as _resolveFilename] (/home/prash/Projects/Electron/pomodoro/node_modules/.pnpm/@cspotcode+source-map-support@0.8.1/node_modules/@cspotcode/source-map-support/source-map-support.js:811:30)
    at Function.Module._load (/home/prash/Projects/Electron/pomodoro/node_modules/.pnpm/runtime-required@1.1.0/node_modules/runtime-required/runtime-required.js:28:44)
    at Module.require (node:internal/modules/cjs/loader:1012:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (/home/prash/Projects/Electron/pomodoro/src/main/main.ts:15:1)
    at Module._compile (node:internal/modules/cjs/loader:1116:14)
    at Module.m._compile (/home/prash/Projects/Electron/pomodoro/node_modules/.pnpm/ts-node@10.8.0_wxuian5givsywcqjoc4lpn66fa/node_modules/ts-node/src/index.ts:1597:23)
    at Module._extensions..js (node:internal/modules/cjs/loader:1169:10)
    ```


text:
Q: Oracle Cloud: Permission denied (publickey,gssapi-keyex,gssapi-with-mic) I created an new Oracle cloud Linux instance, downloaded the private and public keys on creation, and now I cannot access it. I followed the guides and searched around, but I can mostly just find people who got their keys mixed up, which I have double-checked.
It shows as running, but if I try to SSH by doing:
 ssh -i ssh-key-2022-09-18.key ops@xxx.xxx.xxx.xxx
Then I get:
 Permission denied (publickey,gssapi-keyex,gssapi-with-mic).
Any help?

A: If you have used the OCI auto generated keys during Instance Creation then the default username is opc and not ops as mentioned in your question.
You will only be able to connect via SSH only if the keys are not misplaced as there is no way to retrieve the private key after the instance is created.
In case you have misplaced the keys then to upload new keys you will have to work with the boot volume (refer this answer How do you change the public key of a Oracle Cloud Instance? for more details on how to add new SSH key)
Note: To access OCI Instance, there are many other prerequisites like having public IP or accessing via bastion, etc. Please review this https://docs.oracle.com/en-us/iaas/Content/Compute/Tasks/accessinginstance.htm document for more details.


text:
Q: Jar File not executing from PHP I am trying to execute a Jar file from PHP on XAMPP windows server 2012.
A simple "Hello World" jar file execution works
$output = exec("java -jar C:\User\HelloWorld.jar");

echo $output;

However, a Jar file that opens the window of another program (a Browser, Paint, Notepad, etc..), does not execute from PHP although I tested it manually in the command window and it worked. I also tried to execute the jar using a batch file (which also works on clicking) but fails to execute from PHP.
I gave full permissions to the Apache server to act as a logged in user, and still it is not working.
I have been researching for 2 days and trying different combinations of solutions on forums (system, shell_exec, exec,..), but nothing worked for me.
Appreciate anyone's help please, before my VPS subscription ends


text:
Q: AVR USART Random Behaviour I seem to be getting random character in my USART output with an ATMEGA8
uart.c
#define FOSC 8000000
#define BAUD_RATE 9600
#define UBRR_VALUE (uint16_t)(FOSC/16/BAUD_RATE-1)

#include "uart.h"

volatile u8buf UART_RCV_BUFFER;
FILE uart0_str = FDEV_SETUP_STREAM(UARTSendByte, UARTReceiveByte, _FDEV_SETUP_RW);

ISR(USART_RXC_vect)
{
    //got a byte from USART. add to buffer
    volatile uint8_t data;
    scanf("%c",&data);
    if((UART_BUFFER_WRITE(&UART_RCV_BUFFER, data)==1) || (data=='.'))
    {
        //either buffer full or '.' received
        //stop the UART receiver unit + disable interrupt
        UCSRB &= ~((1<<RXEN) | (1<<RXCIE));
    }
}

ISR(USART_UDRE_vect)
{
    volatile uint8_t data;
    if(UART_BUFFER_READ(&UART_RCV_BUFFER, &data)==1)
    {
        //end of buffer reached. nothing more to transmit
        //disable RX
        UCSRB &= ~((1<<RXEN) | (1<<RXCIE));
        //reset buffer
        UART_BUFFER_INIT(&UART_RCV_BUFFER);
        //enable  RX side
        UCSRB |= ((1<<RXEN) | (1<<RXCIE));
    }
    else printf("%c",&data);
}

void UART_WRITE_STRING(char* str)
{
    //Sending a string without any command
    //disable RX/TX interrupts
    UCSRB &= ~((1<<RXCIE) | (1<<UDRIE));
    printf("%s",str);
    //re-enable RX/TX interrupts
    UCSRB |= (1<<RXCIE) | (1<<UDRIE);
}

void UART_INIT(void)
{
    UBRRH = (uint8_t)(UBRR_VALUE>>8); //set UBRR register
    UBRRL = (uint8_t)UBRR_VALUE;
    UCSRC = (1<<URSEL) | (1<<UCSZ1) | (1<<UCSZ0);//set frame format: asynchronous,8data,1stop,no parity
    UCSRB = (1<<TXEN) | (1<<RXEN) | (1<<RXCIE) | (1<<UDRIE);

    UART_BUFFER_INIT(&UART_RCV_BUFFER);
    stdin=&uart0_str;
    stdout=&uart0_str;
}

void UART_BUFFER_INIT(volatile u8buf *buf)
{
    buf->index = 0;
}

uint8_t UART_BUFFER_WRITE(volatile u8buf *buf, volatile uint8_t data)
{
    if(buf->index<UART_RCV_BUF_SIZE)
    {
        buf->index = data;
        buf->index++;
        return 0;
    }
    else return 1;

}

uint8_t UART_BUFFER_READ(volatile u8buf *buf, volatile uint8_t *data)
{
    if(buf->index>0)
    {
        buf->index--;
        *data = buf->buffer[buf->index];
        return 0;
    }
    else return 1;
}

int UARTSendByte(char u8data, FILE *stream)
{
    if(u8data=='\n')
    {
        UARTSendByte('\r',0);
    }
    while(!(UCSRA&(1<<UDRE))){};
    UDR = u8data;
    return 0;
}

int UARTReceiveByte(FILE *stream)
{
    uint8_t data;
    // Wait for byte to be received
    while(!(UCSRA&(1<<RXC))){};
    data=UDR;
    //echo input data
    UARTSendByte(data,stream);
    // Return received data
    return data;
}

main.c
#include "uart.h"
#include "twi.h"

int main (void)
{
    DDRC = 0x01; //set PC0 as output
    PORTC = 0x01; //turn on PC0
    //PD0 = RXD = INPUT
    //PD1 = TXD = OUTPUT
    DDRD = 0x03;

    UART_INIT(); //initialize UART
    sei(); //Enable global interrpts

    //_delay_ms(500);

    UART_WRITE_STRING("Hello World ! 1:)\n");
    UART_WRITE_STRING("Hello World ! 2:)\n");
    UART_WRITE_STRING("Hello World ! 3:)\n");
    for(;;)
    {

    }
}

This upon execution should give me
Hello World ! 1:)
Hello World ! 2:)
Hello World ! 3:)

But what i get is
\n\nHello World ! 1:)
Hello World ! 2:)
Hello World ! 3:)

the number of \n is random. Sometimes there is none, sometimes 1 or 2 or 3. Any idea what I am doing wrong here?

A: It is a good habit to flush serial input buffer on your PC before starting to use it to ensure sender and receiver are synchronized. One useful trick is not to send your raw data, but encapsulate it in a frame of which you can easily recognize start, end and payload. You probably want to add a checksum too, so you can simply check if the data you received is the same as the data you tried to send.
Useful similar other questions:

*

*Why do I need to wait a few moments before sending serial data on my AVR?

*RS232 hotplugging


text:
Q: how to integrate stacknavigator in tabnavigator V 5.x i have this stacknavigator
const Stack= createStackNavigator();
function MyStack() {
  return (
    <Stack.Navigator>
      <Stack.Screen name="Search" component={Search}  options={{title:'Rechercher'}}/>
      <Stack.Screen name="Filmdetail" component={FilmDetail} options={{title:'FilmDetail'}} />
    </Stack.Navigator>
  );
}

and this tabnavigator
const MoviesTabNavigator = createBottomTabNavigator()
  export default function App() {
    return (
      <NavigationContainer>
        <MoviesTabNavigator.Navigator>
          <MoviesTabNavigator.Screen name="Search" component={MyStack} />
          <MoviesTabNavigator.Screen name="Favorites" component={Favorites} />
        </MoviesTabNavigator.Navigator>
      </NavigationContainer>
    )}

the stack navigator don't works anymore when i called it inside tabnavigator,someone can resolve this probleme plz

A: You should have just one NavigationContainer above all the Stacks.
AppNavigation:
import { NavigationContainer } from '@react-navigation/native';

const AppNavigation = () => {
    return (
        <NavigationContainer>
            <Stack.Navigator
              initialRouteName="Login"
              screenOptions={({}) => ({
                headerTintColor: 'white',
                headerStyle: {
                    backgroundColor: appColors.primary
                }
              })}
            >
              <Stack.Screen
                  name="FoodCategories"
                  component={FoodCategories}
                  options={({}) => ({
                      title: 'Просмотр стола',
                  })}
              />
          </Stack.Navigator>
        </NavigationContainer>
    )
}

export default AppNavigation

Tab navigator:
const Tab = createMaterialTopTabNavigator();

const FoodCategories = () => {
    return (
        <Tab.Navigator
            tabBarOptions={{
                indicatorContainerStyle: {
                    backgroundColor: appColors.primary,
                },
                activeTintColor: 'white',
                indicatorStyle: {
                    backgroundColor: 'white',
                },
            }}
        >
            <Tab.Screen
                name="National"
                component={FoodCategory}
                options={({}) => ({
                    title: 'нацио...'
                })}
                initialParams={{ category: 'nationalFood' }}
            />
            <Tab.Screen
                name="FastFood"
                component={FoodCategory}
                options={({}) => ({
                    title: 'фастфуд'
                })}
                initialParams={{ category: 'fastFood' }}
            />
        </Tab.Navigator>
    )
}

export default FoodCategories


text:
Q: Compute the differential of a function $f: S^1 \rightarrow \mathbb{R}^2$ I am struggling a bit in computing the differential of the following function. In particular, I am confused by differentiating w.r.t. $\cos(x)$ and $\sin(x)$.
Let $f: S^1 \rightarrow \mathbb{R}^2$ given by $f(\cos(x), \sin(x)) = (\sin(2x)\cos(x), \sin(2x)\sin(x))$.

Using the comment of @Fakemistake. I have that the differential is
$$df = \begin{pmatrix} 4sin(x)cos(x) & 2cos^2(x) \\ 2sin^2(x) &4sin(x)cos(x)\end{pmatrix}$$


text:
Q: Google Play Store for private channel distribution In my company, we want to distribute an android app for only internal users.
We have one Google apps account (admin account) with our own company's domain name (xyz@sample.com).
We have other employee's email id with the company domain name(xyz@sample.com) and these are not under the Google apps.
Do we need the same Google apps account for all the employees under Google apps admin? As we need to make the app downloadable to all the internal employees too.
OR
Is it possible to make the android app downloadable with our own server's created email ids.
For Google APP account, do we need to pay Rs.150/employee/month?
EDIT:
I do not want to publish my android app on other play store where Google can not interfere.Is there any store? I have searched and found that there are many stores available but which is trustworthy.

A: All you need is your app available on the web for a common download. After in android, you need to download the apk and notify the user to update.
Below is the code I use to download the .apk and install it.
public void UpdateApk(){

            String nameapk = "youapp.apk";
            String urlDownload = "http://youserver/" + nameapk;
            HttpURLConnection conn = (HttpURLConnection) new URL(urlDownload).openConnection();
            conn.setDoInput(true);

            conn.setConnectTimeout(20000);

            conn.connect();

            InputStream is = conn.getInputStream();

            String PATH = Environment.getExternalStorageDirectory() + "/download/";
            File file = new File(PATH);
            file.mkdirs();
            File outputFile = new File(file, nameapk);
            FileOutputStream fos = new FileOutputStream(outputFile);

            byte[] buffer = new byte[1024];
            int len1 = 0;

            while ((len1 = is.read(buffer)) != -1) {
                fos.write(buffer, 0, len1);
            }

            fos.close();
            is.close();

            // till here, it works fine - .apk is download to
            // sdcard in download file

            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/" + nameapk)), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            youcontext.startActivity(intent);

    }

To check the version of the app, see this answer:
https://stackoverflow.com/a/14313280/185022


text:
Q: IEnumWbemClassObject returning null in C++ I was trying to read the Creation Class Name Property of Win32_PhysicalMemoryArray class but on running the code below the IEnumWbemClass object named enumerator was returning null. I am not able to figure out the problem. I would be very thankful  if anyone could help me out.
This is my code:
#include "stdafx.h"
using namespace std;

int main()
{

    HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
    IWbemLocator *locator;
    hr = CoCreateInstance(CLSID_WbemAdministrativeLocator, NULL, CLSCTX_INPROC_SERVER, IID_IWbemLocator, reinterpret_cast< void ** >( &locator ));
    IWbemServices * service;
    hr=locator->ConnectServer((BSTR)L"root\\cimv2", NULL, NULL, NULL, WBEM_FLAG_CONNECT_USE_MAX_WAIT, NULL, NULL, &service);
    IEnumWbemClassObject * enumerator;
    hr = service->ExecQuery((BSTR)L"WQL", (BSTR)L"SELECT * FROM Win32_PhysicalMemoryArray", WBEM_FLAG_FORWARD_ONLY, NULL, &enumerator);
    ULONG retcnt;
    IWbemClassObject * memdevice;
    hr = enumerator->Next(WBEM_INFINITE, 1L, &memdevice, &retcnt);
    variant_t var_val;
    hr = memdevice->Get(L"CreationClassName", 0, &var_val, NULL, NULL);
    cout << var_val.bstrVal;

    CoUninitialize( );
    return 0;
}

Here is the screenshot of the error:
nullptr Exception
Note: There is a reason why i have not used CComPtr<> here. Whenever i was including that an assert faliure was being reported in the header file atlcomcli.h. I think this error might also be due to the nullptr exception of enumerator object. Thanks in advance

A: I solved the issue myself. The main problem was that of setting the required previledges for accessing. This was the reason why enumerate was returning a null pointer. To solve the issue write the following code immediately after making a call to CoinitiallizeEx:
MSDN sample from comments or
Making WMI Queries in C++
Moreover as a note the above code must not be run by anyone in this way. This is because these pointers may leak memory if not used properly or an exception occurs.  Rather
atlbase.h
And
Iwbemdl. h
must be added to use CComPtr (Com Pointer class )  that will manage the construction and destruction automatically.


text:
Q: No connection to Google Compute engine instance after upgrading on advice google team I resize instance from 4 cpu to 2, after this, server not responded, SSH connection timeout to instance.
I cannot understand why this problem occurred, and how to solve it.
Thanks a lot.

A: I suppose that you've followed documentation Changing the Machine Type of a Stopped Instance and after that your VM instance is running, but you're not able to connect via Cloud console web interface and via Cloud Shell with a command gcloud compute ssh.
Please restart your VM instance, if it's possible, and check logs at Compute Engine -> VM instances -> click on NAME_OF_YOUR_VM -> at the VM instance details find section Logs and click on Serial port 1 (console) for any error or warning messages that could explain what happened to your VM instance.
After that, please have a look at the documentation Troubleshooting SSH and follow the instructions. You'll be able to choose appropriate action after checking console log at the previous step.
Also, you can connect to your VM via Serial console by following this guide, but keep in mind that:

The interactive serial console does not support IP-based access
restrictions such as IP whitelists. If you enable the interactive
serial console on an instance, clients can attempt to connect to that
instance from any IP address.

more details you can find in the documentation.
If nothing helped, please add full console log to your question by using hastebin.com or other similar service and describe which steps you've done so far by following Troubleshooting SSH guide.


text:
Q: Java: How do you add data into an object? I'm new to Java. How do you add String data into an Object "myData" and print out the contents of it in main?
public class myData {
  static String[] myArray = new String[] { "Mimi Rudolph", "minirudolph" };

  public static String[] cutName(String string) {
    return string.split(" ");
  }

  String[] fullName = cutName(myArray[0]);
  String skype = myArray[1];
  String github = null;
  Object myData = new Object();

  public myData(String[] fullName, String skype, String github) {
    this.fullName = fullName;
    this.skype = skype;
    this.github = github;
  }

  public static void main(String[] args) {

    Object myData = new Object();
  }
}

A: You need to simply create an instance of your class myData as next:
public static void main(String[] args) {
    myData myData = new myData(myArray, "skype", "github");
    ...
}

To print its content you could override the method toString() for example like this:
@Override
public String toString() {
    return "myData{" +
        "fullName=" + Arrays.toString(fullName) +
        ", skype='" + skype + '\'' +
        ", github='" + github + '\'' +
        ", myData=" + myData +
        '}';
}

Then you will be able to print its content using System.out.println(myData).
So the final code would look like this:
public class myData {
    ...
    @Override
    public String toString() {
        ...
    }

    public static void main(String[] args) {
        myData myData = ...
        System.out.println(myData);
    }
}

A: I think you are looking for something like this:
public class MyData {

private static final String[] myArray = new String[]{"Mimi Rudolph", "minirudolph"};

String[] fullName = cutName(myArray[0]);
String skype = myArray[1];
String github = null;
Object myData = new Object();

private static String[] cutName(String string) {
    return string.split(" ");
}

public MyData(String[] fullName, String skype, String github) {
    this.fullName = fullName;
    this.skype = skype;
    this.github = github;
}

public static void main(String[] args) {
    MyData myData = new MyData(myArray, "Skype string goes here", "githun string goes here");
    System.out.println(myData.fullName);
    System.out.println(myData.github);
    System.out.println(myData.skype);
}
}

A: @Tai, I think you're missing some concepts in your code.
Once Java is an Object Oriented Programming language, you should avoid using the static in your methods when you want to have a new instance of a class.
To call methods with static, you don't need a new instance of an object (can call it as MyData.cutName, for example.
On the other hand, constructors will be accessed when you create a new instance of your object.
I believe you can get rid of the arrays, but I kept it in your cutName method.
You could have something like this.
public class MyData {
    private String fullname;
    private String skype;
    private String github;

    public MyData(String fullname, String skype, String github) {
        this.fullname = fullname;
        this.skype = skype;
        this.github = github;
    }

    public String getFullname() {
        return this.fullname;
    }

    public String getSkype() {
        return this.skype;
    }

    public String getGithub() {
        return this.github;
    }

    public String[] cutName(String string) {
        return string.split(" ");
    }

    @Override
    public String toString() {
        return "Fullname: " + this.fullname + "; Skype: " + this.skype + "; Github: " + this.github;
    }

    public static void main(String[] args) {
        MyData myData = new MyData("Mimi Rudolph", "minirudolph_skype", "minirudolph_githnub");
        System.out.println("First name: " + myData.cutName(myData.getFullname())[0]);
        System.out.println("Last name: " + myData.cutName(myData.getFullname())[1]);
        System.out.println(myData);
    }
}

The output would be:
First name: Mimi
Last name: Rudolph
Fullname: Mimi Rudolph; Skype: minirudolph_skype; Github: minirudolph_githnub

Having the attributes in your class and setting it from the new instance will help you to have reusability.
Hope it helps.

A: Usually you can add string to object by the following simple example:
 String a = "abc";
 Object b = a;
 System.out.println(b);

If you want to assign a complete String array to myData Object, then you need to do the following:
 Object[] myData  = new Object[myArray.length];
        for(int i=0;i<myArray.length;i++){
            myData [i] = myArray[i];
            System.out.println("MyData Object Array holding strings data: "+myData[i]);
        }

In you main method, you need to change object to object of Arrays first:
From - Object myData = new Object();
TO: Object[] myData  = new Object[myArray.length];


text:
Q: hiddenFor helper is pulling id from action parameter, not the viewModel I've stumbled upon a really weird situation with ASP.Net MVC, passing an "id" as an action parameter and an "id" hidden form element.  I have an action that has an "id" parameter.  This id value represents a project.  I have a controller action where I'm creating a data entry form for assigning an employee to the passed in project (I create a drop down list where administrator selects an employee to be assigned to passed project).  By assigning an employee to a project, I create a ProjectEmployee record (project id, employee id, and an id that represents the combination which is an identity column in the database).  The identity column (which is named "id") is also a hidden form element.  This is necessary because I need to be able to edit the project/employee assignment at a later date.
Anyways, when creating a new employee assignment to a project, the project id (which is the "id" being passed to the action) is being applied to the "id" hidden form element.
I'm passing 117 into the action.  117 is the projectId.  It's being set to the "id" hidden field which should be 0 because 0 represents a new project/employee assignemnt.
View Model
id  - unique id that represents the Project/Employee combination
projectId - the "Id" being passed to action
EmployeeId - what the admin is selecting from drop down
rate
startdate
endDate
...

Data Entry Form
@Html.HiddenFor(m => m.Id)
@Html.HiddenFor(m => m.ProjectId)
...
Id: @Model.Id

ProjectId: @Model.ProjectId

So, @Html.HiddenFor(m => m.Id) renders a hidden form element with a value of 117.  @Model.Id renders 0 to the UI.  Stepping through the code I can visually see the value of the Id property to be 0.  How come HiddenFor is getting it's wires crossed and pulling the value of 117?
This bug has made it's way into production so I have a mess on my hands with data getting messed up because instead of creating a new record in the database table, I'm actually UPDATING existing records because the "Id" property is erroneously getting set from 0 (which represents a new record) to 117 (which is the projectId) and therefore am updating a different record.

A:
How come HiddenFor is getting it's wires crossed and pulling the value of 117?

That's by design. All HTML helpers such as TextBoxFor and HiddenFor first use the value of ModelState when binding and then the value of the model. I presume your controller action looks like this:
public ActionResult Foo(int id)
{
    SomeModel model = ...
    // At this stage model.Id = 0
    return View(model);
}

The thing is that the default model binder adds a value into the ModelState with the key id which is used by the helper and the model property value is ignored. This is not a bug. It is how the HTML helpers are designed. It's a bit confusing in the beginning when you don't know it, but once you get accustomed to this behavior you don't fall in the trap a second time.
One possibility to fix the problem is to remove this value from ModelState:
public ActionResult Foo(int id)
{
    ModelState.Remove("id");
    SomeModel model = ...
    // At this stage model.Id = 0
    return View(model);
}

Or rename the Id property inside your model to something else to avoid the conflict.

A: As an alternative to changing your field names, you can make a new helper method that doesn't use the route values when evaluating what to put in the value attribute.
I created this helper for the extremely common id case:
public static MvcHtmlString HiddenIdFor<TModel, TValue>(this HtmlHelper<TModel> html,
        Expression<Func<TModel, TValue>> expression)
    {
        var value = ModelMetadata.FromLambdaExpression(expression, html.ViewData).Model.ToString();
        var builder = new TagBuilder("input");
        builder.MergeAttribute("type", "hidden");
        builder.MergeAttribute("name", ExpressionHelper.GetExpressionText(expression));
        builder.MergeAttribute("value", value);
        return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing));

}

Then you can use this in the template:
@Html.HiddenIdFor(m => m.Id)
@Html.HiddenIdFor(m => m.ProjectId)


text:
Q: Project-specific print margin in Eclipse The print margin can be set by opening preferences and going to General-->Editors-->Text Editors. The default value there is 80 columns.
The 80-column value is fine for me but I'd like to override it for specific projects. Going to the properties of a project I found nothing related to it. Is this possible at all?

A: No, there is only one preference value for this and it is global rather than per project.
See the preference page source org.eclipse.ui.internal.editors.text.TextEditorDefaultsPreferencePage


text:
Q: Why can't I assign any variable to a function return value in pChart? I'm trying to assign a return value from a method to an array and in a second step to place this array into the addPoints() method of pChart.
Right now I'm using the following code:
$dataUsage = array();
for ($i = 1; $i < 31; $i++) {
        $dataUsage[$i - 1] = getDailyUsage($i);
}
$dataUsage[30] = getDailyUsage(31);

The getDailyUsage method looks like this:
function getPeriod() {
    return date("Y-m");
}

function getDailyUsage($day) {
        $var = getPeriod() . "-" . $day;
        global $pdo;
        $sql = "SELECT COUNT(  `id` ) FROM  `logs` WHERE timestamp = '$var'";
        $q = $pdo->prepare($sql);
        $q->execute();
        $q->setFetchMode(PDO::FETCH_ASSOC);
        $number = $q->fetchColumn(0);
        return $number;
}

To display the data into the pChart I'm running this:
$myData->addPoints($dataUsage, "Serie2");

As output I'm getting the default html icon as if I'm not finding the picture I'm looking for.
What really makes me curious is that I don't get any errors if I run this code:
$array = array();
for ($i = 1; $i < 31; $i++) {
    $array[$i - 1] = $i;
}
$array[30] = 31;

$myData->addPoints($array, "Absissa");

Since this is my first post I'm looking for tips to improve my questions, so feel free to leave a comment.
Edit:
If I use:
$dataUsage = array();
for ($i = 1; $i < 31; $i++) {
        $dataUsage[$i - 1] = $i;
}
$dataUsage[30] = $i;

I can draw the image. But I couldn't even run it when I tried:
$myData->addPoints(array(getDailyUsage(1), getDailyUsage(2)), "Absissa")

A: I got help for my problem and want to share the solution:
I had to check for the html source in the browser. The .php file which displays the picture showed the error.
Problem was that the file, which contains the connection information wasn't included.
I recommend you to look at the picture / file if you're working with pChart to avoid those errors.


text:
Q: html2canvas Limitations size/data/width/height I am trying to build a canvas, specifically a family tree, that is very wide and may have many images. If I build the tree without images, the width can span out to 27,000 px and the file size hits 1.7mb. If I build the tree with images for every node the width can span out to 16,385px and the file size hits 2.7mb. I am creating a custom window size based on the canvas element to override the browsers limitations, as specified here: http://html2canvas.hertzen.com/faq . I have also set the scale to 1 (the default).
The issue is if I go over these widths some of the nodes may render blank on Chrome and Firefox, and on IE the canvas gets cut off.
The question comes down to is there some sort of limitation to the amount of data html2canvas can write? Is there a limitation to the width even after the browser limitations are overwritten?
Specifications:
html2canvas version tested with: html2canvas 1.0.0-alpha.12
Browser & version: Chrome Version 78.0.3904.70 (Official Build) (64-bit) , IE-11 Version: 11.805.17763.0, Firefox Quantum: Version 70.0.1 (64-bit)
Operating system: Windows 10


text:
Q: How can I delete the first word from a line? Mon 25-Jul-2011

I want to delete the first word "Mon" with javascript jQuery.
How can i do this ?

A: If you don't want to split the string (faster, less memory consumed), you can use indexOf() with substr():
var original = "Mon 25-Jul-2011";
var result = original.substr(original.indexOf(" ") + 1);

A: var string = "Mon 25-Jul-2011";
var parts = string.split(' ');
parts.shift(); // parts is modified to remove first word
var result;
if (parts instanceof Array) {
  result = parts.join(' ');
}
else {
  result = parts;
}
// result now contains all but the first word of the string.

A: I wanted to remove first word from each items in Array of strings. I did that using split, slice, join.
var str = "Mon 25-Jul-2011"
var newStr = str.split(' ').slice(1).join(' ')
console.log(str)

Run this code in console you will get the expected string.

A: You can manipulate any dom, using their reference id, class or tag. Example

Mon 25-Jul-2011

A: Another solution:
var line = "Mon 25-Jul-2011";
var edited = line.substring( line.indexOf(" ") + 1, line.length );

A: var str = "Mon 25-Jul-2011";
var firstSpace=str.indexOf(" ");
var newStr= str.slice(firstSpace);
//result:"25-Jul-2011"

A: This should output  "25-Jul-2011":
var string = "Mon 25-Jul-2011";
string = string.split(' ').pop();


text:
Q: How to set TableRow on bottom of screen by xml in android I have a problem with set TableRow on bottom of screen. If TableRows between button and GoogleAds are empty, GoogleAds is´nt on bottom of screen. I try almost everything. On left side in this picture (http://qkoment.php5.sk/image/image_screen.PNG) is what I have and on the right side is what I want.
and here is my code:
 <?xml version="1.0" encoding="utf-8"?>
   <TableLayout
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      xmlns:android="http://schemas.android.com/apk/res/android"
      android:id="@+id/TableLayout03"
      xmlns:app="http://schemas.android.com/apk/lib/com.google.ads">
      <TableRow
         android:id="@+id/TableRow04"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:gravity="center">
         <Spinner
            android:id="@+id/Spinner01"
            android:layout_width="wrap_content"
            android:layout_height="40dip"
            android:layout_weight=".3"
            android:background="@drawable/button" >
        </Spinner>
    </TableRow>
    <TableRow
        android:id="@+id/TableRow05"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/tv1"
            android:paddingLeft="10sp"
            android:textColor="@color/blacky"
            android:layout_weight="1">
        </TextView>
    </TableRow>
    <TableRow
        android:id="@+id/TableRow01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center">
    </TableRow>
    <TableRow
        android:id="@+id/TableRow02"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center">
    </TableRow>
    <TableRow
        android:id="@+id/TableRow03"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center">
    </TableRow>
    <TableRow>
    <com.google.ads.AdView
        xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
        android:id="@+id/adView"
        android:padding="0dp"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        ads:loadAdOnCreate="true"
        app:adSize="BANNER"
        android:layout_gravity="bottom"
        app:adUnitId="myID" >
    </com.google.ads.AdView>
    </TableRow>
 </TableLayout>

thanks for every answer/suggestion.

A: It doesn't work like that. Why do you place your Ad in a TableRow?
With RelativeLayout you can place a view on the bottom of the screen with:
android:layout_alignParentBottom="true"


text:
Q: DC offset of amplifiers for 12V single supply operation I want to be able to amplify a signal using op-amps and a single power supply. In order for the op-amps to have maximum swing with a 12V power supply the AC input signal needs to be offsetted to 6V.
After constructing the circuit on a breadboard, the output was not what I expected. I expected the output of the amplifiers to have a wave that oscillates between 5V and 7V, centering at 6V. However, the output I measured was the wave centering at 9V and oscillating between 8V and 10V. The output of the first stage is correct though as I measured the wave oscillating between 5.9V to 6.1V, centering at 6V.
I believe my issue is that my resistor values in the op-amps are too large, therefore not enough current is being fed into the op-amps inputs. I was also thinking of using a linear/ switching regulator to source 6V. Could someone please explain why I'm getting these unexpected results?

Note: LT1006 op-amps aren't actually used in breadboard circuit. LM358's were used instead.

A: Since you only care about the AC component, you want to AC couple the signal.  That leaves the DC bias point up to you and independent of the input signal.
Here is a simplistic circuit that uses a capacitor to AC-couple the signal, then add its own bias voltage:

R1 and R2 are a voltage divider that makes half the power voltage.  This is the only DC connection to the positive input of the opamp, so that will be the average DC level.  C1 lets only the AC component of the input signal pass, and blocks DC.  The DC level to the left of C1 can therefore be anything (within the voltage capability of C1 to withstand) without messing up the DC bias level on its right.
The impedance of the bias voltage is R1//R2 = 50 kΩ.  With C1 of 200 nF, the high pass filter rolloff frequency is 16 Hz.  This rolloff would be suitable for HiFi audio, for example.
R4 and R3 are the feedback around the opamp, in this case yielding a gain of 11.  C2 again blocks DC.  In effect, the feedback voltage divider only works for AC, not for DC.  The DC gain is therefore 1.  The high pass rolloff frequency is set by R3 and C2, which is 16 Hz again.
One disadvantage of this topology is that while C2 works against only R3 to set the rolloff frequency, it works with both R4 and R3 for the DC level to settle.  The DC settling time constant is (R3 + R4)C2 = 110 ms.  That means this circuit will take a bit under a second to settle when first turned on.  For a typical audio amplifier, that wouldn't usually matter.  In some applications, though, you have to consider this.
Anyway, you can use this general concept to get what you want.


text:
Q: tkinter: How to change labels inside the program itself I was asked to edit my code so I decided to include the entire calculator script

from tkinter import *
global choice
choice = 0

#Program
def calculate(*event):
    if choice == 1:
        try:
            add1 = ccalc1.get()
            add2 = ccalc2.get()
        except:
            no = Label(app, text="You must use a number").grid(row=0, column=0)
        answ = add1 + add2
        answer = Label(app, text = answ).grid(row=1, column=0)
    elif choice == 2:
        try:
            sub1 = ccalc1.get()
            sub2 = ccalc2.get()
        except:
            no = Label(app, text="You must use a number").grid(row=1, column=0)
        answ = sub1 - sub2
        answer = Label(app, text = answ).grid(row=1, column=0)
def choice2():
    global choice
    choice = 2
#End Program
#GUI
#Window Info
calc = Tk()
calc.title("Calculator")
calc.geometry("200x140")
#End Window Info

#Build Window
app = Frame(calc)
app.grid()
ccalc1 = IntVar()
ccalc2 = IntVar()

#Widgets
if choice == 0:
    welcome = Label(app, text="Select a choice")
elif choice == 2:
    welcome.config(text="Subtraction")
calcbox1 = Entry(app,textvariable=ccalc1)
calcbox2 = Entry(app,textvariable=ccalc2)
submit = Button(app, text="CALCULATE", command = calculate)

welcome.grid(row=0,column=0)
calcbox1.grid(row=2, column=0)
calcbox2.grid(row=3, column=0)
submit.grid(row=4, column=0)
calc.bind('<Return>', calculate)
#End Widgets

#Menu
menu=Menu(calc)
#Operations
filemenu = Menu(menu,tearoff=0)
filemenu.add_command(label="Subtract", command = choice2)
menu.add_cascade(label="Operations",menu=filemenu)
calc.config(menu=menu)
calc.mainloop()
#End GUI

what wrong is that the welcome label text wont change accordingly.
Update: I included the entire calculator code
Any help is appreciated.

A: It's hard to understand what you expect to happen. For example, look at this code:
#Widgets
if choice == 0:
    welcome = Label(app, text="Select a choice")
elif choice == 2:
    welcome.config(text="Subtraction")

This code will only ever execute once, and choice will always be zero since that's what you initialize it to. It executes once because it's not in a function and not in a loop, so as python parses the code it will run it and move to the next line. That block of text will never be processed a second time.
If you want the label to change when the user selects a menu item, you'll need to execute that code inside the choice2 function:
def choice2():
    global choice
    choice = 2
    welcome.config(text="Subtraction")