text:
Q: Can Git merge --squash preserve commit comments? Is there a way of automatically adding all the commit comments from the squashed mybranch commits when doing a
git merge --squash mybranch

so that the single commit contains a concatenation of all the commit comments from mybranch

A: I think that's what "git merge --squash" does automatically!  Just do the commit with "git commit --no-edit" and I think that's what you'll get.  I see all the commit messages inside .git/SQUASH_MSG immediately after I run the "git merge --squash" command.  Do you?
Personally, I squash into master, but then force-push the result back to my topic branch.  This way my final commit can be code-reviewed via pull-request.
Live example (try these exact commands, this uses my demo server, and really works):
git clone http://vm.bit-booster.com/bitbucket/scm/bb/rebase-example-2.git
cd rebase-example-2
git checkout branch
git reset --hard origin/master
git merge --squash origin/branch
git commit --no-edit

git show
commit 74656c51212526af49382c985419244737141217
Author: G. Sylvie Davies <sylvie@bit-booster.com>
Date:   Mon Dec 26 22:07:50 2016 -0800

    Squashed commit of the following:

    commit 3120cbba4e94e0a81eed2f9ff42e7012cca996bf
    Author: G. Sylvie Davies <sylvie@bit-booster.com>
    Date:   Thu Dec 15 18:24:02 2016 -0800

        b2

    commit ccb522334464879b8f39824031c997b57303475d
    Merge: 6b85efb 026bf0c
    Author: G. Sylvie Davies <sylvie@bit-booster.com>
    Date:   Thu Dec 15 18:13:35 2016 -0800

        m

    commit 6b85efbddbb74d49a096bfc54fd4df15e261b72f
    Author: G. Sylvie Davies <sylvie@bit-booster.com>
    Date:   Thu Dec 15 18:12:51 2016 -0800

        b1

At this point I recommend doing a "git push --force-with-lease" to get this squashed commit up to your remote topic branch ready for code-review.
Note:  I do one fancy thing in the example.  I'm actually squashing into origin/master, not local master, and I first do "git checkout branch" and "git reset --hard origin/master".  This keeps my local master unperturbed by this operation, so that whatever I might be working on there is left alone.
I'm on Git 2.7.4.  Maybe older gits behave differently, I don't know.
If you want to do this all in Web UI, and you happen to be using Atlassian Bitbucket Server (the on-premises version), you can install my Bit-Booster paid add-on, and hit the big "Squash" button it puts on pull-requests.  It does the exact same thing, except that only non-merge commit messages are concatenated.


text:
Q: Detecting agent app launch and termination without polling on Mac OS X I need to be able to detect agent app launch and termination without polling on Mac OS X
Apple's technical note TN2050 suggests using NSWorkspace or Kqueues.
It appears that NSWorkspaceDidLaunchApplicationNotifications wouldn't work with agent app. I don't fully understand why, but it is sensitive to presence of LSUIElement=1 attribute.
KQueue API can only detect process termination using NOTE_EXIT and will successfully detect exit of the app agent. However there no way to detect app launch event using this API.
I also experimented with Kernel Authorization subsystem and discovered that it is possible to detect agent launch using either KAUTH_SCOPE_VNODE with KAUTH_VNODE_EXECUTE or KAUTH_SCOPE_FILEOP with KAUTH_FILEOP_EXEC. However I failed to find a way to detect process termination using KAuth.
Is there a better way of detecting agent app launch and termination, other than using a combination of KAuth to detect launch and KQueue to detect termination?
Thanks

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to configure cdn path on index.html in angular 6 I'm a beginner with angular. I started with angular 6 and am currently unable to understand how to make configurable cdn paths with my index.html in angular project.
Please have a look at my code ::

 <!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Refman</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link rel="stylesheet" href="https://cdn1.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
  <link rel="stylesheet" href="https://cdn2.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>

    <app-root></app-root>

</body>
</html>

I want to make these cdn1 and cdn2 configurable. This means I want to read the cdn path and base url of the cdn from my config.json. How to read them with this path from the .json file.
Please help me. Thanks in advance.

A: Angular suggest Environment variable to manage dynamic variable and configuration like your requirement.
environment.ts
environment.prod.ts
.... custom environment
for more information :
https://medium.com/@balramchavan/separating-production-and-development-http-urls-using-environment-ts-file-in-angular-4c2dd0c5a8b0
http://tattoocoder.com/angular-cli-using-the-environment-option/
https://medium.com/@amcdnl/custom-environments-for-angular-cli-4ce0b82da83b
structure :
https://angular.io/guide/quickstart#the-src-folder

A: You need to import the environment class to your component where your index.html is located:
import { environment } from 'location of environment.ts'

Then you pass the class variable this way:
public pName = environment.propertyname; // .css or a URL

In your index.html, you pass pName to href:
<link rel="stylesheet" href="pName">


text:
Q: best and fastest way to store big amount of data in javascript objects I need to store some data having 3 keys to uniquely determine each item.
For current example I use i, j, z as keys.

console.time('global1');
var global1 = {};

for (var i = 0; i < 100; ++i) {
  for (var j = 0; j < 100; ++j) {
    for (var z = 0; z < 100; ++z) {
      global1[i] = global1[i] || {};
      global1[i][j] = global1[i][j] || {};
      global1[i][j][z] = global1[i][j][z] = { a: 123456789 };
    }
  }
}

console.timeEnd('global1');

console.time('global2');
var global2 = {};

for (var i = 0; i < 100; ++i) {
  for (var j = 0; j < 100; ++j) {
    for (var z = 0; z < 100; ++z) {
      global2[[i,j,z]] = { a: 123456789 };
    }
  }
}

console.timeEnd('global2');

*

*Why chrome do first example really much faster, what type of optimization is it ?

*What best way to store that amount (or bigger) of data?

A: If you run different times both the snippets you can realize that the times are pretty similar, this because the computational complexity of an algorithm basically depend on the number of loop (that are the same).
If you need to store every single values I don't think there is other way to do that.


text:
Q: Get tag of latest git commit I want to find the tag of the last commit if it is present.  So far I have found only the option to get the last tag inside all of the tags..
But I want to know if there is a tag on the last commit or no tag?

A: [edit] @phd pointed out that git tag has a --points-at option, which makes for a nicer command :
git tag --points-at HEAD

my initial answer :
You can use the --points-at option of git for-each-ref :
git for-each-ref --points-at=HEAD

To display only the tag name, and limit the searched refs to tag  :
git for-each-ref --points-at=HEAD --format="%(refname:lstrip=2)" refs/tags


text:
Q: If a text is not wrapped in the button then there should be "..." after some text I want my button value to be Entrepreneurship. Hence, it may not be wrapped in the fixed width button. so What I want is, I want my button value to be Entrepreneu… instead of cutting the extra text in button.
Here is the image.

A: You should be using these style and you will get an ellipsis:
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;

example below:

.truncate {
  width: 75px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
<button class="truncate">Entrepreneurship</button>


text:
Q: How to define a constant by expression in C++? I need some like this:
const float ratio = 1/60;

How to do this?

A: Exactly as you have done but tell the compiler the values in the expression are floats with a "f" suffix
const float ratio = 1.0f/60.0f;

A: You don't really need constexpr, this will work in C or C++:
const float ratio = 1./60;

A: If you need a ratio, as opposed to the result of one, you can use std::ratio:
constexpr one_sixtieth = std::ratio<1, 60>();

constexpr auto n = one_sixtieth.num;
constexpr auto d = one_sixtieth.den;

It comes with a set of useful compile time operations.

A: You try this
const float numerator =1;
const float denominator =60;
const float ratio = numerator/denominator;


text:
Q: Elasticsearch- get all values for a given field? Is it possible to query for all of the values a specific field? Say I have "articles" and each  article has an author, is there a query I can perform to find a list of all authors?

A:
How to get all possible values for field author?

curl -XGET  http://localhost:9200/articles/_search?pretty -d '
{
    "aggs" : {
        "whatever_you_like_here" : {
            "terms" : { "field" : "author", "size":10000 }
        }
    },
    "size" : 0
}'

Note

*

*"size":10000 Get at most 10000 unique values. Default is 10.

*"size":0 By default, "hits" contains 10 documents. We don't need them.

*By default, the buckets are ordered by the doc_count in decreasing order.

Reference: bucket terms aggregation
Also note, according to this page, facets have been replaced by aggregations in Elasticsearch 1.0, which are a superset of facets.

A: another example
request
curl -X POST "http://localhost:9200/_search?pretty=true" -d '
{
  "facets" : {
    "tags" : { "terms" : {"field" : "network.platform"} },
    "size" : 60
  },
  "size" : 0
}
'

response
{
  "took" : 266,
  "timed_out" : false,
  "_shards" : {
    "total" : 650,
    "successful" : 650,
    "failed" : 0
  },
  "hits" : {
    "total" : 41,
    "max_score" : 0.0,
    "hits" : [ ]
  },
  "facets" : {
    "tags" : {
      "_type" : "terms",
      "missing" : 15,
      "total" : 26,
      "other" : 0,
      "terms" : [ {
        "term" : "platform name 1",
        "count" : 20
      }, {
        "term" : "platform name 2",
        "count" : 6
      } ]
    }
  }
}

A: I think what you want is a faceted search. Have a look at this example from the documentation:
http://www.elasticsearch.org/guide/reference/api/search/facets/index.html
curl -X POST "http://localhost:9200/articles/_search?pretty=true" -d '
  {
    "query" : { "query_string" : {"query" : "*"} },
    "facets" : {
      "tags" : { "terms" : {"field" : "author"} }
    }
  }
'

See if you can tailor this to work for you.

A: I think the optimal way is to use elasticsearch aggregation
https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-terms-aggregation.html
GET {index}/{type}/_search
{
  "size": 0, <-- to not display search hits
  "aggs": {
    "{aggregation_name}": {
      "terms": {
        "field": "{filed_value}",
        "size": 10
      }
    }
  }
}

A: You don't mention the Elasticsearch Version, but for ES 1.6, the preferred method is using aggregations.  Here is an example of what I use.
--Get all the STATUS values, which is a nested query.
GET path for data/_search?size=200
{
  "aggs": {
    "something": {
      "nested": {
        "path": "NESTED_PATH"
      },
      "aggs": {
        "somethingCodes": {
          "terms": {
            "field": "NESTED_PATH.STATUS",
            "size": 50
          }
        }
      }
    }
  }
}

and an example Response:
"aggregations": {
      "panels": {
         "doc_count": 5029693,
         "panelCodes": {
            "doc_count_error_upper_bound": 0,
            "sum_other_doc_count": 0,
            "buckets": [
               {
                  "key": "M",
                  "doc_count": 1943107
               },
               {
                  "key": "W",
                  "doc_count": 137904
               },
               {
                  "key": "E",
                  "doc_count": 69080
               },
               {
                  "key": "Y",
                  "doc_count": 4081
               },
               {
                  "key": "N",
                  "doc_count": 1063
               },
               {
                  "key": "T",
                  "doc_count": 483
               },
               {
                  "key": "",
                  "doc_count": 1
               }
            ]
         }
      }
   }

A: Fastest way of checking existing field values:
GET myindex/mytype/<id>/_termvectors?fields=Product.Material.Code

*

*myindex = index

*mytype = type

*<id> = document id

A: Please use the below code to get only list of 'articles' field values from all the content in the index.
curl 'http://localhost:9200/my_index/_search?pretty=true&_source=articles'
It will sure help you.


text:
Q: Using the same form for sign-up and edit - preloading values from the database I have the following function:
function create_table($titles, $id) {
    $buffer = '
';
    foreach ($titles as $k=>$v) {
        $buffer .= '<input type="checkbox" name="' . $k . '" id="' . $k . '">';
        $buffer .= '' . $v . '';
    }
    $buffer .= '
';
    echo $buffer;
}

This takes the values and keys from an associative array and sets up a group of checkboxes.These are for a signup page, but I also want to use the same page for the user to edit their profile. Therefore I need a way of loading the users preferences from the database into the checkboxes 'value' property. I've thought of passing the values into the function by changing the parameters to:
function create_table($titles, $values, $id)

and then calling the function with the following parameters:
    $id = "reasons";
$titles = $reasons_array;
$values = $stmt->fetch(PDO::FETCH_ASSOC);

However, if the user is trying to sign up rather than edit then the PDO Fetch will be trying to fetch from an empty database row.
If I have two different functions, one for editing one for signing up then the file will be full of if(edit==true) statements, but I cant think of another way of getting the values into the function IF the user is trying to edit! Help!

A: simple example
function viewTable($aData, $bEdit = false)
{
    echo $aData['some'];
    // ...
    if ($bEdit) { // or you can use isAuth() function without arg-var
        echo $aData['auth']; // hidden data only for edit page
    }
}

function getData()
{
    $aReturn['some'] = 123; // all vars you need;
    // ...
    if (isAuth()) {
        $aReturn['auth'] = 321; // only for authenticated (for edit)
    }

    return $aReturn;
}

function isAuth()
{
    return true; // check authentication
}

viewTable(getData(), isAuth());


text:
Q: Error nova-chart deployment for Openstack/helm I'm trying to deploy Openstack following the openstack-helm deployment
with NFS  following openstack-helm-deployment
When I launch the nova-chart to deploy nova services, I got this error
on the nova-compute pod
2020-07-01 15:28:48.487 7036 ERROR oslo_service.service [req-11d17c73-10fb-4fad-abc0-ddf4805267e9 - - - - -] Error starting thread.
    2020-07-01 15:28:48.487 7036 ERROR oslo_service.service Traceback (most recent call last):
    2020-07-01 15:28:48.487 7036 ERROR oslo_service.service   File "/var/lib/openstack/lib/python2.7/site-packages/oslo_service/service.py", line 722, in run_service
    2020-07-01 15:28:48.487 7036 ERROR oslo_service.service     service.start()
    2020-07-01 15:28:48.487 7036 ERROR oslo_service.service   File "/var/lib/openstack/lib/python2.7/site-packages/nova/service.py", line 180, in start
    2020-07-01 15:28:48.487 7036 ERROR oslo_service.service     self.rpcserver.start()
    2020-07-01 15:28:48.487 7036 ERROR oslo_service.service   File "/var/lib/openstack/lib/python2.7/site-packages/oslo_messaging/server.py", line 268, in wrapper
    2020-07-01 15:28:48.487 7036 ERROR oslo_service.service     log_after, timeout_timer)
    2020-07-01 15:28:48.487 7036 ERROR oslo_service.service   File "/var/lib/openstack/lib/python2.7/site-packages/oslo_messaging/server.py", line 188, in run_once
    2020-07-01 15:28:48.487 7036 ERROR oslo_service.service     post_fn = fn()
    2020-07-01 15:28:48.487 7036 ERROR oslo_service.service   File "/var/lib/openstack/lib/python2.7/site-packages/oslo_messaging/server.py", line 267, in <lambda>
    2020-07-01 15:28:48.487 7036 ERROR oslo_service.service     states[state].run_once(lambda: fn(self, *args, **kwargs),
    2020-07-01 15:28:48.487 7036 ERROR oslo_service.service   File "/var/lib/openstack/lib/python2.7/site-packages/oslo_messaging/server.py", line 420, in start
    2020-07-01 15:28:48.487 7036 ERROR oslo_service.service     self.listener = self._create_listener()
    2020-07-01 15:28:48.487 7036 ERROR oslo_service.service   File "/var/lib/openstack/lib/python2.7/site-packages/oslo_messaging/rpc/server.py", line 143, in _create_listener
    2020-07-01 15:28:48.487 7036 ERROR oslo_service.service     return self.transport._listen(self._target, 1, None)
    2020-07-01 15:28:48.487 7036 ERROR oslo_service.service   File "/var/lib/openstack/lib/python2.7/site-packages/oslo_messaging/transport.py", line 110, in _listen
    2020-07-01 15:28:48.487 7036 ERROR oslo_service.service     target)
    2020-07-01 15:28:48.487 7036 ERROR oslo_service.service InvalidTarget: A server's target must have topic and server names specified:<Target topic=compute>
    2020-07-01 15:28:48.487 7036 ERROR oslo_service.service
    Traceback (most recent call last):
      File "/var/lib/openstack/lib/python2.7/site-packages/eventlet/queue.py", line 118, in switch
        self.greenlet.switch(value)
      File "/var/lib/openstack/lib/python2.7/site-packages/eventlet/greenthread.py", line 214, in main
        result = function(*args, **kwargs)
      File "/var/lib/openstack/lib/python2.7/site-packages/oslo_service/service.py", line 725, in run_service
        raise SystemExit(1)
    SystemExit: 1

this is my nova.conf file
the conf file has beeen saved as secrets, i delete the passwors for security purposes
[DEFAULT]
compute_driver = libvirt.LibvirtDriver
cpu_allocation_ratio = 3
default_ephemeral_format = ext4
disk_allocation_ratio = 1
firewall_driver = nova.virt.firewall.NoopFirewallDriver
instance_usage_audit = true
instance_usage_audit_period = hour
linuxnet_interface_driver = openvswitch
log_config_append = /etc/nova/logging.conf
metadata_port = 80
metadata_workers = 1
my_ip = 0.0.0.0
notify_on_state_change = vm_and_task_state
osapi_compute_listen = 0.0.0.0
osapi_compute_listen_port = 8774
osapi_compute_workers = 1
ram_allocation_ratio = 1
resume_guests_state_on_host_boot = true
state_path = /var/lib/nova
transport_url = rabbit://nova:@rabbitmq-rabbitmq-0.rabbitmq.openstack.svc.cluster.local:5672,nova:@rabbitmq-rabbitmq-1.rabbitmq.openstack.svc.cluster.local:5672/nova
use_neutron = true
[api_database]
connection = mysql+pymysql://nova:password@mariadb.openstack.svc.cluster.local:3306/nova_api
max_retries = -1
[cache]
backend = dogpile.cache.memcached
enabled = true
memcache_servers = memcached.openstack.svc.cluster.local:11211
[cell0_database]
connection = mysql+pymysql://nova:password@mariadb.openstack.svc.cluster.local:3306/nova_cell0
max_retries = -1
[conductor]
workers = 1
[database]
connection = mysql+pymysql://nova:@mariadb.openstack.svc.cluster.local:3306/nova
max_retries = -1
[glance]
api_servers = http://glance-api.openstack.svc.cluster.local:9292/
num_retries = 3
[ironic]
api_endpoint = http://ironic-api.openstack.svc.cluster.local:6385/
auth_type = password
auth_url = http://keystone-api.openstack.svc.cluster.local:5000/v3
auth_version = v3
memcache_secret_key =
memcache_servers = memcached.openstack.svc.cluster.local:11211
password =
project_domain_name = service
project_name = service
region_name = RegionOne
user_domain_name = service
username = ironic
[keystone_authtoken]
auth_type = password
auth_uri = http://keystone-api.openstack.svc.cluster.local:5000/v3
auth_url = http://keystone-api.openstack.svc.cluster.local:5000/v3
auth_version = v3
memcache_secret_key =
memcache_security_strategy = ENCRYPT
memcached_servers = memcached.openstack.svc.cluster.local:11211
password = password
project_domain_name = service
project_name = service
region_name = RegionOne
user_domain_name = service
username = nova
[libvirt]
connection_uri = qemu+tcp://127.0.0.1/system
cpu_mode = none
disk_cachemodes = network=writeback
hw_disk_discard = unmap
images_rbd_ceph_conf = /etc/ceph/ceph.conf
images_rbd_pool = vms
images_type = qcow2
rbd_secret_uuid = 457eb676-33da-42ec-9a8c-9293d545c337
rbd_user = cinder
virt_type = qemu
[neutron]
auth_type = password
auth_url = http://keystone-api.openstack.svc.cluster.local:5000/v3
auth_version = v3
metadata_proxy_shared_secret = password
password = password
project_domain_name = service
project_name = service
region_name = RegionOne
service_metadata_proxy = true
url = http://neutron-server.openstack.svc.cluster.local:9696/
user_domain_name = service
username = neutron
[oslo_concurrency]
lock_path = /var/lib/nova/tmp
[oslo_messaging_notifications]
driver = messagingv2
[oslo_messaging_rabbit]
rabbit_ha_queues = true
[oslo_middleware]
enable_proxy_headers_parsing = true
[oslo_policy]
policy_file = /etc/nova/policy.yaml
[placement]
auth_type = password
auth_url = http://keystone-api.openstack.svc.cluster.local:5000/v3
auth_version = v3
os_region_name = RegionOne
password =
project_domain_name = service
project_name = service
user_domain_name = service
username = placement
[service_user]
auth_type = password
send_service_user_token = false
[spice]
html5proxy_host = 0.0.0.0
server_listen = 0.0.0.0
[upgrade_levels]
compute = auto
[vnc]
enabled = true
novncproxy_base_url = http://novncproxy.openstack.svc.cluster.local/vnc_auto.html
novncproxy_host = 0.0.0.0
novncproxy_port = 6080
vncserver_listen = 0.0.0.0
[wsgi]
api_paste_config = /etc/nova/api-paste.ini

all other services of nova are running


text:
Q: Does expo, problem with webview, it show page blank screen currency I am working with React Native and expo, yesterday I was working with WebView however my project it show blanck screen, when I compile my project, I see everything through of my phone, I already tried everything to solve it but I have not been successful, somebody can I help me plese?, i don't know what to do.
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { WebView } from 'react-native-webview';

const styles = StyleSheet.create({
 container: {
  flex: 1,
  backgroundColor: '#fff',
  alignItems: 'center',
  justifyContent: 'center',
 },
});

export default function App(){
  return (
    <View style={styles.container}>

Test

    <Text>Test text</Text>
    <WebView
      source={{ uri: 'https://www.youtube.com' }}
    />
    </View>
   );
}

