text:
Q:  element and subtitles - Display weirdly EDIT: I was able to recreate the issue in Codepen, with two identical video elements (and tracks), one on the page and one accessible in a modal. Unfortunately, the cc box doesn't appear at all in the modal:
https://codepen.io/SarahF3000/pen/Rxyjgb

I use a video element to present audio interview, to include subtitles.
So I shorted the height (100px) of the video element.
But it seems there are issues to choose the languages of the subtitles (English, French or Macedonian), the box opening from the CC button doesn't display well, and so are the languages options (we can't click easily on it).
Here is how it appears in Firefox and in Chrome.
And here is the HTML code:
<video controlsList="nodownload" controls>
  <source type="audio/mp3" src="skopje/volhan/volhan1.mp3">
  <track label="English" kind="subtitles" srclang="en" src="skopje/volhan/v1en.vtt" default>
  <track label="French" kind="subtitles" srclang="fr" src="skopje/volhan/v1fr.vtt">
  <track label="Macedonian" kind="subtitles" srclang="mk" src="skopje/volhan/v1mk.vtt">
</video>

And the CSS code:
video {
    object-fit: initial;
    width: 100%;
    height: 100px;
    margin-top: -5px;
}

::cue {
    font-size: 18px;
    color: black;
    background-color: white;
    font-family: 'Fira Sans', sans-serif;
}

Do you know if there is a way to make the CC box appears well?
Thank you very much!
EDIT: I noticed it's linked to the fact that the page is responsive: the video player is inside a bootstrap modal and the "CC box" is always at a certain position of the page: with a 1413px large page and with a 1016px large page. But I still don't know how to fix it.


text:
Q: How to make an information box with selection on top? I'm trying to make the same thing as shown in the attached picture:

I've been looking for an answer online for ages, but I can't seem to find the solution. Do I just make a
 and attach another
 on top of it?

A: I made a very simple example for you

$("#tab1").click(function() {
  $("#section2").hide();
  $("#section1").show();
});

$("#tab2").click(function() {
  $("#section1").hide();
  $("#section2").show();
});
ul {
  list-style-type: none;
  padding: 0;
}

li {
  display: inline-block;
  cursor: pointer;
}

#section2 {
  display: none;
}

Tab 1

Tab 2

    Content 1

    Content 2

redpajama_set_name: RedPajamaStackExchange


text:
Q: Host is not allowed to connect to this mysql database I'm making a web api chat application in ASP.NET Razor Pages in VS Code with SignalR and with MySQL database. (Microsoft SQL Server Management Studio)
I wanted to store the messages and the users in a table, but when I made the MySQL connection I got an error message:
MySql.Data.MySqlClient.MySqlException (0x80004005): Host '' is not allowed to connect to this MySQL server

It can cause, that I connected to the database before in appsettings.json file with ConnectionString?
Here is the ChatHub.cs code:

using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;
using System;
using MySql.Data;
using MySql.Data.MySqlClient;
using probagetrequest.Models;

namespace SignalRChat.Hubs
{
    public class ChatHub : Hub
    {

        public async Task SendMessage(string user, string message)
        {
            string connn = "Server=localhost;Database=DBChatApp;user id=sa;password=xxx";
            MySqlConnection con = new MySqlConnection(connn);
            try {
            Console.WriteLine("Connecting to MySql...");
            con.Open();
            string cmddd = "INSERT INTO Messages (Username,Message) VALUES (@Usernamee,@Messagee)";
            MySqlCommand cmd = new MySqlCommand(cmddd, con);
            cmd.Parameters.Add("@Usernamee", MySqlDbType.VarString).Value = user;
            cmd.Parameters.Add("@Messagee", MySqlDbType.VarString).Value = message;
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.ToString());
            }
            con.Close();
            Console.WriteLine("Done!!!!!");

            Console.WriteLine($"user={user}, message={message}");
            await Clients.All.SendAsync("ReceiveMessage", user, message);
        }
    }
}

A: Did you try logging into MySQL DB through mysql client CLI. I think it's a problem with "mysql user" privileges mentioned in your project to connect to the MySQL DB.
In general, the error you mentioned comes when a new database is setup but left un-configured.
Try the following commands logging into MySQL as super user
mysql> CREATE USER 'root'@'%' IDENTIFIED BY 'root';
mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' WITH GRANT OPTION;


text:
Q: How to draw tangent line at a given point on the circle? I'm trying to draw this picture using TikZ. I'm almost done. After drawing K and the small circle I choose those 2 points (p and \tilde p). The problem is to draw the dashed circle containing those 2 points.
Also other problem is to draw the tangent lines T_1 and T_2. I've found some tricks to draw tangents to a curve but I don't have an open curve to use some positions (as path length).
Finally, how to draw the right angles? That is, the small square for right angles.

Here is my code for the moment. It's similar to the figure, it is not necessary to be exactly the same. Note that I had to do a trick to get the orthogonal circle.
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{calc,through,arrows}
\usetikzlibrary{decorations}
\usetikzlibrary{intersections,patterns}
\usetikzlibrary{decorations.markings}

\begin{document}
\begin{tikzpicture}
\coordinate (q) at (0,0);
\coordinate (t) at (-20:3cm);
\coordinate (t1) at (15:3.5cm);
\draw[name path=circ,fill=white!10] (q) circle (2cm);
\draw[name path=reta] (q)--(t)node[below left]{$T$};
\path[name intersections={of=reta and circ,by={a}}] ;
\coordinate (o) at ($(a)!1cm!-90:(q)$);
\draw[name path=circ1] (o) circle (1cm);
\path[name intersections={of=circ and circ1,by={b}}] ;
\path[name path=linha,draw] (q)--(t1);
\path[name intersections={of=circ1 and linha,by={ztilde,z}}] ;

\draw (a) -- ($(a)!-4pt!(q)$) -- ($(a)!-4pt!(q)!4pt!90:(a)$) -- ($(a)!4pt!90:(q)$);
\draw (b) -- ($(b)!-4pt!(q)$) -- ($(b)!-4pt!(q)!4pt!-90:(b)$) -- ($(b)!4pt!-90:(q)$);

\draw[fill=white] (z)node[above left]{$z$} circle (1.2pt) (ztilde)node[above right]{$\tilde z$} circle (1.2pt) (a)node[below=2pt]{$a$} circle (1.2pt) (b)node[above=2pt]{$b$} circle (1.2pt);
\draw[fill=black] (q)node[left]{$q$} circle (1.2pt);
\node[below left] at (220:2cm){$\mathcal{K}$};
\node[right=1cm] at (o){$\mathcal{C}$};
\end{tikzpicture}
\end{document}


text:
Q: Questions about a pivot I did the tutorial for the pivots and got my first 3 pivots.
But if you plant a pivot and another player finds it, what happens to the pivot? Do you lose it forever? Do you have to find it again? Does it change locations?
I am a bit worried that I might lose the pivots.

A: When you are putting your pivots in the map noone will be able to take them.Only you are able to take them back through the map.When you find the pivot that you are looking for just be sure to pick up all the pivots that you placed so you can use them again.They doesn't change locations and you will not lose them.


text:
Q: Ubuntu 14.04 Daily Image Query I am planning to use Ubuntu 14.04 Alpha build on desktop. I would like to know that, If I keep updating Ubuntu 14.04 LTS on daily basis, will my OS will reach 'Stable' state when the final stable OS will be released on April 2014 ?
Apologies for poor English.

A: Yes, if you install 14.04 and keep updating it, when the final release appears your updated system will be the same than installing from the released stable iso, in theory.
I say "in theory" because you're using an alpha build, and so you're exposed to bugs, including the update system.


text:
Q: connect c++ & Mysql anyone can tell me what's wrong in my prg ?
It say's me :
With this prg i would view a table from MySQL.
This is my code :
int main(void)
{
    //QString mydb = "mydb";
    QSqlDatabase database = QSqlDatabase::addDatabase("mydb");

      //Setup the database
    database.setDatabaseName( "mydb" );
    database.setUserName( "root" );
    database.setPassword( "testpw" );

    if ( !database.open() )
      qDebug("Couldn't open DB");

}

 but i have the errors :

and i dont know why, its my first c++ / mysql prg and i think i have forget anything to download or to include .

