text:
Q: Show that if $\sum_{n=1}^{\infty}a_n$ converges abs. and $(b_n)_{n \in \mathbb{N}}$ is bounded , then $\sum_{n=1}^{\infty} a_nb_n$ converges abs. My attempt:
Since $(b_n)_{n \in \mathbb{N}}$ is bounded it follows that there exists a bounded sequence $$(c_n)_{n \in \mathbb{N}}: 0 \leq |b_n| \leq |c_n|, \forall n \in \mathbb{N}$$
Therefore it follows that: $$\sum_{n=1}^{\infty} a_nb_n \leq \sum_{n=1}^{\infty} a_nc_n$$
Since $\sum_{n=1}^{\infty}a_n$ converges absolutely $\Rightarrow$ $\sum_{n=1}^{\infty}a_n$ converges $\Rightarrow (a_n)_{n \in \mathbb{N}} $ is a null sequence $\Rightarrow \exists N \in \mathbb{N}: \forall n \geq N: |a_n| \lt \frac{\epsilon}{|c|p}$, where $c:= max\{c_1,\dots,c_n,\dots\}, p \in \mathbb{N}$
Then it follows that: $$\forall n \geq N: |a_nc_n|=|a_n||c_n| \lt |a_n||c| \lt \frac{\epsilon}{|c|p}|c|=\frac{\epsilon}{p}$$
$$\Rightarrow \forall n \geq N: |a_{n+1}c_{n+1}+\dots+a_{n+p}c_{n+p}|\leq  |a_{n+1}c_{n+1}|+ \dots +|a_{n+p}c_{n+p}| \lt p\frac{\epsilon}{p}=\epsilon$$
So after Cauchy's convergence test, it follows that $\sum_{n=1}^{\infty} a_nc_n$ is a convergent majorant of $\sum_{n=1}^{\infty} a_nb_n$ and therefore $\sum_{n=1}^{\infty} a_nb_n$ converges absolutely.
Was this proof correct?
And a second part of that question is: If $\sum_{n=1}^{\infty}$ converges, but not absolutely, does $\sum_{n=1}^{\infty} a_nb_n$ converge?
For my proof I didn't really needed $\sum_{n=1}^{\infty}$ to converge absolutely, I just used the fact that it converges when it converges absolutely and since I proved that $\sum_{n=1}^{\infty} a_nb_n$ converges absolutely, it converges as well. Is that right?

A: If $\{b_n\}$ is a convergent sequence, then there exists an $M$ such that $|b_n|\le M$ for all $n$. It then follows that
$$
\sum_{n=0}^{\infty}|a_nb_n| = \sum_{n=0}^{\infty}|a_n||b_n|\le \sum_{n=0}^{\infty}|a_n|M \le M\sum_{n=0}^{\infty}|a_n| < \infty.
$$
The second part is not true. Take $a_n = (-1)^n\frac{1}{n}$ and $b_n = (-1)^n$, then $\{b_n\}$ is bounded, but
$$
\sum_{n=1}^{\infty}a_nb_n = \sum_{n=1}^{\infty}\frac{1}{n},
$$
which diverges.


text:
Q: Is it OK to install Exchange 2016 when ms-Exch-Schema-Version-Pt rangeUpper = 17001 without an Exchange 2019 server? An admin in the organization ran /PrepareSchema from an Exchange 2019 ISO and it succeeded. The following day their application vendor said Exchange 2019 is not supported for mail integration. So the admin decided to continue Exchange migration by running /PrepareAD from an Exchange 2016 ISO and it succeeded. Now I have a source Exchange 2013 server with the following AD attributes:

*

*Schema rangeUpper: 17001

*Exchange Organization Object Version 16217

*Exchange System Object Version: 13237
The goal is to Migrate from Exchange 2013->2016.
Since there is not going to be an Exchange 2019 server, can I still proceed with installing Exchange 2016 even though the Schema has already been extended for Exchange 2019?

A: ETA: Per Joy Zhang's comment, I didn't consider the scenario where you may want to add additional 2016 servers to the Exchange org after running 2019/PrepareAD. Please consider whether that would be a possibility in your environment. My advice below pertains to an environment where no new 2010 servers were added after the prep was completed.

Yes, it's fine. Although I'd run the 2016 schema prep to be sure. It's not going to "overwrite" your 2019 prep. I don't know if it'll just exit and say "nothing to do here", but it won't hurt.
Once you've got the 2016 server in, I'd recommit running the 2019 AD prep just to have everything consistent.
I worked in an environment where we had 2016 prep in situ for years while running a 2010 Exchange org. No issues.
Also, ask for vendor what their roadmap for supporting 2019, if you're on the latest version of their product. It's been more than a year since Exchange 2019 went RTM. Not that it's an excuse, since they can develop against the preview versions. Is their product unsupported if you have any hybrid? (Since you've got no choice there.) I get pretty tired of some vendors holding up the refresh cycle for no good reason - esp when there are not that many changes between versions and they just need to do regression testing, probably.

A: Based on my research, the supported operating system for exchange 2019 is not supported for exchange 2016. For more details: https://docs.microsoft.com/en-us/exchange/plan-and-deploy/supportability-matrix?view=exchserver-2019#supported-operating-system-platforms

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I get a count of rows that match a given year in Rails? I have a project schedule model where I track launch dates and I want to just count the items that match a given year. In this specific case, I want to know how many projects are going to launch in 2014.
Seems pretty simple and I'm thinking the caffeine hasn't hit yet, but for the life of me, I can't get this one to happen. Much appreciated.
Something like this:
@launch_this_year = Project.where(project.launch_date > 12/31/2014)

A: Please try the following code.
@launch_this_year = Project.where("extract(year from launch_at) = ?", 2014).count

A: Part of the issue is around the date format.  Use YYYY-MM-DD instead of MM/DD/YYYY.  Also your date of 'launch_date > 12/31/2014' suggests 2015 dates, not 2014.
@launch_this_year = Project.where('launch_date > ?', '2013-12-31').count

Alternatively, you could let rails convert the date format for you using DateTime.parse
@launch_this_year = Project.where('launch_date > ?', DateTime.parse('12/31/2013')).count

Another item to consider is, in the above query if there are 2014 and 2015 projects, the above query would include both.  If you want strictly 2014 projects, then Bachan solution would work or you could add a date range condition:
@launch_this_year = Project.where(launch_date: DateTime.parse('12/31/2013')..DateTime.parse('1/1/2015')).count
#=> SELECT COUNT(*) FROM `projects` WHERE (`projects`.`launch_date` BETWEEN '2013-12-31 00:00:00' AND '2015-01-01 00:00:00')


text:
Q: How to make AngularJs UI boostrap Pagination work with data I'm using the pagination custom build from here
I don't know how to make the pagination buttons work with my data. Do I have to filter it somehow?
This is where I display my data:

After that, This is where the pagination part is:

<pagination class="pagination" style="right: 10px; position: absolute; margin: 0px;" total-items="total_items" ng-model="bigCurrentPage" max-size="maxSize" class="pagination-sm" boundary-links="true" rotate="false" num-pages="numPages"></pagination>

There is a plunker example for the pagination part, but there's no data involved. Here is the link

A: Yes, you need to filter your data. The pagination directive just gives you a way to present to the user the list of possible pages and lets the user easily control the current page. You need to use the page size (defaults to 10) and the current page value to filter the data and display the correct page.
One way to do this is to add an additional filter to help with skipping:
app.filter('offset', function() {
    return function(input, start) {
        return input.slice(start);
    };
})

and then use this with limitTo to control the paging

Example JSFiddle here


text:
Q: Ruby on Rails image_tag puts two  tags in my HTML I'm still fairly new to Ruby on Rails.  I replaced a image field with the Ruby image_tag.  When I tried to resize the image using CSS, I noticed there was extra blank space below the image...after inspecting the element, I saw there were two  tags for the same image, and I'm not sure why.  Has anyone else seen this happen?
Here is what I put into my code:
<%= image_tag (post.image_url), id: "post-image", class: "img-responsive" %>

And here is what I see when I inspect the image element:

I have no idea why this is happening...any help would be fantastic.  Also, if I have been vague in any way, I apologize.  This is my first question.
Thank you!!
Edit: Here is the code I used:
index.html.erb

<%= notice %>

Posts

      Title
      Content
      Posted

        <% @posts.each do |post| %>
          <%= render partial: 'post', locals: { post: post } %>
        <% end %>

<%= link_to 'New Post', new_post_path %>

_post.html.erb

<% cache post do %>

    <%= link_to image_tag(post.image_url, id: "post-image", class: "img-responsive")  %>

<%= post.title %>

<%= post.content %>

<%= post.posted %>

    <%= link_to 'Show', post %>
    <%= link_to 'Edit', edit_post_path(post) %>
    <%= link_to 'Destroy', post, method: :delete, data: { confirm: 'Are you sure?' } %>

<% end %>

A: I'm sorry, I never saved my file after adding the
 to my file.  After reloading, I saw that there was only a single  tag.  Thanks and sorry again.


text:
Q: Inner join is giving one result when it should give more table1                               table2
id name logo                         id  name  value
1  a    asd                          1   a     2
2  b    asd                          2   a     3
3  c    asd                          3   b     4

Query:
SELECT table1.id,table1.logo,avg(table2.value) as average,
  count(table2.id) as no FROM table1 INNER JOIN table2 ON table1.name = table2.name
    ORDER BY no

this code gives only one result than 2 results

A: because you have no GROUP BY clause, try adding one.
SELECT  a.name,
        a.logo,
        AVG(b.value) avg_val,
        COUNT(*) no
FROM    table1 a
        INNER JOIN table2 b
            ON a.name = b.name
GROUP   BY a.Name
ORDER   BY no

A: FROM  REFERENCE
If you use a group function in a statement containing no
GROUP BY clause, it is equivalent to grouping on all rows.
So Use Group By
SELECT table1.id,table1.logo,avg(table2.value) as average,
       count(table2.id) as no

FROM table1 INNER JOIN table2
ON table1.name = table2.name

GROUP BY table1.name
ORDER BY no

and you should be fine
SEE  SQL FIDDLE


text:
Q: after install kernel 5.4 bluetooth is not working ubuntu version : 20.04
kernel version: 5.4.0-100-generic
Device : Tp-link 500 Adapter
After I downgrade the kernel for my Ubuntu from 5.13 to 5.4 the Bluetooth is not scanning any devices.
in kernel 5.13 working but Nvidia-340 driver is not supporting for this kernel so removed and install 5.4 recommended kernel.
I try all of these commands but had no luck.
sudo rfkill list
    2: hci0: Bluetooth
    Soft blocked: no
    Hard blocked: no

 sudo rfkill unblock bluetooth

 sudo pkill -2 rtbt
 sudo rmmod rtbth
 sudo modprobe rtbth

 sudo rmmod btusb
 sleep 1
 sudo modprobe btusb

  lsusb; dmesg | egrep -i 'blue|firm'

 Bus 002 Device 007: ID 2357:0604 TP-Link