Here is my package.json
{
  "main": "node_modules/expo/AppEntry.js",
  "scripts": {
  "start": "expo start",
  "android": "expo start --android",
  "ios": "expo start --ios",
  "web": "expo start --web",
  "eject": "expo eject"
},
"dependencies": {
  "expo": "~41.0.1",
  "expo-status-bar": "~1.0.4",
  "react": "17.0.2",
  "react-dom": "17.0.2",
  "react-native": "https://github.com/expo/react-native/archive/sdk-41.0.0.tar.gz",
  "react-native-web": "~0.16.3",
  "react-native-webview": "11.2.3"
},
"devDependencies": {
  "@babel/core": "^7.14.3"
},
"private": true

A: Having this issue as well, I noticed if I use the example on the github docs it will load a video, but so far not able to render html or a webpage:
<WebView source={{ uri: 'https://facebook.github.io/react-native/' }} />

A: Copy and paste this into Snack.expo.io
I am a little unclear as to what exactly your problem is but this renders the webpage fine on both android and iphones.
The issue that causes the white screen is the styling. If you remove the styling besides flex: 1, it renders completely.
export default function App(){
  return (
    <WebView
      source={{ uri: 'https://www.youtube.com' }}
    />
   );
}


text:
Q: AspectJ: Access private fields? I want to use an aspect to add getter and setter for a private id field. I know how to add a method through an aspect, but how can I access the private id field?
I thoght that I just have to make the aspect provileged. I tried the following code, but the aspect cannot access the id field.
public privileged aspect MyAspect {

public String Item.getId(){

    return this.id;
}

A possibility would be to user reflection like shown in this blog post: http://blog.m1key.me/2011/05/aop-aspectj-field-access-to-inejct.html
Is reflection the only possibility or is there a way to do it with AspectJ?

A: Are you sure you can't ? I just tested and it ran. Here's my full code:
package com.example;

public class ClassWithPrivate {
    private String s = "myStr";
}

==========

package com.example.aspect;

import com.example.ClassWithPrivate;

privileged public aspect AccessPrivate {

    public String ClassWithPrivate.getS() {
        return this.s;
    }

    public void ClassWithPrivate.setS(String str) {
        this.s = str;
    }
}

==========

package com.example;

public class TestPrivate {

    public static void main(String[] args) {

        ClassWithPrivate test = new ClassWithPrivate();
        System.out.println(test.getS());
        test.setS("hello");
        System.out.println(test.getS());
    }
}

If for some reason, that does not work for you, you can use reflection, or another way as described here:
https://web.archive.org/web/20161215045930/http://blogs.vmware.com/vfabric/2012/04/using-aspectj-for-accessing-private-members-without-reflection.html
However, according to the benchmarks, it may not be worth it.


text:
Q: How can I get the Textbox of a Tabpage in c# UWP? I'm new at c# UWP and I have tried to make a tabcontrol, which worked fine.
Now I tried to get the current textbox of the tabcontrol, but it didn't worked.
I already did it in winforms which worked fine:
private RichTextBox GetRichTextBox()
    {
        RichTextBox richtext= null;
        TabPage tab = tabControl1.SelectedTab;

        if (tab != null)
        {
            richtext = tab .Controls[0] as RichTextBox;
        }
        return richtext ;
    }

So I have no idea how to do the same in UWP.
I would be happy if someone can help me :D
Edit:
The import of the NuGet
xmlns:muxc="using:Microsoft.UI.Xaml.Controls"

Here the tabcontrol from MainPage.xaml:
<!--Tabcontrol-->
    <muxc:TabView HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
            AddTabButtonClick="TabView_AddTabButtonClick"
            TabCloseRequested="TabView_TabCloseRequested"
            Name="EditTabControl">
        <muxc:TabView.TabStripHeader>
            <Grid x:Name="ShellTitlebarInset" Background="Transparent" />
        </muxc:TabView.TabStripHeader>
        <muxc:TabView.TabStripFooter>
            <Grid x:Name="CustomDragRegion" Background="Transparent" />
        </muxc:TabView.TabStripFooter>
    </muxc:TabView>

And here how I've created the tabpages with the textbox
    void NewDocument(string text, string DocTitle)
    {
        var newTab = new muxc.TabViewItem();
        newTab.Header = DocTitle;
        TextBox tb = new TextBox();
        Thickness margin = tb.Margin;
        margin.Top = 40;

        tb.Text = text;
        tb.Margin = margin;
        tb.HorizontalAlignment = HorizontalAlignment.Stretch;
        tb.VerticalAlignment = VerticalAlignment.Stretch;
        tb.AcceptsReturn = true;
        tb.FontSize = 20;
        tb.IsSpellCheckEnabled = true;
        tb.IsHandwritingViewEnabled = true;
        tb.IsTapEnabled = true;
        ScrollViewer.SetVerticalScrollBarVisibility(tb, ScrollBarVisibility.Auto);
        ScrollViewer.SetHorizontalScrollBarVisibility(tb, ScrollBarVisibility.Auto);

        newTab.Content = tb;
        EditTabControl.TabItems.Add(newTab);
        EditTabControl.SelectedIndex = EditTabControl.TabItems.Count - 1;
    }

A: You could try to get the list of the TabViewItems first, after that you could get specific TabItem based on the index. And then you will be able to get the content of TabViewItem and it should be the TextBox Control.
You could refer to the following code:
          //get the tabitems array
        var TabItems = EditTabControl.TabItems.ToArray();
        //get the tabitem based on the index.
        MUXC.TabViewItem targetItem = (MUXC.TabViewItem)TabItems[0];
        //get the textbox you added to the tabitem
        TextBox content = (TextBox)targetItem.Content;
        //change the text
        content.Text = "This is test";


text:
Q: Modal: using modal within elements that were loaded via AJAX after document.load() What happened: I have a page where user has to click on a button and selection is displayed in modal. When they clicked on what ever they wanted div element on the page is updated, via AJAX, which shows what they have selected and has an option "view item".
I have defined that "view item" should open up another modal view which will have all the information on the item, and now, referring to the above paragraph, rather then opening modal view user is being transferred to that page?
Question:
Is their a walk around for modal to be activated on the elements that were loaded after document load stage?
Example code: On initial load user is presented with following code, at this example item was set prior to load:

    Item 1
    view selection

<input type="radio" name="selection" id="selection" value="" data-toggle="modal" data-remote="/selection/search/1"  />Change selection

When user have picked a different item after clicking on "change selection" #dynamic-area was fully updated with a data that was fetched via AJAX on the selected item.
So lets say, if user have picked item 3, we would have code below:

    Item 3
    view selection

<input type="radio" name="selection" id="selection" value="" data-toggle="modal" data-remote="/selection/search/1"  />Change selection

Now if user to click on the "view selection", user is being to the page 'selection/view/3' when user should see modal.

A: After extending this function action worked as it should


text:
Q: List tracks from Soundcloud and play it with Soundmanager 2 on a Wordpress blog first of all this is not a cry for a perfectly coded solution but it would be perfect if someone could at least give me some tips on how to solve this problem which is: I have this custom Wordpress site for a record label. On this site there is of course a section showing the releases of every of their artist's tracks.
The client needs to upload all their tracks to Soundcloud. In the WP backend they can enter the name of the album, upload a cover image and add as many tracks as they want using MagicFields for Wordpress. After adding the album information and the track names they can enter the URL of the specific track hosted on Soundcloud. WP then lists all of these tracks as following:
(It seems I can not upload images so here is the link)
http://postimage.org/image/22ob8ymys/
On the left side you can see Soundmanager2's 360 visualization. Right now the MP3s are uploaded to the label's website (which I need to change) and the link of each list item looks something like this:

Track 1

  ...

As you can see the link leads to specific files, ending with the extension .mp3 to make it playable via SM2. But as you might know you can not easily access an MP3 on Soundcloud. Passing an URL like 'www.soundcloud.com/artist/track1' seems not to work.
I've made some research about Soundcloud's API but guess what, it's too complex for me to understand (that's why I am here).
The documentation on http://soundcloud-sm2.heroku.com/docs/application.html came quite close to what I was looking for but unfortunately I can not use it because the tracks should not be included on the site via JS but PHP.
I hope someone of you could give me some tips on how to solve this specific problem.
Thanks for reading this far ;)

A: You need to get the stream URI using Soundcloud's API. You can get the stream URI by making a request like:
https://api.soundcloud.com/tracks/5677638.json

where 5677638 is the id of the track you want to get the info of.
But you do need an API key which you can request for free at: Soundcloud Developers
So after that you can make a request like:
https://api.soundcloud.com/tracks/5677638.json?consumer_key={your api key}

That request will get you an json encoded string which contains all the info about the track, e.g.:
{
  "id": 5677638,
  "created_at": "2010/09/29 19:46:01 +0000",
  "user_id": 378405,
  "duration": 183945,
  "commentable": true,
  "state": "finished",
  "sharing": "public",
  "tag_list": "electro electrohouse remix green velvet remixcontest remixcompetition remixcomp foem uptempo",
  "permalink": "green-velvet-feat-santiago-bushido-turn-it-up-sander-van-halem-remix",
  "description": "Now let's turn it up up up up! :D Remix comp at http://foem.info/index.php?option=com_content&task=view&id=383&Itemid=97 . Some feedback would be appreciated. ",
  "streamable": true,
  "downloadable": true,
  "genre": "",
  "release": "",
  "purchase_url": null,
  "label_id": null,
  "label_name": "",
  "isrc": "",
  "video_url": null,
  "track_type": "remix",
  "key_signature": "",
  "bpm": 128,
  "title": "Green Velvet feat. Santiago and Bushido - Turn It Up (Sander van Halem Remix)",
  "release_year": null,
  "release_month": null,
  "release_day": null,
  "original_format": "mp3",
  "license": "all-rights-reserved",
  "uri": "https://api.soundcloud.com/tracks/5677638",
  "permalink_url": "http://soundcloud.com/sander-van-halem/green-velvet-feat-santiago-bushido-turn-it-up-sander-van-halem-remix",
  "artwork_url": "http://i1.sndcdn.com/artworks-000002478404-sy6zd5-large.jpg?6cbf23e",
  "waveform_url": "http://w1.sndcdn.com/1Iydbj7KnvOi_m.png",
  "user":  {
    "id": 378405,
    "permalink": "sander-van-halem",
    "username": "Sander van Halem",
    "uri": "https://api.soundcloud.com/users/378405",
    "permalink_url": "http://soundcloud.com/sander-van-halem",
    "avatar_url": "http://i1.sndcdn.com/avatars-000000760311-hwm8iz-large.jpg?6cbf23e"
  },
  "stream_url": "https://api.soundcloud.com/tracks/5677638/stream",
  "download_url": "https://api.soundcloud.com/tracks/5677638/download",
  "playback_count": 1386,
  "download_count": 67,
  "favoritings_count": 17,
  "comment_count": 34,
  "attachments_uri": "https://api.soundcloud.com/tracks/5677638/attachments"
}

As you can see there is an stream_url item which contains the URL you can use to 'embed' the track using SoundManager just like you would with a local mp3.


text:
Q: Why do most of the classes of Java frameworks extend serializable interface? Serialization is technique where we send convert objects into byte code for sending it over the network. Now, a lot of classes of Java frameworks(Spring, hibernate(SessionFactory) et. al) extend serializable interface? Why is that so?
Why searching on the web I found this piece of text "Serialized classes can support coherent versioning and flexible enough to allow gradual evolution of your application object schema".
Is this the correct answer of question above? If yes kindly explain it, if not then what's the actual cause of classes extending serialable interface

