text:
Q: using php/mysql to compare two tables and add missing columns from table1 to table2 Ok, Let's say I have two tables with identical structures but different values :
TABLE1 : column.A, column.B, column.C
TABLE2 : column.A, column.B, column.C

I add columns in table 1, it becomes :
TABLE1 : column.A, column.B, column.C, column.D, column.E, column.F ... column.M
TABLE2 : column.A, column.B, column.C

Now, using php/mysql I want to compare TABLE1 and TABLE2 and add in TABLE2 missing columns from TABLE1. I'm talking structure only (columns, not values). I could do it manually, but I want to avoid it.
Is there a way to do it ?
I can't find any.
EDIT :
I just found out about describe ( https://electrictoolbox.com/mysql-table-structure-describe/ ) which might be a great help on this. I've read all the answers, which look great but I think the best way would be to use DESCRIBE on both tables and then compare the results to add the missing columns to table2 using informations from the DESCRIBE query of table1
EDIT2: Bill Karwin answer is the best one to me. He uses information_schema which is better than DESCRIBE (only difference would be that it could be slower). The only thing after that would be to ALTER TABLE table2 with the informations we got from the query.

A: create table table1 ( a int, b int, c int, d int, e int);

create table table2 (a int, b int, c int);

select t1.column_name
from information_schema.columns as t1
left outer join information_schema.columns as t2
  on t1.table_schema = t2.table_schema
  and t1.column_name = t2.column_name
  and t2.table_name = 'table2'
where (t1.table_schema, t1.table_name) = ('test', 'table1')
  and t2.table_name is NULL;

+-------------+
| COLUMN_NAME |
+-------------+
| d           |
| e           |
+-------------+

To produce the necessary ALTER TABLE statement to add the columns, you'll need to inspect the rest of the columns of that information_schema table. See  https://dev.mysql.com/doc/refman/8.0/en/information-schema-columns-table.html

A: (My answer may be Oracle-specific, but I'm hoping it will lead you to a MySQL solution.)
I'd perform this database operation all inside a database procedure (which you can call from PHP if you want).
In Oracle (which may not help you much), I would:
SELECT column_name FROM user_tab_columns WHERE table_name = 'TABLE1'
MINUS
SELECT column_name FROM user_tab_columns WHERE table_name = 'TABLE2';
(I believe MySQL has similar information_schema built-in tables).
Then put together an alter table statement as such:
EXECUTE IMMEDIATE 'ALTER TABLE TABLE2 ADD (' & ... comma seperated results from the  above SQL ... & ");"
and get data types in the first query too, to include in the alter statement.
-mobailey

A: Doing the task manually is not that complex, and is probably fewer keystrokes than trying to cobble the equivalent from information_schema.columns, etc.

*

*SHOW CREATE TABLE for each table.

*Spot the 'new' columns.

*Copy & paste them into an ALTER TABLE along with ADD COLUMN in front of each.

*Execute the ALTER.

If you need to do this on lots of tables, then I have to ask "why".


text:
Q: при вводе данных, считывает только одну строку a = [str(i) for i in input().split()]
print(f'г. {a[0]}, ул.{a[1]}, д. {a[2]}, кв. {a[3]}')

 Test input:
=========
  Москва
  Воздвиженка
  9
  1

каждый элемент с новой строки, но вводится за один раз

A: в конце каждой строке у вас знак перевода строки, который означает нажатие на Enter. Если вы используете стандартный ввод, то так работать не будет.
Что можно сделать

*

*Подавать данные в строку
Москва Воздвиженка 9 1

*Определить while до первой пустой строки
a = []
while True:
    user_input = input()
    if user_input:
        a.append(user_input)
    else:
        break

Здесь вводить можно столько строк сколько надо, до появления первой пустой строки или другими словами нажатие Enter без введения данных в строку

*Отказаться от стандартного ввода input и хранить и подавать данные из переменной/файла

redpajama_set_name: RedPajamaStackExchange


text:
Q: Dynamically add filter to SQLAlchemy TextClause Assume I have a SQLAlchemy table which looks like:
class Country:
    name = VARCHAR
    population = INTEGER
    continent = VARCHAR
    num_states = INTEGER

My application allow seeing name and population for all Countries. So I have a TextClause which looks like
"select name, population from Country"

I allow raw queries in my application so I don't have option to change this to selectable.
At runtime, I want to allow my users to choose a field name and put a field value on which I want to allow filtering. eg: User can say I only want to see name and population for countries where Continent is Asia. So I dynamically want to add the filter
.where(Country.c.continent == 'Asia')

But I can't add .where to a TextClause.
Similarly, my user may choose to see name and population for countries where num_states is greater than 10. So I dynamically want to add the filter
.where(Country.c.num_states > 10)

But again I can't add .where to a TextClause.
What are the options I have to solve this problem?
Could subquery help here in any way?

A: Please add a filter based on the conditions. filter is used for adding where conditions in sqlalchemy.
Country.query.filter(Country.num_states > 10).all()

You can also do this:
query = Country.query.filter(Country.continent == 'Asia')
if user_input == 'states':
    query = query.filter(Country.num_states > 10)
query = query.all()

A: This is not doable in a general sense without parsing the query. In relational algebra terms, the user applies projection and selection operations to a table, and you want to apply selection operations to it. Since the user can apply arbitrary projections (e.g. user supplies SELECT id FROM table), you are not guaranteed to be able to always apply your filters on top, so you have to apply your filters before the user does. That means you need to rewrite it to SELECT id FROM (some subquery), which requires parsing the user's query.
However, we can sort of cheat depending on the database that you are using, by having the database engine do the parsing for you. The way to do this is with CTEs, by basically shadowing the table name with a CTE.
Using your example, it looks like the following. User supplies query
SELECT name, population FROM country;

You shadow country with a CTE:
WITH country AS (
  SELECT * FROM country
  WHERE continent = 'Asia'
) SELECT name, population FROM country;

Unfortunately, because of the way SQLAlchemy's CTE support works, it is tough to get it to generate a CTE for a TextClause. The solution is to basically generate the string yourself, using a custom compilation extension, something like this:
class WrappedQuery(Executable, ClauseElement):
    def __init__(self, name, outer, inner):
        self.name = name
        self.outer = outer
        self.inner = inner

@compiles(WrappedQuery)
def compile_wrapped_query(element, compiler, **kwargs):
    return "WITH {} AS ({}) {}".format(
        element.name,
        compiler.process(element.outer),
        compiler.process(element.inner))

c = Country.__table__
cte = select(["*"]).select_from(c).where(c.c.continent == "Asia")
query = WrappedQuery("country", cte, text("SELECT name, population FROM country"))
session.execute(query)

From my tests, this only works in PostgreSQL. SQLite and SQL Server both treat it as recursive instead of shadowing, and MySQL does not support CTEs.

A: I couldn't find anything nice for this in the documentation for this. I ended up resorting to pretty much just string processing.... but at least it works!
from sqlalchemy.sql import text

query = """select name, population from Country"""

if continent is not None:
    additional_clause = """WHERE continent = {continent};"""
    query = query + additional_clause
    text_clause = text(
        query.format(
            continent=continent,
        ),
    )
else:
     text_clause = text(query)

with sql_connection() as conn:
    results = conn.execute(text_clause)

You could also chain this logic with more clauses, although you'll have to create a boolean flag for the first WHERE clause and then use AND for the subsequent ones.


text:
Q: Intersection observer does not work with target with position: fixed I am trying to invoke a callback via intersection observer.
I want the target to be style: "position: fixed" and move it via
style.top.
I also specified the root element which is an ancestor of the target with style: "position: relative".
But when the target and the observer intersects, the callback function won't be triggered.
Are there some limitations I missed?
Here is what I typed:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>IO</title>

aaa

bbb

ccc

And here is a codepen demo:
codepen demo
You can click anywhere in the page to start moving the ccc block.

A: Elements with position: fixed are positioned relative to the viewport and the viewport moves. So, fixed positioned elements "move" as you scroll.  Even though #target is a child of #middle, I believe the IntersectionObserver, with whatever it uses under the hood to calculate if the target is entering/leaving the root, never fires the callback because the target is outside of the document flow.
Here is a related issue. There isn't much out in the interwebs related to this issue: https://bugs.chromium.org/p/chromium/issues/detail?id=653240
Note: Setting position: absolute on the target does indeed fire the callback when entering and leaving the viewport.

A: In my case I had my root element (with position:fixed) at the same DOM hierarchy level as the elements I wanted to observe (that were scrollable) and no events were triggered.

When I placed the elements inside the root the events triggered.


text:
Q: Basic Input Output Program to read from local datasheet i'm a coding newbie and i'm having trouble with coding, and would love some help.
Writing in Python 3 by the way.
Basically, the user will input a name (like John Smith), if John Smith belongs to "list R", then the program will print ("John Smith belongs to Company R")
I don't know what these kinds of programs are called, so I couldn't really find it off google.
EDIT: made some progress but get this error when I enter a second name
Traceback (most recent call last):
  File "", line 1, in
    Frank
NameError: name 'Frank' is not defined
I think my code only runs once, and after completion it doesn't return to val = input
R = ["James", "John"]
val = input("Enter Name: ")
if val in R:
    print (val, "is from company R")
else:
    print (val, "is not from company R")

I've
Many thanks!

A: You could enclose your code in a while loop to return to val = input("Enter Name: ") until a blank value is entered.
R = ["James", "John"]
val = input("Enter Name: ")
while val != "":
    if val in R:
        print (val, "is from company R")
    else:
        print (val, "is not from company R")
    val = input("Enter Name: ")


text:
Q: Spark write data into partitioned Hive table very slow I want to store Spark dataframe into Hive table in normal readable text format. For doing so I first did
sqlContext.sql("SET spark.sql.hive.convertMetastoreParquet=false")

My DataFrame is like:
final_data1_df = sqlContext.sql("select a, b from final_data")

and I am trying to write it by:
final_data1_df.write.partitionBy("b").mode("overwrite").saveAsTable("eefe_lstr3.final_data1")

but this is very slow, even slower than HIVE table write. So to resolve this I thought to define partition through Hive DDL statement and then load data like:
sqlContext.sql("""
CREATE TABLE IF NOT EXISTS eefe_lstr3.final_data1(
a BIGINT
)
PARTITIONED BY (b INT)
"""
)
sqlContext.sql("""
INSERT OVERWRITE TABLE eefe_lstr3.final_data1 PARTITION (stategroup)
select * from final_data1""")

but this is giving partitioned Hive table but still parquet formatted data. Am I missing something here?

A: When you create the table explicitly then that DDL defines the table.
Normally text file is the default in Hive but it could have been changed in your environment.
Add "STORED AS TEXTFILE" at the end of the CREATE statement to make sure the table is plain text.


text:
Q: How to start X application with specific width an height? I need to start X applications with specific width an height. I didn't find any good solution except using xdotool xdotool - fake keyboard/mouse input, window management, and more.
Could I just append some arguments after application start command to archive this?


text:
Q: Instance Declarations Bit curious why the instance declaration is needed in the following as a default implementation is provided.
module Example where

class Eq a => EQ a where
    eq :: a -> a -> Bool
    eq = (==)

-- why is this instance declaration needed?
instance EQ Int where
    eq = (==)

f :: Int -> Int -> Bool
f = eq

If I leave out the instance declaration I get an error. I'm sure it's explained somewhere in the Haskell report but it will take a while to find it.

A: I think you're definition of a class, is probably more what in Java/C#/... is a class.
If you write:
class Eq a => EQ a where
    eq :: a -> a -> Bool
    eq = (==)

You only define a typeclass: a way to add functions to a type class and write restrictions. You have not written that every Eq a is an EQ a... You have written that in order to implement EQ a, you have to implement Eq a as well (which is a bit weird here).
Furthermore you have provided a default implementation: eq = (==), but that is only a default implementation for an instance where you do not specify the implementation.
By writing:
instance EQ Int where
    eq = (==)

you have now defined that Int is an EQ. You can make the instance more useful by writing for instance:
instance Eq a => EQ a

Now you have written than all types a for which Eq a holds, also are a type instance of EQ. If you write that however, you have immediately defined the entire universum of EQ since in your class definition, you restricted a to be an instance of EQ, so that means that now, in the entire Haskell universe, eq is equal to (==).
You probably want to say:
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE UndecidableInstances #-}

class EQ a where
    eq :: a -> a -> Bool

instance Eq a => EQ a where
    eq = (==)

Now you defined a typeclass EQ and for every type a that is Eq a, we set eq to (==), but it allows you to define an EQ over other types as well, like data Foo that is not an instance of Eq. Mind that we have to turn on two extensions here. These are compiler specific, and thus are not part of standard Haskell.


text:
Q: what is error Warning in .\libraries\classes\Plugins\AuthenticationPlugin.php#226 Cannot use a scalar value as an array in mysql using phpmyadmin i want to use xampp and phpmyadmin just use mysql in university project i dont use php code and other think just i run xampp and open phpmyadmin in localhost and i got this error:

Warning in .\libraries\classes\Plugins\AuthenticationPlugin.php#226
      Cannot use a scalar value as an array
Backtrace
.\libraries\classes\Plugins\AuthenticationPlugin.php#67:
        PhpMyAdmin\Plugins\AuthenticationPlugin-
  setSessionAccessTime()
       .\libraries\classes\Plugins\AuthenticationPlugin.php#248:
        PhpMyAdmin\Plugins\AuthenticationPlugin->storeCredentials()
       .\libraries\common.inc.php#351: PhpMyAdmin\Plugins\AuthenticationPlugin-
  authenticate()
      .\index.php#27: require_once(.\libraries\common.inc.php)

A: i think the error was caused because of cached session. i had the same issue and clicking the logout button on the top left automatically solve the issue.

A: This error is due to phpmyadmin trying to load data from cache.To fix this issue clear your cache. The best method is to download ccleaner from https://www.ccleaner.com/ (free version is enough). Stop and quit xampp run "clean your pc" in c cleaner. (close all browsers)
restart xampp and your good to go.


text:
Q: OpenVPN client-to-client When using a TUN (layer 3) OpenVPN server with client-to-client disabled, my clients can still talk to each other.
The client-to-client config should prevent this according to the documentation:

Uncomment out the client-to-client directive if you would like
  connecting clients to be able to reach each other over the VPN. By
  default, clients will only be able to reach the server.

Why can the clients continue to communicate to each other when this option is disabled?
Here is my server conf:
port 443
proto tcp
dev tun
ca /etc/openvpn/keys/ca.crt
cert /etc/openvpn/keys/server.crt
key /etc/openvpn/keys/server.key
dh /etc/openvpn/keys/dh4096.pem
topology subnet
server 10.10.201.0 255.255.255.128
ifconfig-pool-persist ipp.txt
crl-verify /etc/openvpn/keys/crl.pem
push "route [omitted]"
push "dhcp-option DNS [omitted]"
keepalive 10 120
comp-lzo
user nobody
group nogroup
persist-key
persist-tun
plugin /usr/lib64/openvpn/plugins/openvpn-plugin-auth-pam.so login
cipher AES-256-CBC
tls-auth /etc/openvpn/keys/pfs.key 0
verb 4

A: You need to do more than just commenting the directive as it says here:

Uncomment this directive to allow different
  clients to be able to "see" each other.
  By default, clients will only see the server.
  To force clients to only see the server, you will also need to appropriately firewall the server's TUN/TAP interface.

Therefore you may configure seperate IP address policy for each client. See the section Configuring client-specific rules and access policies here: https://openvpn.net/index.php/open-source/documentation/howto.html.
and here: https://www.sbarjatiya.com/notes_wiki/index.php/Configuring_separate_IP_and_firewall_rule_for_each_openvpn_client.

A: If client-to-client is enabled, the VPN server forwards client-to-client packets internally without sending them to the IP layer of the host (i.e. to the kernel). The host networking stack does not see those packets at all.
           .-------------------.
           | IP Layer          |
           '-------------------'

           .-------------------.
           | TUN device (tun0) |
           '-------------------'

           .-------------------.
           | OpenVPN server    |
           '-------------------'
             ^           |
          1  |           |  2
             |           v
 .----------------.  .----------------.
 | Client a       |  | Client b       |
 '----------------'  '----------------'

If client-to-client is disabled, the packets from a client to another client go through the host IP layer (iptables, routing table, etc.) of the machine hosting the VPN server: if IP forwarding is enabled, the host might forward the packet (using its routing table) again to the TUN interface and the VPN daemon will forward the packet to the correct client inside the tunnel.
           .-------------------.
           | IP Layer          |  (4) routing, firewall, NAT, etc.
           '-------------------'      (iptables, nftables, conntrack, tc, etc.)
              ^          |
          3   |          |  5
              |          v
           .-------------------.
           | TUN device (tun0) |
           '-------------------'
             ^           |
          2  |           |  6
             |           v
           .-------------------.
           | OpenVPN server    |
           '-------------------'
             ^           |
          1  |           |  7
             |           v
 .----------------.  .----------------.
 | Client a       |  | Client b       |
 '----------------'  '----------------'

In this case (client-to-client disabled), you can block the client-to-client packets using iptables:
 iptables -A FORWARD -i tun0 -o tun0 -j DROP

where tun0 is your VPN interface.

A: The next paragraph of the man page for openvpn answers this question, although it's not necessarily clear at first reading:

Because the OpenVPN server mode handles multiple clients through              a  single tun or tap interface, it is effectively a router.  The              --client-to-client  flag  tells  OpenVPN  to  internally   route              client-to-client  traffic  rather than pushing all client-originating traffic to the TUN/TAP interface.
When this option is used,  each  client  will  "see"  the  other              clients  which  are currently connected.  Otherwise, each client              will only see the server.  Don't use this option if you want  to              firewall tunnel traffic using custom, per-client rules.

The client-to-client option short-circuits the normal routing tables on the server. Removing it does not prevent the clients using the server's routing tables. If those routing tables - and the server's firewall configuration - permit clients to see each other then they will be able to do so.


text:
Q: How to keep zero-length element when using c() on a list? Context: I have a list of Dates objects as an ouput from a function. Some of them can be Date of length 0.
Problem: When I concatenate the elements of the list to get a vector (i.e. do.call(c, mylist)), the latters are dropped. This cause problems when I try to add this vector as a column in a pre-existing dataframe.
Question: Is it possible to "keep" these Date of length 0 elements into the final vector? Do you know a better way to acheive the expected result?
ex_list <- list(structure(14467, class = "Date"),
                structure(14567, class = "Date"),
                structure(numeric(0), class = "Date"))
ex_list
#> [[1]]
#> [1] "2009-08-11"
#>
#> [[2]]
#> [1] "2009-11-19"
#>
#> [[3]]
#> Date of length 0
ex_vector <- do.call(c, ex_list)
ex_vector # the Date of length 0 is dropped
#> [1] "2009-08-11" "2009-11-19"
df <- data.frame(id = c("A", "B", "C"))
df$dates <- ex_vector
#> Error in `$<-.data.frame`(`*tmp*`, dates, value = structure(c(14467, 14567: le tableau de remplacement a 2 lignes, le tableau remplacé en a 3

Created on 2022-06-07 by the reprex package (v2.0.1)
Expected output:

id
dates

A
2009-08-11

B
2009-11-19

C
NA

A: For use in a data frame you'd prefer NA's over Date(0). E.g.
ex_list[sapply(ex_list, rlang::is_empty)] <- NA
ex_vector <- do.call(c, ex_list)
df <- data.frame(id = c("A", "B", "C"))
df$dates <- ex_vector

Or a tidyverse-solution:
library(tidyverse)

data.frame(id = c("A", "B", "C")) |>
  add_column(as_tibble_col(ex_list, column_name = "dates")) |>
  unnest(dates, keep_empty = TRUE)


text:
Q: Non-nullable instance field '_database' must be initialized I am trying to use a database form assets folder in my flutter app. I tried this code :
class DatabaseHelper {
  static const _databaseName = "main.db";
  static const _databaseVersion = 1;

  DatabaseHelper._privateConstructor();
  static final DatabaseHelper instance = DatabaseHelper._privateConstructor();

  static Database _database;
  Future<Database> get database async {
    if (_database != null) return _database;
    _database = await _initDatabase(); // only initialize if not created already
    return _database;
  }

  _initDatabase() async {
    String path = join(await getDatabasesPath(), _databaseName);

    if (!(await databaseExists(path))) {
      ByteData data = await rootBundle.load(join("assets", _databaseName));
      List<int> bytes =
          data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
      await File(path).writeAsBytes(bytes);
    }
    return await openDatabase(path, version: _databaseVersion);
  }
}

But the code is throwning this error at this code   DatabaseHelper._privateConstructor();
error:
The non-nullable variable '_database' must be initialized.
Try adding an initializer expression.
and at this code :
static Database _database;
Non-nullable instance field '_database' must be initialized.
Try adding an initializer expression, or add a field initializer in this constructor, or mark it 'late'.dartnot_initialized_non_nullable_instance_field

i am new to flutter, i don't know what that means... please help me solve this :)

A: The analyzer is complaining because you have _database as it is right now as non-null because you're using the type Database which means a value is guaranteed to be there... non-null. To make something nullable, which this is, you need to put a ? behind the type e.g. Database?
static Database _database;

should be
static Database? _database;

A: You can try late keyword
late Database _database;


text:
Q: Is there a Math3d function to multiply a vertex array with a 4x4 matrix? I've looked at the source code and I haven't found anything, but I want to be shure, just in case. Is there any math3d function that takes a vertex array and multiplies it by a m3dmatrix44f?

A: I'd recommend switching to Eigen or GLM for matrix-wrangling.  Eigen has SIMD routines to speed up batch operations.
They're both header-only.


text:
Q: SAX Parser, new lines being removed after parsing, can I keep them in? (
) I'm unsure on how complicated or easy this issue might be since this is my first project with XML parsing and therefore using the SAX parser.
When pulling down XML from a server, I can see in the XML there are a few
 in the text, a carriage return character, or new line. After the XML has gone through the SAX parser it comes out the other end without those characters.
It comes out as a string and when I add it to a TextView it's just one big block of text, which is obviously not something I want.
Is there a way for me to parse the XML and still keep the
 characters? My idea was to do a String.replace("
", "\n"); right before adding it to the TextView, therefore making use of new lines.
If there is a better way I would love to know but just being able to use
 would be helpful too.
Thanks in advance for any advice you can offer.

A: XML parsers are required to normalize line endings, so CR and CRLF sequences are all turned into LF (CR=x0D, LF=x0A) before presentation to the application.
If you want to retain the CR characters (why??) you should represent them as numeric character references, that is

A: Before starting the parser I am converting my HTTP result into a string, so before I parse I do a String.replace("
", "
");
After parsing new lines show up correctly. I guess the parser ignores carriage return in favour or new lines. Which makes sense I guess.
Hopefully this helps someone down the line.


text:
Q: Delete files existing in another directory tree Maybe it's duplicate to How to delete files in a directory, that exist in another directory?, but I need to consider also path. I just successfully repaired MBR and partition table, now I'm trying to recover on FS level, but the utility "recovers" also the healthy ones. So I want to delete them. Thanks
It might be my bad english, but I need to keep only files with different relative pathname in whole tree. Never mind, the new Beyond Compare can show also same files, not only different ones.


text:
Q: Replacement of HTTParty.send with Faraday I am rails beginner working on a task to replace HTTParty with Faraday. So in codebase I call put/post/get based on the verb like so:
response = HTTParty.send(verb, url, http_options)
I am aware that Faraday provides an option to call them individually like so:
Faraday.put(url) do |req|
Can I somehow abstract it, to call based on the verb.
Please let me know, if I can answer any questions.


text:
Q: Searching Multiple Elements In XML File I'm using the W3C Live Ajax Search found here. Their code only searches one element, the "title".  I would like to have it take the user's query and search through multiple elements, for example, the 'title' and the 'url'.
<?php
$xmlDoc=new DOMDocument();
$xmlDoc->load("live.xml");

$x=$xmlDoc->getElementsByTagName('link');

//get the q parameter from URL
$q=$_GET["q"];

//lookup all links from the xml file if length of q>0
if (strlen($q)>0)
{
$hint="";
for($i=0; $i<($x->length); $i++)
  {
  $d=$x->item($i)->getElementsByTagName('title');
  $z=$x->item($i)->getElementsByTagName('url');
  if ($d->item(0)->nodeType==1)
    {
    //find a link matching the search text
    if (stristr($d->item(0)->childNodes->item(0)->nodeValue,$q) !=false)
      {
      if ($hint=="")
        {
        $hint=
        $z->item(0)->childNodes->item(0)->nodeValue . "
" .
        $d->item(0)->childNodes->item(0)->nodeValue;
        }
      else
        {
        $hint=$hint . "

" .
        $z->item(0)->childNodes->item(0)->nodeValue . "
" .
        $d->item(0)->childNodes->item(0)->nodeValue;
        }
      }
    }
  }
}

// Set output to "no suggestion" if no hint were found
// or to the correct values
if ($hint=="")
  {
  $response="no suggestion";
  }
else
  {
  $response=$hint;
  }

//output the response
echo $response;

?>

Can somebody give me an example of how to make it work?  From what I understand, stristr will only search one haystack and you can't use arrays, so is there another way?  Thanks in advance!

A: Well, I figured out a way:
if ( (stristr($d->item(0)->childNodes->item(0)->nodeValue,$q) !=false) ||
     (stristr($z->item(0)->childNodes->item(0)->nodeValue,$q) !=false) )

I doubt this is the optimal way, so if anybody has a better solution feel free to add it.


text:
Q: Using multiple M2M relationship across multiple database in peewee I have two python projects which maintain their different database connections and sqlite files. model1.py is in the low-level project, model2.py is in the high-level project which using the model class of model1.py. The following is the sample code:
model1.py
from os.path import join, dirname

from peewee import *
from playhouse.sqlite_ext import *

_db = SqliteDatabase(join(dirname(__file__), 'db1.sqlite'))

class Student(Model):
    name = CharField()
    sex = CharField()

    class Meta:
        database = _db

    def __str__(self):
        return 'student name: %s, sex: %s' % (self.name, self.sex)

_db.connect()
_db.create_tables([
    Student,
])

model2.py
from os.path import join, dirname

from peewee import *
from playhouse.sqlite_ext import *

from model1 import *

_db = SqliteDatabase(join(dirname(__file__), 'db2.sqlite'))

class Teacher(Model):
    name = CharField()
    age = IntegerField()

    sample_student = ForeignKeyField(Student, null=True, backref='sample_teacher')
    students = ManyToManyField(Student, backref='teachers')

    class Meta:
        database = _db

    def __str__(self):
        return 'teacher name: %s, age: %d' % (self.name, self.age)

_db.connect()
_db.create_tables([
    Teacher,
    Teacher.students.get_through_model(),
])

main.py
from model1 import *
from model2 import *

if __name__ == '__main__':
    Teacher.students.through_model.delete().execute()
    Teacher.delete().execute()
    Student.delete().execute()

    s1 = Student.create(name='s1', sex='male')
    s2 = Student.create(name='s2', sex='female')

    t1 = Teacher.create(name='t1', age=20)
    t1.students.add(s1)
    t1.students.add(s2)

    t1.sample_student = s1
    t1.save()

    print(t1.sample_student)  # ForeignKeyField works!

    [print(s) for s in Student.select()]
    [print(t) for t in Teacher.select()]

    for s in t1.students:    # crash here: peewee.OperationalError: no such table: teacher_student_through
        print(s)

For the table teacher_student_through, it exists in db2.sqlite database actually. So, is this a bug of peewee or wrong usage of mine?

A: Instead of using the database object for Meta.database, I redesigned the meta model initialization with database proxy for my python package.
_db_proxy = DatabaseProxy()

class PeeweeModel(Model):
    class Meta:
        database = _db_proxy

# skip the other subclass models implementation here...

def setup_database(dbpath):
    '''Initialize database.'''

    database = SqliteDatabase(dbpath)
    _db_proxy.initialize(database)

    database.connect(reuse_if_open=True)
    database.create_tables([
        Model1,
        Model2,
    ])

    return database

The package caller now has the responsibility to initialize the database object, see more documentation about this.
The public PeeweeModel is also available for the high-level python package to extend the database tables, just use it as a common super model class.


text:
Q: html5 multiplayer advice I hope this is okay to ask here as its more a request for advice than a technical problem.
I have been developing a game using html5+js and my goal was to make it multiplayer.  It's a dungeon crawling game and my intent is to have a main village where all players online and in the village can see each other going about and talk and form parties but when a player enters a dungeon its a seperate instance for them and their party.  Party size maxium of 4.
My intention was to use websockets and write a server in c#.  The problem is I just found out that IE does not support websockets and is still holding around 25% of the browser market share.
my options seem to be to use websockets anyway and cut out the IE crowd or maybe drop multiplayer support.  Someone else suggested that I just write world data to a database and have players read from it every frame and update that way.. it sounds horriable.
I found this socket.io thing that seems like it can use websockets OR do the same deal in other ways - but how does this effect me writing a server?  If I use the c# implementation of websockets and socket.io will IE users be able to talk to my server?
Or there may be other ways of doing client->server communication that I don't even know about.
To be completely honest i'm tempted to drop the multiplayer idea!  But before I do I look to you guys for advice and experienced suggestions on how I could handle this.  Thanks for your time and I hope this kind of question is okay here :)

A: Do not drop the multiplayer idea! It's way cooler with multiplayer. :)
Socket.io is a Server-Side JavaScript library. This means that you need Node JS server for it. IE users will be able to talk with Socket.io server, because it uses other protocols if WebSockets are not available. For example: FlashSocket or XHR long-polling. The last technique is available in every browser that supports XHR, but it is inefficient.
The greatest advantage of socket.io is the fallback. You can set it to start with any protocol (like WebSockets) and if the client does not support it, then it tries the others. It is really great, since you can use WebSockets (which will slowly but surely dominate web apps) and still work with browsers which do not support it, like IE or Opera or Safari. I don't know whether there is any other library with this advantage.
I don't know any library for real-time connections for C# (I'm not a C# developer), but it is unlikely that there are none (look at this question). Also note that real-time connections require a bit different server architecture then normal HTTP requests, so probably you will need additional server for handling them.
Also I think that neither nginx nor Apache handle WebSockets (without some hard core tricks) at the moment (but Node JS does!). I'm not sure though.

A: There is no reason to lock yourself in platform-wise for something as simple as transport. Support for these things change over time, and you will want to decouple yourself from them as much as possible. You are, after all, making a game, not a network tech demo.
Have a look at Orbited/Orbited2 TCPSocket. You can write your server as standard TCP in whatever manner you like. This also makes life easier if you decide to make a native client.


text:
Q: Custom Status Bar Color when using WKWebView I am trying to change the status bar color to match the color of a header in my app. The problem is, the app is just a WKWebView loading a web app inside it, so I need to set the status bar to match a header of a website.
I have been trying to figure this out, and have tried several things:

*

*Setting the tint/background color of the main view

*Setting the tint/background color of the WKWebView

*Setting the UINavigationBarStyle

I haven't been able to get it to work at all.
For reference, here is a picture of the main bar (inside the WKWebView, and the status bar. I need a way to make them the same color.

EDIT: I found a solution here, but it only works on the iPhone 8 and below. This solution doesn't work on the iPhone X or above because there is no way to modify it so that it always fits the height of the status bar. Not that I can find at least.

A: Make following change in AppDelegate.siwft didFinishLaunchingWithOptions method
    UINavigationBar.appearance().barTintColor = .init(red: 65.0/255, green: 151.0/255, blue: 176.0/255, alpha: 1.0)
    UINavigationBar.appearance().tintColor = .white
    UINavigationBar.appearance().titleTextAttributes = [.foregroundColor: UIColor.white]
    UINavigationBar.appearance().isTranslucent = false


text:
Q: Hashmap within ArrayList in Java There is a hash map within the ArrayList. the output is like below
[{A=2},{A=3},{B=1},{B=4},{A=3}]

Below I have mentioned my code sample
ArrayList<Map<String, Short>> deviceInfo = new ArrayList<>();
Map<String, Integer> rssiMapper = new HashMap<>();

rssiMapper.put(device.getName(), rssi);
deviceInfo.add(rssiMapper);

I want to take mean value of A and B separately. How can I achieve that

A: Try it like this.
List<Map<String,Integer>> list = List.of(
    Map.of("A", 2),
    Map.of("A", 3),
    Map.of("B", 1),
    Map.of("B", 4),
    Map.of("A", 3));

Map<String, Double> avgs = list.stream()
    .flatMap(m -> m.entrySet().stream())
    .collect(Collectors.groupingBy(
        Entry::getKey,
        Collectors.averagingInt(Entry::getValue)));
System.out.println(avgs);

Prints
{A=2.6666666666666665, B=2.5}

As was suggested, if you are unfamiliar with streams, here is an iterative approach.
Map<String,Double> avgs = new HashMap<>();
Map<String,Integer> count = new HashMap<>();
for (Map<String,Integer> map : list) {
     for (Entry<String,Integer> e : map.entrySet()) {
         String key = e.getKey();
         int value = e.getValue();
         // These just either initialize or update the appropriate
         // values.
         avgs.compute(key, (k,v)-> v == null ? value : v + value);
         count.compute(key, (k,v)->v == null ? 1 : v + 1);
     }
}
// now find the averages.
for(Entry<String,Double> e : avgs.entrySet()) {
    avgs.computeIfPresent(e.getKey(), (k,v)->v/count.get(e.getKey()));
}

System.out.println(avgs);

A: You can create maps to track the sum, count and the mean (i.e. sum / count) of the entries as shown below:
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class Main {
    public static void main(String[] args) {
        List<Map<String, Integer>> list = List.of(Map.of("A", 2), Map.of("A", 3), Map.of("B", 1), Map.of("B", 4),
                Map.of("A", 3));
        Map<String, Integer> sumMap = new HashMap<>();
        Map<String, Integer> countMap = new HashMap<>();
        Map<String, Double> meanMap = new HashMap<>();
        for (Map<String, Integer> map : list) {
            for (Entry<String, Integer> entry : map.entrySet()) {
                sumMap.put(entry.getKey(), sumMap.getOrDefault(entry.getKey(), 0) + entry.getValue());
                countMap.put(entry.getKey(), countMap.getOrDefault(entry.getKey(), 0) + 1);
                meanMap.put(entry.getKey(),
                        (double) sumMap.getOrDefault(entry.getKey(), 0) / countMap.getOrDefault(entry.getKey(), 1));
            }
        }

        // Display
        System.out.println(meanMap);
    }
}

Output:
{A=2.6666666666666665, B=2.5}


text:
Q: python sorted function is not performing numeric sort as expected I have the following code:
dict1={'1':'Ajay','1201':'Badol','102':'Cynthia','2':'Ravi','201':'John'}
for key,val in sorted(dict1.items()):
    print (key,val)

The Output I got:
('1', 'Ajay')
('102', 'Cynthia')
('1201', 'Badol')
('2', 'Ravi')
('201', 'John')

I was expecting:
('1', 'Ajay')
('2', 'Ravi')
('102', 'Cynthia')
('201', 'John')
('1201', 'Badol')

How to achieve this ?

A: It's sorted as string, char by char. You need to convert it to integer in order to be sorted as numbers.
for key,val in sorted(dict1.items(), key=lambda x: int(x[0])):
    print (key,val)

A: I would do, convert the key to int:
dict(sorted({int(k):v for k,v in dict1.items()}.items()))

{1: 'Ajay', 2: 'Ravi', 102: 'Cynthia', 201: 'John', 1201: 'Badol'}

Explanation:
1.{int(k):v for k,v in dict1.items()}: converts each key to int
2. sorted({int(k):v for k,v in dict1.items()}.items()): calls the sorted function on the dictionary based on its keys.
3. dict: sorted function above returns a list of tuples, hence we need to dict it again.

A: Since your keys are strings you get "string" order.
You can provide your own key like this:
>>> for key in sorted(dict1.items(), key=lambda item: int(item[0])):
...   print(key, val)
...
('1', 'Ajay') John
('2', 'Ravi') John
('102', 'Cynthia') John
('201', 'John') John
('1201', 'Badol') John

This treats the leys as numbers, giving what I think you want.


text:
Q: Tailwind import failed
Hi,

I'm trying to build an app using Tailwind and NextJs with some style in SCSS. Everything was working find and I was tweaking some Tailwind class in my components until the app suddenly crashed with this message

./node_modules/next/dist/build/webpack/loaders/css-loader/src/index.js??ruleSet[1].rules[3].oneOf[10].use[1]!./node_modules/next/dist/build/webpack/loaders/postcss-loader/src/index.js??ruleSet[1].rules[3].oneOf[10].use[2]!./node_modules/next/dist/build/webpack/loaders/resolve-url-loader/index.js??ruleSet[1].rules[3].oneOf[10].use[3]!./node_modules/next/dist/compiled/sass-loader/cjs.js??ruleSet[1].rules[3].oneOf[10].use[4]!./styles/globals.scss
TypeError: Cannot read properties of undefined (reading '5')

It appeared just like this, it worked for 3 hours and then just stopped, I did not changed any config files or anything else. I don't understand. After some time looking trough my code I've found that if I remove these import at the top of my global.scss the app works fine, but I don't know where this undefined variable is..

@tailwind base;
@tailwind components;
@tailwind utilities;

here is my tailwind config
module.exports = {
  purge: ['./pages/**/*.{js,ts,jsx,tsx}', './components/**/*.{js,ts,jsx,tsx}'],
  darkMode: false,
  theme: {
    extend: {
      spacing: {
        '2/3': '66.666667%',
      },
      colors: {
        'lavander-grey': '#625F63',
        'lavander-indigo': '#9893DA'

      },
    },
  },
  variants: {
    extend: {},
  },
  plugins: [],

};

package.json

  "engines": {
    "node": ">=14.0"
  },
  "engineStrict": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "graphql": "^16.6.0",
    "graphql-request": "^5.0.0",
    "html-react-parser": "^3.0.4",
    "moment": "^2.29.4",
    "next": "13.0.3",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "react-multi-carousel": "^2.8.2",
    "sass": "^1.56.1",
    "swr": "^1.3.0"
  },
  "devDependencies": {
    "autoprefixer": "^10.4.13",
    "eslint": "^8.27.0",
    "eslint-config-airbnb": "^19.0.4",
    "eslint-config-next": "13.0.3",
    "eslint-plugin-import": "^2.26.0",
    "eslint-plugin-jsx-a11y": "^6.6.1",
    "eslint-plugin-react": "^7.31.10",
    "eslint-plugin-react-hooks": "^4.6.0",
    "postcss": "^8.4.19",
    "tailwindcss": "^3.2.4"

Postcss.config.js

module.exports = {
    plugins: {
      tailwindcss: {},
      autoprefixer: {},
    },
}

thanks for your help

I've tried to install some older Tailwind packages, wiped node_modules, made sure this was not my components the culprit, tried some Tailwind configurations,started a fresh dev server, did some intense googling

A: In order to write those:
@tailwind base;
@tailwind components;
@tailwind utilities;

you need to install postcss. 'postcss` is like webpack, uses plugins and evaluates them to modern CSS syntax that browser understand
 npm install -D tailwindcss postcss autoprefixer postcss-nesting

Then you should have postcss.config.js and have this config:
module.exports = {
  plugins: ["tailwindcss", "postcss-nesting", "autoprefixer"],
};

A: Tailwind is no longer using PurgeCSS under the hood with the release of their JIT compiler as of Tailwind 3.0.
Update the first line of your config to:
content: [
    "./app/**/*.{js,ts,jsx,tsx}",
    "./pages/**/*.{js,ts,jsx,tsx}",
    "./components/**/*.{js,ts,jsx,tsx}",
  ],

As shown in the docs, and be sure to include a postcss.config.js file.


text:
Q: When do you use the Lambda function? And why usually user with map(), filter() function? I studied that lamda function can be used immediately and discarded where it is needed. What is the relationship between map, filter and lamda?
wins = map(lambda x : 'img' + str(x), range(5))
wins = list(wins)

A: lambda is often used when there is a better/more efficient solution. While there are places to use lambda this isn't the most efficient or pythonic solution.
I'd suggest a list comprehension here as it's more readable and efficient for what you're doing.
>>> wins = [f'img{n}' for n in range(5)]
>>> wins
['img0', 'img1', 'img2', 'img3', 'img4']

If your version of python doesn't support f-strings use str.format
wins = ['img{}'.format(n) for n in range(5)]

Or if you want to use map then str.format works here too:
wins = list(map('img{}'.format, range(5)))


text:
Q: How to remove asynchronity from javascript? I am sorry for the general question, but I would really like this one to be handled.
I am used to programming languages live Java or PHP, where program executes line by line, but sometimes I use javascript when it has good libraries.
The asynchronity stuff drives me nuts.
document.body.innerHTML = "";
for(var i=0;i<3;i++){
    document.body.innerHTML+="Hi! ";
    alert();
}

I expect this piece of code to work like this:

*

*Delete the whole content of the "body" tag.

*Print "Hi! "

*Invoke alert.

*Print "Hi! ".

*Invoke alert

*Print "Hi! ".

*Invoke alert.

In reality it works like this:

*

*Invoke alert

*Invoke alert

*Invoke alert

*Delete the whole content of the "body tag".

*Print "Hi! ".

*Print "Hi! ".

*Print "Hi! ".

How to make javascript code behave like a normal program?
Thank you!
UPDATE:
The first duplicate suggestion is not a duplicate at all. It has completely different code (I don't even use setTimeout), different task and different explaination. Even if the answer to my question is hidden there somewhere (in the comment number 56 or something like that), it is so unclear, that should not be taken as a duplicate.
The selected solution in the second duplicate suggestion simply does not work:
function b(){
    document.body.innerHTML = ""; for(var i=0;i<3;i++){
        document.body.innerHTML+="Hi! ";
        alert();
    }
}
function c(){
    setTimeout(b, 1);
};
c();

So NO, NEITHER of these links are duplicates.

A: You can try something like this:

document.body.innerHTML = "";

function update() {
  document.body.innerHTML += "Hi! ";
  alert();
}
for (var i = 0; i < 3; i++) {
  setTimeout(update, 0);
}

Edit:
A bit ugly, but this should do the job

let i = 0;
document.body.innerHTML = "";
requestAnimationFrame(function next() {
  document.body.innerHTML += "Hi! ";
  i++;
  setTimeout(function() {
    alert();
    if (i < 3) {
      requestAnimationFrame(next);
    }
  }, 0)
})


text:
Q: Is there any way to get the value of a key using the key in laravel eloquent (similar to getting value from key in array) We can get the value of a key by $a['yourkey'] in PHP.
Is there any way to do this in laravel collection.

I just didn't want to use a loop so can i get the values under the key 340 without using a loop?
I want to code it this way in my view.
    @foreach($jobseeker[340] as $v){
        //Code here...
    }

A: The thing you are looking for is:
$jobseeker->get(340);


text:
Q: Converting Thread to an Async task in Android I have a list of products in a row in my UI with its respective values.
Product1 --- 10
Product2 --- 12
. . . . . . . . and so on

.
Each row can be clicked and a new custom dialog interface opens where the user can change the value and set new values. The problem is when I change the value and close the dialog box, the value doesn't get updated in the row. I have to open the dialog box and and close it again and then it gets updated. It always updates the "previous" value. For example, If I change Product1 from 10-12 and then open dialog again and change it to 13, it gets updated with "12". I'm using a thread in a separate utility method. I want to convert my Thread implementation to async task and use it in background of onPostExecute. How can I achieve this?
 static void saveMutation(final String productId,
                             final int mutationAmount,
                             final boolean isOpeningStock,
                             final String flightKey,
                             final FlightLegIdentifier fli,
                             final String crew, final String tabletId,
                             final AirFiApplication airFiApplication) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                StockMutation mutation = new StockMutation();
                mutation.setOpeningStock(isOpeningStock);
                mutation.setFlightKey(flightKey);
                mutation.setFli(fli);
                mutation.setProductId(productId);
                mutation.setCrew(crew);
                mutation.setMutationId(String.valueOf(UUID.randomUUID()));
                mutation.setTabletId(tabletId);
                mutation.setMutationAmount(mutationAmount);
                StockMutationDao dao = new StockMutationDao(SHARD_DB);
                dao.createOrUpdate(mutation);
                StockUtils.adjustStock(flightKey, fli, airFiApplication);
                StockUtils.setIsStockChanged(true);
            }
        }).start();
    }

A: problem is that UI can be updated only on UI(main) thread. You can use Handler or runOnUIThread() for updating on UI thread from Non-UI thread.
You can find lot of resources on google.


text:
Q: checkbox value is not getting select on checkbox click I am binding the checkbox value but when I click on checkbox that value is not getting reflected

                                    {{list?.name}}
                                    <input
                                           [(ngModel)]="list.isChecked"
                                           [ngModelOptions]="{standalone: true}"
                                           name="isChecked"
                                           type="checkbox"
                                           (click)="onApplyConcessions()"
                                           value="true">

onApplyConcessions() {
        if (!!this.concessionsApplicable.data && !!this.concessionsApplicable.isConcessionApplied) {
            this.isNoConcessionReasonReq = false;
            const concessionResArr = [];
            for (let i = 0; i < this.concessionsApplicable.data.length; i++) {

                if (!!this.concessionsApplicable.data[i].isChecked && this.concessionsApplicable.data[i].isChecked === true) {
                    concessionResArr.push(this.concessionsApplicable.data[i].id);
                }
            }
            if (concessionResArr.length === 0) {
                this.alertService.showWarningAlert('At least Select 1 concession before proceeding forward');
                return false;
            }
            this.quoteConcessions = {
                'concessionApplied': 'yes',
                'concessions': concessionResArr
            };
        }
        this.applyConcession.emit(this.quoteConcessions);
    }

in 'concessionApplicable' array i am not getting the key 'isChecked' so in that case when I am comparing the value it shows undefined.

A: try to using change() event

        {{list?.name}}
        <input [(ngModel)]="list.isChecked" [ngModelOptions]="{standalone: true}" name="isChecked" type="checkbox"
            (change)="onApplyConcessions()" value="true">


text:
Q: split column to two according dataframe values I have a dataframe like:
library(tidyverse)

tib <- tibble(Dis = c("One", "One", "Two", "Three", "Three"),
             Spray = c("F1", "F1", "F2", "other", "nj"),
             freq= c(80, 20, 1.34, 15.3, 20.2),
             Nom = c("A", "B", "C", "C", "D") )

and I have a dataframe:
f <- c("F1", "F2", "F3", "F4", "F5", "F6", "F7")
s <- c("other", "nj", "na", "ker", "dsf", "dsf", "rth")

fs <- data.frame(f, s)

As you can see the dataframe contains the values of Dis and Spray columns. Every one corresponds to the other.
I want to split the Spray column to two columns according to the data frame.
So, I want the result:
Dis   Spray  freq  Nom    f     s
<chr> <chr> <dbl> <chr> <chr> <chr>
1 One   F1    80    A    F1    other
2 One   F1    20    B    F1    other
3 Two   F2    1.34  C    F2    nj
4 Three other 15.3  C    F1    other
5 Three nj    20.2  D    F2    other

General, I have created the dataframe of f and s to use it as a list with corresponding values. The size of this dataframe with the size of initial tib dataframe will be different!

A: I don't see a way to split the column, but you can use a combination of left_join() and mutate() to achieve the desired output.
library(tidyverse)

tib %>%
    left_join(fs, by = c("Spray" = "s"))
#> # A tibble: 5 x 5
#>   Dis   Spray  freq Nom   f
#>   <chr> <chr> <dbl> <chr> <chr>
#> 1 One   F1    80    A     <NA>
#> 2 One   F1    20    B     <NA>
#> 3 Two   F2     1.34 C     <NA>
#> 4 Three other 15.3  C     F1
#> 5 Three nj    20.2  D     F2

tib %>%
    left_join(fs, by = c("Spray" = "s")) %>%
    left_join(fs, by = c("Spray" = "f"))
#> # A tibble: 5 x 6
#>   Dis   Spray  freq Nom   f     s
#>   <chr> <chr> <dbl> <chr> <chr> <chr>
#> 1 One   F1    80    A     <NA>  other
#> 2 One   F1    20    B     <NA>  other
#> 3 Two   F2     1.34 C     <NA>  nj
#> 4 Three other 15.3  C     F1    <NA>
#> 5 Three nj    20.2  D     F2    <NA>

# Desired output
tib %>%
    left_join(fs, by = c("Spray" = "s")) %>%
    left_join(fs, by = c("Spray" = "f")) %>%
    mutate(f = if_else(is.na(f), Spray, f),
           s = if_else(is.na(s), Spray, s))
#> # A tibble: 5 x 6
#>   Dis   Spray  freq Nom   f     s
#>   <chr> <chr> <dbl> <chr> <chr> <chr>
#> 1 One   F1    80    A     F1    other
#> 2 One   F1    20    B     F1    other
#> 3 Two   F2     1.34 C     F2    nj
#> 4 Three other 15.3  C     F1    other
#> 5 Three nj    20.2  D     F2    nj

Created on 2021-03-08 by the reprex package (v0.3.0)

A: something like this? (I think your expected output is of in row 5, if not I dont know what you are looking for :p)
tib$f <- NA
tib$s <- NA
c <- 1

for (i in tib$Spray){
  if (i %in% f){
    tib$f[c] <- i
    is <- match(i,f)
    tib$s[c] <- s[is]
    c <- c + 1
  }
  else{
    is <- match(i,s)
    tib$f[c] <- f[is]
    tib$s[c] <- i
    c <- c + 1
  }
}


text:
Q: Send RControl keystroke from VBA Macro I'm working on a VBA macro which needs to send a series of keystrokes.  For this application, I need to send a keystroke for Right Control.  Just the normal control is not sufficient.  I've seen the SendKeys method, but I don't see where you can specify which Control key is sent.  I'm hoping it's a quick and simple answer.  Thanks!
P.S. I'm still learning SO, so please let me know if I need to add or change something to comply with community standards.  I'll be glad to modify the post.  Thanks!

A: Have you tried using : {RCTRL}
https://www.autoitscript.com/autoit3/docs/appendix/SendKeys.htm


text:
Q: Optimizing if statements in angular I have following code with multiple 'if' statements.
if($scope.level===1){

    $scope.leftWordList=true
    $scope.previewViewRight=true

    $scope.counter1=5
    $timeout($scope.startFilling, 5000)
    $scope.onTimeout = function(){

      $scope.counter1--;
      mytimeout = $timeout($scope.onTimeout,1000);

      if($scope.counter1==0){
        $timeout.cancel(mytimeout);
        $scope.counter=0
      }
    }
    var mytimeout = $timeout($scope.onTimeout,1000);

  }

  if($scope.level===2){

    console.log("Level 2")

    $scope.leftWordList=true
    $scope.previewViewRight=true

    $scope.counter2=5
    $timeout($scope.startFilling, 5000)
    $scope.onTimeout = function(){

      $scope.counter2--;
      mytimeout = $timeout($scope.onTimeout,1000);

      if($scope.counter2==0){
        $timeout.cancel(mytimeout);
      }
    }
    var mytimeout = $timeout($scope.onTimeout,1000);
  }
  ....

$scope.level goes on till 7, and most of the code inside 'if' is same except for few statements, so I guess there is definitely a scope for optimizing it, but I do not exactly know how.
How can I do this?
UPDATE:
Removed incorrect description of problem statement.

A: When you find yourself with a long list of mutually-exclusive branches like that, the question becomes: Are the branches fundamentally different, or are there commonalities that can be factored?
If they're fundamentally different, either a switch or a function dispatch table immediately comes to mind.
But in your case, it looks a lot like they're just the same logic with a different counter. If so, remove your individual counter properties (counter1, counter2, etc.) and replace them with an array of counters you can index into.
Then grab the level (because if the timeout, you want a consistent value rather than dealing with it having changed before the timeout occurred) and use that throughout, see the *** lines:
var level = $scope.level;                      // ***
console.log("Level " + level)                  // ***

$scope.leftWordList = true
$scope.previewViewRight = true

$scope.counters[level] = 5                     // ***
$timeout($scope.startFilling, 5000)
$scope.onTimeout = function() {

    $scope.counters[level]--;                  // ***
    mytimeout = $timeout($scope.onTimeout, 1000);

    if ($scope.counter[level] == 0) {          // ***
        $timeout.cancel(mytimeout);
    }
}
var mytimeout = $timeout($scope.onTimeout, 1000);

Note that this assumes all of this code is within a function and so the mytimeout and level aren't shared with other invocations of the function.

A: Based on given code, you can make it generic if you change a bit:

*

*You can have a counter object and then based on level, you can update necessary flag.

*If you have any common logic that is applicable for most, then add it before your ifs and reset then in necessary if.

*If your counter has reached 0, you should not initiate a timeout and then clear it. Just check condition before initializing it.

*Your function onTimeout has a similar signature in both ifs. Try to make it a function, rather than copying it in all ifs

Sample Code:
$scope.counter = {
  counter1: null,
  counter2: null,
}

.
.
.

// if block
$scope.leftWordList = true;
$scope.previewViewRight = true;

$scope.counter["counter" + $scope.level] = 5
$timeout($scope.startFilling, 5000)
var mytimeout = $timeout($scope.onTimeout.bind(this, $scope.counter, $scope.level), 1000);

.
.
.

// Generic function
$scope.onTimeout = function(counter, level) {
  if (--$scope.counter["counter" + level] === 0)
    mytimeout = $timeout($scope.onTimeout, 1000);
  else
    $scope.counter = 0
}

Note: I'm assuming you are setting $scope.counter somewhere else. Hence I have reset it in else condition.

A: You can build an object that will help you.
The object will contain all your defenitions of the things that differ from level to level, and the rest you can place inside a "switch-case"
Something like this:
lvlObjects = [];
lvlObject = {};
lvlObject.level = 1;
lvlObject.leftWordList = true;
lvlObject.previewViewRight = true;
....
lvlObjects.push(lvlObject);
//same for more levels.
//then call to a function that fill the scope with current values:
function updateLevel(currentLevel) {
    $scope.level = lvlObjects[currentLevel-1].level; //if needed
    $scope.leftWordList = lvlObjects[currentLevel-1].leftWordList;
    ....
}


text:
Q: Overriding views from main app in engine I am presently working with themes. I need to write a function in the main application_controller to add a path in the engine_controller so that it looks for views in the main app themes before looking for the same views in the Engine.
I do not wish to make any edits to the engine i have made and the view path must be prepended to the engine view load path from the Main application application_controller.


text:
Q: CryptoSwift cannot use swift 2 I would like to use https://github.com/krzyzanowskim/CryptoSwift on my swift project (my swift is 2.1 and Xcode 7.1.1). After I had completed the installation instruction (run build.sh then add the framework file to my project), I still cannot import CryptoSwift framework. Please help.

A: Add the CryptoSwift.framework to the Embedded Binaries section, instead of the Linked Frameworks and Libraries section. Xcode will then include it in the Linked Frameworks and Libraries section as well.

A: Thank you all to answer. I had installed the program by using Cocoapods. Issue is solved


text:
Q: How can i pass the future Time to Wake up the Pending Intent? I'm newer to android and i need to setup the event notification via broadcast receiver .
For now i'm passing the hard coded Time to get the Notification it's working properly... How can i pass the some future time to get the notification at that time...
Tried Code:
   EditText text = (EditText) findViewById(R.id.editText1);
       int time = Integer.parseInt(text.getText().toString());
       Intent intent = new Intent(this, MyReceiver.class);
       PendingIntent pend_intent = PendingIntent.getBroadcast(
                   this.getApplicationContext(), 0, intent, 0);
//calls the alarm
        AlarmManager alarmManager = (AlarmManager) getSystemService(
                               ALARM_SERVICE);
        alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
          + (time * 10000), pend_intent);

A: Use Calendar.getInstance()  to set future time for AlarmManager. for example:
Prepare a Calendar instance with future time when you want to set Aalarm:
public  Calendar cal = Calendar.getInstance();
    cal.set(Calendar.HOUR_OF_DAY, hour);
    cal.set(Calendar.MINUTE, minutes);
    cal.set(Calendar.DAY_OF_MONTH, day);
    cal.set(Calendar.MONTH, month) - 1);
    cal.set(Calendar.YEAR, year);