Bus 002 Device 006: ID 03f0:2641 HP, Inc
[    0.157942] Spectre V2 : Enabling Restricted Speculation for firmware calls
[   15.881696] Bluetooth: Core ver 2.22
[   15.881722] Bluetooth: HCI device and connection manager initialized
[   15.881725] Bluetooth: HCI socket layer initialized
[   15.881727] Bluetooth: L2CAP socket layer initialized
[   15.881729] Bluetooth: SCO socket layer initialized
[   36.101199] Bluetooth: BNEP (Ethernet Emulation) ver 1.3
[   36.101201] Bluetooth: BNEP filters: protocol multicast
[   36.101206] Bluetooth: BNEP socket layer initialized
[   83.965842] Bluetooth: RFCOMM TTY layer initialized
[   83.965850] Bluetooth: RFCOMM socket layer initialized
[   83.965858] Bluetooth: RFCOMM ver 1.11
[  650.091628] audit: type=1107 audit(1646974456.866:50): pid=797 uid=103 auid=4294967295 ses=4294967295 msg='apparmor="DENIED" operation="dbus_method_call"  bus="system" path="/" interface="org.freedesktop.DBus.ObjectManager" member="GetManagedObjects" mask="send" name="org.bluez" pid=6062 label="snap.postman.postman" peer_pid=792 peer_label="unconfined"
[22838.709903] Bluetooth: hci0: urb 00000000c999395d failed to resubmit (2)
[22838.709962] Bluetooth: hci0: failed to disable LE scan: status 0x1f
[23119.156946] Bluetooth: hci0: Ignoring error of Inquiry Cancel command
[25871.673590] Bluetooth: RTBT_Tb: vendor=0x1814, device=0x3298
[25871.673592] Bluetooth: RTBT_Tb: vendor=0x0, device=0x0
[25871.673595] Bluetooth: DynamicAlloc pci_device_id table at 0x000000003d730359 with size 64
[25871.673596] Bluetooth: RTBT_Tb: vendor=0x1814, device=0x3298
[25871.673596] Bluetooth: Convert: vendor=0x1814, device=0x3298
[25871.673597] Bluetooth: RTBT_Tb: vendor=0x0, device=0x0
[25871.673598] Bluetooth: pci_device_id: vendor=0x1814, device=0x3298


text:
Q: Network interfaces and an instance-level private IP address may not be specified on the same request I am trying to create an EC2 instance using boto3 client.run_instances(**parameters) method.
This is the value of my parameters:
    {
   "ImageId":"ami-XXXXXXXXX",
   "InstanceType":"m4.large",
   "KeyName":"my_key",
   "UserData":"Content-Type: multipart/mixed",
   "Monitoring":{
      "Enabled":false
   },
   "MaxCount":1,
   "MinCount":1,
   "IamInstanceProfile":{
      "Name":"proxyIp-YYYYYYYY"
   },
   "NetworkInterfaces":[
      {
         "DeviceIndex":0,
         "AssociatePublicIpAddress":true,
         "Groups":[
            "sg-09999999fe111"
         ],
         "SubnetId":"subnet-06XXXXXXXXX"
      }
   ],
   "PrivateIpAddress":"AA.BB.C.DDD",
   "EbsOptimized":true
}

However the stack is failing on creation of an ec2 isntance with an error :

An error occurred (InvalidParameterCombination) when calling the RunInstances operation: Network interfaces and an instance-level private IP address may not be specified on the same request

Could let me know what is missing. I have checked the parameters they all looks to be fine.

A: It looks like you can request a Private IP address within the NetworkInterfaces block:
            "NetworkInterfaces": [
                {
                    "PrivateDnsName": "ip-10-0-0-157.us-east-2.compute.internal",
                    "PrivateIpAddress": "10.0.0.157",
                    "SourceDestCheck": true,
                    "Status": "in-use",
                    "SubnetId": "subnet-04a636d18e83cfacb",
                    "VpcId": "vpc-1234567890abcdef0",
                }
            ],


text:
Q: How to you modify the precache manifest file generated by Workbox? Need urls to have preceding '/' In the generated precache-manifest.*.js file the URLs all reference relative paths when I need absolute since my app will have some sub-directories as well.
Example of generated file:
self.__precacheManifest = (self.__precacheManifest || []).concat([
  {
    "revision": "1d94d834b7044ec6d4e9",
    "url": "js/app.js"
  },
  {
    "revision": "632f09e6ed606bbed1f1",
    "url": "css/app.css"
  },
  ...
}

When I need it to look like this:
self.__precacheManifest = (self.__precacheManifest || []).concat([
  {
    "revision": "1d94d834b7044ec6d4e9",
    "url": "/js/app.js"
  },
  {
    "revision": "632f09e6ed606bbed1f1",
    "url": "/css/app.css"
  },
  ...
}

I'm using webpack 4.41.0 and workbox-webpack-plugin 4.3.1
Any help would be greatly appreciated! I can add more detail if needed as well.

Here's my webpack config:
let config = {
  entry,

  stats: {
    hash: false,
    version: false,
    timings: false,
    children: false,
    errorDetails: false,
    entrypoints: false,
    performance: inProduction,
    chunks: false,
    modules: false,
    reasons: false,
    source: false,
    publicPath: false,
    builtAt: false
  },

  performance: { hints: false },

  // Valid options: "production" | "development" | "none"
  mode: inProduction ? 'production' : 'development',

  plugins: [
    new CopyPlugin(copyConfig),
    new webpack.ProvidePlugin(providers), // Providers, e.g. jQuery
    new WebpackNotifierPlugin({ title: 'Webpack' }), // OS notification
    new VueLoaderPlugin(), // Vue-loader
    new CleanWebpackPlugin(pathsToClean, cleanOptions), // Clean up pre-compile time
    new ManifestPlugin(manifestOptions), // Manifest file
    new FriendlyErrorsWebpackPlugin({ clearConsole: true }), // Prettify console
    new MiniCssExtractPlugin(cssOptions), // Extract CSS files
    new WebpackMd5Hash(), // use md5 for hashing
    {
      /* Laravel Spark RTL support */
      apply: (compiler) => {
        compiler.hooks.afterEmit.tap('AfterEmitPlugin', (compilation) => {
          exec('node_modules/rtlcss/bin/rtlcss.js public/css/app-rtl.css ./public/css/app-rtl.css', (err, stdout, stderr) => {
            if (stdout) process.stdout.write(stdout);
            if (stderr) process.stderr.write(stderr);
          });
        });
      }
    }
  ],

  module: {
    rules: [
      {
        test: /\.vue$/,
        use: ['vue-loader']
      },
      {
        test: /\.s?css$/,
        use: [
          'style-loader',
          {
            loader: MiniCssExtractPlugin.loader,
            options: { hmr: isHot } // set HMR if flagged
          },
          'css-loader',
          'postcss-loader',
          'sass-loader'
        ]
      }
    ]
  },

  resolve: {
    extensions: ['.js', '.json', '.vue'],
    modules: ['node_modules'],
    alias: {
      'vue$': 'vue/dist/vue.esm.js',
      '~': path.join(__dirname, 'resources/assets/js'),
      jquery: "jquery/src/jquery",
    }
  },

  output: {
    filename: 'js/[name].js',
    // chunkFilename: inProduction ? 'js/[name].[chunkhash].js' : 'js/[name].js',
    path: publicPath,
  },

  optimization: {
    ...optimization,
    concatenateModules: false,
    providedExports: false,
    usedExports: false,
  },

  devtool: inDevelopment ? 'eval-source-map' : false,

  devServer: {
    headers: {
      'Access-Control-Allow-Origin': '*'
    },
    port: port,
    contentBase: publicPath,
    historyApiFallback: true,
    noInfo: false,
    compress: true,
    quiet: true,
    hot: isHot,
  }
}

And my GenerateSW:
new GenerateSW({
    // The cache ID
    cacheId: 'pwa',

    // The path and filename of the service worker file that will be created by the build process, relative to the webpack output directory.
    swDest: path.join(publicPath, 'sw.js'),

    clientsClaim: true,
    skipWaiting: true,

    // Files to exclude from the precache
    exclude: [/\.(?:png|jpg|jpeg|svg)$/, /\.map$/, /manifest\.json$/, /service-worker\.js$/, /sw\.js$/],

    // Default fall-back url
    navigateFallback: '/',

    // An optional array of regular expressions that restricts which URLs the configured navigateFallback behavior applies to.
    // This is useful if only a subset of your site's URLs should be treated as being part of a Single Page App.
    navigateFallbackWhitelist: [
      /^\/media\//,
      /^\/settings\//,
    ],

    // Runtime cache
    runtimeCaching: [
      {
        urlPattern: new RegExp(`${process.env.APP_URL}`),
        handler: 'NetworkFirst',
        options: {
          cacheName: `${process.env.APP_NAME}-${process.env.APP_ENV}`
        }
      },
      {
        urlPattern: new RegExp('https://fonts.(googleapis|gstatic).com'),
        handler: 'CacheFirst',
        options: {
          cacheName: 'google-fonts'
        }
      }
    ]
  }
)

And a couple of defined common variables:
...
// Production flag
const inProduction = process.env.NODE_ENV === 'production'
const inDevelopment = process.env.NODE_ENV === 'development'

// HMR
const isHot = process.argv.includes('--hot')

// Public/webroot path
const publicPath = path.resolve(__dirname, 'public')

// Primary webpack entry point(s)
const entry = {
  /*
   * JS entry point/Vue base component
   * Make sure to import your css files here, e.g. `import '../sass/app.scss'`
   */
  app: path.resolve(__dirname, 'resources/assets/js/app.js'),
}
...

A: For anyone visiting this question, you can use the webpack output.publicPath setting to add a prefix to your manifest URLS like so:
plugins: [
    new InjectManifest({}) // Left here just for reference
],
output: {
    publicPath: '/' // You can add your prefix here
}


text:
Q: Сложный запрос Имеется масив, состоящий их строковых данных
допустим:
$arr[0]='hello'; $arr[1]='world';

Требуется вывести из таблицы бд mysql все записи, определённая ячейка которых соответствует одному из элементов массива:
mysql_query("SELECT title FROM $table WHERE value=*Одному из значений*$arr[]");

Далее сложнее.
Для ячеек, в которых value равен последнему элементу массива, надо вернуть не только title, но и, допустим, descrition (одну или несколько дополнительный ячеек). На примере выше, для всех строк со значением value='world' требуется вернуть не только title, но и description.
Далее ещё сложнее.
Допустим, каждая запись имеет свой уникальный id и значение родителя (его id), что бы иметь возможность обратиться к нему. Можно ли выводить исключительно те записи из БД, в которых не только значение value соответствует значению элемента массива, но и значение value родителя соответствует значению предыдущего элемента массива.
Возможно ли такое вообще в mysql? Заранее спасибо.
A: Так как вопрос про MySQL, то соответственно отвечаю по MySQL, соответственно ответ №1
SELECT title FROM $table WHERE value in ('hello','world')

ответ №2
SELECT title,description FROM $table WHERE value='world'

ответ №3
Не совсем понял вопрос, если не сложно, проиллюстрируйте, что вы хотите получить.
Хранение деревьев в MySQL (как впрочем и в других реляционных БД) - занятие не совсем простое. Посмотрите для начала хотя бы сюда: Работа с MySQL. Деревья.
A: *

*mysql_query("SELECT title FROM $table WHERE value in ('".implode("','", $arr)."')");

*mysql_query("SELECT title, description FROM $table WHERE value='".$arr[sizeof($arr)-1]."'");

*mysql_query("SELECT title, description FROM $table WHERE value='".$arr[sizeof($arr)-1]."'" and (SELECT id FROM $table where value='".$arr[sizeof($arr)-2]."'));, хотя вот тут не уверен.

A: На 3й вопрос, как-то так:
$arr = array( 'hello', 'world', 'of', 'mysql' );
$sql = '
  CREATE TEMPORARY TABLE `child_value` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `value` varchar(255) NOT NULL,
    PRIMARY KEY (`id`)
  );

  INSERT INTO `child_value` ( `value` )
  VALUES
    ("'.implode('"),("', $arr).'");

  CREATE TEMPORARY TABLE `parent_value`
  SELECT * FROM `child_value`;

  SELECT `child`.*
  FROM
    `table` as `child`,
    `table` as `parent`,
    `child_value`,
    `parent_value`
  WHERE
    `child`.`value` = `child_value`.`value` AND
    `child`.`parent_id` = `parent`.`id` AND
    `parent`.`value` = `parent_value`.`value` AND
    `parent_value`.`id` = ( `child_value`.`id` - 1 )
';

echo $sql;


text:
Q: Можно ли в Redmine создать шаблон проекта? Подскажите, можно ли в Redmine сохранить какой-то проект в качестве шаблона и использовать его потом при создании нового схожего проекта? Чтобы не создавать какие-то вещи с 0

A: есть расширения для шаблонов задач.
а шаблонные проектов, с набор задач, подзадач, с настроенным трекером и участниками я делаю так:
создал проект Шаблоны. в нем создаю разные проекты и настраиваю. затем в админке можно такие проекты копировать. вот и все.
к сожалению, только в админке, но это лучше, чем ничего


text:
Q: Cannot set headers after they are sent to the client when I try to make an update request I am trying to create a CRUD. I have the UPDATE created, but when I try to request from postman, I get the following error:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent
  to the client
      at ServerResponse.setHeader (_http_outgoing.js:526:11)
      at ServerResponse.header (E:\freebooks-core-api\node_modules\express\lib\response.js:771:10)
      at ServerResponse.send (E:\freebooks-core-api\node_modules\express\lib\response.js:170:12)
      at ServerResponse.json (E:\freebooks-core-api\node_modules\express\lib\response.js:267:15)
      at ServerResponse.send (E:\freebooks-core-api\node_modules\express\lib\response.js:158:21)
      at Object.exports.success (E:\freebooks-core-api\network\response.js:3:6)
      at E:\freebooks-core-api\components\book\network.js:32:18
      at processTicksAndRejections (internal/process/task_queues.js:97:5) {   code:
  'ERR_HTTP_HEADERS_SENT' } (node:2844)
  UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]:
  Cannot set headers after they are sent to the client
      at ServerResponse.setHeader (_http_outgoing.js:526:11)
      at ServerResponse.header (E:\freebooks-core-api\node_modules\express\lib\response.js:771:10)
      at ServerResponse.send (E:\freebooks-core-api\node_modules\express\lib\response.js:170:12)
      at ServerResponse.json (E:\freebooks-core-api\node_modules\express\lib\response.js:267:15)
      at ServerResponse.send (E:\freebooks-core-api\node_modules\express\lib\response.js:158:21)
      at Object.exports.error (E:\freebooks-core-api\network\response.js:12:6)
      at E:\freebooks-core-api\components\book\network.js:34:16
      at processTicksAndRejections (internal/process/task_queues.js:97:5) (node:2844)
  UnhandledPromiseRejectionWarning: Unhandled promise rejection. This
  error originated either by throwing inside of an async function
  without a catch block, or by rejecting a promise which was not handled
  with .catch(). To terminate the node process on unhandled promise
  rejection, use the CLI flag --unhandled-rejections=strict (see
  https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode).
  (rejection id: 1) (node:2844) [DEP0018] DeprecationWarning: Unhandled
  promise rejections are deprecated. In the future, promise rejections
  that are not handled will terminate the Node.js process with a
  non-zero exit code.