A: I think you can see this as a mean of precaution: having your classes being serializable from the beginning doesn't cost you much.
But adding that later to your code has the potential of being way more expensive.
Beyond that: making your classes serializable actually forces you to think/consider such "aspects" when creating your class. Thus it can help to improve the quality of your design - because you don't forget about that aspect.

A: One possible reason is that web containers may store session data on disk if needed (e.g. high server load and session is inactive for some time). For that to work, all data stored in session (transitively, i.e. all instances referenced directly or indirectly by session data) must be serializable.
Additionally to any data you're storing in session, many frameworks store some data in session as well (session-scoped beans, as a Spring-related example).


text:
Q: URL rewriting not doing what it's supposed to do, but code seems fine I've been working on a website for a friend lately, on which she can upload images of her paintings. Along with those images some information like size and techniques are entered. These images are added to an album which are then displayed in the gallery. The functionality is there, now I just want to rewrite the urls so they don't look like album.php?album_id=xx&name=xx. I want the urls to be like album/id/name. To do that, I have the following rewrite rule:
RewriteRule ^album/([0-9]+)/([0-9a-zA-Z_-]+) album.php?album_id=$1&naam=$2 [NC]

This means that if I'd go to album/1/test, it should get the data for that album and display it, but it doesn't fully work. It does get the data for that album, but the image isn't loaded (even though when inspecting the source it's loaded in correctly) and there isn't any styling anywhere on the page, even though the stylesheets are loaded in correctly. The strange thing is, that if I go to album.php?album_id=1&naam=test the whole page works, so I know the code in the album.php page works. I have also created a test.php file with the following code:
<?php
echo 'ID: ' . $_GET['album_id'] . '<br>';
echo 'Naam: ' . $_GET['naam'];

With the following rewrite rule:
RewriteRule ^test/([0-9]+)/([0-9a-zA-Z_-]+) test.php?album_id=$1&naam=$2 [NC]

If I go to test/1/test, I get what I want:
ID: 1
Naam: test

So I know the rewriting works.
The code for album.php can be found here
Any idea what is causing the styling to not load and the image to not load correctly?

A: It sounds like you are using relative paths for your stylesheet and your images.
If you use for example images/album.jpg for your image, it will look for:
http://www.yoursite.com/images/album.jpg

when you load index.php directly.
However, it will look for:
http://www.yoursite.com/album/1/test/images/album.jpg

with your rewrite rule in place.
An easy solution is to always use absolute paths, relative to the root of the web-server, like:
/images/image.jpg
/styles/styles.css

Note the slash / at the start.


text:
Q: What to do with a random variable when we know its mean and variance but does not know which distribution it is? Let Y be a random variable with mean μ and variance σ^2 where the support is (0, ∞). Suppose you are offered to play a game where you choose a number z between (0, ∞). If a realization of the random variable y is greater than z then you win $z, otherwise you lose z dollars.
a. What value of z maximizes your expected gain? Can this maximum ever result in a loss? following is my work:
Let g(z) denote the expected gain,
g(z)  = z(1-F_{y}(z))-zF_{y}(z)
take diervative with respect to z,
g′(z)  = ((dg(z))/(dz))=1-F_{y}(z)-z∗f_{y}(z)-z∗f_{y}(z)-F_{y}(z)
 = 1-2F_{y}(z)-2z∗f_{y}(z)
let g′(z)  = 0,
1  = 2F_{y}(z)+2z∗f_{y}(z)
F(z)  = (1/2)-z∗f_{y}(z)
replace back to g(z)
g(z)  = z(1-(1/2)-z∗f_{y}(z))-z((1/2)-z∗f_{y}(z))
 = 2z²∗f_{y}(z)
F is the cdf, f is the pdf.
I do not know how to use the mean and variance of Y, the problem is we do not know the distribution of Y.
Now part b:
b. How large is the maximum expected gain for if Y ∼ exponential(λ).
My work again,
f_{y}(y)=λe^{-λy}
F_{y}(y)=1-e^{-λy}
and subs into g′(z)=0⇒1=2F_{y}(z)+2z∗f_{y}(z)
1=2(1-e^{-λz})+2z∗λe^{-λz}
and solve for z, I got z=((1-W((e/2)))/λ)≈((0.314923)/λ)
and replace this into g(z)=2z²∗f_{y}(z),
I got ((2e^{W((e/2))-1}(1-W((e/2)))²)/λ)≈((0.14477)/λ)
I do not think this is quite right.
Any suggestion will be appreciated! Thanks in advance.

A: Assume that $X$ is a continuous random variable.
The expected gain is, as you say LaTExlessly, $z(1-F(z))-zF(z) = z(1-2F(z)) = g(z)$. As Neil pointed out to you, this is $0$ when $z$ equals the median $m$. For
$z > m$, $F(z) > \frac 12$ and so $g(z) < 0$. Since $g(0) = 0$, the question is,
what is the behavior of $g(z)$ in the interval $(0,m)$? In this interval, $z>0$ and
$F(z) < \frac 12$ and so $g(z) > 0$. Thus $g(z)$ does indeed have a positive
maximum in $(0,m)$. The harder question is how can we determine the location of
this maximum from knowledge only of the mean and variance of $X$.
It is known that the difference between the mean $\mu$ and the median $m$ is no
larger than the standard deviation $\sigma$. See for example
here
or there.  Thus, if
$\mu>\sigma$, we can choose $z = \mu-\sigma > 0$ and be guaranteed a nonnegative
(but not necessarily maximal) expected gain.


text:
Q: Form WHERE clause I have an APEX form I'm developing for "user settings". I have a table with a sequence as a primary key and the users ID in another column...in addition to a few columns where each users saved settings are stored (things like "N" for do not receive notices).
I haven't used Oracle APEX in a while so excuse this likely newbie question...The insert works fine, but I'm having trouble with making the form only show the current users values. In my Form Region the source is set to my Table, and I have a WHERE clause like this:
USER_ID = 813309
But that's not working (813309 is my id and I'm just hard-coding it for now). The form always comes up with a "New" record.

A: In such cases, I prefer creating a Report + Form combination (using the Wizard, of course): it creates an interactive report (so that you can review data in a table), and a form which is used to add new records or update/delete existing ones.
Doing so, when you pick a user in interactive report and click the icon at the beginning of a row, Apex redirects you to the form page, passing primary key column value to the form which then fetches appropriate data from the table.
Not that it won't work the way you're trying to do it, it's just simpler if you let Apex do everything for you.
So: did you create an automatic row fetch pre-rendering process? If not, do so because - without it - Apex doesn't know what to fetch. Also, if you hardcoded user_id, it won't do much good. Consider storing username into the table so that you could reference it via :APP_USER Apex variable.

A: For a form to load a specific record you can set the primary key page item to the value you need. You can do so in the url using the link builder from another page or you can set a computation on the item. That is what I would try in your case: add a computation to your item P_USER_ID of type "Static Value" with value 813309. Make sure the computation happens before the "Fetch Row" - the value obviously needs to be set before the process runs.


text:
Q: TS2693: 'T' only refers to a type, but is being used as a value here so as not to repeat the code, I would like to create an abstract class once, which will connect to the appropriate repository depending on the initialization of the class with the appropriate type T. However, I have a problem that I don't know how to call the value T and not the type as a parameter of the getRepository method from typeorm package.
import {getDataSource} from "../utils/data-source";
import {Category} from "../model/category";
import {EntityTarget, ObjectLiteral} from "typeorm";

export abstract class Controller<T> {
    protected repository;

    public init = async () => {
        this.repository = (await getDataSource()).getRepository(T);
    };
}

getRepository(T);
this method has the problem mentioned in the title

A: This is the easiest way to do it, if there isn't a better one
import {getDataSource} from "../utils/data-source";

export abstract class Controller {
    protected repository;

    public init = async (type) => {
        this.repository = (await getDataSource()).getRepository(type);
    };
}


text:
Q: Reuse variable name to point at different data So I am getting tripped up by what appears to be a variable in Python behaving like a pointer in C i.e. For example:
foo = ['item1', 'item2', 'item3']

now if I assign that list to the value of a dictionary whose key is 'bar':
my_dict['bar'] = foo

all is fine, but now if I do:
foo.clear()

then my_dict['bar'] is now empty implying that foo and my_dict['bar'] are just two different names pointing at the same data. How can I get around this so I can dump foo into my_dict['bar'] and then reuse foo for the next item in the dictionary please?
How can I get around this so that I can reuse 'foo'?

A: You're correct in that it's like a pointer. Collections of data, such as lists, dictionaries, objects etc are passed by reference. Therefore when you set mydict["bar"] = foo you were setting it equal to the reference of foo.
To get around this you would need to make a copy of foo. You should get by with a shallow copy
mydict["bar"] = foo[:]
I this case the slice operator will create a new list of all elements in foo, with a new reference value. You could also consider the copy python module, which would have a similar effect but supports deep copy operations. i.e. it create copies of the object itself, and all objects contained within it.
Please also read jasonharper's comment on this. If you don't need a copy of the elements it's more efficient to just create a new empty list


text:
Q: iReport Designer - dynamic list and page number I have put a list inside a rectangle with Relative to Tallest Object property which is inside a frame with Float property. All the components are inside the detail band. The size of the list component depends on the list which is sent from my Java application.
When I print a report with 100 objects inside a list, all records are not printed inside a rectangle. I don not know how I can fix it. Just the first page has a rectangle.
Also, I have a problem with page number. I put the page number variable at the bottom of the detail band with maximum height, but it is printed just on the first page. On other pages there is no any page number.
It would great if someone can help me.


text:
Q: Разница между датами Python Подскажите как вычислить разницу во времени для такой задачи: нужно чтобы при обновлении страницы поста было видно что пост обновлен 5 мин назад, или час назад - вообще некоторое время назад. Так чтобы для пользователей ничего не ломалось если они находятся в разных часовых поясах.
class Post(GenericPage):
    category = models.ForeignKey(Category, null=True, blank=True, on_delete=SET_NULL)
    created_date = models.DateTimeField(default=now, verbose_name='publication date')
    modified_date = AutoLastModifiedField()
    short_description = models.TextField(blank=True, null=True)
    infografic = models.ImageField(upload_to='blog/post/', null=True, blank=True)
    image = models.ImageField(upload_to='blog/thumbnails/', null=True, blank=True)
    related_posts = models.ManyToManyField('self', blank=True)
    active = models.BooleanField(default=True, verbose_name='published')

A: 5 минут одинаковы в любом часовом поясе, вычисляй разницу на сервере, как время запроса - время публикации согласно серверному времени и уже ее передавай на страницу.
Например - время публикации поста (по серверу) - 16:45
Это соответствует 18:45 для часового пояса случайного юзера.
Время загрузки/обновления страницы - 17:00 по серверу
и 19:00 по часовому поясу юзера.
17:00 - 16:45 = 15 минут
19:00 - 18:45 = 15 минут
Т.Е. в контексте этой задачи можно абстрагироваться от пользователя

A: В django для этого уже есть готовая библиотека django.contrib.humanize: https://docs.djangoproject.com/en/2.1/ref/contrib/humanize/#naturaltime
Можно поключать прямо в шаблонах:
{% load humanize %}

