text:
Q: Android tablelayout reducing the gap between two rows As shown in the image i want to reduce the gap between two rows (marked by red color) so that my edit text appears just below the text.

My code

<TableRow
    android:id="@+id/tableRow1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="2dip" >
      <TextView
          android:id="@+id/textView1"
          android:text="@string/projectName"
          android:textSize="16sp"
          android:textAppearance="@string/projectName"
          android:textColor="@color/text_color"/>
</TableRow>

<TableRow
    android:id="@+id/tableRow2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="2dip">

     <EditText
         android:id="@+id/editText"
         android:layout_width="0dp"
         android:layout_height="35dp"
         android:inputType="text"
         android:singleLine="true"
         android:background="@drawable/editbox_background_normal"
         android:layout_weight="1"
         android:padding="5dip"
         />

</TableRow>
      </TableLayout>

A: Get rid of all those paddings
   android:padding="2dip"
   android:padding="5dip"

You can use padding left and right instead.
 Try this
<TableRow
    android:id="@+id/tableRow1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
 >
      <TextView
          android:id="@+id/textView1"
          android:text="@string/projectName"
          android:textSize="16sp"
          android:textAppearance="@string/projectName"
          android:textColor="@color/text_color"/>
</TableRow>

<TableRow
    android:id="@+id/tableRow2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
>

     <EditText
         android:id="@+id/editText"
         android:layout_width="0dp"
         android:layout_height="35dp"
         android:inputType="text"
         android:singleLine="true"
         android:background="@drawable/editbox_background_normal"
         android:layout_weight="1"
         />

</TableRow>
      </TableLayout>

A: Buddy try this,it must help you
<TableRow
        android:id="@+id/tableRow1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="2dip"
         android:layout_marginBottom="10dp">
          <TextView
              android:id="@+id/textView1"
              android:text="@string/projectName"
              android:textSize="16sp"
              android:textAppearance="@string/projectName"
              android:textColor="@color/text_color"/>
    </TableRow>

    <TableRow
        android:id="@+id/tableRow2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="2dip"
     android:layout_marginTop="10dp">

         <EditText
             android:id="@+id/editText"
             android:layout_width="0dp"
             android:layout_height="35dp"
             android:inputType="text"
             android:singleLine="true"
             android:background="@drawable/editbox_background_normal"
             android:layout_weight="1"
             android:padding="5dip"
             />

    </TableRow>
          </TableLayout>


text:
Q: Search console shows my site info but google analytics don't. what should i do? I've indexed my website like around 3 months ago or so; Search console shows my data about my site but google analytics is not showing any stats at all. everywhere in google analytics shows "no data available". I have to mention that when I visit google analytics, I see my property name so I think my site is linked properly.. but I can't understand why it's not showing any stats!
what should I do?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Edge detection with Single-Pass Wireframe Rendering I would like to implement a typical CAD software and therefore need an edge detection algorithm to draw the silhouette of various meshes. Silhouette includes outline, ridges and creases of various objects. Here is an example of a cube created in Blender where the silhouette is made of thick orange lines:

I want to use a geometrical approach where wireframes are drawn on top of the objects and interior lines like diagonals are omitted. The wireframe rendering is described here. In this article, the geometry shader is used to draw the wireframe.
It is also explained that one has to set a per-vertex attribute to decide if a line should be omitted or not.
My question is: How could I decide which lines I have to omit? I use OpenGL as rendering API by the way.
EDIT: To clarify, I really want to draw just the edges that constitutes the silhouette but not any diagonals. Here is an example of what I want to achieve:

A: From your sample pictures I infer that you want to enhance

*

*the silhouette edges, i.e. those that belong to the outline of the projections,

*the salient edges, i.e. those that join two angled faces.

The former are determined by looking at the orientation of the faces: a face is "facing" when the observer is outside the half-space it delimits and conversely. A silhouette edge is one that belongs to a facing face and a non-facing face. Note that this is a viewer-dependent property.
A salient edge is such that it joins two faces forming a sufficiently large angle that the connection is considered non-smooth. (The angle threshold is up to you.) This is a viewer-independent property.

A: Consider freestyle
https://www.blender.org/manual/en/render/freestyle/index.html

Freestyle is an edge- and line-based non-photorealistic (NPR) rendering >engine. It relies on mesh data and z-depth information to draw lines on >selected edge types. Various line styles can be added to produce >artistic ("hand drawn", "painted", etc.) or technical (hard line) looks.

I haven't used it yet, but am planning to give it a try for creating line drawings from 3d models.