As I read in the error, this comes from the following files:
response.js in my network folder
exports.success = function (req, res, data, status) {
  res.status(status || 200)
    .send({
      error: '',
      data
    })
}

exports.error = function (req, res, error, status, log) {
  console.log(log)
  res.status(status || 500)
    .send({
      error,
      data: ''
    })
}

and network.js in my book (component) folder:
const router = require('express').Router()
const response = require('../../network/response')
const controller = require('./controller')

router.get('/', function (req, res) {
    controller.getBooks()
        .then( data => {
            response.success(req, res, data, 200)
        })
        .catch( err => {
            response.error(req, res, 'Unexpected Error', 500, err)
        })
})

router.post('/', function (req, res) {
  const book = req.body
  console.log(book)
  controller.addBook(book).then( data => {
    response.success(req, res, book, 201)
  })
    .catch(err => {
      response.error(req, res, 'Internal error', 500, err)
    })
})

router.patch('/:id', function(req, res) {
  const { id } = req.params
  console.log(id)
  const book = req.body
  controller.updateBook(id, book)
    .then( data => {
        response.success(req, res, data, 200)
    }).catch( err => {
      response.error(req, res, 'Internal error', 500, err)
    })
  res.send('Ok')
})

module.exports = router

but since I am calling the controller and the error is running on that line, this is the code:
const store = require('./store')

function getBooks () {
  return new Promise((resolve, reject) => {

    resolve(store.list())
  })
}

function addBook (book) {
  return new Promise((resolve, reject) => {
    if (!book) {
      reject('I reject')
      return false
    } else {

      resolve(book)
      store.add(book)
    }
  })
}

 function updateBook (id, book) {
  return new Promise( async (resolve, reject) => {
      if (!id || !book) {
          reject('Invalid data')
          return false
      } else {
        const result = await store.update(id, book)
        resolve(result)
      }

  })
}

function deleteBook (id) {
  return new Promise( async (resolve, reject) => {
      if (!id) {
          reject('Invalid data')
          return false
      } else {
        const result = await store.update(id)
        resolve(result)
      }

  })
}

module.exports = {
  addBook,
  getBooks,
  updateBook,
  deleteBook
}

finally the store
const db = require('mongoose')
const Model = require('./model')

db.Promise = global.Promise
db.connect(`mongodb+srv://fewtwtwfwe:efwefwecwecw@ferwrtervsefwg/test?retryWrites=true&w=majority`, {
    useNewUrlParser: true,
    useUnifiedTopology: true
}).then( () => {
    console.log(`Database connected`)
}).catch( err => {
    console.error(err)
})

function addBook(book) {
    const myBook = new Model(book)
    myBook.save()
}

async function getBooks() {
   const books =  await Model.find()
   return books
}

async function updateBook(id, book) {
    const foundBook = await Model.findOne({
        '_id':id
    })
    foundBook.book = book
    const newBook = await foundBook.save()
    return newBook
}

async function deleteBook(id) {
    const foundBook = await Model.findOne({
        '_id':id
    })
}

module.exports = {
    add: addBook,
    list: getBooks,
    update: updateBook,
    delete: deleteBook,
}

I modified the data of the connection to the database, because I am sure that the error does not lie there, I have made other requests and apparently everything is fine. Any idea?

A: You can only send one response for each incoming request.  This particular error message tells you that your code is trying to send two requests.  Most often, this occurs because of improper sequencing of code with asynchronous functions.  That appears to be the case in this route:
router.patch('/:id', function(req, res) {
  const { id } = req.params
  console.log(id)
  const book = req.body
  controller.updateBook(id, book)
    .then( data => {
        response.success(req, res, data, 200)
    }).catch( err => {
      response.error(req, res, 'Internal error', 500, err)
    })
  res.send('Ok')
})

First it executes:
controller.updateBook()

and then while that asynchronous operation is running, it then executes:
res.send('Ok');

Then, sometime later, updateBook() finishes and it calls either the .then() or the .catch() handler and you then try to send another response to the same request.
It appears that you should just remove the res.send('Ok') entirely because you want the response to be sent according to the status of updateBook() in either the .then() or the .catch() handler.

On a completely separate topic, it's a bit of an anti-pattern to wrap a promise returning function in another promise like you are doing in updateBook().  I'd suggest you change this:
function updateBook (id, book) {
  return new Promise( async (resolve, reject) => {
      if (!id || !book) {
          reject('Invalid data')
          return false
      } else {
        const result = await store.update(id, book)
        resolve(result)
      }

  })
}

to this:
function updateBook (id, book) {
    if (!id || !book) {
        return Promise.reject('Invalid data');
    } else {
        return store.update(id, book);
    }
}

FYI, the reason it's an anti-pattern is that it's both unnecessary code and people often make mistakes in error handling which is exactly what you did.  If store.update() rejected, you did not have a try/catch around the await to catch that error so it would have been lost and your promise would have never been resolved or rejected.
You should change all the similarly structured functions to fix this.


text:
Q: Create Azure metrics alert for failedLocationCount I want to create a Azure metrics alert for a Webtest that fires in case a number of locations has failed. I can create this manully than it shows a condition name "Whenever the average failed locations is greater than or equal to 1".
I tried to create this with azure cli command:
$aiId = "<Application Insights Azure-Id>"
$actionGroupId = "<Action Group Azure-Id>"
az monitor metrics alert create -n myAlertName -g myRgName --scopes $aiId --condition "avg availabilityResults/failedLocationCount >= 1" --action $actionGroupId --auto-mitigate true --severity 1

failing with: (BadRequest) Couldn't find a metric named availabilityResults/failedLocationCount. Make sure the name is correct. I also tried --condition "avg failedLocationCount >= 1"`` with same result. Working is --condition "avg availabilityResults/availabilityPercentage <= 85" but I don't want it not on percentage.
For the manual deployed alert I can show the settings via az monitor metrics alert list saying:
"criteria": {
  "additionalProperties": null,
  "componentId": "/subscriptions/xxx",
  "failedLocationCount": 1.0,
  "odataType": "Microsoft.Azure.Monitor.WebtestLocationAvailabilityCriteria",
  "webTestId": "/subscriptions/xxx"
}

My last test was to use the Webtest Azure-Id instead of the Application Insights Azure-Id with no success. (Error message: microsoft.insights/webtests is not a supported platform metric namespace)


text:
Q: How to randomly choose a SKSpriteNode? I want to choose from 4 enemies using random and present it on scene. For that purpose I've made this:
func enemyPicker() -> SKSpriteNode {
    var enemyArray = [mouse, robot, drone, block, bird]
    var countArray = UInt32(enemyArray.count)
    var pickOneEneny = arc4random_uniform(countArray)
    var randomElement = Int(pickOneEnemy)

    return enemyArray.randomElement
}

But Xcode says to me that SKSpriteNode does not have a member named randomElement. And it surely doesn't, but how would I say to my function that I need it to pick and assign that random Int to an actual enemy from array?
I tried to use this answer but it's not working for me. I also tried to change -> SKSpriteNode to SKTexture, String and "T" and had not any luck with it.
My SpriteNodes are declared like:
var mouse = SKSpriteNode()
let mouseAtlas = SKTextureAtlas(named: "mouse")
var mouseArray = [SKTexture]()
mouseArray.append(mouseAtlas.textureNamed("mouse_0"));
mouseArray.append(mouseAtlas.textureNamed("mouse_1"));
mouseArray.append(mouseAtlas.textureNamed("mouse_2"));

mouse = SKSpriteNode(texture: mouseArray[0]);
self.mouse.position = CGPointMake(CGRectGetMaxX(self.frame), CGRectGetMidY(self.frame) - 138)
self.mouse.size = CGSizeMake(self.mouse.size.width, self.mouse.size.height + mouse.size.height / 2)

self.mouse.name = "mouse"
self.addChild(mouse)

A: func enemyPicker() -> SKSpriteNode {
    let enemyArray = [mouse, robot, drone, block, bird]
    return enemyArray[Int(arc4random_uniform(UInt32(enemyArray.count)))]
}