<div>{{ item.date|naturaltime }}</div>

Например, (если 'now' - 17 Фев 2007 16:30:00):
17 Фев 2007 16:30:00 станет - сейчас.
17 Фев 2007 16:29:31 будет - 29 секунд назад.
и т.д.


text:
Q: Error when trying to build solution in TFS 2015 sp3 - can't figure it out We are developing with VS2019, managing all code and builds in On-Prem TFS 2015 service pack 3.
Been running into the following TFS build issue and can't figure out what the real problem is. I verified the FxCopAnalyzers in the solution/projects are installed via Nuget and checked into TFS. This all builds fine locally on my sandbox workstation. The TFS warnings claim the file(s) cannot be found, but they are there. Very frustrating.
In the build config > process tab, the solution is using the Default v12 build template (as are ~50ish other builds) and I've set it to run as a CI build.
I'm missing something, but have been fighting this for so long I think I have tunnel vision. What could the real problem be? Any help is much appreciated. Thanks in advance.
CSC: An instance of analyzer Microsoft.CodeAnalysis.VersionCheckAnalyzer.AnalyzerVersionCheckAnalyzer cannot be created from E:\BuildAgentWorking\4\ACTS\ACTS v1.0 SLN (CI)\src\packages\Microsoft.CodeAnalysis.VersionCheckAnalyzer.2.9.8\analyzers\dotnet\Microsoft.CodeAnalysis.VersionCheckAnalyzer.dll : Could not load file or assembly 'Microsoft.CodeAnalysis, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified..
 CSC: An instance of analyzer Microsoft.CodeQuality.CSharp.Analyzers.Maintainability.CSharpVariableNamesShouldNotMatchFieldNamesAnalyzer cannot be created from E:\BuildAgentWorking\4\ACTS\ACTS v1.0 SLN (CI)\src\packages\Microsoft.CodeQuality.Analyzers.2.9.8\analyzers\dotnet\cs\Microsoft.CodeQuality.CSharp.Analyzers.dll : Could not load file or assembly 'Microsoft.CodeAnalysis, Version=2.9.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified..
 CSC: An instance of analyzer Microsoft.CodeQuality.Analyzers.Maintainability.DoNotIgnoreMethodResultsAnalyzer cannot be created from E:\BuildAgentWorking\4\ACTS\ACTS v1.0 SLN (CI)\src\packages\Microsoft.CodeQuality.Analyzers.2.9.8\analyzers\dotnet\cs\Microsoft.CodeQuality.Analyzers.dll : Could not load file or assembly 'Microsoft.CodeAnalysis, Version=2.9.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified..
 CSC: An instance of analyzer Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.UriPropertiesShouldNotBeStringsAnalyzer cannot be created from E:\BuildAgentWorking\4\ACTS\ACTS v1.0 SLN (CI)\src\packages\Microsoft.CodeQuality.Analyzers.2.9.8\analyzers\dotnet\cs\Microsoft.CodeQuality.Analyzers.dll : Could not load file or assembly 'Microsoft.CodeAnalysis, Version=2.9.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified..
 CSC: An instance of analyzer Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.AbstractTypesShouldNotHaveConstructorsAnalyzer cannot be created from E:\BuildAgentWorking\4\ACTS\ACTS v1.0 SLN (CI)\src\packages\Microsoft.CodeQuality.Analyzers.2.9.8\analyzers\dotnet\cs\Microsoft.CodeQuality.Analyzers.dll : Could not load file or assembly 'Microsoft.CodeAnalysis, Version=2.9.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified..

A: If you've referenced the Microsoft.Net.Compilers pacakge, update it to latest version. If not, add reference to its latest version.
If you have a version of Microsoft.CodeAnalysis.FxCopAnalyzers that is too high for your version of Visual Studio you can get this warning:
warning CS8032 ...

To find the max version supported see this documentation: Install FxCop analyzers in Visual Studio -> FxCopAnalyzers package versions


text:
Q: Pass Perl array to bash script I am attempting to connect to the Footprints API using a Perl script. I am using Perl because that's one of the few languages the Footprints API will work with.
I want this Perl script to gather the data from Footprints, place the data in an array, and pass that array back to the shell script which calls it.
How do I pass an array from a Perl script to a bash script?
Below is the template for connecting to the Footprints API and collecting the data.
Template:
use strict;

use SOAP::Lite;

my $USE_PROXY_SERVER = 1;

my $soap = new SOAP::Lite;

$soap->uri( 'http://fakeserver.phoneycompany.com/MRWebServices' );

if ( $USE_PROXY_SERVER ) {
    $soap->proxy(
        'http://fakeserver.phoneycompany.com/MRcgi/MRWebServices.pl',
        proxy => ['http' => 'http://localhost:8888/'] );
}
else {
    $soap->proxy( 'http://fakeserver.phoneycompany.com/MRcgi/MRWebServices.pl' );
}

my $soapenv = $soap->MRWebServices__search(
    'WebServices',
    'fakepassword',
    '',
    "select mrID, mrTITLE from MASTER78 WHERE mrTITLE LIKE '%of%'"
);

my $result;

if ( $soapenv->fault ) {
    print ${$soapenv->fault}{faultstring} . "\n";
    exit;
}
else {
    $result = $soapenv->result;
}

my @result_list = @{$result};

for ( my $i = 0; $i <= $#result_list; $i++ ) {

    print "RESULT $i\n";

    my $hash_ref = $result_list[$i];

    foreach my $item ( keys %{$hash_ref} ) {
        my $val = $hash_ref->{$item};
        print "$item = '$val'\n";
    }

    print "---------------------\n";
}

In the template, I think it is just printing the key/value pairs to stdout.
I am new to Perl and am only using it to search the Footprints API. I'm not sure if you can somehow capture that data from stdout with the bash script, or if I have to do make an array or a string representation of the array and return that.
In my bash script, I was going to assign the result of the Perl script to a variable like VAR=(perl perl_script.pl). But I don't know how to do that for an array, which was why I was thinking about the string representation of the array, assigning it to a variable and parsing it in bash afterwards.
I don't know how to set that up in Perl though, so I need help with that.

A: Short answer is - you can't pass data structures between programs.
You can just pass text (and binary content, but I'd suggest you don't want to do that here).
One of the easiest ways of doing that is using an existing data interchange format, like JSON:
use JSON;
print to_json(\@result_list);

And then decode the JSON form within your bash script, manually.
Or just y'know, do all the work in perl. It's not that different.

A: While, in general, and probably in this specific case, I would go with the "do it all in X" where X is anything more advanced than the shell, I have had to do this once or twice.  Mostly because I was setting up an interactive shell environment.
What I ended up doing is the same thing that tools like ssh-agent -s do: building the shell commands that would result in the environment being set as desired, and then having the parent shell eval them, e.g.:
eval $(perl perl_script.pl)
Just watch out to ensure every separate command is separated by ; since \n's are (usually) squashed.
Another alternative, which I like a fair bit less, but I've used when generating variables for Windows' batch files, is to output the same to a new file and allow the parent batch file to call it (or, in shell, source it).  I'm not a big fan of temporary files if I can avoid them though it can make debugging a fair bit easier.


text:
Q: Insert result into temp table mariadb i am trying to insert my results to a temporary table i created before.
Dont know why this is not working. Need help thank you.
Code:
SET @serial = '75900101';
DROP TEMPORARY TABLE IF EXISTS machinenametable;
CREATE TEMPORARY TABLE machinenametable (id INT, name VARCHAR(100));

WITH machine_data AS (
SELECT
    *
FROM
    machine m
WHERE
    @serial = m.serial
), machine_id AS (
SELECT
    1 AS id,
    (IF(
        md.identifier LIKE 'PP%',
        (SELECT 'PP'),
        IF(
            md.identifier LIKE 'SHL',
            (SELECT 'SHL'),
            (SELECT 'SL')
        )
    ))  AS machine
FROM machine_data md
)
INSERT INTO machinenametable (id, name)
SELECT id, name FROM machine_id

Something with this Insert into is wrong but i dont have any idea why....
Getting a Error Msg :
SQL-Error[1064] [42000]: (conn=3127818) You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'INSERT INTO machinenametable (id, name)

EDIT:
This is Working:
INSERT INTO machinenametable (id, name)
    SELECT
        1 AS id,
            (CASE WHEN m.identifier LIKE 'PP%' THEN 'PP'
             WHEN m.identifier LIKE 'SHL' THEN 'SHL'
             ELSE 'SL'
             END) AS name
    FROM machine m
    WHERE @serial = m.serial

A: I think the issue is with the usage of the insert command.
Edit the INSERT command and use as
INSERT INTO machinenametable VALUES(id, name)

A: You have very complicated logic for something that seems rather simple.  I think this does what you want:
INSERT INTO machinenametable (id, name)
    SELECT 1,
           (CASE WHEN md.identifier LIKE 'PP%' THEN 'PP'
                 WHEN md.identifier LIKE 'SHL' THEN 'SHL'
                 ELSE 'SL'
            END)
    FROM machine m
    WHERE  @serial = m.serial;

The CTE do nothing useful.  And the use of IF instead of CASE is convoluted.  And using SELECT for constants is simply unnecessary.


text:
Q: How do public ssh servers like git@github.com automatically reject connections and send a message? When I ssh to git@github.com, I get a message that looks like this:
Hi <my username>! You've successfully authenticated, but GitHub does not provide shell access.
The connection is then closed. I understand this is intentional behavior, but how do they do it? Is there a config option in sshd_config? Is it a different or proprietary package to manage ssh connections? How do they change the message to include the username?
I have no idea what to look up to find these answers. Any searches involving TTY allocation seem to only return troubleshooting for servers that shouldn't be doing that.

A: It's either that the user shell is set to /bin/false (or something else that does nothing) and there is a sshd "banner" or "motd" (message of the day) that has that message,
or that the user shell is set to a program that emits that message and exits.


text:
Q: How can we get same channelID at all installation in UAPush plugin + phonegap I need channel-ID to send push notification by PhoneGap plugin in Android/iOS. I'm able to get channel-id same in iOS but Android gives different Channel-Id at all re-installation. I need same Channel-Id at all- reinstallation. Please help me if any one implemented it. Thanks a-lot.

A: I have google but i got that , on each installation , app creates new channel ID. Please follow given link.
http://docs.urbanairship.com/platform/android.html
So, If we want to save and access first created channel-ID over re-installation, we should use permanent storage to store first generated channel-ID and access it at all installation.


text:
Q: Rearranging data in file with awk I have a table
 ID   Comment    Statement
  1    hi         hello
  2    hi         hello
  1    cya        bye
  1    k          ok
  2    kk         ok

How would one go about producing a result like the following, using awk?  So the ID becomes the attribute, and it maintains the same order as the statement.
 1       2
 hi      hi
 cya     N/A
 k       kk

A: This produces your desired output
awk '
  NR>1 {
    ids[$1]
    if (s!=$3) c++
    statements[c]=$3
    s=$3
    comments[$3,$1]=$2
  }
  END {
    for (id in ids)
      printf "%s\t", id
    print ""
    for (i=1; i<=c; i++) {
      for (id in ids) {
        comment = (comments[statements[i],id] ? comments[statements[i],id] : "n/a")
        printf "%s\t", comment
      }
      print ""
    }
  }
