text:
Q: Print the text after the name in python How can I print all names inside my data?
I've tried to convert my data to JSON my seems no luck.
from shareplum import Site
from shareplum import Office365
from shareplum.site import Version
import csv
import json
import numpy as np

authcookie = Office365('https://bboxxeng.sharepoint.com/', username='', password='').GetCookies()
site = Site('https://bboxxeng.sharepoint.com/sites/TESTIAN', version=Version.v2016, authcookie=authcookie)
folder = site.Folder('Shared Documents/test')
#data = folder.get_file('Office ss E1.csv')
#folder = site.Folder('Shared Documents/test')

r = folder.files

print (r)

Output
[{'odata.type': 'SP.File', 'odata.id': "https://bboxxeng.sharepoint.com/sites/TESTIAN/_api/Web/GetFileByServerRelativePath(decodedurl='/sites/TESTIAN/Shared Documents/Test/saaaaa.png')", 'odata.editLink': "Web/GetFileByServerRelativePath(decodedurl='/sites/TESTIAN/Shared%20Documents/Test/saaaaa.png')", 'CheckInComment': '', 'CheckOutType': 2, 'ContentTag': '{B1568967-0820-48B6-80B2-041CAC21B166},1,2', 'CustomizedPageStatus': 0, 'ETag': '"{B1568967-0820-48B6-80B2-041CAC21B166},1"', 'Exists': True, 'IrmEnabled': False, 'Length': '24383', 'Level': 1, 'LinkingUri': None, 'LinkingUrl': '', 'MajorVersion': 1, 'MinorVersion': 0, 'Name': 'saaaaa.png', 'ServerRelativeUrl': '/sites/TESTIAN/Shared Documents/Test/saaaaa.png', 'TimeCreated': '2020-05-11T15:02:15Z', 'TimeLastModified': '2020-05-11T15:02:15Z', 'Title': None, 'UIVersion': 512, 'UIVersionLabel': '1.0', 'UniqueId': 'b1568967-0820-48b6-80b2-041cac21b166'}, {'odata.type': 'SP.File', 'odata.id': "https://bboxxeng.sharepoint.com/sites/TESTIAN/_api/Web/GetFileByServerRelativePath(decodedurl='/sites/TESTIAN/Shared Documents/Test/xz.png')", 'odata.editLink': "Web/GetFileByServerRelativePath(decodedurl='/sites/TESTIAN/Shared%20Documents/Test/xz.png')", 'CheckInComment': '', 'CheckOutType': 2, 'ContentTag': '{245848AF-4533-4B9A-8AB8-1439480329F2},1,2', 'CustomizedPageStatus': 0, 'ETag': '"{245848AF-4533-4B9A-8AB8-1439480329F2},1"', 'Exists': True, 'IrmEnabled': False, 'Length': '30097', 'Level': 1, 'LinkingUri': None, 'LinkingUrl': '', 'MajorVersion': 1, 'MinorVersion': 0, 'Name': 'xz.png', 'ServerRelativeUrl': '/sites/TESTIAN/Shared Documents/Test/xz.png', 'TimeCreated': '2020-05-11T15:43:58Z', 'TimeLastModified': '2020-05-11T15:43:58Z', 'Title': None, 'UIVersion': 512, 'UIVersionLabel': '1.0', 'UniqueId': '245848af-4533-4b9a-8ab8-1439480329f2'}, {'odata.type': 'SP.File', 'odata.id': "https://bboxxeng.sharepoint.com/sites/TESTIAN/_api/Web/GetFileByServerRelativePath(decodedurl='/sites/TESTIAN/Shared Documents/Test/Office 365 E1.csv')", 'odata.editLink': "Web/GetFileByServerRelativePath(decodedurl='/sites/TESTIAN/Shared%20Documents/Test/Office%20365%20E1.csv')", 'CheckInComment': '', 'CheckOutType': 0, 'ContentTag': '{9BF05040-09BB-4534-B9C6-147AA72BD42D},1,1', 'CustomizedPageStatus': 0, 'ETag': '"{9BF05040-09BB-4534-B9C6-147AA72BD42D},1"', 'Exists': True, 'IrmEnabled': False, 'Length': '20347', 'Level': 255, 'LinkingUri': 'https://bboxxeng.sharepoint.com/sites/TESTIAN/Shared%20Documents/Test/Office%20365%20E1.csv?d=w9bf0504009bb4534b9c6147aa72bd42d', 'LinkingUrl': 'https://bboxxeng.sharepoint.com/sites/TESTIAN/Shared Documents/Test/Office 365 E1.csv?d=w9bf0504009bb4534b9c6147aa72bd42d', 'MajorVersion': 2, 'MinorVersion': 0, 'Name': 'Office 365 E1.csv', 'ServerRelativeUrl': '/sites/TESTIAN/Shared Documents/Test/Office 365 E1.csv', 'TimeCreated': '2020-05-11T17:05:59Z', 'TimeLastModified': '2020-05-11T17:05:59Z', 'Title': None, 'UIVersion': 1024, 'UIVersionLabel': '2.0', 'UniqueId': '9bf05040-09bb-4534-b9c6-147aa72bd42d'}, {'odata.type': 'SP.File', 'odata.id': "https://bboxxeng.sharepoint.com/sites/TESTIAN/_api/Web/GetFileByServerRelativePath(decodedurl='/sites/TESTIAN/Shared Documents/Test/xza.png')", 'odata.editLink': "Web/GetFileByServerRelativePath(decodedurl='/sites/TESTIAN/Shared%20Documents/Test/xza.png')", 'CheckInComment': '', 'CheckOutType': 2, 'ContentTag': '{A7D9C903-F789-4153-B9F5-5AE2E23DC6B9},2,3', 'CustomizedPageStatus': 0, 'ETag':
'"{A7D9C903-F789-4153-B9F5-5AE2E23DC6B9},2"', 'Exists': True, 'IrmEnabled': False, 'Length': '44496', 'Level': 1, 'LinkingUri': None, 'LinkingUrl': '', 'MajorVersion': 2, 'MinorVersion': 0, 'Name': 'xza.png', 'ServerRelativeUrl':
'/sites/TESTIAN/Shared Documents/Test/xza.png', 'TimeCreated': '2020-05-11T16:39:08Z', 'TimeLastModified': '2020-05-11T16:45:57Z', 'Title': None, 'UIVersion': 1024, 'UIVersionLabel': '2.0', 'UniqueId': 'a7d9c903-f789-4153-b9f5-5ae2e23dc6b9'}, {'odata.type': 'SP.File', 'odata.id': "https://bboxxeng.sharepoint.com/sites/TESTIAN/_api/Web/GetFileByServerRelativePath(decodedurl='/sites/TESTIAN/Shared Documents/Test/saaaa.png')", 'odata.editLink': "Web/GetFileByServerRelativePath(decodedurl='/sites/TESTIAN/Shared%20Documents/Test/saaaa.png')", 'CheckInComment': '', 'CheckOutType': 2, 'ContentTag': '{95BE4EA4-525A-48C8-8DB7-712E494FB142},2,3', 'CustomizedPageStatus': 0, 'ETag': '"{95BE4EA4-525A-48C8-8DB7-712E494FB142},2"', 'Exists': True, 'IrmEnabled': False, 'Length': '24383', 'Level': 1, 'LinkingUri': None, 'LinkingUrl': '', 'MajorVersion': 2, 'MinorVersion': 0, 'Name': 'saaaa.png', 'ServerRelativeUrl': '/sites/TESTIAN/Shared Documents/Test/saaaa.png', 'TimeCreated': '2020-05-11T14:49:15Z', 'TimeLastModified': '2020-05-11T14:56:56Z', 'Title': None, 'UIVersion': 1024, 'UIVersionLabel': '2.0', 'UniqueId': '95be4ea4-525a-48c8-8db7-712e494fb142'}, {'odata.type': 'SP.File', 'odata.id': "https://bboxxeng.sharepoint.com/sites/TESTIAN/_api/Web/GetFileByServerRelativePath(decodedurl='/sites/TESTIAN/Shared Documents/Test/asas.csv')", 'odata.editLink': "Web/GetFileByServerRelativePath(decodedurl='/sites/TESTIAN/Shared%20Documents/Test/asas.csv')", 'CheckInComment': '', 'CheckOutType': 2, 'ContentTag': '{09CED0C9-2196-4DD2-BB2E-9CCCF1E01BC4},2,2', 'CustomizedPageStatus': 0, 'ETag': '"{09CED0C9-2196-4DD2-BB2E-9CCCF1E01BC4},2"', 'Exists': True, 'IrmEnabled': False, 'Length': '20347', 'Level': 1, 'LinkingUri': 'https://bboxxeng.sharepoint.com/sites/TESTIAN/Shared%20Documents/Test/asas.csv?d=w09ced0c921964dd2bb2e9cccf1e01bc4', 'LinkingUrl': 'https://bboxxeng.sharepoint.com/sites/TESTIAN/Shared Documents/Test/asas.csv?d=w09ced0c921964dd2bb2e9cccf1e01bc4', 'MajorVersion': 2, 'MinorVersion': 0, 'Name': 'asas.csv', 'ServerRelativeUrl': '/sites/TESTIAN/Shared
Documents/Test/asas.csv', 'TimeCreated': '2020-05-14T09:32:36Z', 'TimeLastModified': '2020-05-14T09:33:23Z', 'Title': None, 'UIVersion': 1024, 'UIVersionLabel': '2.0', 'UniqueId': '09ced0c9-2196-4dd2-bb2e-9cccf1e01bc4'}, {'odata.type': 'SP.File', 'odata.id': "https://bboxxeng.sharepoint.com/sites/TESTIAN/_api/Web/GetFileByServerRelativePath(decodedurl='/sites/TESTIAN/Shared Documents/Test/saaaaaa.png')", 'odata.editLink': "Web/GetFileByServerRelativePath(decodedurl='/sites/TESTIAN/Shared%20Documents/Test/saaaaaa.png')", 'CheckInComment': '', 'CheckOutType': 2, 'ContentTag': '{73887AAD-B72D-4418-BB8D-A2F170C366FD},2,3', 'CustomizedPageStatus': 0, 'ETag': '"{73887AAD-B72D-4418-BB8D-A2F170C366FD},2"', 'Exists': True, 'IrmEnabled': False, 'Length': '24290', 'Level': 1, 'LinkingUri': None, 'LinkingUrl': '', 'MajorVersion': 2, 'MinorVersion': 0, 'Name': 'saaaaaa.png', 'ServerRelativeUrl': '/sites/TESTIAN/Shared Documents/Test/saaaaaa.png', 'TimeCreated': '2020-05-11T15:13:43Z', 'TimeLastModified': '2020-05-11T15:24:24Z', 'Title': None, 'UIVersion': 1024, 'UIVersionLabel': '2.0', 'UniqueId': '73887aad-b72d-4418-bb8d-a2f170c366fd'}, {'odata.type': 'SP.File', 'odata.id': "https://bboxxeng.sharepoint.com/sites/TESTIAN/_api/Web/GetFileByServerRelativePath(decodedurl='/sites/TESTIAN/Shared Documents/Test/hey.csv')", 'odata.editLink': "Web/GetFileByServerRelativePath(decodedurl='/sites/TESTIAN/Shared%20Documents/Test/hey.csv')", 'CheckInComment': '', 'CheckOutType': 2, 'ContentTag': '{562E8ED9-5E0F-42D1-A246-C2BA9C9906C0},1,1', 'CustomizedPageStatus': 0, 'ETag': '"{562E8ED9-5E0F-42D1-A246-C2BA9C9906C0},1"', 'Exists': True, 'IrmEnabled': False, 'Length': '20347', 'Level': 1, 'LinkingUri': 'https://bboxxeng.sharepoint.com/sites/TESTIAN/Shared%20Documents/Test/hey.csv?d=w562e8ed95e0f42d1a246c2ba9c9906c0', 'LinkingUrl': 'https://bboxxeng.sharepoint.com/sites/TESTIAN/Shared Documents/Test/hey.csv?d=w562e8ed95e0f42d1a246c2ba9c9906c0', 'MajorVersion': 1, 'MinorVersion': 0, 'Name': 'hey.csv', 'ServerRelativeUrl': '/sites/TESTIAN/Shared Documents/Test/hey.csv', 'TimeCreated': '2020-05-14T11:49:15Z', 'TimeLastModified': '2020-05-14T11:49:15Z', 'Title': None, 'UIVersion': 512, 'UIVersionLabel': '1.0', 'UniqueId': '562e8ed9-5e0f-42d1-a246-c2ba9c9906c0'}]

My Expected Output is to print all Names for example :
xza.png

A: Try this:
for data in r:
    print(data['Name'])

it's just like accessing data in dictionary
Result
saaaaa.png
xz.png
Office 365 E1.csv
xza.png
saaaa.png
asas.csv
saaaaaa.png
hey.csv

A: i checked with a regex validator and it's not a json, it's quite similar. If you only need the names you could try a regex:
\'Name\'\:\s\'([^\']+)\'

and you will have the names of the files on the first capturing group.


text:
Q: exim & dovecot user over quota: reject on send? i have an exim + dovecot mailserver setup with per-user quota (via mysql lookup) running. the server rejects incoming mail from non-local senders when the targeted local mailbox is over quota. the local user can send out mails without restrictions eventho his mailbox is over quota.
i'd prefer the quota to be checked when the local user tries to send an email and return an error like "your account is over quota, please remove some mails first". incoming mails from non-local senders to a local mailbox should be accepted no matter of the quota.
there is a similar configuration described on "Setting up exim":
acl_check_rcpt:
#...
  # Deny sending for local users if almost at quota
        # only run for local domains
  deny  sender_domains = +local_domains
        # list all addresses that are aliases
        # though people shouldn't be sending as
        # them, many scripts do
        !senders = ^postmaster@.*:\
                   ^root@.*:\
                   ^webmaster@.*:\
                   ^error-.*@.*:\
                   ^bounce-.*@.*
        # might need to exclude webmail server here
        # if it does not report the error message
        # note: squirrelmail tested ok for me
        hosts = +local_hosts
        # verify your email client expunges on emptying the trash
        message = You have too much email stored. Please delete some\n\
                  and empty the trash. Then you can send.
        log_message = $sender_address_local_part is over send quota
        condition = ${run{sudo -u root /etc/exim/check-sendquota.sh $sender_address_local_part}{no}{yes}}

it uses a custom script to check the mailbox size - for performance reasons i'd rather use the already existing quota files/system, but i can't figure out the correct "condition" line. i can't see from the current config where exim actually checks for the mailbox size. the current config contains among other things:
exim4.conf:
local_delivery:
    driver = appendfile
    maildir_format
    user = mailserv
    group = mailserv
    mode = 0660
    mode_fail_narrower = false
    envelope_to_add = true
    return_path_add = true
    maildir_tag = ,S=$message_size
    quota_size_regex = ,S=(\d+)
    quota =  ${lookup mysql{SELECT CONCAT(quota, "M") FROM users WHERE account='${local_part}@${domain}'}{$value}{7M}}
    directory = ${lookup mysql{SELECT maildir FROM users WHERE account='${local_part}@${domain}'}}

dovecot.conf:
protocol imap {
    mail_plugins = quota imap_quota
}
plugin {
    quota = maildir:user
    quota_rule = *:storage=5GB
}

A: You need to add a similar quota check to your acl_not_smtp acl, this acl is used for all none smtp mail submitted by local users / processes
http://www.exim.org/exim-html-current/doc/html/spec_html/ch40.html

redpajama_set_name: RedPajamaStackExchange


text:
Q: Exposing SOAP interfaces through a DMZ using Apache httpd I have the following scenario that I am looking for technical guidance.
We want to expose a number of SOAP based services through our company's DMZ using Apache httpd.
To the outside world our clients will have access to
https://www.mycompany.com/servicea, https://www.mycompany.com/serviceb, etc...
The above services will be redirected via Apache RewriteRules to their true destinations. We will open port 1234 in our firewall to allow SOAP traffic from the DMZ to the internal SOAP listeners.
https://www.mycompany.com/servicea --> http://internalip:1234/servicea

https://www.mycompany.com/serviceb --> http://internalip:1234/serviceb

Within our intranet I have simulated the above and it works as outlined.
Will the above system description accomplish what we want to do for users outside our intranet?
Is there a better way or different technologies we should be looking at?
Thanks in advance.

A: Yes. you can make these services available externally.
You need to NAT the external IP (ip address of www.mycompany.com) to IP address of Apache HTTPD server over the port 443.
Someone from Network and Security team should be able to help you doing that.
Apache HTTPD need to configure to listen 443 (look for httpd-ssl.conf).
You may need SSL installation as well.
<VirtualHost *:443>
ServerName www.mycompany.com
#Any addition code e.g. Rewriterules etc
ProxyRequests Off
ProxyPass /servicea http://internalip:1234/servicea
ProxyPass /serviceb http://internalip:1234/serviceb
<VirtualHost>

Good Luck!


text:
Q: Gradle + Android Annotations + Merged Manifest = "Could not find the AndroidManifest" I seem to be running into a problem with Android Annotations finding my Android Manifest when I'm using different manifests for different buildTypes. The error I get is:
java: error: Unexpected error. Please report an issue on AndroidAnnotations, with the following content: java.lang.IllegalStateException: Could not find the AndroidManifest.xml file, going up from path [/Users/jabdulius/Documents/Dropbox/workspace/<app-name>/aa-gen] found using dummy file [file:///Users/jabdulius/Documents/Dropbox/workspace/<app-name>/aa-gen/dummy1379349979895.java] (max atempts: 10)
at com.googlecode.androidannotations.helper.AndroidManifestFinder.findManifestInParentsDirectories(AndroidManifestFinder.java:156)
at com.googlecode.androidannotations.helper.AndroidManifestFinder.findManifestFileThrowing(AndroidManifestFinder.java:93)
at com.googlecode.androidannotations.helper.AndroidManifestFinder.extractAndroidManifestThrowing(AndroidManifestFinder.java:65)
at com.googlecode.androidannotations.helper.AndroidManifestFinder.extractAndroidManifest(AndroidManifestFinder.java:55)
at com.googlecode.androidannotations.AndroidAnnotationProcessor.extractAndroidManifest(AndroidAnnotationProcessor.java:388)
at com.googlecode.androidannotations.AndroidAnnotationProcessor.processThrowing(AndroidAnnotationProcessor.java:358)
at com.googlecode.androidannotations.AndroidAnnotationProcessor.process(AndroidAnnotationProcessor.java:341)
at com.sun.tools.javac.processing.JavacProcessingEnvironment.callProcessor(JavacProcessingEnvironment.java:627)
at com.sun.tools.javac.processing.JavacProcessingEnvironment.discoverAndRunProcs(JavacProcessingEnvironment.java:556)
at com.sun.tools.javac.processing.JavacProcessingEnvironment.doProcessing(JavacProcessingEnvironment.java:701)
at com.sun.tools.javac.main.JavaCompiler.processAnnotations(JavaCompiler.java:987)
at com.sun.tools.javac.main.JavaCompiler.compile(JavaCompiler.java:727)
at com.sun.tools.javac.main.Main.compile(Main.java:353)
at com.sun.tools.javac.api.JavacTaskImpl.call(JavacTaskImpl.java:115)
at org.jetbrains.jps.javac.JavacMain.compile(JavacMain.java:167)
at org.jetbrains.jps.incremental.java.JavaBuilder.compileJava(JavaBuilder.java:375)
at org.jetbrains.jps.incremental.java.JavaBuilder.compile(JavaBuilder.java:278)
at org.jetbrains.jps.incremental.java.JavaBuilder.doBuild(JavaBuilder.java:190)
at org.jetbrains.jps.incremental.java.JavaBuilder.build(JavaBuilder.java:162)
at org.jetbrains.jps.incremental.IncProjectBuilder.runModuleLevelBuilders(IncProjectBuilder.java:1070)
at org.jetbrains.jps.incremental.IncProjectBuilder.runBuildersForChunk(IncProjectBuilder.java:798)
at org.jetbrains.jps.incremental.IncProjectBuilder.buildTargetsChunk(IncProjectBuilder.java:829)
at org.jetbrains.jps.incremental.IncProjectBuilder.buildChunkIfAffected(IncProjectBuilder.java:761)
at org.jetbrains.jps.incremental.IncProjectBuilder.access$800(IncProjectBuilder.java:78)
at org.jetbrains.jps.incremental.IncProjectBuilder$BuildParallelizer$2.run(IncProjectBuilder.java:730)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:439)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at com.intellij.util.concurrency.BoundedTaskExecutor$1.run(BoundedTaskExecutor.java:35)
at org.jetbrains.jps.service.impl.SharedThreadPoolImpl$1.run(SharedThreadPoolImpl.java:41)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:439)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
at java.lang.Thread.run(Thread.java:680)

In Project Settings->Compiles->Annotation Processors, I tried setting a flag ("AndroidManifestFile") to the location of my manifest ("/src/main/AndroidManifest.xml"), but it didn't make a difference.
Here's what my director structure looks like:

And my Annotation Processor settings:

Any ideas?


text:
Q: Download file from Javascript in IE 8 Currently, my code looks like this:
$http.post("/Controller/Method", {
                variable: parameter,
                variable2: jsonObject,
                variable3: parameter3,
                variable4: parameter4
}).then(function (response) {
    var dlAnchorElem = document.getElementById('downloadAnchorElem2');
    var header = response.headers('Content-Disposition');
    var filename = header.split("filename=");
    if (filename[1].charAt(0) === '"' && filename[1].charAt(filename[1].length - 1) === '"') {
        filename[1] = filename[1].substr(1, filename[1].length - 2);
    }
    dlAnchorElem.setAttribute("href", response.data);
    dlAnchorElem.setAttribute("download", filename[1]);
    dlAnchorElem.click();
});

This works great, in Chrome.  Doesn't work in Firefox, Edge, or IE8.  Currently, I'm trying to solve for IE8, cause if that solution is compatible, I can just use that, if not, I can try Filesaver or one of the other cross-browser solutions I've seen that explicitly don't work for IE 8.


text:
Q: Why does re-declaring an argument inside of a try/catch throw a ReferenceError? I mistakenly wrote a re-declaration of an argument as a const in a function and instead of throwing SyntaxError: Identifier 'bar' has already been declared I ended up with ReferenceError: bar is not defined..
What causes this behaviour? It wasn't the expected error, and left me confused for a few minutes.
Example code:
function foo(bar) {
  try {
      console.log(bar);
      const bar = 123;
  } catch(err) { console.log(err) }
}
foo(456);

If I don't wrap the declaration in a try/catch, I get (what I believe to be) the expected error.

A: It's a myth that const and let aren't hoisted at all. They're half-hoisted. :-) That is: Within a block, if const bar or let bar (or class bar { } for that matter) appears anywhere in that block, then bar cannot be used prior to that declaration in the block — even if it exists in a containing scope. This area between the beginning of the block and the declaration is called the Temporal Dead Zone:
function foo(bar) {
  // `bar` is fine here
  try {
      // Temporal Dead Zone, `bar` cannot be used here
      console.log(bar);
      // End of TDZ
      const bar = 123;
      // `bar` would be fine here
  } catch(err) { console.log(err) }
}
foo(456);

A: Because const declarations are block scoped, the const bar declaration gets hoisted to the start of the block. (Just after try {)
That means that bar isn't actually defined when you try to log it, because the hoisting overrides / hides the parameter bar.

A: Taken from here https://tylermcginnis.com/videos/var-let-const/

var is function scoped and if you try to use a variable declared with
  var before the actual declaration, you'll just get undefined. const
  and let are blocked scoped and if you try to use a const or let
  variable before the declaration you'll get a reference error.

A:
Constants are block-scoped, much like variables defined using the let statement.

From this MDN article.
Since you wrapped bar inside a block of braces, its definition is relative to that block. And because you have another bar declaration inside of that block, despite being after the call to it, the compiler will attempt to use this newly defined bar instead of the passed-in parameter. Rename them as separate parameters to mitigate confusion, since one can assume they are holding different data because of your declaration.


text:
Q: Python список кортежей, получить второй элемент каждого кортежа Есть список кортежей:

[('Магазин', 'railway_fork'), ('Игры', 'games'), ('Информация о боте', 'menu_item'),
 ('Пополнить счет', 'info')]

Нужно получить только вторые элементы кортежей:

[('railway_fork'), ('games'), ('railway_fork'), ('info')]

Как это можно сделать?

A: Такой вариант по скорости должен быть быстрее всех:
a = [('Магазин', 'railway_fork'),
     ('Игры', 'games'),
     ('Информация о боте', 'menu_item'),
     ('Пополнить счет', 'info')]
print([x[1] for x in a])

если надо список через запятую то так:
print(*[x[1] for x in a], sep=",")

Бинго!
Однако похоже лучше воспользоваться словарем в вашем случае. И вероятно - с самого начала )) по смыслу данных. Но вам виднее.
Вот такой вариант с преобразованием в словарь:
d=dict(a)
print(*list(d.values()))