/home/boldt/src/workspace/tester/Debug/../src/tester.cpp:33: undefined
  reference to QSqlDatabase::defaultConnection'
  /home/boldt/src/workspace/tester/Debug/../src/tester.cpp:33: undefined
  reference toQSqlDatabase::addDatabase(QString const&, QString
  const&)' /home/boldt/src/workspace/tester/Debug/../src/tester.cpp:36:
  undefined reference to QSqlDatabase::setDatabaseName(QString const&)'
  /home/boldt/src/workspace/tester/Debug/../src/tester.cpp:37: undefined
  reference toQSqlDatabase::setUserName(QString const&)'
  /home/boldt/src/workspace/tester/Debug/../src/tester.cpp:38: undefined
  reference to QSqlDatabase::setPassword(QString const&)'
  /home/boldt/src/workspace/tester/Debug/../src/tester.cpp:40: undefined
  reference toQSqlDatabase::open()'
  /home/boldt/src/workspace/tester/Debug/../src/tester.cpp:41: undefined
  reference to qDebug(char const*, ...)'
  /home/boldt/src/workspace/tester/Debug/../src/tester.cpp:41: undefined
  reference toQSqlDatabase::~QSqlDatabase()'
  /home/boldt/src/workspace/tester/Debug/../src/tester.cpp:43: undefined
  reference to QSqlDatabase::~QSqlDatabase()'
  /home/boldt/src/workspace/tester/Debug/../src/tester.cpp:43: undefined
  reference toQSqlDatabase::~QSqlDatabase()'
  /home/boldt/src/workspace/tester/Debug/../src/tester.cpp:41: undefined
  reference to QSqlDatabase::~QSqlDatabase()' ./src/tester.o: In
  functionQString::QString(char const*)':
  /usr/include/QtCore/qstring.h:419: undefined reference to
  QString::fromAscii_helper(char const*, int)' ./src/tester.o: In
  functionQString::QString(QLatin1String const&)':
  /usr/include/QtCore/qstring.h:694: undefined reference to
  QString::fromLatin1_helper(char const*, int)' ./src/tester.o: In
  functionQString::~QString()': /usr/include/QtCore/qstring.h:880:
  undefined reference to `QString::free(QString::Data*)'

A: Here is some code I use for QT -> MySql.  I personally try to stay completely clear of boost, QT is a much cleaner and complete solution.
Firstly, you'll want these includes:
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>

Inside your project file, please add sql to your Qt variable:
QT += core sql

I believe this logic needs to run inside a Qt event loop.  I recommend using a single shot timer.  Qt offers many example programs that will get you started.
Open up the database.  You don't need to store the database instance variable unless you need to connect to more than 1 database at a time.  QT will keep an internal pointer for you.
QSqlDatabase database = QSqlDatabase::addDatabase( "QMYSQL" );

  //Setup the database
database.setDatabaseName( db );
database.setUserName( usr );
database.setPassword( pass );

if ( !database.open() )
  qDebug("Couldn't open DB");

Here is some code for reading data out of the DB.  In this code I only take the first row returned.  This could be changed by calling query->next() multiple times:
QString sql = QString("SELECT id, type, name FROM table WHERE id = %1").arg( id );

//Go through looking for my mac address
QSqlQuery query( sql);
if ( query.next() )
{
  int id       = query.value( 0 ).toInt();
  int type     = query.value( 1 ).toInt();
  QString str  = query.value( 2 ).toString();

  return true;
}

Here is a function to insert bulk data.  Note in many implementations there is a limit to the number of rows you can insert by a single execBatch() call.  I don't know what the limit is, or how to find it.  However <= 128 should be safe:
bool Database::storeTable( QString table, QStringList &field_list,
                           QHash<QString, QVariantList> &fields )
{
  QString sql;
  QStringList q_marks;
  QSqlQuery query;
  int i;

    //Create my question marks
  for ( i = 0; i < field_list.size(); i++ )
    q_marks.append( "?" );

    //Create my query
  sql = QString::fromUtf8("INSERT INTO %1 ( %2 ) VALUES ( %3 )")
          .arg( table)
          .arg( field_list.join(','))
          .arg( q_marks.join(','));

    //Setup my query
  if ( !query.prepare( sql ) )
  {
    qDebug("Couldn't prepare SQL store statement\r");
    return false;
  }

    //Attach my values and finish
  for ( i = 0; i < field_list.size(); i++ )
    query.addBindValue( fields[ field_list[i]] );

    //Setup my query lookup
  bool result = query.execBatch();
  if ( !result )
    qDebug() << query.lastError().text();
  return result;
}

A: You need to set the include additional directories for boost library.
"Additional Include Directories"
C:\Users\user\Desktop\boost_1_53_0\boost_1_53_0

Here's a detailed explanation with examples
    http://www.boost.org/doc/libs/1_47_0/more/getting_started/windows.html#build-from-the-visual-studio-ide


text:
Q: What's South Korea's country name in API? [SOLVED] the official name is Korea, Republic of. You can's miss any white space when you use it.
I am using Last.FM API, when I try geo.getTopArtists(Get the most popular artists on Last.fm by country), I need to input a parameter :
country (Required) : A country name, as defined by the ISO 3166-1 country names standard.

Then I checked ISO 3116-1, and found South Korea's name is Korea, Republic of
but it doesn't work. Then I tried korea, southkorea,koreaofrepublic ,all failed.
What should I input?
http://ws.audioscrobbler.com/2.0/?method=geo.gettopartists&country=korea&api_key=aa652ac51995d952d83d12093d25d9d9&format=json

A:

It should be ISO 3166-1  country name  standard .
https://en.wikipedia.org/wiki/ISO_3166-1

A: if you copy/paste this link in your browser, you will get the complete list of countries
that are supported by Rest Countries Api.
https://restcountries.com/v2/all
My suggestion is to do it in Firefox, because, list will be formatted in a readable way.
From there, you can search for the any data you might need.
For example, in the case of South Korea, you would go to the link, type 'korea' in the search bar, and you would get two results ( for North and South Korea), and when you expand the JSON object, you could read the exact name of the country as they listed it in their API. "Korea (Republic of)" in this case.


text:
Q: Lag when devices are connected via wi-fi I'm not sure it's the right site for this question, but here is the problem.
I've a console linked with a cable to a router. My internet connection is far from the best but when there aren't other devices it's mostly smooth.
The problem is that whenever I connect a tablet or a smartphone with wi fi to the same router i begin to experience lag in game.
I feel it's strange because it happens even if I'm just browsing the internet. So I'm asking if a similar behaviour is normal and, if not, how can I solve the problem.
I've a Alice Gate VoIP 2 Plus Wi-Fi router connected (with cables) to a decoder, an xbox 360 and an xbox one. I've this problem while I play with the xbox one and the other devices are turned off (I don't know for certain if the xbox 360 has the same problems). Then I've via wi-fi two ipads and my iphone 4S but using only one of these it's enough to cause the problem.
I asked the same question in
Network Engineering(https://networkengineering.stackexchange.com/questions/23042/lag-when-devices-are-connected-via-wi-fi ) and they redirected me here.


text:
Q: postgres coalesce fields, sum and group by maybe someone can help me out with a postgres query.
the table structure looks like this
  nummer   nachname   vorname   cash
 +-------+----------+----------+------+
   2       Bert       Brecht    0,758
   2       Harry      Belafonte 1,568
   3       Elvis      Presley   0,357
   4       Mark       Twain     1,555
   4       Ella       Fitz      0,333
   …

How can I coalesce the fields where "nummer" are the same and sum the cash values?
My output should look like this:
   2       Bert, Brecht      2,326
           Harry, Belafonte
   3       Elvis, Presley    0,357
   4       Mark, Twain       1,888
           Ella, Fitz

I think the part to coalesce should work something like this:
 array_to_string(array_agg(nachname|| ', ' ||coalesce(vorname, '')), '<br />') as name,

Thanks for any help,
tony

A: SELECT
  nummer,
  string_agg(nachname||CASE WHEN vorname IS NULL THEN '' ELSE ', '||vorname END, E'\n') AS name,
  sum(cash) AS total_cash
FROM Table1
GROUP BY nummer;

See this SQLFiddle; note that it doesn't display the newline characters between names, but they're still there.
The CASE statement is used instead of coalesce so you don't have a trailing comma on entries with a last name but no first name. If you want a trailing comma, use format('%s, %s',vorname,nachname) instead and avoid all that ugly string concatenation business:
SELECT
  nummer, string_agg(format('%s, %s', nachname, vorname), E'\n'),
  sum(cash) AS total_cash
FROM Table1
GROUP BY nummer;

If string_agg doesn't work, get a newer PostgreSQL, or mention the version in your questions so it's clear you're using an obsolete version. The query is trivially rewritten to use array_to_string and array_agg anyway.
If you're asking how to sum numbers that're actually represented as text strings like 1,2345 in the database: don't do that. Fix your schema. Format numbers on input and output instead, store them as numeric, float8, integer, ... whatever the appropriate numeric type for the job is.


text:
Q: Magento 2 Facebook Product Feed script in CSV format I am looking for script to run on Magento root which will dynamically generate csv file for facebook product feed.
if anyone have generated script please help me.

A: You can helpful this extension for dynamically generate product feed csv for facebook.
https://marketplace.magento.com/apptrian-facebook-pixel.html


text:
Q: Lync chat 2010 notifications I'm looking for direction on if it's possible to have a win form in the background watch a group chat channel and provide notification popup when a string is typed in chat.
I've only found resources for Lync chat.
Nothing on how to establish a connection to a channel and read the chat as people talk.
Any help is appreciated.


text:
Q: Rails project on Heroku: "We're sorry, but something went wrong" I have just pushed a rails project to heroku, but I get the "We're sorry, but something went wrong."-error when I try to visit the web address. I did heroku run rake db:migrate just after I uploaded the project. Does someone know what the issue might be?
2013-07-07T03:18:40.493412+00:00 heroku[web.1]: State changed from starting to up
2013-07-07T03:19:30.121757+00:00 app[web.1]: => Booting WEBrick
2013-07-07T03:19:30.121757+00:00 app[web.1]: => Rails 3.2.13 application starting in production on http://0.0.0.0:7276
2013-07-07T03:19:30.121757+00:00 app[web.1]: => Call with -d to detach
2013-07-07T03:19:30.121757+00:00 app[web.1]: => Ctrl-C to shutdown server
2013-07-07T03:19:30.121757+00:00 app[web.1]: Started GET "/" for 216.15.124.94 at 2013-07-07 03:19:30 +0000
2013-07-07T03:19:30.298842+00:00 app[web.1]: Processing by PagesController#lelist as HTML
2013-07-07T03:19:30.683128+00:00 app[web.1]: Completed 500 Internal Server Error in 384ms
2013-07-07T03:19:30.680391+00:00 app[web.1]:   Rendered pages/_singlePost.html.erb (39.1ms)
2013-07-07T03:19:30.687518+00:00 app[web.1]:     1: <% @posts.each do |p| %>
2013-07-07T03:19:30.682956+00:00 app[web.1]:   Rendered pages/lelist.html.erb within layouts/application (122.9ms)
2013-07-07T03:19:30.687518+00:00 app[web.1]:     3:

2013-07-07T03:19:30.687741+00:00 app[web.1]:   app/views/pages/_singlePost.html.erb:1:in `_app_views_pages__single_ost_html_erb___4229188597617574554_47615640'
2013-07-07T03:19:30.687741+00:00 app[web.1]:
2013-07-07T03:19:30.687518+00:00 app[web.1]:     4:

2013-07-07T03:19:30.687741+00:00 app[web.1]:   app/views/pages/lelist.html.erb:22:in `_app_views_pages_lelist_html_erb___4165065758361537325_47142940'
2013-07-07T03:19:30.687518+00:00 app[web.1]: LINE 1: SELECT  "posts".* FROM "posts"  WHERE (DATETIME(created_at) ...
2013-07-07T03:19:30.687518+00:00 app[web.1]: : SELECT  "posts".* FROM "posts"  WHERE (DATETIME(created_at) <= DATETIME('2013-07-07 03:19:30.364173')) ORDER BY created_at DESC LIMIT 10 OFFSET 0):
2013-07-07T03:19:30.687518+00:00 app[web.1]: HINT:  No function matches the given name and argument types. You might need to add explicit type casts.
2013-07-07T03:19:30.687741+00:00 app[web.1]:
2013-07-07T03:19:30.687518+00:00 app[web.1]:
2013-07-07T03:19:30.687518+00:00 app[web.1]: ActionView::Template::Error (PGError: ERROR:  function datetime(timestamp without time zone) does not exist
2013-07-07T03:19:30.687518+00:00 app[web.1]:     2:

A little further down in the log I get another error:
2013-07-07T03:35:54.804738+00:00 app[web.1]: ActionView::Template::Error (PGError: ERROR:  function datetime(timestamp without time zone) does not exist
2013-07-07T03:35:54.804738+00:00 app[web.1]: LINE 1: SELECT  "posts".* FROM "posts"  WHERE (DATETIME(created_at) ...
2013-07-07T03:35:54.804738+00:00 app[web.1]:                                                ^
2013-07-07T03:35:54.804738+00:00 app[web.1]: HINT:  No function matches the given name and argument types. You might need to add explicit type casts.
2013-07-07T03:35:54.804738+00:00 app[web.1]: : SELECT  "posts".* FROM "posts"  WHERE (DATETIME(created_at) <= DATETIME('2013-07-07 03:35:54.572183')) ORDER BY created_at DESC LIMIT 10 OFFSET 0):
2013-07-07T03:35:54.804738+00:00 app[web.1]:     1: <% @posts.each do |p| %>
2013-07-07T03:35:54.804738+00:00 app[web.1]:     4:

2013-07-07T03:35:54.804738+00:00 app[web.1]:     2:

2013-07-07T03:35:54.804738+00:00 app[web.1]:     3:

2013-07-07T03:35:54.804934+00:00 app[web.1]:   app/views/pages/_singlePost.html.erb:1:in `_app_views_pages__single_ost_html_erb___4229188597617574554_47615640'
2013-07-07T03:35:54.804934+00:00 app[web.1]:   app/views/pages/lelist.html.erb:22:in `_app_views_pages_lelist_html_erb___4165065758361537325_47142940'

A: Heroku uses postgresql for your database.  DATETIME is not a function postgres supports.  You should set up a postgresql database of the same version in your development environment.  What OS are you on?  If windows, I wrote any answer for that (some of it is applicable even if you're running linux).


text:
Q: simple adding to value in dictionary python I want to append to dictionary as a second value second value to a dictionary
ret = {}
third_value_list =[0,1]
for i in third_value_list:
    #print i
    num_list = [1,2]
    val_list = [0,1]
    dict1 = dict(zip(num_list,val_list))
    print dict1
    num_list2= [1,2]
    val_list2 = [0,6]
    dict2 =dict(zip(num_list2,val_list2))
    print dict2
if set(dict2.items()) - set(dict1.items()):
    print 'true'
    a = set(dict1.items()) - set(dict2.items())
    ret.update (a)
    print ret
    print 'this is before'
    for key in ret:
       ret[key] = [ret[key]]
       ret[key].append(i)
       print ret

current output :
{1: 0, 2: 1}
{1: 0, 2: 6}
{1: 0, 2: 1}
{1: 0, 2: 6}
true
{2: 1}
this is before #below is the final output
{2: [1, 1]}
desire output : {2: [1, 0] ,2: [1, 1]}

A: the anwser for my question is ret [i] = a


text:
Q: Return String from a Future function How can i return a string from a future function?
Future<String> functionA() async {
   var x = await fetchX();
   return x;
}

Future<String> fetchX() {
   return Future.delayed(Duration(seconds: 4), () => 'example');
}

Future<String> la() async {

  print(await functionA()); //this works correctly
  return await functionA(); //this return always an instance of Future
}

How can i return "example" from the future function, there is a method to do it, and where is my error?

A: You need to specify what your function will return. All you have to do is add Future  to the beginning of the method.
Future<String> fetch() async {
    final response = await http.get('url');
    String conteggio = response.body;
    return conteggio;
 }

And you have to do this in a method. You can only assign constant values in fields other than methods.

A: Future<String> fetch() async {
  return
    http.get('url')
    .then((response) => response.body);
 }

That way you can sneak a .catchError into there. :)


text:
Q: How to join a table by a column with tilde separated values I'm trying to match the codes/descriptions from table_2 to each company in table_1. The company_type_string column contains multiple codes separated by ~ that are supposed to match with the codes in table_2.
Table 1:
company    company_type_string
------------------------------
  A         1A~2B~3C
  B         1A~2B
  C         1A
  D         1A~2B~3C~4D

Table 2:
code    description
-----------------------
 1A     Finance
 2B     Law
 3C     Security
 4D     Marketing

Desired output:
company description
----------------------
   A    Finance
   A    Law
   A    Security
   B    Finance
   B    Law
   C    Finance
   D    Finance
   D    Law
   D    Security
   D    Marketing

I've tried using split_string with no success. Is there a way to make this join without altering the DB schema?

A: If you can not fixed the schema, the following query should work:
   SELECT c.company, ct.description
   FROM table_1 c
   CROSS APPLY STRING_SPLIT(c.company_type_string,'~') t
   INNER JOIN table_2 ct
   ON t.value=ct.code;

A: I don't have 2016 yet myself so here is a way you can do this in earlier versions. This is using the DelimitedSplit8K function which you can find here. But the best possible solution would be to normalize your design.
declare @Company table
(
    company char(1)
    , company_type_string varchar(100)
)

insert @Company values
('A', '1A~2B~3C')
, ('B', '1A~2B')
, ('C', '1A')
, ('D', '1A~2B~3C~4D')

declare @Code table
(
    code char(2)
    , description varchar(50)
)

insert @Code values
('1A', 'Finance')
, ('2B', 'Law')
, ('3C', 'Security')
, ('4D', 'Marketing')

select c.company
    , co.description
from @Company c
cross apply dbo.DelimitedSplit8K(c.company_type_string, '~') x
join @Code co on co.code = x.Item

A: Here u have a code sample, the last part is the important for you, is pretty simple, easy to use and memorize.
IF OBJECT_ID('tempdb..#table_1') IS NOT NULL
    DROP TABLE #table_1
CREATE TABLE #table_1
(
company VARCHAR(1),
company_type_string VARCHAR(max)
)

INSERT INTO #table_1 VALUES
('A','1A~2B~3C'),
('B','1A~2B'),
('C','1A'),
('D','1A~2B~3C~4D')

IF OBJECT_ID('tempdb..#table_2') IS NOT NULL
    DROP TABLE #table_2
CREATE TABLE #table_2
(
code VARCHAR(2),
description VARCHAR(30)
)

INSERT INTO #table_2 VALUES
('1A','Finance'),
('2B','Law'),
('3C','Security'),
('4D','Marketing')

SELECT
    company,
    description
FROM #table_1 c
INNER JOIN #table_2 ct
    ON c.company_type_string like '%' + ct.code +  '%'
ORDER BY company


text:
Q: Combinatorial interpretation of composition of power series? This is a minor curiosity that came up in a joint project recently.
Consider the sequence $a_n=3\frac {(2n)!}{(n+2)!(n-1)!}$ (A000245 in OEIS).
It has multiple combinatorial descriptions.
One can write the corresponding generating function, but I will do it with an extra sign.
$$
f(t) = -\sum_{n=0}^{\infty} a_n t^n  = -t-3t^2-9t^3-28t^4-90t^5 -...
$$
which has a simple though inelegant description
$$
f(t) = \frac {(1-t)\sqrt{1-4t}-1+3t}{2t^2}.
$$
So far it is all perfectly boring. But the interesting thing is that this $f$ satisfies the identity
$$
f(f(t))=t.
$$
My questions are:

*

*Has this been observed before?

*Are there any combinatorial interpretations of this identity in terms of the combinatorial descriptions of the sequence $a_n$?

A: Basically $f(f(t)) = t$ is related to the fact that $y = f(t)$ and $t$ satisfy an algebraic relation $$y^2 t^2 - 3 y t + y + t = 0$$ which is symmetric in $y$ and $t$ and its graph passes through $(0,0)$ tangent to the line $y=-t$. That relation corresponds to the identity
$$ \sum_{j=1}^{n-1} a_j a_{n-j} + 3 a_{n+1} - a_{n+2} = 0$$
I don't know if this has a combinatorial interpretation.

A: It seems solutions of the functional equation $g(g(t))=t$ are related to pseudo-involutions of the Riordan group. See http://www.sciencedirect.com/science/article/pii/S0166218X0900016X (Riordan group involutions and the $\Delta$-sequence, by Gi-Sang Cheon, Sung-Tae Jin, Hana Kim and Louis W. Shapiro). From the paper we can get about ten more solutions of this functional equation (Table 1 in the paper). Note that $g(t)=-f(t)$, where $f(t)$ is the generating function from Table 1. The simplest example is $f(t)=\frac{t}{1-t}$ related to the Pascal triangle.

A: When rephrased (using the positive generating series $g=-f$) as the identity $g(-g(-t))=t$, this suggests that there may exist a quadratic nonsymmetric operad with this generating series, which is Koszul and whose Koszul dual is itself.
I do not know such an operad. Looking at Loday's encyclopedia of operads, a possible candidate could have been the operad of Malcev algebras, but Loday only gives the first three terms $1,3,9$, which is probably not enough to draw any conclusion. And moreover, this is not a nonsymmetric operad. It may be possible to try to find one, maybe being guided by the existing combinatorics.
To illustrate, the simpler case of $g(t)=t/(1-t)$ is related to the Associative operad, which is Koszul and self-dual.


text:
Q: Forma mais rápida de acessar propriedades em uma lista C# Tenho um projeto que trabalha com um grande volume de dados, e preciso otimiza-lo para trazer resultados de alguns cálculos em um tempo consideravelmente pequeno. Sei que tenho diversos aspectos para levar em consideração, como a estrutura em que os dados foram salvos no Banco de Dados, a forma como estou realizando o acesso a eles, como estou realizando os cálculos entre outros, mas desconsiderando todos estes itens, gostaria que fosse levado em consideração apenas a questão colocada abaixo.
Minha dúvida é mais conceitual que um problema em meu código. Mas algo específico...
Considere a seguinte lista:
var minhaLista = new List<MeuObjeto>
{
   // Objetos...
};

meuObjeto possui as seguintes propriedades:
public class MeuObjeto
{
  public int Prop1 {get; set;}
  public string Prop2 {get; set;}
  public decimal Prop3 {get; set;}
  public bool Prop4 {get; set;}
}

Preciso acessar cada uma das propriedades em um laço de repetição com n itens da forma mais rápida possível e econômica em relação a memória. Mas se tiver de escolher entre velocidade e memória, devo escolher velocidade.
Cada milissegundo é muito importante, por isso estou levando em consideração alguns aspectos como o for ser mais rápido que o foreach, ou ainda declarar uma constante com 0 e usa-la para instanciar a variável de controle do laço ser melhor que instanciar diretamente com 0.
Por isso, considere INICIO da seguinte forma:
private const int INICIO = 0;

Considere OutroObjeto como um objeto semelhante a MeuObjeto apenas para exemplo.
Forma 1:
var outraLista = new List<OutroObjeto>();

for (int i = INICIO; i < minhaLista.Count; i++)
{
   var outroObjeto = new OutroObjeto
   {
      Prop1 = minhaLista[i].Prop1,
      Prop2 = minhaLista[i].Prop2,
      Prop3 = minhaLista[i].Prop3,
      Prop4 = minhaLista[i].Prop4
   };
   outraLista.Add(outroObjeto );
}

Neste caso, para cada propriedade é feita uma busca na lista pelo
  objeto na posição i?

Forma 2:
var outraLista = new List<OutroObjeto>();

for (int i = INICIO; i < minhaLista.Count; i++)
{
   var meuObjetoI = minhaLista[i];

   var outroObjeto = new OutroObjeto
   {
      Prop1 = meuObjetoI.Prop1,
      Prop2 = meuObjetoI.Prop2,
      Prop3 = meuObjetoI.Prop3,
      Prop4 = meuObjetoI.Prop4
   };
   outraLista.Add(outroObjeto );
}

Aparentemente este trecho trabalha de forma semelhante ao foreach,
  mas o acesso a cada propriedade do objeto na posição i da lista
  será mais rápido que na Forma 1?
Tecnicamente meuObjetoI apenas aponta para o objeto da lista na
  posição i que já está alocado na memória, correto?

Qual seria a forma mais indicada levando em consideração o tempo e o
  consumo de memória? Ou existe uma terceira opção que seja melhor?

A: Pré-compute o que for possível
Zero é uma constante, então não precisa se preocupar com ela. Mas .Count será reavaliado em cada interação, caso o compilador não consiga "provar" que minhaLista é uma  variável estritamente local. Como não há considerações sobre isso, então então primeira otimização é usar for para diminuir pressão sobre o garbage collector, e pré-computar .Count:
var count = minhaLista.Count;

for (int i = 0; i < count; i++)
{
    ...
}

Essa otimização assume que a lista tem tamanho constante.
Diminuir as indireções 1
Como comentado, cada indireção a resolver é um processamento a mais, pelo menos em teoria. Isso pode ser uma otimização burra, mas novamente, se minhaLista não for estritamente local, dentro do for:
for (int i = 0; i < limit; i++)
{
    var item = minhaLista[ i ];
    var outroObjeto = new OutroObjeto
    {
        Prop1 = item.Prop1,
        Prop2 = item.Prop2,
        Prop3 = item.Prop3,
        Prop4 = item.Prop4
    };
    outraLista.Add(outroObjeto );
}

Isso corta os repetidos acessos tipo minhaLista[i].Obj.
Diminuindo indireções 2
Propriedades simples, ou propriedades com ascensores simples ({get;set;}) tem código extremamente otimizado, então o código acima, embora pareça verborrágico, talvez já seja o mais rápido possível. No entanto uma cópia assim talvez viole o princípio do DRY, então criar um construtor de OutroObjeto que aceite MeuObjeto é interessante pois:

*

*Melhora a expressividade do seu código

*Diminui a indireção, pois metade das propriedades serão acessos locais de um dos objetos.

Uma alternativa é pendurar um método .ToOutro() em MeuObjeto, fazendo algo parecido ao conteúdo do for, acima.
var minhaLista = new List<MeuObjeto>();
...

var outraLista = new List<OutroObjeto>();
var count = minhaLista.Count;

for (int i = 0; i < count; i++)
{
    outraLista.Add( minhaLista[ i ].ToOutro() );
}

Depende um tanto do gosto pessoal. Se achar preferível um .To da vida mas feio misturar domínios da aplicação, um método de extensão é o caminho de ter um código que liga os objetos, sem estar em nenhum dos objetos.
Readonly collection
O maquinário de List<> é complicado. Tem de ser. Mas tentar substituir essa funcionalidade por uma implementação caseira não tem lá o melhor dos prognósticos. No entanto "tudo" o que o seu código acima faz é copiar uma lista de objetos em outra. Dai a pergunta, nova lista tem de ser dinâmica?
Se a resposta for na negativa, especificamente se a nova lista criada não é depois modificada em termos de quantidade de registros, então:
var minhaLista = new List<MeuObjeto>();
...
var count = minhaLista.Count;
var outraLista = new OutroObjeto[count];

for (int i = 0; i < count; i++)
    outraLista[ i ] = minhaLista[ i ].ToOutro();

Readonly object
Essa é uma proposta radical, mas que é de fato utilizada em lugares onde a performance é absolutamente prioritária: objetos somente leitura, e se forem pequenos o suficiente, structs em vez de objetos.
Não é uma transição que deve ser feita sem muito estudo. Sair de classes mutantes para struct é difícil, e propenso a erros. Se esses objetos vem de banco de dados, daí a sugestão é de não ir por esse caminho.
Mas se esses objetos forem de alguma forma dados efêmeros, carregados para serem descartados ou produtos de cálculos, utilizar classes/structs somente leitura te dá a garantia que esses dados não serão alterados em hipótese nenhuma, que talvez evite esse tipo de conversão, e abre algumas otimizações em nível de compilador, que podem acelerar bem a execução do código.

A:
Neste caso, para cada propriedade é feita uma busca na lista pelo objeto na posição i?

Busca não é exatamente a palavra, acho que ela implica em um processamento longo. É feito um acesso direto ao elemento de acordo com o índice. É um acesso a um ponto da memória como qualquer variável.
Essencialmente não faz diferença se está acessando a variável como um elemento ou como um objeto todo. Se no final terá que acessar todos elementos isto pouco muda. Claro que depende do que vai fazer, o que pode ser melhor em um contexto pode ser pior em outro.
Eu não arriscaria dizer com toda certeza qual seria mais rápido sem testar em condições apropriadas, o que nem sempre sabemos fazer. Ainda assim o resultado do teste em operação simples pode ser irrelevante dentro de outro contexto. Já vi diversas vezes a pessoa testar em condições controladas para obter o resultado mais preciso e depois quando usa em produção acontece outra coisa.

Aparentemente este trecho trabalha de forma semelhante ao foreach, mas o acesso a cada propriedade do objeto na posição i da lista será mais rápido que na Forma 1?

Não tem nada parecido com o foreach. O foreach trabalha com um objeto enumerador, acessa outros métodos, tem mais dificuldade de otimização e principalmente tem uma proposta bem diferente da apresentada.

Tecnicamente meuObjetoI apenas aponta para o objeto da lista na posição i que já está alocado na memória, correto?

Correto, neste caso. Você receberá o valor armazenado no elemento da lista. Como é um objeto por referência, receberá a referência (ou ponteiro se preferir) para o objeto e não o objeto em si. Se o tipo fosse por valor receberia ele.

Qual seria a forma mais indicada levando em consideração o tempo e o consumo de memória? Ou existe uma terceira opção que seja melhor?

Não vejo motivos para a segunda forma. ela é pior. Tenho sérias dúvidas se realmente precisa fazer isto. O que posso dizer é que sem contexto tudo pode ser certo ou errado. Eu acho que dá pra fazer melhor, mas depende do contexto.
Conclusão
No geral eu não sei se cada milissegundo é tão importante assim. Principalmente sem contexto. Vejo pessoas muito experientes fazer tudo errado tentando otimizar. Otimizar certo é mais difícil do que parece.
Não acho que seja o caso mas muitas vezes escolher não se preocupar com a memória é escolher ter pior velocidade. Pra ver como é complexo.
Não sei se é tão verdade que o foreach é mais lento que o for. Eu já mostrei aqui no SOpt que não é bem assim. Este é um dos motivos que as pessoas erram tentando otimizar, acreditam em verdades falsas.
Espero que esta resposta sirva mais até para desmistificar a ideia da otimização do que até responder o caso específico que nem parece ser relevante.
Coloquei no GitHub para referência futura.

A: As duas formas crescem linearmente com o tamanho da sua lista, então a diferença é pequena.
Mas a segunda forma é um pouco pior em questão de performance e memória porque apesar de ser apenas um ponteiro, você precisa alocar o endereço e memória pra ele apontar para o objeto da minhaLista[i] todas as vezes e este é um passo extra e desnecessário.
Como perguntou de outra forma, você poderia passar para o construtor do OutroObjeto e deixar ele tratar internamente as propriedades necessárias, sem precisar alocar variáveis temporárias, já que você adiciona a referência na sua outraLista.
Forma 3:
for (int i = INICIO; i < minhaLista.Count; i++)
{
    outraLista.Add(new OutroObjeto(minhaLista[i]));
}


text:
Q: How to initialize a structure on definition? Is there a way to declare a structure with default initalisation values?
I have a header file which defines a structur like this:
typedef struct struc_s
{
    size_t cost const = 2000;
    size_t dmg const = 100;
    size_t def const = 100;
    size_t hull const = 1500;
    size_t shield const = 300;
    size_t capacity const = 2;
    size_t destruc const = 10;
} struc_t;

But this ofcourse doesn't work.
I would also be fine with a way of declaring a var of type struc_t in this header file. But as I remember right. I would have to decalre it in the c file as extern
What I want to do is every where where this header is included i want to be able to do var = struc_s.dmg and and the result should be that var holds the value 100.
But I dont want to declare struc_s anywhere else then in the header. Is there a way to archive this behavior?

A: Not in the way you want.
When you do a typedef, you're defining the shape of a memory region, a process distinct from allocating and filling it.
A possible alternative:
typedef struct
{
    size_t cost;
    size_t dmg;
    size_t def;
    size_t hull;
    size_t shield;
    size_t capacity;
    size_t destruc;
} struc_t;

#ifndef DEFAULT_STRUC_VALUES_DEFINED
#define DEFAULT_STRUC_VALUES_DEFINED

const struc_t DEFAULT_STRUC = {
    .cost = 2000,
    .dmg = 100,
    .def = 100,
    .hull = 1500,
    .shield = 300,
    .capacity = 2,
    .destruc = 10
};
#endif

and then when you want to create a new one:
struc_t *new_struc = malloc(sizeof(struc_t));
memcpy(new_struc, DEFAULT_STRUC, sizeof(struc_t));

As a sidenote, is there a reason you're using size_t for your structure members? There's nothing inherently wrong with it, but it may change from platform to platform.

A: typedef struct struc_s
{
int a;
int b;
}s;

This is type definition and Not a declaration of object.You can initialize at the time of declaring object.
C89-style initializers are used when contiguous members may be given.
s obj={1,2};

For non contiguous or out of order members list, designated initializer style may be used
s obj={.a=1,.b=2};

     or

s obj={.b=2,.a=1};

A third way is copy the value of an existing object of the same type
s obj1=obj;


text:
Q: Can't install PG rubygem on Centos I am attempting to run gem install pg on my Centos VPS but am getting
Building native extensions.  This could take a while...
ERROR:  Error installing pg:
    ERROR: Failed to build gem native extension.

    /usr/local/rvm/rubies/ruby-2.0.0-p247/bin/ruby extconf.rb
checking for pg_config... no
No pg_config... trying anyway. If building fails, please try again with
 --with-pg-config=/path/to/pg_config
checking for libpq-fe.h... no
Can't find the 'libpq-fe.h header
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.

Provided configuration options:
    --with-opt-dir
    --without-opt-dir
    --with-opt-include
    --without-opt-include=${opt-dir}/include
    --with-opt-lib
    --without-opt-lib=${opt-dir}/lib
    --with-make-prog
    --without-make-prog
    --srcdir=.
    --curdir
    --ruby=/usr/local/rvm/rubies/ruby-2.0.0-p247/bin/ruby
    --with-pg
    --without-pg
    --with-pg-config
    --without-pg-config
    --with-pg_config
    --without-pg_config
    --with-pg-dir
    --without-pg-dir
    --with-pg-include
    --without-pg-include=${pg-dir}/include
    --with-pg-lib
    --without-pg-lib=${pg-dir}/

I have installed postgres 9.3 as you can see here (yum list installed | grep postgres)
postgresql-libs.x86_64              8.4.13-1.el6_3                     @base
postgresql93.x86_64                 9.3.1-1PGDG.rhel6                  @pgdg93
postgresql93-devel.x86_64           9.3.1-1PGDG.rhel6                  @pgdg93
postgresql93-libs.x86_64            9.3.1-1PGDG.rhel6                  @pgdg93
postgresql93-server.x86_64          9.3.1-1PGDG.rhel6                  @pgdg93

A: Try this solution and restart your session
export PATH="/usr/pgsql-9.3/bin:$PATH"

or try
yum install libpqxx-devel
gem install pg -- --with-pg-config=/usr/pgsql-9.4/bin/pg_config

A: You can install the postgresql libs using yum:
yum install postgresql-libs

This should install the referred library so you can try to install the gem again.


text:
Q: How to reset checked checkboxes on button click? (vue.js) I am working on a custom search filter, where you can tick off checkboxes to better fit what you're looking for. (Working with Vue.js)
I also want to add a "clear" button, that gets rid of your all the ticks you made previously in the checkboxes. I have this for the button:
<button @click="clear">
     クリアする
</button>

and I'm not so sure how to define the method but I wrote it like so:
methods: {
    clear() {
      (this.selectLocations = []), (this.selectItems = []);
    }
}

this is the code I have for the checkboxes:

                <input type="checkbox" :value="value" v-model="selectItems[index]" />
                {{ value }}

where selectItems is defined as an empty array in the data property:
data() {
    return {
      selectItems: []
    };
  },

Can somebody please help me figure this out?

A: I don't know where this.selectLocations comes from because I don't see it in the template, but your function cannot work like that.
To reset your selectItems, you'd need to say:
clear() {
  this.selectItems = [];
}

This will empty the selected items and deselect all checkboxes again.

A: This is better approach imo.

    <template>

        <button @click="clear()">Clear</button>

          {{ item.label }}
          <input v-model="item.selected" type="checkbox" />

    </template>


text:
Q: How to implement Swift's or Objective-C's mutable pointers in Python? The following function requires a "mutable pointer". How do I represent that in Python?
Swift:
func CGPDFDocumentGetVersion(
  _ document: CGPDFDocument?,
  _ majorVersion: UnsafeMutablePointer<Int32>,
  _ minorVersion: UnsafeMutablePointer<Int32>
)

Objective-C:
void CGPDFDocumentGetVersion (
  CGPDFDocumentRef document,
  int *majorVersion,
  int *minorVersion
);

Seems a bit mad that the function returns values in this way, nonetheless.
I've tried just supplying variables, already assigned to empty values, but I get a segmentation fault. If the variables are undefined, I get:
NameError: name 'x' is not defined

Here's some code that causes a Sgmentation fault. It's very easy to get these if CoreGraphics doesn't like the input.
file = "/path/to/file.pdf"
pdf = CGPDFDocumentCreateWithProvider(CGDataProviderCreateWithFilename(file))
x = None
y = None
version = CGPDFDocumentGetVersion(pdf, x, y)

A: You don't need mutable pointers at all.  There are two common uses for pointers to int (or similar storage) in C-like code, and Python provides better ways to do both.
Case 1:  Multiple return values
A C-like function can't return more than one value without defining a new struct and allocating memory for it.  That's tedious enough the job is often foisted off onto the calling function, which provides pointers to the storage it has allocated in advance.
In Python, you'd just return an object... in your case, a tuple or namedtuple:
import collections

Version = collections.namedtuple(
  'Version',
  ('major', 'minor'),
  )

class PDFDocument:

    def __init__(self, ...):
        # Figure out major and minor version numbers, then...
        self.version = Version(major, minor)

pdf_doc = PDFDocument(...)
major, minor = pdf_doc.version
...

Case 2: Announcing Errors
A C-like function that needs to signal that an error has occurred will typically return some "illegal" value.  If there is no such value it can use, an alternative is to take a pointer to some storage the caller owns, where it will scribble its exit status on its way out.
In Python, you'd just raise an exception, which is better in almost every way.


text:
Q: Is Data protection capability sufficient for securize application files I want to prevent modifications from my application files stored in Documents directory.
I try CryptoSwift and AES256CBC libs but they greatly slow down my application which has multiple read / write files
Enabling Data Protection capability on my application project it enough for prevent user to modifying theses files content ?

A: The data protection feature is secure against everyone except the iPhone owner if the iPhone is not jailbroken. It uses AES encryption and the encryption key is stored in the keychain.
The data protection feature used Common Crypto that uses the hardware encryption engine and is very fast, on my iPhone 6s 1MB encrypts in ~2.3 mSec, a rate of > 400MB/s.


text: Q: "on form submit" trigger on response spreadsheet stopped working with google change I have a google form with a response spreadsheet and code (on the sheet) that is associated with an "on form submit" trigger.  This has been working without issue for years.  Google's recent change to the security/Oauth seems to have broken it.  It does not appear that the code is even firing when the form is submitted.  Has anyone else experienced this since google's latest changes?  I was asked to reauthorize and I typed "continue" to do so and I can execute the code manually, but the triggers appear not to work.


text:
Q: Flexible vertical html layout I need solve some task in vanilla html+css - bootstrap code for desktop browser-based application. So, I can't use libraries such as jQuery or Ext.
There are container 'wrapper' with three boxes - 'header', 'pane', 'content'. I need the following - wrapper and all three boxes always fit into single screen and take 100% of height/width
Header is going to be a toolbar and pane is a fixed height box. Content takes the rest of the screen.
I'm unable to make content fit into the rest of page. Can anybody help me ?
Another problem - I need to have testarea in the pane and content. Of course, there are lot's of such contols but I can't use them because this is bootstrap code.
I've created sample page: http://jsfiddle.net/madhollander/6r4nu/
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>filterIt</title>

    <button type="button">Apply</button>

        <textarea class="textbox" id="command" wrap="off">command sample</textarea>

        <textarea class="textbox" wrap="off" id='log'>log sample</textarea>

A: You're simply using the Flexbox module incorrectly.  Some properties only apply to flex containers, others only apply to flex items.  Also never use the old Flexbox properties unless you're also using the modern properties.
http://codepen.io/cimmanon/pen/DcesF
#wrapper {
  position: absolute;
  top: 0px;
  left: 0px;
  right: 0;
  bottom: 0px;
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  -webkit-box-orient: vertical;
  -moz-box-orient: vertical;
  -webkit-box-direction: normal;
  -moz-box-direction: normal;
  -webkit-flex-direction: column;
  -ms-flex-direction: column;
  flex-direction: column;
}

#header {
  width: 100%;
  background-color: blue;
}

#pane {
  width: 100%;
  height: 100px;
  background-color: black;
  -webkit-box-flex: 1;
  -moz-box-flex: 1;
  -webkit-flex: 1 1;
  -ms-flex: 1 1;
  flex: 1 1;
}

#content {
  width: 100%;
  background-color: green;
  overflow-x: scroll;
  overflow-y: scroll;
  -webkit-box-flex: 1;
  -moz-box-flex: 1;
  -webkit-flex: 1 1;
  -ms-flex: 1 1;
  flex: 1 1;
}

.textbox {
  width: 100%;
  display: block;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  resize: none;
  overflow-x: scroll;
  overflow-y: scroll;
}

A: What you could do to make this 'fluid' layout is to set the #wrapper to height: 100%;
This stretches it to the body's height (which you should also set to 100% - as some browsers handle this different from others)
Furthermore, you could set a percentage for each element in height which you can always change to your liking, ofcourse you should set min-height rather than height, otherwise your elements will overflow and cause layout glitches.
Your page will then look like this:
http://jsfiddle.net/6r4nu/1/

A: Not sure I understand your question correctly, but here you go anyway:
If you need the three div's to fill the page vertically, you just need to give your wrapper  (and further parent elements) a height of 100%. Then to fill the page, each div gets a height of 33.3%.
like this:
#wrapper{
height:100%;
}
#header, #content, #pane{
height:33.3%
}

If they shouldn't be equally heigh, just re-calculate the percentage so they add up to 100%.


text: Q: Optimization in more than 1 variables I have a function of x1, x2, x3 and x4 i.e. y=f(x1, x2, x3, x4). I do not know the exact functional form but I have 50+ different settings of x1, x2, x3 and x4 and the corresponding y values. I want to find, in r, the values of x1, x2, x3 and x4 that approximately minimize my function f(x1, x2, x3, x4).


text:
Q: How will you roll out Windows 7 to your network's PCs when it is released? Seeing as Vista didn't have a really high uptake rate amongst businesses, are you planning to roll Windows 7 out to your Windows XP network and if so, how do you plan on doing it?
This question is mostly due to the fact that there isn't an upgrade path from XP to 7, so it would seem that the nuke & pave approach is all that's available & this seems like it's going to be a pain for larger (or even smaller) networks.   Is Microsoft releasing a way to install Windows 7 without wiping out the whole Windows XP install?

A: Typically the way we do new OS rollouts is as new machines are put on the floor or as existing machines need to be regenned.  It's strict policy to not have anything stored on C: drives which makes it pretty easy to just do a wipe and load.  Our PC's are all leased as well so when machines come off lease the new ones go out with the new OS.

A: As always with our company, the IT department will get first stab at the new OS. I'm already running Windows 7 (and have been since the beta, through a few of the subsequent builds, and now the RC). Luckily our department workstations are reaching their set EOL, so when we upgrade the physical machines, we'll up grade the OS as well.
Probably the biggest challenge facing deployment is training. There were a ton of aesthetic changes from XP to Vista, and there are quite a few changes between Vista and Windows 7 (making the adjustment from XP to Windows 7 quite an ordeal).
We're planning on using my past 6 month's experience, in conjunction with the various Win7 Features webpages and instructional videos to help ease the transition.

A: We purchase an OEM license for the OS with each PC, and don't generally upgrade it unless there is an obvious reason.  Recently we have purchased Vista with the XP downgrade and installed XP.  We are hoping to skip Vista, although a couple of us are testing it.  I am not sure how Windows 7 will be introduced .. it will most likely be OEM and so will depend on when we start buying again!
In any case, if you decide to upgrade a PC from XP to W7, I suggest a clean install rather than doing an in-place upgrade.

A: We will likely use the Microsoft Deployment Toolkit 2010 (aka MDT) when it comes out of beta.  The current MDT 2008 version supports Vista migrations nicely including migrating user state with the User State Migration Tool (USMT) 3.0.
With MDT, you are basically creating a custom image of your target OS.  Part of the process includes creating a WinPE image that the target system boots into in order run the USMT and other prerequisites before formatting the drive and shoving down your new OS image.  Once the OS has been replaced, USMT takes care of putting the user settings back.
To be honest, I'm still new to the product.  So I might be slightly off in a few places, but that's basically the gist of it.

A: Due to weak centralized configuration controls (it's a political thing) our upgrade method is generally in sync with the hardware replacement cycle. In other words, we upgrade OS when we replace the hardware. The one exception will be the general computing labs which are all imaged. But our hardware there is just old enough that Win7 may not run well.

A: Windows 7 is a nice os which I would probably use at home but not at work - there's nothing revolutional. It's not a cost related questions - as we are msdn subscribers, we don't care. It's just because XP/XPx64 is very stable and still supported. Maybe when Office15 will be out and strictly require IE9 available only for Vista/W7, we'll think about upgrading.

A: Note that if you want to retain profiles from xp you will need to go through some pain converting them to Vista or Windows 7 because of the new file structure.  I just went from XP to Vista and experienced this.
Microsoft has a good white paper on this conversion and the tools needed to pull it off.  Most Microsoft programs convert over well but it's hit and miss on many other programs.
This link should help:
technet.microsoft.com/en-us/library/cc748927(WS.10).aspx
If you plan on retaining profiles you will need to read the docs.

A: One of my clients has decided to do 100% of all upgrades via attrition.
They submit their disk build to Dell and all future orders will come with their chosen baseline.


text:
Q: Paypal REST api - How to control the display language? I'm working on the PayPal REST API with the official PHP SDK: https://github.com/paypal/rest-api-sdk-php
However I notice the REST call point me to a check out page (Sandbox mode) in Chinese locale, any idea how to control the display language as English?
I found the same question is asked a year before but no answer: REST Api integration - how to force payment page's language?
Or either solution are provided base on Classic API, looks like not applicable on REST API:
How can I control the language displayed in the Paypal Sandbox?

A: There are no LOCALE options you can pass to the REST API, however, if you set the shipping address for the transaction it should update automatically. You can test with the call below.
curl -v https://api.sandbox.paypal.com/v1/payments/payment -H 'Content-Type: application/json' -H 'Authorization: Bearer {ACCESS_TOKEN}' \
-d '{
  "intent":"sale",
  "redirect_urls":{
    "return_url":"http://localhost",
    "cancel_url":"http://localhost"
  },
  "payer":{
    "payment_method":"paypal"
  },
  "transactions":[
    {
        "amount":{
            "total":"7.47",
            "currency":"USD"
        },
        "item_list":{
            "shipping_address":{
                "recipient_name":"Test Test",
                "type":"business",
                "line1":"187 Alameda Santos",
                "city":"Sao Paulo",
                "country_code":"BR",
                "postal_code":"01119",
                "state":"Condominio Edificio Platinum"
            }
        },
        "description":"This is the payment transaction description."
    }
  ]
}'

A: in addition to Aaron answer, you can use ExpressCheckout REST api to set a LOCALE see https://developer.paypal.com/webapps/developer/docs/classic/api/merchant/SetExpressCheckout_API_Operation_NVP/

A: you can pass locale parameter using the PayPal REST APIS as mentioned here -
https://developer.paypal.com/docs/api/payments/v1/
Example
"application_context":{
    "locale":"en_IN",
    "brand_name":"MY BRAND",
    "landing_page":"Billing"
}


text:
Q: reinterpret_cast to QObject's subling I've got some kind of object factory (template based), that works pretty good for my purposes. But now I've tried to work with class, that derives from both QObject and pure abstract class (interface) and I've got strange run-time errors.
Here the simple picture of this class (Derived)
class Interface  {
public:
    Interface(){}
    virtual ~Interface(){}
    virtual int getResult() = 0;
};

class Derived : public QObject, public Interface {
    Q_OBJECT
public:
    explicit Derived(QObject *parent = 0);
    int getResult();
};

and its implementation in derived.cpp:
#include "derived.h"
Derived::Derived(QObject *parent)
    : QObject(parent) {
}
int Derived::getResult() {
    return 55;
}

When I try to cast void pointer to the Interface, I'll get unexpected (for me) behavior, it can be or runtime error, or other method call (it depends of classes' size).
#include "derived.h"
void * create() {
    return new Derived();
}

int main(int argc, char *argv[]) {
    Interface * interface = reinterpret_cast<Interface *>(create());
    int res = interface->getResult(); // Run-time error, or other method is called here
    return 0;
}

Could you explain me why I cannot cast void pointer to interface? And is there any workaround?
Thanks for your responses

A: Reinterpreting a pointer to a derived class as a pointer to a base class gives undefined behaviour. This is highlighted by multiple inheritance: since there is more than one base class, and the two base subobjects must have different addresses, they can't both have the same address as the derived object. So the pointer returned by your create function points to a Derived, but not necessarily to the Interface subobject. It could point to QObject subobject, or to neither.
The best option is to return Derived* or Interface* from your function; if it must be void* for some reason, then the only well-defined cast you can make is back to Derived*, which can then be converted to Interface* using standard conversions.
By using void* you have thrown away all static and dynamic knowledge of the type; the only way to restore that information is to cast back to the correct type.

A: Mixing reinterpret_cast with multiple inheritance will likely cause all kinds of problems. In your case, the void* will probably point to the QObject part of the Derived, not the Interface part.
It would probably work better with a dynamic_cast, which can adjust the pointer to point to the correct subobject of the derived class.

A: Note that in general, the need for these types of casts are a sign of bad design. In your specific case, your factory function needs to return an Interface*. void* in C++ where no C interfacing is involved is just unnecessary and bad.
Apart from all this, factory functions are something of a Java thing, and only required when applying strict design methodology, which often adds more fluff than contributing to clean and bug-free code.
If that doesn't cut it, you'll want dynamic_cast. In Qt for QObjects, you can see if qobject_cast has any merit in your situation.


text:
Q: How to set a do...while loop on a switch statement and add inputs? I'm currently working on a project that must take a integer 1-10 switch it to a double then multiple that double with a quantity. However, all of these have to be input by the user like you're ordering something from a restaurant. The problem I'm having is getting a loop of the above that stores the total (price * quantity) and then adds it all up. exp: 1 * 5 = 5 + 4.5 * 2 = 9 = total of 14. I have to loop this to a point where the user can terminate the loop with an input. I've tried doing this by adding a counter++ to the switch as a case but nothing I do seems to work. Below is the current code I'm working on.
So all in all, I need below to loop (until prompted not to) and continuously add up the totals until I get one final total at the System.out.println("total"); line
 /*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package Menu;
import java.util.Scanner;
/**
 *
 * @author -------
 */

public class Menu {

    public static void main(String[] args) {
    Scanner input= new Scanner(System.in);
    Scanner keyboard = new Scanner (System.in);

    double price = 0;
    int ItemNum;
    int quantity;
    double change;
    double total;
    double payment;
    int counter = 1;

    System.out.println("Welcome to Home Italliano!\nHit enter for menu.");
    keyboard.nextLine();

    System.out.println("Menu" +"\n"+"(1)Noodles - 1.15$"+"\n"+"(2)Pizza Slice - 3.00$"
        +"\n"+"(3)Lasagna - 4.99$"+"\n"+"(4)Beverage - 2.25"+"\n"+"(5)Md. Pizza - 7.85$"+"\n"+
        "(6)Lg. Pizza - 11.10$"+"\n"+"(7)Calzone - 3.30$"+"\n"+"(8)Garlic Knot - 1.25$"
        +"\n"+"(9)Rg. Pasta - 8.00$"+"\n"+"(10)Triple Meat Pasta - 9.99$");

    while (counter ==1)
    System.out.println("Please input the number of the item you wish to order. hit 0 for total.");
    ItemNum = input.nextInt();

    System.out.println("Please enter the quantity for this item");
    quantity = input.nextInt();

    total = price * quantity;

    switch (ItemNum){
        case 0:
            counter++;
        case 1:
            price = 1.15;
            break;
        case 2:
            price = 3.00;
            break;
        case 3:
            price = 4.99;
            break;
        case 4:
            price = 2.25;
            break;
        case 5:
            price = 7.85;
            break;
        case 6:
            price = 11.10;
            break;
        case 7:
            price = 3.30;
            break;
        case 8:
            price = 1.25;
        case 9:
            price = 8.00;
            break;
        case 10:
            price = 9.99;
            break;
        default:
                System.out.println("Please enter a menu item.");

    }

    System.out.println(total);

        }

            }

A: Some hints:

*

*Enclose your logic in an infinite loop (i.e. while(true)).

*Mind your curly brackets for the loop

*Either use a specific int or use Scanner.nextLine to get a String representation of the input (i.e. "q" for "quit"), and break the infinite loop if matched (you will need some String->int conversion in this case)

*It's "Italiano", with one "l"

A: Your while loop doesnt have any braces:
while (counter ==1)

A: as other have pointed out: Your while loop is missing the braces and thus only affects the second line.
Also: You are accessing the price before you have determined it through your switch clause.
While it might work if you add the braces, your solution should look more like this:
1, Create a private class for the Items on the Menu. Such a MenuItem would have a name and a price.
2, Then create a java.utils.HashMap of MenuItems. Then you init this map with your Menu.
A Map maps a given Key (in this case the menuNumber) to a given Object (in our case a MenuItem Object)
E.g.:
menuMap.put(1, new MenuItem("Noodles", Double.valueOf("1.15"));

3, Do the Initial Output;
System.out.println("Menu:");
for(String key: menuMap.keySet())
{
    System.out.println(menuMap.get(key).toString());
}

4, Create a while loop, like such
//Initially Scan for and validate ItemChoice
while(!inputMenuNumber == 'Exit Signal')
{
    //Scan for and validate Input Amount

    MenuItem chosenItem = menuMap.get(inputMenuNumber);
    total = chosenItem.getItemPrice() * Integer.valueOf(inputAmount);

    //Scan for and validate ItemChoice
}
Sytem.out.println(total);

It makes the code a lot easier to read and to comprehend.
If you have any questions, don't hesitate to ask.


text:
Q: SQL query: Copy all rows with Store_ID = 1 I have a table review_store with two columns: review_id and store_id
If I had to replace 1 with 2, I would do this:
UPDATE review_store
SET store_id = '2'
WHERE store_id = '1'

How do I copy/duplicate every row in which store_ID = 1 to Store_ID = 2 ?

A: I assume you mean create new records in the same table. Use INSERT SELECT
INSERT INTO review_store
SELECT review_id, '2' as Store_id
FROM review_store
WHERE Store_id = '1'

A: INSERT INTO review_store (review_id, store_id)
SELECT review_id, 2
FROM review_store
WHERE store_id = 1

A: INSERT INTO `review_store` SELECT 2, review_id FROM `review_store` WHERE store_id = 1

Note that if you have an id column, you should add a blank field for it, so
INSERT INTO `review_store` SELECT '', 2, review_id FROM `review_store` WHERE store_id = 1

Check the order of your fields, too. If review_id comes before store_id, you'll need to re-order the select.


text:
Q: NetBeans Java GUI builder I have a Java application that I can choose the design option next to source and use the GUI builder but some are without that option design and I cannot use GUI builder on them. Is there a way to use GUI builder if that option is not present there?

A: You can only switch between Source and Design if you created that file as a Swing GUI Form through the New File window of NetBeans. This is the window I mean:

A: I think you can only choose when you select a JForm rather than a Java Class


text:
Q: Constructing a Select List with OptGroup groups Current project:

*

*ASP.NET 4.5.2

*MVC 5

I am trying to build a select menu with OptGroups from the Model, but my problem is that I cannot seem to build the OptGroups themselves.
My model:
[DisplayName("City")]
public string CityId { get; set; }
private IList<SelectListItem> _CityName;
public IList<SelectListItem> CityName {
  get {
    List<SelectListItem> list = new List<SelectListItem>();
    Dictionary<Guid, SelectListGroup> groups = new Dictionary<Guid, SelectListGroup>();
    List<Region> region = db.Region.Where(x => x.Active == true).OrderBy(x => x.RegionName).ToList();
    foreach(Region item in region) {
      groups.Add(item.RegionId, new SelectListGroup() { Name = item.RegionName });
    }
    List<City> city = db.City.Where(x => x.Active == true).ToList();
    foreach(City item in city) {
      list.Add(new SelectListItem() { Text = item.CityName, Value = item.CityId.ToString(), Group = groups[item.RegionId] });
    }
    return list;
  }
  set { _CityName = value; }
}

Each city can be in a region. I want a select menu to group the cities by region. By all that I can figure out, the code above is supposed to do the job, but instead I get a drop-down menu with all cities grouped under the OptGroup named System.Web.Mvc.SelectListGroup
The key thing in the above code is that I first iterate through the Regions, and put them into a Dictionary, with the RegionId set to be the key that brings back the RegionName (which itself is formatted as a SelectListGroup).
Then I iterate through the Cities, and assign to each city the group that matches the city's RegionId.
I have not seen any examples on the Internet that actually pull content from a database -- 100% of all examples use hard-coded SelectListGroup and SelectListItem values.
My View is also correct, AFAIK:
@Html.DropDownListFor(x => x.CityId, new SelectList(Model.CityName, "Value", "Text", "Group", 1), "« ‹ Select › »", htmlAttributes: new { @class = "form-control" })

As you can see, the Group is supposed to be brought into the SelectList, and the DropDownList is being created with OptGroups, just not the correct ones.
My resulting drop-down menu looks something like this:
« ‹ Select › »
System.Web.Mvc.SelectListGroup
  City1
  City2
  ...
  LastCity

When it should be like this:
« ‹ Select › »
Region1
  City2
  City4
  City5
Region2
  City3
  City1
  City6

Suggestions?

Modified solution: I have followed the solution provided by Stephen Muecke, but have modified it slightly.
One of the general rules of MVC is that you have a model that is heavier than the controller, and that the model defines your business logic. Stephen asserts that all database access should be done in the controller. I have come to agree with both.
One of my biggest "issues" is that any creation of a drop-down menu or any other pre-populated form element needs to be called every time the page is called. That means, for either a creation or edit page, you need to call it not only on the [HttpGet] method, but also in the [HttpPost] method where the model is sent back to the view because it did not properly validate. This means you have to add code (traditionally via ViewBags) to each Method, just to pre-populate elements like drop-down lists. This is called code duplication, and is not a Good Thing. There has to be a better way, and thanks to Stephen's guidance, I have found one.
The problem with keeping data access out of the Model is that you need to populate your model with the data. The problem with avoiding code reuse and avoiding potential errors is that you should not do the job of binding data to elements in the controller. This latter action is business logic, and rightfully belongs in the model. The business logic in my case is that I need to limit user input to a list of cities, grouped by region, that the administrator can select from a drop-down. So while we might assemble the data in the controller, we bind it to the model in the model. My mistake before was doing both in the model, which was entirely inappropriate.
By binding the data to the model in the model, we avoid having to bind it twice - once in each of the [HttpGet] and [HttpPost] methods of the controller. We only have to bind it once, in the model that is handled by both methods. And if we have a more generic model that can be shared between Create and Edit functions, we can do this binding in only one spot instead of four (but I don't have this degree of genericness, so I won't give that as an example)
So to start out, we actually peel off the entire data-assembly, and stick it inside its own class:
public class SelectLists {
  public static IEnumerable<SelectListItem> CityNameList() {
    ApplicationDbContext db = new ApplicationDbContext();
    List<City> items = db.City.Where(x => x.Active == true).OrderBy(x => x.Region.RegionName).ThenBy(x => x.CityName).ToList();
    return new SelectList(items, "CityId", "CityName", "Region.RegionName", 1);
  }
}

This exists within the namespace, but beneath the controller of the section we are dealing with. For clarity's sake, I stuck it at the very end of the file, just before the closing of the namespace.
Then we look at the model for this page:
public string CityId { get; set; }
private IEnumerable<SelectListItem> _CityName;
public IEnumerable<SelectListItem> CityName {
  get { return SelectLists.CityNameList(); }
  set { _CityName = value; }
}

Note: Even though the CityId is a Guid and the DB field is a uniqueidentifier, I am bringing this value in as a string through the view because client-side validation sucks donkey balls for Guids. It's far easier to do client-side validation on a drop-down menu if the Value is handled as a string instead of a Guid. You just convert it back into a Guid before you plunk it back into the master model for that table. Plus, CityName is not an actual field in the City table - it exists purely as a placeholder for the drop-down menu itself, which is why it exists in the CreateClientViewModel for the Create page. That way, in the view we can create a DropDownListFor that explicitly binds the CityId to the drop-down menu, actually allowing client-side validation in the first place (Guids are just an added headache).
The key thing is the get {}. As you can see, no more copious code which does DB access, just a simple SelectLists which targets the class, and a calling of the method CityNameList(). You can even pass variables on to the method, so you can have the same method bring back different variations of the same drop-down menu. Say, if you wanted one drop-down on one page (Create) to have its options grouped by OptGroups, and another drop-down (Edit) to not have any groupings of options.
The actual model ends up being even simpler than before:
@Html.DropDownListFor(x => x.CityId, Model.CityName, "« ‹ Select › »", htmlAttributes: new { @class = "form-control" })

No need to modify the element that brings in the drop-down list's data -- you just call it via Model.ElementName.
I hope this helps.

A: Firstly, you view model should not contain database access code to populate its properties. That is the responsibility of the controller and you have made your code impossible to unit test. Start by changing the model to
public class CreateClientViewModel
{
    [DisplayName("City")]
    public string CityId { get; set; }
    public IList<SelectListItem> CityList { get; set; }
    ....
}

Then in the controller, you can use one of the overloads of SelectList that accepts a groupName to generate the collection
var cities = var cities = db.City.Include(x => x.Region).Where(x => x.Active == true)
    .OrderBy(x => x.Region.RegionName).ThenBy(x => x.CityName);

var model = new CreateClientViewModel()
{
    CityList = new SelectList(cities, "CityId", "CityName", "Region.RegionName", null, null)
};
return View(model);

And in the view
@Html.DropDownListFor(x => x.CityId, Model.CityList , "« ‹ Select › »", new { @class = "form-control" })

As an alternative, you can also do this using the Group property of SelectListItem
var model = new CreateClientViewModel()
{
    CityList = new List<SelectListItem> // or initialize this in the constructor
};
var cities = var cities = db.City.Include(x => x.Region).Where(x => x.Active == true).GroupBy(x => x.Region.RegionName);
foreach(var regionGroup in cities)
{
    var optionGroup = new SelectListGroup() { Name = regionGroup.Key };
    foreach(var city in regionGroup)
    {
        model.CityList.Add(new SelectListItem() { Value = city.CityId.ToString(), Text = city.CityName, Group = optionGroup });
    }
}
return View(model);

A: I used this brilliant library: DropDownList Optgroup MVC 1.0.0
Nuget link
This is how to use it:

*

*Get your list ready:
var ethnicityData = new List<GroupedSelectListItem> {
        new GroupedSelectListItem() { Value="British", Text ="British", GroupName = "White", GroupKey="1"},
        new GroupedSelectListItem() { Value="Irish", Text ="Irish", GroupName = "White", GroupKey="1"},
        new GroupedSelectListItem() { Value="White Other", Text ="White Other", GroupName = "White", GroupKey="1"},
        new GroupedSelectListItem() { Value="Other Ethin Group", Text ="Other Ethin Group", GroupName = "Other Ethnic Group", GroupKey="2"},
        new GroupedSelectListItem() { Value="Chinese", Text ="Chinese", GroupName = "Other Ethnic Group", GroupKey="2"},
        new GroupedSelectListItem() { Value="Other mixed background", Text ="Other mixed background", GroupName = "Mixed", GroupKey="4"},
        new GroupedSelectListItem() { Value="White and Asian", Text ="White and Asian", GroupName = "Mixed", GroupKey="4"},
        new GroupedSelectListItem() { Value="White and Black African", Text ="White and Black African", GroupName = "Mixed", GroupKey="4"},
        new GroupedSelectListItem() { Value="White and Black Caribbean", Text ="White and Black Caribbean", GroupName = "Mixed", GroupKey="4"},
        new GroupedSelectListItem() { Value="Other Black background", Text ="Other Black background", GroupName = "Black or Black British", GroupKey="5"},
        new GroupedSelectListItem() { Value="Caribbean", Text ="Caribbean", GroupName = "Black or Black British", GroupKey="5"},
        new GroupedSelectListItem() { Value="African", Text ="African", GroupName = "Black or Black British", GroupKey="5"},
        new GroupedSelectListItem() { Value="Bangladeshi", Text ="Bangladeshi", GroupName = "Asian or Asian British", GroupKey="6"},
        new GroupedSelectListItem() { Value="Other Asian background", Text ="Other Asian background", GroupName = "Asian or Asian British", GroupKey="6"},
        new GroupedSelectListItem() { Value="Indian", Text ="Indian", GroupName = "Asian or Asian British", GroupKey="6"},
        new GroupedSelectListItem() { Value="Pakistani", Text ="Pakistani", GroupName = "Asian or Asian British", GroupKey="6"},
        new GroupedSelectListItem() { Value="Not Stated", Text ="Not Stated", GroupName = "Not Stated", GroupKey="3"}

};

*Use it like this:
@Html.DropDownGroupListFor(model => model.Ethnicity,ethnicityData, "", new { @class = "form-control" })


text:
Q: Java Multithreading - a basic parallel example of Sieve of Eratosthenes I would like to create a simple parallel Sieve of Erastosthenes Java program, that would be at least a bit more effective then a serial version I've posted below.
  public void runEratosthenesSieve(int upperBound) {
      int upperBoundSquareRoot = (int) Math.sqrt(upperBound);
      boolean[] isComposite = new boolean[upperBound + 1];
      for (int m = 2; m <= upperBoundSquareRoot; m++) {
            if (!isComposite[m]) {
                  System.out.print(m + " ");
               int threads=4;
               for (int n=1; n<=threads; n++) {
                  int job;
                  if (n==1) {job = m * m;} else {job = (n-1)*upperBound/threads;}
                  int upToJob = n*upperBound/threads;
                   for (int k = job;  k <= upToJob; k += m)
                  {
                       isComposite[k] = true;
                  }
               }
            }
      }
      for (int m = upperBoundSquareRoot; m <= upperBound; m++)
            if (!isComposite[m])
                  System.out.print(m + " ");
  }

I have created a loop for dividing work for 4 threads. Though I don't know how to make actual thread code from it. How to send variables and start  4 threads with part of job for each.

A: I can propose following solution: there are 4 workers thread and 1 master thread. Worker threads get jobs from queue. Job is basically 3 numbers: from, to, step. Master mean while must wait until all threads a done. When they're done it searches for next prime number and create 4 jobs. Synchronization between master and workers can be achieved using Semaphore: master tries to acquire 4 permits while every worker releases 1 permit when it's done.
public class Sieve {

    // Number of workers. Make it static for simplicity.
    private static final int THREADS = 4;

    // array must be shared between master and workers threads so make it class property.
    private boolean[] isComposite;
    // Create blocking queue with size equal to number of workers.
    private BlockingQueue<Job> jobs = new ArrayBlockingQueue<Job>(THREADS);
    private Semaphore semaphore = new Semaphore(0);
    // Create executor service in order to reuse worker threads.
    // we can use just new Thread(new Worker()).start(). But using thread pools more effective.
    private ExecutorService executor = Executors.newFixedThreadPool(THREADS);

    public void runEratosthenesSieve(int upperBound) {
        int upperBoundSquareRoot = (int) Math.sqrt(upperBound);
        isComposite = new boolean[upperBound + 1];

        // Start workers.
        for (int i = 0; i < THREADS; i++) {
            executor.submit(new Worker());
        }
        for (int m = 2; m <= upperBoundSquareRoot; m++) {
            if (!isComposite[m]) {
                System.out.print(m + " ");
                for (int n=1; n<= THREADS; n++) {
                    int from;
                    if (n == 1) {
                        from = m * m;
                    } else {
                        from = (n-1)*upperBound/THREADS;
                    }
                    Job job = new Job(from, n*upperBound/threads, m);
                    // Submit job to queue. We don't care which worker gets the job.
                    // Important only that only 1 worker get the job. But BlockingQueue does all synchronization for us.
                    jobs.put(job);
                }
                // Wait until all jobs are done.
                semaphore.acquire(THREADS);
            }
        }
        for (int i = 0; i < n; i++) {
            // put null to shutdown workers.
            jobs.put(null);
        }
        for (int m = upperBoundSquareRoot; m <= upperBound; m++) {
            if (!isComposite[m]) {
                System.out.print(m + " ");
            }
        }
    }

    private class Job {
        public int from, to, step;

        public Job(int from, int to, int step) {
            this.from = from;
            this.to = to;
            this.step = step;
        }
    }

    private Worker implements Runnable {
        while (true) {
            Job job = jobs.take();
            // null means workers must shutdown
            if (job == null) {
                return;
            }
            for (int i = job.from; i <= job.to; i += job.step) {
                isComposite[i] = true;
            }
            // Notify master thread that a job was done.
            semaphore.release();
        }
    }
}


text:
Q: pip + requirements.txt: strange behaviour. Keeps downloading various verions of pandas This is what is observed with pip and pandas

The following is my requirements.txt
asgiref==3.3.1
auditlog3 == 1.0.1
click==7.1.2
auditlog3
dj-database-url==0.5.0
Django==3.1.13
django-cors-headers
django-watchman
djangorestframework
djangorestframework-simplejwt
django-jsonfield == 1.4.1
gunicorn
pillow == 8.3.1
psycopg2==2.8.6
PyJWT==2.0.1
python-dotenv
python-dateutil == 2.6.0
pytz==2020.5
sqlparse==0.2.4
requests
FPDF==1.7.2
pandas

and pip and python verions
$ python -V
Python 3.9.7
$ pip --version
pip 21.2.3 from /opt/venv/lib/python3.9/site-packages/pip (python 3.9)

No clue what to do from here. Can someone help

A: This is normal behaviour of the dependency resolver:

*

*It downloads the most recent version that fits your version specification and python version

*then checks the dependencies against the rest of your requirements.txt

*It fits -> done. It does not -> repeat at step 1 with seconda most recent version

In your case, you see multiple iterations of step 1-3 with decreasing versions.
See also this github post


text:
Q: Which Rspec convention is more up to date? Which Rspec convention is more up to date and should be used in new projects ?
subject { [] }
it { should == [] }

or
subject { [] }
it { expect(subject).to eq([]) }

I haven't found way of composing shorter version using subject implicitly with expect method.

A: Using expect (your second example) is the more up to date version. Rspec is moving away from methods being added onto existing objects (such as should) because they can occasionally cause odd behavior.

A: As stated in http://myronmars.to/n/dev-blog/2012/06/rspecs-new-expectation-syntax
"In the future, we plan to change the defaults so that only expect is available unless you explicitly enable should. We may do this as soon as RSpec 3.0, but we want to give users plenty of time to get acquianted with it"
I copy from this site: "The underlying problem is RSpec's should syntax: for should to work properly, it must be defined on every object in the system… but RSpec does not own every object in the system and cannot ensure that it always works consistently. As we've seen, it doesn't work as RSpec expects on proxy objects. Note that this isn't just a problem with RSpec; it's a problem with minitest/spec's must_xxx syntax as well."
Personally, I use a mix of both still, as all "shoulda" matchers use the old syntax anyway, and are so easy to use...


text:
Q: How to check WP Customize Control I trying this directly in my theme:

$mods = $wp_customize->get_control('header_text');
 if (isset($mods)) {
    echo 'YES';
} else {
    echo 'No';
}

But nothing happened. and in debug.log : undefined variable wp_customize...

A: I'm not sure what exactly you're trying to accomplish, but if you're wanting to manipulate customizer controls until the customize_register action has fired. So do something like this:
add_action( 'customize_register', function( $wp_customize ) {
    $control = $wp_customize->get_control( 'header_text' );
    if ( $control ) {
        error_log( 'header_text control exists' );
    } else {
        error_log( 'header_text control does not exist' );
    }
}, 100 );

A: Use get_theme_mod and this work:

$mod = get_theme_mod('header_text');
 if ( $mod != 0 ) {
    # code...
    echo 'YES';
} else {
    echo 'No';
}

In this case I wanted to check if the Title and the slogam of the site was hidden or not.
To get the string> ID of the MOD is simply. inspect the option with the Customizer open, as show the image:


text:
Q: Creating sequence of events in ActionScript3 I am new to AS3 and Flash. I have a very simple question. I want to create a sequence of event for my enemies in a game I am working on. So when my enemy is hit, I want the death animations to be played and after the animation is complete I want to remove the enemy object from the stage. The death animation takes about 3 seconds, so after 3 seconds I want to remove the enemy Object.
So this are the set of events I want
  1. Enemy hit check
  2. if hit, play death animation
  3. wait for 3 seconds
  4. remove the Enemy object from the stage.

I have used the Unity engine extensively and they have coroutines which work quite well if you want to create a sequence at different time intervals.
How can we do something like that in Flash with AS3?
Thanks!

A: I'm going to take your chain of events and make a slightly more detailed chain of events.

*

*Enemy Hit Check
The built-in Flash functions hitTestObject and hitTestPoint will serve you well if you're thinking relatively simple hit test checking.  If you're looking for complex hit test checking (something inside of something else, checking from within) I would highly recommend "Bit-map hit testing" which is slightly more complicated.  Luckily, there are a plethora of online tutorials that can help.

*if hit, play the death animation
If you're using a MovieClip, you can set a frame by frame animation.  After you've built your animation in, simply call .gotoAndPlay(f) on your clip to frame f where f is the starting frame of your death animation, in order to get the animation going.

*Wait for 3 seconds.
If your animation takes 3 seconds anyway, put a function call in the last frame of your death animation sequence that sends an event up the chain to your "main class."

*Remove the Enemy Object from the stage.
You can then go off of the event in step 3 to remove the enemy from the stage.
Let me know if you have any clarifications/additional questions and I'll do my best to help out.


text:
Q: iso-8859-1 vs utf-8 android I have an object in retriving http post response from webserver. However unicode will requires me to do the following
BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "UTF-8"), 8);

instead of my usual
BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);

If i were to use unicode for all response, will it affect my normal text?

A: You sould check what the webserver responses. It can be iso-8859-1 or UTF-8. Check the Charset of the Content-Type header from the HTTP response


text:
Q: Converting standard normal distribution to skew normal distribution I have a random variable $Z$ that is generated based on a standard, normal distribution which I want to transform to follow a skewed, normal distribution, say with skew $\alpha$, standard deviation $\sigma$, and mean $\mu$. I know that to convert $Z$ to a normal distribution with standard deviation $\sigma$ and mean $\mu$ I can use the transformation $\sigma Z+\mu$, but am unsure how to incorporate the skew factor. Any help would be much appreciated!
To be more specific, I have a program which generates values based on a standard, normal distribution. It has poor functionality, so will not generate values based on a skew normal distribution, so I would like to be able to take those data points and transform them individually. For instance, if I had skew $\alpha = 0$, then I believe I could achieve this by taking the given data point $x$ and applying $x \mapsto \sigma x+\mu$. I'm not sure how to do this for general $\alpha$ though.


text:
Q: How to sort based on date and time from a sql query into a GridView Sorting the function like this on page load:
protected void Page_Load(object sender, EventArgs e)
{
    ViewState["sortOrder"] = "Desc";
    ViewState["sortExp"] = "Completed Date";
    PD("Completed Date", "Desc", true);
}

public void PD(string sortExp, string sortDir, bool blOnLoad)
{
    string qry = @"Select [status] 'Status', [Completed Date] 'Completed Date' FROM [mydb1].[dbo].[table1]";
    using (SqlConnection conn = new SqlConnection(gloString))
    {
        try
        {
            SqlCommand cmd = new SqlCommand(qry, conn);

            SqlDataAdapter da = new SqlDataAdapter(query, conn);

            myDataSet = new DataSet();
            da.Fill(myDataSet);

            myDataView = new DataView();
            myDataView = myDataSet.Tables[0].DefaultView;

            if (sortExp != string.Empty)
            {
                myDataView.Sort = string.Format("{0} {1}", sortExp, sortDir);
            }

            yourTasksGV.DataSource = myDataView;
            yourTasksGV.DataBind();
        }
        catch (Exception ex)
        {
            string error = ex.Message;
        }
    }
}
protected void yourTasksGV_Sorting(object sender, GridViewSortEventArgs e)
{
    ViewState["sortExp"] = e.SortExpression;
    PD(e.SortExpression, sortOrder, false);
}
public string sortOrder
{
    get
    {
        if (ViewState["sortOrder"].ToString() == "Desc")
        {
            ViewState["sortOrder"] = "Asc";
        }
        else
        {
            ViewState["sortOrder"] = "Desc";
        }

        return ViewState["sortOrder"].ToString();
    }
    set
    {
        ViewState["sortOrder"] = value;
    }
}

The [Completed Date] column is of datetime type.
RTRIM(Att12) 'Completed Date' = "May 20 2015  2:44PM"
RTRIM(CONVERT(VARCHAR(10), Att12, 101)) + ' ' + RIGHT(CONVERT(VARCHAR, RTRIM(Att12), 100), 7) 'Completed Date' = "05/20/2015  2:44PM" //this is being used for the bottom result.

After the above code runs, this is the result:
Completed Date
06/11/2015 11:39AM
06/11/2015  3:38PM
06/11/2015  1:12PM
06/11/2015  1:11PM
06/11/2015  1:06PM
06/11/2015  1:05PM
06/11/2015  1:04PM
06/11/2015  1:03PM
06/10/2015  9:35AM
06/09/2015 12:29PM
06/09/2015 12:24PM
06/09/2015 12:20PM
06/09/2015  9:40AM
06/09/2015  9:16AM
06/09/2015  9:11AM
06/05/2015 10:33AM
06/05/2015  8:35AM

As you can see the 11:39AM is always stuck at the top.
How can I modify the script to ensure is it correctly sorted.

A: Try with square bracket around the sort expression:
ViewState["sortOrder"] = "DESC";
ViewState["sortExp"] = "[Completed Date]";

Also, your [Completed Date] field should be of DateTime datatype. Don't convert it to string to get the required format. You can use string formatting to get any desired formatting for output. So your select statement should return Att12 datetime field:
Select [status] 'Status', [Att12] 'Completed Date' FROM [mydb1].[dbo].[table1]"

Then for display you can use string formatting:
DateTime.Now.ToString("dd-MM-yyyy hh:mm tt")

Or you can format the column in your grid to display the date time that format. For formatting reference you can checkout Custom Date and Time Format Strings.

A: Have you tried putting brackets around Completed Date?
ViewState["sortExp"] = "[Completed Date]";


text:
Q: passing $(this) with "var _this" Got his code, easy task:
1.Click list item
2.get list item values
3.put in input
4.change them manually
5.save them back to the list item per klick
After clicking multiple list items and saving them, the values are changed for all the list items that have been klicked on before, too.
Seems like "_this" is saving all the connections.
Any idea how to make this work? Big thanks!

        Name1

        Name2

        Name3

<input id="editName">

$("#foo").on('click', '.bar', function() {

    _this = $(this);
    edit(_this);
    });

function edit(_this) {

    var name = _this.parent().children(".name").text();
    $("#editName").val(name);

    $("#save").click( function() {
        _this.parent().find(".name").text(  $("#edit input#editName").val()  );
        });

    };

A: each time edit(_this) is invoked you bind a new delegate and after let say 3 times this method called... next time you will press the '#save' you will get three different invocations of this delegate.
to solve this you can add a variable that will get the _this value and hold it:
var _thisglobal='';

get out the biding function from edit(_this) and use the global value _thisglobal instead of _this:
function edit(_this) {
    _thisglobal=_this;
    var name = _this.parent().children(".name").text();
    $("#editName").val(name);

    };

$("#save").click( function() {
        _thisglobal.parent().find(".name").text(  $("#edit input#editName").val()  );
        });