Now pass cal.getTimeInMillis() as second parameter instead of System.currentTimeMillis()+ (time * 10000) in alarmManager.set

A: Use Calancer to get time in millis.
For e.g.
Calendar mCalendar = Calendar.getInstance();
mCalendar.setTimeInMillis(System.currentTimeMillis());

Now into you Alarm manager set method, Use Set Method like this.
mAlarmManager.set(AlarmManager.RTC_WAKEUP, mCalendar.getTimeInMillis()
            + mTime * 10000, mPendingIntent);

Hope It Helps
Cheers
-Aman


text:
Q: Adding a test certificate for SSL on heroku is failing I followed the steps outlined here https://devcenter.heroku.com/articles/ssl-certificate-self to add a test certificate for SSL endpoint at heroku
When i try to add it by running 'heroku certs:add server.crt server.key'
I get the following error:
!    Invalid certificate or key. Please verify that your files contain a valid chain of trust, or contact support@heroku.com
Anybody have an idea what I'm missing and how to resolve this?
Thanks

A: There are some problems with indeed, but you can try using ssldoctor: https://github.com/heroku/heroku-ssl-doctor


text:
Q: how to remove an item in a javascript array with json form i have this json structure and I made it into an array. I was trying to remove the entry, but this code failed on me: Remove item from array if it exists in a 'disallowed words' array
var historyList = []; // assuming this already has the array filled