A: Через comprehension и без лишних преобразований в словарь:
lst = [('Магазин', 'railway_fork'), ('Игры', 'games'), ('Информация о боте', 'menu_item'), ('Пополнить счет', 'info')]
print([y for x, y, *z in lst])

На выходе:
['railway_fork', 'games', 'menu_item', 'info']

A: Через множественный for:
second_elems = []

# Может быть больше 2 элементов
for k, v in tuple_list:
    # k - 0-й элемент
    second_elems.append((v,))

Нужно получить только вторые элементы кортежей: [('railway_fork'), ('games'), ('railway_fork'), ('info')]

Я так понял, что вам нужен именно список кортежей, поэтому в second_elems.append((v)) я добавляю кортеж с единственным элементом.

A: Можно через zip
lst = [('Магазин', 'railway_fork'), ('Игры', 'games'),
       ('Информация о боте', 'menu_item'), ('Пополнить счет', 'info')]

print([(item,) for item in list(zip(*lst))[1]])
# [('railway_fork',), ('games',), ('menu_item',), ('info',)]

print(*[item for item in list(zip(*lst))[1]])
# railway_fork games menu_item info

print([item for item in list(zip(*lst))[1]])
# ['railway_fork', 'games', 'menu_item', 'info']

Или так:
print([lst[i][1] for i in range(len(lst))])
# ['railway_fork', 'games', 'menu_item', 'info']