' file

You have to remember a few things to maintain the order.

A: awk 'BEGIN { colwidth=8; format="%-" colwidth "s"; printf format "%s\n","1","2"; };
  NR==1 {next;};
  /^ *1/ { if (NR>2) print col2; col2="N/A"; printf format,$2; };
  /^ *2/ { col2=$2; };
  END { print col2;} ' file
1       2
hi      hi
cya     N/A
k       kk


text:
Q: How can i edit the error message box in CF-7? i had add some extra field on the CF-7 form everything work fine except the respond message box. im getting something like this
https://i.stack.imgur.com/JulGC.png
but i was hoping to get the error message only display next to my "Submit" Button.
is there anyway i can archive that? Im new to wordpress so im not really sure where can i start.

A: you can use jquery validation. You can easily implement jquery validation in contact form 7
here is sample code for jquery validation.
$(".wpcf7-form").validate({
    rules: {
       yourname: "required",
     youremail: {
       required: true,
       email: true
      },
    },
       messages: {
        yourname: "Please include your name.",
        youremail: "Please include a valid email address.",
        yourmessage: "Please tell me how I can help you.",

    },
});

or PHP code,Link contact form 7
add_filter( 'wpcf7_validate_email*', 'custom_email_confirmation_validation_filter', 20, 2 );

function custom_email_confirmation_validation_filter( $result, $tag ) {
if ( 'your-email-confirm' == $tag->name ) {
    $your_email = isset( $_POST['your-email'] ) ? trim( $_POST['your-email'] ) : '';
    $your_email_confirm = isset( $_POST['your-email-confirm'] ) ? trim( $_POST['your-email-confirm'] ) : '';

    if ( $your_email != $your_email_confirm ) {
        $result->invalidate( $tag, "Are you sure this is the correct address?" );
    }
}

return $result;
}

or may use this plugin. Jquery Validation For Contact Form 7
Hope this wiull helps you.


text:
Q: My node.js server doesn't work when launched from another directory I'm trying to get my node.js server to launch on startup.  If I'm in my server folder and type:
node server.js

It runs just fine and launches python scripts that are in the same folder.
But if I run it from outside that directory or from an init script, like this:
node /home/servers/server.js

It starts, and receives calls, but is not running the python scripts as it is supposed to.
Does anyone know what is going on and how I can fix it?  Thanks.

A: When you run node, it references all filesystem calls from the directory node was called from, instead of the directory that app.js is in, so if you're trying to require('./myfile'), myfile.js will need to be in the directory you're running node in.
Run this simple script from different directories to see it in action (it runs ls, lovingly copied from here):
var sys = require('sys')
var exec = require('child_process').exec;
function puts(error, stdout, stderr) { sys.puts(stdout) }
exec("ls -la", puts);

As to your Python problem, you should develop an empirical location to call app.js from, and use that when locating scripts.

A: You can also change the directory to ensure you're where you need to be. Just add something like this to the top of your file:
__dirname points to the directory containing the current file. For this example I will be assuming the following repo structure:
repo/
    src/
        index.js
    package.json

And inside index.js I will put:
const path = require('path');

process.chdir(path.join(__dirname));


text:
Q: Texture makes entire scene Black and White? OpenTK I have a texture where it is a 4x4 grid in a 256x256 pixel jpg. If i use that picture for my texture, my entire scene turns black and white. However if I use a different pattern, a checkerboard, the scene has color again. I did make the 2nd texture in GIMP if that has something to do with it. I have quite a lot of code so If anyone has an idea what could be the problem that would be awesome. Otherwise, I will paste bin the code so that you can probably find the one thing I missed lol.
Basically, I just followed the StencilCSG OpenTK example for loading a jpg. I also used the wrap modes for textures. It seems like if I just use some random texture from Google Images it works but my own textures make it all black and white. I think it has to do with how GIMP saves the files in SRGB but idk.
EDIT:
I found a work around right after I decided to post a question. I just disable textures after I render my textured square. I found a FAQ for opengl textures that said to disable and enable when needed. This works but I didnt think you needed to do that. Anyway, I would still love to know what was happening behind the scenes to make my scene black and white.

A: Solution, turn off textures after you render all of your textured polys.


text:
Q: Creating a pdf from byte type list in python I am trying to remove contact information from a pdf(that contains a MCQ question each page). I have extracted the text from the pdf and created a list containing the list of words that actually need. I am having trouble now creating a new pdf. Here is the code i used
'''from fpdf import FPDF '''
text = textract.process("/home/hari/Desktop/test.pdf")
#print(text)
words= []
words = text.split()
to_pop =[]
#print(words)
final = []
for i in range(len(words)):
  if(words[i]== b'Contact.' or words[i] == b':' or words[i] == b'8400-582-582,' or words[i] == b'8604-582-582' ):
    to_pop.append(i)
    words[i] = ''

for i in range(len(words)):
  if (i not in to_pop):
    final.append(words[i])