function add() {
     var newHistory = {
                ID: randomString(),
                Name: $('#txtVaccineName').val(),
                DoseDate: doseDate,
                ResultDate: resultDate,
                Notes: $('#txtResultNotes').val()
            };
     historyList.push(newHistory);
};

function removeEntry(value) {
  historyList.remove('ID', value);
};

Array.prototype.remove = function(name, value) {
            array = this;
            var rest = $.grep(this, function(item) {
                return (item[name] != value);
            });

            array.length = rest.length;
            $.each(rest, function(n, obj) {
                array[n] = obj;
            });
        };

A: You could use a property filter to match the item in your history list. Below is the sample quick code to do so, I've modified your history list a bit.
A quick test in FF, shows that it works!
var historyList = []; // assuming this already has the array filled

function addToHistory(name, notes) {
     var newHistory = {
          ID: new Date().getTime(),
          Name: name,
          DoseDate: "Somedate",
          ResultDate: "SomeResultDate",
          Notes: notes,
          toString: function() {return this.Name;}
     };
     historyList.push(newHistory);
};

var Util = {};

/**
 * Gets the index if first matching item in an array, whose
 * property (specified by name) has the value specified by "value"
 * @return index of first matching item or false otherwise
 */
Util.arrayIndexOf = function(arr, filter) {
   for(var i = 0, len = arr.length; i < len; i++)  {
      if(filter(arr[i]))   {
         return i;
      }
   }
   return -1;
};