A: a = [('Магазин', 'railway_fork'), ('Игры', 'games'),
     ('Информация о боте', 'menu_item'),
     ('Пополнить счет', 'info')]

print(a[0][1], ",", a[1][1],",", a[2][1],",", a[3][1])


text:
Q: Rename Multiple file on using .cmd or .bat I have directory which contain no. of file like this
abac_273#jj.txt ,
hhh.78448#kkpp.txt ,
dgfhf@ytyt#llltyui.txt

I need to write batch script where I need to rename those file like this
jj.txt ,   kkpp.txt,   llltyui.txt

In simple words, I need to find out # from end and return string after # as output.
Can you please help me out to solve this

A: for /f "tokens=1*delims=#" %%a in ('dir /b /a-d "*#*"') do echo(ren "%%a#%%b" "%%b"

should provide what you want - reduce each %% to % if you execute this from the prompt instead of as a batch line.
If it works correctly for you, change the echo(ren to ren to actually do the change - this code will simply report the proposed change to the screen.


text:
Q: Appcelerator - Images missing from Android App Store package
*

*When I preview ('Run') my app to a connected Android Device all the
images work as expected.

*If I dig out the APK from the build > android > bin folder and install it on a device, all images work as expected.

However:

*

*If I 'Package' for the 'Android App Store' then install the resulting APK on a phone - some of the images are missing.

Is this simply because I am not installing the APK via the app store or is something else going on please!?

A: I am making all the Noob errors at the moment. This time the issue was to do with image paths.
An image path of
"images/brake-fluid.jpg"
will work on iOS and within the dev environment on Android... but really should be
"/images/brake-fluid.jpg"
to work on the exported Android builds too (note initial forward slash).


text:
Q: Error "Unable to find the requested .Net Framework Data Provider. It may not be installed" I am using Visual Studio 2008 and oracle database 10g.
I trying to connect to the backend like this:
Subwindow "Server explorer". Push button "Connect to database" and make next chain
Data Connection->Choose Data Source->Oracle Database->oracle Data provider for .Net->Continue->Data Source name : oraclexe->Userneme: hr password: hr -> Test connection (answer "Test connected succeeded ")->push button OK and:
"Unable to find the requested .Net Framework Data Provider. It May not be installed"

I have made changes to machine.config
<add name="Oracle Data Provider for .NET"
invariant="Oracle.DataAccess.Client" description="Oracle Data Provider for .NET"
type="Oracle.DataAccess.Client.OracleClientFactory,
Oracle.DataAccess, Version=2.111.6.20, Culture=neutral, PublicKeyToken=89b483f429c47342" />

But then to same error persists. What to do?

A: Oracle data providers are specific for an architecture. If you download a 64-bit driver you need to build your application as 64bit (or AnyCPU if the target OS is 64bit).
The problem is that Visual Studio is 32-bit, so you also need a 32bit driver installed.

A: A couple of suggestions:

*

*Don't use the EF beta. If you do, use the 32-bit version. The driver does not work as advertised as of October 2010, the install was misconfigured for 64 bit applications and odac dll's were placed in the wrong system folder, aside from other issues.

*Stick with ado.net and do some simple queries before tackling the project, if you are using someone else's project or downloaded it from somewhere.

*Visual studio project files keep suggested locations for assemblies in the project file, look for those and remove the "hint" path if this is someone else's project.

*Download and install the client files:
http://www.oracle.com/technology/software/tech/windows/odpnet/index.html since you did not specify that you have the client files installed.

In summary, you are probably using one version of the driver for the design tool and another for the underlying connections. I know this sounds weird but I've run into it several times already. The only way forward is to take it apart. If you start with an ADO.NET base connection test you'll find the problem.
Below is a simple connection to get started.
Thanks,
Aldo
using System;
using System.Data.Common;
using Oracle.DataAccess.Client;

namespace EntityFrameworkForOracle
{
    internal class Test1Connection
    {
        internal void InternalTestRead()
        {
            using (var con = Database.GetLocalConnection())
            {
                con.Open();
                var cmd = Database.GetCommand(con);

                const string sql = @"select *
                            from TESTTABLE";

                cmd.CommandText = sql;
                var reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    Console.WriteLine("\t{0}\t{1}", reader[0], reader[1]);
                }

                reader.Close();

                con.Close();
                con.Dispose();

                cmd.Dispose();
            }
        }

    }

    public static class Database
    {
        private const string ProviderName = "Oracle.DataAccess.Client";
        private const string LocalConnectionString = "User Id=system;Password=XXX;Data Source=localhost:XXXX/XXXX;enlist=true;pooling=true";

        private static readonly DbProviderFactory Factory = DbProviderFactories.GetFactory(ProviderName);

        public static DbCommand GetCommand(DbConnection con)
        {
            var cmd = Factory.CreateCommand();
            if (cmd != null)
            {
                cmd.Connection = con;

                return cmd;
            }
            return null;
        }

        public static DbCommand GetCommand(string cmdText, DbConnection con)
        {
            var cmd = GetCommand(con);
            cmd.CommandText = cmdText;

            return cmd;
        }

        public static DbConnection GetLocalConnection()
        {
            var con = Factory.CreateConnection();
            if (con != null)
            {
                con.ConnectionString = LocalConnectionString;

                return con;
            }
            return null;
        }

        public static void CloseConnection(OracleConnection connection)
        {
            connection.Close();
            connection.Dispose();
        }
    }

}


text: Q: Воспроизведение аудио (mp3) как потока Существует ли возможность трансляции аудио в браузер без загрузки самого файла на Web Audio API (без icecast итп). Например загрузка потока в буфер и воспроизведение. Требуется чтоб файл нельзя было скачать (скрыть путь). В конечном итоге должен получится простой плеер для продажи аудио. Может какая простенькая лайбрари JS,PHP?


text:
Q: LSTM Sequence Prediction in Keras just outputs last step in the input I am currently working with Keras using Tensorflow as the backend. I have a LSTM Sequence Prediction model shown below that I am using to predict one step ahead in a data series (input 30 steps [each with 4 features], output predicted step 31).
model = Sequential()

model.add(LSTM(
    input_dim=4,
    output_dim=75,
    return_sequences=True))
model.add(Dropout(0.2))

model.add(LSTM(
    150,
    return_sequences=False))
model.add(Dropout(0.2))

model.add(Dense(
    output_dim=4))
model.add(Activation("linear"))

model.compile(loss="mse", optimizer="rmsprop")
return model

The issue I'm having is that after training the model and testing it - even with the same data it trained on - what it outputs is essentially the 30th step in the input. My first thought is the patterns of my data must be too complex to accurately predict, at least with this relatively simple model, so the best answer it can return is essentially the last element of the input. To limit the possibility of over-fitting I've tried turning training epochs down to 1 but the same behavior appears. I've never observed this behavior before though and I have worked with this type of data before with successful results (for context, I'm using vibration data taken from 4 points on a complex physical system that has active stabilizers; the prediction is used in a pid loop for stabilization hence why, at least for now, I'm using a simpler model to keep things fast).
Does that sound like the most likely cause, or does anyone have another idea? Has anyone seen this behavior before? In case it helps with visualization here is what the prediction looks like for one vibration point compared to the desired output (note, these screenshots are zoomed in smaller selections of a very large dataset - as @MarcinMożejko noticed I did not zoom quite the same both times so any offset between the images is due to that, the intent is to show the horizontal offset between the prediction and true data within each image):

...and compared to the 30th step of the input:

Note: Each data point seen by the Keras model is an average over many actual measurements with the window of the average processed along in time. This is done because the vibration data is extremely chaotic at the smallest resolution I can measure so instead I use this moving average technique to predict the larger movements (which are the more important ones to counteract anyway). That is why the offset in the first image appears as many points off instead of just one, it is 'one average' or 100 individual points of offset.
    .
-----Edit 1, code used to get from the input datasets 'X_test, y_test' to the plots shown above-----
model_1 = lstm.build_model()  # The function above, pulled from another file 'lstm'

model_1.fit(
    X_test,
    Y_test,
    nb_epoch=1)

prediction = model_1.predict(X_test)

temp_predicted_sensor_b = (prediction[:, 0] + 1) * X_b_orig[:, 0]

sensor_b_y = (Y_test[:, 0] + 1) * X_b_orig[:, 0]

plot_results(temp_predicted_sensor_b, sensor_b_y)
plot_results(temp_predicted_sensor_b, X_b_orig[:, 29])

For context:
X_test.shape = (41541, 30, 4)
Y_test.shape = (41541, 4)
X_b_orig is the raw (averaged as described above) data from the b sensor. This is multiplied by the prediction and input data when plotting to undo normalization I do to improve the prediction. It has shape (41541, 30).
----Edit 2----
Here is a link to a complete project setup to demonstrate this behavior:
https://github.com/ebirck/lstm_sequence_prediction

A: That is because for your data(stock data?), the best prediction for 31st value is the 30th value itself.The model is correct and fits the data.
I also have similar experience predicting the stock data.

A: I feel I should post a follow-up, since it seems this post has been getting more attention than my other questions.
Ferret Zhang's answer is correct (and has been accepted), and I find this discovery is actually quite funny when you understand it in relation to stock / cryptocurrency data which some have commented about. What sequence prediction is ultimately doing is assigning statistical weights to different moves, to pick the highest probability move and 'predict' it will happen. In the case of stock data, in a vacuum it is (at least at this scale) completely random, there is equal probability of moving up or down, and hence the model predicts that it will stay the exact same.
The model, in a sense, learned that the best way to play is to not play at all :)