text:
Q: Fatal error: Call to a member function fetch() on a non-object on old php 5.1 code now running on php 5.4 I have this old code that was written around the time of PHP 5.1, I am trying to make it all work on a newer server running php5.4 however I am getting this error from the code below:
Fatal error: Call to a member function fetch() on a non-object
<?php
/**
* <b>Database Connection</b> class.
* @author Php Object Generator
* @version 3.0 / PHP5.1
* @see http://www.phpobjectgenerator.com/
* @copyright Free for personal & commercial use. (Offered under the BSD license)
*/
Class Database
{
private function Database()
{
    $databaseName = $GLOBALS['configuration']['db'];
    $driver = $GLOBALS['configuration']['pdoDriver'];
    $serverName = $GLOBALS['configuration']['host'];
    $databaseUser = $GLOBALS['configuration']['user'];
    $databasePassword = $GLOBALS['configuration']['pass'];
    $databasePort = $GLOBALS['configuration']['port'];

    $databaseName = 'bitbsoft_butlers';
    $driver = $GLOBALS['configuration']['pdoDriver'];
    $serverName = 'localhost';
    $databaseUser = 'bitbsoft_butlers';
    $databasePassword = 'Sherw00d123';
    $databasePort = '3306';

    if (!isset($this->connection))
    {
        $this->connection = new PDO($driver.':host='.$serverName.';port='.$databasePort.';dbname='.$databaseName, $databaseUser, $databasePassword);
        $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
    if (!$this->connection)
    {
        throw new Exception('I cannot connect to the database. Please edit configuration.php with your database configuration.');
    }
}

public static function Connect()
{
    static $database = null;
    if (!isset($database))
    {
        $database = new Database();
    }
    return $database->connection;
}

public static function Reader($query, $connection)
{
    try
    {
        $result = $connection->Query($query);
    }
    catch(PDOException $e)
    {
        return false;
    }
    return $result;
}

public static function Read($result)
{
    try
    {
        return $result->fetch();
    }
    catch (PDOException $e)
    {
        return false;
    }
}

public static function NonQuery($query, $connection)
{
    try
    {
        $r = $connection->query($query);
        if ($r === false)
        {
            return 0;
        }
        return $r->rowCount();
    }
    catch (PDOException $e)
    {
        return false;
    }

}

public static function Query($query, $connection)
{
    try
    {
        $i = 0;
        $r = $connection->query($query);
        foreach ($r as $row)
        {
            $i++;
        }
        return  $i;
    }
    catch (PDOException $e)
    {
        return false;
    }
}

public static function InsertOrUpdate($query, $connection)
{
    try
    {
        $r = $connection->query($query);
        return $connection->lastInsertId();
    }
    catch (PDOException $e)
    {
        return false;
    }
}
}
?>

Now the error is being thrown by the line fetch() but I am confused as to what has changed from 5.1 to 5.4 that would cause this, would really appreciate any help on this.
Many thanks


text:
Q: Angular2 Tutorial: Promise error (type not assignable) in Service I'm following the tutorial "Angular Tour of Heroes" at the Angular.io site.
I've setup the project with Angular CLI (see environment versions at the end of this post).
I'm stuck at point 5 (services) :
using the same files provided by the tutorial, I get the following error in line 9 of 'hero.service.ts':
Failed to compile.

/home/myuser/angular-tour-of-heroes/src/app/hero.service.ts (9,4): Type 'Hero[]' is not assignable to type 'Promise<Hero[]>'.
  Property 'then' is missing in type 'Hero[]'.

This is the code of the service (file 'hero.service.ts'):
import { Injectable } from '@angular/core';
import { Hero } from './hero';
import { HEROES } from './mock-heroes';

@Injectable()

export class HeroService {
  getHeroes(): Promise<Hero[]> {
    return Promise.resolve(HEROES);
  }
}

And this is a snippet of the component (app.component.ts) that acts when the service promise resolves:
export class AppComponent implements OnInit {
  title = 'Tour of Heroes';
  heroes: Hero[];
  selectedHero: Hero;

  constructor(private heroService: HeroService) { }

  getHeroes(): void {
    this.heroService.getHeroes().then(heroes => this.heroes = heroes);
  }

  ngOnInit(): void {
    this.getHeroes();
  }

  onSelect(hero: Hero): void {
    this.selectedHero = hero;
  }
}

I just saw this other post about a similar error in the tutorial, but the error depicted there complaints about property 'length' instead of 'then':
Type 'Promise' is not assignable to type 'Hero[]'. Property 'length' is missing in type 'Promise'.

As I said, I'm stuck here, I don't know if my environment could have something to do with the error. I'm using Ubuntu 14.04  (ARM Chromebook with crouton Chroot), node v7.10.0, npm 4.6.1, angular 4.1.3, angular-cli 1.0.6 :
$ ng --version
    _                      _                 ____ _     ___
   / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
  / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
 / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
/_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
               |___/
@angular/cli: 1.0.6
node: 7.10.0
os: linux arm
@angular/common: 4.1.3
@angular/compiler: 4.1.3
@angular/core: 4.1.3
@angular/forms: 4.1.3
@angular/http: 4.1.3
@angular/platform-browser: 4.1.3
@angular/platform-browser-dynamic: 4.1.3
@angular/router: 4.1.3
@angular/cli: 1.0.6
@angular/compiler-cli: 4.1.3


text:
Q: Upgrading Group Policy Central Store We have a 2x Server 2003 DC's, and manage group policy using the administrative tools on a couple Windows 7 workstations. We've just started using the domain central store to ensure that we're all seeing the same settings. I'm just slightly confused about how the administrative templates work when dealing with multiple versions of a product.
Am I correct in assuming that if I copy the the newest (Server 2012/Windows 8) templates in to the central store, I will have available all of the settings for Server 2012/Windows 8 as well as any settings specific to preceding operating systems, such as Server 2008/7/Vista/XP? Or do I need to add the set of ADMX/ADML files for each OS, in which case there are name conflicts?
Also, how does this work for templates for other MSFT products, such as IE or Office? Do you need the set of templates for each version?
Thanks for any help you can provide.

A: Updating the central store to the newer versions won't break any old settings in your GPOs. All they will do is change the GUI of your "Group Policy Management Console". This applies to the windows ones as well as any out of the box office ones etc.
Now with that said, there might be some setting in the latest admx files that only apply to the most recent software, etc. but that is usually outlined in it's help.
Office admx files do have some overlap for some settings, but generally speaking I would try to use the one that matches the version you have installed for the computer it is targeted for.

A: To answer your questions directly: if you copy the Windows 8 / Server 2012 files over top of the 7/2008 files, you'll get the functionality of all of the new options, plus whatever MS has left in them from past versions --  historically, MS has made the Windows group policy files cumulative, and the help for each setting elaborates on the behaviour between versions.
That is not the case with some other products, like MS Office. Office does have some overlap in settings between versions, but most settings are targeted to specific Office versions. That is to say, you should have different policy files for Word 2003 and Word 2010.
There isn't any strict rule for how this works - it depends on the product and how that specific policy is written.


text:
Q: Save variable value in python Is there a way to SAVE the value of a variable (say an integer) in python?
My problem involves calling (entering and exiting) multiple times the same python script (python file, not python function) which in the end creates a txt file. I'd like to name the txt files depending on the number of times the python code was called: txt1.txt,..., txt100.txt for example.
EDIT:
The question is not related with the SAVE parameter in fortran. My mistake.

A: Not really.  The best you can do is to use a global variable:
counter = 0
def count():
    global counter
    counter += 1
    print counter

An alternative which bypasses the need for the global statement would be something like:
from itertools import count
counter = count()
def my_function():
    print next(counter)

or even:
from itertools import count
def my_function(_counter=count()):
    print next(_counter)

A final version takes advantage of the fact that functions are first class objects and can have attributes added to them whenever you want:
def my_function():
    my_function.counter += 1
    print my_function.counter

my_function.counter = 0 #initialize.  I suppose you could think of this as your `data counter /0/ statement.

However, it looks like you actually want to save the count within a file or something.  That's not too hard either.  You just need to pick a filename:
def count():
    try:
        with open('count_data') as fin:
            i = int(count_data.read())
    except IOError:
        i = 0
    i += 1
    print i
    with open('count_data','w') as fout:
        fout.write(str(i))

A: NOTE: I'm assuming that what you mean by:

calling (entering and exiting) multiple times the same python code

is that you want to call the whole Python script multiple times, in which case you need to serialize your counter in some way external to the Python interpreter, to make it available next time. If you're just asking about calling the same function or method several times within one Python session, you can do that a variety of ways and I'd point you to mgilson's answer.
There are plenty of ways to serialize things, but your implementation doesn't really have anything to do with the language. Do you want to store it in a database? Write the value to a file? Or is it enough to just retrieve an appropriate value from context? For instance, this code will get you a new file each time it is called, based on the contents of output_dir. It's obviously rough, but you get the idea:
import os

def get_next_filename(output_dir):
    '''Gets the next numeric filename in a sequence.

    All files in the output directory must have the same name format,
    e.g. "txt1.txt".
    '''

    n = 0
    for f in os.listdir(output_dir):
        n = max(n, int(get_num_part(os.path.splitext(f)[0])))
    return 'txt%s.txt' % (n + 1)

def get_num_part(s):
    '''Get the numeric part of a string of the form "abc123".

    Quick and dirty implementation without using regex.'''

    for i in xrange(len(s)):
        if s[i:].isdigit():
            return s[i:]
    return ''

Or of course you can just write a file called something like runnum.cfg somewhere next to the Python script, and write your current run number into it, then read that when the code launches.

A: mgilson's response provides good options to the original question.  Another approach is to refactor the code to separate the concerns of choosing filenames from computing + saving.  Here's a code sketch:
for i in ...:
   filename = 'txt%d.txt' % (i,)
   do_something_then_save_results(..., filename)

If you need to do this in a lot of places and want to reduce code duplication, a generator function can be useful:
def generate_filenames(pattern, num):
   for i in xrange(num):
       yield pattern % (i,)

...
for filename in generate_filenames('txt%d.txt', ...):
   do_something_then_save_results(..., filename)

Replace "..." with whatever's meaningful in your application.


text:
Q: kendo UI window z-index how can I remove z-index of the kendo window? I don`t want window to be modal, so I did like this .Modal(false). But of no use , window is rendering with z-index of 10003 like a popup. My intention is to render 9 windows on a same page ,put 3 windows per row in a table. Because of z-index , layout is distracting. If I can able to remove z-index, I can succeed.
@(Html.Kendo().Window()
.Name("window")
.Title("About Alvar Aalto")

.Modal(false)
.Content(@<text>

        Artek Alvar Aalto - Armchair 402

        Alvar Aalto is one of the greatest names in modern architecture and design.
        Glassblowers at the iittala factory still meticulously handcraft the legendary
        vases that are variations on one theme, fluid organic shapes that let the end user
        ecide the use. Interpretations of the shape in new colors and materials add to the
        growing Alvar Aalto Collection that remains true to his original design.

</text>)
.Draggable()
.Resizable()
.Width(600)
.Actions(actions => actions.Pin().Minimize().Maximize().Close())

)

A: I don't believe this can be done with the available configuration options. You could try using .Visible(false) and then manually adjust the z-index for each window to make it visible, but I imagine this would be brittle.
So I would recommend extending the window widget to create your own window type which doesn't manipulate the z-index in this way; this would keep your code encapsulated in its own class. See my answer here for some more information regarding extending kendoWindow (and a simple example). As far as I can see, the main method responsible for the z-index behavior is window.toFront(), so you'd probably have to rewrite that.

A: Since you plan to render the windows in a 3 by 3 grid I guess that you don't want to move or resize them and what you need from a KendoUI window is just the styling, correct? If so, you should take a look into panels styling (see KendoUI demo here) where you can style your code as a KendoUI window but, of course, you can neither move, nor hide nor resize.
You just need to use the following HTML:

Header
Block with header

A: the z-index is set on the "style" property dynamically of the div.
with css all you need is an !important rule that will override styles defined on the element.
  #mycontainer .k-window{
        z-index: 3 !important;
  }


text:
Q: workbench access issue "this app is blocked by Transaction Security" some of my colleagues have issue with accessing to workbench. When they try to login they receive below error:

app_blocked: this app is blocked by Transaction Security

Is it SalesForce account issue?

A: Apparently, there is something called Enhanced Transaction Security. Here's the Salesforce documentation for it. I had not heard of this before your question.
I guess your admin/company prevents access to certain features for certain users.


text:
Q: How to create a file with the names of cities and the state of the city from OpenStreetMap? Is it posible to extract data from OpenStreetMap that only contains the name of a city and the name of the state from these city?
I want to build a CSV file, where each row contains "city;state".
For example:
San Francisco;California
Annapolis;Marryland
....

At the moment I'm using osmfilter and osmconvert to create a file from all cities.
osmfilter file.o5m --keep="place=city or ( place=town and population>=1000 )" --drop-relations --drop-ways > cities.osm
osmconvert cities.osm --all-to-nodes --csv="name" --csv-headline > cities.csv

But how can I add the information about the state / country?


text:
Q: MySQL Database on RDS with memory issues I am facing high memory utilization issue on RDS MySQL server. We are having other issues too, can someone give me a help?
My database has 120GB, including indexes.
Can anyone help me out to understand, RDS memory consumption and freeing behavior?
How we can able to know what causing high memory utilization? How we can avoid it?
RDS Configuration:- db.m5.4xlarge (vCPU = 16 and RAM = 64 GB)
Here are some variables:

bulk_insert_buffer_size - 8388608
innodb_buffer_pool_chunk_size - 134217728
innodb_buffer_pool_dump_at_shutdown - ON
innodb_buffer_pool_dump_now - OFF
innodb_buffer_pool_dump_pct - 25
innodb_buffer_pool_filename - ib_buffer_pool
innodb_buffer_pool_instances8
innodb_buffer_pool_load_abort - OFF
innodb_buffer_pool_load_at_startupON
innodb_buffer_pool_load_now - OFF
innodb_buffer_pool_size - 47244640256
innodb_change_buffer_max_size - 25
innodb_change_buffering - all
innodb_log_buffer_size16777216
innodb_sort_buffer_size - 2097152
join_buffer_size262144
key_buffer_size - 16777216
myisam_sort_buffer_size - 8388608
net_buffer_length - 16384
preload_buffer_size - 32768
read_buffer_size131072
read_rnd_buffer_size262144
sort_buffer_size262144
sql_buffer_result - OFF
max_tmp_tables32
tmp_table_size6316621824
have_query_cacheYES
query_cache_limit - 0
query_cache_min_res_unit4096
query_cache_size0
query_cache_typeON
query_cache_wlock_invalidateOFF
innodb_page_cleaners4
max_connections - 2500
max_user_connections0
thread_stack196608
binlog_cache_size - 32768
binlog_stmt_cache_size32768
have_query_cacheYES
host_cache_size - 728
innodb_disable_sort_file_cacheOFF
innodb_ft_cache_size8000000
innodb_ft_result_cache_limit2000000000
innodb_ft_total_cache_size640000000
key_cache_age_threshold - 300
key_cache_block_size1024
key_cache_division_limit100
max_binlog_cache_size - 18446744073709547520
max_binlog_stmt_cache_size18446744073709547520
metadata_locks_cache_size - 1024
query_cache_limit - 0
query_cache_min_res_unit4096
query_cache_size0
query_cache_typeON
query_cache_wlock_invalidateOFF
stored_program_cache256
table_definition_cache2000
table_open_cache31512
table_open_cache_instances16
thread_cache_size - 33
connect_timeout - 60
delayed_insert_timeout300
have_statement_timeoutYES
innodb_flush_log_at_timeout - 1
innodb_lock_wait_timeout50
innodb_rollback_on_timeoutOFF
interactive_timeout - 30
lock_wait_timeout - 31536000
net_read_timeout30
net_write_timeout - 60
rpl_stop_slave_timeout31536000
slave_net_timeout - 60
wait_timeout10
+-------------------------------------+----------------------+

**Part of Innodb Status**
-------------------------------------+
InnoDB
=====================================
2019-10-02 14:21:22 0x2b94c2f40700 INNODB MONITOR OUTPUT
=====================================
Per second averages calculated from the last 33 seconds
-----------------
BACKGROUND THREAD
-----------------
srv_master_thread loops: 63575 srv_active, 0 srv_shutdown, 11740 srv_idle
srv_master_thread log flush and writes: 75314
----------
SEMAPHORES
----------
OS WAIT ARRAY INFO: reservation count 55391770
OS WAIT ARRAY INFO: signal count 26184149
RW-shared spins 0, rounds 86600920, OS waits 42401698
RW-excl spins 0, rounds 462913252, OS waits 12003058
RW-sx spins 23109, rounds 530146, OS waits 16312
Spin rounds per wait: 86600920.00 RW-shared, 462913252.00 RW-excl, 22.94 RW-sx
--------
FILE I/O
--------
I/O thread 0 state: waiting for completed aio requests (insert buffer thread)
I/O thread 1 state: waiting for completed aio requests (log thread)
I/O thread 2 state: waiting for completed aio requests (read thread)
I/O thread 3 state: waiting for completed aio requests (read thread)
I/O thread 4 state: waiting for completed aio requests (read thread)
I/O thread 5 state: waiting for completed aio requests (read thread)
I/O thread 6 state: waiting for completed aio requests (write thread)
I/O thread 7 state: waiting for completed aio requests (write thread)
I/O thread 8 state: waiting for completed aio requests (write thread)
I/O thread 9 state: waiting for completed aio requests (write thread)
Pending normal aio reads: [0, 0, 0, 0] , aio writes: [0, 0, 0, 0] ,
 ibuf aio reads:, log i/o's:, sync i/o's:
Pending flushes (fsync) log: 1; buffer pool: 0
32457638 OS file reads, 4421652 OS file writes, 2294794 OS fsyncs
2 pending preads, 0 pending pwrites
782.52 reads/s, 16384 avg bytes/read, 82.57 writes/s, 69.24 fsyncs/s
-------------------------------------
INSERT BUFFER AND ADAPTIVE HASH INDEX
-------------------------------------
Ibuf: size 1, free list len 13566, seg size 13568, 371078 merges
merged operations:
 insert 454633, delete mark 124835, delete 12938
discarded operations:
 insert 0, delete mark 0, delete 0
Hash table size 10093739, node heap has 4264 buffer(s)
Hash table size 10093739, node heap has 135474 buffer(s)
Hash table size 10093739, node heap has 1471 buffer(s)
Hash table size 10093739, node heap has 59948 buffer(s)
Hash table size 10093739, node heap has 19650 buffer(s)
Hash table size 10093739, node heap has 1081 buffer(s)
Hash table size 10093739, node heap has 7542 buffer(s)
Hash table size 10093739, node heap has 47145 buffer(s)
168373.38 hash searches/s, 14089.63 non-hash searches/s
---
LOG
---
Log sequence number 804344096126
Log flushed up to 804344095294
Pages flushed up to 803851900229
Last checkpoint at803851900229
1 pending log flushes, 0 pending chkp writes
1251611 log i/o's done, 38.88 log i/o's/second
----------------------
BUFFER POOL AND MEMORY
----------------------
Total large memory allocated 48375005184
Dictionary memory allocated 2461293
Buffer pool size 2883584
Free buffers 7704
Database pages 2599305
Old database pages 959347
Modified db pages104790
Pending reads2
Pending writes: LRU 0, flush list 0, single page 0
Pages made young 215190608, not young 1218564644
3804.95 youngs/s, 45715.22 non-youngs/s
Pages read 32426535, created 1349697, written 2650097
783.43 reads/s, 2.97 creates/s, 33.67 writes/s
Buffer pool hit rate 1000 / 1000, young-making rate 2 / 1000 not 32 / 1000
Pages read ahead 97.03/s, evicted without access 0.00/s, Random read ahead 0.00/s
LRU len: 2599305, unzip_LRU len: 0
I/O sum[251384]:cur[3936], unzip sum[0]:cur[0]
----------------------
INDIVIDUAL BUFFER POOL INFO
----------------------
---BUFFER POOL 0
Buffer pool size 360448
Free buffers 923
Database pages 324971
Old database pages 119939
Modified db pages13414
Pending reads0
Pending writes: LRU 0, flush list 0, single page 0
Pages made young 26775448, not young 149344221
483.59 youngs/s, 5762.25 non-youngs/s
Pages read 4020738, created 170517, written 337016
103.39 reads/s, 0.67 creates/s, 2.18 writes/s
Buffer pool hit rate 1000 / 1000, young-making rate 2 / 1000 not 32 / 1000
Pages read ahead 12.88/s, evicted without access 0.00/s, Random read ahead 0.00/s
LRU len: 324971, unzip_LRU len: 0
I/O sum[31423]:cur[492], unzip sum[0]:cur[0]
---BUFFER POOL 1
Buffer pool size 360448
Free buffers 961
Database pages 324942
Old database pages 119929
Modified db pages13177
Pending reads0
Pending writes: LRU 0, flush list 0, single page 0
Pages made young 25415387, not young 141982022
425.65 youngs/s, 4656.50 non-youngs/s
Pages read 3816124, created 167340, written 316273
79.30 reads/s, 0.03 creates/s, 4.48 writes/s
Buffer pool hit rate 1000 / 1000, young-making rate 2 / 1000 not 32 / 1000
Pages read ahead 0.00/s, evicted without access 0.00/s, Random read ahead 0.00/s
LRU len: 324942, unzip_LRU len: 0
I/O sum[31423]:cur[492], unzip sum[0]:cur[0]
---BUFFER POOL 2
Buffer pool size 360448
Free buffers 927
Database pages 324869
Old database pages 119903
Modified db pages12944
Pending reads1
Pending writes: LRU 0, flush list 0, single page 0
Pages made young 27297719, not young 150838953
481.65 youngs/s, 6947.94 non-youngs/s
Pages read 4077648, created 168214, written 330297
101.91 reads/s, 0.09 creates/s, 5.15 writes/s
Buffer pool hit rate 1000 / 1000, young-making rate 2 / 1000 not 31 / 1000
Pages read ahead 15.73/s, evicted without access 0.00/s, Random read ahead 0.00/s
LRU len: 324869, unzip_LRU len: 0
I/O sum[31423]:cur[492], unzip sum[0]:cur[0]
---BUFFER POOL 3
Buffer pool size 360448
Free buffers 957
Database pages 324872
Old database pages 119903
Modified db pages13846
Pending reads0
Pending writes: LRU 0, flush list 0, single page 0
Pages made young 27241158, not young 152596490
508.68 youngs/s, 5102.88 non-youngs/s
Pages read 4079040, created 165287, written 332920
101.63 reads/s, 0.06 creates/s, 4.33 writes/s
Buffer pool hit rate 1000 / 1000, young-making rate 1 / 1000 not 16 / 1000
Pages read ahead 10.12/s, evicted without access 0.00/s, Random read ahead 0.00/s
LRU len: 324872, unzip_LRU len: 0
I/O sum[31423]:cur[492], unzip sum[0]:cur[0]
---BUFFER POOL 4
Buffer pool size 360448
Free buffers 970
Database pages 324930
Old database pages 119924
Modified db pages13306
Pending reads0
Pending writes: LRU 0, flush list 0, single page 0
Pages made young 27071975, not young 156302791
495.53 youngs/s, 4981.52 non-youngs/s
Pages read 4202662, created 168923, written 335712
106.24 reads/s, 0.61 creates/s, 4.76 writes/s
Buffer pool hit rate 1000 / 1000, young-making rate 3 / 1000 not 36 / 1000
Pages read ahead 12.76/s, evicted without access 0.00/s, Random read ahead 0.00/s
LRU len: 324930, unzip_LRU len: 0
I/O sum[31423]:cur[492], unzip sum[0]:cur[0]
---BUFFER POOL 5
Buffer pool size 360448
Free buffers 1000
Database pages 324927
Old database pages 119923
Modified db pages12453
Pending reads0
Pending writes: LRU 0, flush list 0, single page 0
Pages made young 29017652, not young 165174087
520.92 youngs/s, 6319.20 non-youngs/s
Pages read 4381293, created 171171, written 331047
104.78 reads/s, 0.58 creates/s, 7.24 writes/s
Buffer pool hit rate 1000 / 1000, young-making rate 3 / 1000 not 46 / 1000
Pages read ahead 15.91/s, evicted without access 0.00/s, Random read ahead 0.00/s
LRU len: 324927, unzip_LRU len: 0
I/O sum[31423]:cur[492], unzip sum[0]:cur[0]
---BUFFER POOL 6
Buffer pool size 360448
Free buffers 973
Database pages 324822
Old database pages 119884
Modified db pages13399
Pending reads0
Pending writes: LRU 0, flush list 0, single page 0
Pages made young 25561540, not young 148607714
404.81 youngs/s, 5283.75 non-youngs/s
Pages read 3835345, created 169647, written 334254
89.85 reads/s, 0.42 creates/s, 3.21 writes/s
Buffer pool hit rate 1000 / 1000, young-making rate 2 / 1000 not 34 / 1000
Pages read ahead 11.21/s, evicted without access 0.00/s, Random read ahead 0.00/s
LRU len: 324822, unzip_LRU len: 0
I/O sum[31423]:cur[492], unzip sum[0]:cur[0]
---BUFFER POOL 7
Buffer pool size 360448
Free buffers 993
Database pages 324972
Old database pages 119942
Modified db pages12251
Pending reads1
Pending writes: LRU 0, flush list 0, single page 0
Pages made young 26809729, not young 153718366
484.11 youngs/s, 6661.19 non-youngs/s
Pages read 4013685, created 168598, written 332578
96.33 reads/s, 0.52 creates/s, 2.30 writes/s
Buffer pool hit rate 1000 / 1000, young-making rate 3 / 1000 not 47 / 1000
Pages read ahead 18.42/s, evicted without access 0.00/s, Random read ahead 0.00/s
LRU len: 324972, unzip_LRU len: 0
I/O sum[31423]:cur[492], unzip sum[0]:cur[0]
--------------
ROW OPERATIONS
--------------
0 queries inside InnoDB, 0 queries in queue
4 read views open inside InnoDB
Process ID=14412, Main thread ID=47944612980480, state: sleeping
Number of rows inserted 76778123, updated 1282408, deleted 102505, read 277730269604
1496.74 inserts/s, 47.06 updates/s, 1.30 deletes/s, 3574606.95 reads/s
----------------------------
END OF INNODB MONITOR OUTPUT
============================

A: innodb_buffer_pool_size is 47G -- this is good, and the main user of RAM.
tmp_table_size seems to be set to 6G -- This is dangerously high.  If you happen to run a few complex queries at the same time, you could run out of RAM, thereby leading to swapping, which is very bad for MySQL performance.  Set it to no more than 600M.
If that does not suffice, let's see all of SHOW VARIABLES; and SHOW GLOBAL STATUS;.  Also, show us the evidence that proclaims "memory issues".


text:
Q: How to encode Japanese characters in xsd:base64Binary field in XML I am trying to compose an XML document that will get sent to some target system. (There isn't a particular system, I'm just trying to implement a messaging standard.)  The document schema gives the type of a particular field as xsd:base64Binary.  No problem, I just base64-encode the content of the field when serializing.  But what if the original value of the field contains Unicode characters?  In my case I'm dealing with Japanese characters.
The programming language I'm using represents these characters internally with their Unicode values. Ex:

"た" (HIRAGANA LETTER TA) = 0x305F.

So before I can base64-encode this value I need a way to transform it from a double-wide byte to a series of single-width bytes. UTF-8 encoding comes to mind, so the value would become:

0xE3 0x81 0x9F

This base64-encodes to:

44Gf

So presumably that's what would go in my document.  There's just one wrinkle to this.  The system that is receiving the XML document will have to "know" somehow that the base64-decoded value of the field is UTF-8 encoded.  I can't find anything in the standard for the messaging format that says that once the value of the field is base64-decoded, the resulting value is UTF-8 (or any other format) encoded.  I was hoping the correct thing to do in this scenario is described in the XML spec, but I haven't been able to find anything definitive.
One thought that comes to mind is that maybe the character encoding of the base64-decoded value is supposed to be the same as the character encoding named in the XML prolog, for example:

<?xml version="1.0" encoding="UTF-8" ?>

So if my XML document has this, then is the receiving system supposed to know that once the field in question is base64-decoded, that it is still UTF-8 encoded?


text:
Q: Whats the difference between MySQL and MySQLi concerning Character-Encoding? I was using mysqli in php code to connect to database, i like its OOP features.
Database contains data in Persian language and collation is set to utf8_persian_ci.
after creating a connection, the charset is set to utf8:
<?php

class DBHandler {

    private $DB_HOST = "localhost"; //localhost
    private $DB_USER = "------"; //root
    private $DB_PASS = "------"; // ""
    private $DB_NAME = "------"; //test
    private $mysqli;
    private $username;

    public function __construct($user) {
        $this->username = $user;
        // CONNECT TO THE DATABASE
        $this->mysqli = new mysqli($this->DB_HOST, $this->DB_USER, $this->DB_PASS, $this->DB_NAME);
        if (mysqli_connect_errno()) {
            throw new Exception("Unable to connect to the database. Error number: " . $this->mysqli->connect_errno);
        }
        $this->mysqli->set_charset("uft8");
    }

    public function __destruct() {
        //We are done with the database. Close the connection handle.
        $this->mysqli->close();
    }
}

i was expecting to retrieve data in proper encoding, but after query-ing the database, all characters turned to ?.
I simply replaced all mysqli instances with mysql function and everything worked fine.
I'm wondering what was causing that and what can i do to use mysqli functions and get data   in right encoding ?

A: First of all: the mysql extension is deprecated. You're better off sticking to mysqli, or switching to PDO.
What you're saying about the question marks (diamonds?), isn't necessarily a DB issue. Might be your script is using a wrong encoding. Lots of people having the diamond thing, and it can be solved with a single line of code.
header('Content-Type: text/html; charset=utf-8');


text:
Q: Multiple 'Submit' buttons on same page I have 2 separate functions that are submitting on the same page (listing_details.tpl.php).  One will not work, I think maybe because of one of the submits is using AJAX.  I'm all ears for any possible solutions.
The error in the console reads
POST http://staynsurf.biz/modules/listing/post.php 404 (Not Found)

Javascript for the book_it_button
function subTotal() {
    var check_in = $('#checkin').val();
    var check_out = $('#checkout').val();
    var guest = $('#number_of_guests').val();

if(check_in!='' && check_out!='' && guest!='') {
    $('.spinner').show();
    $.ajax({
        type: "POST",
        url: '<?php print SITE_MOD; ?>listing/ajax_subtotal.php',
        data: $('#book_it_form').serialize(),
        dataType:'json',
        success: function(data) {
            $('.spinner').hide();
            if(data['result'] == 'success'){
                $('#subtotal').html('<?php echo $_SESSION["ses_currency_symbol"]; ?>'+data['pricing']);
                $('#book_it_button').removeAttr('disabled');
                $('#show_more_subtotal_info').css({'display':'block'});
                $('#service_fee').html('<?php echo $_SESSION["ses_currency_symbol"]; ?>'+data['service_fee']);
                $('#sub_total').val(data['pricing']);
                $('#serviceFee').val(data['service_fee']);
            } else {
                $('#book_it_enabled').css({'display':'none'});
                $('#show_more_subtotal_info').css({'display':'none'});
                $('#book_it_disabled').css({'display':'block'});
                $('#book_it_disabled_message').html(data['error']);
                return false;
            }
        }
    });
    return false;
}
}

$("#checkin, #checkout").attr( 'readOnly' , 'true' );
$("#checkin, #checkout").keypress(function(event) {event.preventDefault();});
$(function() {
var dates = $( "#checkin, #checkout" ).datepicker({
    minDate:0,
    maxDate:"+3Y",
    nextText:"",
    prevText:"",
    numberOfMonths:1,

    changeMonth: false,
    onSelect: function( selectedDate ) {
        var option = this.id == "checkin" ? "minDate" : "maxDate",
        instance = $( this ).data( "datepicker" ),
        date = $.datepicker.parseDate(
        instance.settings.dateFormat ||
        $.datepicker._defaults.dateFormat,
        selectedDate, instance.settings );

        dates.not( this ).datepicker( "option", option, date );
        var i=$.datepicker._defaults.dateFormat;
        j=$.datepicker.parseDate(i,$("#checkin").val());
        l=$.datepicker.parseDate(i,$("#checkout").val());
    },
    onClose: function(){
        $('#book_it_button').attr({'disabled':'disabled'});
        $('#subtotal').html('');
        $('#show_more_subtotal_info').css({'display':'none'});
        $('#book_it_disabled').css({'display':'none'});
        $('#book_it_enabled').css({'display':'block'});
        if(this.id== "checkin") {
            var theDate = new Date($(this).datepicker('getDate'));
            // this sets "theDate" 1 day forward of start date
            theDate.setDate(theDate.getDate() + 1);
            // set min date for the end date as one day after start date
            $('#checkout').datepicker('option','minDate',theDate);
        }
        subTotal();
    }
});
});

Input for the book_it_button
   <button type="submit" class="button-glossy green" id="book_it_button" disabled="disabled">

Javascript for other submit
       <script type="text/javascript">
  $(function () {
    $('form').on('submit', function (e) {
      $.ajax({
        type: 'post',
        url: 'post.php',
        data: $('form').serialize(),
        success: function () {
          alert('form was submitted');
        }
      });
      e.preventDefault();
    });
  });
</script>

A: Put each submit button and the relevant fields inside it's own  section.


text:
Q: If I have used "On the one hand", do I need to write "on the other hand" somewhere after? I am an English learner in mainland China. I have a question regarding the structure "On the one hand... On the other hand" and would really appreciate it if anyone can elucidate this point.
Please mind that I already know from other posts that "On the other hand" can be used independently without a previous "On the one hand".
My question is: if I have already used "on the one hand", do I have to use "on the other hand" later? Or is it okay to use "on the one hand" followed by contrasting phrases like "by contrast"?

A: The usual construction in the English (or any similar) language would be:
On the one hand... On the other [hand]... — Cambridge Dict.

"On the one hand I'd like a job that pays more, but on the other hand I enjoy the work I'm doing at the moment."

Sometimes, we do not explicitly state "on the one hand", but it is often assumed.
The following Google Ngram shows that "on the other hand" is used more frequently than "on the one hand".

On the other hand, using "on the one hand" without "on the other hand" will sound odd, or illogical, to a native speaker at least. There may not be any rules regarding this other than general usage trends.


text:
Q: Get child item view of recyclerView in api 19 After searching about how to access child of recyclerview in a fragment I found below code:
    recyclerViewMenuItems.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            new Handler().postDelayed(() -> addNewVenueItem = recyclerViewMenuItems.findViewHolderForLayoutPosition(2).itemView.findViewById(R.id.textViewMenuItem), 50);
            recyclerViewMenuItems.getViewTreeObserver().removeOnGlobalLayoutListener(this);
        }
    });

so, this part of code work correctly, BUT!
the problem is when i want to find another child, I use this code :
    recyclerViewMenuItems.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            new Handler().postDelayed(() -> addNewVenueItem = recyclerViewMenuItems.findViewHolderForLayoutPosition(2).itemView.findViewById(R.id.textViewMenuItem), 50);
            recyclerViewMenuItems.getViewTreeObserver().removeOnGlobalLayoutListener(this);

            new Handler().postDelayed(() -> storeItem = recyclerViewMenuItems.findViewHolderForLayoutPosition(7).itemView.findViewById(R.id.textViewMenuItem), 50);
            recyclerViewMenuItems.getViewTreeObserver().removeOnGlobalLayoutListener(this);

        }
    });

every things is OK in android api level 26, But in api 19 device storeItem that is second view to find it, returns null!
how can I access to childs view of recyclerview (not only on child, more than one child view is the question)


text:
Q: Limitation of number of sum() in a query in MySQL 8? I recently installed MySQL 8 and found out that some queries no longer run. The error is:
SQL Error (1022): Can't write; duplicate key in table 'C:\WINDOWS\SERVIC~1\NETWOR~1\AppData\Local\Temp\#sql2db8_13_26'
There were no issues with MySQL 5.7 or older versions.
All my research in forums showed that this usually happens in case of foreign keys and constraints. I don't have any, just Primary key and 2 indexes.
My query produces 843 columns with KPIs all of which are aggregated with sum(). What made me impression is that if I remove approx 2/3 of the query content the query runs normally without any errors. Also if I remove group by or all of sums there are no issues either.
So I am wondering whether there is any new limatitaion of number of aggregate operators in MySQL 8.0.
A simplified example of my query is below. Table is running MyISAM.
select Time,eNodeB,
round((sum(`L.E-RAB.SuccEst.QCI.1`)/sum(`L.E-RAB.AttEst.QCI.1`))*100,3) as RAB_Est_SR,
sum(`L.E-RAB.AttEst.QCI.1`) as RAB_Est_att,
...
from h_cell
where enodeb='10006' and time>='2018-01-01'
group by time

A: No! there is no limitation. As your error message said, you have duplicate key for grouping. This means your usage of GROUP BY is not true! You must use every column (Except scalar ones) in front of select in GROUP clause.
So, you must change your query to:
select Time,eNodeB,
round((sum(`L.E-RAB.SuccEst.QCI.1`)/sum(`L.E-RAB.AttEst.QCI.1`))*100,3) as RAB_Est_SR,
sum(`L.E-RAB.AttEst.QCI.1`) as RAB_Est_att,
...
from h_cell
where enodeb='10006' and time>='2018-01-01'
group by time,eNodeB


text:
Q: GpsStatus.Listener registers only if GPS is on I have a widget that displays the current user location using a LocationManager. i conserve battery by disabling a local broadcast manager for location updates through a system broadcast manager that indicates if the screen is on or off. To accompany the battery saving effort, i am trying to implement a GpsStatus.Listener to tell me if the gps has been turned on or off so i can use it in my locationmanager. Everything works perfectly if i load the widget ONLY IF THE GPS IS ON. The GpsStatus.Listener fails to fire if the widget is loaded when the GPS IS OFF. Obviously there is an imperefct workaround (load with gps on) but i am curious and ask why the listener doesn't work if the gps is off at runtime. I am using os 4.0.3 and my manifest includes fine location. ta.
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
                     int[] appWidgetIds)
{
    // Get all ids
    thisWidget = new ComponentName(context, MyWidgetProvider.class);
    this.appWidgetManager = appWidgetManager;
    int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);

    remoteViews = new RemoteViews(context.getPackageName(), R.layout.main);
    remoteViews.setTextViewText(R.id.update, "running......");
    appWidgetManager.updateAppWidget(thisWidget, remoteViews);

    ServicesManager = new MyLocationManager(context);
    streetAddress = new CellAddress(context, ServicesManager);
    ServicesManager.lm.addGpsStatusListener(myGPSListener);

    filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
    filter.addAction(Intent.ACTION_SCREEN_OFF);
    context.getApplicationContext().registerReceiver(mReceiver, filter);

    LocalBroadcastManager.getInstance(context).registerReceiver(receiveUpdatedLocation,
            new IntentFilter("sendUpdatedLocation"));

    if (!(ServicesManager.isInternet()))
    {
        remoteViews.setTextViewText(R.id.update, "Address not available" + "\n\n" +
                                    "Check data connection....");
        appWidgetManager.updateAppWidget(thisWidget, remoteViews);
    }
    else
    {
        remoteViews.setTextViewText(R.id.update, streetAddress.address$);
        appWidgetManager.updateAppWidget(thisWidget, remoteViews);
    }

    Log.d(TAG, "onUpdate");
}

GpsStatus.Listener myGPSListener = new GpsStatus.Listener()
{

    public void onGpsStatusChanged(int event)
    {
        if(event == GpsStatus.GPS_EVENT_STARTED)
        {
        Log.d(TAG, "GPS Started");
        } else if(event == GpsStatus.GPS_EVENT_STOPPED) {
        Log.d(TAG, "GPS Stopped");
        }
    }

};


text:
Q: Efficiently refactoring piece of Swift code to be less redundant In the code below, A key is remapped to B key, and vice versa. The remapping is activated via a SwiftUI toggle switch.

In example presented here the same block of code is used in three different functions.
Additionally, the loop that iterates through the function call is also used in all three of these functions.
I've been struggling to simplify this code and make it less redundant for more than a day. Any help would be greatly appreciated.

let aKey: UInt64 = 0x700000004
let bKey: UInt64 = 0x700000005

func isKeyboardServiceClientForUsagePage(_ serviceClient: IOHIDServiceClient, _ usagePage: UInt32, _ usage: UInt32) -> Bool {
    return IOHIDServiceClientConformsTo(serviceClient, usagePage, usage) == 1
}

func updateKeyboardKeyMapping(_ keyMap: [[String: UInt64]]) {
    let eventSystemClient = IOHIDEventSystemClientCreateSimpleClient(kCFAllocatorDefault)

    guard let serviceClients = IOHIDEventSystemClientCopyServices(eventSystemClient) as? [IOHIDServiceClient] else {
        return
    }

    for serviceClient in serviceClients {
        let usagePage = UInt32(kHIDPage_GenericDesktop)
        let usage = UInt32(kHIDUsage_GD_Keyboard)

        if isKeyboardServiceClientForUsagePage(serviceClient, usagePage, usage) {
            IOHIDServiceClientSetProperty(serviceClient, kIOHIDUserKeyUsageMapKey as CFString, keyMap as CFArray)
        }
    }
}

func areKeysMappedOnAnyServiceClient() -> Bool {
    let eventSystemClient = IOHIDEventSystemClientCreateSimpleClient(kCFAllocatorDefault)

    guard let serviceClients = IOHIDEventSystemClientCopyServices(eventSystemClient) as? [IOHIDServiceClient] else {
        return false
    }

    for serviceClient in serviceClients {
        let usagePage = UInt32(kHIDPage_GenericDesktop)
        let usage = UInt32(kHIDUsage_GD_Keyboard)

        if isKeyboardServiceClientForUsagePage(serviceClient, usagePage, usage) {
            guard let keyMapping = IOHIDServiceClientCopyProperty(serviceClient, kIOHIDUserKeyUsageMapKey as CFString) as? [[String: UInt64]] else {
                return false
            }

            if keyMapping.contains(where: { $0[kIOHIDKeyboardModifierMappingSrcKey] == aKey && $0[kIOHIDKeyboardModifierMappingDstKey] == bKey }) &&
                keyMapping.contains(where: { $0[kIOHIDKeyboardModifierMappingSrcKey] == bKey && $0[kIOHIDKeyboardModifierMappingDstKey] == aKey })
            {
                return true
            }
        }
    }

    return false
}

func remapABBA() {
    let keyMap: [[String: UInt64]] = [
        [
            kIOHIDKeyboardModifierMappingSrcKey: aKey,
            kIOHIDKeyboardModifierMappingDstKey: bKey,
        ],
        [
            kIOHIDKeyboardModifierMappingSrcKey: bKey,
            kIOHIDKeyboardModifierMappingDstKey: aKey,
        ],
    ]

    updateKeyboardKeyMapping(keyMap)
}

func resetKeyMapping() {
    updateKeyboardKeyMapping([])
}

And here's the SwiftUI part if you would like to try the app:
import SwiftUI

struct ContentView: View {
    @State private var remapKeys = areKeysMappedOnAnyServiceClient()

    var body: some View {
        HStack {
            Spacer()
            Toggle(isOn: $remapKeys, label: { Text("Remap A → B and B → A.") })
                .toggleStyle(SwitchToggleStyle())
                .onChange(of: remapKeys, perform: toggleKeyboardRemapping)
            Spacer()
        }
    }
}

private func toggleKeyboardRemapping(_ remapKeys: Bool) {
    if remapKeys {
        remapABBA()
    } else {
        resetKeyMapping()
    }
}

A: OK... this is going to take some time to answer.
It seems like you're lacking in a place to store things. That's why you have to use the same block of code over and over. We can solve that with a view model...
In here I'm going to hide away the logic of what is happening from the view and only expose what the view needs access to in order to display itself.
// we make it observable so the view can subscribe to it.
class KeyMappingViewModel: ObservableObject {
  private let aKey: UInt64 = 0x700000004
  private let bKey: UInt64 = 0x700000005

  private let srcKey = kIOHIDKeyboardModifierMappingSrcKey
  private let dstKey = kIOHIDKeyboardModifierMappingDstKey

  private var keyMap: [[String: UInt64]] {
    [
      [
        srcKey: aKey,
        dstKey: bKey,
      ],
      [
        srcKey: bKey,
        dstKey: aKey,
      ],
    ]
  }

  // A more concise way to get hold of the client ref
  private var client: IOHIDEventSystemClientRef {
    IOHIDEventSystemClientCreateSimpleClient(kCFAllocatorDefault)
  }

  // Making this published means the view can use it as state in the Toggle
  @Published var toggleState: Bool {
    didSet {
      if toggleState {
        client.updateKeyMapping(keyMap)
      } else {
        client.updateKeyMapping([])
      }
    }
  }

  init() {
    // set the initial value by asking the client if it has any keys mapped
    toggleState = client.areKeysMappedOnAnyServiceClient(aKey: aKey, bKey: bKey)
  }
}

I'm going to make extensions of IOHIDServiceClient and IOHIDEventSystemClientRef to encapsulate your logic...
extension IOHIDEventSystemClientRef {
  private var srcKey: String { kIOHIDKeyboardModifierMappingSrcKey }
  private var dstKey: String { kIOHIDKeyboardModifierMappingDstKey }

  // Make this an optional var on the client ref itself.
  private var serviceClients: [IOHIDServiceClient]? {
    IOHIDEventSystemClientCopyServices(self) as? [IOHIDServiceClient]
  }

  func areKeysMappedOnAnyServiceClient(aKey: UInt64, bKey: UInt64) -> Bool {
    // Nice Swift 5.7 syntax with the optional var
    guard let serviceClients else {
      return false
    }
    // I made this more concise with a filter and map.
    // Also, using the extension we can make use of keyPaths to get the values.
    return serviceClients.filter(\.isForGDKeyboard)
      .compactMap(\.keyMapping)
      .map { keyMapping in
        keyMapping.contains(where: { $0[srcKey] == aKey && $0[dstKey] == bKey }) &&
        keyMapping.contains(where: { $0[srcKey] == bKey && $0[dstKey] == aKey })
      }
      .contains(true)
  }

  func updateKeyMapping(_ keyMap: [[String: UInt64]]) {
    // serviceClients is optional so we can just ? it.
    // if it's nil, nothing after the ? happens.
    serviceClients?.filter(\.isForGDKeyboard)
      .forEach {
        IOHIDServiceClientSetProperty($0, kIOHIDUserKeyUsageMapKey as CFString, keyMap as CFArray)
      }
  }
}

extension IOHIDServiceClient {
  var isForGDKeyboard: Bool {
    let usagePage = UInt32(kHIDPage_GenericDesktop)
    let usage = UInt32(kHIDUsage_GD_Keyboard)
    return IOHIDServiceClientConformsTo(self, usagePage, usage) == 1
  }

  var keyMapping: [[String: UInt64]]? {
    IOHIDServiceClientCopyProperty(self, kIOHIDUserKeyUsageMapKey as CFString) as? [[String: UInt64]]
  }
}

Doing all of this means that your view can look something like this...
import SwiftUI

struct ContentView: View {
  @ObservedObject var viewModel: KeyMappingViewModel = .init()

  var body: some View {
    HStack {
      Spacer()
      Toggle(isOn: $viewModel.toggleState) {
        Text("Remap A → B and B → A.")
      }
      .toggleStyle(SwitchToggleStyle())
      Spacer()
    }
  }
}

This contains all your same logic and TBH wasn't too bad already.
My main changes were to take the free functions and vars and add them to their respective types.
So, the update and areKeysMapped... functions now belong to the IOHIDEventSystemClientRef type.
The isForGDKeyboard and keyMapping vars now belong to the IOHIDServiceClient type.
Doing this removed a lot of the repeated code you had as you no longer had to continuously call free functions. It also meant we unlocked some very Swifty keyPath usage which helped make some of the logic more concise.
Then we made a view model. This allowed us to keep all the moving parts of the view in one place. It had a place to easily get hold of the client. It also meant we could hide a lot of the stuff inside the view model by making it private.
This meant that the view only had one thing it could do. Which is to use the binding to the toggleState. Everything else was behind closed doors to the view.


text:
Q: How to know what variant expl3 functions to provide in a package? This question stems from a bug report to my package, pdfoverlay.
The function in question is:
\cs_new_protected:Nn \pdfoverlay_set_pdf:n
  {
    \file_if_exist:nTF { #1 }
      {
        \str_gset:Nn \g__pdfoverlay_pdf_file_name_str { #1 }
        \__pdfoverlay_count_pdf_pages:
        \int_gzero:N \g__pdfoverlay_page_int
        \bool_gset_true:N \g__pdfoverlay_output_active_bool
        \bool_gset_false:N \g__pdfoverlay_action_pending_bool
      }
      {
        \msg_error:nnn { pdfoverlay } { file-not-found } { #1 }
      }
  }

This works fine provided you pass a PDF filename directly to the macro. But if you store the PDF filename in a macro, it fails, because str_gset:Nn just detokenizes the control sequence.
Generating variants of \pdfoverlay_set_pdf:n (e.g., V or o or x) works around this.
Questions

*

*Should a style file provide these variants in this kind of case? Or Should they be left for a user to generate if they need them?

*There's a LaTeX interface (\pdfoverlaySetPDF) which calls \pdfoverlay_set_pdf:n. There always seems to be risks (which I don't adequately understand) in forcing things to expand. But would there be a problem with creating a variety of variants and then calling \pdfoverlay_set_pdf:x from the LaTeX interface?


text:
Q: Can sys.argv handle optional arguments? from sys import argv
script, lira_cbt, [eur_hedge] = argv

if eur_hedge == None:
    #Do x
else:
    #Do y

I want it to be able to run with just lira_cbt as an argument (doing x), or with both lira_cbt and eur_hedge (doing y). Can this be achieved with sys.argv?

A: If this is to be part of more than a throw-away script, consider using argparse http://docs.python.org/library/argparse.html
At the moment it will be much more complicated, but it will help you keep documented the options your program accepts and also provide useful error messages unlike a
"too many values to unpack" that the user might not understand.

A: Just use the length of sys.argv
if len(sys.argv) == 2:
  # do X
else:
  # do Y

A: Another option is to extract the values from the argv list using try:
lira_cbt = sys.argv[1]
try:
  eur_hedge = sys.argv[2]
except IndexError:
  eur_hedge = None

if eur_hedge == None:
    # Do X
else:
    # Do Y

You could also take a look at getopt for a more flexible parser of command line arguments.

A: You can simply check the length of sys.argv.
if len(sys.argv) < 2:
    # Error, not enough arguments

lira_cbt = sys.argv[1]
if len(sys.argv) == 2:
    # Do X
else:
    eur_hedge = sys.argv[2]
    # Do Y

A: If I may suggest an alternative approach:
from sys import argv
option_handle_list = ['--script', '--lira_cbt', '--eur_hedge']
options = {}
for option_handle in option_handle_list:
    options[option_handle[2:]] = argv[argv.index(option_handle) + 1] if option_handle in argv else None
if options['eur_hedge'] == None:
    #Do x
else:
    #Do y

A: Here is a simple example that tries to read the argv1 input but does something else if one isn't provided.
from sys import argv

try:
    x = argv[1]
    print("x" + " Was given as an argument")
except:
    print("No Input Provided")

Console Output


text:
Q: Docusign rate limit to receive documents in 1 envelope I am trying to switch to the production API of Docusign. When I submit the required 20 envelopes for approval they do not get approved. I recieved a log file that lists multiple GET requests. It violates the API rules, only one GET request per envelope per 15 minutes is allowed according to the documentation. (https://developers.docusign.com/esign-rest-api/guides/resource-limits)
When I list my envelope and loop through the envelope multiple times to get the documents out of it. I do multiple GET requests to the same envelope and that's why I think I get a rate limit error.
In the example below, you can see that when I retrieve the envelope, I immediately loop over the documents inside the envelope and get the documents with the getDucument method as described in the documentation. (https://developers.docusign.com/esign-rest-api/code-examples/get-an-envelope-document-list)
public function getEnvelopeDocument ($envelopeId)
    {
        $documents = $this->envelopeApi->listDocuments(config('docusign.id'), $envelopeId);
        try {
            foreach($documents->getEnvelopeDocuments() as $document)
            {
                $docs[] =  $this->envelopeApi->getDocument((config('docusign.id')), $document->getDocumentId(), $envelopeId);
            }
        } catch (ApiException $e){
            dd("Error connecting Docusign : " . $e->getResponseBody()->errorCode . " " . $e->getResponseBody()->message);
        }
    }

Am I violating the API rate limiter? If so, what would be the allowed way to retrieve documents inside an envelope.

A: My interpretation of the code is that you are performing the following calls in sequence:
GET /envelopes/{envelopeId}/documents - ListDocuments
GET /envelopes/{envelopeId}/documents/1 - get document 1
GET /envelopes/{envelopeId}/documents/2 - get document 2
and so on.
If this is the case, you are not in violation of the API limit. If you were to make two calls to the ListDocuments or to one of the individual documents within 15 minutes that would be a polling violation.
To confirm everything is acceptable, you might capture API logs to confirm you're hitting each unique endpoint only once. Info on API logs is available here: https://support.docusign.com/guides/ndse-user-guide-api-request-logging


text:
Q: Uncaught (in promise) SyntaxError: Unexpected token T in JSON at position 0 When I try send an array of data to the frontend, it works fine, but when I try to send a sample text to the frontend from the server, getting the error Unexpected token T in JSON at position 0. I am getting this error on console.log(data).
fetch("/something", {
    method: "POST",
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify(data)
  }).then(function (response) {
    // The API call was successful!
    console.log(response);
    return response.json();
  }).then(function (data) {
    // This is the JSON from our response
    console.log(data);

  });

router.post('/something', () => {
  console.log(req.body);
    res.send('This is sample');
});

A: This is because res.send() automatically sets the Content-Type response header as well based on the argument passed to the send() method. In your case, send() is not detecting a json object as an argument. So, the content type is not json in the response header.
You could use res.json() method to send the string as json.
router.post('/something', () => {
  console.log(req.body);
    res.json('This is sample');
});

Or, pass a javascript object to res.send() and it would automatically convert it into json.
router.post('/something', () => {
  console.log(req.body);
    res.send({data: 'This is sample'});
});

Note: res.json() uses res.send() under the hood. Read this article to understand the difference between the two methods.


text:
Q: unable to resolve dns after enable ipf I running on Solaris 10 platform.
Before I enable IPF, I able to ping and traceroute to yahoo.com
After I enabled the IPf, I could not ping nor traceroute to yahoo.com
However when I ping to IP 69.147.114.224 (one of yahoo resolved IP) directly, it gives me response.
It seem to be that IPF block the DNS resolvability.
How could I solve it?

A: Add a firewall rule to allow UDP and TCP traffic on port 53.

A: Add the pass out rule:
pass out quick from any to any keep state


text:
Q: I've answered my own bounty question, and days later someone provided a duplicate answer, and the bounty goes to him? I offered a bounty on this question that I asked last year.
I have provided the answer with working code, and days later someone else provided a "duplicate" answer without code.
Currently the highest voted "duplicated" answer is borrowed from existing comments and answers, and more importantly does not even contain a code example.
Because the bounty can't go back to the poster, now the bounty goes to him.
I feel this is not fair.

A: At the time of me answering this question, the "duplicate" answer you are talking about has a score of 1, and if it doesn't reach a score of at least 2 at the end of the grace period, the answer will not receive the bounty (see How does the bounty system work?).
However, the answer can't be called a duplicate because it is not a copy-paste of an already existing answer. Even though it may have borrowed ideas from your answer, it has details not present in your answer and is a new answer in all rights.
But, if you ever step upon an answer which you think is a duplicate, flag it as in need of moderator intervention explaining your reason, and it would be removed if it is genuinely a duplicate. Also, the community is at work at all times, and if such answers are present, then they would be downvoted a lot. So, I don't think that a change of rule is required.


text:
Q: Error during install via USB: Initramfs unpacking failed: decoding failed I'm in the process of dual booting the latest Ubuntu LTS release alongside my pre-existing Windows 10 install. I'm having a weird error when installing via USB: Initramfs unpacking failed: decoding failed. I have been searching the web and have tried all manner of troubleshooting steps from others with the same error but nothing seems to fix it.
A picture of the error along with some graphical artefacts (the morse-esque dots look like they're meant to be more text). Down the bottom there are also some circles half cut off by the bottom of the monitor, although they're not captured here.

I have tried:

*

*Disabling secure boot

*Disabling virtualisation support

*Removing any CPU/RAM overclocks

*Making sure SATA mode is AHCI

*Changing USB sticks

*Changing from USB 3 ports to USB 2 ports

*Making sure BitLocker is not enabled (for any drives)

*Using Rufus to write in both ISO and DD mode

*Changing Rufus' 'Partition scheme' setting from MBR to GPT

*Making sure CSM is disabled

*Making sure I'm booting in UEFI mode

*Checksum on the ISO

None of this has done anything. In fact, in some cases I get different errors - some MCE's complaining about the CPU - although now I can't seem to get it to do this again. As far as I'm aware there are no hardware issues though as I can boot into and use the Win 10 install just fine.
Lots of forum posts talk about changing the decompression settings in an initramfs config file but as I am installing and can't actually get into the OS yet I can't do this can I? This seems like a step to help those who are encountering this after a full install.
Specs:

*

*MOBO: ASUS ROG Strix X570-F Gaming

*CPU: AMD Ryzen 9 3950x

*GPU: ROG Strix 2080ti

*RAM: 32GB DDR4 Corsair Vengeance

*PSU: Corsair 750W TXm Series


text:
Q: Is there an elegant way to check if index can be requested in a numpy array? I am looking for an elegant way to check if a given index is inside a numpy array (for example for BFS algorithms on a grid).
The following code does what I want:
import numpy as np

def isValid(np_shape: tuple, index: tuple):
    if min(index) < 0:
        return False
    for ind,sh in zip(index,np_shape):
        if ind >= sh:
            return False
    return True

arr = np.zeros((3,5))
print(isValid(arr.shape,(0,0))) # True
print(isValid(arr.shape,(2,4))) # True
print(isValid(arr.shape,(4,4))) # False

But I'd prefer something build-in or more elegant than writing my own function including python for-loops (yikes)

A: You can try:
def isValid(np_shape: tuple, index: tuple):
    index = np.array(index)
    return (index >= 0).all() and (index < arr.shape).all()

arr = np.zeros((3,5))
print(isValid(arr.shape,(0,0))) # True
print(isValid(arr.shape,(2,4))) # True
print(isValid(arr.shape,(4,4))) # False

A: I have benchmarked the answers quite a bit, and come to the conclusion that actually the explicit for loop as provided in my code performs best.
Dmitri's solution is wrong for several reasons (tuple1 < tuple2 just compares the first value; ideas like np.all(ni < sh for ind,sh in zip(index,np_shape)) fail as the input to all returns a generator, not a list etc).
@mozway's solution is correct, but all the casts make it a lot slower. Also it always needs to consider all numbers for casting, while an explicit loop can stop earlier, I suppose.
Here is my benchmark (Method 0 is @mozway's solution, Method 1 is my solution):


text:
Q: lsof +d doesn't work properly on live CD mkdir testdir
cat > testdir/whatever

when running from live CD (Ubuntu)
lsof +d testdir shows nothing while cat is still running
Does it have something to do with overlay fs?
Can the behaviour be fixed with some parameter?


text:
Q: If max value exists in nested dictionary, print another value in same dictionary Am new to python and have a nested dictionary from a CSV that looks like this:
data = {
         {object: a, type: 1, value: 1.50, another_value: 2}
         {object: b, type: 1, value: 3.67, another_value: 4}
       }

I am trying print data from different columns if a value exists. First, I want to find the max number in all entries in the 'value' column. Then I want to print the 'object' if that max value exists within that dictionary.
So in this instance I want my output to look like:
print('Max value is 3.67 which is found in object b)

I've managed this far:
data = {see above}
max_list[]

for row in data:
    values = float(row['value'])
    max_list.append(values)

max_value = max(max_list)

if max_value in data
    max_object = data(['object'])

print('Max value: {} which is found in object {}'.format(max_value, max_object))

Any help would be appreciated! Thanks!

A: Assuming that you made a mistake there
data = [
    {"object": "a", "type": 1, "value": 1.50, "another_value": 2},
    {"object": "b", "type": 1, "value": 3.67, "another_value": 4},
    {"object": "c", "type": 2, "value": 3.50, "another_value": 6},
]

sorted_data = sorted(data, key=lambda k: k['value'])
maxx = sorted_data[-1]
print('Max value: {} which is found in object {}'.format(maxx['value'], maxx['object']))


text:
Q: How to send data from exacttarget to sfdc using v5 connector I am using v5 connector to integrate salesforce and exacttarget.
How can I send exacttarget data back to salesforce.
Thanks

A: What kind of data are we talking about? Reporting data on email sends will automatically be sent back to Salesforce anytime you send an email to a Salesforce Report or Campaign. Unsubscribes and Profile Centers (assuming you are using the default) are configured to automatically update fields in Salesforce too.
If you are looking for a two-way synchronization of data, that unfortunately doesn't really exist. There is the ability to import objects from Salesforce into the Marketing Cloud, either through an Import Interaction or the new Data Stream features in Contact Builder, but the communication form those is strictly one-way (Salesforce into Marketing Cloud).
If you wanted to move subscriber information back to Salesforce you would have to do an export to your FTP, and then re-upload in Salesforce. This process can be automated in Automation Studio.
Hope that helps!


text:
Q: Strange Windows/Python/Popen Issue When I run the following:
import subprocess
subprocess.check_call('dir', shell=True)

The result always shows me the contents of C:\, no matter what directory I started the Python interpreter in.  I even tried this:
import subprocess
subprocess.check_call('dir', shell=True, cwd='C:\\foo\\bar\\baz')

and that doesn't work either.  I'm also having trouble building an application using Scons (Python-based build tool),  for what appears to be the same reason:
scons: Building targets ...
cl /Fobuild\Animation.obj /c src\Animation.cpp /TP /DSFML_STATIC /EHsc /MD /Zi /Ideps/Box2D_v2.2.1 / Ideps/LuaJIT-2.0.2/src /Ideps/SFML-2.0/include /Ideps/include /nologo
Animation.cpp
c1xx : fatal error C1083: Cannot open source file: 'src\Animation.cpp': No such file or directory
scons: * [build\Animation.obj] Error 2
scons: building terminated because of errors.

Note that src\Animation.cpp actually does exist.  I assume this happens b/c cl.exe is running from C:\ instead of the actual location where the Python interpreter is running from.
I thought this might be a problem with my environment variables, but I checked them and everything seems OK.  I also removed/reinstalled Python, to no avail.
What's going on here?

A: You should escape '\' or use raw string (r'....').
>>> 'C:\foo\bar\baz'
'C:\x0coo\x08ar\x08az'
>>> r'C:\foo\bar\baz'
'C:\\foo\\bar\\baz'

A: Fixed it!  Problem was the AutoRun setting in the registry...not sure how that got set, but it was.  To resolve this, go to:

HKEY_CURRENT_USER\Software\Microsoft\Command Processor

In the registry, and delete the AutoRun setting.  My AutoRun looked like this:

cd C:\

Which was completely screwing everything up.


text:
Q: How can I tell (or prove) packets are being dropped by my router or my ISP? I have a Hitron router that was provided by my ISP, and I have it configured to forward ports to devices on my LAN. I used to be able to access machines on the LAN from machines on the LAN by way of WAN IP of the router. For example
curl https://$(curl icanhazip.com)

would, in fact, make an HTTPS connection assuming I had a server listening behind the router.
Example:
client (192.168.0.42) ---> router (192.168.0.1) ---> dns for me.example.com, returns my WAN IP - same thing curl icanhazip.com returns. Example 203.0.113.42
client (source:192.168.0.42, dest:203.0.113.42:443) ---> nothing. Hangs forever. Or until timeout.

That used to work just fine.
Now I can only access the router via my gateway of 192.168.0.1, but that only goes directly to the router, not to any of the machines behind it. If I want to connect to a server on the LAN I have to use the IP directly.
But the weird thing is that if I'm not connected to my wifi - literally any other network - then I can connect to my external IP and the traffic is correctly forwarded.
client(source: 192.0.2.42, dest: 203.0.113.42:443) ---> router ---> web server (192.168.0.42)

Is it possible to figure out where my packets are getting dropped? I've looked around for any kind of information in the router itself, but no dice. I also reached out to my ISP on Twitter, but they also weren't much help. I've used ping & traceroute - either attempts to connect to the routers public IP fail. I've also spun up wireshark, and can see the ping packets go out and other traffic attempts, but I'm not familiar enough with it to know if there's a way to use it to say, "Ah yes, these packets are definitely getting dropped at X". I've also completely disabled the firewall at the router level, as well as mucked with any setting that looked remotely promising (even screwing up my router bad enough to have to do a hard reset on it, I think that was configuring the IP passthru).
Is it possible for me to verify that the packets are either getting dropped by my router, or getting dropped at the ISP level? And if so, how would I do that?
EDIT
For further fun and excitement, apparently this only applies to lower ports. I don't know what the exact range is, but it appears that higher ports still allow connections.

A: It sounds like the problem is incorrectly configured hairpin NAT, which is something some SOHO routers automatically configure correctly and in others that requires specific routing and NAT rules.
https://serverfault.com/a/557776


text:
Q: This helps to understand something Should it be

This helps understand something

Or

This helps to understand something

Note that it is not

This helps us understand something,

although this is what I want to express.


text:
Q: Numbers whose digits sum to 7 Let $S$ be the sequence of all positive integers whose decimal digits add to exactly 7, in increasing order:
$$S = \langle7, 16, 25, \ldots, 70, 106, 115, 124, \ldots 160, 205, \ldots, 10230010, \ldots\rangle$$
What is an efficient algorithm for finding the $n$th element of this sequence for a given positive integer $n$?

A: You can solve this by doing a binary search on the number of elements in the sequence below some number $M$.
To count how many numbers there are $\le M$ we must find a way to construct the numbers. The idea is the following: Go through each prefix of $M$, and assume that the next digit is less than the corresponding digit of $M$. Then the remaining digits $d_k,\dots,d_n$ can be set freely with a constraint of the form $d_k + \dots + d_n = l$, where $l$ is what is left of $7$ after subtracting the first digits. This is a standard counting problem.

A: A good point to start is to quickly determine the number of such numbers below certain "mielstone" limits.
Using the usual stars and bars argument, there are $m+7\choose 7$ such numbers below $10^m$.
And more generally, if $a$ is any number with digitsum $ s\le 7$, then there are $m+7-s\choose 7-s$ such numbers $x$ with $a\cdot 10^m\le x<(a+1)\cdot 10^m$. These facts allow you to find rather quickly suitable estimates that converge to the desired result.

A: Observation: after $7,000,000$, all subsequent numbers from this list will be formed by sequentially inserting $0$'s into the $7$ digit numbers in the list (since after $1,111,111$, there can be no "new" combinations). As such, if we can formulate the sequence up to $7,000,000$, we'll be done in general.
Aim: to efficiently calculate the sequence up to $7,000,000$, at which point all future terms depend on previous terms. In doing so, generate a list of all 7 digit combinations, which will become the "base" for all further terms.
The method:

*

*Take the multiples of $7$ in base $10$.

*Translate these into base $8$. This will give you every number which, when viewed in base $10$, has digits which sum to 7 in order, plus some extras, whose digits sum to multiples of 7.

*Manually remove these extras up to $7,000,000$ (still thinking of a better way, but this isn't so inefficient for this value).

*Subsequent terms in the sequence are obtained by sequentially adding $0$'s to previous values.

Some more detail:
In base $10$, the trick for working out if a number is divisible by $9$ is if and only if the sum of the digits is a multiple of $9$. The proof for this is slightly enlightening:
$$a_na_{n-1}\ldots a_0 = \sum_{i=0}^na_i10^i\equiv \sum_{i=0}^na_i\mod9$$ as $10\equiv 1 \mod 9$. What's important here is that $10 = 9+1$. The same thing will work in base $8$ with multiples of $7$

When we translate the multiples of $7$ into base $8$, we get:
$$7\mapsto7\\14\mapsto16\\21\mapsto 25\\28\mapsto34\\35\mapsto43\\\vdots$$
In base $8$ the multiples of $7$ are exactly the numbers whose digits sum to a multiple of $7$ in numerical order. If we then interpret the numbers we get as if they were in base $10$, we will get an almost one-to-one correspondence with the base $10$ integers whose digit sum to $7$.
Now this will also include numbers whose digits sum to $14, 21, \ldots$.

A: Let me try answering it a fun way...
base 10 will use 9x-2 to make a set like (7, 16, 24,...100000000006)
Now what numbers do we need to ignore? Those that sum greater than 7...now there's a trick to only get these numbers from the set above in programming....
when you hit a number that sums over 7 using the above series you take the number, find the last digit with a number in it, subtract 1 and move it to the end, and add 1 to the digit after...
So for 70 since 7 is the last digit we subtract 1 to make 6, move that to the end (06) and add a 1 to the digit after 7 (106) to get the next number in the series...
160 would jump to 205 (6-1=5, add 1 after)
250 will be 304
340 will be 403
430 will be 502
520 will be 601
610 will be 700
700 will be 1006
1,060 will be 1,105
...
10,600,000 will be 11,000,005
so you could do something like this...
input n
ans=7
n=n-1
do until n=0
   Ans=Ans+9
   If sum(eachnuminans)>7
       Ans=Ans-9
       Pos=Find(first nonzero location)
       X=ans(pos)
       Ans(pos)=0
       Ans(pos+1)=ans(pos+1)+1
       Ans(1)=X-1
   Loop
   n=n-1
Loop


text:
Q: Can an existentially quantified formula be a tautology I was wondering if a formula of the form $\exists xP(x)$, where $P(x)$ is any formula, can be a tautology. To me the domain could be empty, and therefore it is not satisfiable in every structure. But from an intuitive standpoint this is hard to grasp, especially if there are several quantifiers nested and implications involved, where the antecedent might then be false.

A: Ultimately this depends on exactly what semantics we use. Most presentations of first-order logic do not allow the domain to be empty; consequently, sentences like "$\exists x(x=x)$" are tautologies. On the other hand, if we do allow the empty domain, then no sentence of the form "$\exists xP$" can be a tautology since such a sentence cannot hold in the empty structure (similarly, no sentence of the form "$\forall x P$" can be a contradiction since such a sentence cannot fail in the empty structure).


text:
Q: Is there a way to preserve recursive children order with Normalizr? I am retrieving a sorted array of comments from the server. Each comment has a comment.children attribute that is also a sorted array of other comments. These can be nested n deep. E.g:
const nestedComments = [
  {
    id: 1,
    body: "parent comment",
    children: [
        {
          id: 4,
          body: 'child comment',
          children: [
            {
              id: 7,
              body: 'grandchild comment #1',
              children: [],
            },
            {
              id: 6,
              body: 'grandchild comment #2',
              children: [],
            },
            {
              id: 5,
              body: 'grandchild comment #3',
              children: [],
            },
          ]
        },
        {
          id: 3,
          body: 'second child comment',
          children: []
        }
    ],
  },
  {
    id: 8,
    body: 'parent comment #2',
    children: []
  },
];

Then I use the normalizr library to normalize it like this:
const commentSchema = new schema.Entity('comments');
const commentListSchema = new schema.Array(commentSchema);
commentSchema.define({children: commentListSchema});
const normalizedComments = normalize(nestedComments, commentListSchema);

The result is pretty much as expected:
{
  entities: {
    // All of the comments ordered their id's, this is fine and what I want
  },
  results: [1,8] // understandable but not what I want
}

So it preserves the order of the root comments but doesn't do anything for the nested child comments. Is there a way to do this so that each group of siblings has its own results array? Something that looks like this:
results: [[1,8], [4,3], [7,6,5]];

Or maybe there is a better way to preserve that information and I'd appreciate hearing about that as well.

A: The answer that will work for me was already present in the results. The comments in the entities stores an array of the children ids that is in the original order.
entities: {
  {
    id: 1,
    body: 'parent comment',
    children: [4,3]
  },
  ...
  {
    id: 4,
    body: 'child comment',
    children: [7,6,5],
  },
  ...
}


text:
Q: I need to get arrow key presses, but keyDown won't call (Swift) I am trying to build a Mac App which displays images and I want to move on to the next image when I press the right arrow key. I have looked all over stackoverflow and the internet, but just can't seem to get it.
What I tried... I tried to use keyDown(theEvent: NSEvent)but it does not call when I press any keys. I believe this is because it is not in a text field of some kind, but not sure.
What Happens... When i'm testing the program, I press a key (with keyDown function ready to println("Key Pressed")) and I get the OS X reject noise and no println to the console.
I have heard of some people subclassing NSView to override acceptsFirstResponder, but I am new to subclassing so any direction you could point me in would be great. Or if there is a way to do it w/o subclassing NSView that would be great!
Thanks in advance! Sorry for the noobness.

A: Subclassing is less difficult than it seems.
Short tutorial:
General assumption: keystrokes are going to be received in the view of a NSViewController subclass and to be processed in the view controller class

*

*Create a new Cocoa Class named MyView as a subclass of NSView

*Replace the contents of the created class with
import Cocoa

let leftArrowKey = 123
let rightArrowKey = 124

protocol MyViewDelegate {
  func didPressLeftArrowKey()
  func didPressRightArrowKey()
}

class MyView: NSView {

   var delegate : MyViewDelegate?

   override func keyDown(event: NSEvent) {
     let character = Int(event.keyCode)
     switch character {
     case leftArrowKey, rightArrowKey:
       break
     default:
       super.keyDown(event)
     }
   }

   override func keyUp(event: NSEvent) {
     let character = Int(event.keyCode)
     switch character {
     case leftArrowKey:
       delegate?.didPressLeftArrowKey()
     case rightArrowKey:
       delegate?.didPressRightArrowKey()
     default:
       super.keyUp(event)
     }
   }

    override var acceptsFirstResponder : Bool {
      return true
    }
  }

*

*Change the class of the view of the ViewController in Interface Builder to MyView

*In the ViewController class add the protocol MyViewDelegate- for example
class ViewController: NSViewController, MyViewDelegate {

*In viewDidLoad() add
let view = self.view as! MyView
view.delegate = self
self.nextResponder = view

*Implement the following delegate methods and add your code to switch the image(s)
func didPressLeftArrowKey() {
  println("didPressLeftArrowKey")
  // process keystroke left arrow
}

func didPressRightArrowKey() {
  println("didPressRightArrowKey")
  // process keystroke right arrow
}

The delegate methods are called when the appropriate arrow keys are released

A: let kLeftArrowKeyCode:  UInt16  = 123
let kRightArrowKeyCode: UInt16  = 124
let kDownArrowKeyCode:  UInt16  = 125
let kUpArrowKeyCode:    UInt16  = 126

override func keyDown(with event: NSEvent) {
          switch event.keyCode {
          case kLeftArrowKeyCode:
              print("left")
              break
          case kRightArrowKeyCode:
              print("right")
              break
          case kDownArrowKeyCode:
              print("down")
              break
          case kUpArrowKeyCode:
              print("up")
              break
          default:
              print("other")
              super.keyDown(with: event)
              break
          }
          print("Key with number: \(event.keyCode) was pressed")
}


text:
Q: setContentView not executed after onRestoreInstanceState I have the following problem:
After onRestoreInstanceState is called, I notice that while setContentView is supposed to be called, I keep getting all sorts of exceptions that imply that setContentView isn't executed - missing findViewById, getWindow().setFeatureInt() throwing exception because content view isn't called, black screen instead of the actual screen I am expecting, etc.
Am I doing something wrong here?
Thanks

A: You should call setContentView() in OnCreate() of your activity.


text:
Q: Angularjs why this html page(view) does not integrate with Angular
I have an Angularjs site that works. However one html file(view) does not integrate with Angular. The flight fields are not show and the button is not active.
Can anybody help?

Pagamento

Pagamento do Voo

Voo: {{flight.fromairport.name}}  ➝ {{flight.toairport.name}}

Horário: {{flight.departure | formatDateTime}}h

Lugares disponíveis: {{flight.availableseats}}

Aeronave: {{flight.airplane.name}}

Preço atual: R$ {{flight.price | formatPrice}}

  <button class="button" ui-sref="client.payment({flight:flightid})" >Pagar com Paypal</button>

----------------   Java script -----------------

    'use strict';

/**
 * @ngdoc function
 * @name flyvipApp.controller:AboutCtrl
 * @description
 * # AboutCtrl
 * Controller of the flyvipApp
 */
angular.module('flyvipApp')
  .controller('PaymentCtrl', function ($scope, SharedData, $rootScope, $state, $stateParams, Authorization, $http) {

    var api = "http://flyvip.com.br/app/api/";
    var userid = Authorization.currentUser().user.id;

    $rootScope.sidePanel = false;
    SharedData.selectedMenu.setItem('voos');
    $scope.menu = SharedData.selectedMenu;
    $rootScope.homeClient = false;
    $scope.orderedFlights = {data: []};
    $scope.flag = false;
    var _flightid = _id;
    var _airplaneid = $scope.flight.airplane.id;
    var _dateofdeparture = $scope.flight.dateofdeparture;
    var _dateofarrival = $scope.flight.dateofarrival;
    var _airportdeparture = $scope.flight.fromairport.id;
    var _airportarrival = $scope.flight.toairport.id;
    var _price = $scope.flight.price;
    var _seats = $scope.flight.availableseats;
    var _status = $scope.flight.flightstatus;
    var _reason = $scope.flight.reason;

    var flight = {
      flightid: _flightid,
      airplaneid: _airplaneid,
      dateofdeparture: _dateofdeparture,
      dateofarrival: _dateofarrival,
      airportofdeparture: _airportdeparture,
      airportofarrival: _airportarrival,
      price: _price,
      seats: _seats,
      flightstatus: _status,
      reason: _reason,
      invoicenum: "122344",
      passengerid: $scope.passengerid
    };
    $http({method: "POST", url: api + "DoWriteLog.php",msg:'Entrei neste script!', headers: {'Content-Type': 'application/x-www-form-urlencoded'}}).success(function(response, status, headers, config) {
  });
    $http({method: "POST", url: api + "DoPayment.php", data: flight, headers: {'Content-Type': 'application/x-www-form-urlencoded'}}).success(function(response, status, headers, config) {
      if (response.success) {
        $scope.flag = true;
      }
      else
        $scope.flag = false;
    })});

A: You are not assigning flight object to scope try this:
$scope.flight = {
...
}

Also I can see that most of the variables are not declared in that object except flight.fromairport.
I'm not sure where are you getting the data from, but make sure it is assigned to $scope.flight at some point.


text:
Q: Align fixed navigation-div to the right outer div The navigation bar sticks to the left of the container-div. But I want it to stick to the right. I tried several things but none of them worked. So here is the barebones code.
How can I get a navigation bar that sticks to the right side, ending exactly where my container-div ends?
PS: It has to be fixed because I want the navigation to stay at the top of the browser window, no matter how much the user scrolls down.

#container {
    margin: 0 auto;
    width: 820px;
}

#navigation {
    position: fixed;
    z-index: 10000;
    display:block;
}

A: OK, I had a guess at your HTML code and build up this for you: http://jsfiddle.net/vdL6b/
From what I can imagine you're trying to achieve, it's possible with one of two solutions:

*

*Removing position:fixed; and adding float: right; to your navigation CSS.

*Adding right: 0; to define the position.

I chose the latter. Here's an example using the first.


text:
Q: How to check if image moved by finger? (Manipulation) I already working with manipulations over images on canvas. Now, I need to check, if image moved on canvas using fingers. How to do this?
     void Window_ManipulationDelta(object sender, ManipulationDeltaEventArgs e)
        {
            Image photoToMove = e.OriginalSource as Image;
            int photoIndex = photos.IndexOf(photoToMove);

            System.Windows.Media.Matrix rectsMatrix = ((MatrixTransform)photoToMove.RenderTransform).Matrix;
            rectsMatrix.RotateAt(e.DeltaManipulation.Rotation,
                                 e.ManipulationOrigin.X,
                                 e.ManipulationOrigin.Y);
            rectsMatrix.ScaleAt(e.DeltaManipulation.Scale.X,
                                e.DeltaManipulation.Scale.X,
                                e.ManipulationOrigin.X,
                                e.ManipulationOrigin.Y);
            rectsMatrix.Translate(e.DeltaManipulation.Translation.X,
                                  e.DeltaManipulation.Translation.Y);
            MatrixTransform newImageMTransform = new MatrixTransform(rectsMatrix);
            photoToMove.RenderTransform = newImageMTransform;

            Rect containingRect =
                new Rect(((FrameworkElement)e.ManipulationContainer).RenderSize);

            Rect shapeBounds =
                photoToMove.RenderTransform.TransformBounds(
                    new Rect(photoToMove.RenderSize));

            if (e.IsInertial && !containingRect.Contains(shapeBounds))
            {
                e.Complete();
            }

            if (e.DeltaManipulation.Translation.X > 0 || e.DeltaManipulation.Translation.Y > 0)
            {
                imageMoved = true;
            }
            else
            {
                imageMoved = false;
            }

            e.Handled = true;

        }

At now, this code always says me "imageMoved == true".


text:
Q: Using prototype functions in higher order functions in javascript I'm trying to concat an array of arrays using reduce and I figured that I could use the Array.prototype.concat function like this:
arr = [[1],[2],[3]]
arr.reduce((a, b) => Array.prototype.concat(a, b), [])

Which works fine and gives me the array [1, 2, 3]. Then I thought I could be even smarter and do it like this:
arr = [[1],[2],[3]]
arr.reduce(Array.prototype.concat, [])

This however gives me an error:
TypeError: Array.prototype.concat called on null or undefined
    at Array.reduce (native)
    at Object.<anonymous> (/home/axel/Developer/temp/reduce2.js:2:5)
    at Module._compile (module.js:556:32)
    at Object.Module._extensions..js (module.js:565:10)
    at Module.load (module.js:473:32)
    at tryModuleLoad (module.js:432:12)
    at Function.Module._load (module.js:424:3)
    at Module.runMain (module.js:590:10)
    at run (bootstrap_node.js:394:7)
    at startup (bootstrap_node.js:149:9)

It seems to think that Array.prototype.concat is undefined. Why is this?

A: concat operates as a method with respect to some object (i.e., the this value of the method's execution). When you pass a function into a function, you do not pass along any this value. Thus, you're effectively doing something similar to:
var rawConcat = Array.prototype.concat;
rawConcat(a,b);

You can use bind to create a copy of a function with a particular this burned into it:
arr.reduce(Array.prototype.concat.bind(Array.prototype), [])

However, now that that's cleared up, there are several other issues that stop you from doing this.
For one, reduce actually gets four arguments, including the current index and the whole array. You ignore these by having your (a,b)=> lambda only pass two of those four arguments into concat. That's fine, but when you supply a function directly as an argument to reduce, it will use all four arguments, so you'll get the result of the call Array.prototype.concat(a, b, currentIndex, arr).
Furthermore, what you're doing isn't a sensible use of Array.prototype. The concat function concatenates its arguments and appends them to a copy of the this value. Since Array.prototype is itself just an empty array (albeit with many own-properties that other arrays use as inherited properties), this is effectively the same as [].concat(a,b) or (perhaps even more readably) a.concat(b).

A: Array.prototype.concat expects the context (this) to be an Array and in your first example the context is actually Array.prototype which incidentally looks exactly like an Array, hence it works.
Your second example however, passes the concat function by reference so the context is null or undefined.
The more correct way to do this would be to use Function.prototype.call to bind the context to one of the arrays or call the method directly on the array, e.g.
arr = [[1],[2],[3]];
arr.reduce((a, b) => Array.prototype.concat.call(a, b), []);

// Or

arr.reduce((a, b) => a.concat(b), []);


text:
Q: What is the best way to Parse a scanned PDF file using PHP or JS? I have a translation website and I would like to parse PDF files so that I can count words and I set the price for translation.
I have tried Poppler JS before. But It can't handle the scanned files. How should I handle them?
For example this PDF is a scanned article. It is a PDF file but each page is a picture and I need to extract the text:

A: What you are looking for is an OCR library. There are a bunch of options to do this, here are some Software Recommendation Stack Exchange links:
Scan Text Document To PDF With OCR
JavaScript library for OCR