/**
 * Matches if the property specified by pName in the given item,
 * has a value specified by pValue
 * @return true if there is a match, false otherwise
 */
var propertyMatchFilter = function(pName, pValue)  {
   return function(item) {
      if(item[pName] === pValue) {
         return true;
      }
      return false;
   }
}

/**
 * Remove from history any item whose property pName has a value
 * pValue
 */
var removeHistory = function(pName, pValue)   {
   var nameFilter = propertyMatchFilter(pName, pValue);
   var idx = Util.arrayIndexOf(historyList, nameFilter);
   if(idx != -1)  {
      historyList.splice(idx, 1);
   }
};

// ---------------------- Tests -----------------------------------
addToHistory("history1", "Note of history1");
addToHistory("history2", "Note of history2");
addToHistory("history3", "Note of history3");
addToHistory("history4", "Note of history4");

alert(historyList); // history1,history2,history3,history4

removeHistory("Name", "history1");

alert(historyList); // history2,history3,history4

removeHistory("Notes", "Note of history3");

alert(historyList); // history2,history4

A: The entire Array.prototype.remove function can be inlined as follows:
function removeEntry(value) {
  historyList = $.grep(historyList, function(item) {
    return (item.ID !== value);
  });
}

You can, of course, create a function to wrap $.grep or the predicate as you wish.  (And if you do, you probably don't want to modify Array.prototype; prefer modifying historyList itself (using Array.prototype.splice) or creating a (likely static) function elsewhere.)
Also, this problem does not relate to the SO question you mention in your question, as far as I can tell.


text:
Q: TypeScript Proper Unhandled promise rejection for aws-sdk I'm trying to return the name of an AWS Secrets Manager Secret.
I have a working example WHEN it finds a match for my param, but throws the UnhandledPromiseRejectionWarning:Unhandled promise rejection
Looking for help on how to handle the rejection (or suppress it) and print out the name (if it exists) or print secret doesn't exist if it doesn't.
// Set Params for Describe Secret
const params = {SecretId: `${dir.name}`};

const response = sm.describeSecret(params).promise()

console.log((await response).Name)

I haven't been able to find much related to TS only JS. I'm also fairly new to JS/TS

A: Figured out how to do what I wanted
const response = await sm.describeSecret(params).promise()
 .then((data) => data.Name).catch(() => {})


text:
Q: Optimal mount options for Windows Server 2012 R2 The Problem
I have a directory that is shared by a Windows Server 2012 R2. Some Linux clients (Ubuntu 14.04) mount this share via /etc/fstab:
//10.1.1.1/MyShare /mnt/myshare cifs rw,nounix,noserverino,sec=ntlm,_netdev,iocharset=utf8,user=myuser,password=mypassword,uid=1000,gid=1000 0 0

Although working perfectly for some time, every now and then (e.g., after 1-2 hours) the mount becomes inaccessible and all processes using (or trying to access) it hang for about 5 minutes. After that, normal operation continues again for a few hours when it hangs again. Windows clients can access the share without any problem.
Before migrating to Windows Server 2012 R2, the directory was shared by a Windows 7 VM running on a Windows Server 2008. This worked perfectly fine (for the same Linux client configuration).
I can see four possible causes for the malfunction:

*

*Bug in Windows Server 2012 R2

*Bug in cifs-utils

*Network/hardware problems (unlikely because no problems with Windows clients)

*Wrong configuration of sharing/mounting

The Question
The purpose of this question is basically to eliminate the possibility of wrong server or client configuration by asking how the correct/optimal setup should look like. Of course, any other hint is welcome, too.
1. Linux Side
What mount.cifs options should I use to mount a Windows Server 2012 R2 Share in Linux (via fstab)?
E.g., what about the optimal values for vers, sec, iocharset, etc? Should I use nounixor noserverino or any other parameters?

Additional information:

*

*Authentication is done using a local user on the Windows Server, so the Acitve Directory/domain should not be involved.

*CIFS Version 2.02

*$ mount.cifs -V
mount.cifs version: 6.0

*$ cat /proc/version
Linux version 3.13.0-45-generic (buildd@phianna) (gcc version 4.8.2 (Ubuntu 4.8.2-19ubuntu1) ) #74-Ubuntu SMP Tue Jan 13 19:36:28 UTC 2015

2. Windows Side
Are there any special settings on the Windows Server side to improve the Windows/Linux interoperability?

@mods: Please do not migrate this to Unix & Linux because I had already posted it there 3 months ago (and deleted it now as no one has posted an answer).


text:
Q: ols_step_all_possible in R not working with variables with numbers I have a linear regression model that was already done through the "lm" function and I want to perform the "ols_step_all_possible" function on it. Problem is that the dependent variable begins with "2020" (and for descriptive purposes, I don't think it makes sense to remove the number from the variable names). For the lm function I used `` to signify that it's a variable name, but when I perform olsrr on the model I get:
Error in str2lang(x) : <text>:1:5: unexpected input
1: 2020_
        ^

Does anyone know how to get around this?


text:
Q: #MYSQL facing error 1136 column count doesn't match value count at row 1 I am trying to execute the below query through a java program.
mysql> INSERT INTO TRANSACTION_DETAILS
 (txn_id,txnd_stocksymbol,price,qty) values('1000400058','TFSCU','10.27','10');

ERROR 1136 (21S01): Column count doesn't match value count at row 1

However, I am facing error 1136.
I have the same count of fields and values.
My table description is :
mysql> desc transaction_details;
+------------------+--------------+------+-----+---------+-------+
| Field            | Type         | Null | Key | Default | Extra |
+------------------+--------------+------+-----+---------+-------+
| txn_id           | int(11)      | YES  |     | NULL    |       |
| txnd_stocksymbol | varchar(10)  | YES  |     | NULL    |       |
| price            | decimal(7,2) | YES  |     | NULL    |       |
| qty              | int(10)      | YES  |     | NULL    |       |
+------------------+--------------+------+-----+---------+-------+
4 rows in set (0.01 sec)

Please suggest what I am missing.


text:
Q: spring-data-mongodb: Method findAndReplace, findAndModify... and auditing I have a couple of questions about the method findAndReplace of spring-data-mongodb:

*

*Is this operation really atomic?

*What is the reason for the methods
findAndReplace, findAndModify... methods not trigger the auditing
event?
 @Autowired
MongoOperations mongoOperations;
...
public void persist() {

        final Query query = new Query();
        query.addCriteria(where("id").is(product.getId()));

        mongoOperations.findAndReplace(query, entity, new FindAndReplaceOptions().upsert().returnNew());

Thank you


text:
Q: D3 Grouped Bar Chart From Arrays I'm really having trouble with D3 and need some help changing my existing barchart to be a grouped barchart The barchart is being used within a tooltip and currently looks like:

Each colour represents a sector of industry (pink = retail, teal = groceries...etc).
I need to change the bar chart so that it compares the percentage change in each industry with the world average percentage change in this industry.
At the moment the bar chart is being created from an array of data. I also have an array with the world percentage values.
So imagine:
countryData = [10,-20,-30,-63,-23,20],
worldData = [23,-40,-23,-42,-23,40]
Where index 0 = retail sector, index 1 = grocery sector, etc.
I need to plot a grouped barchart comparing each sector to the world average (show the world average in red). This is a bit tricky to explain so I drew it for you (...excuse the shoddy drawing).

Please can someone help me change my existing tooltip?
Here's the current code. If you want to simulate the data values changing.
If you want to scrap my existing code that's fine.
 .on('mouseover', ({ properties }) => {
        // get county data
        const mobilityData = covid.data[properties[key]] || {};

      const {
        retailAverage,
        groceryAverage,
        parksAverage,
        transitAverage,
        workplaceAverage,
        residentialAverage,
      } = getAverage(covid1);

      let avgArray = [retailAverage, groceryAverage, parksAverage, transitAverage, workplaceAverage, retailAverage];
      let categoriesNames = ["Retail", "Grocery", "Parks", "Transit", "Workplaces", "Residential"];

        // create tooltip
        div = d3.select('body')
          .append('div')
          .attr('class', 'tooltip')
          .style('opacity', 0);

        div.html(properties[key]);

        div.transition()
          .duration(200)
          .style('opacity', 0.9);

        // calculate bar graph data for tooltip
        const barData = [];

        Object.keys(mobilityData).forEach((industry) => {
          const stringMinusPercentage = mobilityData[industry].slice(0, -1);
          barData.push(+stringMinusPercentage); // changing it to an integer value, from string
        });

        //combine the two lists for the combined bar graph
        var combinedList = [];
        for(var i = 0; i < barData.length; i++) {
          const stringMinusPercentage2 = +(avgArray[i].slice(0, -1));
          const object = {category: categoriesNames[i], country: barData[i], world: stringMinusPercentage2}
          combinedList.push(object); //Push object into list
        }
        console.log(combinedList);

        // barData = barData.sort(function (a, b) {  return a - b;  });
        // sort into ascending ^ keeping this in case we need it later
        const height2 = 220;
        const width2 = 250;
        const margin = {
          left: 50, right: 10, top: 20, bottom: 15,
        };

        // create bar chart svg
        const svgA = div.append('svg')
          .attr('height', height2)
          .attr('width', width2)
          .style('border', '1px solid')
          .append('g')
        // apply the margins:
          .attr('transform', `translate(${[`${margin.left},${margin.top}`]})`);

        const barWidth = 30; // Width of the bars

        // plot area is height - vertical margins.
        const chartHeight = height2 - margin.top - margin.left;

        // set the scale:
        const yScale = d3.scaleLinear()
          .domain([-100, 100])
          .range([chartHeight, 0]);

        // draw some rectangles:
        svgA
          .selectAll('rect')
          .data(barData)
          .enter()
          .append('rect')
          .attr('x', (d, i) => i * barWidth)
          .attr('y', (d) => {
            if (d < 0) {
              return yScale(0); // if the value is under zero, the top of the bar is at yScale(0);
            }

            return yScale(d); // otherwise the rectangle top is above yScale(0) at yScale(d);
          })
          .attr('height', (d) => Math.abs(yScale(0) - yScale(d))) // the height of the rectangle is the difference between the scale value and yScale(0);
          .attr('width', barWidth)
          .style('fill', (d, i) => colours[i % 6]) // colour the bars depending on index
          .style('stroke', 'black')
          .style('stroke-width', '1px');

        // Labelling the Y axis
        const yAxis = d3.axisLeft(yScale);
        svgA.append('text')
          .attr('class', 'y label')
          .attr('text-anchor', 'end')
          .attr('x', -15)
          .attr('y', -25)
          .attr('dy', '-.75em')
          .attr('transform', 'rotate(-90)')
          .text('Percentage Change (%)');

        svgA.append('g')
          .call(yAxis);
      })
      .on('mouseout', () => {
        div.style('opacity', 0);
        div.remove();
      })
      .on('mousemove', () => div
        .style('top', `${d3.event.pageY - 140}px`)
        .style('left', `${d3.event.pageX + 15}px`));

    svg.append('g')
      .attr('transform', 'translate(25,25)')
      .call(colorLegend, {
        colorScale,
        circleRadius: 10,
        spacing: 30,
        textOffset: 20,
      });

  };

  drawMap(svg1, geoJson1, geoPath1, covid1, key1, 'impact1');
  drawMap(svg2, geoJson2, geoPath2, covid2, key2, 'impact2');
};

A: In short I would suggest you to use two Band Scales for x axis. I've attached a code snippet showing the solution.
Enjoy ;)