text:
Q: Paste specific text and the start and end of every row I would like to paste in every row at the start and end a specific text
I tried this
 d <- c("Mon","Tues","Wednes","Thurs","Fri","Satur","Sun")
 week <- paste("DAY", d, "day", sep="")

But it makes only the first part
How is it possible to make?

A: Maybe you want this
week <- paste("DAY", paste0(d, "day"), sep="")

such that
> week
[1] "DAYMonday"    "DAYTuesday"   "DAYWednesday" "DAYThursday"
[5] "DAYFriday"    "DAYSaturday"  "DAYSunday"

A: Or we can use sprintf
sprintf("DAY%sday", d)
#[1] "DAYMonday"    "DAYTuesday"   "DAYWednesday" "DAYThursday"  "DAYFriday"    "DAYSaturday"  "DAYSunday"

Or with glue
glue::glue("DAY{d}day")


text:
Q: Consuming RESTful API with Angular Stack I have an Angular 12 web application where I need to display data from a RESTful API protected by OAUTH 2.0 using a Client ID and an API key.  What is the secure and standard way to implement this?  Any advice, examples, or tutorials would be helpful.

A: There is a Bearer type specified in the Authorization header for use with OAuth bearer tokens (meaning the client app simply has to present ("bear") the token). The value of the header is the access token the client received from the Authorization Server.
Create a HTTP helper and add this code there,
    constructor(
    private http: HttpClient
  ) {}

.
postWithToken(url: string, params: object): Observable<any> {
  let headers = new HttpHeaders({
    "Content-Type": "application/json",
    "Access-Control-Allow-Methods": "*",
    "Access-Control-Allow-Origin": "*",
    Authorization: "Bearer AYjcyMzY3ZDhiNmJkNTY",
  });
  return this.http
    .post<any>("http://localhost/"+ url, params, {
      headers: headers,
    })
    .pipe(
      tap(
        (data) => {
          return data;
        },
        (error) => {
          if (error.status == 500) {
            console.log("No valid Session Exists");
            return;
          } else {
            console.log("Internal server error!", 3000);
            return;
          }
        }
      )
    );}

Where
AYjcyMzY3ZDhiNmJkNTY