text:
Q: How to convert contents of .tmp file to png I have a PHP script that, if a user-uploaded image file isn't a .png image, it will use Imagemagick to convert it to .png before saving it to a server. However it can only use the .tmp file from the HTML form, so it has to convert the CONTENTS while keeping the .tmp (and its filename) intact. This is my code so far:
if (exif_imagetype($tmpName) != IMAGETYPE_PNG) {
    $uploadOk = 0; // don't upload later
    $im = new Imagick("$tmpName");
    $im->setImageFormat( "png" );
    file_put_contents($tmpName, '');
    file_put_contents(file_get_contents($im), $tmpName);
    if (exif_imagetype($tmpName) != IMAGETYPE_PNG) { //check again
        // try again or throw error somehow?
    } else {
        $uploadOk = 1;
    }
} else {
    $uploadOk = 1;
}

How do I properly use Imagick to convert the contents of my temp file into a png version of the original (non png) image?
EDIT: It could also be that the script should work fine, and the problem is something entirely different. Not sure at this point.

A: if you are to use, IMAGICK library, then you can use something like this:
...need to explain how you get the .tmp file, which I guess by using a form on your site... so...
.. get the post file
// This equals to 'some/server/path/temp/filename.tmp'
$original_image = $_FILE['tmp_name'];
// Lets work on the Imagick...
$img = new Imagick($original_image);
$img->setImageBackgroundColor('white');// red, black..etc
$img = $img->flattenImages(); // Use this instead.
$img->setImageFormat('png');

$new_image_name = 'nice_image_name.png';
$img->writeImage($new_image_name);

See if that works for you...


text:
Q: Hide ANR messages Android I'm doing a streaming app and I really need to run this app with a foreground service... I have also to call prepare on a MediaPlayer object instead of prepareAsync because this case on some phone onPrepared event is not fired. This means that Android may show up an ANR message if streaming takes a long time, how can I hide this message? Is this possible?
Thanks in advance

A:
how can I hide this message? Is this possible?

You cannot hide this message. Call prepare() on a background thread if prepareAsync() is giving you difficulty.


text:
Q: Open Camera from WebView File Chooser in Android Lollipop I am creating a webview app. I want file chooser functionality from the webview. I successfully created the file chooser but it opens file manager to choose file.
Now I want camera to be open when user clicks on choose file.
public class MainActivity extends AppCompatActivity{

public static final String PAGE_URL  = "http://192.168.94.1/fileupload/";

private static final int INPUT_FILE_REQUEST_CODE = 1;
private static final int FILECHOOSER_RESULTCODE = 1;
private static final String TAG = MainActivity.class.getSimpleName();
private WebView webView;
private WebSettings webSettings;
private ValueCallback<Uri> mUploadMessage;
private Uri mCapturedImageURI = null;
private ValueCallback<Uri[]> mFilePathCallback;
private String mCameraPhotoPath;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    webView = (WebView) findViewById(R.id.activity_main_webview);
    webSettings = webView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setLoadWithOverviewMode(true);
    webSettings.setAllowFileAccess(true);
    webView.setWebViewClient(new Client());
    webView.setWebChromeClient(new ChromeClient());
    if (Build.VERSION.SDK_INT >= 19) {
        webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
    } else if (Build.VERSION.SDK_INT >= 11 && Build.VERSION.SDK_INT < 19) {
        webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    }
    webView.loadUrl(Constants.URL);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        if (requestCode != INPUT_FILE_REQUEST_CODE || mFilePathCallback == null) {
            super.onActivityResult(requestCode, resultCode, data);
            return;
        }
        Uri[] results = null;

        if (resultCode == Activity.RESULT_OK) {
            if (data == null) {
                if (mCameraPhotoPath != null) {
                    results = new Uri[]{Uri.parse(mCameraPhotoPath)};
                }
            } else {
                String dataString = data.getDataString();
                if (dataString != null) {
                    results = new Uri[]{Uri.parse(dataString)};
                }
            }
        }
        mFilePathCallback.onReceiveValue(results);
        mFilePathCallback = null;
    } else if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
        if (requestCode != FILECHOOSER_RESULTCODE || mUploadMessage == null) {
            super.onActivityResult(requestCode, resultCode, data);
            return;
        }
        if (requestCode == FILECHOOSER_RESULTCODE) {
            if (null == this.mUploadMessage) {
                return;
            }
            Uri result = null;
            try {
                if (resultCode != RESULT_OK) {
                    result = null;
                } else {
                    result = data == null ? mCapturedImageURI : data.getData();
                }
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), "activity :" + e,
                        Toast.LENGTH_LONG).show();
            }
            mUploadMessage.onReceiveValue(result);
            mUploadMessage = null;
        }
    }
    return;
}
private File createImageFile() throws IOException {
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES);
    File imageFile = File.createTempFile(
            imageFileName,  /* prefix */
            ".jpg",         /* suffix */
            storageDir      /* directory */
    );
    return imageFile;
}

public class ChromeClient extends WebChromeClient {
    public boolean onShowFileChooser(WebView view, ValueCallback<Uri[]> filePath, WebChromeClient.FileChooserParams fileChooserParams) {
        if (mFilePathCallback != null) {
            mFilePathCallback.onReceiveValue(null);
        }
        mFilePathCallback = filePath;
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            File photoFile = null;
            try {
                photoFile = createImageFile();
                takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
            } catch (IOException ex) {
                Log.e(TAG, "Unable to create Image File", ex);
            }

            if (photoFile != null) {
                mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                        Uri.fromFile(photoFile));
            } else {
                takePictureIntent = null;
            }
        }
        Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
        contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
        contentSelectionIntent.setType("image/*");
        Intent[] intentArray;
        if (takePictureIntent != null) {
            intentArray = new Intent[]{takePictureIntent};
        } else {
            intentArray = new Intent[0];
        }
        Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
        chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
        chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
        startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);
        return true;
    }

    public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
        mUploadMessage = uploadMsg;
        File imageStorageDir = new File(
                Environment.getExternalStoragePublicDirectory(
                        Environment.DIRECTORY_PICTURES)
                , "ViewPeer");
        if (!imageStorageDir.exists()) {
            imageStorageDir.mkdirs();
        }
        File file = new File(
                imageStorageDir + File.separator + "IMG_"
                        + String.valueOf(System.currentTimeMillis())
                        + ".jpg");
        mCapturedImageURI = Uri.fromFile(file);

        final Intent captureIntent = new Intent(
                android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");

        Intent chooserIntent = Intent.createChooser(i, "Image Chooser");
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS
                , new Parcelable[]{captureIntent});
        startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
    }

    public void openFileChooser(ValueCallback<Uri> uploadMsg) {
        openFileChooser(uploadMsg, "");
    }

    public void openFileChooser(ValueCallback<Uri> uploadMsg,
                                String acceptType,
                                String capture) {
        openFileChooser(uploadMsg, acceptType);
    }
}

public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
        webView.goBack();
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

public class Client extends WebViewClient {
    ProgressDialog progressDialog;

    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (url.contains("mailto:")) {
            view.getContext().startActivity(
                    new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
            return true;
        } else {
            view.loadUrl(url);
            return true;
        }
    }
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(MainActivity.this);
            progressDialog.setMessage("Loading...");
            progressDialog.show();
        }
    }

    public void onPageFinished(WebView view, String url) {
        try {
            if (progressDialog.isShowing()) {
                progressDialog.dismiss();
                progressDialog = null;
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }
}
}

The above code works fine but it opens file manager from where I can select an image. But I want to open camera from where user can directly click the image to upload.
Please help me :)

A: Instead of Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
Use ACTION_IMAGE_CAPTURE  like this
 /*************************** Camera Intent Start ************************/

                // Define the file-name to save photo taken by Camera activity

                String fileName = "Camera_Example.jpg";

                // Create parameters for Intent with filename

                ContentValues values = new ContentValues();

                values.put(MediaStore.Images.Media.TITLE, fileName);

                values.put(MediaStore.Images.Media.DESCRIPTION,"Image capture by camera");

                // imageUri is the current activity attribute, define and save it for later usage

                imageUri = getContentResolver().insert(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

                /**** EXTERNAL_CONTENT_URI : style URI for the "primary" external storage volume. ****/

                // Standard Intent action that can be sent to have the camera
                // application capture an image and return it.

                Intent intent = new Intent( MediaStore.ACTION_IMAGE_CAPTURE );

                 intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);

                 intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);

                startActivityForResult( intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);

             /*************************** Camera Intent End ************************/


text:
Q: Javascript not trigering and alert function is working I have Asp.net web application given by client with UI layer and its speaking with webservices. I am creating  another asp.net web application copy pasted all the HTML,CSS and images other files.
ERROR :
I have Master page and child page.
In child pages I have lot of JavaScript for validating the text box.
Javascript like:
$(document).ready
rules and messages)
they getting form tag from master for binding.
But when I click the submit button, it's not validation the control
and I have placed alert box inside the JavaScript and its working.
Kindly help here...
alert box  is working..and validation is not work in same JavaScript.
How to check the JavaScript is correctly bound with form tag?
Same problem appears in another set of master and Child page. I corrected the form tag. Like master page form tag should be in child page. It's validating properly.

A: alert outside the $(document).ready to check weather its coming inside the script also can you post the code for futhe


text:
Q: Reindexing elastic search index which have parent-child types Description of problem :
I have a index(sourceIndex) which have two types(Type A & Type B), Type A is a child type and Type B is parent of Type A , i happened to update analyzers for documents in sourceIndex so i created "destinatedIndex" with new analyzers and now i want to move documents to destinationIndex , biut when i use 'ReIndex' Api i am getting below error ,

{
   "error": {
      "root_cause": [
         {
            "type": "illegal_argument_exception",
            "reason": "Can't specify parent if no parent field has been configured"
         }
      ],
      "type": "illegal_argument_exception",
      "reason": "Can't specify parent if no parent field has been configured"
   },
   "status": 400
}

How do i proceed to reindex documents from one index to another when when the source index ahve parent child relation types , also please let me know if i miss anything.
Thanks,
K

A: I figured out a way to re-index in the above mentioned scenarios.
I created destination index with analyzers and parent child mappings(created parent and child types at a time) , and then used reindex query to reindex from source to destination(new index) indices.Doing so i was able to eliminate parent-child relation complexities.
Thanks,
K.


text:
Q: Flex: Programmatically firing event listeners I would like to programmatically fire an event on a spark checkbox.
I have a tab bar which has tabs enabled according to various checkboxes. I am loading data into these tabs. Sometimes tabs 1 and 2 will be enabled. Other times tabs 2 and 3.  Other times tab 4 by itself (and all the other combinations).
I have tried to enable the VBox (in action script) which is in my view stack but it seems to freeze the application. The VBox enables correctly upon user input on the check box. If I set the checkbox to be selected it does not fire the event and so does not enable the tab. Is it possible to manually fire an event in Flex. I have tried to see if I can take the checkbox and get the event and fire it. Unfortunately I can only see addEventListener, hasEventLister and removeEventListener. There is no way of getting the events that are already on the checkbox

A: To dispatch and event from a component:
component.dispatchEvent(event)
Example:
var evt:MouseEvent=new MouseEvent(MouseEvent.CLICK)
this.checkBox.dispatchEvent(evt)
it doesn't put the selecte mark but you could set it programmaticaly with
this.checkBox.selected=true