//Assuming the following data final format
var finalData = [
  {
    "groupKey": "Retail",
    "sectorValue": 70,
    "worldValue": 60
  },
  {
    "groupKey": "Grocery",
    "sectorValue": 90,
    "worldValue": 90
  },
  {
    "groupKey": "other",
    "sectorValue": -20,
    "worldValue": 30
  }
];
var colorRange = d3.scaleOrdinal().range(["#00BCD4", "#FFC400", "#ECEFF1"]);
var subGroupKeys = ["sectorValue", "worldValue"];

var svg = d3.select("svg");
var margin = {top: 20, right: 20, bottom: 30, left: 40};
var width = +svg.attr("width") - margin.left - margin.right;
var height = +svg.attr("height") - margin.top - margin.bottom;
var container = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// The scale spacing the groups, your "sectors":
var x0 = d3.scaleBand()
        .domain(finalData.map(d => d.groupKey))
    .rangeRound([0, width])
    .paddingInner(0.1);

// The scale for spacing each group's bar, your "sector bar":
var x1 = d3.scaleBand()
        .domain(subGroupKeys)
    .rangeRound([0, x0.bandwidth()])
    .padding(0.05);

var yScale = d3.scaleLinear()
  .domain([-100, 100])
  .rangeRound([height, 0]);