is your OAuth access token. This token can read from browser cookie or session.
You can call this from your service.js file
 httpService
  .postWithToken("YOUR API END-POINT", requestBody)
  .subscribe((data) => {
    if (
      data.httpStatusCode == 200 &&
      data.data != null &&
      data.data != undefined
        ) {
//your code here to display the data from BE server
}


text:
Q: How to replace an element of an array in a specific way I'm solving a problem with this concept:
It is a classroom, and I have to replace an available seat with a name, but in a specific way: it is replaced in the last row, from right to left. If the classroom is full it will show a message that there are no places available.
I have no idea how to replace an available seat in the order that the problem says.
import numpy as np

classroom1 = np.array([["Martha", "Available"],
                       ["Max", "Anahi"],
                       ["Available", "Available"],
                       ["Alexis", "Rigel"]])

So far I can replace a seat of my choice manually, but not in the way the problem states.
for example:
classroom1[0,1] = "Alex"
print(classroom1)

[["Martha", "Alex"],
 ["Max", "Anahi"],
 ["Available", "Available"],
 ["Alexis", "Rigel"]]

But I still can't get an idea of how to solve it according to the problem. I don't know how to solve it.

A: We can use reverse indexing or negative indexing to solve this problem. With positive/normal indexing you traverse through an array start through end. But with reverse indexing you use "-" sign with indexes and it traverses in the reverse direction.
consider this example:
x = np.array(['a','b','c','d','e','f','g'])
print(x[2])
print(x[-5])

so both these instructions will pring out 'c'
one thing to remember is that in reverse indexing we start from -1 so if you want to print 'g' you would have to pass x[-1]
Now to your original problem:
you have a 2 dimensional array that means you will have to pass two negative indexes to do the required modification

classroom[index of subarray][index of element within subarray]

consider another example:
classroom1[0,1] = "Alex"
print(classroom1)
[["Martha", "Alex"],
 ["Max", "Anahi"],
 ["Available", "Available"],
 ["Alexis", "Rigel"]]

say we want to update the seat at index 0 in array at index 2, so we will have to do reverse indexing as follows:
classroom[-2][-2] = "Peter"
[["Martha", "Alex"],
 ["Max", "Anahi"],
 ["Peter", "Available"],
 ["Alexis", "Rigel"]]

A: Code:-
import numpy as np

classroom1 = np.array([["Martha", "Available"],
                       ["Max", "Anahi"],
                       ["Available", "Available"],
                       ["Alexis", "Rigel"]])
list_of_names=['Yash','Sam','Itachi','Ace']

seats_available=0
for i in range(len(classroom1)):
    for j in range(len(classroom1[0])):
        if classroom1[i][j]=="Available":
            seats_available+=1
#Enter the students in order right to left and starting from the last
count=0
for i in range(len(classroom1)-1,-1,-1):
    for j in range(len(classroom1[0])-1,-1,-1):
        if classroom1[i][j]=="Available":
            if seats_available and count<len(list_of_names):
                classroom1[i][j]=list_of_names[count]
                count+=1
                seats_available-=1
print(classroom1)  #as you can see Ace is not present cause there is no available seats for them when he appeared.

Output:-
[['Martha' 'Itachi']
 ['Max' 'Anahi']
 ['Sam' 'Yash']
 ['Alexis' 'Rigel']]

A: Here is a solution which can scale to huge data by using vectorized functions of numpy.
classroom1= np.array([["Martha", "Available"],
                   ["Max", "Anahi"],
                   ["Available", "Available"],
             ["Alexis", "Rigel"]])
list_of_names = ['Yash','Sam','Itachi','Ace']
# Get the indices of "Available" seats.
free_seat_idx = np.transpose(np.nonzero(data=="Available"))
# Reverse the "Available" seat indices as they will be replaced from last row.
reversed_fs_idx = np.flip(free_seat_idx, axis=0)

# Fetch the names from list and put them in respective flattened index.
K = classroom1.shape[1]
idx = 0 # index of name list
for val in reversed_fs_idx:
    flat_idx = val[0]*K + val[1]
    np.put(classroom1, flat_idx, list_of_names[idx])
    idx += 1
print(classroom1)

Output
[['Martha' 'Itachi']
 ['Max' 'Anahi']
 ['Sam' 'Yash']
 ['Alexis' 'Rigel']]


text:
Q: Highcharts: dynamically change the tooltip formatter? I want to format a reusable Highcharts tooltip dependent on a global value. (I'm using the same chart to switch between currency and numeric values: if I'm showing currency data on the chart, I want to format the tooltip as currency.)
However, this in the Highcharts tooltip function seems to refer to the local data point only, and I don't seem to be able to pass a value in.
How do I either pass a value in, or get a global value? This is my code right now, which fails horribly:
getChartTooltip: function() {
    return function(graphType) {
        var prefix = (graphType === 'currency') ? '$' : ''; // Fails
        return prefix + Highcharts.numberFormat(this.y, 0);
    };
},

initializeChart: function() {
  var graphType = 'currency';
  var chartOptions = {};
  chartOptions.tooltip = {
      formatter: getChartTooltip(graphType)
  };
  // create chart, etc...
  $('change-chart-type').on('click', function() {
     // Try to update the tooltip formatter, fail horribly...
     graphType = 'number';
     chart.series[0].update({
         tooltip: {
             formatter: _this.getChartTooltip(graphType)
         }
     });
 });

What's a better way to do this?

A: You don't need to change the tooltip.formatter, because it's the formatter itself who will change the tooltip.
I would try something like :
tooltip: {
     formatter: function() {
          var unit = ' $',
              result = this.value;
          if(this.series.name == 'your_currency_serie_name'){
               result += unit;
          }
          return result;
     }
}

Where 'your_currency_serie_name' is the name of the serie which refers to currency values.

A: You can set the tooltip options in each series as well via the valueDecimals, valuePrefix, and valueSuffix options. The tooltip will then use these options for displaying the data. Live demo.
Generic setup:
...
        series: [{
            tooltip: {
                valueDecimals: 0,
                valuePrefix: '',
                valueSuffix: ''
            },
            data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
        }, {
            tooltip: {
                valueDecimals: 2,
                valuePrefix: '$',
                valueSuffix: ' USD'
            },
            data: [129.9, 171.5, 1106.4, 1129.2, 1144.0, 1176.0, 1135.6, 1148.5, 1216.4, 1194.1, 195.6, 154.4]
        }]
...


text:
Q: GraphQL for open banking APIs Can we use GraphQL for open banking APIs? As different customers have different requirements, does it makes sense to build open banking APIs using GraphQL instead of standard microservices?

A: GraphQL is not so common in the open banking world. I think this is mainly due to the fact that GraphQL very much assumes random data access, while very often this is not possible with banking backend systems, which are being accessed through open banking APIs. Here is one example of GraphQL banking API: https://kontist.dev/docs/


text:
Q: How to pull data from form's field to curl_setopt it's my very first time posting question here and looking forward for further interaction with the community here.
I have a php FUNCTION [A] that showing a form's field to get user input for API Key:
/**
* Generates a settings input for API Key
* @param void
* @return HTML
**/
function ss88_settings_field_api_key_callback($args) {
    $p_id_option = get_option('ss88_api_key', ss88_api_key_default_value());
    ?>
    <input
        type="text"
        name="ss88_api_key"
        value="<?php echo escape_value($p_id_option); ?>"
        pattern="[0-9a-zA-Z]+"
        title="ss88 API Key should only contain numbers and letters." />
    <?php
}

And I have a php [FUNCTION B] that should be authenticate API key and process URL:
// Function to send the request
function pus_shortcode_shorten_url($atts, $content){

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://ss88.my/api/url/add");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['url' => $content]));
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "Authorization: Bearer **XXXXXXXXXX**",
        "Content-Type: application/json"
    ]);

    $response = curl_exec($ch);
    curl_close($ch);

    if($object = json_decode($response)){
        if(isset($object->shorturl)){
            return $object->shorturl;
        }
    }

    return $content;
}

Question:
How do I pass the data input by user from FUNCTION [A] to FUNCTION [B] -> to replace "XXXXXXX"
Any help and advice shall be greatly appreciated


text:
Q: UIControlEventTouchUpInside not firing after UIPanGesture For customization reasons I'm building my own slider control, which is build using several UIImageViews and a UIButton if needed. I've got the panning working using a UIPanGestureRecognizer, which is working fine. I'm trying to hook an event in that will handle the code for UIControlEventTouchUpInside, but I can't get it to fire after the Pan event fires. I've got this working with both a UITapGestureRecognizer and using the built in event for the UIButton, but it only fires if it's the only gesture. I need to know when the user is no longer dragging the slider left and right, but it can only happen after the user lifts his/her/its finger from the screen (I can't use timers to see when the movement stopped because the user may still be deciding which direction to go after starting the Pan).
The short version: How do I know when a user stops panning a control and lifts his finger off the screen?

A: Let's say you initialize your recognizer like this:
UIPanGestureRecognizer *grPan=[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panning:)];

you can do this:
-(void)panning:(UIPanGestureRecognizer *)senderGestureRecognizer {
    if(senderGestureRecognizer.state==UIGestureRecognizerStateEnded)
    {
        //User stopped panning (lifted finger)
    }
}


text:
Q: Why runnung mvn clean install command (on a Spring Boot project) I obtain unit test failure also if I commented out these methods to skip tests? I am not working with Spring\Spring Boot from several years and I am starting a project with this technology so I have some doubts.
I am working on a simple project retrieved from GIT and starting working on it implementing my functionality. It works fine but I have the following doubts.
From command line (into the root directory of my project) I compile it using the command:
mvn clean install

in order to delete the previous version of my application and then compile, test & package again my application.
Then I start my application by this command:
mvn spring-boot:run

And the application correctly starts:
It starts without problem. My doubt is in the previous phase when I perform the mvn clean install command. It performs also the unit tests defined inside the project but all test failed. And here the strange behavior.
I obtain exception like this:
Running com.springboot.excelapi.integration.ExcelResourceUnitTest
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.001 sec <<< FAILURE! - in com.springboot.excelapi.integration.ExcelResourceUnitTest
initializationError(com.springboot.excelapi.integration.ExcelResourceUnitTest)  Time elapsed: 0 sec  <<< ERROR!
java.lang.Exception: No runnable methods
        at org.junit.runners.BlockJUnit4ClassRunner.validateInstanceMethods(BlockJUnit4ClassRunner.java:191)
        at org.junit.runners.BlockJUnit4ClassRunner.collectInitializationErrors(BlockJUnit4ClassRunner.java:128)
        at org.junit.runners.ParentRunner.validate(ParentRunner.java:416)
        at org.junit.runners.ParentRunner.<init>(ParentRunner.java:84)
        at org.junit.runners.BlockJUnit4ClassRunner.<init>(BlockJUnit4ClassRunner.java:65)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.<init>(SpringJUnit4ClassRunner.java:138)
        at org.springframework.test.context.junit4.SpringRunner.<init>(SpringRunner.java:49)
        at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
        at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:481)
        at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:104)
        at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:86)
        at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
        at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
        at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
        at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:33)
        at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:283)
        at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:173)
        at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:153)
        at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:128)
        at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:203)
        at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:155)
        at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:103)

and at the end of the Maven install phase I have the following summary that says that all the tests are failed:
Tests run: 4, Failures: 0, Errors: 2, Skipped: 0

[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  11.251 s
[INFO] Finished at: 2020-02-16T19:24:02+01:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.18.1:test (default-test) on project excel-api: There are test failures.
[ERROR]
[ERROR] Please refer to C:\Users\nobil\Documents\workspace-sts-3.9.11.RELEASE\spring-boot-excel-api-master.zip_expanded\spring-boot-excel-api-master\target\surefire-reports for the individual test results.
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException

The strange thing is that I commented out all the test methods into my JUnit classes. For example the previous error is related to this test class:
package com.springboot.excelapi.integration;

import java.io.IOException;
import java.util.List;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;

import com.springboot.excelapi.Application;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = { Application.class })
@WebAppConfiguration
@ActiveProfiles(profiles = { "no-liquibase" })
public class ExcelResourceUnitTest {