Now final contains all the text that is needed. How do I now create a new pdf from this?
A sample of the content contained in final is:
[b'egkeSjkF', b'ku', b'CHEMICAL', b'BONDING', b'with', b'Anurag', b'Sir', b'01', b'Out', b'of', b'following', b'which', b'one', b'has', b'least', b'value', b'of', b'melting', b'point', b'(A)', b'LiCl', b'(B)', b'BeCl2', b'(C)', b'MgCl2', b'(D)', b'CaCl2', b'02', b'Out', b'of', b'following', b'which', b'one', b'has', b'maximum', b'ionic', b'character', b'(A)', b'NaCl', b'(B)', b'KCl', b'(C)', b'CaCl2', b'(D)', b'MgCl2', b'03', b'Which', b'of', b'the', b'following', b'has', b'highest', b'melting', b'point', b'(A)', b'NaCl', b'(B)', b'NaI', b'(C)', b'NaBr', b'(D)', b'NaF', b'04', b'What', b'is', b'not', b'true', b'about', b'resonance', b'?', b'(A)', b'The', b'resonating', b'structures', b'are', b'hypothetical', b'(B)', b'The', b'unpaired', b'electrons', b'in', b'various', b'resonating', b'structures', b'are', b'same', b'(C)', b'Hybrid', b'structure', b'is', b'most', b'energetic', b'(D)', b'Hybrid', b'structure', b'is', b'least', b'energetic', b'05', b'Which', b'of', b'the', b'following', b'conditions', b'is', b'not', b'correct', b'for', b'resonating', b'structures', b'?', b'(A)', b'The', b'contributing', b'structures', b'must', b'have', b'the', b'same',

I need to create a new page for every question.

A: Let us say you have your list, l, of those bytes.
You can do the following:
from fpdf import FPDF

pdf = FPDF()
pdf.add_page()
pdf.set_font('Arial', '', 12)
# multi_cell will wrap the input to it
pdf.multi_cell(0, 5, " ".join(i.decode('latin-1','replace') for i in l))

pdf.output('test_output.pdf')

Edit: FPDF uses latin-1 encoding by default so we have to decode into that.


text: Q: What is a dac file, and how do I use it? I have taken backup of mailboxes of exchange server by "Code two" software.There are files generated by it are SDF(.sdf),BAK(.bak),xml and DAC(.dac).I searched so many times ,i haven't got any information regarding DAC(.dac) files.Does anybody has any idea about it?


text:
Q: Using groupby to count a percent for each user I have a dataframe that looks like this:
    completed       User
0      false       sftcb
1       true      jsftcb
2       true      aynood
3       true     poantar
4      false      aynood
5       true       brrow
6       true       brrow
7       true       paose
8       true       pimes
9      false       brrow

What I want to get the percentages of "true" for each user. I tried using:
df1 = df.groupby('user')

But this did not perform the operation. Any help is appreciated

A: Adding to Josmoor98's answer, you should do a mapping first, because of the values being interpreted as strings. If you wish to display the values as % with a fixed amount of decimal places, then you use pandas option.display.float_format:
pd.options.display.float_format = '{:.2f}%'.format
df['completed'] = df['completed'].map({'true':True,'false':False})
print(df.groupby('User')['completed'].mean()*100)

Output:
User
aynood    50.00%
brrow     67.67%
jsftcb    100.00%
paose     100.00%
pimes     100.00%
poantar   100.00%
sftcb     0.00%
Name: complete, dtype: float64

A: Presumably you received a KeyError here. You can try the following.
df.groupby('User').mean() * 100


text:
Q: Why is the . (dot) directory from "ansible-galaxy" command removed when using - Jenkins docker image I'm trying to create a custom docker image using a Dockerfile. In my Dockerfile I have installed ansible and I can confirm this works from earlier experience, but when I am using the command ansible-galaxy to install a specific role or collection (collection in this case) it is NOT stored in the installed path.
OUTPUT FROM DOCKER BUILD:
(Previous steps works)
     ...
Step 11/11 : RUN ansible-galaxy collection install community.vmware
 ---> Running in e222fee67b89
Process install dependency map
Installing 'community.vmware:1.1.0' to '/home/me/.ansible/collections/ansible_collections/community/vmware'

When I try to run a container from this image the path /home/me/.ansible/collections/ansible_collections/community/vmware does not exists, so after running the container I have to use the docker exec and manually run the command ansible-galaxy collection install community.vmware.

Any help would be greatly appreciated.
Thanks.

A: Instead of running the ansible-galaxy command when building the image itself, I pull the ansible collection to my computer from GitHub and copy the collection to /usr/share/jenkins/ref/. Following the Jenkins docker documentation.
COPY .ansible/collection  /usr/share/jenkins/ref/

The jenkins docker image is built with a script which copies the files from the  /usr/share/jenkins/ref/ directory to the jenkins home directory.


text:
Q: Powershell Start-ThreadJob cannot validate on 'Name' coming from array Currently I'm facing an issue where Start-ThreadJob in Powershell returns an error: Cannot validate parameter on argument Name. The argument is null or empty. And I'm not able correct this problem. I want to import a csv, parse that to an array list, and use the Start-ThreadJob, as provided here Invoke-Webrequest Example #8, to download files simultaneously.
I'm importing a 2-column populated csv file, and parse this to an array list. CSV example:
FileName,URL
Abalone,https://archive.ics.uci.edu/ml/machine-learning-databases/abalone/abalone.data
Adult,https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data
Annealing,https://archive.ics.uci.edu/ml/machine-learning-databases/annealing/anneal.data

Some code:
$csv = '.\dataset.csv'
$files = @()
Import-Csv $csv | ForEach-Object{$files += @(@{OutFile = $_.FileName},@{Uri = $_.URL})}
$files

$jobs = @()

foreach ($file in $files) {
    $jobs += Start-ThreadJob -Name $file.OutFile -ScriptBlock {
        $params = $using:file
        Invoke-WebRequest @params
    }
}

Write-Host "Downloads started..."
Wait-Job -Job $jobs

foreach ($job in $jobs) {
    Receive-Job -Job $job
}

However, mine keeps giving the error stated above, and not downloading anything. While if I'm using the example code provided in the link above, it works (of course).
What is wrong in my code or parsing to the array list, such that Start-ThreadJob keeps returning an error message?
ANSWER
Thanks to @Mathias the problem was in the code when parsing to an array.
It should be: Import-Csv $csv | ForEach-Object{$files += @(@{OutFile = $_.FileName;Uri = $_.URL})}


text:
Q: How to do the diagonal decomposition of this matrix? Given a matrix G as a N*N symmetric matrix, in which

$$G_{ij} = \begin{cases}
           \sum_{j=1}^{N} \frac{1}{R_{ij}},  &\quad \mbox{if j = i} \\
           -\frac{1}{R_{ij}},                &\quad \mbox{otherwise}\end{cases}$$

$R_{ii}$ and $R_{ij}$ are greater than $0$ and $R_{ii}>R_{ij}$. Matrix $G$ is a symmetric diagonal dominant matrix.
how to do the eigen-decompostion? to transfer this matrix to $G = W D W^{-1} $format, where D is a diagonal N*N matrix.
Since matrix G is a symmetric matrix, thus $W^{-1} = W^{T}$, where$ W^{T} $ means the transpose of $W$.
I tried that let $W = 1_{N \times N}$, $W$ is $N$*$N$ matrix with all the elements being $1$, but it seems not correct.
So, how to write a general term of $W$ toward this $N$*$N$ matrix? Thank you.


text:
Q: I2C slave device address bouncing around I am interfacing an SHT20 with a Raspberry Pi via I2C.
In Linux, I am using i2cdetect from the i2c-tools package.
The issue is that I'm expecting to see a static address in this table, but instead I am seeing multiple addresses. More specifically, every time I run the command, I get a different output. Sometimes I get no addresses, sometimes I get a random address. Below is my command output. All three commands were run within a couple of seconds.
root@test-pi:~# i2cdetect -y 1
     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
00:          -- -- -- -- -- -- -- -- -- -- -- -- --
10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
20: -- -- -- -- -- -- 26 -- -- -- -- -- -- -- -- --
30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
70: -- -- -- -- -- -- -- --
root@test-pi:~# i2cdetect -y 1
     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
00:          -- -- -- -- -- -- -- -- -- -- -- -- --
10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
70: -- -- -- -- -- -- -- --
root@test-pi:~# i2cdetect -y 1
     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
00:          -- -- -- -- -- -- -- -- -- -- -- -- --
10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
70: -- -- -- -- 74 -- -- --

On the electronics side, I'm using 10k pullups, 100nF across VDD and VSS, and feeding 3V3. Note that below, I'm mounting the sensor upside down, the way it's shown in the datasheet at the top of section 3, hence the image showing pins 1+6 as not connected. They are going to the correct location.

In the attached oscilloscope screenshot, CH1 is my SCL and CH2 is my SDA.

Firstly, not sure why SCL comes to two different levels on the low end, I was expecting a more consistent waveform on SCL. Secondly, my SDA doesn't look like data - it more or less just follows SCL.
Do those waveforms look kosher? Is there a signal that I need to be sending from the master before looking for the address (Section 5.2 of the datasheet mentions a start/stop sequence, but I think the kernel driver handles that automatically)? Are there any other measurements that would help me figure out what is going on?

A: The pins are connected wrong in the schematic.
According to the datasheet, the pins for SDA and SCL are 1 & 6.
In the schematic you connect them to 3 & 4.
The same applies to supply pins 2 & 5. Datasheet says 2 is ground and 5 is VDD.


text:
Q: std::set_intersection, Intersection list with offset I need get the intersection list between two vectors. And in my case vectors are vector of user type. So to get the number encapsulated I must use a comparer function.
Also I want to able get the intersection with a offSet. For example given two vectors  {1,2,3,4,6,8} and {5,  7,  9,10} . Intersection with offSet 2 is { 3,8 } since 3 + 2 = 5 and 8 + 2 = 10.
I suppose the code below should work but instead {3,8} I am getting {3,6,8} . I couldn't figure out how to use comparer function of std::set_intersection. What am I missing?
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>

struct A
{
    A ( int in ) { a = in; }
    int getNumber() { return a; }

    bool operator< ( A rhs )
    {
        return this->a < rhs.a;
    }
    int a;
};

int main()
{
    std::vector<A> v1{1,2,3,4,6,8};
    std::vector<A> v2{5,  7,  9,10};
    int offSet = 2;
    auto lessThanWithOffset = [offSet]( A lhs,  A rhs)
    {
        return lhs.getNumber() + offSet < rhs.getNumber();
    };

    std::sort(v1.begin(), v1.end());
    std::sort(v2.begin(), v2.end());

    std::vector<A> v_intersection;
    std::set_intersection(v1.begin(), v1.end(),
                          v2.begin(), v2.end(),
                          std::back_inserter(v_intersection), lessThanWithOffset);

    for(auto n : v_intersection)
        std::cout << n.getNumber() << ' ';
}

A: See this, since

The type T satisfies Compare if

*

*The type T satisfies BinaryPredicate, and

  Given

*

*comp, an object of type Compare

*equiv(a, b), an expression equivalent to !comp(a, b) && !comp(b, a)
The following expressions must be valid and have their specified effects

*

*For all a, comp(a,a)==false

*If comp(a,b)==true then comp(b,a)==false

*if comp(a,b)==true and comp(b,c)==true then comp(a,c)==true

*For all a, equiv(a,a)==true

*If equiv(a,b)==true, then equiv(b,a)==true

*If equiv(a,b)==true and equiv(b,c)==true, then equiv(a,c)==true

so equiv(A(6), A(7)) == true because !((6+2) < 7) && !((7+2) < 6)
Actually, your lessThanWithOffset isn't complied with standard because
equiv(A(6), A(8)) == true and equiv(A(8), A(10)) == true, but equiv(A(6), A(10)) == false


text:
Q: How to detect and remove dead TCP connections in twisted? I am running a Iot socket server with twisted. Laterly I find if the device is hardware reset, the TCP connection is still kept in server side. I guess the TCP connection has no time to get disconnect since the microcontroller has been reset.
Since I only allow one device one connection, if the TCP connection goes to dead, and server has not got the disconnect request, and new connection request will be rejected.
Yes, I do define a timeout timer in twisted. But we think the timeout timer is too long, about 5 min. After waiting for 5 min, the device can reconnect to the server.
Any ideas to handle such issue ? So far I add a user command via web api, to trigger disconnect command to socket server and allow new connection.
But any idea better ? Ping back ?

A: I think you need to implement heartbeat, at specific interval client have to send some data/event to the server(heartbeat).
The server can track those heartbeat events and set timeout, if there no heartbeat from client for some time, you can consider that client connection is dead now and can disconnect client using lossConnection method of transport object. you can find transport object in all protocol classes.
transport.loseConnection()

I am using this mechanism in real time game server.


text:
Q: Laravel whereIn() acting like orWhereIn() There are 3 tables:

*

*meals

*tags

*meal_tag

I want to get all meals that have all of the tags from an url query.
For example: .../api/query?tags=1,2,3
In this example I want to fetch all meals that have

tag1 AND tag2 AND tag3

,but my query returns meals that have

tag1 OR tag2 OR tag3

Here is my query:
   $query = Meal::query();
   ...

   if ($request->has('tags')) {

        $inputTags = $request->query('tags');

        $tags = explode(',', $inputTags);

        $query = $query->whereHas('tags', function($q) use ($tags) {
            $q->whereIn('tags.id', $tags);
        });
    }

A: IN() checks whether a value is within a set of values, for any value matched then return true, It doesn't verify for all values to be present,
To achieve for what you are trying you need to check each tag id individually using whereHas to make sure all of these are present
if ($request->has('tags')) {
    $inputTags = $request->query('tags');
    $tags = explode(',', $inputTags);
    foreach($tags as $tag){
        $query = $query->whereHas('tags', function($q) use ($tag) {
            $q->where('id','=', $tag);
        });
    }
}


text:
Q: Viewbag doesn't exist in current context My old view have problem with Viewbag or html.action or @model with error doesn't exist in current context but if i create new view it work correctly.
I use mvc 5 and never update from another version
this is my wb.config code
  <runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
  <dependentAssembly>
    <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
    <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="1.0.0.0-5.2.0.0" newVersion="5.2.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
  </dependentAssembly>
</assemblyBinding>


text:
Q: React: Unable to render component Hi guys I am new to React .Just want to render my component into app component but unable to do so here is my code :
conditionalView.js:
import React, { Component } from 'react'

export class conditionalView extends Component {
    render() {
        return (

Conditional View

        )
    }
}

export default conditionalView

App.js
import logo from './logo.svg';
import './App.css';
import Bike from './bike';
import Car from './car';
import FnEvent from './FnEvent';
import ClsEvent from './ClsEvent';
import ClsEventBind from './ClsEventBind';
import conditionalView from './conditionalView';
function App() {
  return (

        {/*
        <Bike name="Caliber 125"  />
        <Car name="Maruti 800"  /> */}
       {/* <FnEvent />
       <ClsEvent /> */}
        {/* <ClsEventBind /> */}
       <conditionalView />

  );
}

export default App;

index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import reactDom from 'react-dom';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);
reportWebVitals();

Basically i want to render content of conditionView.js component into App.js but it is not picking up the content.

A: In react custom components are supposted to start with capital letters. For standard HTML elements, like div, span use lower case.
Also, no need to export twice from ConditionalView.
You can export at the same time of declaration along with the default keyword.
import React, { Component } from 'react'

export default class conditionalView extends Component {
    render() {
        return (

Conditional View

        )
    }
}

A: Your component should be PascalCase: ConditionalView, not conditionalView.

A: React components should always start with a capital letter, so rename <conditionalView /> to <ConditionalView />,
and update the import statement too;
import ConditionalView from './conditionalView';