//and then you will need to append both, groups and bars
var groups = container.append('g')
  .selectAll('g')
  .data(finalData, d => d.groupKey)
  .join("g")
  .attr("transform", (d) => "translate(" + x0(d.groupKey) + ",0)");

//define groups bars, one per sub group
var bars = groups
  .selectAll("rect")
  .data(d => subGroupKeys.map(key => ({ key, value: d[key], groupKey: d.groupKey })), (d) => "" + d.groupKey + "_" + d.key)
  .join("rect")
  .attr("fill", d => colorRange(d.key))
  .attr("x", d => x1(d.key))
  .attr("width", (d) => x1.bandwidth())
  .attr('y', (d) => Math.min(yScale(0), yScale(d.value)))
  .attr('height', (d) => Math.abs(yScale(0) - yScale(d.value)));

//append x axis
container.append("g")
    .attr("class", "axis")
    .attr("transform", "translate(0," + height + ")")
    .call(d3.axisBottom(x0));

//append y axis
container.append("g")
    .attr("class", "y axis")
    .call(d3.axisLeft(yScale))
    .append("text")
    .attr("x", 2)
    .attr("y", yScale(yScale.ticks().pop()) + 0.5)
    .attr("dy", "0.32em")
    .attr("fill", "#000")
    .attr("font-weight", "bold")
    .attr("text-anchor", "start")
    .text("Values");