text:
Q: Payload contains two or more files with the same destination I launched my application in Visual Studio 2015 and now i am getting an error on the PlayerFramework saying that it is being loaded more then once.  Is anyone having this issue?
Error:
Severity    Code    Description Project File    Line
Error       Payload contains two or more files with the same destination path 'Microsoft.PlayerFramework.dll'. Source files:
C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1\ExtensionSDKs\Microsoft.PlayerFramework.Xaml\2.0.0.0\References\CommonConfiguration\neutral\Microsoft.PlayerFramework.dll
C:\Dailymotion\dailymotion-windows-universal\Dailymotion.Core\bin\Debug\Microsoft.PlayerFramework.dll   Dailymotion.Windows (Dailmotion.Windows\Dailymotion.Windows)


text:
Q: max date, find balance for each user in 2 tables MYSQL I have two tables containing users balances. One is a daily table, called daily, where only today's balances appear and a second one that consolidates previous balances of users in previous days.
The daily table looks something like:
+---------+-------------------------+----------+----------+----------+
| user_id |   transactions_date     | balance1 | Balance2 | Balance3 |
+---------+-------------------------+----------+----------+----------+
| john    | 2018-05-29 10:10:00.100 |      100 |        0 |        0 |
| mike    | 2018-05-29 09:10:01.300 |      677 |        9 |      100 |
| john    | 2018-05-29 11:05:22.450 |      100 |        2 |       99 |
| philip  | 2018-05-29 10:09:40.200 |        4 |        0 |        1 |
| john    | 2018-05-29 08:21:10.090 |        6 |        0 |        0 |
| mike    | 2018-05-29 12:03:30.200 |      900 |        0 |        1 |
| mike    | 2018-05-29 10:05:00.100 |      188 |        0 |        2 |
| philip  | 2018-05-29 05:24:11.320 |       47 |        0 |        3 |
+---------+-------------------------+----------+----------+----------+

and the consolidation table has the same structure and looks like:
+---------+-------------------------+----------+----------+----------+
| user_id |   transactions_date     | balance1 | Balance2 | Balance3 |
+---------+-------------------------+----------+----------+----------+
| john    | 2018-05-24 17:10:00.200 |        9 |       11 |      198 |
| mike    | 2018-04-12 08:11:44.800 |      100 |       13 |       13 |
| philip  | 2018-05-21 12:00:59.320 |       99 |     1000 |      122 |
| jenna   | 2018-05-10 08:12:22.211 |     2000 |        0 |       11 |
| jenna   | 2018-05-11 10:09:10.199 |     2999 |        1 |        1 |
| paul    | 2018-04-01 12:12:11.191 |      888 |      100 |      100 |
+---------+-------------------------+----------+----------+----------+

My query needs to find for each user it MAX date_transaction, so I should need a result like :
+---------+-------------------------+----------+----------+----------+
| user_id |   transactions_date     | balance1 | Balance2 | Balance3 |
+---------+-------------------------+----------+----------+----------+
| john    | 2018-05-29 11:05:22.450 |      100 |        2 |       99 |
| mike    | 2018-05-29 12:03:30.200 |      900 |        0 |        1 |
| philip  | 2018-05-29 10:09:40.200 |        4 |        0 |        1 |
| jenna   | 2018-05-11 10:09:10.199 |     2999 |        1 |        1 |
| paul    | 2018-04-01 12:12:11.191 |      888 |      100 |      100 |
+---------+-------------------------+----------+----------+----------+

I could manage to reach a result with this query for the daily table to get the max date by user:
SELECT
    t2.user_id ,
    t2.balance1 ,
    t2.balance2,
    t2.balance3
FROM
    (
        SELECT
            user_id ,
            MAX(transactions_date) AS max
        FROM
            daily
        GROUP BY
            user_id
    ) t1 ,
    (
        SELECT
            user_id ,
            balance1 ,
            balance2 ,
            balance3 ,
            transactions_date
        FROM
            daily
    ) t2
WHERE
    t1.user_id = t2.user_id
AND t1.max = t2.transactions_date

I do not know if there is a better way to do this process on table daily first. Then I tried to get the max date_transaction by user_id joining the daily and consolidation table without a result.
I added a Mysqlfiddle
Any help is much appreciated.

A: SELECT
    A.*
FROM
    (SELECT * FROM daily
     UNION ALL
     SELECT * FROM consolidation) A
JOIN
    (SELECT
        T.user_id, MAX(transactions_date) max_user_trans_date
     FROM
        (SELECT * FROM daily
         UNION ALL
         SELECT * FROM consolidation) T
     GROUP BY T.user_id) B
ON A.user_id=B.user_id AND A.transactions_date=B.max_user_trans_date;

See it run on SQL Fiddle.


text:
Q: How to understand PlaySound function API document and implement it in MASM? I know that putting 20001h in PlaySound function as the last parameter can make the music play synchronously. But why is 20001h? I also wanted the music played in the background "repeatedly" but I couldn't understand the API document since it does not mention 20001h stands for SND_SYNC nor show what stands for SND_LOOP.
Need some enlightenment, big thank!
This is my code:
includelib Winmm.lib
PlaySound PROTO,
        pszSound:PTR BYTE,
        hmod:DWORD,
        fdwSound:DWORD

file BYTE "test.wav",0
SND_SYNC DWORD 0

main proc
    mov SND_SYNC, 20001H
    INVOKE PlaySound, OFFSET file, NULL, SND_SYNC

.......

A:
I know that putting 20001h in PlaySound function as the last parameter can make the music play synchronously.

That is incorrect. It plays the file asynchronously.
The last parameter is a bitmask, it can hold multiple flags OR'ed together. SND_SYNC is defined as 00000h (the absence of any other flags), whereas 20001h is a combination of SND_ASYNC (00001h) OR'ed with SND_FILENAME (20000h).
SND_LOOP (00008h) can only be used in combination with SND_ASYNC.
So, to accomplish what you want:

I also wanted the music played in the background "repeatedly"

You need to combine the SND_FILENAME, SND_ASYNC, and SND_LOOP flags. That numeric value is 20009h.
Here are all of the flags you can use with PlaySound(). Their meanings are explained in PlaySound's documentation 1:

Name
Value

SND_SYNC
0x00000000

SND_ASYNC
0x00000001

SND_NODEFAULT
0x00000002

SND_MEMORY
0x00000004

SND_LOOP
0x00000008

SND_NOSTOP
0x00000010

SND_PURGE
0x00000040

SND_APPLICATION
0x00000080

SND_NOWAIT
0x00002000

SND_ALIAS
0x00010000

SND_ALIAS_ID
0x00110000

SND_FILENAME
0x00020000

SND_RESOURCE
0x00040000

SND_SENTRY
0x00080000

SND_RING
0x00100000

SND_SYSTEM
0x00200000

1 Note: SND_RING is undocumented, but you can see that SND_ALIAS_ID is a combination of SND_RING OR'ed with SND_ALIAS.


text:
Q: SwiftUI where to store and manage app specific files Where do I store files, like 1k png files, specific to my app in SwiftUI? I do not want them accesable from outside the app and I want to be able to download and delete them. I don't think CoreData is the right place for them or user defaults because they are not key value pairs.
I also need to know how much storage is available to the app for these files and manage this.


text:
Q: Many-to-many relation and form with extra field I am struggling with Many-to-Many model and form. What is the best way to show extra level field when creating a new Person with skill. I am going also to edit it later.
I am trying to achieve an effect in forms like that:
[input text] name
[select] skill name (there are choices in the model)
[input text] level of the skill

I tried things which people were suggesting but I couldn't make it to work. For example inlineformset + through.
Later on, I would like also to give the user a chance to add multiple sets of skill+level, maybe it is worth to think about it in advance?
My models and form:
class PersonSkill(models.Model):
    person = models.ForeignKey('Person', on_delete=models.CASCADE)
    skill = models.ForeignKey('Skill', on_delete=models.CASCADE)
    level = models.CharField(max_length=50, choices=[(1, 'working'),
                                                     (2, 'advanced'),
                                                     (3, 'champion')], null=True, blank=True)

class Skill(models.Model):
    name = models.CharField(max_length=50, null=True, blank=True)

    def __str__(self):
        return self.name

class Person(models.Model):
    name = models.CharField(max_length=30, null=True, blank=True)
    skill = models.ManyToManyField('Skill', through='PersonSkill', blank=True)

    def __str__(self):
        return self.name

class PersonForm(forms.ModelForm):
    class Meta:
        model = Person
        fields = ('name',)


text:
Q: Removing all fragments with same tag I open new fragments with this :
fragment = new Frag_Business_Dialog();
fragment.setArguments(bundle);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE).add(R.id.mainContent, fragment,"mesaj_chat").commit();

and i remove them by this on button press:
  getFragmentManager().beginTransaction().remove(getFragmentManager().findFragmentByTag("mesaj_chat")).commit();

My app can open one or two... or many same fragments. And i want to remove all of them with the same tag by one line of code ( one press of a button ). With the code above i remove one by one. How can i tag all this fragments and remove them at once?
Thanks!

A: I've not tried it but I'd say keep the count of how many fragments you have and then loop on this count to remove all the fragments one by one.


text:
Q: Bash String Interpolation wget I'm trying to download files using wget and for some reason I think I'm encountering some problems with string interpolation. I have a list of files to be downloaded that I have successfully parsed etc (no small feat for me) and would like to incorporate these into a for loop wget statement combo which downloads these files en masse.
Please forgive me the URLs won't work for you because the password and data have been changed.
I have tried single and double quotes as well as escaping a few characters in the URL (the &s and @s which I presume are at the marrow of this).
   list of files

   files.txt

   /results/KIDFROST@LARAZA.com--B627-.txt.gz
   /results/KIDFROST@LARAZA.com--B626-part002.csv.gz
   /results/KIDFROST@LARAZA.com--B62-part001.csv.gz

wget statement works as a single command
   wget -O files/$i "https://tickhistory.com/HttpPull/Download?           user=KIDFROST@LARAZA.com&pass=RICOSUAVE&file=/results/KIDFROST@LARAZA.com--N6265-.txt.gz"

but a loop doesn't work
   for i in `cat files.txt`; do
       wget -O files/$i "https://tickhistory.com/HttpPull/Download?  user=KIDFROST@LARAZA.com&pass=RICOSUAVE&file=$i"
   done

A: Edit: Main issues was "files/$i" instead of "files$i" (see comments)
Don't use a for-loop/cat for reading files, use a while/read loop. Less problems with buffer-overflow/splitting/etc...
while read -r i; do
  wget -O "files$i" "https://tickhistory.com/HttpPull/Download?  user=KIDFROST@LARAZA.com&pass=RICOSUAVE&file=$i"
done < files.txt

Also make sure you quote variables to prevent expansion/splitting errors. Also not really sure why you're doing files/$i, since $i has full path.


text:
Q: Find the Same day of Previous Year Given by Current Year Date in SQL Server I am working with SQL Server, The scenario is to find out the Same Day's Date of Previous Year as of Today's Day.
Suppose 2014-03-06 is Today Date and Day is Thursday I want to Find the Same day in Previous lies in the same week .which is 2013-03-07
can any body help?
HERE is what i Have Written:
 DECLARE @DateFrom AS DATETIME
 DECLARE @DateTo AS DATETIME

SET @DateFrom = '2014-01-01'
SET @DateTo = '2014-02-10'

DECLARE @Count AS INT

SET @Count = DATEDIFF(DAY, @DateFrom, @DateTo)