    /*
    @Test
    public void processCompVibrAndTempoExcelTabTest()
    {
        final ExcelService excelService = new ExcelService();

        try {
            excelService.processCompVibrAndTempExcelTab();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    */

}

as you can see this class contains a single test method that is commented out.
So why when I perform the mvn clean install command it seems that it is trying to execute test method that at the moment are disabled by commenting out it?

A: If you don't want to run the test use @Ignore on class or single test method.
It seems that there are still tests that run (4 tests as maven summarizes)
so all-in-all probably you shouldn't always run mvn -DskipTests clean install or at least not always run it because you'll still want the working tests to run.
Now as for the error, you should have at least one public method annotated with @Test so leave the method but comment out its content (again, IMO its better to use @Ignore as I've said before)


text:
Q: i want to create a stored procedure in sql that select certain rows in a table and then apply input condition on it i want to make a store procedure or a function that select certain rows from column and then allow the user to update another column in the same table, the user should be allowed to enter the input value after the select process
alter PROC AcceptReject
@department as int,@result as bit

as
begin
select*
from Job_Seeker_apply_Job
where hr_response = 1 and department=@department
update Job_Seeker_apply_Job
set manager_response =@result

the user at the beginning should enter department number which is int value then after the selection process the user should be able to update a column called manager_response for the selected rows only


text:
Q: Can't run global babel-node in es2015 mode so when I install these packages locally they work, but when installed globally (and removed them locally)
 npm i babel-cli -g
 npm i -g babel-preset-es2015
 npm i -g babel-preset-es2015-node

seems like that flag isn't setting es2016-node to look in the global package list. anyways this following error occurs:

npm run start myfile.js

babel-node --presets es2015-node -- bin/myScript.js "myfile.js"

/usr/local/Cellar/node/6.1.0/lib/node_modules/babel-cli/node_modules/babel-core/lib/transformation/file/options/option-manager.js:395
          throw new Error("Couldn't find preset " + (0, _stringify2.default)(val) + " relative to directory " + (0, _stringify2.default)(dirname));
          ^

Error: Couldn't find preset "es2015-node" relative to directory "/Users/user/project/bin"
    at /usr/local/Cellar/node/6.1.0/lib/node_modules/babel-cli/node_modules/babel-core/lib/transformation/file/options/option-manager.js:395:17
    at Array.map (native)
    at OptionManager.resolvePresets (/usr/local/Cellar/node/6.1.0/lib/node_modules/babel-cli/node_modules/babel-core/lib/transformation/file/options/option-manager.js:387:20)
    at OptionManager.mergePresets (/usr/local/Cellar/node/6.1.0/lib/node_modules/babel-cli/node_modules/babel-core/lib/transformation/file/options/option-manager.js:370:10)

npm ERR! Darwin 14.5.0
npm ERR! argv "/usr/local/Cellar/node/6.1.0/bin/node" "/usr/local/bin/npm" "run" "start" "myfile.js"
npm ERR! node v6.1.0
npm ERR! npm  v3.7.3
npm ERR! code ELIFECYCLE
npm ERR! project@0.0.0 start: `babel-node --presets es2015-node -- bin/myScript.js "myfile.js"`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the project@0.0.0 start script 'babel-node --presets es2015-node -- bin/myScript.js "myfile.js"'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the project package,

A: A hint is in the error message:

Couldn't find preset "es2015-node" relative to directory "/Users/user/project/bin"

Install the presets locally and have them saved as dependencies in your package.json by using the --save flag:
npm install --save babel-preset-es2015-node babel-preset-es2015

It is a wise move by Babel that presets are looked for locally only. This way you are forced to produce a module that is portable by describing the necessary dependencies required for its operation within the package.json, which are then installed by users via npm install.

A: npm update

solved the issue for me.


text:
Q: SQL Server cannot connect to localhost:1433 I have checked the above post
https://learn.microsoft.com/en-us/sql/database-engine/configure-windows/configure-a-server-to-listen-on-a-specific-tcp-port?view=sql-server-ver16
and I am sure my SQL Server is listening on port 1433.
But when I login through ssms, in server name, if I use
localhost:1433

an error will be thrown, but if I just use
localhost

then I can login successfully, why?


text:
Q: Python: extract text request from url I try to extract users requests from url. I try to search answer, but I only find how to parse string.
But I have a problem, that I should identify a lot of urls with request and when I try to get string with attribute, attributes with text are different.
I mean when I try
pat = re.compile(r"\?\w+=(.*)")
search = ['yandex.ru/search', 'youtube.com/results', 'google.com/search', 'google.ru/search', 'go.mail.ru/search', 'search.yahoo.com/search', 'market.yandex.ru/search', 'bing.com/search']
for i in urls:
    u = re.findall(pat, i)
    if any(ext in i for ext in search):
        if len(u) > 0:
            str = urllib.unquote(u[0])
            print str
            print {k: [s for s in v] for k, v in parse_qs(str).items()}

And it looks like
chromesearch&clid=2196598&text=королевы крика смотреть онлайн&lr=213&redircnt=1467230336.1
{'text': ['\xd0\xba\xd0\xbe\xd1\x80\xd0\xbe\xd0\xbb\xd0\xb5\xd0\xb2\xd1\x8b \xd0\xba\xd1\x80\xd0\xb8\xd0\xba\xd0\xb0 \xd1\x81\xd0\xbc\xd0\xbe\xd1\x82\xd1\x80\xd0\xb5\xd1\x82\xd1\x8c \xd0\xbe\xd0\xbd\xd0\xbb\xd0\xb0\xd0\xb9\xd0\xbd'], 'clid': ['2196598'], 'lr': ['213'], 'redircnt': ['1467230336.1']}
минималистичный+стиль&newwindow=1&biw=1280&bih=909&source=lnms&tbm=isch&sa=X&ved=0ahUKEwikhI2M_s3NAhXBBiwKHfbEBEEQ_AUIBigB#imgrc=Er7qLiHoEGPIGM:
{'bih': ['909'], 'newwindow': ['1'], 'source': ['lnms'], 'ved': ['0ahUKEwikhI2M_s3NAhXBBiwKHfbEBEEQ_AUIBigB#imgrc=Er7qLiHoEGPIGM:'], 'tbm': ['isch'], 'biw': ['1280'], 'sa': ['X']}
минималистичный+стиль&newwindow=1&biw=1280&bih=909&source=lnms&tbm=isch&sa=X&ved=0ahUKEwikhI2M_s3NAhXBBiwKHfbEBEEQ_AUIBigB#imgrc=Er7qLiHoEGPIGM:
{'bih': ['909'], 'newwindow': ['1'], 'source': ['lnms'], 'ved': ['0ahUKEwikhI2M_s3NAhXBBiwKHfbEBEEQ_AUIBigB#imgrc=Er7qLiHoEGPIGM:'], 'tbm': ['isch'], 'biw': ['1280'], 'sa': ['X']}
rjulf+ddjlbim+ytdthysq+gby+rjl+d+,fyrjvfn&ie=utf-8&oe=utf-8&gws_rd=cr&ei=ezZ0V-7iOoab6ASvlJe4Dg
{'ie': ['utf-8'], 'oe': ['utf-8'], 'gws_rd': ['cr'], 'ei': ['ezZ0V-7iOoab6ASvlJe4Dg']}
маскаи гейла&lr=10750&clid=1985551-210&win=213
{'win': ['213'], 'clid': ['1985551-210'], 'lr': ['10750']}
1&q=как+выбрать+смартфон
{'q': ['\xd0\xba\xd0\xb0\xd0\xba \xd0\xb2\xd1\x8b\xd0\xb1\xd1\x80\xd0\xb0\xd1\x82\xd1\x8c \xd1\x81\xd0\xbc\xd0\xb0\xd1\x80\xd1\x82\xd1\x84\xd0\xbe\xd0\xbd']}
Jade+Jantzen&ie=utf-8&oe=utf-8&gws_rd=cr&ei=FQB0V9WbIoahsAH5zZGACg
{'ie': ['utf-8'], 'oe': ['utf-8'], 'gws_rd': ['cr'], 'ei': ['FQB0V9WbIoahsAH5zZGACg']}

Is any way to get only text to all strings?

A: You can access the text using a dictionary lookup to get the list, then access the first element of the list:
d = {'text': ['\xd0\xba\xd0\xbe\xd1\x80\xd0\xbe\xd0\xbb\xd0\xb5\xd0\xb2\xd1\x8b \xd0\xba\xd1\x80\xd0\xb8\xd0\xba\xd0\xb0 \xd1\x81\xd0\xbc\xd0\xbe\xd1\x82\xd1\x80\xd0\xb5\xd1\x82\xd1\x8c \xd0\xbe\xd0\xbd\xd0\xbb\xd0\xb0\xd0\xb9\xd0\xbd'], 'clid': ['2196598'], 'lr': ['213'], 'redircnt': ['1467230336.1']}
text = d['text'][0]

>>> print text
королевы крика смотреть онлайн

Or you can get it directly from the parse_qs result:
>>> print urlparse.parse_qs(s)['text'][0]
королевы крика смотреть онлайн

To apply that to your code such that it will work for all values:
print {k: v[0] for k, v in parse_qs(str).items()}

i.e. take the first item of each values list.

If you want to print the dictionaries and have the strings appear in the proper representation, i.e. not as produced by repr, you could use the json module to dump the dictionary objects as strings, then print them:
import json

d = {'text': ['\xd0\xba\xd0\xbe\xd1\x80\xd0\xbe\xd0\xbb\xd0\xb5\xd0\xb2\xd1\x8b \xd0\xba\xd1\x80\xd0\xb8\xd0\xba\xd0\xb0 \xd1\x81\xd0\xbc\xd0\xbe\xd1\x82\xd1\x80\xd0\xb5\xd1\x82\xd1\x8c \xd0\xbe\xd0\xbd\xd0\xbb\xd0\xb0\xd0\xb9\xd0\xbd'], 'clid': ['2196598'], 'lr': ['213'], 'redircnt': ['1467230336.1']}
s = json.dumps(d, ensure_ascii=False)

>>> print s
{"text": ["королевы крика смотреть онлайн"], "clid": ["2196598"], "lr": ["213"], "redircnt": ["1467230336.1"]}


text:
Q: Odd ratio vs Wald test. Contradiction or missunderstanding? I have the folowing model:
mod.log.diab <- glm(data = data_train, INFEC ~ DIABETES, family = binomial(link = 'logit'))

This gives the folowing OR:
>exp(mod.log.diab$coefficients)
(Intercept)  DIABETESno
   2.826087    1.469822

This value is greater than 1 so we can say that the variable is significant.
But when I apply a Wald test I get the folowing answer:
>regTermTest(mod.log.diab, "DIABETES")

Wald test for DIABETES
 in glm(formula = INFEC ~ DIABETES, family = binomial(link = "logit"),
    data = data_train)
F =  2.34702  on  1  and  1560  df: p= 0.12573

The pvalue is greater than 0.05 so we reject H0, the test says that is not significant.
How I have to interpret this, who has the truth OR or the test?
The question does not finish yet because if I upgrade the model with more explicative variables:
mod.log.cat <- glm(data = train.cat, INFEC ~ DIABETES + EDAD + HCTO, family = binomial(link = 'logit'))

I get the folowing OR:
>exp(mod.log.mult$coefficients)
(Intercept)  DIABETESno        EDAD        HCTO
  1.3275634   1.0751666   0.9817025   1.0558760

And the folowing Wald test output:
Wald test for EDAD
 in glm(formula = INFEC ~ DIABETES + EDAD + HCTO, family = binomial(link = "logit"),
    data = train.cat)
F =  18.90695  on  1  and  1558  df: p= 1.4615e-05
Wald test for DIABETES
 in glm(formula = INFEC ~ DIABETES + EDAD + HCTO, family = binomial(link = "logit"),
    data = train.cat)
F =  0.4122714  on  1  and  1558  df: p= 0.52091
Wald test for HCTO
 in glm(formula = INFEC ~ DIABETES + EDAD + HCTO, family = binomial(link = "logit"),
    data = train.cat)
F =  41.87676  on  1  and  1558  df: p= 1.2986e-10

This time DIABETES does not reject the wald test, like in the simple model. But the strange fact is all odd ratios are near similar, so they are near 1. What is the conclusion? How is possible with OR near to 1 some variabels are significant and others no?
Thanks.


text:
Q: Rails3: validates_with, in what place I should put MyValidator? I have an validator EmailValidator and class User:
class EmailValidator < ActiveModel::Validator
  def validate(record)
    record.errors[:base] << "error"  unless record.email.scan("@")
end

class User < ActiveRecord::Base
  validates_with EmailValidator
end

If I put EmailValidator definition in separate file in lib/ directory, or in user.rb after User class definition I get an error:
/usr/lib/ruby/gems/svn/gems/rspec-core-2.0.0.beta.16/lib/rspec/core/backward_compatibility.rb:20:in `const_missing': uninitialized constant User::EmailValidator (NameError)

But if I put EmailValidator definition before User definition in user.rb like in example above it is ok.
In what place I should put EmailValidator?

A: You should be able to just put it in lib/email_validator.rb in the latest Rails 3 HEAD, and have it autoload.
Are you using an older version?
For a brief time (i.e. until the commit was reverted), files in lib were not being autoloaded -- and I believe this is still the goal, but the implementation was buggy so that change was reverted for now. To be safe and fully forward-compatible, add the following line to your config/application.rb:
config.autoload_paths      += %W( #{config.root}/lib )

Alternatively, if the code works in when using your app but not when running RSpec, then this could be a bug in RSpec rather than in Rails.

A: I resolved a similar problem putting something like this in
RAILS_APP/config/initializers/my_custom_file.rb

require 'mylibfile' # it will load file found in lib/mylibfile.rb

this solution pemits to load custom libs during application boot


text:
Q: Remove all external links from posts I have website what contain hundreads articles.
is there some way, how to remove all external links from all posts by one click/script?

A: You can do this by a SQL query, example:
UPDATE wp_posts
SET post_content = CONCAT(
    LEFT(post_content, LOCATE('<a', post_content) - 1),
    SUBSTRING(post_content, LOCATE('</a>', post_content, LOCATE('<a', post_content) + 2) + 4))
WHERE post_content LIKE '%<a%';


text:
Q: Cannot get the first value of stream, BLOC pattern in flutter I am making my first project using BLOC pattern and I am stuck on this one thing. I have made a bloc class and put a search function inside. I want to search through the very first value of the stream and add the result to the stream. but for some reason the complier does not go into that logic.
Kindly tell me what's wrong. is there a better way to do this. I have not been able to find any extensive demo or documentation on reactive programming.
import 'package:mathecad/Models/assignment.dart';
import 'package:mathecad/Resources/repository.dart';
import 'package:rxdart/rxdart.dart';

class AssignmentBloc {
  final _repository = Repository(true);
  final _assignmentStream = PublishSubject<List<Assignment>>();

  Stream<List<Assignment>> get assignments => _assignmentStream.stream.asBroadcastStream();

  getAssignments() async {
    List<Assignment> list = await _repository.getAllAssignments();
    _assignmentStream.sink.add(list);
  }

  filterByCourse(String course) async {
    List<Assignment> _filteredAssignments = [];
    if (course == 'All') {
      _assignmentStream.first.then((assignmentList) => _assignmentStream.sink.add(assignmentList));
    } else {
      assignments.first.then((asssignmentList) {
        asssignmentList.forEach((assignment) {   //  =========== code not executed =============
          if (assignment.session.course.name == course) {
            _filteredAssignments.add(assignment);
          }
        });
        _assignmentStream.sink.add(_filteredAssignments);
      }, onError: (error) {
        print("Error" + error);
      });
    }
  }

  dispose() {
    _assignmentStream.close();
  }
}

The stream is used to build a list view in a screen.
Expanded(
              flex: 15,
              child: StreamBuilder(
                initialData: null,
                stream: _bloc.assignments,
                builder: (context, AsyncSnapshot<List<Assignment>> snapshot) {
                  if (snapshot.hasData) {
                    return ListView.builder(
                      physics: BouncingScrollPhysics(),
                      padding: EdgeInsets.symmetric(horizontal: 8.0),
                      itemCount: snapshot.data.length,
                      itemBuilder: (context, index) {
                        return AssignmentTile(assignment: snapshot.data[index]);
                      },
                    );
                  } else {
                    return Center(
                        child: CircularProgressIndicator(
                      strokeWidth: 3,
                    ));
                  }
                },
              ),
            ),


text:
Q: How can I retrieve number of records in queue with SalesForce push topic How can I retrieve number of records in queue with SalesForce push topic?
I want to be notify for every change in the queue, one of those changes is new records in the queue, is there any way to do that?
count() can't be use in push topics
Thanks
Tzelon M

A: What you can do is create a separate object, let's call it QueueSize. Each object type would have a single instance of a QueueSize record, which would contain a field for the size. You could then implement triggers that would increment/decrement the QueueSize's size field, and do a PushTopic on that object.
The caveat is that depending on the activity of your queue size's fluctuations, this might not scale well as the record would constantly be in contention for locking.


text:
Q: Show different data in webpage when clicked depending on the ID I am trying to show user data when clicking link depending on a story ID. However, the page is showing the same data from one row in the database every time (web link is showing a different ID 'php?story_id=10' etc. but it's still showing the same data.
I have this function:
function displayStories(){
include('conn/conn.php');

$queryread = "SELECT Users.ID, Users.FirstName, Stories.Age, Stories.Story,
Stories.Image FROM `Stories` INNER JOIN `Users` ON Users.ID = Stories.User_ID";

$result = mysqli_query($conn, $queryread) or die(mysqli_error($conn));

if(mysqli_num_rows($result) > 0 ){

while($row = mysqli_fetch_assoc($result)){

$name = $row["FirstName"];
$idData = $row["ID"];
$age = $row["Age"];
$story = $row["Story"];
$limit = mb_strimwidth($story, 0, 300, "...");

echo

"

$name

$age years old

$limit

";

}
}
mysqli_close($conn);
}

And this to query to display the data(variables called in HTML):
include('conn/conn.php');

$str = htmlentities($_GET["story_id"]);

$query = "SELECT * "
           . "FROM Stories "
           . "WHERE ID='$str'";

$result = mysqli_query($conn, $query) or die(mysqli_error($conn));

$queryread = "SELECT Users.FirstName, Stories.Age, Stories.Story,
Stories.Image FROM `Stories` INNER JOIN `Users` ON Users.ID = Stories.User_ID";

$result1 = mysqli_query($conn, $queryread) or die(mysqli_error($conn));

if(mysqli_num_rows($result1) > 0 ){

    while($row = mysqli_fetch_assoc($result1)){

        $name = $row["FirstName"];
        $age = $row["Age"];
        $story = $row["Story"];
        $image = $row["Image"];

}
}
mysqli_close($conn);
?>

EDIT
Had two queries when I only needed one.
$str = htmlentities($_GET["story_id"]);

$queryread = "SELECT Stories.ID, Users.FirstName, Stories.Age, Stories.Story, Stories.Image FROM `Stories` INNER JOIN `Users` ON Users.ID = Stories.User_ID
WHERE Stories.ID='$str'";

$result1 = mysqli_query($conn, $queryread) or die(mysqli_error($conn));

if(mysqli_num_rows($result1) > 0 ){

    while($row = mysqli_fetch_assoc($result1)){

        $name = $row["FirstName"];
        $age = $row["Age"];
        $story = $row["Story"];
        $image = $row["Image"];

}
}
mysqli_close($conn);
?>

A: you are reading the data from (result1) not from (result).
Change this one while($row = mysqli_fetch_assoc($result1)){
to
while($row = mysqli_fetch_assoc($result)){
and then it will works fine with you .


text:
Q: Adding constrain to check if there exist a combination of pairs such that it statisfy a ratio? Lets say I have a set of items in a set x0, ..., x14 each consisting its own values v0, ..., v14
I am trying to at most 8 items such that I get the maximum value.
I am able to get the following maximization problem
max v0*x0 + ... + v14*x14
s.t.
x0 + ... + x14 <= 8
0 <= x0 <= 1
.
.
0 <= x14 <= 1

However, I need to add another constrains, that is for the items chosen, I should be able to pair them such that their ratio is less than 2.
i.e. lets say that the item chosen is x0, x1, x3, x4, x8, x9, x10, x11 with the maximum value they would also have a configuration of pairing such that,
(v0 * x0)/(v1 * x1)  <= 2,
(v3 * x3)/(v9 * x9)  <= 2,
(v4 * x4)/(v11 * x11)<= 2,
(v8 * x8)/(v10 * x10)<= 2,

Any idea on how to formulate the above set of constrains?

A: So you can precompute the valid pairs, and their value (the sum of the 2 elements)
So there are at most 14 * 13 / 2 potential ordered pairs, much less valid ones.
You need to select 4 pairs subject to the constraint that once a pair is selected, any pairs involving the same elements cannot be selected. This is a simple at most one constraints on 14 subsets of pairs.
for all item in items:
  sum(bool_pair for all bool_pair involving item) <= 1

You can use CP-SAT or the linear solver wrapper to solve this.


text:
Q: How to get acknowledgement after producing to kafka sink i.e. using FlinkKafkaProducer09 stream.addSink(new FlinkKafkaProducer09<String>("Topic-name", new SimpleStringSchema(),
properties));

Is there any callback or on completion for FlinkkafkaProducer?

A: You can try sending a message to the producer.
And once you send the message, you can write a callback on it. Thought it is an expensive operation, you should generally try to avoid it.

The send() method is asynchronous. When called it adds the record to a
  buffer of pending record sends and immediately returns. This allows
  the producer to batch together individual records for efficiency.

You can look at its usage:
 ProducerRecord<byte[],byte[]> record = new ProducerRecord<byte[],byte[]>("the-topic", key, value);
producer.send(myRecord,
           new Callback() {
               public void onCompletion(RecordMetadata metadata, Exception e) {
                   if(e != null)
                       e.printStackTrace();
                   System.out.println("The offset of the record we just sent is: " + metadata.offset());
               }
           });

Refer the documentation for more details.


text:
Q: Django Master-Detail View Plugins Let's say I have 3 django apps, app Country, app Social and app Financial.
Country is a 'master navigation' app. It lists all the countries in a 'index' view and shows details for each country on its 'details' view.
Each country's details include their Social details (from the social app) and their Financial details (from the financial app).
Social and Financial both have a detail view (for each country)
Is there an elegant way to 'plug' in those sub-detail views into the master detail view provided by Countries? So for each country detail page I would see 2 tabs showing the social and the financial details for that country.

A: 2 common solution I use for this problem:
Partial Templates:
Create a template for rendering "social" and "financial" that does not need stuff from the view, other than the object it is working on (and uses the objects functions or template tags to render it).
then you can easily {% include %} it (and set the needed variable first).
This partial view does not render a full HTML page, but only a single DIV or some other HTML element you wish to use. If you also need a "social-only" page, you can create a page that renders the header and then includes the partial template. You can use a convention like _template.html for the partial template, and template.html for the regular template.
AJAX:
Make your "social" and "financial" views aware of being called in XMLHTTPRequest (request.is_ajax()). If they are, they return only a DIV element, without all the HTML around it. This way your master page can render without it, and add that content on the fly.
The AJAX way has several advantages: you don't render the plugin views on the same request as the whole page, so if you have many of these plugin views, the master page will load faster, and you can have a smart javascript choose only the relevant plugin views to ask for.
Also, you can use the normal view to generate data you need in the template (which you can't really do in the Partial Templates method).


text:
Q: why I do not get my total count of a column with sum function in R? I have tried for already several hours to get a total count of one column using sum, in R. It worked in one case nicely but in this case it doesn't and do not understand why.
here it is a fake data set
fake_data <- structure(list(age_recoded_band = c("0-19", "20-39", "40-59",
"60+"), country = c("India", "India", "India", "India"), count_age_country = c(921L,
24601L, 11446L, 2561L), comorbidities = c("asthma", "asthma",
"asthma", "asthma"), count_study_pop_comorb = c(27L, 570L, 330L,
142L), comorbidity_rate = c(0.0293159609120521, 0.0231697898459412,
0.0288310326751704, 0.0554470909800859), count_age_group_standard_pop = c(4772L,
102286L, 55505L, 12827L), total_counts_stnd_pop = c(175390L,
175390L, 175390L, 175390L), expected_comorb_study_pop = c(139.895765472313,
2369.94512418194, 1600.26646863533, 711.219836001562)), row.names = c(NA,
-4L), groups = structure(list(age_recoded_band = c("0-19", "20-39",
"40-59", "60+"), .rows = structure(list(1L, 2L, 3L, 4L), ptype = integer(0), class = c("vctrs_list_of",
"vctrs_vctr", "list"))), row.names = c(NA, 4L), class = c("tbl_df",
"tbl", "data.frame"), .drop = TRUE), class = c("grouped_df",
"tbl_df", "tbl", "data.frame"))

I am applying the sum on expected_comorb_study_pop and do not get the answer I want
dt_total_expected_standard_pop <- fake_data %>%
  dplyr::mutate(total_expected_study_pop_comorb = sum(expected_comorb_study_pop))

I actually get the same result as in expected_comorb_study_pop which is wrong. The total is 4,819.
Does someone know why sum function does not give me the output desired?

A: There is a grouping attribute and there was only one row per group, resulting in the sum to return exactly that single value.  If we do ungroup, it will work
library(dplyr)
fake_data %>%
     ungroup %>%
     summarise(total_expected_study_pop_comorb = sum(expected_comorb_study_pop,
                  na.rm = TRUE))

summarise returns a single row.  If we need to create a new column use mutate


text:
Q: How did anyone not notice what Lara Lor-Van was carrying How did anyone not notice that Lara Lor-Van was carrying a baby for a full term? Considering that Kryptonians prohibited cross breeding,

Thousands of years ago, the Kryptonian law council prohibited
  scientists from crossbreeding Kryptonians and fauna after
  monstrosities were created.
The Genesis Chamber was created on the planet Krypton to store the
  Growth Codex and all the unborn Kryptonian embryos that would populate
  future Kryptonian society. It was submerged in amniotic fluid, where
  Aquabots were used to control and maintain the chamber, so no
  Kryptonians could enter or contaminate the birthing process.

Did Kal El , hide here for the whole term?
And it seems she was at least pretty important to Krypton, as she was to be considered one of the brightest minds on Krypton, so it would be pretty hard to hide her. So it would be pretty hard to do that one would think?

A: After the failure of her husband to convince the Council of Justice to stop mining the planetary core, Jor-El and Lara Lor-Van apparently isolated themselves, conducting scientific research, building an experimental pod and having a baby.
Given the rift between the Council and Jor-El, the ubiquity of advanced tele-presence devices and her obvious need to hide her 'delicate condition' from her peers, the likelihood is that she simply withdrew from public life for a few months.
She certainly wasn't shy about wearing maternity-wear (as the concept art below shows) but one assumes this was to be worn inside the family's citadel and not outside.


text:
Q: jquery one table inherit height from another I have two tables, with same amount of tr's. They are both loading dynamically and I can't merge them. Here's how they look like for example: LINK

The content of first table is loading from database and sometimes users can enter 3 or 4 lines of text into td (that's why I can't declare table/tr/td height). Content of second table is always the same (there will be always one line of text)

Is it possible (with javascript/jquery), that table 2 somehow inherit table rows height from table 1 (if user enter longer text) and perfectly align like here: LINK ?
I'm trying to do it like this but I have completely no idea how to check height of an element without declaring it in css first:
var tableH = $("#table1 tr").height();
$("#table2 tr").css("min-height", tableH);

A: This gets pretty close
var itemNum = 0;

$("#table1 tr").each(function() {
  $("#table2 tr:nth-child(" + (itemNum+1) + ")").height( $(this).height() );
  itemNum++;
});

EDIT
Added +1 to itemNum. nth-child is 1-based. Seems to work on your fiddle
EDIT 2
As per thirdender's suggestion, this can be simplified to
$("#table1 tr").each(function(itemNum) {
  $("#table2 tr:nth-child(" + (itemNum+1) + ")").height( $(this).height() );
});

A: Semantically, it makes sense to merge the tables. Here's some quick code that will do just that:
jQuery(function($) {
  var table2Rows = $("#table2 tr");
  $("#table1 tr").each(function(i) {
    table2Rows.eq(i).contents().appendTo(this);
  });
});

Demo
If you're generating the tables using jQuery or server side code, it makes sense to do the merge then (if possible) instead of later (using this code).
Also, I noticed some of the cells in the second table are empty… I updated the code to make the cells from the first table stretch (increased colspan) to fill that empty space: see updated jsFiddle.
Also, I think semantically it would make even more sense to make each day's activities a separate TBODY: see even more updated jsFiddle :-p

A: How about something like this:
$('#table2 td').each(function () {
  $(this).height($($('#table1 td')[$(this).index()]).height());
});

(untested)

A: I am curious why you are doing this with TR and trying to get the row height.
Depending on what technology you are using to get the data there will be some good ways to combine the data.  Is it coming across as JSON?
Maybe you can build it as fluid rows and use the spans to keep them aligned as you add records.
Also it will keep it from losing alignment as you add data.
http://jsfiddle.net/4pdCq/7/
I imported the bootstrap.css to make this work.

Subject

Hour

Users

Monday

English English English english english english

3pm

User1

Espanol

4pm

User2

Tuesday

Italian

1pm

User3

French

2pm

User4

Wednesday

Japanese

10pm

User5