<script src="https://d3js.org/d3.v7.min.js"></script>

<svg width="600" height="400"></svg>


text:
Q: How to Sync more than 5000 items SharePoint Calendar to Outlook using Connect to Outlook Option How to Sync more than 5000 items in SharePoint Calendar to Outlook using Connect to Outlook Option. Getting error that "HTTP 500.  The server returned the following error message:  The attempted operation is prohibited because it exceeds the list view threshold enforced by the administrator."
Any Suggestion or Workaround will be appreciated.
Thanks in Advance.

A: This issue occurs because SharePoint Online uses the Large List Resource Throttling feature. By default, the list view threshold is configured at 5,000 items.
To work around this issue, you can manage your list as the article.


text:
Q: Where to put system partition on 12 disk hardware raid setup I'm going to rent a server with 12 SATA disks hardware raid(planned to be configured as raid5), and I'm wondering what's the best practice  where to put system partition in that case and the most efficient configuration. I'm going to use the server to serve static files, and the main reason for getting such a server is that I need lot's of space.

A: Totally impossible to answer. If that is going to be ONE raid 5 (which borders stupid if you ask me - I would at least make it raid 6, 12 discs it too many for a raid 5 in my eyes) then the only logical sense is "on all discs", as a separate first raid group. Otherwise you loose space (as the discs then have different free space). A Raid 10 or Raid 6 for the system is the only logical way to go.
Unless that is a pure file store, then the layout is disputable - if that is a database, I would split out some discs so I don't loose log and data at the same time.
I would say that is the nice time to put in a small SSD for the operating system. Many servers support that. But if not - well ;) A system partition, Raid 6 on all discs.


text:
Q: how to run sc.textFile() inside a foreach loop and do a union on it? so this is what I have been trying and I'm a newbie here working with spark!
I'm trying to execute this code
val ii=sc.parallelize(Seq(("e.txt"),("r.txt"))).foreach{i => sc.textFile(i)}

but I'm getting "Nullpointer exception"
Thanks!

A: You can just add multiple files to the sc.textFile. You should not use the sc inside of a map operation. The map function will be distributed to the different executors, and the sc lives in the driver. Therefore it will throw a Nullpointer exception.
a.txt contents:
a.txt:line1
a.txt:line2

b.txt contents:
b.txt:line1
b.txt:line2

Spark allows you to add more files in the same operation:
scala> sc.textFile("a.txt,b.txt").collect()
res1: Array[String] = Array(a.txt:line1, a.txt:line2, b.txt:line1, b.txt:line2)

Hope this helps and have fun with Spark!


text:
Q: jQuery selector for elements with name attribute How can I select elements which contains "name" attribute ?
Example of the elements :
<select id="itemPK.country.id_id" name="itemPK.country.id"><option value="7">India</option><option value="8">Malaysia</option></select>

<input id="point_id" name="point" type="number" value="">

A: $('[name]')

try this you can get all elements having name

A: The attribute selectors are what you need:
$('input[name="point"]')...
$('[name="something"]') //In case it's not specifically an <input> element

Good luck
Edit: I see, you may have asked for elements which contain a certain attribute, not those that contain X value in the name attribute. The answer provided by PSR is the way to go. This is the documentation for the "Has attribute" selector.

A: Use the attribute selector
$("*[name='point']")


text:
Q: Pack and install Node package in offline mode with yarn I try to add a package (not published) in my project in offline mode.

I configured the yarn-offline-mirror in the yarnrc of my project :
yarn-offline-mirror "./yarn-offline-mirror"

I modify manually the package.json :
 "dependencies": {
        "@xxx/yyy": "1.0.0",
 }

I packed my package :
yarn pack --filename @xxx/yyy@1.0.0
I moved manually the package @xxx/yyy@1.0.0 in the folder "yarn-offline-mirror" of my project.

I run in my project :
yarn install --offline

I obtain :

error Couldn't find any versions for "@xxx/yyy"
  that matches "1.0.0" in our cache (possible versions are
  ""). This is usually caused by a missing entry in the
  lockfile, running Yarn without the --offline flag may help fix this
  issue.

If I publish and install my package @xxx/yyy@1.0.0 in my project (in online mode)  and after, I reinstall in offline mode with yarn-offline-mirror, it works.
But I want pack and add my package @xxx/yyy@1.0.0 in my project without publish  my package (in the case where I have no internet connection).

A: I am pretty sure you have followed the blog which contains all the steps.
I followed it as well, there is an important point it is not obvious.
The yarn-offline-mirro is based on yarn.lock file (which is auto-generated after you run yarn install). That is key relevant point in the procedure and was not well highlighted in the blog post.
Install your package as whatever other package in "online" mode with yarn install and you will see the packages .tgz are in your [off-line-folder], then you can delete [node_modules] in your project folder eventually you can execute yarn cache clean or even move you offline, but NEVER delete the yarn.lock.
After that, yarn install --offline should work as expected.


text:
Q: Is Event Tracking in Google Analytics associated with built-in metrics? In Google Analytics (GA) I am working with Event Tracking and would like to do queries on Events, joining the with associated metrics such as Page, Source, etc. Within GA, Is an Event associated or related to these metrics or are they completely independent? This article (Google Analytics Event Tracking by Page) seems to suggest that they are related, but wanted to verify.

A: They are.
You can build custom reports that drill down from source to event categories and then actions and labels. Or custom reports that drill down from pages to events or the other way around.