CREATE TABLE #current_year /*This Year*/
(
  [Date] DATETIME ,
  WeekNum INT,
  [Day] VARCHAR(20),
  Data INT
)
CREATE TABLE #last_year /*This Year -1*/
(
  [Date] DATETIME ,
  WeekNum INT,
  [Day] VARCHAR(20),
  Data INT
)
WHILE ( @Count > 0 )
        BEGIN
            INSERT  INTO #current_year
            VALUES  ( CONVERT(VARCHAR(10), @DateFrom, 101),
                      DATEPART(week,@DateFrom),
                      DATENAME(weekday, @DateFrom),@Count)
            INSERT  INTO #last_year
            VALUES  ( CONVERT(VARCHAR(10), DATEADD(YEAR, -1, @DateFrom), 101),
                      DATEPART(week,DATEADD(YEAR,1,@DateFrom)),
                      DATENAME(weekday, DATEADD(YEAR, -1, @DateFrom)),@Count)
            SET @DateFrom = DATEADD(day, 1, @DateFrom)
            SET @Count = @Count - 1
        END
        SELECT * from #current_year
        SELECT * from #last_year

        SELECT CONVERT(varchar(10),#current_year.[Date],111) AS CYDate,
               --ISNULL(CONVERT(varchar(10),#last_year.[Date],111) ,/*CONVERT(varchar(10),DateAdd(dd, 1, DATEADD(yy, -1, #current_year.Date)),111)*/) AS LYDate
               --CONVERT(varchar(10),#last_year.[Date],111) AS LYDate
               Coalesce(CONVERT(varchar(10),#last_year.[Date],111) ,DateAdd(dd, 1, DATEADD(yy, -1, #current_year.Date))) AS LYDate,
               #current_year.Data AS CD,
               #last_year.Data AS LD
               FROM #current_year
               --LEFT JOIN #last_year ON #last_year.WeekNum = #current_year.WeekNum
   --                                 AND #last_year.[Day] = #current_year.[Day]
                                    Left JOIN #last_year ON #last_year.WeekNum =  DatePart(wk, GETDATE())

DROP TABLE #current_year
DROP TABLE #last_year

Here is the Output:
Here is the output after adding your solution, now in left join it excludes (NULL) data of previous year

A: Basically you need to find difference in days between same dates in this and previous years, then understand "day difference" by mod 7, and sum it with date in previous year:
DECLARE @now DATETIME
SET @now = '2014-03-06'

SELECT CAST (DATEADD(YEAR, -1, @now) + (CAST (@now as INT) - CAST (DATEADD(YEAR, -1, @now) AS INT)) % 7 AS DATE)

Returns
2013-03-07

A: Try
DECLARE @now Date
SET @now = '2014-06-03'
SELECT DATEADD(week, -52, @now)

A: SELECT DateName(dw, DATEADD(yy, -1, GETDATE()))

gives Wednesday
SELECT DateName(dw, DateAdd(dd, 1, DATEADD(yy, -1, GETDATE())))

gives Thursday
edit:
SELECT DateAdd(dd, 1, DATEADD(yy, -1, GETDATE()))

gives '2013-03-07 17:30:16.590'
you need to cast the date as per you requirement..
update:
change this part with,
Left JOIN #last_year ON #last_year.WeekNum =  DatePart(wk, GETDATE())

in your case:
Left JOIN #last_year ON DatePart(wk,  #last_year.[Date]) =  DatePart(wk, #current_year.[Date])

update 2:
Left JOIN #last_year ON (MONTH(#last_year.[Date])=MONTH(#current_year.[Date]) and Day(#last_year.[Date])=Day(#current_year.[Date]))

Output:

or
output:
Left JOIN #last_year ON (#last_year.WeekNum = #current_year.WeekNum and #last_year.[Day] = #current_year.[Day])

choose which ever is your required output.

A: DECLARE @Date DATE = '2014-03-06'
SELECT DATEADD(WEEK,-52,@Date)

Retrun value :

2013-03-07


text:
Q: Ruby: Method Help I am a computer science major, and we are just learning Ruby.  I am very lost on this problem we are supposed to solve, mostly syntax issues.  Here is what we are to do:

Write a method that takes an array of strings and a block and calls this block on each string. Recall that the keyword to call a block is yield. The syntax for the call is the following:

method(["blah", "Blah"]) {...}

Test the method by passing it a block that prints the result of applying reverse to each string. Print out the original array after the call.
  Test it again by passing a block that calls reverse!. Print out the original array. Observe the differences, explain them in comments.

I'm not sure how to do this problem at all.  I'm especially new to block and yield.

A: def my_method(array, &block)
  array.each{|a| yield a}
end

array = ["one", "two", "three"]
my_method(array) do |a|
  puts a.reverse
end
#=> eno
#=> owt
#=> eerht
array
#=> ["one", "two", "three"]
my_method(array) do |a|
  puts a.reverse!
end
#=> eno
#=> owt
#=> eerht
array
#=> ["eno", "owt", "eerht"]


text:
Q: Building LINQ query to get List of Dictionaries from Dictionary of string/HashSet of Dictionary of String/String? I need to convert one traditional logic into LINQ query (Method Syntax).
I looked at few questions already asked on this forum. One that came very close to my scenario is this: Dictionary<string, List<Dictionary<string,string>>> query using linq. But I am still having difficulty converting my following logic into equivalent LINQ (Method Syntax) query. I need help. I am still learning LINQ, so please bear with me.
Dictionary<String, HashSet<Dictionary<String, String>>> myData = BuildMyData();
String givenKey = GetGivenKey();
String givenValue = GetGivenValue();

// I need LINQ (Method syntax) equivalant to following logic:
List<Dictionary<String, String>> matched = new List<Dictionary<String, String>>();
foreach(KeyValuePair<String, HashSet<Dictionary<String, String>>> kvp in myData)
    foreach (Dictionary<String, String> dict in kvp.Value)
        if (dict.ContainsKey(givenKey) && dict[givenKey] == givenValue)
        {
            matched.Add(dict);
            break;
        }

How can I build matched using LINQ methods syntax?
I tried following, but this gives me two errors -
matched = myData.Where(kvp => kvp.Value.Where(dict =>
                dict.ContainsKey(givenKey) && dict[givenKey] == givenValue)).ToList();

But that gives me two errors:

*

*CS0029 Cannot implicitly convert type 'System.Collections.Generic.IEnumerable>' to 'bool'

*CS1662 Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type

What am I doing wrong? and How do I fix it?

A: You can use SelectMany to get the dictionaries in each Value:
 matched = myData
    .SelectMany(kv => kv.Value)
    .Where(dict => dict.TryGetValue(givenKey, out string value) && value == givenValue)
    .ToList();

Whenever you see a nested foreach the LINQ way is to use SelectMany.
Your query doesn't work because you are selecting the KeyValuePairs instead of each Values dictionary and also because you pass an enumerable to Where instead of something that returns a bool(a so called predicate).


text:
Q: API or any other way to access IMDB TOP 250 list? I have done extensive research and found that I couldn't find an API. Is there any available API to get the TOP 250 list?
Or another way to get access to the list?
I tried accessing the page HTML and parsing in my JSP backend. But the problem here is that I get only a skeleton, the list loads as AJAX.
Any way of web scraping it?
Any usage Idea would be appreciated...

A: The easiest way is to just download the data from the IMDb alternate interfaces.
The file you want is ratings.list.gz.  The Top 250 films are listed in the first section.

A: Yes now there is a API called the omdbapi
http://www.omdbapi.com/

A: I came across this problem too and I solved it with some scraping. Here is the Python code:
import requests
import re

top250_url = "http://akas.imdb.com/chart/top"

def get_top250():
    r = requests.get(top250_url)
    html = r.text.split("\n")
    result = []
    for line in html:
        line = line.rstrip("\n")
        m = re.search(r'data-titleid="tt(\d+?)">', line)
        if m:
            _id = m.group(1)
            result.append(_id)
    #
    return result

It returns the IMDb IDs of the Top 250 movies. Then, using the imdbpy package you can ask all the information about a movie, since you have the movie ID.

A: Available from there:
http://api.myapifilms.com/imdb.do
Get url for it is there: (You'll need a free token)
 http://api.myapifilms.com/imdb/top?token=GET A FREE API KEY&format=json&data=0

(Not my site)

A: https://www.theimdbapi.com/
this one is great, i am usng from sometime now


text:
Q: Passing MySQL query results to Javascript/Jquery in Django I am trying to send mysql query results in the context of my Django template to a Javascript variable. I am using pivot.js https://github.com/nicolaskruchten/pivottable which requires jquery and the jquery UI.
In the Django view:
cursor.execute(query)
data = dictfetchall(cursor)
json_data = json.dumps(data, cls=DateTimeEncoder)
context['pivot_data'] = json_data

This works and I am able to see the data in the javascript console but for some reason it is not formatted properly.
From my Django template:
{% load staticfiles %}
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>
<script type='text/javascript' src="{% static "js/pivot.js" %}"></script>
<script type='text/javascript'>
    var pivotData = '{{ pivot_data }}';
    $("#output").pivotUI(
        pivotData,
        {
            rows: ["XXX"],
            cols: ["YYY"]
        }
        );
</script>

A: The following is going to be a string (it's a JSON object that you quoted):
var pivotData = '{{ pivot_data }}';

You can do:
var pivotData = {{ pivot_data }};

But this is bad practice, as it's akin to eval-ing the JSON data (and will fail certain on special characters, as documented here).
A better approach would be:
var pivotData = JSON.parse('{{ pivot_data }}');


text:
Q: Is there a library for TLS 1.1 or TLS 1.2 in Python 2.6? I've got an assignment to create a socket server and client that communicate securely. I have to use either TLS 1.1 or 1.2 to avoid BEAST attacks. We're given Python version 2.6, but this doesn't have support for TLS 1.1 or 1.2.
Are there any external libraries you guys know of that implement this in Python 2.6, or would I be better off using the Python 3.4 dev version that added support?

A: From a quick test, if you build pyOpenSSL on top of OpenSSL 1.0.1, it looks like you get TLSv1.1 and 1.2 support. And it supports Python 2.6+/3.2+.
The API is different from the stock ssl module, but the Connection object is not that different from ssl.SSLSocket, so there's a good chance porting will just be a trivial search-and-replace.
With the current released version 0.13.1, there is implicit TLS 1.1 and 1.2 support, but no way to explicitly request or require them. The best you can do from the client side is set SSLv23_METHOD add OP_NO_SSLv2 and OP_NO_SSLv3 options, which guarantees TLS 1.0, 1.1, or 1.2. I haven't tested what you can do from the server side.
With the trunk code (the patch in #1020632 has been committed), there is explicit 1.1 and 1.2 support. From the client side, you can use TLSv1_1_METHOD to get TLSv1.1 only, TLSv1_2_METHOD to get TLSv1.2 only, and probably (I haven't tested) SSLv23_METHOD with OP_NO_SSLv2, OP_NO_SSLv3, and OP_NO_TLSv1 to get 1.1 or 1.2. Again, I haven't tested what you can do from the server side.
You should be able to pip install bzr+lp:pyopenssl to install the trunk; if not, check it out or download a current tarball and pip install that.

My guess is that you can write code that always gets 1.2 when using properly-built pyOpenSSL 0.13.1 and OpenSSL 1.0.0 or later, but may silently use something worse if either the client or server environment is built in a way that doesn't meet those requirements, and have no way to detect the problem. If you want the connection to fail instead of fall back in that case (which you probably do), it looks like you'll need a newer pyOpenSSL.

Here's my first test on a mostly-clean OS X 10.8.5 machine with Homebrew and pip installed:
$ brew install --universal openssl
$ sudo LDFLAGS=-L/usr/local/opt/openssl/lib CPPFLAGS=-I/usr/local/opt/openssl/include pip-2.6 install pyOpenSSL
$ python2.6
>>> import socket, OpenSSL
>>> OpenSSL.SSL.SSLeay_version(OpenSSL.SSL.SSLEAY_VERSION)
'OpenSSL 1.0.1e 11 Feb 2013'
>>> ctx = OpenSSL.SSL.Context(OpenSSL.SSL.SSLv23_METHOD)
>>> sock = socket.socket()
>>> ssock = OpenSSL.SSL.Connection(ctx, sock)
>>> ssock.connect_ex(('www.ssllabs.com', 443))
0
>>> ssock.send('GET /ssltest/viewMyClient.html HTTP/1.1\r\nHost: www.ssllabs.com\r\n\r\n')
66
>>> ssock.recv(16384)
-- snipped headers for chunked reply
>>> ssock.recv(16384)
'2000\r\n'
>>> d = ssock.recv(16384)
>>> d.find('TLS 1.1')
2324
>>> d.find('TLS 1.0')
2432
>>> d[2324:2432]
'TLS 1.1	\r\n\t\tYes	\t\t\t\r\n\t
\r\n\t
\r\n\t\t'

This proves (assuming ssltest.org is correct) that we not only claim TLS 1.1 support, but also made a 1.2 or 1.1 connection.


text:
Q: bash tab completion not working in graphical shells I have a fresh install of xubuntu 14.04 with xrdp installed.

*

*tab completion works when logged in via ssh

*tab completion doesn't work when using any graphical shell (terminal, xterm, ...)

*/usr/share/bash-completion/bash_completion is there

*dot-sourcing that file doesn't help, too, in graphical shells

*/bin/bash is the default shell and is also returned by echo $SHELL

*the usual lines in .bashrc are there

those are the lines in .bashrc (for every user on the system - it's actually also in the skeleton file in /etc/skel/.bashrc):
if ! shopt -oq posix; then
  if [ -f /usr/share/bash-completion/bash_completion ]; then
    . /usr/share/bash-completion/bash_completion
  elif [ -f /etc/bash_completion ]; then
    . /etc/bash_completion
  fi
fi

What else could cause the tab completion to not work?

A: Just found an answer here.
It's xfce what's blocking the use of tab.
edit ~/.config/xfce4/xfconf/xfce-perchannel-xml/xfce4-keyboard-shortcuts.xml
find this line:
<property name="<Super>Tab" type="string" value="switch_window_key"/>
NOTE: there can be multiple lines containing name="<Super>Tab", so keep searching until you find the one also containing the value="switch_window_key".
and change it to:
<!--<property name="<Super>Tab" type="string" value="switch_window_key"/>-->
Relog.


text:
Q: JAVA GC Major GC vs Minor GC In our latency sensitive app we have caching data (which resides in TG) and short lived object which die out in the YG. I have seen there is significant difference in the minor GC time and Major GC time. I suspected that it is related to relatively larger size of TG.
Could anyone explain how the GC time correlates with the TG size. Minor GC is quite frequent and fast.

A: Objects which survive minor collection in YG gets moved to TG/Old generation to free up space in YG. Size of YG is kept small to ensure that minor collection doesn't take much time and can be run more frequently. And during these minor GC objects which still have references are moved to TG.
So TG size is more because usually bigger objects which survive few YG cleanups move to this segment. Also cleanup in TG doesn't run very frequently so it can have bigger memory allocated.
So minor GC cleans up objects in YG but major GC cleans up YG as well as TG.

A: The main point is that GC time is dictated not by the TG size, but by the number of objects in it. A performance-sensitive application should not use the heap for caching. There is a wide range of existing caching libraries that support off-heap caches.


text:
Q: Promise in Pipe transform I don't want to use "| async pipe" because I don't want to get data for every component. My transform function below:
 transform(key: string, ...args) {
  this.storage.get("dictionary").then((dict) => {
   var translated = dict[key] || "noResource";
   console.log("key = "+key + ", value = "+translated);
   return translated;
  });
}

I can get key and values but value does not rendered. I tried ngZone but not working.

A: If you want the pipe to be asynchronous and update itself later I think the only way is by using WrappedValue.
For example like this where the Promise updates the pipe after 1s. In your use-case it's going the work exactly the same way.
See live demo: https://stackblitz.com/edit/angular-knamur?file=src%2Fapp%2Ftest-async.ts
@Pipe({name: 'testAsync', pure: false})
export class TestAsyncPipe implements PipeTransform {

  private val: number;
  private originalValue: number;

  constructor(private _ref: ChangeDetectorRef) {}

  transform(value: number): any {
    if (value === this.originalValue) {
      return this.val;
    } else {
      new Promise(resolve => {
        setTimeout(() => resolve(value * 2), 1000) ;
      }).then((v: number) => {
        this.val = v + 1;
        this._ref.markForCheck();
      });
    }

    this.originalValue = value;
    this.val = value;

    return WrappedValue.wrap(value);
  }
}

Then in template use:
{{ 42 | testAsync }}

After 1s it'll update the template and show 85.

A: I don't understand why you don't want to use the only "buildin" pipe that matches your case.
says your pipe is :
 @Pipe({name: 'mypipe'})
    export class MyPipe implements PipeTransform
    {
        transform(key: string, ...args) {
            // watch out you missed the return statement !!
            -->return<-- this.storage.get("dictionary").then((dict) => {
            var translated = dict[key] || "noResource";
            console.log("key = "+key + ", value = "+translated);
            return translated;
        });
    }

the in your template you could just use
{{ 'mykey' | mypipe | async }}

If you don't want to use async pipe you will be forced to mimic is logic who is already dead simple and bug proof. No gain for you.


text:
Q: flexigrid how to access url posted parameters when they are sent to script Edit to answer:
I have tried the following
$(document).ajaxSuccess (function(ev, xhr, s) {
    document.write('url: ' + s.data);
});

And I just get a blank page - it does write out the right data though, just not the rest of the page
Hi, I am using flexigrid, and im posting parameters to from flexigrid.js to a php script to return json to the grid.
Flexigrid allows me to sort, filter etc. just as jquery should allow.
I want to catch the last posted parameters to flexigrid so that I can build a csv to allow download of the same (full) information.
However, flexigrid wont allow me to access the posted parameters.
Is this because flexigrid script keeps all those parameters in its own scope? I notice a variable/object called sitems inside firebug that basically has all the info I need, but javascript wont let me access it. Is there any way to access parameters sent to flexigrid? any help is much appreciated.
Cheers Ke

A: Well I'm not familiar with flexigrid but taking a quick peak at the source used on their homepage, it uses jQuery's $.ajax to make the requests to your PHP backend. So although the flexigrid API may not allow you to discover the parameters that it is posting, you can use the hooks that jQuery provides (the global ajax events) to monitor what is going on. In particular, ajaxSuccess will give you the info you want once the flexigrid request to your backend has returned successfully, at which point you can use the data that was posted to build your CSV link.
Try pasting this into the firebug console while on the flexigrid homepage, running it and then clicking a column header in the Example 3 (Flexigrid with a dynamic data):
$(document).ajaxSuccess(
    function(ev, xhr, options) {
        console.info(options.data);
    }
);

You should see the data value that was used in the $.ajax request made by the flexegrid in your console output. e.g.
page=1&rp=15&sortname=printable_name&sortorder=asc&query=&qtype=name


text:
Q: Global Shell Variables? As a system administrator with root access on a unix machine, is it possible to provide default shell variables to all users of a system?
That is, as an individual unix user, I can define environmental variables in my bash shell by editing my .bash_profile
export FOO="BAR"

Is there a way to provide all users with a default set of environmental variables without editing each user's individual shell variables?  If there a way to provide specific users with default variables?
Long time *nix user here, but I've never done much on the administering a unix machine side, so my apologies if this is a dump/naive question.

A: If am understanding your question correctly, you need system wide environmental variables that can be accessed by all users in the system. If so, you could set it from /etc/profile. From here,
The /etc/profile file is not very different however it is used to set system wide environmental variables on users shells. The variables are sometimes the same ones that are in the .bash_profile, however this file is used to set an initial PATH or PS1 for all shell users of the system.

A: For setting global variables, there may a number of approaches, depending on your users' shells, and whether or not your system supports a login.conf capability database or similar, which should apply, no matter what shell a user has.
The simplest approach is to add the definitions you want to the relevant system files under /etc. Depending on the shells used on the system, you may find yourself setting up and managing multiple files. For example, sh and bash probably expect to find /etc/profile, zsh looks for /etc/zprofile, whereas csh or tcsh will look for something different.
If your system supports the capability database, you only need to modify one file, and all settings should be applied correctly. Under FreeBSD, for example, you'd add your envar definition to the setenv capability for any class of user that needs it:
default:\
        :setenv=BLOCKSIZE=K,FOO=BAR:\
        :tc=default:

Rebuild the database, and at next login $FOO should be set.
If you don't have login.conf, there may be a different method of globally configuring users' environments on your system.
To set variables for a particular user, I think you'd need to use the first approach, where you'd test the value of the $USER variable in a case statement or similar construct supported by the particular shell. For example, this should work in sh and compatible:
case $USER in
    root) FOO=ROOTBAR;;
    *) FOO=USERBAR;;
esac
export FOO


text:
Q: laravel i need add values to table in database i need to add Task_id from My Form  to task_id in database  This Code in the controller is working fine but i need it To add id value withput deleting old one  like
if task_id in the database have  (3)
and the Task id from the form is (8) it should be (3,8)
but My controller delete (3) and put (,8)
i need it to be in this format to expload it later
      public function store(){
    Enrollee::where('path_id',1 )->where('user_id',Auth::user()->id )->update([
    'user_id'  => auth()->user()->id ,
    'task_id'  => ','.request('Task_id')

]);

A: It's doing that because you're overwriting the task_id variable, simply fix by doing so:
public function store(){

    $enrollee = Enrollee::where('path_id',1)->where('user_id',Auth::user()->id)->first()

    Enrollee::where('path_id',1 )->where('user_id',Auth::user()->id )->update([
        'user_id'  => auth()->user()->id,
        'task_id'  => $enrollee->task_id.','.request('Task_id')
    ]);

}

A: store(){

    $oldTasks = Enrollee::where([['path_id', '=', 1],['user_id','=',Auth::user()->id])->first();

    Enrollee::where('path_id',1 )->where('user_id',Auth::user()->id )->update([
    'user_id'  => auth()->user()->id ,
    'task_id'  => $oldTasks.','.request('Task_id')

]);


text:
Q: Не удаётся вставить повторяющийся ключ в базу данных Создаю приложение для зоомагазина. При попытке добавления новой записи возникает исключение, мол, невозможно добавить повторяющийся ID.
Текст запроса - "Insert into dbo.[Другие товары] ([id_Товара], [Название], [Цена]) VALUES ('{0}', '{1}', '{2}')", ID, Name, Price Запрос рабочий, проверен напрямую в SQL
Генерация ID происходит так textBox1.Text = Guid.NewGuid().ToString();.
То есть, ни о каком повторяющимся идентификаторе и речи быть не может. Следует также сказать, что запись в таблицу добавляется, но исключение всё равно возникает.
Код обработчика события:
 private void btn_addData_Click(object sender, EventArgs e)
    {
        textBox1.Text = Guid.NewGuid().ToString();
        if (dal.SaveNewProduct(textBox1.Text, txbx_productName.Text.Trim(), decimal.Parse(txbx_productPriсe.Text)))
            this.DialogResult = DialogResult.OK;
        else
            this.DialogResult = DialogResult.No;
    }

Код метода:
 public bool SaveNewProduct(string ID, string Name, decimal Price)
    {

        string queryForAddInProduct = string.Format("Insert into dbo.[Другие товары] ([id_Товара], [Название], [Цена]) VALUES ('{0}', '{1}', '{2}')", ID, Name, Price);
        bool flagresult = false;
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            SqlCommand command = new SqlCommand(queryForAddInProduct, connection);
            try
            {
                connection.Open();
                command.ExecuteNonQuery();
                if (command.ExecuteNonQuery() == 1)
                    flagresult = true;
                connection.Dispose();
            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.ToString());
            }
            return flagresult;
        }
    }

A: Так вы два раза один и тот же запрос выполняете, один раз без проверки результата, а второй раз уже с проверкой:
command.ExecuteNonQuery();          // 1-й раз
if (command.ExecuteNonQuery() == 1) // 2-й раз
    flagresult = true;

Первое исполнение проходит успешно, а но втором уже выходит исключение. Поэтому и запись в базу добавляется и ошибка выходит.


text:
Q: import stripe using node js + typescript I need to import stripe in to my application
First i installed stripe npm package
npm install stripe --save

Stripe documentation says that secret key should be set before connect the api.
In Node it likes this
var stripe = require('stripe')(' your stripe API key ');

I need to convert it to typescript
I tried following way . but it didnt work for me
import * as stripe from 'stripe';
stripe('sk_test_...')

if some can help me to solve this problem it will great help to me to continue my project without delay.
Thank you

A: It's a feature request. Go give it another thumbs up.

A: You can refer to the repo on GitHub:
https://github.com/stripe/stripe-node
import Stripe from 'stripe';

const stripe = new Stripe('sk_test_...', {
  apiVersion: '2020-08-27',
});

const createCustomer = async () => {
  const params: Stripe.CustomerCreateParams = {
    description: 'test customer',
  };

  const customer: Stripe.Customer = await stripe.customers.create(params);

  console.log(customer.id);
};
createCustomer();

A: As of stripe 8.0.1 the package has its own typeing so it is not necessary to install additional types. Just import it like this:

import Stripe from 'stripe';

A: Update: The solution below is outdated and for those using stripe@8.0.1 or greater the answer from David Dehghan should be used.
As britzkopf said, stripe don't provide their own definitions yet (and probably never will), but you can use the type definitions from @types/stripe.
npm install stripe @types/stripe

And then import and construct the Stripe class as follows.
import * as Stripe from 'stripe';
const stripe = new Stripe('xxx_xxx_xxx');

If you want finer grained imports for some reason you can use this (somewhat hacky) approach instead.
import { resources } from 'stripe';
const stripeData = require('stripe')('xxx_xxx_xxx');
const customers = new resources.Customers(stripeData, null);

A: I had the same problem and the solution provided did not work for me:
import * as Stripe from 'stripe';
const stripe = new Stripe('xxx_xxx_xxx');

Using this approach, I got this error

[ts] Cannot use 'new' with an expression whose type lacks a call or
  construct signature. stripe.ts(1, 1): Type originates at this import.
  A namespace-style import cannot be called or constructed, and will
  cause a failure at runtime. Consider using a default import or import
  require here instead. (alias) class Stripe (alias) namespace Stripe
  import Stripe

I got it working using "allowSyntheticDefaultImports": true in tsconfig.json
With this compile option, the following is valid in TypeScript:
import Stripe from "stripe";

const secret = process.env.STRIPE_SECRET!;
export const stripe = new Stripe(secret);

A: From the official documentation:
import Stripe from 'stripe';
const stripe = new Stripe('sk_test_...');


text:
Q: How to use distinct and MAX(id) in same query SQL? I have table "batchtracing" with 8999 rows for batchno for id 7434.
I want DISTINCT batchno for this table. For all DISTINCTbatcho i have 47 rows.
For every batchno i want to get MAX(ID) but for every row.
My questions is: How can i have MAX(id) for every DISTINCT batchno
I try this but is not my solution, this put me for all rows same value at column id.
SELECT DISTINCT batchno,
                          (SELECT     MAX(id) AS Expr1
                            FROM          batchtracing) AS id
FROM         batchtracing AS batchtracing_1
WHERE     (contentid = '7434')

To get what i need i use 3 query, but i want just one because is slowly.
What i do now:
Step 1: SELECT DISTINCT batchno, batchstatus FROM batchTracing WHERE (contentid = " & contentid & ") AND (batchstatus = 'active') ORDER BY batchno

Step 2:SELECT MAX(id) AS Expr1 FROM batchTracing WHERE (batchno = '" & batchno & "') AND (contentid = '" & contentid & "')

Step 3: SELECT batchstatus FROM batchtracing WHERE id =  batchTracingID

This method is very slowly and i want just one query to result all this.

A: Use rownumber:
Select b.*
From (select b.*, row_number() over (partition by batchno order by id desc) as seqnum
     From batchtracing
    ) b
Where seqnum = 1

A: You're over complicating this - you just need to group by batch number
SELECT batchno, MAX(id)
FROM batchtracing
WHERE contentid = '7434'
GROUP BY batchno

If contentid is a numeric column, you should remove the quotes round 7434 to avoid unnecessary conversions.

A: It sounds like you want to use GROUP BY.
select batchno, max(id)
  from batchtracing
 where contentid = 7434
 group by batchno

A: If I understand your question correctly, all you need to do is use a GROUP BY:
Select  BatchNo, Max(Id) As Id
From    BatchTracing
Where   ContentId = '7434'
Group By BatchNo

A: SELECT batchno, max(Id)
FROM batchTracing
Where ContentId = '7434'
GROUP BY batchno


text:
Q: How can I show/hide divs dynamically (on KeyUp, iTunes style) using Javascript/jQuery and a text or search field with case insensitive I set out on a journey to create an iTunes-like search using Javascript. I learned about jQuery, and with some help from people on StackOverflow, I was successful.
I've come back here to share with you a very simple way to create a dynamic hide/show list based on the user input.
Let's search!

The entirety of the tutorial code can be found here.
And a JSFiddle for it is here!

A: First, create a simple Div Layout with some text in the divs and search bar above it.

      <form>
        <input id="searchfield" type="text" onclick="value=''" value="Case Sensitive Search">
      </form>

Cat

Black

White

Orange

Dog

Rat

Zebra

Wolf

CSS:
      .container {
        width: 100%;
      }
      .horizontal_containers {
        height:10%;
        border: solid 3px #B30015;
        font-size: 45px;
        text-align: center;
      }

Second, you will make a script utilizing jQuery. Remember the title says this is a Dynamic Search, meaning (for us) we want to update the search with each key typed:
$("#searchfield").keyup(function() {

Note: Need a selector refresher?
Then we will set a variable to the value in #searchfield:
  var str = $("#searchfield").val();  //get current value of id=searchfield

To ensure we show all the divs in our list when there is nothing in the searchfield we create an if statement based on the length of our new variable (str):
  if (str.length == 0) {
    //if searchfield is empty, show all
    $(".horizontal_containers").show();
  }

Last, we do the actual hiding of the divs if the length of str is not 0:
  else {
    //if input contains matching string, show div
    //if input does not contain matching string, hide div
    $("div:contains('" + str + "').horizontal_containers").show();
    $("div:not(:contains('" + str + "')).horizontal_containers").hide();
  }
});

The div:contains() and div:not(:contains()) statements are what set the conditions. It's essentially an if statement. They search the text contained within the div, not the div attributes. If you want to search a deeper div structure you can use more than one selector in the script's jQuery statements like so:
if (str.length == 0) {
//if searchfield is empty, show all
  $(".container .color").show();
  } else {
    //if input contains matching string, show div
    //if input does not contain matching string, hide div
    $(".container div:contains('" + str + "').color").show();
    $(".container div:not(:contains('" + str + "')).color").hide();
  }

Replace the script statement you already have to give it a try.
Note: The nesting structure of your divs must match that in your selector.
And that's essentially it. If you have tips to improve this, know how to change it to a case insensitive search, or anything else you can think of, please let me know!
Thanks to MrXenoType I have learned case insensitivity for the :contains function.
To create a case insensitive search for this project simply add:
$.expr[":"].contains = $.expr.createPseudo(function(arg) {
    return function( elem ) {
        return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
    };
});

This creates a pseudo for the contains function. Place this code above your other script (within the same script) to make true for only this script.

A: So good to see Nick was successful on this experiment. good job on learning how to do it :)
Just in case you haven't encountered this jquery plugin, you might want to take a look at it too it's called Quick search.
https://github.com/riklomas/quicksearch
And I've used it on numerous pages and it works like a charm. example:
http://fedmich.com/works/types-of-project.htm

A: Try:
$.expr[":"].contains_nocase = $.expr.createPseudo(function(arg) {
    return function( elem ) {
        return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
    };
});

for adding a :contains_nocase() selector with jQuery 1.8


text:
Q: stat() got an unexpected keyword argument 'follow_symlinks' Web search found links to bugs, I don't write complicated code on Python, just want to confirm I understand syntax:
https://docs.python.org/3/library/pathlib.html
Path.stat(*, follow_symlinks=True)¶
But when I write Path(filepath).stat(follow_symlinks=False) I'm getting "stat() got an unexpected keyword argument 'follow_symlinks'" error. lstat() in place of stat(follow_symlinks=False) does job done.
Python 3.8.5. TIA

A: You're reading it correctly. You just missed the footnote. From the page you linked

Changed in version 3.10: The follow_symlinks parameter was added.

So if you want to use that keyword argument, you need Python 3.10 or newer. Otherwise, as you've already figured out, just use lstat.


text:
Q: Creating animation to the D3 and SVG elements I am trying to create Olympic logo(with five circles) using the SVG and D3.JS,
by getting the circle properties from the JSON data,and then i want to assign some animations to the circles, possibly swapping first circle with the last circle, through animation. i came half way through the code but i am struck with how to access circles and add some transitions.my code is here.
JSBIN

A: What I usually do is have an update function which receives the data and updates the nodes accordingly an additional parameter I add is a animation flag to perform transitions on update
function update(data, animate) {
   // bind data
   // enter
   // enter + update
   // - if animate = true perform animation
   // exit
}

demo


text:
Q: Python code for seaborn boxplot to edit x-axis interval ticks to show more of the box and less of outliers I am trying to edit a boxplot I have to show me more of the box itself and less of the outliers. The data I am working with is skewed to the right with extreme outliers. I want the plot to show the outliers but towards the right side compiled together and not taking as much space as seen below:

Python code:
plt.figure(figsize=(20,10))
plt.xlim(0,(max(df_var)+5))
plt.ylabel('Counts')
sns.boxplot(x=df_var, notch=True, flierprops={"marker": "x"}, width = 0.5, medianprops={"color": "coral"})
plt.text((max(df_var) - 0.1*max(df_var)), 0.45, stat_str, style='italic',
        bbox={'facecolor': 'red', 'alpha': 0.5, 'pad': 10})

xtick_loc = [1, 2, 3, 4, 5, 10, 50, 200]

plt.xticks(xtick_loc)

plt.show()