A: This might be happening because you are exporting component more than once
  export class conditionalView extends Component {

remove the  export keyword from here


text:
Q: Use USB webcam instead of built in FaceTime webcam There are some websites where you can turn on your webcam to chat with other people. On some of these sites it is possible to select which cam you want to use if you have more then just one connected. But on some other sites you can't select which cam you will use. If you visit those sites with an iMac you always get the built-in iSight cam turned on. There seems to be no way on these sites to select any other webcam that is connected via USB.
I already tried the script named "isight disabler" found here: http://techslaves.org/isight-disabler/, but this script turns off ALL cams, not just only the iSight cam.
Is there a way to selectively turn off only the built-in iSight cam, without turning off any other cams?

A: You could give CamTwist a try. It lets you take video inputs and remap them to virtual video sources that most apps can access.

I've used it to remap a Firewire video camera connected to my laptop (via a Firewire to Thunderbolt connector) as my main video chat camera when doing a google hangout. It also let me overlay graphics into the camera video before sending it out to google.


text:
Q: Error while using EVP_MD_CTX_cleanup(ctx ) in C++ using openssl 1.1.0 I am trying to run/compile old code that was made in 2018 using an old OpenSSL version.
I faced so many errors, but I solved them all. Now I'm just stucking with last error on this line:
EVP_MD_CTX_cleanup(ctx)

The error is here:
 error: 'EVP_MD_CTX_cleanup' was not declared in this scope; did you mean 'EVP_MD_CTX_create'?
   22 |         if ( EVP_MD_CTX_cleanup(ctx ) != 1 ) { }

The code for that part is below:
#ifndef SHA256_HPP
#define SHA256_HPP

#include <openssl/evp.h>
#include <array>

class sha256
{
public:
    inline sha256()
        : ctx()
    {
        if ( EVP_DigestInit_ex(ctx, EVP_sha256(), nullptr ) != 1 ) {
            throw "EVP_DigestInit_ex() failed";
        }
    }

    inline ~sha256()
    {
        if ( EVP_MD_CTX_cleanup(ctx ) != 1 ) { }
    }

    sha256( sha256 const& ) = delete;

    sha256& operator=( sha256 const& ) = delete;

    sha256( sha256&& ) = delete;

    sha256& operator=( sha256&& ) = delete;

    inline std::array<unsigned char, 32> hash( unsigned char const* const data, int const len )
    {
        if ( EVP_DigestUpdate(ctx, data, len ) != 1 ) {
            throw "EVP_DigestUpdate() failed";
        }

        std::array<unsigned char, 32> hash;
        unsigned int hash_size = sizeof( hash );

        if ( EVP_DigestFinal_ex(ctx, hash.data(), &hash_size ) != 1 ) {
            throw "EVP_DigestFinal_ex() failed";
        }

        if ( hash_size != sizeof( hash ) ) {
            throw "unexpected hash size";
        }

        return hash;
    }

private:
    EVP_MD_CTX *ctx;
};

#endif // SHA256_HPP

I tried:
if ( EVP_MD_CTX_free(ctx ) != 1 )
if ( EVP_MD_CTX_destroy (ctx ) != 1 )

But still, I have the same error.
Any ideas what I have to change to make it run on Openssl 1.1.0 on cygwin64?

A: OpenSSL 1.1.0 is not that old, just a few years. Are you sure that is the correct version you are supposed to be using?  More likely, you should be using 1.0.2 instead, as EVP_MD_CTX_cleanup() doesn't exist in 1.1.0.
One of the major changes in 1.1.0 was changing the majority of OpenSSL's structs into opaque pointers instead.  The code you showed should not work in any version, as you are passing a null EVP_MD_CTX* pointer to all of the EVP_Digest...() functions, which will not work.
The code likely looked more like this originally, before you mucked around with it:
class sha256
{
public:
    inline sha256()
    {
        EVP_MD_CTX_init(&ctx); // <-- init with this

        if ( EVP_DigestInit_ex(&ctx, ...) != 1 ) { // <-- use '&' here
            ...
        }
    }

    inline ~sha256()
    {
        if ( EVP_MD_CTX_cleanup(&ctx) != 1 ) { } // <-- use '&' here
    }

    ...

    inline std::array<unsigned char, 32> hash( unsigned char const* const data, int const len )
    {
        if ( EVP_DigestUpdate(&ctx, ...) != 1 ) { // <-- use '&' here
            ...
        }

        ...

        if ( EVP_DigestFinal_ex(&ctx, ...) != 1 ) { // <-- use '&' here
            ...
        }

        ...
    }

private:
    EVP_MD_CTX ctx; // <-- no '*' here
};

In OpenSSL 1.1.0, that would look like this instead:
class sha256
{
public:
    inline sha256()
    {
        ctx = EVP_MD_CTX_new(); // <-- init with this
        if ( !ctx ) {
            ...
        }

        if ( EVP_DigestInit_ex(ctx, ...) != 1 ) { // <-- no '&' here
            ...
        }
    }

    inline ~sha256()
    {
        EVP_MD_CTX_free(ctx); // <-- no '&' here
    }

    ...

    inline std::array<unsigned char, 32> hash( unsigned char const* const data, int const len )
    {
        if ( EVP_DigestUpdate(ctx, ...) != 1 ) { // <-- no '&' here
            ...
        }

        ...

        if ( EVP_DigestFinal_ex(ctx, ...) != 1 ) { // <-- no '&' here
            ...
        }

        ...
    }

private:
    EVP_MD_CTX *ctx; // <-- use '*' here
};


text:
Q: Java Generics type to have an specific annotation I have a class which should have a typed parameter. Is it possible for me to ensure that the type should have a particular annotation? Below is what I'm trying to achieve. But it doesn't work. Is there any other way in which we can mandate the type to have a particular annotation? Version of Java is 1.6
abstract class Test<T extends javax.xml.bind.annotation.XmlRootElement>{
    public abstract T unmarshall();
}

@XmlRootElement(name = "user", namespace = "abc.com")
class User{
    //Some fields
}

class Test extends Test<User>{
    public User unmarshall(){
        //unarshall
    }
}

A: You cannot do that in plain JAVA. But with AspectJ I think you could do that (at least some years ago I could generate compile errors and show them in Eclipse when something was wrong annotated).


text:
Q: Appending to List Eror I'm new to Python and am struggling with the syntax to join a new value to a list and then add that to a list of lists. loc_ref and from_loc are both pre-existing lists and user_says is a user input field using user_says = input("Enter Data")
print(loc_ref,"\n")  #returns [['COMPANY|ADDRESS|CITY|STATE|LOCATION']]
print(from_loc,"\n") #returns ['COMPANY A', '1515 STREET RD', 'CITYA', 'ST']
print([user_says])
loc_ref = loc_ref.append(from_loc + [user_says])
print(loc_ref)  #returns None

Why is loc_ref returning None ?

A: That is because the method append returns None. Sounds weird? That's because it works in-place and changes the list loc_ref, but will always return None.
All you have to do is simply change your line to:
loc_ref.append(from_loc + [user_says])

The original list will simply have the appended value in it, at the last position.
Read more about it here:

The append() method adds a single item to the existing list. It doesn't return a new list; rather it modifies the original list.

A: You're setting the value of loc_ref to None
loc_ref = loc_ref.append(from_loc + [user_says])
list.append does not return the list with the appended value, it returns None, as a result, loc_ref is set to None
Try just:
loc_ref.append(from_loc + [user_says]) and get rid of the loc_ref =

A: https://www.programiz.com/python-programming/methods/list/append

As mentioned, the append() method only modifies the original list. It doesn't return any value.

append() is  a method that doesn't return anything just doing  loc_ref.append(from_loc + [user_says]) will be enough


text:
Q: Magento ignoring layout rules Magento 1.9.x
I have these rules in local.xml:
<catalog_category_default>
    <reference name="root">
        <action method="setTemplate"><template>page/1column.phtml</template></action>
    </reference>
</catalog_category_default>

<catalog_category_layered>
    <reference name="root">
        <action method="setTemplate"><template>page/1column.phtml</template></action>
    </reference>
</catalog_category_layered>

In the admin panel all categories are set to Page Layout: No Layout Updates
And yet all my category pages are on 3 column layouts.
What am I missing?


text:
Q: MongoDB: If MapReduce is set to non atomic, what happens to newly written data? I'm planning on building an application as follows:

*

*Node server receives logs from mobile devices and is inserted into Mongo as they come.

*An incremental MapReduce job is ran to calculate new fields from the data.

*The data is then pre-aggregated by minutes, hours, days, etc.

*All the while, the data in mongo is queried by a front-end visualization app.

I have a couple concerns:

*

*If I set the nonAtomic flag to true, what happens if new data is being written to the db as the MapReduce job runs?

*

*Is it written to the db? If so, I'm assuming this data wouldn't be included in the current         incremental MapReduce job.

*Or, is the database locked and the write is lost?

*As the MapReduce job and then the time aggregations run, can existing data already in the database be served to my front-end?

Thanks!

A: The following describes MongoDB 2.6. nonAtomic is an option for the out portion of map/reduce. It's not related to how map/reduce is ingesting documents from the source collection, only how it is outputting documents to the target collection.
Map/reduce uses a cursor over the input documents (created from query, sort, limit), so the rules for cursors apply to input documents to map/reduce.
When nonAtomic is false, during the out stage of the map/reduce, the output database is locked, so writes to that database will have to wait, and will possibly time out as failures on the client.
If nonAtomic is true, while the out stage of a map/reduce is running, data can be read from the database and served to the front end, but since the reads can interleave with the output from the map/reduce, the data served may be in an intermediate state.


text:
Q: C# accessing element of object from List<> using for loop instead of foreach trying to brush up my foundation on C#. How do I print the value of objects from a List? I have a List and wants to print out the Name and Age to console.
I can use foreach loop to print them out easily with whole name and age but I am just curious how to do it through a for loop here is my code which I fail of coz
Thank you for your opinion and help
namespace Rextester
{
    public class Person
    {

        public string Name {get;set;}
        public int Age {get; set;}

    }
    public class Program
    {
        public static void Main(string[] args)
        {

            var People = new List<Person>
            {
                new Person{Name ="mary", Age= 60},
                new Person{Name ="john", Age = 40},
                new Person{Name ="peter", Age= 50},
                new Person{Name ="jane", Age=30}
            };

            foreach(var obj in People)
            {
                Console.WriteLine(obj.Name + obj.Age);
            }

            for(int i=0; i<People.Count; i++)
            {
                var name = People[i].Name;
                var age = People[i].Age;
                Console.WriteLine(name[i]); // result is char in each index of string m, o ,t, e  instead of name - mary, john, peter, jane
                Console.WriteLine(age[i]);// error: Cannot apply indexing with [] to an expression of type 'int'
            }
        }
    }
}

A: You almost did everything by yourself:
Console.WriteLine(People[i].Name);
Console.WriteLine(People[i].Age);


text:
Q: 'LEA reg, mem' equivalent? Is there a x86 instruction or set of instructions, equivalent of the instruction:
lea rax, [rsp + 0x20]

I have tried the following set of instructions that I thought would be the equivalent:
push rbx
lea rbx, [rsp + 0x20]
mov rax, rbx
pop rbx

However, the alternate set of instructions causes an access violation. So the question is, is there a working equivalent of the instruction lea reg, mem?


text:
Q: Setting up SFTP users that are jailed to their home directories with Chef I'm hoping someone can help me figure out how to chroot jail users to their home directories for SFTP with Chef. I've tried multiple SSH cookbooks and Googled for an answer for several days with no luck (though honestly it's possible I just don't know what to search for).
What I've done so far is setup a data bag for users that successfully creates the users, assigns them to an sftponly group, and creates their home directory in a domain.tld format.
My problem is that once I try to connect via SFTP I can successfully be placed in the user's home directory, but can simply move up to either the parent directory or the root directory of the server. I've setup SFTP before, it was full of problems but I finally got it to work. I'd like to be able to just have all of the setup handled by Chef though.
This is what I need to know:

*

*Which Chef cookbook should I use?

*What attributes / settings do I need to specifically set to Chroot jail a user in the sftponly group to their home directory while still allowing the root user SSH access?

A: The final step for SFTP chroot is after creating a sftponly group and configuring openssh is ensuring the user's $HOME is owned by root. If the user owns their home directory, the sftponly configurations will not be applied.
Next, you can sudo mkdir a directory within that user's $HOME and ensure the user owns that directory—this is where they can upload files. I typically add a public directory within the root-owned $HOME directory where other users and processes can drop files.