text:
Q: g1 gc write barrier: exclusive-or and shifts I am reading the paper Garbage-First Garbage Collection (http://cs.williams.edu/~dbarowy/cs334s18/assets/p37-detlefs.pdf), in section 2.2 it mentions the write barrier. In order to filter out the object from the same region, it has the following code, when rTmp is 0 means rX and rY contains pointer from the same region
rTmp := rX XOR rY
rTmp := rTmp >> LogOfHeapRegionSize

But if assume LogOfHeapRegionSize is 4 (bin=100), and rX starts the address (bin 0), rY starts the address (bin 111), clearly, they are not in the same region, but apply the code above, we have
111 XOR 000 = 111
111 >> 4 = 0

gives they are in the same region, why? Am I understand the code in the right way?


text:
Q: Remove blobs of certain size from video mage OpenCV Python I have the following image coming from a segmentation network.
This is the representation of a road(white), ground(blue) and threes(green) which can be seen clearly in the input image below.

As you can see the segmented image has a lot of unwanted blobs and rough edges. I would like to filter out these blobs and clean the edges.
I have tried a couple of different methods:
First I tried to detect the blobs and then fill in the blobs. This works really well but the problem is that my blobs are not shaped like a circle or a square. So when filling them in, not only the blob but also a area around it is filled in.
def filterBlobs(image,size):

    imageGray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    # Detect blobs.
    keypoints = detector.detect(imageGray)

    for x in range(1,len(keypoints)):
        image=cv2.circle(image, (np.int(keypoints[x].pt[0]),np.int(keypoints[x].pt[1])), radius=np.int(keypoints[x].size), color=(0,255,0), thickness=-1)

return image

I have also tried to find all the contours with a certain size and fill those contours with a color. Only problem her is that if the contour is not closed it wont be filled. I tried to approximate the ploy of the contour with approxPolyDP and also tried convexHull but both did not gave nice results.
def filterContours(image,size):
    edged = cv2.Canny(image, 175, 200)

    cv2.imshow("canny", edged)

    contours, hierarchy = cv2.findContours(edged, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    #cv2.drawContours(image, contours, -1, (0,0,255), 100)

    for contour in contours:
        area = cv2.contourArea(contour)
        print(area)
        #if area < size:
            #cv2.drawContours(image,[contour],0,255,-1)
        cv2.fillPoly(image, pts =[contour], color=(0,0,255), maxLevel=2)
        #cv2.drawContours(image, [approx], -1, (0, 0, 255), 3)
        #hull = cv2.convexHull(cnt)

    return image

I have also tried medianblur. This gives a really nice smoothing of the edges but offcourse does not remove the blobs. I suspect the solution is a combination of medianblur and blob filling.
median = cv2.medianBlur(img, 21)

I also tried Morphological Transformations with open and close. While open gave the best result it was also not really good. This is because a lot of detail was lost with a large kernel size, there where still unwanted blobs and the edges where not smooth.
    kernel = np.ones((5,5),np.uint8)
    img = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel)

What I am ideally looking for is a method which cleans the segmented image in such a way that the segmented image clearly represents the road on the input image. And that all the noise from the segmented image is gone.
I think that it should look something like 4 blobs.
1 in the middle for the road
1 blob on both sides of the road for the ground
1 blob in the back representing the threes
Please also provide a Python code example if possible. A c++ example is also welcome I can translate it to Python.
Thanks Sieuwe
EDIT: Forgot to add that this is running real time from a video feed. A FPS of around 15 to 20 is my target. Any heavy processing which takes a long time is not possible. It is running on a i7 and GTX1080 so there is enough power for moderate processing.


text:
Q: How can I copy part of an iMessage message? - What prevents Apple and Google from offering this functionality? Starting from iOS 10, Apple changed1 the "tap and hold" gesture in Messages so that you cannot select just a couple of words from the messages to copy.
And, as far as I know, Google did the same with Android.
I don't believe that it was done to just introduce into messages "tapback" which uses the same long-tapping as text selection.
Is there any objective reason for consciously disabling text selection in Messages?
Are there legal or regulative reasons for disabling text selection in Messages?

A: Yes, there is an objective reason for consciously disabling text selection in messages. Possible there's even more than one.
The most obvious one is that it allows for introducing other features than text selection in messages by using the same touch gesture for those other features.
However it is not so that it is impossible to copy only part of a text message with iOS 10 and newer - it is just more complicated. You can copy part of a text message by tapping and holding on the message, select "More...", press the forward arrow, and then tap and hold on the text message to select as usual.
There are no legal or regulative requirements in the US or in Europe that explicitly requires Apple to not offer text selection in messages. There could however be a patent that prevents Apple from doing so without licensing.


text:
Q: How to get a child nested list within a record using EFCore Linq I have 3 Tables 1.Books 2.PO 3.Books_PO. I would like to pull a single PO record using books_po ref table but I want a list of books within that record.
 Books                    PO                 books_PO
ID   Name             ID    ponumber       poId    bookId
1    book1            3     1234           3       2
2    book2            5     2323           3       3
3    book3

My current query only brings back one book when I need a list of 2 books. If I return .ToList() I get 2 records for the PO but still one book. I am curious to know what I'm trying to do is possible?
ctx.books_po.Where(a => a.po.Id == 3).Include(b => b.Books).FirstorDefault();

A: I think you are looking for GroupBy
var singleRecord = ctx.books_po
.Where(a => a.po.Id == 3)
.Include(b => b.Books)
.GroupBy(a => a.po, a => a.Books).FirstOrDefault();

You will get a single record with two fields singleRecord.Key and
singleRecord.ToList() will be all the bookIds under that po (== 3)

A: Why not using Books dbContexts instead of book_po ?
ctx.Books.Where(x => x.books_po.poId == 3).ToList();


text:
Q: Insertion Sort Doing Nothing I wrote the following insertion sort yesterday (I started learning C 3 days ago). For some reason, the sort does not modify the array AT ALL.
#include <stdio.h>
int *insert(int arr[], int index, int item);
int *isort(int arr[]);
int main() {
    int a[17] = {1, 2, 9, 5, 3, 2, 1, 6, 5, 9, 0, 1, 3, 4, 2, 3, 4};
    int *b = isort(a);
    for (int i = 0; i < 17; i += 1) {
        printf("%d ", b[i]);
    }
    return 0;
}
int *insert(int arr[], int index, int item) {
    --index;
    while (index >= 0 && item < arr[index]) {
        arr[index + 1] = arr[index];
        --index;
    }
    arr[index + 1] = item;
    return arr;
}
int *isort(int arr[]) {
    for (int i = 1; i < sizeof(arr) - 1; i++) {
        arr = insert(arr, i, arr[i]);
    }
    return arr;
}

I'm thinking it could be my compiler, as I'm running a compiler that is on a non unix machine: lcc-win, but I'm not sure. Is there some fundamental thing I'm missing here?

A: int *isort(int arr[]) {
    for (int i = 1; i < sizeof(arr) - 1; i++) {
        arr = insert(arr, i, arr[i]);
    }
    return arr;
}

In this function sizeof(arr) actually returns the size of the pointer and not the size of the array.
In C a special rule says an array parameter is actually adjusted to a parameter of the corresponding pointer type.
That is:
int *isort(int arr[]) { /* ... */ }

is equivalent to this:
int *isort(int *arr) { /* ... */ }

To fix this, add a new parameter in your function that takes the size of the array:
int *isort(int arr[], size_t size) { /* ... */ }

A: The first problem, as has been pointed out, is that the isort function uses the sizeof operator on a pointer. The way C treats arrays is a little strange at first glance. The name of an array is a pointer to its first element. So when you call isort like this:
int *b = isort(a);

you are simply pushing a pointer to the array onto the stack. In the definition of isort,
int *isort(int arr[])

declares arr to be a pointer to int just like
int *isort(int *arr)

C is even more confusing in this respect: if you had said:
int *isort(int arr[17])

the arr variable is still just a pointer to int ... the "17" here is discarded! Even with this syntax, sizeof(arr) will still be the size of a pointer to int.
On a 32-bit system (ILP32), sizeof(arr) will always be 4, however big the array is.
Therefore, you need to pass the size of the array to isort. A good general way to do this is to define a macro like this:
#define NITEMS(arr) (sizeof(arr)/sizeof(arr[0]))

This will calculate the number of elements in an array of any type.
Your next problem is more a style one than an actual error:
arr = insert(arr, i, arr[i]);

This calls the insert function with a reference to "arr". The array is modified through this reference, and then a pointer to that array is returned. It will always be the same pointer as you sent in the first place, so this assignment actually does nothing, harmlessly. Like I say, a style problem, not a code error.
The final issue is your isort function stops one short (after you correct the sizeof problem), since you went from 1 to sizeof-1. Here is a fixed version:
#include <stdio.h>
#define NITEMS(arr) (sizeof(arr)/sizeof(arr[0]))

int *insert(int arr[], int index, int item);
int *isort(int arr[], size_t nitems);
int main() {
    int a[17] = {1, 2, 9, 5, 3, 2, 1, 6, 5, 9, 0, 1, 3, 4, 2, 3, 4};
    int *b = isort(a, NITEMS(a));
    for (int i = 0; i < NITEMS(a); i += 1) {
        printf("%d ", b[i]);
    }
    printf("\n");
    return 0;
}

int *insert(int arr[], int index, int item) {
    --index;
    while (index >= 0 && item < arr[index]) {
        arr[index + 1] = arr[index];
        --index;
    }
    arr[index + 1] = item;
    return arr;
}

int *isort(int arr[], size_t nitems) {
    for (int i = 1; i < nitems; i++) {
        insert(arr, i, arr[i]);
    }
    return arr;
}


text:
Q: Dimension of Blowup algebra
Let $R$ be a Noetherian ring, if $I$ is an ideal of ring $R$, then the blowup algebra of $R$ is the subalgebra of $R[x]$ given by $B_I(R):=R\bigoplus Ix\bigoplus I^2x^2\bigoplus \dots \cong R[Ix]$. Show that the dimension of $B_I(R)$ is the maximum of the numbers $\dim R/P$, where $P$ ranges over minimal primes containing $I$, and $1+\dim R/Q$ where $Q$ ranges over minimal primes not containing $I$. (Eisenbud, Exercise 13.8 (2).)

I am able to show the minimal primes of $B_I(R)$ are the ideals of the form $PR[x]\bigcap B_I(R)$, where $P$ is a minimal ideal of $R$. Thus we can reduce to the case where $R$ is an integral domain by factoring out some minimal prime. However,  then I am not sure how to proceed.
I think I somehow found a way like following. First, show that if $P$ is a prime of $R$, then $PR[x]\bigcap B_I(R)$ is a prime of blowup algebra. Then, we can prove $B_I(R)/PR[x]\bigcap B_I(R)\cong B_{(I+P)/P}(R/P)$. If $P$ contains $I$, the dimension is obviously maximal among $\dim R/P$; otherwise, we can prove if $P_1\supset P_2\supset\dots$ is a chain of distinct primes in $R$, then $P_1R[x]\bigcap B_I(R)\supset P_2R[x]\bigcap B_I(R)\supset \dots$ is a chain of distinct prime of $B_I(R)$ and we know the correspondence between their minimal ideals, thus we can create a chain of primes in $B_{(I+Q)/Q}(R/Q)$ which has length $\dim R/Q+1$(since $(I+Q)/Q$ is nonzero), here $Q$ is a minimal prime not containing $I$. And the other side of dimension equality is obvious (i.e. by Nagata's Altitude Formula).


text:
Q: Can I restore my data to an older version of macOS? I had to send in my old Mac (10.11) for screen repair, and worked on a replacement MacBook with 10.14. Now, I'd like to transfer my data back from the replacement's Time Machine to the old Mac. I don't want Mojave because the very real downsides of breaking some pieces of software I rely on don't outweigh the cosmetic benefits.
Now, Migration Assistant tells me I cannot use my backup on the old Mac!
Is there a way to transfer only the data and leave the macOS untouched? User data and OS should really be separate.